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