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