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