]>
git.proxmox.com Git - pve-storage.git/blob - PVE/Diskmanage.pm
1 package PVE
::Diskmanage
;
13 use PVE
::Tools
qw(extract_param run_command file_get_contents file_read_firstline dir_glob_regex dir_glob_foreach trim);
15 my $SMARTCTL = "/usr/sbin/smartctl";
16 my $ZPOOL = "/sbin/zpool";
17 my $SGDISK = "/sbin/sgdisk";
18 my $PVS = "/sbin/pvs";
19 my $LVS = "/sbin/lvs";
20 my $LSBLK = "/bin/lsblk";
28 sub verify_blockdev_path
{
31 die "missing path" if !$rel_path;
32 my $path = abs_path
($rel_path);
33 die "failed to get absolute path to $rel_path\n" if !$path;
35 die "got unusual device path '$path'\n" if $path !~ m
|^/dev/(.*)$|;
37 $path = "/dev/$1"; # untaint
39 assert_blockdev
($path);
45 my ($dev, $noerr) = @_;
47 if ($dev !~ m
|^/dev/| || !(-b
$dev)) {
48 return undef if $noerr;
49 die "not a valid block device\n";
56 my ($disk, $uuid) = @_;
58 assert_blockdev
($disk);
60 # we should already have checked if it is in use in the api call
61 # but we check again for safety
62 die "disk $disk is already in use\n" if disk_is_used
($disk);
64 my $id = $uuid || 'R';
65 run_command
([$SGDISK, $disk, '-U', $id]);
75 my $disklist = get_disks
($dev, 1);
77 die "'$disk' is not a valid local disk\n" if !defined($disklist->{$dev});
78 return 1 if $disklist->{$dev}->{used
};
84 my ($disk, $healthonly) = @_;
86 assert_blockdev
($disk);
92 if ($disk =~ m!^/dev/(nvme\d+n\d+)$!) {
93 my $info = get_sysdir_info
("/sys/block/$1");
94 $disk = "/dev/".($info->{device
}
95 or die "failed to get nvme controller device for $disk\n");
98 my $cmd = [$SMARTCTL, '-H'];
99 push @$cmd, '-A', '-f', 'brief' if !$healthonly;
103 $returncode = run_command
($cmd, noerr
=> 1, outfunc
=> sub{
106 # ATA SMART attributes, e.g.:
107 # ID# ATTRIBUTE_NAME FLAGS VALUE WORST THRESH FAIL RAW_VALUE
108 # 1 Raw_Read_Error_Rate POSR-K 100 100 000 - 0
110 # SAS and NVME disks, e.g.:
111 # Data Units Written: 5,584,952 [2.85 TB]
112 # Accumulated start-stop cycles: 34
114 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+(.*)$/) {
117 $entry->{name
} = $2 if defined $2;
118 $entry->{flags
} = $3 if defined $3;
119 # the +0 makes a number out of the strings
120 $entry->{value
} = $4+0 if defined $4;
121 $entry->{worst
} = $5+0 if defined $5;
122 # some disks report the default threshold as --- instead of 000
123 if (defined($6) && $6 eq '---') {
124 $entry->{threshold
} = 0;
126 $entry->{threshold
} = $6+0 if defined $6;
128 $entry->{fail
} = $7 if defined $7;
129 $entry->{raw
} = $8 if defined $8;
130 $entry->{id
} = $1 if defined $1;
131 push @{$smartdata->{attributes
}}, $entry;
132 } elsif ($line =~ m/(?:Health Status|self\-assessment test result): (.*)$/ ) {
133 $smartdata->{health
} = $1;
134 } elsif ($line =~ m/Vendor Specific SMART Attributes with Thresholds:/) {
136 delete $smartdata->{text
};
137 } elsif ($line =~ m/=== START OF (READ )?SMART DATA SECTION ===/) {
139 } elsif (defined($type) && $type eq 'text') {
140 $smartdata->{text
} = '' if !defined $smartdata->{text
};
141 $smartdata->{text
} .= "$line\n";
142 # extract wearout from nvme/sas text, allow for decimal values
143 if ($line =~ m/Percentage Used(?: endurance indicator)?:\s*(\d+(?:\.\d+)?)\%/i) {
144 $smartdata->{wearout
} = 100 - $1;
146 } elsif ($line =~ m/SMART Disabled/) {
147 $smartdata->{health
} = "SMART Disabled";
153 # bit 0 and 1 mark an severe smartctl error
154 # all others are for disk status, so ignore them
156 if ((defined($returncode) && ($returncode & 0b00000011)) || $err) {
157 die "Error getting S.M.A.R.T. data: Exit code: $returncode\n";
160 $smartdata->{type
} = $type;
165 sub get_lsblk_info
() {
166 my $cmd = [$LSBLK, '--json', '-o', 'path,parttype,fstype'];
170 run_command
($cmd, outfunc
=> sub {
172 $output .= "$line\n";
176 return $res if $output eq '';
178 my $parsed = eval { decode_json
($output) };
180 my $list = $parsed->{blockdevices
} // [];
184 parttype
=> $_->{parttype
},
185 fstype
=> $_->{fstype
}
192 my $get_devices_by_partuuid = sub {
193 my ($lsblk_info, $uuids, $res) = @_;
195 $res = {} if !defined($res);
197 foreach my $dev (sort keys %{$lsblk_info}) {
198 my $uuid = $lsblk_info->{$dev}->{parttype
};
199 next if !defined($uuid) || !defined($uuids->{$uuid});
200 $res->{$dev} = $uuids->{$uuid};
206 sub get_zfs_devices
{
207 my ($lsblk_info) = @_;
210 return {} if !check_bin
($ZPOOL);
212 # use zpool and parttype uuid,
213 # because log and cache do not have
216 run_command
([$ZPOOL, 'list', '-HPLv'], outfunc
=> sub {
219 if ($line =~ m
|^\t([^\t]+)\t|) {
226 # because maybe zfs tools are not installed
230 "6a898cc3-1dd2-11b2-99a6-080020736631" => 1, # apple
231 "516e7cba-6ecf-11d6-8ff8-00022d09712b" => 1, # bsd
235 $res = $get_devices_by_partuuid->($lsblk_info, $uuids, $res);
240 sub get_lvm_devices
{
241 my ($lsblk_info) = @_;
244 run_command
([$PVS, '--noheadings', '--readonly', '-o', 'pv_name'], outfunc
=> sub{
247 if ($line =~ m
|^/dev/|) {
253 # if something goes wrong, we do not want
254 # to give up, but indicate an error has occured
258 "e6d6d379-f507-44c2-a23c-238f2a3df928" => 1,
261 $res = $get_devices_by_partuuid->($lsblk_info, $uuids, $res);
266 sub get_ceph_journals
{
267 my ($lsblk_info) = @_;
271 '45b0969e-9b03-4f30-b4c6-b4b80ceff106' => 1, # journal
272 '30cd0809-c2b2-499c-8879-2d6b78529876' => 2, # db
273 '5ce17fce-4087-4169-b7ff-056cc58473f9' => 3, # wal
274 'cafecafe-9b03-4f30-b4c6-b4b80ceff106' => 4, # block
277 $res = $get_devices_by_partuuid->($lsblk_info, $uuids, $res);
282 # reads the lv_tags and matches them with the devices
283 sub get_ceph_volume_infos
{
286 my $cmd = [ $LVS, '-S', 'lv_name=~^osd-', '-o', 'devices,lv_name,lv_tags',
287 '--noheadings', '--readonly', '--separator', ';' ];
289 run_command
($cmd, outfunc
=> sub {
291 $line =~ s/(?:^\s+)|(?:\s+$)//g; # trim whitespaces
293 my $fields = [ split(';', $line) ];
295 # lvs syntax is /dev/sdX(Y) where Y is the start (which we do not need)
296 my ($dev) = $fields->[0] =~ m
|^(/dev/[a-z
]+[^(]*)|;
297 if ($fields->[1] =~ m
|^osd-
([^-]+)-|) {
299 # $result autovivification is wanted, to not creating empty hashes
300 if (($type eq 'block' || $type eq 'data') && $fields->[2] =~ m/ceph.osd_id=([^,]+)/) {
301 $result->{$dev}->{osdid
} = $1;
302 $result->{$dev}->{bluestore
} = ($type eq 'block');
303 if ($fields->[2] =~ m/ceph\.encrypted=1/) {
304 $result->{$dev}->{encrypted
} = 1;
307 # undef++ becomes '1' (see `perldoc perlop`: Auto-increment)
308 $result->{$dev}->{$type}++;
322 run_command
(['udevadm', 'info', '-p', $dev, '--query', 'all'], outfunc
=> sub {
328 return undef if !$info;
330 return undef if $info !~ m/^E: DEVTYPE=disk$/m;
331 return undef if $info =~ m/^E: ID_CDROM/m;
333 # we use this, because some disks are not simply in /dev
334 # e.g. /dev/cciss/c0d0
335 if ($info =~ m/^E: DEVNAME=(\S+)$/m) {
336 $data->{devpath
} = $1;
338 return if !defined($data->{devpath
});
340 $data->{serial
} = 'unknown';
341 if ($info =~ m/^E: ID_SERIAL_SHORT=(\S+)$/m) {
342 $data->{serial
} = $1;
346 if ($info =~ m/^E: ID_PART_TABLE_TYPE=gpt$/m) {
352 if ($info =~ m/^E: ID_ATA_ROTATION_RATE_RPM=(\d+)$/m) {
356 if ($info =~ m/^E: ID_BUS=usb$/m) {
360 if ($info =~ m/^E: ID_MODEL=(.+)$/m) {
364 $data->{wwn
} = 'unknown';
365 if ($info =~ m/^E: ID_WWN=(.*)$/m) {
369 if ($info =~ m/^E: DEVLINKS=(.+)$/m) {
370 my @devlinks = grep(m
#^/dev/disk/by-id/(ata|scsi|nvme(?!-eui))#, split (/ /, $1));
371 $data->{by_id_link
} = $devlinks[0] if defined($devlinks[0]);
377 sub get_sysdir_size
{
380 my $size = file_read_firstline
("$sysdir/size");
383 # linux always considers sectors to be 512 bytes,
384 # independently of real block size
388 sub get_sysdir_info
{
391 return undef if ! -d
"$sysdir/device";
395 $data->{size
} = get_sysdir_size
($sysdir) or return;
397 # dir/queue/rotational should be 1 for hdd, 0 for ssd
398 $data->{rotational
} = file_read_firstline
("$sysdir/queue/rotational") // -1;
400 $data->{vendor
} = file_read_firstline
("$sysdir/device/vendor") || 'unknown';
401 $data->{model
} = file_read_firstline
("$sysdir/device/model") || 'unknown';
403 if (defined(my $device = readlink("$sysdir/device"))) {
404 # strip directory and untaint:
405 ($data->{device
}) = $device =~ m!([^/]+)$!;
411 sub get_wear_leveling_info
{
412 my ($smartdata) = @_;
413 my $attributes = $smartdata->{attributes
};
415 if (defined($smartdata->{wearout
})) {
416 return $smartdata->{wearout
};
421 # Common register names that represent percentage values of potential
422 # failure indicators used in drivedb.h of smartmontool's. Order matters,
423 # as some drives may have multiple definitions
424 my @wearoutregisters = (
425 "Media_Wearout_Indicator",
427 "Wear_Leveling_Count",
428 "Perc_Write\/Erase_Ct_BC",
429 "Perc_Rated_Life_Remain",
430 "Remaining_Lifetime_Perc",
431 "Percent_Lifetime_Remain",
433 "PCT_Life_Remaining",
434 "Lifetime_Remaining",
435 "Percent_Life_Remaining",
436 "Percent_Lifetime_Used",
437 "Perc_Rated_Life_Used"
440 # Search for S.M.A.R.T. attributes for known register
441 foreach my $register (@wearoutregisters) {
442 last if defined $wearout;
443 foreach my $attr (@$attributes) {
444 next if $attr->{name
} !~ m/$register/;
445 $wearout = $attr->{value
};
456 my $dh = IO
::Dir-
>new ($dir);
459 while (defined(my $tmp = $dh->read)) {
460 next if $tmp eq '.' || $tmp eq '..';
471 if (-l
$sysdir && readlink($sysdir) =~ m
|host
[^/]*/session
[^/]*|) {
480 return $type eq 'ssd' || $type eq 'nvme';
484 my ($disks, $nosmart, $include_partitions) = @_;
489 my $mounts = PVE
::ProcFSTools
::parse_proc_mounts
();
491 foreach my $mount (@$mounts) {
492 next if $mount->[0] !~ m
|^/dev/|;
493 $mounted->{abs_path
($mount->[0])} = $mount->[1];
496 my $lsblk_info = get_lsblk_info
();
498 my $journalhash = get_ceph_journals
($lsblk_info);
499 my $ceph_volume_infos = get_ceph_volume_infos
();
501 my $zfshash = get_zfs_devices
($lsblk_info);
503 my $lvmhash = get_lvm_devices
($lsblk_info);
505 my $disk_regex = ".*";
506 if (defined($disks)) {
509 } elsif (ref($disks) ne 'ARRAY') {
510 die "disks is not a string or array reference\n";
512 # we get cciss/c0d0 but need cciss!c0d0
513 $_ =~ s
|cciss
/|cciss
!| for @$disks;
515 $disk_regex = "(?:" . join('|', @$disks) . ")";
518 dir_glob_foreach
('/sys/block', $disk_regex, sub {
520 # whitelisting following devices
521 # hdX: ide block device
522 # sdX: sd block device
523 # vdX: virtual block device
524 # xvdX: xen virtual block device
525 # nvmeXnY: nvme devices
526 # cciss!cXnY: cciss devices
527 return if $dev !~ m/^(h|s|x?v)d[a-z]+$/ &&
528 $dev !~ m/^nvme\d+n\d+$/ &&
529 $dev !~ m/^cciss\!c\d+d\d+$/;
531 my $data = get_udev_info
("/sys/block/$dev");
532 return if !defined($data);
533 my $devpath = $data->{devpath
};
535 my $sysdir = "/sys/block/$dev";
537 # we do not want iscsi devices
538 return if is_iscsi
($sysdir);
540 my $sysdata = get_sysdir_info
($sysdir);
541 return if !defined($sysdata);
543 my $type = 'unknown';
545 if ($sysdata->{rotational
} == 0) {
547 $type = 'nvme' if $dev =~ m/^nvme\d+n\d+$/;
549 } elsif ($sysdata->{rotational
} == 1) {
550 if ($data->{rpm
} != -1) {
552 } elsif ($data->{usb
}) {
558 my $health = 'UNKNOWN';
563 my $smartdata = get_smart_data
($devpath, !is_ssdlike
($type));
564 $health = $smartdata->{health
} if $smartdata->{health
};
566 if (is_ssdlike
($type)) {
567 # if we have an ssd we try to get the wearout indicator
568 my $wearval = get_wear_leveling_info
($smartdata);
569 $wearout = $wearval if defined($wearval);
574 # we replaced cciss/ with cciss! above
575 # but in the result we need cciss/ again
576 # because the caller might want to check the
577 # result again with the original parameter
578 if ($dev =~ m
|^cciss
!|) {
579 $dev =~ s
|^cciss
!|cciss
/|;
582 $disklist->{$dev} = {
583 vendor
=> $sysdata->{vendor
},
584 model
=> $data->{model
} || $sysdata->{model
},
585 size
=> $sysdata->{size
},
586 serial
=> $data->{serial
},
596 my $by_id_link = $data->{by_id_link
};
597 $disklist->{$dev}->{by_id_link
} = $by_id_link if defined($by_id_link);
601 my $osdencrypted = 0;
603 my $journal_count = 0;
607 my $partpath = $devpath;
609 # remove part after last / to
610 # get the base path for the partitions
611 # e.g. from /dev/cciss/c0d0 get /dev/cciss
612 $partpath =~ s/\/[^\/]+$//;
614 my $determine_usage = sub {
615 my ($devpath, $sysdir, $is_partition) = @_;
617 return 'LVM' if $lvmhash->{$devpath};
618 return 'ZFS' if $zfshash->{$devpath};
620 my $info = $lsblk_info->{$devpath} // {};
622 my $parttype = $info->{parttype
};
623 if (defined($parttype)) {
625 if $parttype eq '21686148-6449-6e6f-744e-656564454649';
627 if $parttype eq 'c12a7328-f81f-11d2-ba4b-00a0c93ec93b';
628 return 'ZFS reserved'
629 if $parttype eq '6a945a3b-1dd2-11b2-99a6-080020736631';
632 my $fstype = $info->{fstype
};
633 if (defined($fstype)) {
634 return "${fstype} (mounted)" if $mounted->{$devpath};
637 return 'mounted' if $mounted->{$devpath};
639 return if !$is_partition;
641 # for devices, this check is done explicitly later
642 return 'Device Mapper' if !dir_is_empty
("$sysdir/holders");
647 my $collect_ceph_info = sub {
650 my $ceph_volume = $ceph_volume_infos->{$devpath} or return;
651 $journal_count += $ceph_volume->{journal
} // 0;
652 $db_count += $ceph_volume->{db
} // 0;
653 $wal_count += $ceph_volume->{wal
} // 0;
654 if (defined($ceph_volume->{osdid
})) {
655 $osdid = $ceph_volume->{osdid
};
656 $bluestore = 1 if $ceph_volume->{bluestore
};
657 $osdencrypted = 1 if $ceph_volume->{encrypted
};
660 my $result = { %{$ceph_volume} };
661 $result->{journals
} = delete $result->{journal
}
662 if $result->{journal
};
668 dir_glob_foreach
("$sysdir", "$dev.+", sub {
671 $partitions->{$part} = $collect_ceph_info->("$partpath/$part");
672 my $lvm_based_osd = defined($partitions->{$part});
674 $partitions->{$part}->{devpath
} = "$partpath/$part";
675 $partitions->{$part}->{parent
} = "$devpath";
676 $partitions->{$part}->{gpt
} = $data->{gpt
};
677 $partitions->{$part}->{type
} = 'partition';
678 $partitions->{$part}->{size
} =
679 get_sysdir_size
("$sysdir/$part") // 0;
680 $partitions->{$part}->{used
} =
681 $determine_usage->("$partpath/$part", "$sysdir/$part", 1);
682 $partitions->{$part}->{osdid
} //= -1;
684 # Avoid counting twice (e.g. partition on which the LVM for the
685 # DB OSD resides is present in the $journalhash)
686 return if $lvm_based_osd;
688 # Legacy handling for non-LVM based OSDs
690 if (my $mp = $mounted->{"$partpath/$part"}) {
691 if ($mp =~ m
|^/var/lib
/ceph/osd/ceph-
(\d
+)$|) {
693 $partitions->{$part}->{osdid
} = $osdid;
697 if (my $journal_part = $journalhash->{"$partpath/$part"}) {
698 $journal_count++ if $journal_part == 1;
699 $db_count++ if $journal_part == 2;
700 $wal_count++ if $journal_part == 3;
701 $bluestore = 1 if $journal_part == 4;
703 $partitions->{$part}->{journals
} = 1 if $journal_part == 1;
704 $partitions->{$part}->{db
} = 1 if $journal_part == 2;
705 $partitions->{$part}->{wal
} = 1 if $journal_part == 3;
706 $partitions->{$part}->{bluestore
} = 1 if $journal_part == 4;
710 my $used = $determine_usage->($devpath, $sysdir, 0);
711 if (!$include_partitions) {
712 foreach my $part (sort keys %{$partitions}) {
713 next if $partitions->{$part}->{used
} eq 'partition';
714 $used //= $partitions->{$part}->{used
};
717 # fstype might be set even if there are partitions, but showing that is confusing
718 $used = 'partitions' if scalar(keys %{$partitions});
720 $used //= 'partitions' if scalar(keys %{$partitions});
721 # multipath, software raid, etc.
722 # this check comes in last, to show more specific info
724 $used //= 'Device Mapper' if !dir_is_empty
("$sysdir/holders");
726 $disklist->{$dev}->{used
} = $used if $used;
728 $collect_ceph_info->($devpath);
730 $disklist->{$dev}->{osdid
} = $osdid;
731 $disklist->{$dev}->{journals
} = $journal_count if $journal_count;
732 $disklist->{$dev}->{bluestore
} = $bluestore if $osdid != -1;
733 $disklist->{$dev}->{osdencrypted
} = $osdencrypted if $osdid != -1;
734 $disklist->{$dev}->{db
} = $db_count if $db_count;
735 $disklist->{$dev}->{wal
} = $wal_count if $wal_count;
737 if ($include_partitions) {
738 foreach my $part (keys %{$partitions}) {
739 $disklist->{$part} = $partitions->{$part};
749 my ($part_path) = @_;
751 my $st = stat($part_path);
753 next if !$st->mode || !S_ISBLK
($st->mode) || !$st->rdev;
754 my $major = PVE
::Tools
::dev_t_major
($st->rdev);
755 my $minor = PVE
::Tools
::dev_t_minor
($st->rdev);
756 my $partnum_path = "/sys/dev/block/$major:$minor/";
760 $partnum = file_read_firstline
("${partnum_path}partition");
762 die "Partition does not exist\n" if !defined($partnum);
764 #untaint and ensure it is a int
765 if ($partnum =~ m/(\d+)/) {
767 die "Partition number $partnum is invalid\n" if $partnum > 128;
769 die "Failed to get partition number\n";
776 my ($part_path) = @_;
778 my ($dev, $block_dev);
779 if ($part_path =~ m
|^/dev/(.*)$|) {
781 my $link = readlink "/sys/class/block/$dev";
782 $block_dev = $1 if $link =~ m
|([^/]*)/$dev$|;
785 die "Can't parse parent device\n" if !defined($block_dev);
786 die "No valid block device\n" if index($dev, $block_dev) == -1;
788 $block_dev = "/dev/$block_dev";
789 die "Block device does not exsists\n" if !(-b
$block_dev);
794 sub locked_disk_action
{
796 my $res = PVE
::Tools
::lock_file
('/run/lock/pve-diskmanage.lck', undef, $sub);
801 sub assert_disk_unused
{
804 die "device '$dev' is already in use\n" if disk_is_used
($dev);
809 sub append_partition
{
810 my ($dev, $size) = @_;
813 $devname =~ s
|^/dev/||;
816 dir_glob_foreach
("/sys/block/$devname", qr
/\Q
$devname\E.*?
(\d
+)/, sub {
817 my ($part, $partid) = @_;
819 if ($partid >= $newpartid) {
820 $newpartid = $partid + 1;
824 $size = PVE
::Tools
::convert_size
($size, 'b' => 'mb');
826 run_command
([ $SGDISK, '-n', "$newpartid:0:+${size}M", $dev ],
827 errmsg
=> "error creating partition '$newpartid' on '$dev'");
831 # loop again to detect the real partiton device which does not always follow
832 # a strict $devname$partition scheme like /dev/nvme0n1 -> /dev/nvme0n1p1
833 dir_glob_foreach
("/sys/block/$devname", qr
/\Q
$devname\E.*$newpartid/, sub {
836 $partition = "/dev/$part";