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