]> git.proxmox.com Git - pve-storage.git/blob - PVE/Storage.pm
drop absolute udevadm path
[pve-storage.git] / PVE / Storage.pm
1 package PVE::Storage;
2
3 use strict;
4 use warnings;
5 use Data::Dumper;
6
7 use POSIX;
8 use IO::Select;
9 use IO::File;
10 use IO::Socket::IP;
11 use IPC::Open3;
12 use File::Basename;
13 use File::Path;
14 use Cwd 'abs_path';
15 use Socket;
16 use Time::Local qw(timelocal);
17
18 use PVE::Tools qw(run_command file_read_firstline dir_glob_foreach $IPV6RE);
19 use PVE::Cluster qw(cfs_read_file cfs_write_file cfs_lock_file);
20 use PVE::DataCenterConfig;
21 use PVE::Exception qw(raise_param_exc raise);
22 use PVE::JSONSchema;
23 use PVE::INotify;
24 use PVE::RPCEnvironment;
25 use PVE::SSHInfo;
26
27 use PVE::Storage::Plugin;
28 use PVE::Storage::DirPlugin;
29 use PVE::Storage::LVMPlugin;
30 use PVE::Storage::LvmThinPlugin;
31 use PVE::Storage::NFSPlugin;
32 use PVE::Storage::CIFSPlugin;
33 use PVE::Storage::ISCSIPlugin;
34 use PVE::Storage::RBDPlugin;
35 use PVE::Storage::CephFSPlugin;
36 use PVE::Storage::ISCSIDirectPlugin;
37 use PVE::Storage::GlusterfsPlugin;
38 use PVE::Storage::ZFSPoolPlugin;
39 use PVE::Storage::ZFSPlugin;
40 use PVE::Storage::DRBDPlugin;
41 use PVE::Storage::PBSPlugin;
42
43 # Storage API version. Increment it on changes in storage API interface.
44 use constant APIVER => 8;
45 # Age is the number of versions we're backward compatible with.
46 # This is like having 'current=APIVER' and age='APIAGE' in libtool,
47 # see https://www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html
48 use constant APIAGE => 7;
49
50 # load standard plugins
51 PVE::Storage::DirPlugin->register();
52 PVE::Storage::LVMPlugin->register();
53 PVE::Storage::LvmThinPlugin->register();
54 PVE::Storage::NFSPlugin->register();
55 PVE::Storage::CIFSPlugin->register();
56 PVE::Storage::ISCSIPlugin->register();
57 PVE::Storage::RBDPlugin->register();
58 PVE::Storage::CephFSPlugin->register();
59 PVE::Storage::ISCSIDirectPlugin->register();
60 PVE::Storage::GlusterfsPlugin->register();
61 PVE::Storage::ZFSPoolPlugin->register();
62 PVE::Storage::ZFSPlugin->register();
63 PVE::Storage::DRBDPlugin->register();
64 PVE::Storage::PBSPlugin->register();
65
66 # load third-party plugins
67 if ( -d '/usr/share/perl5/PVE/Storage/Custom' ) {
68 dir_glob_foreach('/usr/share/perl5/PVE/Storage/Custom', '.*\.pm$', sub {
69 my ($file) = @_;
70 my $modname = 'PVE::Storage::Custom::' . $file;
71 $modname =~ s!\.pm$!!;
72 $file = 'PVE/Storage/Custom/' . $file;
73
74 eval {
75 require $file;
76
77 # Check perl interface:
78 die "not derived from PVE::Storage::Plugin\n"
79 if !$modname->isa('PVE::Storage::Plugin');
80 die "does not provide an api() method\n"
81 if !$modname->can('api');
82 # Check storage API version and that file is really storage plugin.
83 my $version = $modname->api();
84 die "implements an API version newer than current ($version > " . APIVER . ")\n"
85 if $version > APIVER;
86 my $min_version = (APIVER - APIAGE);
87 die "API version too old, please update the plugin ($version < $min_version)\n"
88 if $version < $min_version;
89 import $file;
90 $modname->register();
91
92 # If we got this far and the API version is not the same, make some
93 # noise:
94 warn "Plugin \"$modname\" is implementing an older storage API, an upgrade is recommended\n"
95 if $version != APIVER;
96 };
97 if ($@) {
98 warn "Error loading storage plugin \"$modname\": $@";
99 }
100 });
101 }
102
103 # initialize all plugins
104 PVE::Storage::Plugin->init();
105
106 our $iso_extension_re = qr/\.(?:iso|img)/i;
107
108 # PVE::Storage utility functions
109
110 sub config {
111 return cfs_read_file("storage.cfg");
112 }
113
114 sub write_config {
115 my ($cfg) = @_;
116
117 cfs_write_file('storage.cfg', $cfg);
118 }
119
120 sub lock_storage_config {
121 my ($code, $errmsg) = @_;
122
123 cfs_lock_file("storage.cfg", undef, $code);
124 my $err = $@;
125 if ($err) {
126 $errmsg ? die "$errmsg: $err" : die $err;
127 }
128 }
129
130 # FIXME remove maxfiles for PVE 7.0
131 my $convert_maxfiles_to_prune_backups = sub {
132 my ($scfg) = @_;
133
134 return if !$scfg;
135
136 my $maxfiles = delete $scfg->{maxfiles};
137
138 if (!defined($scfg->{'prune-backups'}) && defined($maxfiles)) {
139 my $prune_backups;
140 if ($maxfiles) {
141 $prune_backups = { 'keep-last' => $maxfiles };
142 } else { # maxfiles 0 means no limit
143 $prune_backups = { 'keep-all' => 1 };
144 }
145 $scfg->{'prune-backups'} = PVE::JSONSchema::print_property_string(
146 $prune_backups,
147 'prune-backups'
148 );
149 }
150 };
151
152 sub storage_config {
153 my ($cfg, $storeid, $noerr) = @_;
154
155 die "no storage ID specified\n" if !$storeid;
156
157 my $scfg = $cfg->{ids}->{$storeid};
158
159 die "storage '$storeid' does not exist\n" if (!$noerr && !$scfg);
160
161 $convert_maxfiles_to_prune_backups->($scfg);
162
163 return $scfg;
164 }
165
166 sub storage_check_node {
167 my ($cfg, $storeid, $node, $noerr) = @_;
168
169 my $scfg = storage_config($cfg, $storeid);
170
171 if ($scfg->{nodes}) {
172 $node = PVE::INotify::nodename() if !$node || ($node eq 'localhost');
173 if (!$scfg->{nodes}->{$node}) {
174 die "storage '$storeid' is not available on node '$node'\n" if !$noerr;
175 return undef;
176 }
177 }
178
179 return $scfg;
180 }
181
182 sub storage_check_enabled {
183 my ($cfg, $storeid, $node, $noerr) = @_;
184
185 my $scfg = storage_config($cfg, $storeid);
186
187 if ($scfg->{disable}) {
188 die "storage '$storeid' is disabled\n" if !$noerr;
189 return undef;
190 }
191
192 return storage_check_node($cfg, $storeid, $node, $noerr);
193 }
194
195 # storage_can_replicate:
196 # return true if storage supports replication
197 # (volumes alocated with vdisk_alloc() has replication feature)
198 sub storage_can_replicate {
199 my ($cfg, $storeid, $format) = @_;
200
201 my $scfg = storage_config($cfg, $storeid);
202 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
203 return $plugin->storage_can_replicate($scfg, $storeid, $format);
204 }
205
206 sub storage_ids {
207 my ($cfg) = @_;
208
209 return keys %{$cfg->{ids}};
210 }
211
212 sub file_size_info {
213 my ($filename, $timeout) = @_;
214
215 return PVE::Storage::Plugin::file_size_info($filename, $timeout);
216 }
217
218 sub get_volume_notes {
219 my ($cfg, $volid, $timeout) = @_;
220
221 my ($storeid, $volname) = parse_volume_id($volid);
222 my $scfg = storage_config($cfg, $storeid);
223 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
224
225 return $plugin->get_volume_notes($scfg, $storeid, $volname, $timeout);
226 }
227
228 sub update_volume_notes {
229 my ($cfg, $volid, $notes, $timeout) = @_;
230
231 my ($storeid, $volname) = parse_volume_id($volid);
232 my $scfg = storage_config($cfg, $storeid);
233 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
234
235 $plugin->update_volume_notes($scfg, $storeid, $volname, $notes, $timeout);
236 }
237
238 sub volume_size_info {
239 my ($cfg, $volid, $timeout) = @_;
240
241 my ($storeid, $volname) = parse_volume_id($volid, 1);
242 if ($storeid) {
243 my $scfg = storage_config($cfg, $storeid);
244 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
245 return $plugin->volume_size_info($scfg, $storeid, $volname, $timeout);
246 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
247 return file_size_info($volid, $timeout);
248 } else {
249 return 0;
250 }
251 }
252
253 sub volume_resize {
254 my ($cfg, $volid, $size, $running) = @_;
255
256 my $padding = (1024 - $size % 1024) % 1024;
257 $size = $size + $padding;
258
259 my ($storeid, $volname) = parse_volume_id($volid, 1);
260 if ($storeid) {
261 my $scfg = storage_config($cfg, $storeid);
262 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
263 return $plugin->volume_resize($scfg, $storeid, $volname, $size, $running);
264 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
265 die "resize file/device '$volid' is not possible\n";
266 } else {
267 die "unable to parse volume ID '$volid'\n";
268 }
269 }
270
271 sub volume_rollback_is_possible {
272 my ($cfg, $volid, $snap) = @_;
273
274 my ($storeid, $volname) = parse_volume_id($volid, 1);
275 if ($storeid) {
276 my $scfg = storage_config($cfg, $storeid);
277 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
278 return $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
279 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
280 die "snapshot rollback file/device '$volid' is not possible\n";
281 } else {
282 die "unable to parse volume ID '$volid'\n";
283 }
284 }
285
286 sub volume_snapshot {
287 my ($cfg, $volid, $snap) = @_;
288
289 my ($storeid, $volname) = parse_volume_id($volid, 1);
290 if ($storeid) {
291 my $scfg = storage_config($cfg, $storeid);
292 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
293 return $plugin->volume_snapshot($scfg, $storeid, $volname, $snap);
294 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
295 die "snapshot file/device '$volid' is not possible\n";
296 } else {
297 die "unable to parse volume ID '$volid'\n";
298 }
299 }
300
301 sub volume_snapshot_rollback {
302 my ($cfg, $volid, $snap) = @_;
303
304 my ($storeid, $volname) = parse_volume_id($volid, 1);
305 if ($storeid) {
306 my $scfg = storage_config($cfg, $storeid);
307 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
308 $plugin->volume_rollback_is_possible($scfg, $storeid, $volname, $snap);
309 return $plugin->volume_snapshot_rollback($scfg, $storeid, $volname, $snap);
310 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
311 die "snapshot rollback file/device '$volid' is not possible\n";
312 } else {
313 die "unable to parse volume ID '$volid'\n";
314 }
315 }
316
317 sub volume_snapshot_delete {
318 my ($cfg, $volid, $snap, $running) = @_;
319
320 my ($storeid, $volname) = parse_volume_id($volid, 1);
321 if ($storeid) {
322 my $scfg = storage_config($cfg, $storeid);
323 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
324 return $plugin->volume_snapshot_delete($scfg, $storeid, $volname, $snap, $running);
325 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
326 die "snapshot delete file/device '$volid' is not possible\n";
327 } else {
328 die "unable to parse volume ID '$volid'\n";
329 }
330 }
331
332 # check if a filesystem on top of a volume needs to flush its journal for
333 # consistency (see fsfreeze(8)) before a snapshot is taken - needed for
334 # container mountpoints
335 sub volume_snapshot_needs_fsfreeze {
336 my ($cfg, $volid) = @_;
337
338 my ($storeid, $volname) = parse_volume_id($volid);
339 my $scfg = storage_config($cfg, $storeid);
340 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
341 return $plugin->volume_snapshot_needs_fsfreeze();
342 }
343
344 # check if a volume or snapshot supports a given feature
345 # $feature - one of:
346 # clone - linked clone is possible
347 # copy - full clone is possible
348 # replicate - replication is possible
349 # snapshot - taking a snapshot is possible
350 # sparseinit - volume is sparsely initialized
351 # template - conversion to base image is possible
352 # $snap - check if the feature is supported for a given snapshot
353 # $running - if the guest owning the volume is running
354 # $opts - hash with further options:
355 # valid_target_formats - list of formats for the target of a copy/clone
356 # operation that the caller could work with. The
357 # format of $volid is always considered valid and if
358 # no list is specified, all formats are considered valid.
359 sub volume_has_feature {
360 my ($cfg, $feature, $volid, $snap, $running, $opts) = @_;
361
362 my ($storeid, $volname) = parse_volume_id($volid, 1);
363 if ($storeid) {
364 my $scfg = storage_config($cfg, $storeid);
365 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
366 return $plugin->volume_has_feature($scfg, $feature, $storeid, $volname, $snap, $running, $opts);
367 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
368 return undef;
369 } else {
370 return undef;
371 }
372 }
373
374 sub volume_snapshot_list {
375 my ($cfg, $volid) = @_;
376
377 my ($storeid, $volname) = parse_volume_id($volid, 1);
378 if ($storeid) {
379 my $scfg = storage_config($cfg, $storeid);
380 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
381 return $plugin->volume_snapshot_list($scfg, $storeid, $volname);
382 } elsif ($volid =~ m|^(/.+)$| && -e $volid) {
383 die "send file/device '$volid' is not possible\n";
384 } else {
385 die "unable to parse volume ID '$volid'\n";
386 }
387 # return an empty array if dataset does not exist.
388 }
389
390 sub get_image_dir {
391 my ($cfg, $storeid, $vmid) = @_;
392
393 my $scfg = storage_config($cfg, $storeid);
394 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
395
396 my $path = $plugin->get_subdir($scfg, 'images');
397
398 return $vmid ? "$path/$vmid" : $path;
399 }
400
401 sub get_private_dir {
402 my ($cfg, $storeid, $vmid) = @_;
403
404 my $scfg = storage_config($cfg, $storeid);
405 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
406
407 my $path = $plugin->get_subdir($scfg, 'rootdir');
408
409 return $vmid ? "$path/$vmid" : $path;
410 }
411
412 sub get_iso_dir {
413 my ($cfg, $storeid) = @_;
414
415 my $scfg = storage_config($cfg, $storeid);
416 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
417
418 return $plugin->get_subdir($scfg, 'iso');
419 }
420
421 sub get_vztmpl_dir {
422 my ($cfg, $storeid) = @_;
423
424 my $scfg = storage_config($cfg, $storeid);
425 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
426
427 return $plugin->get_subdir($scfg, 'vztmpl');
428 }
429
430 sub get_backup_dir {
431 my ($cfg, $storeid) = @_;
432
433 my $scfg = storage_config($cfg, $storeid);
434 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
435
436 return $plugin->get_subdir($scfg, 'backup');
437 }
438
439 # library implementation
440
441 sub parse_vmid {
442 my $vmid = shift;
443
444 die "VMID '$vmid' contains illegal characters\n" if $vmid !~ m/^\d+$/;
445
446 return int($vmid);
447 }
448
449 # NOTE: basename and basevmid are always undef for LVM-thin, where the
450 # clone -> base reference is not encoded in the volume ID.
451 # see note in PVE::Storage::LvmThinPlugin for details.
452 sub parse_volname {
453 my ($cfg, $volid) = @_;
454
455 my ($storeid, $volname) = parse_volume_id($volid);
456
457 my $scfg = storage_config($cfg, $storeid);
458
459 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
460
461 # returns ($vtype, $name, $vmid, $basename, $basevmid, $isBase, $format)
462
463 return $plugin->parse_volname($volname);
464 }
465
466 sub parse_volume_id {
467 my ($volid, $noerr) = @_;
468
469 return PVE::Storage::Plugin::parse_volume_id($volid, $noerr);
470 }
471
472 # test if we have read access to volid
473 sub check_volume_access {
474 my ($rpcenv, $user, $cfg, $vmid, $volid) = @_;
475
476 my ($sid, $volname) = parse_volume_id($volid, 1);
477 if ($sid) {
478 my ($vtype, undef, $ownervm) = parse_volname($cfg, $volid);
479 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
480 # require at least read access to storage, (custom) templates/ISOs could be sensitive
481 $rpcenv->check_any($user, "/storage/$sid", ['Datastore.AllocateSpace', 'Datastore.Audit']);
482 } elsif (defined($ownervm) && defined($vmid) && ($ownervm == $vmid)) {
483 # we are owner - allow access
484 } elsif ($vtype eq 'backup' && $ownervm) {
485 $rpcenv->check($user, "/storage/$sid", ['Datastore.AllocateSpace']);
486 $rpcenv->check($user, "/vms/$ownervm", ['VM.Backup']);
487 } else {
488 # allow if we are Datastore administrator
489 $rpcenv->check($user, "/storage/$sid", ['Datastore.Allocate']);
490 }
491 } else {
492 die "Only root can pass arbitrary filesystem paths."
493 if $user ne 'root@pam';
494 }
495
496 return undef;
497 }
498
499 my $volume_is_base_and_used__no_lock = sub {
500 my ($scfg, $storeid, $plugin, $volname) = @_;
501
502 my ($vtype, $name, $vmid, undef, undef, $isBase, undef) =
503 $plugin->parse_volname($volname);
504
505 if ($isBase) {
506 my $vollist = $plugin->list_images($storeid, $scfg);
507 foreach my $info (@$vollist) {
508 my (undef, $tmpvolname) = parse_volume_id($info->{volid});
509 my $basename = undef;
510 my $basevmid = undef;
511
512 eval{
513 (undef, undef, undef, $basename, $basevmid) =
514 $plugin->parse_volname($tmpvolname);
515 };
516
517 if ($basename && defined($basevmid) && $basevmid == $vmid && $basename eq $name) {
518 return 1;
519 }
520 }
521 }
522 return 0;
523 };
524
525 # NOTE: this check does not work for LVM-thin, where the clone -> base
526 # reference is not encoded in the volume ID.
527 # see note in PVE::Storage::LvmThinPlugin for details.
528 sub volume_is_base_and_used {
529 my ($cfg, $volid) = @_;
530
531 my ($storeid, $volname) = parse_volume_id($volid);
532 my $scfg = storage_config($cfg, $storeid);
533 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
534
535 $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
536 return &$volume_is_base_and_used__no_lock($scfg, $storeid, $plugin, $volname);
537 });
538 }
539
540 # try to map a filesystem path to a volume identifier
541 sub path_to_volume_id {
542 my ($cfg, $path) = @_;
543
544 my $ids = $cfg->{ids};
545
546 my ($sid, $volname) = parse_volume_id($path, 1);
547 if ($sid) {
548 if (my $scfg = $ids->{$sid}) {
549 if ($scfg->{path}) {
550 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
551 my ($vtype, $name, $vmid) = $plugin->parse_volname($volname);
552 return ($vtype, $path);
553 }
554 }
555 return ('');
556 }
557
558 # Note: abs_path() return undef if $path doesn not exist
559 # for example when nfs storage is not mounted
560 $path = abs_path($path) || $path;
561
562 foreach my $sid (keys %$ids) {
563 my $scfg = $ids->{$sid};
564 next if !$scfg->{path};
565 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
566 my $imagedir = $plugin->get_subdir($scfg, 'images');
567 my $isodir = $plugin->get_subdir($scfg, 'iso');
568 my $tmpldir = $plugin->get_subdir($scfg, 'vztmpl');
569 my $backupdir = $plugin->get_subdir($scfg, 'backup');
570 my $privatedir = $plugin->get_subdir($scfg, 'rootdir');
571 my $snippetsdir = $plugin->get_subdir($scfg, 'snippets');
572
573 if ($path =~ m!^$imagedir/(\d+)/([^/\s]+)$!) {
574 my $vmid = $1;
575 my $name = $2;
576
577 my $vollist = $plugin->list_images($sid, $scfg, $vmid);
578 foreach my $info (@$vollist) {
579 my ($storeid, $volname) = parse_volume_id($info->{volid});
580 my $volpath = $plugin->path($scfg, $volname, $storeid);
581 if ($volpath eq $path) {
582 return ('images', $info->{volid});
583 }
584 }
585 } elsif ($path =~ m!^$isodir/([^/]+$iso_extension_re)$!) {
586 my $name = $1;
587 return ('iso', "$sid:iso/$name");
588 } elsif ($path =~ m!^$tmpldir/([^/]+\.tar\.gz)$!) {
589 my $name = $1;
590 return ('vztmpl', "$sid:vztmpl/$name");
591 } elsif ($path =~ m!^$privatedir/(\d+)$!) {
592 my $vmid = $1;
593 return ('rootdir', "$sid:rootdir/$vmid");
594 } elsif ($path =~ m!^$backupdir/([^/]+\.(?:tgz|(?:(?:tar|vma)(?:\.(?:${\PVE::Storage::Plugin::COMPRESSOR_RE}))?)))$!) {
595 my $name = $1;
596 return ('backup', "$sid:backup/$name");
597 } elsif ($path =~ m!^$snippetsdir/([^/]+)$!) {
598 my $name = $1;
599 return ('snippets', "$sid:snippets/$name");
600 }
601 }
602
603 # can't map path to volume id
604 return ('');
605 }
606
607 sub path {
608 my ($cfg, $volid, $snapname) = @_;
609
610 my ($storeid, $volname) = parse_volume_id($volid);
611
612 my $scfg = storage_config($cfg, $storeid);
613
614 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
615 my ($path, $owner, $vtype) = $plugin->path($scfg, $volname, $storeid, $snapname);
616 return wantarray ? ($path, $owner, $vtype) : $path;
617 }
618
619 sub abs_filesystem_path {
620 my ($cfg, $volid) = @_;
621
622 my $path;
623 if (parse_volume_id ($volid, 1)) {
624 activate_volumes($cfg, [ $volid ]);
625 $path = PVE::Storage::path($cfg, $volid);
626 } else {
627 if (-f $volid) {
628 my $abspath = abs_path($volid);
629 if ($abspath && $abspath =~ m|^(/.+)$|) {
630 $path = $1; # untaint any path
631 }
632 }
633 }
634
635 die "can't find file '$volid'\n" if !($path && -f $path);
636
637 return $path;
638 }
639
640 my $volname_for_storage = sub {
641 my ($cfg, $volid, $target_storeid) = @_;
642
643 my (undef, $name, $vmid, undef, undef, undef, $format) = parse_volname($cfg, $volid);
644 my $target_scfg = storage_config($cfg, $target_storeid);
645
646 my (undef, $valid_formats) = PVE::Storage::Plugin::default_format($target_scfg);
647 my $format_is_valid = grep { $_ eq $format } @$valid_formats;
648 die "unsupported format '$format' for storage type $target_scfg->{type}\n" if !$format_is_valid;
649
650 (my $name_without_extension = $name) =~ s/\.$format$//;
651
652 if ($target_scfg->{path}) {
653 return "$vmid/$name_without_extension.$format";
654 } else {
655 return "$name_without_extension";
656 }
657 };
658
659 sub storage_migrate {
660 my ($cfg, $volid, $target_sshinfo, $target_storeid, $opts, $logfunc) = @_;
661
662 my $base_snapshot = $opts->{base_snapshot};
663 my $snapshot = $opts->{snapshot};
664 my $ratelimit_bps = $opts->{ratelimit_bps};
665 my $insecure = $opts->{insecure};
666 my $with_snapshots = $opts->{with_snapshots} ? 1 : 0;
667 my $allow_rename = $opts->{allow_rename} ? 1 : 0;
668
669 my ($storeid, $volname) = parse_volume_id($volid);
670
671 my $scfg = storage_config($cfg, $storeid);
672
673 # no need to migrate shared content
674 return $volid if $storeid eq $target_storeid && $scfg->{shared};
675
676 my $tcfg = storage_config($cfg, $target_storeid);
677
678 my $target_volname;
679 if ($opts->{target_volname}) {
680 $target_volname = $opts->{target_volname};
681 } elsif ($scfg->{type} eq $tcfg->{type}) {
682 $target_volname = $volname;
683 } else {
684 $target_volname = $volname_for_storage->($cfg, $volid, $target_storeid);
685 }
686
687 my $target_volid = "${target_storeid}:${target_volname}";
688
689 my $target_ip = $target_sshinfo->{ip};
690
691 my $ssh = PVE::SSHInfo::ssh_info_to_command($target_sshinfo);
692 my $ssh_base = PVE::SSHInfo::ssh_info_to_command_base($target_sshinfo);
693 local $ENV{RSYNC_RSH} = PVE::Tools::cmd2string($ssh_base);
694
695 my @cstream;
696 if (defined($ratelimit_bps)) {
697 @cstream = ([ '/usr/bin/cstream', '-t', $ratelimit_bps ]);
698 $logfunc->("using a bandwidth limit of $ratelimit_bps bps for transferring '$volid'") if $logfunc;
699 }
700
701 my $migration_snapshot;
702 if (!defined($snapshot)) {
703 if ($scfg->{type} eq 'zfspool') {
704 $migration_snapshot = 1;
705 $snapshot = '__migration__';
706 }
707 }
708
709 my @formats = volume_transfer_formats($cfg, $volid, $target_volid, $snapshot, $base_snapshot, $with_snapshots);
710 die "cannot migrate from storage type '$scfg->{type}' to '$tcfg->{type}'\n" if !@formats;
711 my $format = $formats[0];
712
713 my $import_fn = '-'; # let pvesm import read from stdin per default
714 if ($insecure) {
715 my $net = $target_sshinfo->{network} // $target_sshinfo->{ip};
716 $import_fn = "tcp://$net";
717 }
718
719 my $target_apiver = 1; # if there is no apiinfo call, assume 1
720 my $get_api_version = [@$ssh, 'pvesm', 'apiinfo'];
721 my $match_api_version = sub { $target_apiver = $1 if $_[0] =~ m!^APIVER (\d+)$!; };
722 eval { run_command($get_api_version, logfunc => $match_api_version); };
723
724 my $send = ['pvesm', 'export', $volid, $format, '-', '-with-snapshots', $with_snapshots];
725 my $recv = [@$ssh, '--', 'pvesm', 'import', $target_volid, $format, $import_fn, '-with-snapshots', $with_snapshots];
726 if (defined($snapshot)) {
727 push @$send, '-snapshot', $snapshot
728 }
729 if ($migration_snapshot) {
730 push @$recv, '-delete-snapshot', $snapshot;
731 }
732 push @$recv, '-allow-rename', $allow_rename if $target_apiver >= 5;
733
734 if (defined($base_snapshot)) {
735 # Check if the snapshot exists on the remote side:
736 push @$send, '-base', $base_snapshot;
737 push @$recv, '-base', $base_snapshot;
738 }
739
740 my $new_volid;
741 my $pattern = volume_imported_message(undef, 1);
742 my $match_volid_and_log = sub {
743 my $line = shift;
744
745 $new_volid = $1 if ($line =~ $pattern);
746
747 if ($logfunc) {
748 chomp($line);
749 $logfunc->($line);
750 }
751 };
752
753 volume_snapshot($cfg, $volid, $snapshot) if $migration_snapshot;
754
755 if (defined($snapshot)) {
756 activate_volumes($cfg, [$volid], $snapshot);
757 } else {
758 activate_volumes($cfg, [$volid]);
759 }
760
761 eval {
762 if ($insecure) {
763 my $input = IO::File->new();
764 my $info = IO::File->new();
765 open3($input, $info, $info, @{$recv})
766 or die "receive command failed: $!\n";
767 close($input);
768
769 my ($ip) = <$info> =~ /^($PVE::Tools::IPRE)$/ or die "no tunnel IP received\n";
770 my ($port) = <$info> =~ /^(\d+)$/ or die "no tunnel port received\n";
771 my $socket = IO::Socket::IP->new(PeerHost => $ip, PeerPort => $port, Type => SOCK_STREAM)
772 or die "failed to connect to tunnel at $ip:$port\n";
773 # we won't be reading from the socket
774 shutdown($socket, 0);
775
776 eval { run_command([$send, @cstream], output => '>&'.fileno($socket), errfunc => $logfunc); };
777 my $send_error = $@;
778
779 # don't close the connection entirely otherwise the receiving end
780 # might not get all buffered data (and fails with 'connection reset by peer')
781 shutdown($socket, 1);
782
783 # wait for the remote process to finish
784 while (my $line = <$info>) {
785 $match_volid_and_log->("[$target_sshinfo->{name}] $line");
786 }
787
788 # now close the socket
789 close($socket);
790 if (!close($info)) { # does waitpid()
791 die "import failed: $!\n" if $!;
792 die "import failed: exit code ".($?>>8)."\n";
793 }
794
795 die $send_error if $send_error;
796 } else {
797 run_command([$send, @cstream, $recv], logfunc => $match_volid_and_log);
798 }
799
800 die "unable to get ID of the migrated volume\n"
801 if !defined($new_volid) && $target_apiver >= 5;
802 };
803 my $err = $@;
804 warn "send/receive failed, cleaning up snapshot(s)..\n" if $err;
805 if ($migration_snapshot) {
806 eval { volume_snapshot_delete($cfg, $volid, $snapshot, 0) };
807 warn "could not remove source snapshot: $@\n" if $@;
808 }
809 die $err if $err;
810
811 return $new_volid // $target_volid;
812 }
813
814 sub vdisk_clone {
815 my ($cfg, $volid, $vmid, $snap) = @_;
816
817 my ($storeid, $volname) = parse_volume_id($volid);
818
819 my $scfg = storage_config($cfg, $storeid);
820
821 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
822
823 activate_storage($cfg, $storeid);
824
825 # lock shared storage
826 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
827 my $volname = $plugin->clone_image($scfg, $storeid, $volname, $vmid, $snap);
828 return "$storeid:$volname";
829 });
830 }
831
832 sub vdisk_create_base {
833 my ($cfg, $volid) = @_;
834
835 my ($storeid, $volname) = parse_volume_id($volid);
836
837 my $scfg = storage_config($cfg, $storeid);
838
839 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
840
841 activate_storage($cfg, $storeid);
842
843 # lock shared storage
844 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
845 my $volname = $plugin->create_base($storeid, $scfg, $volname);
846 return "$storeid:$volname";
847 });
848 }
849
850 sub map_volume {
851 my ($cfg, $volid, $snapname) = @_;
852
853 my ($storeid, $volname) = parse_volume_id($volid);
854
855 my $scfg = storage_config($cfg, $storeid);
856
857 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
858
859 return $plugin->map_volume($storeid, $scfg, $volname, $snapname);
860 }
861
862 sub unmap_volume {
863 my ($cfg, $volid, $snapname) = @_;
864
865 my ($storeid, $volname) = parse_volume_id($volid);
866
867 my $scfg = storage_config($cfg, $storeid);
868
869 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
870
871 return $plugin->unmap_volume($storeid, $scfg, $volname, $snapname);
872 }
873
874 sub vdisk_alloc {
875 my ($cfg, $storeid, $vmid, $fmt, $name, $size) = @_;
876
877 die "no storage ID specified\n" if !$storeid;
878
879 PVE::JSONSchema::parse_storage_id($storeid);
880
881 my $scfg = storage_config($cfg, $storeid);
882
883 die "no VMID specified\n" if !$vmid;
884
885 $vmid = parse_vmid($vmid);
886
887 my $defformat = PVE::Storage::Plugin::default_format($scfg);
888
889 $fmt = $defformat if !$fmt;
890
891 activate_storage($cfg, $storeid);
892
893 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
894
895 # lock shared storage
896 return $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
897 my $old_umask = umask(umask|0037);
898 my $volname = eval { $plugin->alloc_image($storeid, $scfg, $vmid, $fmt, $name, $size) };
899 my $err = $@;
900 umask $old_umask;
901 die $err if $err;
902 return "$storeid:$volname";
903 });
904 }
905
906 sub vdisk_free {
907 my ($cfg, $volid) = @_;
908
909 my ($storeid, $volname) = parse_volume_id($volid);
910 my $scfg = storage_config($cfg, $storeid);
911 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
912
913 activate_storage($cfg, $storeid);
914
915 my $cleanup_worker;
916
917 # lock shared storage
918 $plugin->cluster_lock_storage($storeid, $scfg->{shared}, undef, sub {
919 # LVM-thin allows deletion of still referenced base volumes!
920 die "base volume '$volname' is still in use by linked clones\n"
921 if &$volume_is_base_and_used__no_lock($scfg, $storeid, $plugin, $volname);
922
923 my (undef, undef, undef, undef, undef, $isBase, $format) =
924 $plugin->parse_volname($volname);
925 $cleanup_worker = $plugin->free_image($storeid, $scfg, $volname, $isBase, $format);
926 });
927
928 return if !$cleanup_worker;
929
930 my $rpcenv = PVE::RPCEnvironment::get();
931 my $authuser = $rpcenv->get_user();
932
933 $rpcenv->fork_worker('imgdel', undef, $authuser, $cleanup_worker);
934 }
935
936 sub vdisk_list {
937 my ($cfg, $storeid, $vmid, $vollist) = @_;
938
939 my $ids = $cfg->{ids};
940
941 storage_check_enabled($cfg, $storeid) if ($storeid);
942
943 my $res = {};
944
945 # prepare/activate/refresh all storages
946
947 my $storage_list = [];
948 if ($vollist) {
949 foreach my $volid (@$vollist) {
950 my ($sid, undef) = parse_volume_id($volid);
951 next if !defined($ids->{$sid});
952 next if !storage_check_enabled($cfg, $sid, undef, 1);
953 push @$storage_list, $sid;
954 }
955 } else {
956 foreach my $sid (keys %$ids) {
957 next if $storeid && $storeid ne $sid;
958 next if !storage_check_enabled($cfg, $sid, undef, 1);
959 my $content = $ids->{$sid}->{content};
960 next if !($content->{rootdir} || $content->{images});
961 push @$storage_list, $sid;
962 }
963 }
964
965 my $cache = {};
966
967 activate_storage_list($cfg, $storage_list, $cache);
968
969 foreach my $sid (keys %$ids) {
970 next if $storeid && $storeid ne $sid;
971 next if !storage_check_enabled($cfg, $sid, undef, 1);
972
973 my $scfg = $ids->{$sid};
974 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
975 $res->{$sid} = $plugin->list_images($sid, $scfg, $vmid, $vollist, $cache);
976 @{$res->{$sid}} = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @{$res->{$sid}} if $res->{$sid};
977 }
978
979 return $res;
980 }
981
982 sub template_list {
983 my ($cfg, $storeid, $tt) = @_;
984
985 die "unknown template type '$tt'\n"
986 if !($tt eq 'iso' || $tt eq 'vztmpl' || $tt eq 'backup' || $tt eq 'snippets');
987
988 my $ids = $cfg->{ids};
989
990 storage_check_enabled($cfg, $storeid) if ($storeid);
991
992 my $res = {};
993
994 # query the storage
995 foreach my $sid (keys %$ids) {
996 next if $storeid && $storeid ne $sid;
997
998 my $scfg = $ids->{$sid};
999 my $type = $scfg->{type};
1000
1001 next if !$scfg->{content}->{$tt};
1002
1003 next if !storage_check_enabled($cfg, $sid, undef, 1);
1004
1005 $res->{$sid} = volume_list($cfg, $sid, undef, $tt);
1006 }
1007
1008 return $res;
1009 }
1010
1011 sub volume_list {
1012 my ($cfg, $storeid, $vmid, $content) = @_;
1013
1014 my @ctypes = qw(rootdir images vztmpl iso backup snippets);
1015
1016 my $cts = $content ? [ $content ] : [ @ctypes ];
1017
1018 my $scfg = PVE::Storage::storage_config($cfg, $storeid);
1019
1020 $cts = [ grep { defined($scfg->{content}->{$_}) } @$cts ];
1021
1022 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1023
1024 activate_storage($cfg, $storeid);
1025
1026 my $res = $plugin->list_volumes($storeid, $scfg, $vmid, $cts);
1027
1028 @$res = sort {lc($a->{volid}) cmp lc ($b->{volid}) } @$res;
1029
1030 return $res;
1031 }
1032
1033 sub uevent_seqnum {
1034
1035 my $filename = "/sys/kernel/uevent_seqnum";
1036
1037 my $seqnum = 0;
1038 if (my $fh = IO::File->new($filename, "r")) {
1039 my $line = <$fh>;
1040 if ($line =~ m/^(\d+)$/) {
1041 $seqnum = int($1);
1042 }
1043 close ($fh);
1044 }
1045 return $seqnum;
1046 }
1047
1048 sub activate_storage {
1049 my ($cfg, $storeid, $cache) = @_;
1050
1051 $cache = {} if !$cache;
1052
1053 my $scfg = storage_check_enabled($cfg, $storeid);
1054
1055 return if $cache->{activated}->{$storeid};
1056
1057 $cache->{uevent_seqnum} = uevent_seqnum() if !$cache->{uevent_seqnum};
1058
1059 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1060
1061 if ($scfg->{base}) {
1062 my ($baseid, undef) = parse_volume_id ($scfg->{base});
1063 activate_storage($cfg, $baseid, $cache);
1064 }
1065
1066 if (!$plugin->check_connection($storeid, $scfg)) {
1067 die "storage '$storeid' is not online\n";
1068 }
1069
1070 $plugin->activate_storage($storeid, $scfg, $cache);
1071
1072 my $newseq = uevent_seqnum ();
1073
1074 # only call udevsettle if there are events
1075 if ($newseq > $cache->{uevent_seqnum}) {
1076 system ("udevadm settle --timeout=30"); # ignore errors
1077 $cache->{uevent_seqnum} = $newseq;
1078 }
1079
1080 $cache->{activated}->{$storeid} = 1;
1081 }
1082
1083 sub activate_storage_list {
1084 my ($cfg, $storeid_list, $cache) = @_;
1085
1086 $cache = {} if !$cache;
1087
1088 foreach my $storeid (@$storeid_list) {
1089 activate_storage($cfg, $storeid, $cache);
1090 }
1091 }
1092
1093 sub deactivate_storage {
1094 my ($cfg, $storeid) = @_;
1095
1096 my $scfg = storage_config ($cfg, $storeid);
1097 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1098
1099 my $cache = {};
1100 $plugin->deactivate_storage($storeid, $scfg, $cache);
1101 }
1102
1103 sub activate_volumes {
1104 my ($cfg, $vollist, $snapname) = @_;
1105
1106 return if !($vollist && scalar(@$vollist));
1107
1108 my $storagehash = {};
1109 foreach my $volid (@$vollist) {
1110 my ($storeid, undef) = parse_volume_id($volid);
1111 $storagehash->{$storeid} = 1;
1112 }
1113
1114 my $cache = {};
1115
1116 activate_storage_list($cfg, [keys %$storagehash], $cache);
1117
1118 foreach my $volid (@$vollist) {
1119 my ($storeid, $volname) = parse_volume_id($volid);
1120 my $scfg = storage_config($cfg, $storeid);
1121 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1122 $plugin->activate_volume($storeid, $scfg, $volname, $snapname, $cache);
1123 }
1124 }
1125
1126 sub deactivate_volumes {
1127 my ($cfg, $vollist, $snapname) = @_;
1128
1129 return if !($vollist && scalar(@$vollist));
1130
1131 my $cache = {};
1132
1133 my @errlist = ();
1134 foreach my $volid (@$vollist) {
1135 my ($storeid, $volname) = parse_volume_id($volid);
1136
1137 my $scfg = storage_config($cfg, $storeid);
1138 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1139
1140 eval {
1141 $plugin->deactivate_volume($storeid, $scfg, $volname, $snapname, $cache);
1142 };
1143 if (my $err = $@) {
1144 warn $err;
1145 push @errlist, $volid;
1146 }
1147 }
1148
1149 die "volume deactivation failed: " . join(' ', @errlist)
1150 if scalar(@errlist);
1151 }
1152
1153 sub storage_info {
1154 my ($cfg, $content, $includeformat) = @_;
1155
1156 my $ids = $cfg->{ids};
1157
1158 my $info = {};
1159
1160 my @ctypes = PVE::Tools::split_list($content);
1161
1162 my $slist = [];
1163 foreach my $storeid (keys %$ids) {
1164 my $storage_enabled = defined(storage_check_enabled($cfg, $storeid, undef, 1));
1165
1166 if (defined($content)) {
1167 my $want_ctype = 0;
1168 foreach my $ctype (@ctypes) {
1169 if ($ids->{$storeid}->{content}->{$ctype}) {
1170 $want_ctype = 1;
1171 last;
1172 }
1173 }
1174 next if !$want_ctype || !$storage_enabled;
1175 }
1176
1177 my $type = $ids->{$storeid}->{type};
1178
1179 $info->{$storeid} = {
1180 type => $type,
1181 total => 0,
1182 avail => 0,
1183 used => 0,
1184 shared => $ids->{$storeid}->{shared} ? 1 : 0,
1185 content => PVE::Storage::Plugin::content_hash_to_string($ids->{$storeid}->{content}),
1186 active => 0,
1187 enabled => $storage_enabled ? 1 : 0,
1188 };
1189
1190 push @$slist, $storeid;
1191 }
1192
1193 my $cache = {};
1194
1195 foreach my $storeid (keys %$ids) {
1196 my $scfg = $ids->{$storeid};
1197
1198 next if !$info->{$storeid};
1199 next if !$info->{$storeid}->{enabled};
1200
1201 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1202 if ($includeformat) {
1203 my $pd = $plugin->plugindata();
1204 $info->{$storeid}->{format} = $pd->{format}
1205 if $pd->{format};
1206 $info->{$storeid}->{select_existing} = $pd->{select_existing}
1207 if $pd->{select_existing};
1208 }
1209
1210 eval { activate_storage($cfg, $storeid, $cache); };
1211 if (my $err = $@) {
1212 warn $err;
1213 next;
1214 }
1215
1216 my ($total, $avail, $used, $active) = eval { $plugin->status($storeid, $scfg, $cache); };
1217 warn $@ if $@;
1218 next if !$active;
1219 $info->{$storeid}->{total} = int($total);
1220 $info->{$storeid}->{avail} = int($avail);
1221 $info->{$storeid}->{used} = int($used);
1222 $info->{$storeid}->{active} = $active;
1223 }
1224
1225 return $info;
1226 }
1227
1228 sub resolv_server {
1229 my ($server) = @_;
1230
1231 my ($packed_ip, $family);
1232 eval {
1233 my @res = PVE::Tools::getaddrinfo_all($server);
1234 $family = $res[0]->{family};
1235 $packed_ip = (PVE::Tools::unpack_sockaddr_in46($res[0]->{addr}))[2];
1236 };
1237 if (defined $packed_ip) {
1238 return Socket::inet_ntop($family, $packed_ip);
1239 }
1240 return undef;
1241 }
1242
1243 sub scan_nfs {
1244 my ($server_in) = @_;
1245
1246 my $server;
1247 if (!($server = resolv_server ($server_in))) {
1248 die "unable to resolve address for server '${server_in}'\n";
1249 }
1250
1251 my $cmd = ['/sbin/showmount', '--no-headers', '--exports', $server];
1252
1253 my $res = {};
1254 run_command($cmd, outfunc => sub {
1255 my $line = shift;
1256
1257 # note: howto handle white spaces in export path??
1258 if ($line =~ m!^(/\S+)\s+(.+)$!) {
1259 $res->{$1} = $2;
1260 }
1261 });
1262
1263 return $res;
1264 }
1265
1266 sub scan_cifs {
1267 my ($server_in, $user, $password, $domain) = @_;
1268
1269 my $server = resolv_server($server_in);
1270 die "unable to resolve address for server '${server_in}'\n" if !$server;
1271
1272 # we only support Windows 2012 and newer, so just use smb3
1273 my $cmd = ['/usr/bin/smbclient', '-m', 'smb3', '-d', '0', '-L', $server];
1274 push @$cmd, '-W', $domain if defined($domain);
1275
1276 push @$cmd, '-N' if !defined($password);
1277 local $ENV{USER} = $user if defined($user);
1278 local $ENV{PASSWD} = $password if defined($password);
1279
1280 my $res = {};
1281 my $err = '';
1282 run_command($cmd,
1283 noerr => 1,
1284 errfunc => sub {
1285 $err .= "$_[0]\n"
1286 },
1287 outfunc => sub {
1288 my $line = shift;
1289 if ($line =~ m/(\S+)\s*Disk\s*(\S*)/) {
1290 $res->{$1} = $2;
1291 } elsif ($line =~ m/(NT_STATUS_(\S+))/) {
1292 my $status = $1;
1293 $err .= "unexpected status: $1\n" if uc($1) ne 'SUCCESS';
1294 }
1295 },
1296 );
1297 # only die if we got no share, else it's just some followup check error
1298 # (like workgroup querying)
1299 raise($err) if $err && !%$res;
1300
1301 return $res;
1302 }
1303
1304 sub scan_zfs {
1305
1306 my $cmd = ['zfs', 'list', '-t', 'filesystem', '-Hp', '-o', 'name,avail,used'];
1307
1308 my $res = [];
1309 run_command($cmd, outfunc => sub {
1310 my $line = shift;
1311
1312 if ($line =~m/^(\S+)\s+(\S+)\s+(\S+)$/) {
1313 my ($pool, $size_str, $used_str) = ($1, $2, $3);
1314 my $size = $size_str + 0;
1315 my $used = $used_str + 0;
1316 # ignore subvolumes generated by our ZFSPoolPlugin
1317 return if $pool =~ m!/subvol-\d+-[^/]+$!;
1318 return if $pool =~ m!/basevol-\d+-[^/]+$!;
1319 push @$res, { pool => $pool, size => $size, free => $size-$used };
1320 }
1321 });
1322
1323 return $res;
1324 }
1325
1326 sub resolv_portal {
1327 my ($portal, $noerr) = @_;
1328
1329 my ($server, $port) = PVE::Tools::parse_host_and_port($portal);
1330 if ($server) {
1331 if (my $ip = resolv_server($server)) {
1332 $server = $ip;
1333 $server = "[$server]" if $server =~ /^$IPV6RE$/;
1334 return $port ? "$server:$port" : $server;
1335 }
1336 }
1337 return undef if $noerr;
1338
1339 raise_param_exc({ portal => "unable to resolve portal address '$portal'" });
1340 }
1341
1342
1343 sub scan_iscsi {
1344 my ($portal_in) = @_;
1345
1346 my $portal;
1347 if (!($portal = resolv_portal($portal_in))) {
1348 die "unable to parse/resolve portal address '${portal_in}'\n";
1349 }
1350
1351 return PVE::Storage::ISCSIPlugin::iscsi_discovery($portal);
1352 }
1353
1354 sub storage_default_format {
1355 my ($cfg, $storeid) = @_;
1356
1357 my $scfg = storage_config ($cfg, $storeid);
1358
1359 return PVE::Storage::Plugin::default_format($scfg);
1360 }
1361
1362 sub vgroup_is_used {
1363 my ($cfg, $vgname) = @_;
1364
1365 foreach my $storeid (keys %{$cfg->{ids}}) {
1366 my $scfg = storage_config($cfg, $storeid);
1367 if ($scfg->{type} eq 'lvm' && $scfg->{vgname} eq $vgname) {
1368 return 1;
1369 }
1370 }
1371
1372 return undef;
1373 }
1374
1375 sub target_is_used {
1376 my ($cfg, $target) = @_;
1377
1378 foreach my $storeid (keys %{$cfg->{ids}}) {
1379 my $scfg = storage_config($cfg, $storeid);
1380 if ($scfg->{type} eq 'iscsi' && $scfg->{target} eq $target) {
1381 return 1;
1382 }
1383 }
1384
1385 return undef;
1386 }
1387
1388 sub volume_is_used {
1389 my ($cfg, $volid) = @_;
1390
1391 foreach my $storeid (keys %{$cfg->{ids}}) {
1392 my $scfg = storage_config($cfg, $storeid);
1393 if ($scfg->{base} && $scfg->{base} eq $volid) {
1394 return 1;
1395 }
1396 }
1397
1398 return undef;
1399 }
1400
1401 sub storage_is_used {
1402 my ($cfg, $storeid) = @_;
1403
1404 foreach my $sid (keys %{$cfg->{ids}}) {
1405 my $scfg = storage_config($cfg, $sid);
1406 next if !$scfg->{base};
1407 my ($st) = parse_volume_id($scfg->{base});
1408 return 1 if $st && $st eq $storeid;
1409 }
1410
1411 return undef;
1412 }
1413
1414 sub foreach_volid {
1415 my ($list, $func) = @_;
1416
1417 return if !$list;
1418
1419 foreach my $sid (keys %$list) {
1420 foreach my $info (@{$list->{$sid}}) {
1421 my $volid = $info->{volid};
1422 my ($sid1, $volname) = parse_volume_id($volid, 1);
1423 if ($sid1 && $sid1 eq $sid) {
1424 &$func ($volid, $sid, $info);
1425 } else {
1426 warn "detected strange volid '$volid' in volume list for '$sid'\n";
1427 }
1428 }
1429 }
1430 }
1431
1432 sub decompressor_info {
1433 my ($format, $comp) = @_;
1434
1435 if ($format eq 'tgz' && !defined($comp)) {
1436 ($format, $comp) = ('tar', 'gz');
1437 }
1438
1439 my $decompressor = {
1440 tar => {
1441 gz => ['tar', '-z'],
1442 lzo => ['tar', '--lzop'],
1443 zst => ['tar', '--zstd'],
1444 },
1445 vma => {
1446 gz => ['zcat'],
1447 lzo => ['lzop', '-d', '-c'],
1448 zst => ['zstd', '-q', '-d', '-c'],
1449 },
1450 };
1451
1452 die "ERROR: archive format not defined\n"
1453 if !defined($decompressor->{$format});
1454
1455 my $decomp;
1456 $decomp = $decompressor->{$format}->{$comp} if $comp;
1457
1458 my $info = {
1459 format => $format,
1460 compression => $comp,
1461 decompressor => $decomp,
1462 };
1463
1464 return $info;
1465 }
1466
1467 sub archive_info {
1468 my ($archive) = shift;
1469 my $info;
1470
1471 my $volid = basename($archive);
1472 if ($volid =~ /^(vzdump-(lxc|openvz|qemu)-.+\.(tgz$|tar|vma)(?:\.(${\PVE::Storage::Plugin::COMPRESSOR_RE}))?)$/) {
1473 my $filename = "$1"; # untaint
1474 my ($type, $format, $comp) = ($2, $3, $4);
1475 my $format_re = defined($comp) ? "$format.$comp" : "$format";
1476 $info = decompressor_info($format, $comp);
1477 $info->{filename} = $filename;
1478 $info->{type} = $type;
1479
1480 if ($volid =~ /^(vzdump-${type}-([1-9][0-9]{2,8})-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2}))\.${format_re}$/) {
1481 $info->{logfilename} = "$1.log";
1482 $info->{vmid} = int($2);
1483 $info->{ctime} = timelocal($8, $7, $6, $5, $4 - 1, $3);
1484 $info->{is_std_name} = 1;
1485 } else {
1486 $info->{is_std_name} = 0;
1487 }
1488 } else {
1489 die "ERROR: couldn't determine archive info from '$archive'\n";
1490 }
1491
1492 return $info;
1493 }
1494
1495 sub archive_remove {
1496 my ($archive_path) = @_;
1497
1498 my $dirname = dirname($archive_path);
1499 my $archive_info = eval { archive_info($archive_path) } // {};
1500 my $logfn = $archive_info->{logfilename};
1501
1502 unlink $archive_path or die "removing archive $archive_path failed: $!\n";
1503
1504 if (defined($logfn)) {
1505 my $logpath = "$dirname/$logfn";
1506 if (-e $logpath) {
1507 unlink $logpath or warn "removing log file $logpath failed: $!\n";
1508 }
1509 }
1510 }
1511
1512 sub extract_vzdump_config_tar {
1513 my ($archive, $conf_re) = @_;
1514
1515 die "ERROR: file '$archive' does not exist\n" if ! -f $archive;
1516
1517 my $pid = open(my $fh, '-|', 'tar', 'tf', $archive) ||
1518 die "unable to open file '$archive'\n";
1519
1520 my $file;
1521 while (defined($file = <$fh>)) {
1522 if ($file =~ $conf_re) {
1523 $file = $1; # untaint
1524 last;
1525 }
1526 }
1527
1528 kill 15, $pid;
1529 waitpid $pid, 0;
1530 close $fh;
1531
1532 die "ERROR: archive contains no configuration file\n" if !$file;
1533 chomp $file;
1534
1535 my $raw = '';
1536 my $out = sub {
1537 my $output = shift;
1538 $raw .= "$output\n";
1539 };
1540
1541 run_command(['tar', '-xpOf', $archive, $file, '--occurrence'], outfunc => $out);
1542
1543 return wantarray ? ($raw, $file) : $raw;
1544 }
1545
1546 sub extract_vzdump_config_vma {
1547 my ($archive, $comp) = @_;
1548
1549 my $raw = '';
1550 my $out = sub { $raw .= "$_[0]\n"; };
1551
1552 my $info = archive_info($archive);
1553 $comp //= $info->{compression};
1554 my $decompressor = $info->{decompressor};
1555
1556 if ($comp) {
1557 my $cmd = [ [@$decompressor, $archive], ["vma", "config", "-"] ];
1558
1559 # lzop/zcat exits with 1 when the pipe is closed early by vma, detect this and ignore the exit code later
1560 my $broken_pipe;
1561 my $errstring;
1562 my $err = sub {
1563 my $output = shift;
1564 if ($output =~ m/lzop: Broken pipe: <stdout>/ || $output =~ m/gzip: stdout: Broken pipe/ || $output =~ m/zstd: error 70 : Write error : Broken pipe/) {
1565 $broken_pipe = 1;
1566 } elsif (!defined ($errstring) && $output !~ m/^\s*$/) {
1567 $errstring = "Failed to extract config from VMA archive: $output\n";
1568 }
1569 };
1570
1571 my $rc = eval { run_command($cmd, outfunc => $out, errfunc => $err, noerr => 1) };
1572 my $rerr = $@;
1573
1574 $broken_pipe ||= $rc == 141; # broken pipe from vma POV
1575
1576 if (!$errstring && !$broken_pipe && $rc != 0) {
1577 die "$rerr\n" if $rerr;
1578 die "config extraction failed with exit code $rc\n";
1579 }
1580 die "$errstring\n" if $errstring;
1581 } else {
1582 run_command(["vma", "config", $archive], outfunc => $out);
1583 }
1584
1585 return wantarray ? ($raw, undef) : $raw;
1586 }
1587
1588 sub extract_vzdump_config {
1589 my ($cfg, $volid) = @_;
1590
1591 my ($storeid, $volname) = parse_volume_id($volid);
1592 if (defined($storeid)) {
1593 my $scfg = storage_config($cfg, $storeid);
1594 if ($scfg->{type} eq 'pbs') {
1595 storage_check_enabled($cfg, $storeid);
1596 return PVE::Storage::PBSPlugin->extract_vzdump_config($scfg, $volname, $storeid);
1597 }
1598 }
1599
1600 my $archive = abs_filesystem_path($cfg, $volid);
1601 my $info = archive_info($archive);
1602 my $format = $info->{format};
1603 my $comp = $info->{compression};
1604 my $type = $info->{type};
1605
1606 if ($type eq 'lxc' || $type eq 'openvz') {
1607 return extract_vzdump_config_tar($archive, qr!^(\./etc/vzdump/(pct|vps)\.conf)$!);
1608 } elsif ($type eq 'qemu') {
1609 if ($format eq 'tar') {
1610 return extract_vzdump_config_tar($archive, qr!\(\./qemu-server\.conf\)!);
1611 } else {
1612 return extract_vzdump_config_vma($archive, $comp);
1613 }
1614 } else {
1615 die "cannot determine backup guest type for backup archive '$volid'\n";
1616 }
1617 }
1618
1619 sub prune_backups {
1620 my ($cfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
1621
1622 my $scfg = storage_config($cfg, $storeid);
1623 die "storage '$storeid' does not support backups\n" if !$scfg->{content}->{backup};
1624
1625 if (!defined($keep)) {
1626 die "no prune-backups options configured for storage '$storeid'\n"
1627 if !defined($scfg->{'prune-backups'});
1628 $keep = PVE::JSONSchema::parse_property_string('prune-backups', $scfg->{'prune-backups'});
1629 }
1630
1631 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1632 return $plugin->prune_backups($scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc);
1633 }
1634
1635 my $prune_mark = sub {
1636 my ($prune_entries, $keep_count, $id_func) = @_;
1637
1638 return if !$keep_count;
1639
1640 my $already_included = {};
1641 my $newly_included = {};
1642
1643 foreach my $prune_entry (@{$prune_entries}) {
1644 my $mark = $prune_entry->{mark};
1645 my $id = $id_func->($prune_entry->{ctime});
1646 $already_included->{$id} = 1 if defined($mark) && $mark eq 'keep';
1647 }
1648
1649 foreach my $prune_entry (@{$prune_entries}) {
1650 my $mark = $prune_entry->{mark};
1651 my $id = $id_func->($prune_entry->{ctime});
1652
1653 next if defined($mark) || $already_included->{$id};
1654
1655 if (!$newly_included->{$id}) {
1656 last if scalar(keys %{$newly_included}) >= $keep_count;
1657 $newly_included->{$id} = 1;
1658 $prune_entry->{mark} = 'keep';
1659 } else {
1660 $prune_entry->{mark} = 'remove';
1661 }
1662 }
1663 };
1664
1665 sub prune_mark_backup_group {
1666 my ($backup_group, $keep) = @_;
1667
1668 my $keep_all = delete $keep->{'keep-all'};
1669
1670 if ($keep_all || !scalar(grep {$_ > 0} values %{$keep})) {
1671 $keep = { 'keep-all' => 1 } if $keep_all;
1672 foreach my $prune_entry (@{$backup_group}) {
1673 $prune_entry->{mark} = 'keep';
1674 }
1675 return;
1676 }
1677
1678 my $prune_list = [ sort { $b->{ctime} <=> $a->{ctime} } @{$backup_group} ];
1679
1680 $prune_mark->($prune_list, $keep->{'keep-last'}, sub {
1681 my ($ctime) = @_;
1682 return $ctime;
1683 });
1684 $prune_mark->($prune_list, $keep->{'keep-hourly'}, sub {
1685 my ($ctime) = @_;
1686 my (undef, undef, $hour, $day, $month, $year) = localtime($ctime);
1687 return "$hour/$day/$month/$year";
1688 });
1689 $prune_mark->($prune_list, $keep->{'keep-daily'}, sub {
1690 my ($ctime) = @_;
1691 my (undef, undef, undef, $day, $month, $year) = localtime($ctime);
1692 return "$day/$month/$year";
1693 });
1694 $prune_mark->($prune_list, $keep->{'keep-weekly'}, sub {
1695 my ($ctime) = @_;
1696 my ($sec, $min, $hour, $day, $month, $year) = localtime($ctime);
1697 my $iso_week = int(strftime("%V", $sec, $min, $hour, $day, $month, $year));
1698 my $iso_week_year = int(strftime("%G", $sec, $min, $hour, $day, $month, $year));
1699 return "$iso_week/$iso_week_year";
1700 });
1701 $prune_mark->($prune_list, $keep->{'keep-monthly'}, sub {
1702 my ($ctime) = @_;
1703 my (undef, undef, undef, undef, $month, $year) = localtime($ctime);
1704 return "$month/$year";
1705 });
1706 $prune_mark->($prune_list, $keep->{'keep-yearly'}, sub {
1707 my ($ctime) = @_;
1708 my $year = (localtime($ctime))[5];
1709 return "$year";
1710 });
1711
1712 foreach my $prune_entry (@{$prune_list}) {
1713 $prune_entry->{mark} //= 'remove';
1714 }
1715 }
1716
1717 sub volume_export {
1718 my ($cfg, $fh, $volid, $format, $snapshot, $base_snapshot, $with_snapshots) = @_;
1719
1720 my ($storeid, $volname) = parse_volume_id($volid, 1);
1721 die "cannot export volume '$volid'\n" if !$storeid;
1722 my $scfg = storage_config($cfg, $storeid);
1723 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1724 return $plugin->volume_export($scfg, $storeid, $fh, $volname, $format,
1725 $snapshot, $base_snapshot, $with_snapshots);
1726 }
1727
1728 sub volume_import {
1729 my ($cfg, $fh, $volid, $format, $base_snapshot, $with_snapshots, $allow_rename) = @_;
1730
1731 my ($storeid, $volname) = parse_volume_id($volid, 1);
1732 die "cannot import into volume '$volid'\n" if !$storeid;
1733 my $scfg = storage_config($cfg, $storeid);
1734 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1735 return $plugin->volume_import($scfg, $storeid, $fh, $volname, $format,
1736 $base_snapshot, $with_snapshots, $allow_rename) // $volid;
1737 }
1738
1739 sub volume_export_formats {
1740 my ($cfg, $volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1741
1742 my ($storeid, $volname) = parse_volume_id($volid, 1);
1743 return if !$storeid;
1744 my $scfg = storage_config($cfg, $storeid);
1745 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1746 return $plugin->volume_export_formats($scfg, $storeid, $volname,
1747 $snapshot, $base_snapshot,
1748 $with_snapshots);
1749 }
1750
1751 sub volume_import_formats {
1752 my ($cfg, $volid, $base_snapshot, $with_snapshots) = @_;
1753
1754 my ($storeid, $volname) = parse_volume_id($volid, 1);
1755 return if !$storeid;
1756 my $scfg = storage_config($cfg, $storeid);
1757 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
1758 return $plugin->volume_import_formats($scfg, $storeid, $volname,
1759 $base_snapshot, $with_snapshots);
1760 }
1761
1762 sub volume_transfer_formats {
1763 my ($cfg, $src_volid, $dst_volid, $snapshot, $base_snapshot, $with_snapshots) = @_;
1764 my @export_formats = volume_export_formats($cfg, $src_volid, $snapshot, $base_snapshot, $with_snapshots);
1765 my @import_formats = volume_import_formats($cfg, $dst_volid, $base_snapshot, $with_snapshots);
1766 my %import_hash = map { $_ => 1 } @import_formats;
1767 my @common = grep { $import_hash{$_} } @export_formats;
1768 return @common;
1769 }
1770
1771 sub volume_imported_message {
1772 my ($volid, $want_pattern) = @_;
1773
1774 if ($want_pattern) {
1775 return qr/successfully imported '([^']*)'$/;
1776 } else {
1777 return "successfully imported '$volid'\n";
1778 }
1779 }
1780
1781 # bash completion helper
1782
1783 sub complete_storage {
1784 my ($cmdname, $pname, $cvalue) = @_;
1785
1786 my $cfg = PVE::Storage::config();
1787
1788 return $cmdname eq 'add' ? [] : [ PVE::Storage::storage_ids($cfg) ];
1789 }
1790
1791 sub complete_storage_enabled {
1792 my ($cmdname, $pname, $cvalue) = @_;
1793
1794 my $res = [];
1795
1796 my $cfg = PVE::Storage::config();
1797 foreach my $sid (keys %{$cfg->{ids}}) {
1798 next if !storage_check_enabled($cfg, $sid, undef, 1);
1799 push @$res, $sid;
1800 }
1801 return $res;
1802 }
1803
1804 sub complete_content_type {
1805 my ($cmdname, $pname, $cvalue) = @_;
1806
1807 return [qw(rootdir images vztmpl iso backup snippets)];
1808 }
1809
1810 sub complete_volume {
1811 my ($cmdname, $pname, $cvalue) = @_;
1812
1813 my $cfg = config();
1814
1815 my $storage_list = complete_storage_enabled();
1816
1817 if ($cvalue =~ m/^([^:]+):/) {
1818 $storage_list = [ $1 ];
1819 } else {
1820 if (scalar(@$storage_list) > 1) {
1821 # only list storage IDs to avoid large listings
1822 my $res = [];
1823 foreach my $storeid (@$storage_list) {
1824 # Hack: simply return 2 artificial values, so that
1825 # completions does not finish
1826 push @$res, "$storeid:volname", "$storeid:...";
1827 }
1828 return $res;
1829 }
1830 }
1831
1832 my $res = [];
1833 foreach my $storeid (@$storage_list) {
1834 my $vollist = PVE::Storage::volume_list($cfg, $storeid);
1835
1836 foreach my $item (@$vollist) {
1837 push @$res, $item->{volid};
1838 }
1839 }
1840
1841 return $res;
1842 }
1843
1844 # Various io-heavy operations require io/bandwidth limits which can be
1845 # configured on multiple levels: The global defaults in datacenter.cfg, and
1846 # per-storage overrides. When we want to do a restore from storage A to storage
1847 # B, we should take the smaller limit defined for storages A and B, and if no
1848 # such limit was specified, use the one from datacenter.cfg.
1849 sub get_bandwidth_limit {
1850 my ($operation, $storage_list, $override) = @_;
1851
1852 # called for each limit (global, per-storage) with the 'default' and the
1853 # $operation limit and should udpate $override for every limit affecting
1854 # us.
1855 my $use_global_limits = 0;
1856 my $apply_limit = sub {
1857 my ($bwlimit) = @_;
1858 if (defined($bwlimit)) {
1859 my $limits = PVE::JSONSchema::parse_property_string('bwlimit', $bwlimit);
1860 my $limit = $limits->{$operation} // $limits->{default};
1861 if (defined($limit)) {
1862 if (!$override || $limit < $override) {
1863 $override = $limit;
1864 }
1865 return;
1866 }
1867 }
1868 # If there was no applicable limit, try to apply the global ones.
1869 $use_global_limits = 1;
1870 };
1871
1872 my ($rpcenv, $authuser);
1873 if (defined($override)) {
1874 $rpcenv = PVE::RPCEnvironment->get();
1875 $authuser = $rpcenv->get_user();
1876 }
1877
1878 # Apply per-storage limits - if there are storages involved.
1879 if (defined($storage_list) && @$storage_list) {
1880 my $config = config();
1881
1882 # The Datastore.Allocate permission allows us to modify the per-storage
1883 # limits, therefore it also allows us to override them.
1884 # Since we have most likely multiple storages to check, do a quick check on
1885 # the general '/storage' path to see if we can skip the checks entirely:
1886 return $override if $rpcenv && $rpcenv->check($authuser, '/storage', ['Datastore.Allocate'], 1);
1887
1888 my %done;
1889 foreach my $storage (@$storage_list) {
1890 next if !defined($storage);
1891 # Avoid duplicate checks:
1892 next if $done{$storage};
1893 $done{$storage} = 1;
1894
1895 # Otherwise we may still have individual /storage/$ID permissions:
1896 if (!$rpcenv || !$rpcenv->check($authuser, "/storage/$storage", ['Datastore.Allocate'], 1)) {
1897 # And if not: apply the limits.
1898 my $storecfg = storage_config($config, $storage);
1899 $apply_limit->($storecfg->{bwlimit});
1900 }
1901 }
1902
1903 # Storage limits take precedence over the datacenter defaults, so if
1904 # a limit was applied:
1905 return $override if !$use_global_limits;
1906 }
1907
1908 # Sys.Modify on '/' means we can change datacenter.cfg which contains the
1909 # global default limits.
1910 if (!$rpcenv || !$rpcenv->check($authuser, '/', ['Sys.Modify'], 1)) {
1911 # So if we cannot modify global limits, apply them to our currently
1912 # requested override.
1913 my $dc = cfs_read_file('datacenter.cfg');
1914 $apply_limit->($dc->{bwlimit});
1915 }
1916
1917 return $override;
1918 }
1919
1920 # checks if the storage id is available and dies if not
1921 sub assert_sid_unused {
1922 my ($sid) = @_;
1923
1924 my $cfg = config();
1925 if (my $scfg = storage_config($cfg, $sid, 1)) {
1926 die "storage ID '$sid' already defined\n";
1927 }
1928
1929 return undef;
1930 }
1931
1932 1;