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