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