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