]> git.proxmox.com Git - pve-storage.git/blame - PVE/Diskmanage.pm
api: add wipedisk call
[pve-storage.git] / PVE / Diskmanage.pm
CommitLineData
cbba9b5b
DC
1package PVE::Diskmanage;
2
3use strict;
4use warnings;
d5c80a5b 5
cbba9b5b
DC
6use PVE::ProcFSTools;
7use Data::Dumper;
8use Cwd qw(abs_path);
3196c387 9use Fcntl ':mode';
262ad7a9 10use File::Basename;
92ae59df 11use File::stat;
8cd6d7e8 12use JSON;
cbba9b5b
DC
13
14use PVE::Tools qw(extract_param run_command file_get_contents file_read_firstline dir_glob_regex dir_glob_foreach trim);
15
16my $SMARTCTL = "/usr/sbin/smartctl";
17my $ZPOOL = "/sbin/zpool";
18my $SGDISK = "/sbin/sgdisk";
19my $PVS = "/sbin/pvs";
19dcd1ad 20my $LVS = "/sbin/lvs";
8cd6d7e8 21my $LSBLK = "/bin/lsblk";
cbba9b5b 22
525b4a6e
FE
23sub check_bin {
24 my ($path) = @_;
25
26 return -x $path;
27}
28
cbba9b5b
DC
29sub verify_blockdev_path {
30 my ($rel_path) = @_;
31
32 die "missing path" if !$rel_path;
33 my $path = abs_path($rel_path);
34 die "failed to get absolute path to $rel_path\n" if !$path;
35
36 die "got unusual device path '$path'\n" if $path !~ m|^/dev/(.*)$|;
37
38 $path = "/dev/$1"; # untaint
39
40 assert_blockdev($path);
41
42 return $path;
43}
44
45sub assert_blockdev {
46 my ($dev, $noerr) = @_;
47
48 if ($dev !~ m|^/dev/| || !(-b $dev)) {
49 return undef if $noerr;
50 die "not a valid block device\n";
51 }
52
53 return 1;
54}
55
56sub init_disk {
57 my ($disk, $uuid) = @_;
58
59 assert_blockdev($disk);
60
61 # we should already have checked if it is in use in the api call
62 # but we check again for safety
63 die "disk $disk is already in use\n" if disk_is_used($disk);
64
65 my $id = $uuid || 'R';
66 run_command([$SGDISK, $disk, '-U', $id]);
67 return 1;
68}
69
70sub disk_is_used {
71 my ($disk) = @_;
72
73 my $dev = $disk;
74 $dev =~ s|^/dev/||;
75
7a98a62d 76 my $disklist = get_disks($dev, 1);
cbba9b5b
DC
77
78 die "'$disk' is not a valid local disk\n" if !defined($disklist->{$dev});
79 return 1 if $disklist->{$dev}->{used};
80
81 return 0;
82}
83
84sub get_smart_data {
dd902da7 85 my ($disk, $healthonly) = @_;
cbba9b5b
DC
86
87 assert_blockdev($disk);
88 my $smartdata = {};
dc1311cb 89 my $type;
cbba9b5b 90
9018a4e6 91 my $returncode = 0;
c9bd3d22 92
c3442aa5
WB
93 if ($disk =~ m!^/dev/(nvme\d+n\d+)$!) {
94 my $info = get_sysdir_info("/sys/block/$1");
95 $disk = "/dev/".($info->{device}
96 or die "failed to get nvme controller device for $disk\n");
97 }
c9bd3d22 98
dd902da7
DC
99 my $cmd = [$SMARTCTL, '-H'];
100 push @$cmd, '-A', '-f', 'brief' if !$healthonly;
101 push @$cmd, $disk;
102
cbba9b5b 103 eval {
dd902da7 104 $returncode = run_command($cmd, noerr => 1, outfunc => sub{
cbba9b5b
DC
105 my ($line) = @_;
106
1c999553
FG
107# ATA SMART attributes, e.g.:
108# ID# ATTRIBUTE_NAME FLAGS VALUE WORST THRESH FAIL RAW_VALUE
109# 1 Raw_Read_Error_Rate POSR-K 100 100 000 - 0
dc1311cb
FG
110#
111# SAS and NVME disks, e.g.:
112# Data Units Written: 5,584,952 [2.85 TB]
113# Accumulated start-stop cycles: 34
114
bd54091c 115 if (defined($type) && $type eq 'ata' && $line =~ m/^([ \d]{2}\d)\s+(\S+)\s+(\S{6})\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(.*)$/) {
cbba9b5b 116 my $entry = {};
bd54091c 117
1c999553
FG
118 $entry->{name} = $2 if defined $2;
119 $entry->{flags} = $3 if defined $3;
cbba9b5b 120 # the +0 makes a number out of the strings
1c999553
FG
121 $entry->{value} = $4+0 if defined $4;
122 $entry->{worst} = $5+0 if defined $5;
bd54091c
DC
123 # some disks report the default threshold as --- instead of 000
124 if (defined($6) && $6 eq '---') {
125 $entry->{threshold} = 0;
126 } else {
127 $entry->{threshold} = $6+0 if defined $6;
128 }
1c999553
FG
129 $entry->{fail} = $7 if defined $7;
130 $entry->{raw} = $8 if defined $8;
131 $entry->{id} = $1 if defined $1;
cbba9b5b 132 push @{$smartdata->{attributes}}, $entry;
5db2d529 133 } elsif ($line =~ m/(?:Health Status|self\-assessment test result): (.*)$/ ) {
cbba9b5b
DC
134 $smartdata->{health} = $1;
135 } elsif ($line =~ m/Vendor Specific SMART Attributes with Thresholds:/) {
dc1311cb
FG
136 $type = 'ata';
137 delete $smartdata->{text};
138 } elsif ($line =~ m/=== START OF (READ )?SMART DATA SECTION ===/) {
139 $type = 'text';
140 } elsif (defined($type) && $type eq 'text') {
141 $smartdata->{text} = '' if !defined $smartdata->{text};
142 $smartdata->{text} .= "$line\n";
2c048efd
DC
143 # extract wearout from nvme/sas text, allow for decimal values
144 if ($line =~ m/Percentage Used(?: endurance indicator)?:\s*(\d+(?:\.\d+)?)\%/i) {
ea928fd4
DC
145 $smartdata->{wearout} = 100 - $1;
146 }
dd902da7
DC
147 } elsif ($line =~ m/SMART Disabled/) {
148 $smartdata->{health} = "SMART Disabled";
cbba9b5b
DC
149 }
150 });
151 };
9018a4e6
DC
152 my $err = $@;
153
154 # bit 0 and 1 mark an severe smartctl error
155 # all others are for disk status, so ignore them
156 # see smartctl(8)
157 if ((defined($returncode) && ($returncode & 0b00000011)) || $err) {
158 die "Error getting S.M.A.R.T. data: Exit code: $returncode\n";
159 }
dc1311cb
FG
160
161 $smartdata->{type} = $type;
162
cbba9b5b
DC
163 return $smartdata;
164}
165
b6bbc2ab 166sub get_lsblk_info() {
59c03cd9 167 my $cmd = [$LSBLK, '--json', '-o', 'path,parttype,fstype'];
8cd6d7e8
DC
168 my $output = "";
169 my $res = {};
170 eval {
171 run_command($cmd, outfunc => sub {
172 my ($line) = @_;
173 $output .= "$line\n";
174 });
175 };
176 warn "$@\n" if $@;
177 return $res if $output eq '';
178
179 my $parsed = eval { decode_json($output) };
180 warn "$@\n" if $@;
181 my $list = $parsed->{blockdevices} // [];
182
b6bbc2ab 183 $res = { map {
59c03cd9
FE
184 $_->{path} => {
185 parttype => $_->{parttype},
186 fstype => $_->{fstype}
187 }
b6bbc2ab 188 } @{$list} };
8cd6d7e8
DC
189
190 return $res;
191}
192
193my $get_devices_by_partuuid = sub {
b6bbc2ab 194 my ($lsblk_info, $uuids, $res) = @_;
8cd6d7e8
DC
195
196 $res = {} if !defined($res);
197
b6bbc2ab
FE
198 foreach my $dev (sort keys %{$lsblk_info}) {
199 my $uuid = $lsblk_info->{$dev}->{parttype};
200 next if !defined($uuid) || !defined($uuids->{$uuid});
201 $res->{$dev} = $uuids->{$uuid};
8cd6d7e8
DC
202 }
203
204 return $res;
205};
206
cbba9b5b 207sub get_zfs_devices {
b6bbc2ab 208 my ($lsblk_info) = @_;
8cd6d7e8 209 my $res = {};
cbba9b5b 210
525b4a6e 211 return {} if !check_bin($ZPOOL);
4526dffa 212
cbba9b5b
DC
213 # use zpool and parttype uuid,
214 # because log and cache do not have
215 # zfs type uuid
216 eval {
217 run_command([$ZPOOL, 'list', '-HPLv'], outfunc => sub {
218 my ($line) = @_;
219
220 if ($line =~ m|^\t([^\t]+)\t|) {
8cd6d7e8 221 $res->{$1} = 1;
cbba9b5b
DC
222 }
223 });
224 };
225
226 # only warn here,
227 # because maybe zfs tools are not installed
228 warn "$@\n" if $@;
229
8cd6d7e8
DC
230 my $uuids = {
231 "6a898cc3-1dd2-11b2-99a6-080020736631" => 1, # apple
232 "516e7cba-6ecf-11d6-8ff8-00022d09712b" => 1, # bsd
233 };
cbba9b5b 234
cbba9b5b 235
b6bbc2ab 236 $res = $get_devices_by_partuuid->($lsblk_info, $uuids, $res);
8cd6d7e8
DC
237
238 return $res;
cbba9b5b
DC
239}
240
241sub get_lvm_devices {
b6bbc2ab 242 my ($lsblk_info) = @_;
8cd6d7e8 243 my $res = {};
cbba9b5b
DC
244 eval {
245 run_command([$PVS, '--noheadings', '--readonly', '-o', 'pv_name'], outfunc => sub{
246 my ($line) = @_;
247 $line = trim($line);
248 if ($line =~ m|^/dev/|) {
8cd6d7e8 249 $res->{$line} = 1;
cbba9b5b
DC
250 }
251 });
252 };
253
254 # if something goes wrong, we do not want
255 # to give up, but indicate an error has occured
256 warn "$@\n" if $@;
257
8cd6d7e8
DC
258 my $uuids = {
259 "e6d6d379-f507-44c2-a23c-238f2a3df928" => 1,
260 };
cbba9b5b 261
b6bbc2ab 262 $res = $get_devices_by_partuuid->($lsblk_info, $uuids, $res);
cbba9b5b 263
8cd6d7e8 264 return $res;
cbba9b5b
DC
265}
266
267sub get_ceph_journals {
b6bbc2ab 268 my ($lsblk_info) = @_;
8cd6d7e8
DC
269 my $res = {};
270
271 my $uuids = {
272 '45b0969e-9b03-4f30-b4c6-b4b80ceff106' => 1, # journal
273 '30cd0809-c2b2-499c-8879-2d6b78529876' => 2, # db
274 '5ce17fce-4087-4169-b7ff-056cc58473f9' => 3, # wal
275 'cafecafe-9b03-4f30-b4c6-b4b80ceff106' => 4, # block
276 };
277
b6bbc2ab 278 $res = $get_devices_by_partuuid->($lsblk_info, $uuids, $res);
cbba9b5b 279
8cd6d7e8 280 return $res;
cbba9b5b
DC
281}
282
19dcd1ad
DC
283# reads the lv_tags and matches them with the devices
284sub get_ceph_volume_infos {
285 my $result = {};
286
248f43f5
TL
287 my $cmd = [ $LVS, '-S', 'lv_name=~^osd-', '-o', 'devices,lv_name,lv_tags',
288 '--noheadings', '--readonly', '--separator', ';' ];
19dcd1ad
DC
289
290 run_command($cmd, outfunc => sub {
291 my $line = shift;
248f43f5
TL
292 $line =~ s/(?:^\s+)|(?:\s+$)//g; # trim whitespaces
293
294 my $fields = [ split(';', $line) ];
19dcd1ad
DC
295
296 # lvs syntax is /dev/sdX(Y) where Y is the start (which we do not need)
41f93ece 297 my ($dev) = $fields->[0] =~ m|^(/dev/[a-z]+[^(]*)|;
19dcd1ad
DC
298 if ($fields->[1] =~ m|^osd-([^-]+)-|) {
299 my $type = $1;
248f43f5 300 # $result autovivification is wanted, to not creating empty hashes
79f4a7bf 301 if (($type eq 'block' || $type eq 'data') && $fields->[2] =~ m/ceph.osd_id=([^,]+)/) {
19dcd1ad
DC
302 $result->{$dev}->{osdid} = $1;
303 $result->{$dev}->{bluestore} = ($type eq 'block');
bfb3d42d
DC
304 if ($fields->[2] =~ m/ceph\.encrypted=1/) {
305 $result->{$dev}->{encrypted} = 1;
306 }
19dcd1ad 307 } else {
248f43f5 308 # undef++ becomes '1' (see `perldoc perlop`: Auto-increment)
19dcd1ad
DC
309 $result->{$dev}->{$type}++;
310 }
311 }
312 });
313
314 return $result;
315}
316
cbba9b5b
DC
317sub get_udev_info {
318 my ($dev) = @_;
319
320 my $info = "";
321 my $data = {};
322 eval {
d3a5e309 323 run_command(['udevadm', 'info', '-p', $dev, '--query', 'all'], outfunc => sub {
cbba9b5b
DC
324 my ($line) = @_;
325 $info .= "$line\n";
326 });
327 };
328 warn $@ if $@;
329 return undef if !$info;
330
331 return undef if $info !~ m/^E: DEVTYPE=disk$/m;
332 return undef if $info =~ m/^E: ID_CDROM/m;
333
334 # we use this, because some disks are not simply in /dev
335 # e.g. /dev/cciss/c0d0
336 if ($info =~ m/^E: DEVNAME=(\S+)$/m) {
337 $data->{devpath} = $1;
338 }
339 return if !defined($data->{devpath});
340
341 $data->{serial} = 'unknown';
342 if ($info =~ m/^E: ID_SERIAL_SHORT=(\S+)$/m) {
343 $data->{serial} = $1;
344 }
345
346 $data->{gpt} = 0;
347 if ($info =~ m/^E: ID_PART_TABLE_TYPE=gpt$/m) {
348 $data->{gpt} = 1;
349 }
350
351 # detect SSD
352 $data->{rpm} = -1;
353 if ($info =~ m/^E: ID_ATA_ROTATION_RATE_RPM=(\d+)$/m) {
354 $data->{rpm} = $1;
355 }
356
357 if ($info =~ m/^E: ID_BUS=usb$/m) {
358 $data->{usb} = 1;
359 }
360
865bdbd9
DC
361 if ($info =~ m/^E: ID_MODEL=(.+)$/m) {
362 $data->{model} = $1;
363 }
364
cbba9b5b
DC
365 $data->{wwn} = 'unknown';
366 if ($info =~ m/^E: ID_WWN=(.*)$/m) {
367 $data->{wwn} = $1;
368 }
369
0f0d99a3
SI
370 if ($info =~ m/^E: DEVLINKS=(.+)$/m) {
371 my @devlinks = grep(m#^/dev/disk/by-id/(ata|scsi|nvme(?!-eui))#, split (/ /, $1));
372 $data->{by_id_link} = $devlinks[0] if defined($devlinks[0]);
373 }
374
cbba9b5b
DC
375 return $data;
376}
377
40be5c5c
FE
378sub get_sysdir_size {
379 my ($sysdir) = @_;
380
381 my $size = file_read_firstline("$sysdir/size");
382 return if !$size;
383
384 # linux always considers sectors to be 512 bytes,
385 # independently of real block size
386 return $size * 512;
387}
388
cbba9b5b
DC
389sub get_sysdir_info {
390 my ($sysdir) = @_;
391
461a9fd8
DC
392 return undef if ! -d "$sysdir/device";
393
cbba9b5b
DC
394 my $data = {};
395
40be5c5c 396 $data->{size} = get_sysdir_size($sysdir) or return;
cbba9b5b
DC
397
398 # dir/queue/rotational should be 1 for hdd, 0 for ssd
571b6f26 399 $data->{rotational} = file_read_firstline("$sysdir/queue/rotational") // -1;
cbba9b5b
DC
400
401 $data->{vendor} = file_read_firstline("$sysdir/device/vendor") || 'unknown';
402 $data->{model} = file_read_firstline("$sysdir/device/model") || 'unknown';
403
c3442aa5
WB
404 if (defined(my $device = readlink("$sysdir/device"))) {
405 # strip directory and untaint:
406 ($data->{device}) = $device =~ m!([^/]+)$!;
407 }
408
cbba9b5b
DC
409 return $data;
410}
411
6965a670 412sub get_wear_leveling_info {
dbad606d 413 my ($smartdata) = @_;
ea928fd4
DC
414 my $attributes = $smartdata->{attributes};
415
416 if (defined($smartdata->{wearout})) {
417 return $smartdata->{wearout};
418 }
6965a670
DC
419
420 my $wearout;
421
dbad606d
JJS
422 # Common register names that represent percentage values of potential
423 # failure indicators used in drivedb.h of smartmontool's. Order matters,
424 # as some drives may have multiple definitions
425 my @wearoutregisters = (
426 "Media_Wearout_Indicator",
427 "SSD_Life_Left",
428 "Wear_Leveling_Count",
429 "Perc_Write\/Erase_Ct_BC",
430 "Perc_Rated_Life_Remain",
431 "Remaining_Lifetime_Perc",
432 "Percent_Lifetime_Remain",
433 "Lifetime_Left",
434 "PCT_Life_Remaining",
435 "Lifetime_Remaining",
436 "Percent_Life_Remaining",
437 "Percent_Lifetime_Used",
438 "Perc_Rated_Life_Used"
439 );
440
441 # Search for S.M.A.R.T. attributes for known register
442 foreach my $register (@wearoutregisters) {
443 last if defined $wearout;
444 foreach my $attr (@$attributes) {
445 next if $attr->{name} !~ m/$register/;
446 $wearout = $attr->{value};
447 last;
6965a670
DC
448 }
449 }
450
6965a670
DC
451 return $wearout;
452}
453
10a48db5
DC
454sub dir_is_empty {
455 my ($dir) = @_;
456
457 my $dh = IO::Dir->new ($dir);
458 return 1 if !$dh;
459
460 while (defined(my $tmp = $dh->read)) {
461 next if $tmp eq '.' || $tmp eq '..';
462 $dh->close;
463 return 0;
464 }
465 $dh->close;
466 return 1;
467}
468
eebcdb11
DC
469sub is_iscsi {
470 my ($sysdir) = @_;
471
472 if (-l $sysdir && readlink($sysdir) =~ m|host[^/]*/session[^/]*|) {
473 return 1;
474 }
475
476 return 0;
477}
478
4731eb11
TL
479my sub is_ssdlike {
480 my ($type) = @_;
481 return $type eq 'ssd' || $type eq 'nvme';
482}
483
7e14102a 484sub mounted_blockdevs {
cbba9b5b
DC
485 my $mounted = {};
486
487 my $mounts = PVE::ProcFSTools::parse_proc_mounts();
488
489 foreach my $mount (@$mounts) {
490 next if $mount->[0] !~ m|^/dev/|;
491 $mounted->{abs_path($mount->[0])} = $mount->[1];
492 };
493
7e14102a
FE
494 return $mounted;
495}
496
497sub get_disks {
498 my ($disks, $nosmart, $include_partitions) = @_;
499 my $disklist = {};
500
501 my $mounted = mounted_blockdevs();
502
b6bbc2ab 503 my $lsblk_info = get_lsblk_info();
8cd6d7e8 504
b6bbc2ab 505 my $journalhash = get_ceph_journals($lsblk_info);
19dcd1ad 506 my $ceph_volume_infos = get_ceph_volume_infos();
cbba9b5b 507
b6bbc2ab 508 my $zfshash = get_zfs_devices($lsblk_info);
cbba9b5b 509
b6bbc2ab 510 my $lvmhash = get_lvm_devices($lsblk_info);
cbba9b5b 511
52a064af
DC
512 my $disk_regex = ".*";
513 if (defined($disks)) {
514 if (!ref($disks)) {
515 $disks = [ $disks ];
516 } elsif (ref($disks) ne 'ARRAY') {
517 die "disks is not a string or array reference\n";
518 }
519 # we get cciss/c0d0 but need cciss!c0d0
5045e0b7 520 $_ =~ s|cciss/|cciss!| for @$disks;
52a064af
DC
521
522 $disk_regex = "(?:" . join('|', @$disks) . ")";
1590fc13
DC
523 }
524
52a064af 525 dir_glob_foreach('/sys/block', $disk_regex, sub {
cbba9b5b 526 my ($dev) = @_;
cbba9b5b
DC
527 # whitelisting following devices
528 # hdX: ide block device
529 # sdX: sd block device
530 # vdX: virtual block device
531 # xvdX: xen virtual block device
532 # nvmeXnY: nvme devices
38ddd4ce 533 # cciss!cXnY: cciss devices
cbba9b5b
DC
534 return if $dev !~ m/^(h|s|x?v)d[a-z]+$/ &&
535 $dev !~ m/^nvme\d+n\d+$/ &&
38ddd4ce 536 $dev !~ m/^cciss\!c\d+d\d+$/;
cbba9b5b 537
532e89e7 538 my $data = get_udev_info("/sys/block/$dev");
cbba9b5b
DC
539 return if !defined($data);
540 my $devpath = $data->{devpath};
541
542 my $sysdir = "/sys/block/$dev";
543
cbba9b5b 544 # we do not want iscsi devices
eebcdb11 545 return if is_iscsi($sysdir);
cbba9b5b
DC
546
547 my $sysdata = get_sysdir_info($sysdir);
548 return if !defined($sysdata);
549
550 my $type = 'unknown';
551
552 if ($sysdata->{rotational} == 0) {
553 $type = 'ssd';
4731eb11 554 $type = 'nvme' if $dev =~ m/^nvme\d+n\d+$/;
cbba9b5b
DC
555 $data->{rpm} = 0;
556 } elsif ($sysdata->{rotational} == 1) {
557 if ($data->{rpm} != -1) {
558 $type = 'hdd';
559 } elsif ($data->{usb}) {
560 $type = 'usb';
561 $data->{rpm} = 0;
562 }
563 }
564
acd3d916 565 my $health = 'UNKNOWN';
6965a670 566 my $wearout = 'N/A';
7a98a62d
FG
567
568 if (!$nosmart) {
569 eval {
4731eb11 570 my $smartdata = get_smart_data($devpath, !is_ssdlike($type));
dd902da7
DC
571 $health = $smartdata->{health} if $smartdata->{health};
572
4731eb11 573 if (is_ssdlike($type)) {
7a98a62d 574 # if we have an ssd we try to get the wearout indicator
dbad606d 575 my $wearval = get_wear_leveling_info($smartdata);
9250ddfe 576 $wearout = $wearval if defined($wearval);
acd3d916 577 }
7a98a62d
FG
578 };
579 }
cbba9b5b 580
fc7c0e05
DC
581 # we replaced cciss/ with cciss! above
582 # but in the result we need cciss/ again
583 # because the caller might want to check the
584 # result again with the original parameter
585 if ($dev =~ m|^cciss!|) {
586 $dev =~ s|^cciss!|cciss/|;
587 }
588
cbba9b5b
DC
589 $disklist->{$dev} = {
590 vendor => $sysdata->{vendor},
865bdbd9 591 model => $data->{model} || $sysdata->{model},
cbba9b5b
DC
592 size => $sysdata->{size},
593 serial => $data->{serial},
594 gpt => $data->{gpt},
595 rpm => $data->{rpm},
596 type => $type,
597 wwn => $data->{wwn},
598 health => $health,
599 devpath => $devpath,
600 wearout => $wearout,
601 };
602
0f0d99a3
SI
603 my $by_id_link = $data->{by_id_link};
604 $disklist->{$dev}->{by_id_link} = $by_id_link if defined($by_id_link);
605
cbba9b5b 606 my $osdid = -1;
e2bd817c 607 my $bluestore = 0;
bfb3d42d 608 my $osdencrypted = 0;
cbba9b5b
DC
609
610 my $journal_count = 0;
e2bd817c
DC
611 my $db_count = 0;
612 my $wal_count = 0;
cbba9b5b 613
cbba9b5b
DC
614 my $partpath = $devpath;
615
616 # remove part after last / to
617 # get the base path for the partitions
618 # e.g. from /dev/cciss/c0d0 get /dev/cciss
619 $partpath =~ s/\/[^\/]+$//;
620
01aa7d75
FE
621 my $determine_usage = sub {
622 my ($devpath, $sysdir, $is_partition) = @_;
623
624 return 'LVM' if $lvmhash->{$devpath};
625 return 'ZFS' if $zfshash->{$devpath};
626
627 my $info = $lsblk_info->{$devpath} // {};
d3857eeb
FE
628
629 my $parttype = $info->{parttype};
630 if (defined($parttype)) {
631 return 'BIOS boot'
632 if $parttype eq '21686148-6449-6e6f-744e-656564454649';
633 return 'EFI'
634 if $parttype eq 'c12a7328-f81f-11d2-ba4b-00a0c93ec93b';
635 return 'ZFS reserved'
636 if $parttype eq '6a945a3b-1dd2-11b2-99a6-080020736631';
637 }
638
01aa7d75
FE
639 my $fstype = $info->{fstype};
640 if (defined($fstype)) {
641 return "${fstype} (mounted)" if $mounted->{$devpath};
642 return "${fstype}";
643 }
644 return 'mounted' if $mounted->{$devpath};
645
646 return if !$is_partition;
647
648 # for devices, this check is done explicitly later
649 return 'Device Mapper' if !dir_is_empty("$sysdir/holders");
650
651 return 'partition';
652 };
653
41f93ece
FE
654 my $collect_ceph_info = sub {
655 my ($devpath) = @_;
656
657 my $ceph_volume = $ceph_volume_infos->{$devpath} or return;
658 $journal_count += $ceph_volume->{journal} // 0;
659 $db_count += $ceph_volume->{db} // 0;
660 $wal_count += $ceph_volume->{wal} // 0;
661 if (defined($ceph_volume->{osdid})) {
662 $osdid = $ceph_volume->{osdid};
663 $bluestore = 1 if $ceph_volume->{bluestore};
664 $osdencrypted = 1 if $ceph_volume->{encrypted};
665 }
6a1919b1
FE
666
667 my $result = { %{$ceph_volume} };
668 $result->{journals} = delete $result->{journal}
669 if $result->{journal};
670 return $result;
41f93ece
FE
671 };
672
89c27ea8
FE
673 my $partitions = {};
674
cbba9b5b
DC
675 dir_glob_foreach("$sysdir", "$dev.+", sub {
676 my ($part) = @_;
677
6a1919b1
FE
678 $partitions->{$part} = $collect_ceph_info->("$partpath/$part");
679 my $lvm_based_osd = defined($partitions->{$part});
680
89c27ea8 681 $partitions->{$part}->{devpath} = "$partpath/$part";
2949c537 682 $partitions->{$part}->{parent} = "$devpath";
89c27ea8 683 $partitions->{$part}->{gpt} = $data->{gpt};
31ed94cc 684 $partitions->{$part}->{type} = 'partition';
89c27ea8
FE
685 $partitions->{$part}->{size} =
686 get_sysdir_size("$sysdir/$part") // 0;
01aa7d75
FE
687 $partitions->{$part}->{used} =
688 $determine_usage->("$partpath/$part", "$sysdir/$part", 1);
6a1919b1 689 $partitions->{$part}->{osdid} //= -1;
41f93ece
FE
690
691 # Avoid counting twice (e.g. partition on which the LVM for the
692 # DB OSD resides is present in the $journalhash)
693 return if $lvm_based_osd;
694
695 # Legacy handling for non-LVM based OSDs
696
0cca5356 697 if (my $mp = $mounted->{"$partpath/$part"}) {
cbba9b5b
DC
698 if ($mp =~ m|^/var/lib/ceph/osd/ceph-(\d+)$|) {
699 $osdid = $1;
6a1919b1 700 $partitions->{$part}->{osdid} = $osdid;
cbba9b5b
DC
701 }
702 }
703
0180fa42
TL
704 if (my $journal_part = $journalhash->{"$partpath/$part"}) {
705 $journal_count++ if $journal_part == 1;
706 $db_count++ if $journal_part == 2;
707 $wal_count++ if $journal_part == 3;
708 $bluestore = 1 if $journal_part == 4;
6a1919b1
FE
709
710 $partitions->{$part}->{journals} = 1 if $journal_part == 1;
711 $partitions->{$part}->{db} = 1 if $journal_part == 2;
712 $partitions->{$part}->{wal} = 1 if $journal_part == 3;
713 $partitions->{$part}->{bluestore} = 1 if $journal_part == 4;
e2bd817c 714 }
cbba9b5b
DC
715 });
716
01aa7d75 717 my $used = $determine_usage->($devpath, $sysdir, 0);
2949c537
FE
718 if (!$include_partitions) {
719 foreach my $part (sort keys %{$partitions}) {
720 next if $partitions->{$part}->{used} eq 'partition';
721 $used //= $partitions->{$part}->{used};
722 }
415dc398
FE
723 } else {
724 # fstype might be set even if there are partitions, but showing that is confusing
725 $used = 'partitions' if scalar(keys %{$partitions});
01aa7d75
FE
726 }
727 $used //= 'partitions' if scalar(keys %{$partitions});
cbba9b5b
DC
728 # multipath, software raid, etc.
729 # this check comes in last, to show more specific info
730 # if we have it
01aa7d75 731 $used //= 'Device Mapper' if !dir_is_empty("$sysdir/holders");
cbba9b5b
DC
732
733 $disklist->{$dev}->{used} = $used if $used;
41f93ece
FE
734
735 $collect_ceph_info->($devpath);
736
cbba9b5b 737 $disklist->{$dev}->{osdid} = $osdid;
e2bd817c
DC
738 $disklist->{$dev}->{journals} = $journal_count if $journal_count;
739 $disklist->{$dev}->{bluestore} = $bluestore if $osdid != -1;
bfb3d42d 740 $disklist->{$dev}->{osdencrypted} = $osdencrypted if $osdid != -1;
e2bd817c
DC
741 $disklist->{$dev}->{db} = $db_count if $db_count;
742 $disklist->{$dev}->{wal} = $wal_count if $wal_count;
2949c537
FE
743
744 if ($include_partitions) {
745 foreach my $part (keys %{$partitions}) {
746 $disklist->{$part} = $partitions->{$part};
747 }
748 }
cbba9b5b
DC
749 });
750
751 return $disklist;
752
753}
754
3196c387
WL
755sub get_partnum {
756 my ($part_path) = @_;
757
92ae59df 758 my $st = stat($part_path);
3196c387 759
ceb7b1ed
FE
760 die "error detecting block device '$part_path'\n"
761 if !$st || !$st->mode || !S_ISBLK($st->mode) || !$st->rdev;
762
92ae59df
AA
763 my $major = PVE::Tools::dev_t_major($st->rdev);
764 my $minor = PVE::Tools::dev_t_minor($st->rdev);
3196c387
WL
765 my $partnum_path = "/sys/dev/block/$major:$minor/";
766
767 my $partnum;
768
769 $partnum = file_read_firstline("${partnum_path}partition");
770
481f6177 771 die "Partition does not exist\n" if !defined($partnum);
3196c387
WL
772
773 #untaint and ensure it is a int
774 if ($partnum =~ m/(\d+)/) {
775 $partnum = $1;
776 die "Partition number $partnum is invalid\n" if $partnum > 128;
777 } else {
778 die "Failed to get partition number\n";
779 }
780
781 return $partnum;
782}
783
0d28307d
WL
784sub get_blockdev {
785 my ($part_path) = @_;
786
1207620c
TL
787 my ($dev, $block_dev);
788 if ($part_path =~ m|^/dev/(.*)$|) {
789 $dev = $1;
790 my $link = readlink "/sys/class/block/$dev";
791 $block_dev = $1 if $link =~ m|([^/]*)/$dev$|;
792 }
0d28307d
WL
793
794 die "Can't parse parent device\n" if !defined($block_dev);
795 die "No valid block device\n" if index($dev, $block_dev) == -1;
796
797 $block_dev = "/dev/$block_dev";
798 die "Block device does not exsists\n" if !(-b $block_dev);
799
800 return $block_dev;
801}
802
e39e8ee2
DC
803sub locked_disk_action {
804 my ($sub) = @_;
805 my $res = PVE::Tools::lock_file('/run/lock/pve-diskmanage.lck', undef, $sub);
806 die $@ if $@;
807 return $res;
808}
809
0370861c 810sub assert_disk_unused {
76c1e57b
DC
811 my ($dev) = @_;
812
0370861c 813 die "device '$dev' is already in use\n" if disk_is_used($dev);
76c1e57b
DC
814
815 return undef;
816}
817
1dc3038d
DC
818sub append_partition {
819 my ($dev, $size) = @_;
820
821 my $devname = $dev;
822 $devname =~ s|^/dev/||;
823
824 my $newpartid = 1;
825 dir_glob_foreach("/sys/block/$devname", qr/\Q$devname\E.*?(\d+)/, sub {
826 my ($part, $partid) = @_;
827
828 if ($partid >= $newpartid) {
829 $newpartid = $partid + 1;
830 }
831 });
832
833 $size = PVE::Tools::convert_size($size, 'b' => 'mb');
834
835 run_command([ $SGDISK, '-n', "$newpartid:0:+${size}M", $dev ],
836 errmsg => "error creating partition '$newpartid' on '$dev'");
837
838 my $partition;
839
840 # loop again to detect the real partiton device which does not always follow
841 # a strict $devname$partition scheme like /dev/nvme0n1 -> /dev/nvme0n1p1
842 dir_glob_foreach("/sys/block/$devname", qr/\Q$devname\E.*$newpartid/, sub {
843 my ($part) = @_;
844
845 $partition = "/dev/$part";
846 });
847
848 return $partition;
849}
850
cb057e21
FE
851# Check if a disk or any of its partitions has a holder.
852# Can also be called with a partition.
853# Expected to be called with a result of verify_blockdev_path().
854sub has_holder {
855 my ($devpath) = @_;
856
857 my $sysdir = "/sys/class/block/";
858
859 my $dev = $devpath;
860 $dev =~ s|^/dev/||;
861
862 return $devpath if !dir_is_empty("${sysdir}/${dev}/holders");
863
864 my $found;
865
866 dir_glob_foreach("/sys/block/${dev}", "${dev}.+", sub {
867 my ($part) = @_;
868
869 $found = "/dev/${part}" if !dir_is_empty("${sysdir}/${part}/holders");
870 });
871
872 return $found;
873}
874
3bf7f889
FE
875# Basic check if a disk or any of its partitions is mounted.
876# Can also be called with a partition.
877# Expected to be called with a result of verify_blockdev_path().
878sub is_mounted {
879 my ($devpath) = @_;
880
881 my $mounted = mounted_blockdevs();
882
883 return $devpath if $mounted->{$devpath};
884
885 my $dev = $devpath;
886 $dev =~ s|^/dev/||;
887
888 my $found;
889
890 dir_glob_foreach("/sys/block/${dev}", "${dev}.+", sub {
891 my ($part) = @_;
892
893 my $partpath = "/dev/${part}";
894
895 $found = $partpath if $mounted->{$partpath};
896 });
897
898 return $found;
899}
900
262ad7a9
FE
901# Wipes all labels and the first 200 MiB of a disk/partition (or the whole if it is smaller).
902# Expected to be called with a result of verify_blockdev_path().
903sub wipe_blockdev {
904 my ($devpath) = @_;
905
906 my $wipefs_cmd = ['wipefs', '--all', $devpath];
907
908 my $dd_cmd = ['dd', 'if=/dev/zero', "of=${devpath}", 'bs=1M', 'conv=fdatasync'];
909
910 my $devname = basename($devpath);
911 my $dev_size = PVE::Tools::file_get_contents("/sys/class/block/$devname/size");
912
913 ($dev_size) = $dev_size =~ m|(\d+)|; # untaint $dev_size
914 die "Couldn't get the size of the device $devname\n" if !defined($dev_size);
915
916 my $size = ($dev_size * 512 / 1024 / 1024);
917 my $count = ($size < 200) ? $size : 200;
918
919 push @{$dd_cmd}, "count=${count}";
920
921 print "wiping disk/partition: ${devpath}\n";
922
923 run_command($wipefs_cmd, errmsg => "error wiping labels for '${devpath}'");
924 run_command($dd_cmd, errmsg => "error wiping '${devpath}'");
925}
926
cbba9b5b 9271;