]> git.proxmox.com Git - pve-storage.git/blame - PVE/Diskmanage.pm
pbs: fix typo
[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
525b4a6e
FE
23sub check_bin {
24 my ($path) = @_;
525b4a6e
FE
25 return -x $path;
26}
27
cbba9b5b
DC
28sub 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
44sub 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
55sub 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
69sub disk_is_used {
70 my ($disk) = @_;
71
72 my $dev = $disk;
73 $dev =~ s|^/dev/||;
74
7a98a62d 75 my $disklist = get_disks($dev, 1);
cbba9b5b
DC
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
83sub get_smart_data {
dd902da7 84 my ($disk, $healthonly) = @_;
cbba9b5b
DC
85
86 assert_blockdev($disk);
87 my $smartdata = {};
dc1311cb 88 my $type;
cbba9b5b 89
9018a4e6 90 my $returncode = 0;
c9bd3d22 91
c3442aa5
WB
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 }
c9bd3d22 97
dd902da7
DC
98 my $cmd = [$SMARTCTL, '-H'];
99 push @$cmd, '-A', '-f', 'brief' if !$healthonly;
100 push @$cmd, $disk;
101
cbba9b5b 102 eval {
dd902da7 103 $returncode = run_command($cmd, noerr => 1, outfunc => sub{
cbba9b5b
DC
104 my ($line) = @_;
105
1c999553
FG
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
dc1311cb
FG
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
bd54091c 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+(.*)$/) {
cbba9b5b 115 my $entry = {};
bd54091c 116
1c999553
FG
117 $entry->{name} = $2 if defined $2;
118 $entry->{flags} = $3 if defined $3;
cbba9b5b 119 # the +0 makes a number out of the strings
1c999553
FG
120 $entry->{value} = $4+0 if defined $4;
121 $entry->{worst} = $5+0 if defined $5;
bd54091c
DC
122 # some disks report the default threshold as --- instead of 000
123 if (defined($6) && $6 eq '---') {
124 $entry->{threshold} = 0;
125 } else {
126 $entry->{threshold} = $6+0 if defined $6;
127 }
1c999553
FG
128 $entry->{fail} = $7 if defined $7;
129 $entry->{raw} = $8 if defined $8;
130 $entry->{id} = $1 if defined $1;
cbba9b5b 131 push @{$smartdata->{attributes}}, $entry;
5db2d529 132 } elsif ($line =~ m/(?:Health Status|self\-assessment test result): (.*)$/ ) {
cbba9b5b
DC
133 $smartdata->{health} = $1;
134 } elsif ($line =~ m/Vendor Specific SMART Attributes with Thresholds:/) {
dc1311cb
FG
135 $type = 'ata';
136 delete $smartdata->{text};
137 } elsif ($line =~ m/=== START OF (READ )?SMART DATA SECTION ===/) {
138 $type = 'text';
139 } elsif (defined($type) && $type eq 'text') {
140 $smartdata->{text} = '' if !defined $smartdata->{text};
141 $smartdata->{text} .= "$line\n";
2c048efd
DC
142 # extract wearout from nvme/sas text, allow for decimal values
143 if ($line =~ m/Percentage Used(?: endurance indicator)?:\s*(\d+(?:\.\d+)?)\%/i) {
ea928fd4
DC
144 $smartdata->{wearout} = 100 - $1;
145 }
dd902da7
DC
146 } elsif ($line =~ m/SMART Disabled/) {
147 $smartdata->{health} = "SMART Disabled";
cbba9b5b
DC
148 }
149 });
150 };
9018a4e6
DC
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 }
dc1311cb
FG
159
160 $smartdata->{type} = $type;
161
cbba9b5b
DC
162 return $smartdata;
163}
164
b6bbc2ab 165sub get_lsblk_info() {
59c03cd9 166 my $cmd = [$LSBLK, '--json', '-o', 'path,parttype,fstype'];
8cd6d7e8
DC
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
b6bbc2ab 182 $res = { map {
59c03cd9
FE
183 $_->{path} => {
184 parttype => $_->{parttype},
185 fstype => $_->{fstype}
186 }
b6bbc2ab 187 } @{$list} };
8cd6d7e8
DC
188
189 return $res;
190}
191
192my $get_devices_by_partuuid = sub {
b6bbc2ab 193 my ($lsblk_info, $uuids, $res) = @_;
8cd6d7e8
DC
194
195 $res = {} if !defined($res);
196
b6bbc2ab
FE
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};
8cd6d7e8
DC
201 }
202
203 return $res;
204};
205
cbba9b5b 206sub get_zfs_devices {
b6bbc2ab 207 my ($lsblk_info) = @_;
8cd6d7e8 208 my $res = {};
cbba9b5b 209
525b4a6e 210 return {} if !check_bin($ZPOOL);
4526dffa 211
cbba9b5b
DC
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|) {
8cd6d7e8 220 $res->{$1} = 1;
cbba9b5b
DC
221 }
222 });
223 };
224
225 # only warn here,
226 # because maybe zfs tools are not installed
227 warn "$@\n" if $@;
228
8cd6d7e8
DC
229 my $uuids = {
230 "6a898cc3-1dd2-11b2-99a6-080020736631" => 1, # apple
231 "516e7cba-6ecf-11d6-8ff8-00022d09712b" => 1, # bsd
232 };
cbba9b5b 233
cbba9b5b 234
b6bbc2ab 235 $res = $get_devices_by_partuuid->($lsblk_info, $uuids, $res);
8cd6d7e8
DC
236
237 return $res;
cbba9b5b
DC
238}
239
240sub get_lvm_devices {
b6bbc2ab 241 my ($lsblk_info) = @_;
8cd6d7e8 242 my $res = {};
cbba9b5b
DC
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/|) {
8cd6d7e8 248 $res->{$line} = 1;
cbba9b5b
DC
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
8cd6d7e8
DC
257 my $uuids = {
258 "e6d6d379-f507-44c2-a23c-238f2a3df928" => 1,
259 };
cbba9b5b 260
b6bbc2ab 261 $res = $get_devices_by_partuuid->($lsblk_info, $uuids, $res);
cbba9b5b 262
8cd6d7e8 263 return $res;
cbba9b5b
DC
264}
265
266sub get_ceph_journals {
b6bbc2ab 267 my ($lsblk_info) = @_;
8cd6d7e8
DC
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
b6bbc2ab 277 $res = $get_devices_by_partuuid->($lsblk_info, $uuids, $res);
cbba9b5b 278
8cd6d7e8 279 return $res;
cbba9b5b
DC
280}
281
19dcd1ad
DC
282# reads the lv_tags and matches them with the devices
283sub get_ceph_volume_infos {
284 my $result = {};
285
248f43f5
TL
286 my $cmd = [ $LVS, '-S', 'lv_name=~^osd-', '-o', 'devices,lv_name,lv_tags',
287 '--noheadings', '--readonly', '--separator', ';' ];
19dcd1ad
DC
288
289 run_command($cmd, outfunc => sub {
290 my $line = shift;
248f43f5
TL
291 $line =~ s/(?:^\s+)|(?:\s+$)//g; # trim whitespaces
292
293 my $fields = [ split(';', $line) ];
19dcd1ad
DC
294
295 # lvs syntax is /dev/sdX(Y) where Y is the start (which we do not need)
41f93ece 296 my ($dev) = $fields->[0] =~ m|^(/dev/[a-z]+[^(]*)|;
19dcd1ad
DC
297 if ($fields->[1] =~ m|^osd-([^-]+)-|) {
298 my $type = $1;
248f43f5 299 # $result autovivification is wanted, to not creating empty hashes
79f4a7bf 300 if (($type eq 'block' || $type eq 'data') && $fields->[2] =~ m/ceph.osd_id=([^,]+)/) {
19dcd1ad
DC
301 $result->{$dev}->{osdid} = $1;
302 $result->{$dev}->{bluestore} = ($type eq 'block');
bfb3d42d
DC
303 if ($fields->[2] =~ m/ceph\.encrypted=1/) {
304 $result->{$dev}->{encrypted} = 1;
305 }
19dcd1ad 306 } else {
248f43f5 307 # undef++ becomes '1' (see `perldoc perlop`: Auto-increment)
19dcd1ad
DC
308 $result->{$dev}->{$type}++;
309 }
310 }
311 });
312
313 return $result;
314}
315
cbba9b5b
DC
316sub get_udev_info {
317 my ($dev) = @_;
318
319 my $info = "";
320 my $data = {};
321 eval {
d3a5e309 322 run_command(['udevadm', 'info', '-p', $dev, '--query', 'all'], outfunc => sub {
cbba9b5b
DC
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
865bdbd9
DC
360 if ($info =~ m/^E: ID_MODEL=(.+)$/m) {
361 $data->{model} = $1;
362 }
363
cbba9b5b
DC
364 $data->{wwn} = 'unknown';
365 if ($info =~ m/^E: ID_WWN=(.*)$/m) {
366 $data->{wwn} = $1;
367 }
368
0f0d99a3
SI
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
cbba9b5b
DC
374 return $data;
375}
376
40be5c5c
FE
377sub 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
cbba9b5b
DC
388sub get_sysdir_info {
389 my ($sysdir) = @_;
390
461a9fd8
DC
391 return undef if ! -d "$sysdir/device";
392
cbba9b5b
DC
393 my $data = {};
394
40be5c5c 395 $data->{size} = get_sysdir_size($sysdir) or return;
cbba9b5b
DC
396
397 # dir/queue/rotational should be 1 for hdd, 0 for ssd
571b6f26 398 $data->{rotational} = file_read_firstline("$sysdir/queue/rotational") // -1;
cbba9b5b
DC
399
400 $data->{vendor} = file_read_firstline("$sysdir/device/vendor") || 'unknown';
401 $data->{model} = file_read_firstline("$sysdir/device/model") || 'unknown';
402
c3442aa5
WB
403 if (defined(my $device = readlink("$sysdir/device"))) {
404 # strip directory and untaint:
405 ($data->{device}) = $device =~ m!([^/]+)$!;
406 }
407
cbba9b5b
DC
408 return $data;
409}
410
6965a670 411sub get_wear_leveling_info {
dbad606d 412 my ($smartdata) = @_;
ea928fd4
DC
413 my $attributes = $smartdata->{attributes};
414
415 if (defined($smartdata->{wearout})) {
416 return $smartdata->{wearout};
417 }
6965a670
DC
418
419 my $wearout;
420
dbad606d
JJS
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;
6965a670
DC
447 }
448 }
449
6965a670
DC
450 return $wearout;
451}
452
10a48db5
DC
453sub 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
eebcdb11
DC
468sub 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
4731eb11
TL
478my sub is_ssdlike {
479 my ($type) = @_;
480 return $type eq 'ssd' || $type eq 'nvme';
481}
482
7e14102a 483sub mounted_blockdevs {
cbba9b5b
DC
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
7e14102a
FE
493 return $mounted;
494}
495
496sub get_disks {
497 my ($disks, $nosmart, $include_partitions) = @_;
498 my $disklist = {};
499
500 my $mounted = mounted_blockdevs();
501
b6bbc2ab 502 my $lsblk_info = get_lsblk_info();
8cd6d7e8 503
b6bbc2ab 504 my $journalhash = get_ceph_journals($lsblk_info);
19dcd1ad 505 my $ceph_volume_infos = get_ceph_volume_infos();
cbba9b5b 506
b6bbc2ab 507 my $zfshash = get_zfs_devices($lsblk_info);
cbba9b5b 508
b6bbc2ab 509 my $lvmhash = get_lvm_devices($lsblk_info);
cbba9b5b 510
52a064af
DC
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
5045e0b7 519 $_ =~ s|cciss/|cciss!| for @$disks;
52a064af
DC
520
521 $disk_regex = "(?:" . join('|', @$disks) . ")";
1590fc13
DC
522 }
523
52a064af 524 dir_glob_foreach('/sys/block', $disk_regex, sub {
cbba9b5b 525 my ($dev) = @_;
cbba9b5b
DC
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
38ddd4ce 532 # cciss!cXnY: cciss devices
cbba9b5b
DC
533 return if $dev !~ m/^(h|s|x?v)d[a-z]+$/ &&
534 $dev !~ m/^nvme\d+n\d+$/ &&
38ddd4ce 535 $dev !~ m/^cciss\!c\d+d\d+$/;
cbba9b5b 536
532e89e7 537 my $data = get_udev_info("/sys/block/$dev");
cbba9b5b
DC
538 return if !defined($data);
539 my $devpath = $data->{devpath};
540
541 my $sysdir = "/sys/block/$dev";
542
cbba9b5b 543 # we do not want iscsi devices
eebcdb11 544 return if is_iscsi($sysdir);
cbba9b5b
DC
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';
4731eb11 553 $type = 'nvme' if $dev =~ m/^nvme\d+n\d+$/;
cbba9b5b
DC
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
acd3d916 564 my $health = 'UNKNOWN';
6965a670 565 my $wearout = 'N/A';
7a98a62d
FG
566
567 if (!$nosmart) {
568 eval {
4731eb11 569 my $smartdata = get_smart_data($devpath, !is_ssdlike($type));
dd902da7
DC
570 $health = $smartdata->{health} if $smartdata->{health};
571
4731eb11 572 if (is_ssdlike($type)) {
7a98a62d 573 # if we have an ssd we try to get the wearout indicator
dbad606d 574 my $wearval = get_wear_leveling_info($smartdata);
9250ddfe 575 $wearout = $wearval if defined($wearval);
acd3d916 576 }
7a98a62d
FG
577 };
578 }
cbba9b5b 579
fc7c0e05
DC
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
cbba9b5b
DC
588 $disklist->{$dev} = {
589 vendor => $sysdata->{vendor},
865bdbd9 590 model => $data->{model} || $sysdata->{model},
cbba9b5b
DC
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
0f0d99a3
SI
602 my $by_id_link = $data->{by_id_link};
603 $disklist->{$dev}->{by_id_link} = $by_id_link if defined($by_id_link);
604
cbba9b5b 605 my $osdid = -1;
e2bd817c 606 my $bluestore = 0;
bfb3d42d 607 my $osdencrypted = 0;
cbba9b5b
DC
608
609 my $journal_count = 0;
e2bd817c
DC
610 my $db_count = 0;
611 my $wal_count = 0;
cbba9b5b 612
cbba9b5b
DC
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
01aa7d75
FE
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} // {};
d3857eeb
FE
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
01aa7d75
FE
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
41f93ece
FE
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 }
6a1919b1
FE
665
666 my $result = { %{$ceph_volume} };
667 $result->{journals} = delete $result->{journal}
668 if $result->{journal};
669 return $result;
41f93ece
FE
670 };
671
89c27ea8
FE
672 my $partitions = {};
673
cbba9b5b
DC
674 dir_glob_foreach("$sysdir", "$dev.+", sub {
675 my ($part) = @_;
676
6a1919b1
FE
677 $partitions->{$part} = $collect_ceph_info->("$partpath/$part");
678 my $lvm_based_osd = defined($partitions->{$part});
679
89c27ea8 680 $partitions->{$part}->{devpath} = "$partpath/$part";
2949c537 681 $partitions->{$part}->{parent} = "$devpath";
89c27ea8 682 $partitions->{$part}->{gpt} = $data->{gpt};
31ed94cc 683 $partitions->{$part}->{type} = 'partition';
89c27ea8
FE
684 $partitions->{$part}->{size} =
685 get_sysdir_size("$sysdir/$part") // 0;
01aa7d75
FE
686 $partitions->{$part}->{used} =
687 $determine_usage->("$partpath/$part", "$sysdir/$part", 1);
6a1919b1 688 $partitions->{$part}->{osdid} //= -1;
41f93ece
FE
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
0cca5356 696 if (my $mp = $mounted->{"$partpath/$part"}) {
cbba9b5b
DC
697 if ($mp =~ m|^/var/lib/ceph/osd/ceph-(\d+)$|) {
698 $osdid = $1;
6a1919b1 699 $partitions->{$part}->{osdid} = $osdid;
cbba9b5b
DC
700 }
701 }
702
0180fa42
TL
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;
6a1919b1
FE
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;
e2bd817c 713 }
cbba9b5b
DC
714 });
715
01aa7d75 716 my $used = $determine_usage->($devpath, $sysdir, 0);
2949c537
FE
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 }
415dc398
FE
722 } else {
723 # fstype might be set even if there are partitions, but showing that is confusing
724 $used = 'partitions' if scalar(keys %{$partitions});
01aa7d75
FE
725 }
726 $used //= 'partitions' if scalar(keys %{$partitions});
cbba9b5b
DC
727 # multipath, software raid, etc.
728 # this check comes in last, to show more specific info
729 # if we have it
01aa7d75 730 $used //= 'Device Mapper' if !dir_is_empty("$sysdir/holders");
cbba9b5b
DC
731
732 $disklist->{$dev}->{used} = $used if $used;
41f93ece
FE
733
734 $collect_ceph_info->($devpath);
735
cbba9b5b 736 $disklist->{$dev}->{osdid} = $osdid;
e2bd817c
DC
737 $disklist->{$dev}->{journals} = $journal_count if $journal_count;
738 $disklist->{$dev}->{bluestore} = $bluestore if $osdid != -1;
bfb3d42d 739 $disklist->{$dev}->{osdencrypted} = $osdencrypted if $osdid != -1;
e2bd817c
DC
740 $disklist->{$dev}->{db} = $db_count if $db_count;
741 $disklist->{$dev}->{wal} = $wal_count if $wal_count;
2949c537
FE
742
743 if ($include_partitions) {
744 foreach my $part (keys %{$partitions}) {
745 $disklist->{$part} = $partitions->{$part};
746 }
747 }
cbba9b5b
DC
748 });
749
750 return $disklist;
751
752}
753
3196c387
WL
754sub get_partnum {
755 my ($part_path) = @_;
756
92ae59df 757 my $st = stat($part_path);
3196c387 758
ceb7b1ed
FE
759 die "error detecting block device '$part_path'\n"
760 if !$st || !$st->mode || !S_ISBLK($st->mode) || !$st->rdev;
761
92ae59df
AA
762 my $major = PVE::Tools::dev_t_major($st->rdev);
763 my $minor = PVE::Tools::dev_t_minor($st->rdev);
3196c387
WL
764 my $partnum_path = "/sys/dev/block/$major:$minor/";
765
766 my $partnum;
767
768 $partnum = file_read_firstline("${partnum_path}partition");
769
481f6177 770 die "Partition does not exist\n" if !defined($partnum);
3196c387
WL
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
0d28307d
WL
783sub get_blockdev {
784 my ($part_path) = @_;
785
1207620c
TL
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 }
0d28307d
WL
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
e39e8ee2
DC
802sub 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
0370861c 809sub assert_disk_unused {
76c1e57b
DC
810 my ($dev) = @_;
811
0370861c 812 die "device '$dev' is already in use\n" if disk_is_used($dev);
76c1e57b
DC
813
814 return undef;
815}
816
1dc3038d
DC
817sub 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
70dc7098
TL
850my sub strip_dev :prototype($) {
851 my ($devpath) = @_;
852 $devpath =~ s|^/dev/||;
853 return $devpath;
854}
855
cb057e21
FE
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().
859sub has_holder {
860 my ($devpath) = @_;
861
70dc7098 862 my $dev = strip_dev($devpath);
cb057e21 863
70dc7098 864 return $devpath if !dir_is_empty("/sys/class/block/${dev}/holders");
cb057e21
FE
865
866 my $found;
cb057e21
FE
867 dir_glob_foreach("/sys/block/${dev}", "${dev}.+", sub {
868 my ($part) = @_;
70dc7098 869 $found = "/dev/${part}" if !dir_is_empty("/sys/class/block/${part}/holders");
cb057e21
FE
870 });
871
872 return $found;
873}
874
3bf7f889
FE
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().
878sub is_mounted {
879 my ($devpath) = @_;
880
881 my $mounted = mounted_blockdevs();
882
883 return $devpath if $mounted->{$devpath};
884
70dc7098 885 my $dev = strip_dev($devpath);
3bf7f889
FE
886
887 my $found;
3bf7f889
FE
888 dir_glob_foreach("/sys/block/${dev}", "${dev}.+", sub {
889 my ($part) = @_;
3bf7f889
FE
890 my $partpath = "/dev/${part}";
891
892 $found = $partpath if $mounted->{$partpath};
893 });
894
895 return $found;
896}
897
262ad7a9
FE
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().
900sub wipe_blockdev {
901 my ($devpath) = @_;
902
262ad7a9
FE
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
839afff8
TL
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
f7a95153 918 if (scalar($to_wipe->@*) > 0) {
d9381782 919 print "found child partitions to wipe: ". join(', ', $to_wipe->@*) ."\n";
839afff8
TL
920 }
921 push $to_wipe->@*, $devpath; # put actual device last
922
923 print "wiping block device ${devpath}\n";
262ad7a9 924
839afff8 925 run_command(['wipefs', '--all', $to_wipe->@*], errmsg => "error wiping '${devpath}'");
fa6d05ab
TL
926
927 run_command(
928 ['dd', 'if=/dev/zero', "of=${devpath}", 'bs=1M', 'conv=fdatasync', "count=${count}"],
929 errmsg => "error wiping '${devpath}'",
930 );
262ad7a9
FE
931}
932
cbba9b5b 9331;