]> git.proxmox.com Git - pve-storage.git/blob - PVE/Diskmanage.pm
follouwp: get_ceph_volume_infos: code and comment cleanup
[pve-storage.git] / PVE / Diskmanage.pm
1 package PVE::Diskmanage;
2
3 use strict;
4 use warnings;
5 use PVE::ProcFSTools;
6 use Data::Dumper;
7 use Cwd qw(abs_path);
8 use Fcntl ':mode';
9
10 use PVE::Tools qw(extract_param run_command file_get_contents file_read_firstline dir_glob_regex dir_glob_foreach trim);
11
12 my $SMARTCTL = "/usr/sbin/smartctl";
13 my $ZPOOL = "/sbin/zpool";
14 my $SGDISK = "/sbin/sgdisk";
15 my $PVS = "/sbin/pvs";
16 my $LVS = "/sbin/lvs";
17 my $UDEVADM = "/bin/udevadm";
18
19 sub verify_blockdev_path {
20 my ($rel_path) = @_;
21
22 die "missing path" if !$rel_path;
23 my $path = abs_path($rel_path);
24 die "failed to get absolute path to $rel_path\n" if !$path;
25
26 die "got unusual device path '$path'\n" if $path !~ m|^/dev/(.*)$|;
27
28 $path = "/dev/$1"; # untaint
29
30 assert_blockdev($path);
31
32 return $path;
33 }
34
35 sub assert_blockdev {
36 my ($dev, $noerr) = @_;
37
38 if ($dev !~ m|^/dev/| || !(-b $dev)) {
39 return undef if $noerr;
40 die "not a valid block device\n";
41 }
42
43 return 1;
44 }
45
46 sub init_disk {
47 my ($disk, $uuid) = @_;
48
49 assert_blockdev($disk);
50
51 # we should already have checked if it is in use in the api call
52 # but we check again for safety
53 die "disk $disk is already in use\n" if disk_is_used($disk);
54
55 my $id = $uuid || 'R';
56 run_command([$SGDISK, $disk, '-U', $id]);
57 return 1;
58 }
59
60 sub disk_is_used {
61 my ($disk) = @_;
62
63 my $dev = $disk;
64 $dev =~ s|^/dev/||;
65
66 my $disklist = get_disks($dev, 1);
67
68 die "'$disk' is not a valid local disk\n" if !defined($disklist->{$dev});
69 return 1 if $disklist->{$dev}->{used};
70
71 return 0;
72 }
73
74 sub get_smart_data {
75 my ($disk, $healthonly) = @_;
76
77 assert_blockdev($disk);
78 my $smartdata = {};
79 my $type;
80
81 my $returncode = 0;
82
83 if ($disk =~ m!^/dev/(nvme\d+n\d+)$!) {
84 my $info = get_sysdir_info("/sys/block/$1");
85 $disk = "/dev/".($info->{device}
86 or die "failed to get nvme controller device for $disk\n");
87 }
88
89 my $cmd = [$SMARTCTL, '-H'];
90 push @$cmd, '-A', '-f', 'brief' if !$healthonly;
91 push @$cmd, $disk;
92
93 eval {
94 $returncode = run_command($cmd, noerr => 1, outfunc => sub{
95 my ($line) = @_;
96
97 # ATA SMART attributes, e.g.:
98 # ID# ATTRIBUTE_NAME FLAGS VALUE WORST THRESH FAIL RAW_VALUE
99 # 1 Raw_Read_Error_Rate POSR-K 100 100 000 - 0
100 #
101 # SAS and NVME disks, e.g.:
102 # Data Units Written: 5,584,952 [2.85 TB]
103 # Accumulated start-stop cycles: 34
104
105 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+(.*)$/) {
106 my $entry = {};
107
108
109 $entry->{name} = $2 if defined $2;
110 $entry->{flags} = $3 if defined $3;
111 # the +0 makes a number out of the strings
112 $entry->{value} = $4+0 if defined $4;
113 $entry->{worst} = $5+0 if defined $5;
114 # some disks report the default threshold as --- instead of 000
115 if (defined($6) && $6 eq '---') {
116 $entry->{threshold} = 0;
117 } else {
118 $entry->{threshold} = $6+0 if defined $6;
119 }
120 $entry->{fail} = $7 if defined $7;
121 $entry->{raw} = $8 if defined $8;
122 $entry->{id} = $1 if defined $1;
123 push @{$smartdata->{attributes}}, $entry;
124 } elsif ($line =~ m/(?:Health Status|self\-assessment test result): (.*)$/ ) {
125 $smartdata->{health} = $1;
126 } elsif ($line =~ m/Vendor Specific SMART Attributes with Thresholds:/) {
127 $type = 'ata';
128 delete $smartdata->{text};
129 } elsif ($line =~ m/=== START OF (READ )?SMART DATA SECTION ===/) {
130 $type = 'text';
131 } elsif (defined($type) && $type eq 'text') {
132 $smartdata->{text} = '' if !defined $smartdata->{text};
133 $smartdata->{text} .= "$line\n";
134 } elsif ($line =~ m/SMART Disabled/) {
135 $smartdata->{health} = "SMART Disabled";
136 }
137 });
138 };
139 my $err = $@;
140
141 # bit 0 and 1 mark an severe smartctl error
142 # all others are for disk status, so ignore them
143 # see smartctl(8)
144 if ((defined($returncode) && ($returncode & 0b00000011)) || $err) {
145 die "Error getting S.M.A.R.T. data: Exit code: $returncode\n";
146 }
147
148 $smartdata->{type} = $type;
149
150 return $smartdata;
151 }
152
153 sub get_zfs_devices {
154 my $list = {};
155
156 return {} if ! -x $ZPOOL;
157
158 # use zpool and parttype uuid,
159 # because log and cache do not have
160 # zfs type uuid
161 eval {
162 run_command([$ZPOOL, 'list', '-HPLv'], outfunc => sub {
163 my ($line) = @_;
164
165 if ($line =~ m|^\t([^\t]+)\t|) {
166 $list->{$1} = 1;
167 }
168 });
169 };
170
171 # only warn here,
172 # because maybe zfs tools are not installed
173 warn "$@\n" if $@;
174
175 my $applezfsuuid = "6a898cc3-1dd2-11b2-99a6-080020736631";
176 my $bsdzfsuuid = "516e7cba-6ecf-11d6-8ff8-00022d09712b";
177
178 dir_glob_foreach('/dev/disk/by-parttypeuuid', "($applezfsuuid|$bsdzfsuuid)\..+", sub {
179 my ($entry) = @_;
180 my $real_dev = abs_path("/dev/disk/by-parttypeuuid/$entry");
181 $list->{$real_dev} = 1;
182 });
183
184 return $list;
185 }
186
187 sub get_lvm_devices {
188 my $list = {};
189 eval {
190 run_command([$PVS, '--noheadings', '--readonly', '-o', 'pv_name'], outfunc => sub{
191 my ($line) = @_;
192 $line = trim($line);
193 if ($line =~ m|^/dev/|) {
194 $list->{$line} = 1;
195 }
196 });
197 };
198
199 # if something goes wrong, we do not want
200 # to give up, but indicate an error has occured
201 warn "$@\n" if $@;
202
203 my $lvmuuid = "e6d6d379-f507-44c2-a23c-238f2a3df928";
204
205 dir_glob_foreach('/dev/disk/by-parttypeuuid', "$lvmuuid\..+", sub {
206 my ($entry) = @_;
207 my $real_dev = abs_path("/dev/disk/by-parttypeuuid/$entry");
208 $list->{$real_dev} = 1;
209 });
210
211 return $list;
212 }
213
214 sub get_ceph_journals {
215 my $journalhash = {};
216
217 my $journal_uuid = '45b0969e-9b03-4f30-b4c6-b4b80ceff106';
218 my $db_uuid = '30cd0809-c2b2-499c-8879-2d6b78529876';
219 my $wal_uuid = '5ce17fce-4087-4169-b7ff-056cc58473f9';
220 my $block_uuid = 'cafecafe-9b03-4f30-b4c6-b4b80ceff106';
221
222 dir_glob_foreach('/dev/disk/by-parttypeuuid', "($journal_uuid|$db_uuid|$wal_uuid|$block_uuid)\..+", sub {
223 my ($entry, $type) = @_;
224 my $real_dev = abs_path("/dev/disk/by-parttypeuuid/$entry");
225 if ($type eq $journal_uuid) {
226 $journalhash->{$real_dev} = 1;
227 } elsif ($type eq $db_uuid) {
228 $journalhash->{$real_dev} = 2;
229 } elsif ($type eq $wal_uuid) {
230 $journalhash->{$real_dev} = 3;
231 } elsif ($type eq $block_uuid) {
232 $journalhash->{$real_dev} = 4;
233 }
234 });
235
236 return $journalhash;
237 }
238
239 # reads the lv_tags and matches them with the devices
240 sub get_ceph_volume_infos {
241 my $result = {};
242
243 my $cmd = [ $LVS, '-S', 'lv_name=~^osd-', '-o', 'devices,lv_name,lv_tags',
244 '--noheadings', '--readonly', '--separator', ';' ];
245
246 run_command($cmd, outfunc => sub {
247 my $line = shift;
248 $line =~ s/(?:^\s+)|(?:\s+$)//g; # trim whitespaces
249
250 my $fields = [ split(';', $line) ];
251
252 # lvs syntax is /dev/sdX(Y) where Y is the start (which we do not need)
253 my ($dev) = $fields->[0] =~ m|^(/dev/[a-z]+)|;
254 if ($fields->[1] =~ m|^osd-([^-]+)-|) {
255 my $type = $1;
256 # $result autovivification is wanted, to not creating empty hashes
257 if (($type eq 'block' || $type eq 'data') && $fields->[2] =~ m/ceph.osd_id=([^,])/) {
258 $result->{$dev}->{osdid} = $1;
259 $result->{$dev}->{bluestore} = ($type eq 'block');
260 } else {
261 # undef++ becomes '1' (see `perldoc perlop`: Auto-increment)
262 $result->{$dev}->{$type}++;
263 }
264 }
265 });
266
267 return $result;
268 }
269
270 sub get_udev_info {
271 my ($dev) = @_;
272
273 my $info = "";
274 my $data = {};
275 eval {
276 run_command([$UDEVADM, 'info', '-p', $dev, '--query', 'all'], outfunc => sub {
277 my ($line) = @_;
278 $info .= "$line\n";
279 });
280 };
281 warn $@ if $@;
282 return undef if !$info;
283
284 return undef if $info !~ m/^E: DEVTYPE=disk$/m;
285 return undef if $info =~ m/^E: ID_CDROM/m;
286
287 # we use this, because some disks are not simply in /dev
288 # e.g. /dev/cciss/c0d0
289 if ($info =~ m/^E: DEVNAME=(\S+)$/m) {
290 $data->{devpath} = $1;
291 }
292 return if !defined($data->{devpath});
293
294 $data->{serial} = 'unknown';
295 if ($info =~ m/^E: ID_SERIAL_SHORT=(\S+)$/m) {
296 $data->{serial} = $1;
297 }
298
299 $data->{gpt} = 0;
300 if ($info =~ m/^E: ID_PART_TABLE_TYPE=gpt$/m) {
301 $data->{gpt} = 1;
302 }
303
304 # detect SSD
305 $data->{rpm} = -1;
306 if ($info =~ m/^E: ID_ATA_ROTATION_RATE_RPM=(\d+)$/m) {
307 $data->{rpm} = $1;
308 }
309
310 if ($info =~ m/^E: ID_BUS=usb$/m) {
311 $data->{usb} = 1;
312 }
313
314 if ($info =~ m/^E: ID_MODEL=(.+)$/m) {
315 $data->{model} = $1;
316 }
317
318 $data->{wwn} = 'unknown';
319 if ($info =~ m/^E: ID_WWN=(.*)$/m) {
320 $data->{wwn} = $1;
321 }
322
323 return $data;
324 }
325
326 sub get_sysdir_info {
327 my ($sysdir) = @_;
328
329 return undef if ! -d "$sysdir/device";
330
331 my $data = {};
332
333 my $size = file_read_firstline("$sysdir/size");
334 return undef if !$size;
335
336 # linux always considers sectors to be 512 bytes,
337 # independently of real block size
338 $data->{size} = $size * 512;
339
340 # dir/queue/rotational should be 1 for hdd, 0 for ssd
341 $data->{rotational} = file_read_firstline("$sysdir/queue/rotational") // -1;
342
343 $data->{vendor} = file_read_firstline("$sysdir/device/vendor") || 'unknown';
344 $data->{model} = file_read_firstline("$sysdir/device/model") || 'unknown';
345
346 if (defined(my $device = readlink("$sysdir/device"))) {
347 # strip directory and untaint:
348 ($data->{device}) = $device =~ m!([^/]+)$!;
349 }
350
351 return $data;
352 }
353
354 sub get_wear_leveling_info {
355 my ($attributes, $model) = @_;
356
357 my $wearout;
358
359 my $vendormap = {
360 'kingston' => 231,
361 'samsung' => 177,
362 'intel' => 233,
363 'sandisk' => 233,
364 'crucial' => 202,
365 'default' => 233,
366 };
367
368 # find target attr id
369
370 my $attrid;
371
372 foreach my $vendor (keys %$vendormap) {
373 if ($model =~ m/$vendor/i) {
374 $attrid = $vendormap->{$vendor};
375 # found the attribute
376 last;
377 }
378 }
379
380 if (!$attrid) {
381 $attrid = $vendormap->{default};
382 }
383
384 foreach my $attr (@$attributes) {
385 next if $attr->{id} != $attrid;
386 $wearout = $attr->{value};
387 last;
388 }
389
390 return $wearout;
391 }
392
393 sub dir_is_empty {
394 my ($dir) = @_;
395
396 my $dh = IO::Dir->new ($dir);
397 return 1 if !$dh;
398
399 while (defined(my $tmp = $dh->read)) {
400 next if $tmp eq '.' || $tmp eq '..';
401 $dh->close;
402 return 0;
403 }
404 $dh->close;
405 return 1;
406 }
407
408 sub is_iscsi {
409 my ($sysdir) = @_;
410
411 if (-l $sysdir && readlink($sysdir) =~ m|host[^/]*/session[^/]*|) {
412 return 1;
413 }
414
415 return 0;
416 }
417
418 sub get_disks {
419 my ($disk, $nosmart) = @_;
420 my $disklist = {};
421
422 my $mounted = {};
423
424 my $mounts = PVE::ProcFSTools::parse_proc_mounts();
425
426 foreach my $mount (@$mounts) {
427 next if $mount->[0] !~ m|^/dev/|;
428 $mounted->{abs_path($mount->[0])} = $mount->[1];
429 };
430
431 my $dev_is_mounted = sub {
432 my ($dev) = @_;
433 return $mounted->{$dev};
434 };
435
436 my $journalhash = get_ceph_journals();
437 my $ceph_volume_infos = get_ceph_volume_infos();
438
439 my $zfslist = get_zfs_devices();
440
441 my $lvmlist = get_lvm_devices();
442
443 # we get cciss/c0d0 but need cciss!c0d0
444 if (defined($disk) && $disk =~ m|^cciss/|) {
445 $disk =~ s|cciss/|cciss!|;
446 }
447
448 dir_glob_foreach('/sys/block', '.*', sub {
449 my ($dev) = @_;
450 return if defined($disk) && $disk ne $dev;
451 # whitelisting following devices
452 # hdX: ide block device
453 # sdX: sd block device
454 # vdX: virtual block device
455 # xvdX: xen virtual block device
456 # nvmeXnY: nvme devices
457 # cciss!cXnY: cciss devices
458 return if $dev !~ m/^(h|s|x?v)d[a-z]+$/ &&
459 $dev !~ m/^nvme\d+n\d+$/ &&
460 $dev !~ m/^cciss\!c\d+d\d+$/;
461
462 my $data = get_udev_info("/sys/block/$dev");
463 return if !defined($data);
464 my $devpath = $data->{devpath};
465
466 my $sysdir = "/sys/block/$dev";
467
468 # we do not want iscsi devices
469 return if is_iscsi($sysdir);
470
471 my $sysdata = get_sysdir_info($sysdir);
472 return if !defined($sysdata);
473
474 my $type = 'unknown';
475
476 if ($sysdata->{rotational} == 0) {
477 $type = 'ssd';
478 $data->{rpm} = 0;
479 } elsif ($sysdata->{rotational} == 1) {
480 if ($data->{rpm} != -1) {
481 $type = 'hdd';
482 } elsif ($data->{usb}) {
483 $type = 'usb';
484 $data->{rpm} = 0;
485 }
486 }
487
488 my $health = 'UNKNOWN';
489 my $wearout = 'N/A';
490
491 if (!$nosmart) {
492 eval {
493 my $smartdata = get_smart_data($devpath, ($type ne 'ssd'));
494 $health = $smartdata->{health} if $smartdata->{health};
495
496 if ($type eq 'ssd') {
497 # if we have an ssd we try to get the wearout indicator
498 my $wearval = get_wear_leveling_info($smartdata->{attributes}, $data->{model} || $sysdir->{model});
499 $wearout = $wearval if $wearval;
500 }
501 };
502 }
503
504 my $used;
505
506 $used = 'LVM' if $lvmlist->{$devpath};
507
508 $used = 'mounted' if &$dev_is_mounted($devpath);
509
510 $used = 'ZFS' if $zfslist->{$devpath};
511
512 # we replaced cciss/ with cciss! above
513 # but in the result we need cciss/ again
514 # because the caller might want to check the
515 # result again with the original parameter
516 if ($dev =~ m|^cciss!|) {
517 $dev =~ s|^cciss!|cciss/|;
518 }
519
520 $disklist->{$dev} = {
521 vendor => $sysdata->{vendor},
522 model => $data->{model} || $sysdata->{model},
523 size => $sysdata->{size},
524 serial => $data->{serial},
525 gpt => $data->{gpt},
526 rpm => $data->{rpm},
527 type => $type,
528 wwn => $data->{wwn},
529 health => $health,
530 devpath => $devpath,
531 wearout => $wearout,
532 };
533
534 my $osdid = -1;
535 my $bluestore = 0;
536
537 my $journal_count = 0;
538 my $db_count = 0;
539 my $wal_count = 0;
540
541 my $found_partitions;
542 my $found_lvm;
543 my $found_mountpoints;
544 my $found_zfs;
545 my $found_dm;
546 my $partpath = $devpath;
547
548 # remove part after last / to
549 # get the base path for the partitions
550 # e.g. from /dev/cciss/c0d0 get /dev/cciss
551 $partpath =~ s/\/[^\/]+$//;
552
553 dir_glob_foreach("$sysdir", "$dev.+", sub {
554 my ($part) = @_;
555
556 $found_partitions = 1;
557
558 if (my $mp = &$dev_is_mounted("$partpath/$part")) {
559 $found_mountpoints = 1;
560 if ($mp =~ m|^/var/lib/ceph/osd/ceph-(\d+)$|) {
561 $osdid = $1;
562 }
563 }
564
565 if ($lvmlist->{"$partpath/$part"}) {
566 $found_lvm = 1;
567 }
568
569 if ($zfslist->{"$partpath/$part"}) {
570 $found_zfs = 1;
571 }
572
573 if ($journalhash->{"$partpath/$part"}) {
574 $journal_count++ if $journalhash->{"$partpath/$part"} == 1;
575 $db_count++ if $journalhash->{"$partpath/$part"} == 2;
576 $wal_count++ if $journalhash->{"$partpath/$part"} == 3;
577 $bluestore = 1 if $journalhash->{"$partpath/$part"} == 4;
578 }
579
580 if (!dir_is_empty("$sysdir/$part/holders") && !$found_lvm) {
581 $found_dm = 1;
582 }
583 });
584
585 if ($ceph_volume_infos->{$devpath}) {
586 $journal_count += $ceph_volume_infos->{$devpath}->{journal} // 0;
587 $db_count += $ceph_volume_infos->{$devpath}->{db} // 0;
588 $wal_count += $ceph_volume_infos->{$devpath}->{wal} // 0;
589 if ($ceph_volume_infos->{$devpath}->{osdid}) {
590 $osdid = $ceph_volume_infos->{$devpath}->{osdid};
591 $bluestore = 1 if $ceph_volume_infos->{$devpath}->{bluestore};
592 }
593 }
594
595 $used = 'mounted' if $found_mountpoints && !$used;
596 $used = 'LVM' if $found_lvm && !$used;
597 $used = 'ZFS' if $found_zfs && !$used;
598 $used = 'Device Mapper' if $found_dm && !$used;
599 $used = 'partitions' if $found_partitions && !$used;
600
601 # multipath, software raid, etc.
602 # this check comes in last, to show more specific info
603 # if we have it
604 $used = 'Device Mapper' if !$used && !dir_is_empty("$sysdir/holders");
605
606 $disklist->{$dev}->{used} = $used if $used;
607 $disklist->{$dev}->{osdid} = $osdid;
608 $disklist->{$dev}->{journals} = $journal_count if $journal_count;
609 $disklist->{$dev}->{bluestore} = $bluestore if $osdid != -1;
610 $disklist->{$dev}->{db} = $db_count if $db_count;
611 $disklist->{$dev}->{wal} = $wal_count if $wal_count;
612 });
613
614 return $disklist;
615
616 }
617
618 sub get_partnum {
619 my ($part_path) = @_;
620
621 my ($mode, $rdev) = (stat($part_path))[2,6];
622
623 next if !$mode || !S_ISBLK($mode) || !$rdev;
624 my $major = PVE::Tools::dev_t_major($rdev);
625 my $minor = PVE::Tools::dev_t_minor($rdev);
626 my $partnum_path = "/sys/dev/block/$major:$minor/";
627
628 my $partnum;
629
630 $partnum = file_read_firstline("${partnum_path}partition");
631
632 die "Partition does not exists\n" if !defined($partnum);
633
634 #untaint and ensure it is a int
635 if ($partnum =~ m/(\d+)/) {
636 $partnum = $1;
637 die "Partition number $partnum is invalid\n" if $partnum > 128;
638 } else {
639 die "Failed to get partition number\n";
640 }
641
642 return $partnum;
643 }
644
645 sub get_blockdev {
646 my ($part_path) = @_;
647
648 my $dev = $1 if $part_path =~ m|^/dev/(.*)$|;
649 my $link = readlink "/sys/class/block/$dev";
650 my $block_dev = $1 if $link =~ m|([^/]*)/$dev$|;
651
652 die "Can't parse parent device\n" if !defined($block_dev);
653 die "No valid block device\n" if index($dev, $block_dev) == -1;
654
655 $block_dev = "/dev/$block_dev";
656 die "Block device does not exsists\n" if !(-b $block_dev);
657
658 return $block_dev;
659 }
660
661 sub locked_disk_action {
662 my ($sub) = @_;
663 my $res = PVE::Tools::lock_file('/run/lock/pve-diskmanage.lck', undef, $sub);
664 die $@ if $@;
665 return $res;
666 }
667
668 sub assert_disk_unused {
669 my ($dev) = @_;
670
671 die "device '$dev' is already in use\n" if disk_is_used($dev);
672
673 return undef;
674 }
675
676 1;