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