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