]>
git.proxmox.com Git - pve-storage.git/blob - PVE/Diskmanage.pm
1 package PVE
::Diskmanage
;
14 use PVE
::Tools
qw(extract_param run_command file_get_contents file_read_firstline dir_glob_regex dir_glob_foreach trim);
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";
23 my sub strip_dev
:prototype($) {
25 $devpath =~ s
|^/dev/||;
34 sub verify_blockdev_path
{
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;
41 die "got unusual device path '$path'\n" if $path !~ m
|^/dev/(.*)$|;
43 $path = "/dev/$1"; # untaint
45 assert_blockdev
($path);
51 my ($dev, $noerr) = @_;
53 if ($dev !~ m
|^/dev/| || !(-b
$dev)) {
55 die "not a valid block device\n";
62 my ($disk, $uuid) = @_;
64 assert_blockdev
($disk);
66 # we should already have checked these in the api call, but we check again for safety
67 die "$disk is a partition\n" if is_partition
($disk);
68 die "disk $disk is already in use\n" if disk_is_used
($disk);
70 my $id = $uuid || 'R';
71 run_command
([$SGDISK, $disk, '-U', $id]);
81 my $disklist = get_disks
($dev, 1, 1);
83 die "'$disk' is not a valid local disk\n" if !defined($disklist->{$dev});
84 return 1 if $disklist->{$dev}->{used
};
90 my ($disk, $healthonly) = @_;
92 assert_blockdev
($disk);
96 if ($disk =~ m!^/dev/(nvme\d+n\d+)$!) {
97 my $info = get_sysdir_info
("/sys/block/$1");
98 $disk = "/dev/".($info->{device
}
99 or die "failed to get nvme controller device for $disk\n");
102 my $cmd = [$SMARTCTL, '-H'];
103 push @$cmd, '-A', '-f', 'brief' if !$healthonly;
106 my $returncode = eval {
107 run_command
($cmd, noerr
=> 1, outfunc
=> sub {
110 # ATA SMART attributes, e.g.:
111 # ID# ATTRIBUTE_NAME FLAGS VALUE WORST THRESH FAIL RAW_VALUE
112 # 1 Raw_Read_Error_Rate POSR-K 100 100 000 - 0
114 # SAS and NVME disks, e.g.:
115 # Data Units Written: 5,584,952 [2.85 TB]
116 # Accumulated start-stop cycles: 34
118 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 $entry->{name
} = $2 if defined $2;
122 $entry->{flags
} = $3 if defined $3;
123 # the +0 makes a number out of the strings
124 # fixme remove next line in major release, use normalized instead
125 $entry->{value
} = $4+0 if defined $4;
126 $entry->{normalized
} = $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;
132 $entry->{threshold
} = $6+0 if defined $6;
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:/) {
142 delete $smartdata->{text
};
143 } elsif ($line =~ m/=== START OF (READ )?SMART DATA SECTION ===/) {
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;
152 } elsif ($line =~ m/SMART Disabled/) {
153 $smartdata->{health
} = "SMART Disabled";
159 # bit 0 and 1 mark a fatal error, other bits are for disk status -> ignore (see man 8 smartctl)
160 if ((defined($returncode) && ($returncode & 0b00000011)) || $err) {
161 die "Error getting S.M.A.R.T. data: Exit code: $returncode\n";
164 $smartdata->{type
} = $type;
170 my $cmd = [$LSBLK, '--json', '-o', 'path,parttype,fstype'];
172 eval { run_command
($cmd, outfunc
=> sub { $output .= "$_[0]\n"; }) };
174 return {} if $output eq '';
176 my $parsed = eval { decode_json
($output) } // {};
178 my $list = $parsed->{blockdevices
} // [];
183 parttype
=> $_->{parttype
},
184 fstype
=> $_->{fstype
}
190 my sub get_devices_by_partuuid
{
191 my ($lsblk_info, $uuids, $res) = @_;
193 $res = {} if !defined($res);
195 foreach my $dev (sort keys %{$lsblk_info}) {
196 my $uuid = $lsblk_info->{$dev}->{parttype
};
197 next if !defined($uuid) || !defined($uuids->{$uuid});
198 $res->{$dev} = $uuids->{$uuid};
204 sub get_zfs_devices
{
205 my ($lsblk_info) = @_;
208 return {} if !check_bin
($ZPOOL);
210 # use zpool and parttype uuid, because log and cache do not have zfs type uuid
212 run_command
([$ZPOOL, 'list', '-HPLv'], outfunc
=> sub {
214 if ($line =~ m
|^\t([^\t]+)\t|) {
220 # only warn here, because maybe zfs tools are not installed
224 "6a898cc3-1dd2-11b2-99a6-080020736631" => 1, # apple
225 "516e7cba-6ecf-11d6-8ff8-00022d09712b" => 1, # bsd
229 $res = get_devices_by_partuuid
($lsblk_info, $uuids, $res);
234 sub get_lvm_devices
{
235 my ($lsblk_info) = @_;
238 run_command
([$PVS, '--noheadings', '--readonly', '-o', 'pv_name'], outfunc
=> sub{
241 if ($line =~ m
|^/dev/|) {
247 # if something goes wrong, we do not want to give up, but indicate an error has occurred
251 "e6d6d379-f507-44c2-a23c-238f2a3df928" => 1,
254 $res = get_devices_by_partuuid
($lsblk_info, $uuids, $res);
259 sub get_ceph_journals
{
260 my ($lsblk_info) = @_;
264 '45b0969e-9b03-4f30-b4c6-b4b80ceff106' => 1, # journal
265 '30cd0809-c2b2-499c-8879-2d6b78529876' => 2, # db
266 '5ce17fce-4087-4169-b7ff-056cc58473f9' => 3, # wal
267 'cafecafe-9b03-4f30-b4c6-b4b80ceff106' => 4, # block
270 $res = get_devices_by_partuuid
($lsblk_info, $uuids, $res);
275 # reads the lv_tags and matches them with the devices
276 sub get_ceph_volume_infos
{
279 my $cmd = [ $LVS, '-S', 'lv_name=~^osd-', '-o', 'devices,lv_name,lv_tags',
280 '--noheadings', '--readonly', '--separator', ';' ];
282 run_command
($cmd, outfunc
=> sub {
284 $line =~ s/(?:^\s+)|(?:\s+$)//g; # trim whitespaces
286 my $fields = [ split(';', $line) ];
288 # lvs syntax is /dev/sdX(Y) where Y is the start (which we do not need)
289 my ($dev) = $fields->[0] =~ m
|^(/dev/[a-z
]+[^(]*)|;
290 if ($fields->[1] =~ m
|^osd-
([^-]+)-|) {
292 # $result autovivification is wanted, to not creating empty hashes
293 if (($type eq 'block' || $type eq 'data') && $fields->[2] =~ m/ceph.osd_id=([^,]+)/) {
294 $result->{$dev}->{osdid
} = $1;
295 $result->{$dev}->{bluestore
} = ($type eq 'block');
296 if ($fields->[2] =~ m/ceph\.encrypted=1/) {
297 $result->{$dev}->{encrypted
} = 1;
300 # undef++ becomes '1' (see `perldoc perlop`: Auto-increment)
301 $result->{$dev}->{$type}++;
315 run_command
(['udevadm', 'info', '-p', $dev, '--query', 'all'], outfunc
=> sub {
323 return if $info !~ m/^E: DEVTYPE=(disk|partition)$/m;
324 return if $info =~ m/^E: ID_CDROM/m;
326 # we use this, because some disks are not simply in /dev e.g. /dev/cciss/c0d0
327 if ($info =~ m/^E: DEVNAME=(\S+)$/m) {
328 $data->{devpath
} = $1;
330 return if !defined($data->{devpath
});
332 $data->{serial
} = 'unknown';
333 $data->{serial
} = $1 if $info =~ m/^E: ID_SERIAL_SHORT=(\S+)$/m;
335 $data->{gpt
} = $info =~ m/^E: ID_PART_TABLE_TYPE=gpt$/m ?
1 : 0;
338 $data->{rpm
} = $1 if $info =~ m/^E: ID_ATA_ROTATION_RATE_RPM=(\d+)$/m; # detects SSD implicit
340 $data->{usb
} = 1 if $info =~ m/^E: ID_BUS=usb$/m;
342 $data->{model
} = $1 if $info =~ m/^E: ID_MODEL=(.+)$/m;
344 $data->{wwn
} = 'unknown';
345 $data->{wwn
} = $1 if $info =~ m/^E: ID_WWN=(.*)$/m;
347 if ($info =~ m/^E: DEVLINKS=(.+)$/m) {
348 my @devlinks = grep(m
#^/dev/disk/by-id/(ata|scsi|nvme(?!-eui))#, split (/ /, $1));
349 $data->{by_id_link
} = $devlinks[0] if defined($devlinks[0]);
355 sub get_sysdir_size
{
358 my $size = file_read_firstline
("$sysdir/size");
361 # linux always considers sectors to be 512 bytes, independently of real block size
365 sub get_sysdir_info
{
368 return if ! -d
"$sysdir/device";
372 $data->{size
} = get_sysdir_size
($sysdir) or return;
374 # dir/queue/rotational should be 1 for hdd, 0 for ssd
375 $data->{rotational
} = file_read_firstline
("$sysdir/queue/rotational") // -1;
377 $data->{vendor
} = file_read_firstline
("$sysdir/device/vendor") || 'unknown';
378 $data->{model
} = file_read_firstline
("$sysdir/device/model") || 'unknown';
380 if (defined(my $device = readlink("$sysdir/device"))) {
381 ($data->{device
}) = $device =~ m!([^/]+)$!; # strip directory and untaint
387 sub get_wear_leveling_info
{
388 my ($smartdata) = @_;
389 my $attributes = $smartdata->{attributes
};
391 if (defined($smartdata->{wearout
})) {
392 return $smartdata->{wearout
};
397 # Common register names that represent percentage values of potential failure indicators used
398 # in drivedb.h of smartmontool's. Order matters, as some drives may have multiple definitions
399 my @wearoutregisters = (
400 "Media_Wearout_Indicator",
402 "Wear_Leveling_Count",
403 "Perc_Write\/Erase_Ct_BC",
404 "Perc_Rated_Life_Remain",
405 "Remaining_Lifetime_Perc",
406 "Percent_Lifetime_Remain",
408 "PCT_Life_Remaining",
409 "Lifetime_Remaining",
410 "Percent_Life_Remaining",
411 "Percent_Lifetime_Used",
412 "Perc_Rated_Life_Used"
415 # Search for S.M.A.R.T. attributes for known register
416 foreach my $register (@wearoutregisters) {
417 last if defined $wearout;
418 foreach my $attr (@$attributes) {
419 next if $attr->{name
} !~ m/$register/;
420 $wearout = $attr->{value
};
431 my $dh = IO
::Dir-
>new ($dir);
434 while (defined(my $tmp = $dh->read)) {
435 next if $tmp eq '.' || $tmp eq '..';
446 if (-l
$sysdir && readlink($sysdir) =~ m
|host
[^/]*/session
[^/]*|) {
455 return $type eq 'ssd' || $type eq 'nvme';
458 sub mounted_blockdevs
{
461 my $mounts = PVE
::ProcFSTools
::parse_proc_mounts
();
463 foreach my $mount (@$mounts) {
464 next if $mount->[0] !~ m
|^/dev/|;
465 $mounted->{abs_path
($mount->[0])} = $mount->[1];
471 # returns hashmap of abs mount path -> first part of /proc/mounts (what)
475 my $mounts = PVE
::ProcFSTools
::parse_proc_mounts
();
477 foreach my $mount (@$mounts) {
478 $mounted->{abs_path
($mount->[1])} = $mount->[0];
485 my ($disks, $nosmart, $include_partitions) = @_;
488 my $mounted = mounted_blockdevs
();
490 my $lsblk_info = get_lsblk_info
();
492 my $journalhash = get_ceph_journals
($lsblk_info);
493 my $ceph_volume_infos = get_ceph_volume_infos
();
495 my $zfshash = get_zfs_devices
($lsblk_info);
497 my $lvmhash = get_lvm_devices
($lsblk_info);
499 my $disk_regex = ".*";
500 if (defined($disks)) {
503 } elsif (ref($disks) ne 'ARRAY') {
504 die "disks is not a string or array reference\n";
506 # we get cciss/c0d0 but need cciss!c0d0
507 $_ =~ s
|cciss
/|cciss
!| for @$disks;
509 if ($include_partitions) {
510 # Proper blockdevice is needed for the regex, use parent for partitions.
511 for my $disk ($disks->@*) {
512 next if !is_partition
("/dev/$disk");
513 $disk = strip_dev
(get_blockdev
("/dev/$disk"));
517 $disk_regex = "(?:" . join('|', @$disks) . ")";
520 dir_glob_foreach
('/sys/block', $disk_regex, sub {
522 # whitelisting following devices
523 # - hdX ide block device
524 # - sdX scsi/sata block device
525 # - vdX virtIO block device
526 # - xvdX: xen virtual block device
527 # - nvmeXnY: nvme devices
528 # - cciss!cXnY cciss devices
529 return if $dev !~ m/^(h|s|x?v)d[a-z]+$/ &&
530 $dev !~ m/^nvme\d+n\d+$/ &&
531 $dev !~ m/^cciss\!c\d+d\d+$/;
533 my $data = get_udev_info
("/sys/block/$dev") // return;
534 my $devpath = $data->{devpath
};
536 my $sysdir = "/sys/block/$dev";
538 # we do not want iscsi devices
539 return if is_iscsi
($sysdir);
541 my $sysdata = get_sysdir_info
($sysdir);
542 return if !defined($sysdata);
544 my $type = 'unknown';
546 if ($sysdata->{rotational
} == 0) {
548 $type = 'nvme' if $dev =~ m/^nvme\d+n\d+$/;
550 } elsif ($sysdata->{rotational
} == 1) {
551 if ($data->{rpm
} != -1) {
553 } elsif ($data->{usb
}) {
559 my ($health, $wearout) = ('UNKNOWN', 'N/A');
562 my $smartdata = get_smart_data
($devpath, !is_ssdlike
($type));
563 $health = $smartdata->{health
} if $smartdata->{health
};
565 if (is_ssdlike
($type)) { # if we have an ssd we try to get the wearout indicator
566 my $wear_level = get_wear_leveling_info
($smartdata);
567 $wearout = $wear_level if defined($wear_level);
572 # we replaced cciss/ with cciss! above, but in the result we need cciss/ again because the
573 # caller might want to check the result again with the original parameter
574 if ($dev =~ m
|^cciss
!|) {
575 $dev =~ s
|^cciss
!|cciss
/|;
578 $disklist->{$dev} = {
579 vendor
=> $sysdata->{vendor
},
580 model
=> $data->{model
} || $sysdata->{model
},
581 size
=> $sysdata->{size
},
582 serial
=> $data->{serial
},
591 $disklist->{$dev}->{mounted
} = 1 if exists $mounted->{$devpath};
593 my $by_id_link = $data->{by_id_link
};
594 $disklist->{$dev}->{by_id_link
} = $by_id_link if defined($by_id_link);
596 my ($osdid, $bluestore, $osdencrypted) = (-1, 0, 0);
597 my ($journal_count, $db_count, $wal_count) = (0, 0, 0);
599 my $partpath = $devpath;
600 # remove trailing part to get the partition base path, e.g. /dev/cciss/c0d0 -> /dev/cciss
601 $partpath =~ s/\/[^\/]+$//;
603 my $determine_usage = sub {
604 my ($devpath, $sysdir, $is_partition) = @_;
606 return 'LVM' if $lvmhash->{$devpath};
607 return 'ZFS' if $zfshash->{$devpath};
609 my $info = $lsblk_info->{$devpath} // {};
611 if (defined(my $parttype = $info->{parttype
})) {
612 return 'BIOS boot'if $parttype eq '21686148-6449-6e6f-744e-656564454649';
613 return 'EFI' if $parttype eq 'c12a7328-f81f-11d2-ba4b-00a0c93ec93b';
614 return 'ZFS reserved' if $parttype eq '6a945a3b-1dd2-11b2-99a6-080020736631';
617 return "$info->{fstype}" if defined($info->{fstype
});
618 return 'mounted' if $mounted->{$devpath};
620 return if !$is_partition;
622 # for devices, this check is done explicitly later
623 return 'Device Mapper' if !dir_is_empty
("$sysdir/holders");
625 return; # unused partition
628 my $collect_ceph_info = sub {
631 my $ceph_volume = $ceph_volume_infos->{$devpath} or return;
632 $journal_count += $ceph_volume->{journal
} // 0;
633 $db_count += $ceph_volume->{db
} // 0;
634 $wal_count += $ceph_volume->{wal
} // 0;
635 if (defined($ceph_volume->{osdid
})) {
636 $osdid = $ceph_volume->{osdid
};
637 $bluestore = 1 if $ceph_volume->{bluestore
};
638 $osdencrypted = 1 if $ceph_volume->{encrypted
};
641 my $result = { %{$ceph_volume} };
642 $result->{journals
} = delete $result->{journal
} if $result->{journal
};
647 dir_glob_foreach
("$sysdir", "$dev.+", sub {
650 $partitions->{$part} = $collect_ceph_info->("$partpath/$part");
651 my $lvm_based_osd = defined($partitions->{$part});
653 $partitions->{$part}->{devpath
} = "$partpath/$part";
654 $partitions->{$part}->{parent
} = "$devpath";
655 $partitions->{$part}->{mounted
} = 1 if exists $mounted->{"$partpath/$part"};
656 $partitions->{$part}->{gpt
} = $data->{gpt
};
657 $partitions->{$part}->{type
} = 'partition';
658 $partitions->{$part}->{size
} = get_sysdir_size
("$sysdir/$part") // 0;
659 $partitions->{$part}->{used
} = $determine_usage->("$partpath/$part", "$sysdir/$part", 1);
660 $partitions->{$part}->{osdid
} //= -1;
662 # avoid counting twice (e.g. partition with the LVM for the DB OSD is in $journalhash)
663 return if $lvm_based_osd;
665 # Legacy handling for non-LVM based OSDs
666 if (my $mp = $mounted->{"$partpath/$part"}) {
667 if ($mp =~ m
|^/var/lib
/ceph/osd/ceph-
(\d
+)$|) {
669 $partitions->{$part}->{osdid
} = $osdid;
673 if (my $journal_part = $journalhash->{"$partpath/$part"}) {
674 $journal_count++ if $journal_part == 1;
675 $db_count++ if $journal_part == 2;
676 $wal_count++ if $journal_part == 3;
677 $bluestore = 1 if $journal_part == 4;
679 $partitions->{$part}->{journals
} = 1 if $journal_part == 1;
680 $partitions->{$part}->{db
} = 1 if $journal_part == 2;
681 $partitions->{$part}->{wal
} = 1 if $journal_part == 3;
682 $partitions->{$part}->{bluestore
} = 1 if $journal_part == 4;
686 my $used = $determine_usage->($devpath, $sysdir, 0);
687 if (!$include_partitions) {
688 foreach my $part (sort keys %{$partitions}) {
689 $used //= $partitions->{$part}->{used
};
692 # fstype might be set even if there are partitions, but showing that is confusing
693 $used = 'partitions' if scalar(keys %{$partitions});
695 $used //= 'partitions' if scalar(keys %{$partitions});
696 # multipath, software raid, etc.
697 # this check comes in last, to show more specific info
699 $used //= 'Device Mapper' if !dir_is_empty
("$sysdir/holders");
701 $disklist->{$dev}->{used
} = $used if $used;
703 $collect_ceph_info->($devpath);
705 $disklist->{$dev}->{osdid
} = $osdid;
706 $disklist->{$dev}->{journals
} = $journal_count if $journal_count;
707 $disklist->{$dev}->{bluestore
} = $bluestore if $osdid != -1;
708 $disklist->{$dev}->{osdencrypted
} = $osdencrypted if $osdid != -1;
709 $disklist->{$dev}->{db
} = $db_count if $db_count;
710 $disklist->{$dev}->{wal
} = $wal_count if $wal_count;
712 if ($include_partitions) {
713 $disklist->{$_} = $partitions->{$_} for keys %{$partitions};
721 my ($part_path) = @_;
723 my $st = stat($part_path);
725 die "error detecting block device '$part_path'\n"
726 if !$st || !$st->mode || !S_ISBLK
($st->mode) || !$st->rdev;
728 my $major = PVE
::Tools
::dev_t_major
($st->rdev);
729 my $minor = PVE
::Tools
::dev_t_minor
($st->rdev);
730 my $partnum_path = "/sys/dev/block/$major:$minor/";
732 my $partnum = file_read_firstline
("${partnum_path}partition");
733 die "Partition does not exist\n" if !defined($partnum);
734 die "Failed to get partition number\n" if $partnum !~ m/(\d+)/; # untaint
736 die "Partition number $partnum is invalid\n" if $partnum > 128;
742 my ($part_path) = @_;
744 my ($dev, $block_dev);
745 if ($part_path =~ m
|^/dev/(.*)$|) {
747 my $link = readlink "/sys/class/block/$dev";
748 $block_dev = $1 if $link =~ m
|([^/]*)/$dev$|;
751 die "Can't parse parent device\n" if !defined($block_dev);
752 die "No valid block device\n" if index($dev, $block_dev) == -1;
754 $block_dev = "/dev/$block_dev";
755 die "Block device does not exists\n" if !(-b
$block_dev);
763 return defined(eval { get_partnum
($dev_path) });
766 sub locked_disk_action
{
768 my $res = PVE
::Tools
::lock_file
('/run/lock/pve-diskmanage.lck', undef, $sub);
773 sub assert_disk_unused
{
775 die "device '$dev' is already in use\n" if disk_is_used
($dev);
779 sub append_partition
{
780 my ($dev, $size) = @_;
783 $devname =~ s
|^/dev/||;
786 dir_glob_foreach
("/sys/block/$devname", qr
/\Q
$devname\E.*?
(\d
+)/, sub {
787 my ($part, $partid) = @_;
789 if ($partid >= $newpartid) {
790 $newpartid = $partid + 1;
794 $size = PVE
::Tools
::convert_size
($size, 'b' => 'mb');
796 run_command
([ $SGDISK, '-n', "$newpartid:0:+${size}M", $dev ],
797 errmsg
=> "error creating partition '$newpartid' on '$dev'");
801 # loop again to detect the real partition device which does not always follow
802 # a strict $devname$partition scheme like /dev/nvme0n1 -> /dev/nvme0n1p1
803 dir_glob_foreach
("/sys/block/$devname", qr
/\Q
$devname\E.*$newpartid/, sub {
806 $partition = "/dev/$part";
812 # Check if a disk or any of its partitions has a holder.
813 # Can also be called with a partition.
814 # Expected to be called with a result of verify_blockdev_path().
818 my $dev = strip_dev
($devpath);
820 return $devpath if !dir_is_empty
("/sys/class/block/${dev}/holders");
823 dir_glob_foreach
("/sys/block/${dev}", "${dev}.+", sub {
825 $found = "/dev/${part}" if !dir_is_empty
("/sys/class/block/${part}/holders");
831 # Basic check if a disk or any of its partitions is mounted.
832 # Can also be called with a partition.
833 # Expected to be called with a result of verify_blockdev_path().
837 my $mounted = mounted_blockdevs
();
839 return $devpath if $mounted->{$devpath};
841 my $dev = strip_dev
($devpath);
844 dir_glob_foreach
("/sys/block/${dev}", "${dev}.+", sub {
846 my $partpath = "/dev/${part}";
848 $found = $partpath if $mounted->{$partpath};
854 # Currently only supports GPT-partitioned disks.
855 sub change_parttype
{
856 my ($partpath, $parttype) = @_;
858 my $err = "unable to change partition type for $partpath";
860 my $partnum = get_partnum
($partpath);
861 my $blockdev = get_blockdev
($partpath);
862 my $dev = strip_dev
($blockdev);
864 my $info = get_disks
($dev, 1);
865 die "$err - unable to get disk info for '$blockdev'\n" if !defined($info->{$dev});
866 die "$err - disk '$blockdev' is not GPT partitioned\n" if !$info->{$dev}->{gpt
};
868 run_command
(['sgdisk', "-t${partnum}:${parttype}", $blockdev], errmsg
=> $err);
871 # Wipes all labels and the first 200 MiB of a disk/partition (or the whole if it is smaller).
872 # If called with a partition, also sets the partition type to 0x83 'Linux filesystem'.
873 # Expected to be called with a result of verify_blockdev_path().
877 my $devname = basename
($devpath);
878 my $dev_size = PVE
::Tools
::file_get_contents
("/sys/class/block/$devname/size");
880 ($dev_size) = $dev_size =~ m
|(\d
+)|; # untaint $dev_size
881 die "Couldn't get the size of the device $devname\n" if !defined($dev_size);
883 my $size = ($dev_size * 512 / 1024 / 1024);
884 my $count = ($size < 200) ?
$size : 200;
887 dir_glob_foreach
("/sys/class/block/${devname}", "${devname}.+", sub {
889 push $to_wipe->@*, "/dev/${part}" if -b
"/dev/${part}";
892 if (scalar($to_wipe->@*) > 0) {
893 print "found child partitions to wipe: ". join(', ', $to_wipe->@*) ."\n";
895 push $to_wipe->@*, $devpath; # put actual device last
897 print "wiping block device ${devpath}\n";
899 run_command
(['wipefs', '--all', $to_wipe->@*], errmsg
=> "error wiping '${devpath}'");
902 ['dd', 'if=/dev/zero', "of=${devpath}", 'bs=1M', 'conv=fdatasync', "count=${count}"],
903 errmsg
=> "error wiping '${devpath}'",
906 if (is_partition
($devpath)) {
907 eval { change_parttype
($devpath, '8300'); };
912 # FIXME: Remove once we depend on systemd >= v249.
913 # Work around udev bug https://github.com/systemd/systemd/issues/18525 ensuring database is updated.
914 sub udevadm_trigger
{
917 return if scalar(@devs) == 0;
919 eval { run_command
(['udevadm', 'trigger', @devs]); };