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