]> git.proxmox.com Git - pve-storage.git/blob - PVE/Diskmanage.pm
Diskmanage: detect osds/journals/etc. created with ceph-volume
[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
249 my $fields = [split(';', $line)];
250
251 # lvs syntax is /dev/sdX(Y) where Y is the start (which we do not need)
252 my ($dev) = $fields->[0] =~ m|^(/dev/[a-z]+)|;
253 if ($fields->[1] =~ m|^osd-([^-]+)-|) {
254 my $type = $1;
255 # we use autovivification here to not concern us with
256 # creation of empty hashes
257 if (($type eq 'block' || $type eq 'data') &&
258 $fields->[2] =~ m/ceph.osd_id=([^,])/)
259 {
260 $result->{$dev}->{osdid} = $1;
261 $result->{$dev}->{bluestore} = ($type eq 'block');
262 } else {
263 # if $foo is undef $foo++ results in '1' (and is well defined)
264 $result->{$dev}->{$type}++;
265 }
266 }
267 });
268
269 return $result;
270 }
271
272 sub get_udev_info {
273 my ($dev) = @_;
274
275 my $info = "";
276 my $data = {};
277 eval {
278 run_command([$UDEVADM, 'info', '-p', $dev, '--query', 'all'], outfunc => sub {
279 my ($line) = @_;
280 $info .= "$line\n";
281 });
282 };
283 warn $@ if $@;
284 return undef if !$info;
285
286 return undef if $info !~ m/^E: DEVTYPE=disk$/m;
287 return undef if $info =~ m/^E: ID_CDROM/m;
288
289 # we use this, because some disks are not simply in /dev
290 # e.g. /dev/cciss/c0d0
291 if ($info =~ m/^E: DEVNAME=(\S+)$/m) {
292 $data->{devpath} = $1;
293 }
294 return if !defined($data->{devpath});
295
296 $data->{serial} = 'unknown';
297 if ($info =~ m/^E: ID_SERIAL_SHORT=(\S+)$/m) {
298 $data->{serial} = $1;
299 }
300
301 $data->{gpt} = 0;
302 if ($info =~ m/^E: ID_PART_TABLE_TYPE=gpt$/m) {
303 $data->{gpt} = 1;
304 }
305
306 # detect SSD
307 $data->{rpm} = -1;
308 if ($info =~ m/^E: ID_ATA_ROTATION_RATE_RPM=(\d+)$/m) {
309 $data->{rpm} = $1;
310 }
311
312 if ($info =~ m/^E: ID_BUS=usb$/m) {
313 $data->{usb} = 1;
314 }
315
316 if ($info =~ m/^E: ID_MODEL=(.+)$/m) {
317 $data->{model} = $1;
318 }
319
320 $data->{wwn} = 'unknown';
321 if ($info =~ m/^E: ID_WWN=(.*)$/m) {
322 $data->{wwn} = $1;
323 }
324
325 return $data;
326 }
327
328 sub get_sysdir_info {
329 my ($sysdir) = @_;
330
331 return undef if ! -d "$sysdir/device";
332
333 my $data = {};
334
335 my $size = file_read_firstline("$sysdir/size");
336 return undef if !$size;
337
338 # linux always considers sectors to be 512 bytes,
339 # independently of real block size
340 $data->{size} = $size * 512;
341
342 # dir/queue/rotational should be 1 for hdd, 0 for ssd
343 $data->{rotational} = file_read_firstline("$sysdir/queue/rotational") // -1;
344
345 $data->{vendor} = file_read_firstline("$sysdir/device/vendor") || 'unknown';
346 $data->{model} = file_read_firstline("$sysdir/device/model") || 'unknown';
347
348 if (defined(my $device = readlink("$sysdir/device"))) {
349 # strip directory and untaint:
350 ($data->{device}) = $device =~ m!([^/]+)$!;
351 }
352
353 return $data;
354 }
355
356 sub get_wear_leveling_info {
357 my ($attributes, $model) = @_;
358
359 my $wearout;
360
361 my $vendormap = {
362 'kingston' => 231,
363 'samsung' => 177,
364 'intel' => 233,
365 'sandisk' => 233,
366 'crucial' => 202,
367 'default' => 233,
368 };
369
370 # find target attr id
371
372 my $attrid;
373
374 foreach my $vendor (keys %$vendormap) {
375 if ($model =~ m/$vendor/i) {
376 $attrid = $vendormap->{$vendor};
377 # found the attribute
378 last;
379 }
380 }
381
382 if (!$attrid) {
383 $attrid = $vendormap->{default};
384 }
385
386 foreach my $attr (@$attributes) {
387 next if $attr->{id} != $attrid;
388 $wearout = $attr->{value};
389 last;
390 }
391
392 return $wearout;
393 }
394
395 sub dir_is_empty {
396 my ($dir) = @_;
397
398 my $dh = IO::Dir->new ($dir);
399 return 1 if !$dh;
400
401 while (defined(my $tmp = $dh->read)) {
402 next if $tmp eq '.' || $tmp eq '..';
403 $dh->close;
404 return 0;
405 }
406 $dh->close;
407 return 1;
408 }
409
410 sub is_iscsi {
411 my ($sysdir) = @_;
412
413 if (-l $sysdir && readlink($sysdir) =~ m|host[^/]*/session[^/]*|) {
414 return 1;
415 }
416
417 return 0;
418 }
419
420 sub get_disks {
421 my ($disk, $nosmart) = @_;
422 my $disklist = {};
423
424 my $mounted = {};
425
426 my $mounts = PVE::ProcFSTools::parse_proc_mounts();
427
428 foreach my $mount (@$mounts) {
429 next if $mount->[0] !~ m|^/dev/|;
430 $mounted->{abs_path($mount->[0])} = $mount->[1];
431 };
432
433 my $dev_is_mounted = sub {
434 my ($dev) = @_;
435 return $mounted->{$dev};
436 };
437
438 my $journalhash = get_ceph_journals();
439 my $ceph_volume_infos = get_ceph_volume_infos();
440
441 my $zfslist = get_zfs_devices();
442
443 my $lvmlist = get_lvm_devices();
444
445 # we get cciss/c0d0 but need cciss!c0d0
446 if (defined($disk) && $disk =~ m|^cciss/|) {
447 $disk =~ s|cciss/|cciss!|;
448 }
449
450 dir_glob_foreach('/sys/block', '.*', sub {
451 my ($dev) = @_;
452 return if defined($disk) && $disk ne $dev;
453 # whitelisting following devices
454 # hdX: ide block device
455 # sdX: sd block device
456 # vdX: virtual block device
457 # xvdX: xen virtual block device
458 # nvmeXnY: nvme devices
459 # cciss!cXnY: cciss devices
460 return if $dev !~ m/^(h|s|x?v)d[a-z]+$/ &&
461 $dev !~ m/^nvme\d+n\d+$/ &&
462 $dev !~ m/^cciss\!c\d+d\d+$/;
463
464 my $data = get_udev_info("/sys/block/$dev");
465 return if !defined($data);
466 my $devpath = $data->{devpath};
467
468 my $sysdir = "/sys/block/$dev";
469
470 # we do not want iscsi devices
471 return if is_iscsi($sysdir);
472
473 my $sysdata = get_sysdir_info($sysdir);
474 return if !defined($sysdata);
475
476 my $type = 'unknown';
477
478 if ($sysdata->{rotational} == 0) {
479 $type = 'ssd';
480 $data->{rpm} = 0;
481 } elsif ($sysdata->{rotational} == 1) {
482 if ($data->{rpm} != -1) {
483 $type = 'hdd';
484 } elsif ($data->{usb}) {
485 $type = 'usb';
486 $data->{rpm} = 0;
487 }
488 }
489
490 my $health = 'UNKNOWN';
491 my $wearout = 'N/A';
492
493 if (!$nosmart) {
494 eval {
495 my $smartdata = get_smart_data($devpath, ($type ne 'ssd'));
496 $health = $smartdata->{health} if $smartdata->{health};
497
498 if ($type eq 'ssd') {
499 # if we have an ssd we try to get the wearout indicator
500 my $wearval = get_wear_leveling_info($smartdata->{attributes}, $data->{model} || $sysdir->{model});
501 $wearout = $wearval if $wearval;
502 }
503 };
504 }
505
506 my $used;
507
508 $used = 'LVM' if $lvmlist->{$devpath};
509
510 $used = 'mounted' if &$dev_is_mounted($devpath);
511
512 $used = 'ZFS' if $zfslist->{$devpath};
513
514 # we replaced cciss/ with cciss! above
515 # but in the result we need cciss/ again
516 # because the caller might want to check the
517 # result again with the original parameter
518 if ($dev =~ m|^cciss!|) {
519 $dev =~ s|^cciss!|cciss/|;
520 }
521
522 $disklist->{$dev} = {
523 vendor => $sysdata->{vendor},
524 model => $data->{model} || $sysdata->{model},
525 size => $sysdata->{size},
526 serial => $data->{serial},
527 gpt => $data->{gpt},
528 rpm => $data->{rpm},
529 type => $type,
530 wwn => $data->{wwn},
531 health => $health,
532 devpath => $devpath,
533 wearout => $wearout,
534 };
535
536 my $osdid = -1;
537 my $bluestore = 0;
538
539 my $journal_count = 0;
540 my $db_count = 0;
541 my $wal_count = 0;
542
543 my $found_partitions;
544 my $found_lvm;
545 my $found_mountpoints;
546 my $found_zfs;
547 my $found_dm;
548 my $partpath = $devpath;
549
550 # remove part after last / to
551 # get the base path for the partitions
552 # e.g. from /dev/cciss/c0d0 get /dev/cciss
553 $partpath =~ s/\/[^\/]+$//;
554
555 dir_glob_foreach("$sysdir", "$dev.+", sub {
556 my ($part) = @_;
557
558 $found_partitions = 1;
559
560 if (my $mp = &$dev_is_mounted("$partpath/$part")) {
561 $found_mountpoints = 1;
562 if ($mp =~ m|^/var/lib/ceph/osd/ceph-(\d+)$|) {
563 $osdid = $1;
564 }
565 }
566
567 if ($lvmlist->{"$partpath/$part"}) {
568 $found_lvm = 1;
569 }
570
571 if ($zfslist->{"$partpath/$part"}) {
572 $found_zfs = 1;
573 }
574
575 if ($journalhash->{"$partpath/$part"}) {
576 $journal_count++ if $journalhash->{"$partpath/$part"} == 1;
577 $db_count++ if $journalhash->{"$partpath/$part"} == 2;
578 $wal_count++ if $journalhash->{"$partpath/$part"} == 3;
579 $bluestore = 1 if $journalhash->{"$partpath/$part"} == 4;
580 }
581
582 if (!dir_is_empty("$sysdir/$part/holders") && !$found_lvm) {
583 $found_dm = 1;
584 }
585 });
586
587 if ($ceph_volume_infos->{$devpath}) {
588 $journal_count += $ceph_volume_infos->{$devpath}->{journal} // 0;
589 $db_count += $ceph_volume_infos->{$devpath}->{db} // 0;
590 $wal_count += $ceph_volume_infos->{$devpath}->{wal} // 0;
591 if ($ceph_volume_infos->{$devpath}->{osdid}) {
592 $osdid = $ceph_volume_infos->{$devpath}->{osdid};
593 $bluestore = 1 if $ceph_volume_infos->{$devpath}->{bluestore};
594 }
595 }
596
597 $used = 'mounted' if $found_mountpoints && !$used;
598 $used = 'LVM' if $found_lvm && !$used;
599 $used = 'ZFS' if $found_zfs && !$used;
600 $used = 'Device Mapper' if $found_dm && !$used;
601 $used = 'partitions' if $found_partitions && !$used;
602
603 # multipath, software raid, etc.
604 # this check comes in last, to show more specific info
605 # if we have it
606 $used = 'Device Mapper' if !$used && !dir_is_empty("$sysdir/holders");
607
608 $disklist->{$dev}->{used} = $used if $used;
609 $disklist->{$dev}->{osdid} = $osdid;
610 $disklist->{$dev}->{journals} = $journal_count if $journal_count;
611 $disklist->{$dev}->{bluestore} = $bluestore if $osdid != -1;
612 $disklist->{$dev}->{db} = $db_count if $db_count;
613 $disklist->{$dev}->{wal} = $wal_count if $wal_count;
614 });
615
616 return $disklist;
617
618 }
619
620 sub get_partnum {
621 my ($part_path) = @_;
622
623 my ($mode, $rdev) = (stat($part_path))[2,6];
624
625 next if !$mode || !S_ISBLK($mode) || !$rdev;
626 my $major = PVE::Tools::dev_t_major($rdev);
627 my $minor = PVE::Tools::dev_t_minor($rdev);
628 my $partnum_path = "/sys/dev/block/$major:$minor/";
629
630 my $partnum;
631
632 $partnum = file_read_firstline("${partnum_path}partition");
633
634 die "Partition does not exists\n" if !defined($partnum);
635
636 #untaint and ensure it is a int
637 if ($partnum =~ m/(\d+)/) {
638 $partnum = $1;
639 die "Partition number $partnum is invalid\n" if $partnum > 128;
640 } else {
641 die "Failed to get partition number\n";
642 }
643
644 return $partnum;
645 }
646
647 sub get_blockdev {
648 my ($part_path) = @_;
649
650 my $dev = $1 if $part_path =~ m|^/dev/(.*)$|;
651 my $link = readlink "/sys/class/block/$dev";
652 my $block_dev = $1 if $link =~ m|([^/]*)/$dev$|;
653
654 die "Can't parse parent device\n" if !defined($block_dev);
655 die "No valid block device\n" if index($dev, $block_dev) == -1;
656
657 $block_dev = "/dev/$block_dev";
658 die "Block device does not exsists\n" if !(-b $block_dev);
659
660 return $block_dev;
661 }
662
663 sub locked_disk_action {
664 my ($sub) = @_;
665 my $res = PVE::Tools::lock_file('/run/lock/pve-diskmanage.lck', undef, $sub);
666 die $@ if $@;
667 return $res;
668 }
669
670 sub assert_disk_unused {
671 my ($dev) = @_;
672
673 die "device '$dev' is already in use\n" if disk_is_used($dev);
674
675 return undef;
676 }
677
678 1;