]> git.proxmox.com Git - pve-storage.git/blob - PVE/Diskmanage.pm
Fix #2020: use /sys to map nvmeXnY to nvmeX
[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 get_disks {
375 my ($disk, $nosmart) = @_;
376 my $disklist = {};
377
378 my $mounted = {};
379
380 my $mounts = PVE::ProcFSTools::parse_proc_mounts();
381
382 foreach my $mount (@$mounts) {
383 next if $mount->[0] !~ m|^/dev/|;
384 $mounted->{abs_path($mount->[0])} = $mount->[1];
385 };
386
387 my $dev_is_mounted = sub {
388 my ($dev) = @_;
389 return $mounted->{$dev};
390 };
391
392 my $journalhash = get_ceph_journals();
393
394 my $zfslist = get_zfs_devices();
395
396 my $lvmlist = get_lvm_devices();
397
398 # we get cciss/c0d0 but need cciss!c0d0
399 if (defined($disk) && $disk =~ m|^cciss/|) {
400 $disk =~ s|cciss/|cciss!|;
401 }
402
403 dir_glob_foreach('/sys/block', '.*', sub {
404 my ($dev) = @_;
405 return if defined($disk) && $disk ne $dev;
406 # whitelisting following devices
407 # hdX: ide block device
408 # sdX: sd block device
409 # vdX: virtual block device
410 # xvdX: xen virtual block device
411 # nvmeXnY: nvme devices
412 # cciss!cXnY: cciss devices
413 return if $dev !~ m/^(h|s|x?v)d[a-z]+$/ &&
414 $dev !~ m/^nvme\d+n\d+$/ &&
415 $dev !~ m/^cciss\!c\d+d\d+$/;
416
417 my $data = get_udev_info("/sys/block/$dev");
418 return if !defined($data);
419 my $devpath = $data->{devpath};
420
421 my $sysdir = "/sys/block/$dev";
422
423 # we do not want iscsi devices
424 return if -l $sysdir && readlink($sysdir) =~ m|host[^/]*/session[^/]*|;
425
426 my $sysdata = get_sysdir_info($sysdir);
427 return if !defined($sysdata);
428
429 my $type = 'unknown';
430
431 if ($sysdata->{rotational} == 0) {
432 $type = 'ssd';
433 $data->{rpm} = 0;
434 } elsif ($sysdata->{rotational} == 1) {
435 if ($data->{rpm} != -1) {
436 $type = 'hdd';
437 } elsif ($data->{usb}) {
438 $type = 'usb';
439 $data->{rpm} = 0;
440 }
441 }
442
443 my $health = 'UNKNOWN';
444 my $wearout = 'N/A';
445
446 if (!$nosmart) {
447 eval {
448 my $smartdata = get_smart_data($devpath, ($type ne 'ssd'));
449 $health = $smartdata->{health} if $smartdata->{health};
450
451 if ($type eq 'ssd') {
452 # if we have an ssd we try to get the wearout indicator
453 my $wearval = get_wear_leveling_info($smartdata->{attributes}, $data->{model} || $sysdir->{model});
454 $wearout = $wearval if $wearval;
455 }
456 };
457 }
458
459 my $used;
460
461 $used = 'LVM' if $lvmlist->{$devpath};
462
463 $used = 'mounted' if &$dev_is_mounted($devpath);
464
465 $used = 'ZFS' if $zfslist->{$devpath};
466
467 # we replaced cciss/ with cciss! above
468 # but in the result we need cciss/ again
469 # because the caller might want to check the
470 # result again with the original parameter
471 if ($dev =~ m|^cciss!|) {
472 $dev =~ s|^cciss!|cciss/|;
473 }
474
475 $disklist->{$dev} = {
476 vendor => $sysdata->{vendor},
477 model => $data->{model} || $sysdata->{model},
478 size => $sysdata->{size},
479 serial => $data->{serial},
480 gpt => $data->{gpt},
481 rpm => $data->{rpm},
482 type => $type,
483 wwn => $data->{wwn},
484 health => $health,
485 devpath => $devpath,
486 wearout => $wearout,
487 };
488
489 my $osdid = -1;
490 my $bluestore = 0;
491
492 my $journal_count = 0;
493 my $db_count = 0;
494 my $wal_count = 0;
495
496 my $found_partitions;
497 my $found_lvm;
498 my $found_mountpoints;
499 my $found_zfs;
500 my $found_dm;
501 my $partpath = $devpath;
502
503 # remove part after last / to
504 # get the base path for the partitions
505 # e.g. from /dev/cciss/c0d0 get /dev/cciss
506 $partpath =~ s/\/[^\/]+$//;
507
508 dir_glob_foreach("$sysdir", "$dev.+", sub {
509 my ($part) = @_;
510
511 $found_partitions = 1;
512
513 if (my $mp = &$dev_is_mounted("$partpath/$part")) {
514 $found_mountpoints = 1;
515 if ($mp =~ m|^/var/lib/ceph/osd/ceph-(\d+)$|) {
516 $osdid = $1;
517 }
518 }
519
520 if ($lvmlist->{"$partpath/$part"}) {
521 $found_lvm = 1;
522 }
523
524 if ($zfslist->{"$partpath/$part"}) {
525 $found_zfs = 1;
526 }
527
528 if ($journalhash->{"$partpath/$part"}) {
529 $journal_count++ if $journalhash->{"$partpath/$part"} == 1;
530 $db_count++ if $journalhash->{"$partpath/$part"} == 2;
531 $wal_count++ if $journalhash->{"$partpath/$part"} == 3;
532 $bluestore = 1 if $journalhash->{"$partpath/$part"} == 4;
533 }
534
535 if (!dir_is_empty("$sysdir/$part/holders") && !$found_lvm) {
536 $found_dm = 1;
537 }
538 });
539
540 $used = 'mounted' if $found_mountpoints && !$used;
541 $used = 'LVM' if $found_lvm && !$used;
542 $used = 'ZFS' if $found_zfs && !$used;
543 $used = 'Device Mapper' if $found_dm && !$used;
544 $used = 'partitions' if $found_partitions && !$used;
545
546 # multipath, software raid, etc.
547 # this check comes in last, to show more specific info
548 # if we have it
549 $used = 'Device Mapper' if !$used && !dir_is_empty("$sysdir/holders");
550
551 $disklist->{$dev}->{used} = $used if $used;
552 $disklist->{$dev}->{osdid} = $osdid;
553 $disklist->{$dev}->{journals} = $journal_count if $journal_count;
554 $disklist->{$dev}->{bluestore} = $bluestore if $osdid != -1;
555 $disklist->{$dev}->{db} = $db_count if $db_count;
556 $disklist->{$dev}->{wal} = $wal_count if $wal_count;
557 });
558
559 return $disklist;
560
561 }
562
563 sub get_partnum {
564 my ($part_path) = @_;
565
566 my ($mode, $rdev) = (stat($part_path))[2,6];
567
568 next if !$mode || !S_ISBLK($mode) || !$rdev;
569 my $major = int($rdev / 0x100);
570 my $minor = $rdev % 0x100;
571 my $partnum_path = "/sys/dev/block/$major:$minor/";
572
573 my $partnum;
574
575 $partnum = file_read_firstline("${partnum_path}partition");
576
577 die "Partition does not exists\n" if !defined($partnum);
578
579 #untaint and ensure it is a int
580 if ($partnum =~ m/(\d+)/) {
581 $partnum = $1;
582 die "Partition number $partnum is invalid\n" if $partnum > 128;
583 } else {
584 die "Failed to get partition number\n";
585 }
586
587 return $partnum;
588 }
589
590 sub get_blockdev {
591 my ($part_path) = @_;
592
593 my $dev = $1 if $part_path =~ m|^/dev/(.*)$|;
594 my $link = readlink "/sys/class/block/$dev";
595 my $block_dev = $1 if $link =~ m|([^/]*)/$dev$|;
596
597 die "Can't parse parent device\n" if !defined($block_dev);
598 die "No valid block device\n" if index($dev, $block_dev) == -1;
599
600 $block_dev = "/dev/$block_dev";
601 die "Block device does not exsists\n" if !(-b $block_dev);
602
603 return $block_dev;
604 }
605
606 sub locked_disk_action {
607 my ($sub) = @_;
608 my $res = PVE::Tools::lock_file('/run/lock/pve-diskmanage.lck', undef, $sub);
609 die $@ if $@;
610 return $res;
611 }
612
613 sub assert_disk_unused {
614 my ($dev) = @_;
615
616 die "device '$dev' is already in use\n" if disk_is_used($dev);
617
618 return undef;
619 }
620
621 1;