]> git.proxmox.com Git - pve-storage.git/blob - PVE/Diskmanage.pm
disk management: set more specific type for nvme
[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 text, allow for decimal values
138 if ($line =~ m/Percentage Used:\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, $model) = @_;
400 my $attributes = $smartdata->{attributes};
401
402 if (defined($smartdata->{wearout})) {
403 return $smartdata->{wearout};
404 }
405
406 my $wearout;
407
408 my $vendormap = {
409 'kingston' => 231,
410 'samsung' => 177,
411 'intel' => 233,
412 'sandisk' => 233,
413 'crucial' => 202,
414 'default' => 233,
415 };
416
417 # find target attr id
418
419 my $attrid;
420
421 foreach my $vendor (keys %$vendormap) {
422 if ($model =~ m/$vendor/i) {
423 $attrid = $vendormap->{$vendor};
424 # found the attribute
425 last;
426 }
427 }
428
429 if (!$attrid) {
430 $attrid = $vendormap->{default};
431 }
432
433 foreach my $attr (@$attributes) {
434 next if $attr->{id} != $attrid;
435 $wearout = $attr->{value};
436 last;
437 }
438
439 return $wearout;
440 }
441
442 sub dir_is_empty {
443 my ($dir) = @_;
444
445 my $dh = IO::Dir->new ($dir);
446 return 1 if !$dh;
447
448 while (defined(my $tmp = $dh->read)) {
449 next if $tmp eq '.' || $tmp eq '..';
450 $dh->close;
451 return 0;
452 }
453 $dh->close;
454 return 1;
455 }
456
457 sub is_iscsi {
458 my ($sysdir) = @_;
459
460 if (-l $sysdir && readlink($sysdir) =~ m|host[^/]*/session[^/]*|) {
461 return 1;
462 }
463
464 return 0;
465 }
466
467 my sub is_ssdlike {
468 my ($type) = @_;
469 return $type eq 'ssd' || $type eq 'nvme';
470 }
471
472 sub get_disks {
473 my ($disks, $nosmart) = @_;
474 my $disklist = {};
475
476 my $mounted = {};
477
478 my $mounts = PVE::ProcFSTools::parse_proc_mounts();
479
480 foreach my $mount (@$mounts) {
481 next if $mount->[0] !~ m|^/dev/|;
482 $mounted->{abs_path($mount->[0])} = $mount->[1];
483 };
484
485 my $dev_is_mounted = sub {
486 my ($dev) = @_;
487 return $mounted->{$dev};
488 };
489
490 my $parttype_map = get_parttype_info();
491
492 my $journalhash = get_ceph_journals($parttype_map);
493 my $ceph_volume_infos = get_ceph_volume_infos();
494
495 my $zfshash = get_zfs_devices($parttype_map);
496
497 my $lvmhash = get_lvm_devices($parttype_map);
498
499 my $disk_regex = ".*";
500 if (defined($disks)) {
501 if (!ref($disks)) {
502 $disks = [ $disks ];
503 } elsif (ref($disks) ne 'ARRAY') {
504 die "disks is not a string or array reference\n";
505 }
506 # we get cciss/c0d0 but need cciss!c0d0
507 map { s|cciss/|cciss!| } @$disks;
508
509 $disk_regex = "(?:" . join('|', @$disks) . ")";
510 }
511
512 dir_glob_foreach('/sys/block', $disk_regex, sub {
513 my ($dev) = @_;
514 # whitelisting following devices
515 # hdX: ide block device
516 # sdX: sd block device
517 # vdX: virtual block device
518 # xvdX: xen virtual block device
519 # nvmeXnY: nvme devices
520 # cciss!cXnY: cciss devices
521 return if $dev !~ m/^(h|s|x?v)d[a-z]+$/ &&
522 $dev !~ m/^nvme\d+n\d+$/ &&
523 $dev !~ m/^cciss\!c\d+d\d+$/;
524
525 my $data = get_udev_info("/sys/block/$dev");
526 return if !defined($data);
527 my $devpath = $data->{devpath};
528
529 my $sysdir = "/sys/block/$dev";
530
531 # we do not want iscsi devices
532 return if is_iscsi($sysdir);
533
534 my $sysdata = get_sysdir_info($sysdir);
535 return if !defined($sysdata);
536
537 my $type = 'unknown';
538
539 if ($sysdata->{rotational} == 0) {
540 $type = 'ssd';
541 $type = 'nvme' if $dev =~ m/^nvme\d+n\d+$/;
542 $data->{rpm} = 0;
543 } elsif ($sysdata->{rotational} == 1) {
544 if ($data->{rpm} != -1) {
545 $type = 'hdd';
546 } elsif ($data->{usb}) {
547 $type = 'usb';
548 $data->{rpm} = 0;
549 }
550 }
551
552 my $health = 'UNKNOWN';
553 my $wearout = 'N/A';
554
555 if (!$nosmart) {
556 eval {
557 my $smartdata = get_smart_data($devpath, !is_ssdlike($type));
558 $health = $smartdata->{health} if $smartdata->{health};
559
560 if (is_ssdlike($type)) {
561 # if we have an ssd we try to get the wearout indicator
562 my $wearval = get_wear_leveling_info($smartdata, $data->{model} || $sysdata->{model});
563 $wearout = $wearval if defined($wearval);
564 }
565 };
566 }
567
568 my $used;
569
570 $used = 'LVM' if $lvmhash->{$devpath};
571
572 $used = 'mounted' if &$dev_is_mounted($devpath);
573
574 $used = 'ZFS' if $zfshash->{$devpath};
575
576 # we replaced cciss/ with cciss! above
577 # but in the result we need cciss/ again
578 # because the caller might want to check the
579 # result again with the original parameter
580 if ($dev =~ m|^cciss!|) {
581 $dev =~ s|^cciss!|cciss/|;
582 }
583
584 $disklist->{$dev} = {
585 vendor => $sysdata->{vendor},
586 model => $data->{model} || $sysdata->{model},
587 size => $sysdata->{size},
588 serial => $data->{serial},
589 gpt => $data->{gpt},
590 rpm => $data->{rpm},
591 type => $type,
592 wwn => $data->{wwn},
593 health => $health,
594 devpath => $devpath,
595 wearout => $wearout,
596 };
597
598 my $by_id_link = $data->{by_id_link};
599 $disklist->{$dev}->{by_id_link} = $by_id_link if defined($by_id_link);
600
601 my $osdid = -1;
602 my $bluestore = 0;
603 my $osdencrypted = 0;
604
605 my $journal_count = 0;
606 my $db_count = 0;
607 my $wal_count = 0;
608
609 my $found_partitions;
610 my $found_lvm;
611 my $found_mountpoints;
612 my $found_zfs;
613 my $found_dm;
614 my $partpath = $devpath;
615
616 # remove part after last / to
617 # get the base path for the partitions
618 # e.g. from /dev/cciss/c0d0 get /dev/cciss
619 $partpath =~ s/\/[^\/]+$//;
620
621 dir_glob_foreach("$sysdir", "$dev.+", sub {
622 my ($part) = @_;
623
624 $found_partitions = 1;
625
626 if (my $mp = &$dev_is_mounted("$partpath/$part")) {
627 $found_mountpoints = 1;
628 if ($mp =~ m|^/var/lib/ceph/osd/ceph-(\d+)$|) {
629 $osdid = $1;
630 }
631 }
632
633 if ($lvmhash->{"$partpath/$part"}) {
634 $found_lvm = 1;
635 }
636
637 if ($zfshash->{"$partpath/$part"}) {
638 $found_zfs = 1;
639 }
640
641 if (my $journal_part = $journalhash->{"$partpath/$part"}) {
642 $journal_count++ if $journal_part == 1;
643 $db_count++ if $journal_part == 2;
644 $wal_count++ if $journal_part == 3;
645 $bluestore = 1 if $journal_part == 4;
646 }
647
648 if (!dir_is_empty("$sysdir/$part/holders") && !$found_lvm) {
649 $found_dm = 1;
650 }
651 });
652
653 if (my $ceph_volume = $ceph_volume_infos->{$devpath}) {
654 $journal_count += $ceph_volume->{journal} // 0;
655 $db_count += $ceph_volume->{db} // 0;
656 $wal_count += $ceph_volume->{wal} // 0;
657 if (defined($ceph_volume->{osdid})) {
658 $osdid = $ceph_volume->{osdid};
659 $bluestore = 1 if $ceph_volume->{bluestore};
660 $osdencrypted = 1 if $ceph_volume->{encrypted};
661 }
662 }
663
664 $used = 'mounted' if $found_mountpoints && !$used;
665 $used = 'LVM' if $found_lvm && !$used;
666 $used = 'ZFS' if $found_zfs && !$used;
667 $used = 'Device Mapper' if $found_dm && !$used;
668 $used = 'partitions' if $found_partitions && !$used;
669
670 # multipath, software raid, etc.
671 # this check comes in last, to show more specific info
672 # if we have it
673 $used = 'Device Mapper' if !$used && !dir_is_empty("$sysdir/holders");
674
675 $disklist->{$dev}->{used} = $used if $used;
676 $disklist->{$dev}->{osdid} = $osdid;
677 $disklist->{$dev}->{journals} = $journal_count if $journal_count;
678 $disklist->{$dev}->{bluestore} = $bluestore if $osdid != -1;
679 $disklist->{$dev}->{osdencrypted} = $osdencrypted if $osdid != -1;
680 $disklist->{$dev}->{db} = $db_count if $db_count;
681 $disklist->{$dev}->{wal} = $wal_count if $wal_count;
682 });
683
684 return $disklist;
685
686 }
687
688 sub get_partnum {
689 my ($part_path) = @_;
690
691 my $st = stat($part_path);
692
693 next if !$st->mode || !S_ISBLK($st->mode) || !$st->rdev;
694 my $major = PVE::Tools::dev_t_major($st->rdev);
695 my $minor = PVE::Tools::dev_t_minor($st->rdev);
696 my $partnum_path = "/sys/dev/block/$major:$minor/";
697
698 my $partnum;
699
700 $partnum = file_read_firstline("${partnum_path}partition");
701
702 die "Partition does not exist\n" if !defined($partnum);
703
704 #untaint and ensure it is a int
705 if ($partnum =~ m/(\d+)/) {
706 $partnum = $1;
707 die "Partition number $partnum is invalid\n" if $partnum > 128;
708 } else {
709 die "Failed to get partition number\n";
710 }
711
712 return $partnum;
713 }
714
715 sub get_blockdev {
716 my ($part_path) = @_;
717
718 my $dev = $1 if $part_path =~ m|^/dev/(.*)$|;
719 my $link = readlink "/sys/class/block/$dev";
720 my $block_dev = $1 if $link =~ m|([^/]*)/$dev$|;
721
722 die "Can't parse parent device\n" if !defined($block_dev);
723 die "No valid block device\n" if index($dev, $block_dev) == -1;
724
725 $block_dev = "/dev/$block_dev";
726 die "Block device does not exsists\n" if !(-b $block_dev);
727
728 return $block_dev;
729 }
730
731 sub locked_disk_action {
732 my ($sub) = @_;
733 my $res = PVE::Tools::lock_file('/run/lock/pve-diskmanage.lck', undef, $sub);
734 die $@ if $@;
735 return $res;
736 }
737
738 sub assert_disk_unused {
739 my ($dev) = @_;
740
741 die "device '$dev' is already in use\n" if disk_is_used($dev);
742
743 return undef;
744 }
745
746 sub append_partition {
747 my ($dev, $size) = @_;
748
749 my $devname = $dev;
750 $devname =~ s|^/dev/||;
751
752 my $newpartid = 1;
753 dir_glob_foreach("/sys/block/$devname", qr/\Q$devname\E.*?(\d+)/, sub {
754 my ($part, $partid) = @_;
755
756 if ($partid >= $newpartid) {
757 $newpartid = $partid + 1;
758 }
759 });
760
761 $size = PVE::Tools::convert_size($size, 'b' => 'mb');
762
763 run_command([ $SGDISK, '-n', "$newpartid:0:+${size}M", $dev ],
764 errmsg => "error creating partition '$newpartid' on '$dev'");
765
766 my $partition;
767
768 # loop again to detect the real partiton device which does not always follow
769 # a strict $devname$partition scheme like /dev/nvme0n1 -> /dev/nvme0n1p1
770 dir_glob_foreach("/sys/block/$devname", qr/\Q$devname\E.*$newpartid/, sub {
771 my ($part) = @_;
772
773 $partition = "/dev/$part";
774 });
775
776 return $partition;
777 }
778
779 1;