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