]> git.proxmox.com Git - pve-guest-common.git/blame - src/PVE/AbstractConfig.pm
snapshots: delete parent property if new snapshot name is already a parent to existin...
[pve-guest-common.git] / src / PVE / AbstractConfig.pm
CommitLineData
58a3c91c
FG
1package PVE::AbstractConfig;
2
3use strict;
4use warnings;
5
6use PVE::Tools qw(lock_file lock_file_full);
7use PVE::INotify;
8use PVE::Cluster;
9use PVE::Storage;
10
67b3581e 11use PVE::GuestHelpers qw(typesafe_ne);
14f17b49
DM
12use PVE::ReplicationConfig;
13use PVE::Replication;
14
58a3c91c
FG
15my $nodename = PVE::INotify::nodename();
16
17# Printable string, currently either "VM" or "CT"
18sub guest_type {
19 my ($class) = @_;
20 die "abstract method - implement me ";
21}
22
23sub __config_max_unused_disks {
24 my ($class) = @_;
25
26 die "implement me - abstract method\n";
27}
28
29# Path to the flock file for this VM/CT
30sub config_file_lock {
31 my ($class, $vmid) = @_;
32 die "abstract method - implement me";
33}
34
35# Relative config file path for this VM/CT in CFS
36sub cfs_config_path {
37 my ($class, $vmid, $node) = @_;
38 die "abstract method - implement me";
39}
40
41# Absolute config file path for this VM/CT
42sub config_file {
43 my ($class, $vmid, $node) = @_;
44
45 my $cfspath = $class->cfs_config_path($vmid, $node);
46 return "/etc/pve/$cfspath";
47}
48
49# Read and parse config file for this VM/CT
50sub load_config {
51 my ($class, $vmid, $node) = @_;
52
53 $node = $nodename if !$node;
54 my $cfspath = $class->cfs_config_path($vmid, $node);
55
56 my $conf = PVE::Cluster::cfs_read_file($cfspath);
57 die "Configuration file '$cfspath' does not exist\n"
58 if !defined($conf);
59
60 return $conf;
61}
62
63# Generate and write config file for this VM/CT
64sub write_config {
65 my ($class, $vmid, $conf) = @_;
66
67 my $cfspath = $class->cfs_config_path($vmid);
68
69 PVE::Cluster::cfs_write_file($cfspath, $conf);
70}
71
810ee088
OB
72# Pending changes related
73
74sub parse_pending_delete {
75 my ($class, $data) = @_;
7b9d1ade
TL
76
77 return {} if !$data;
78
810ee088
OB
79 $data =~ s/[,;]/ /g;
80 $data =~ s/^\s+//;
7b9d1ade
TL
81
82 my $pending_deletions = {};
83 for my $entry (split(/\s+/, $data)) {
84 my ($force, $key) = $entry =~ /^(!?)(.*)$/;
7b9d1ade
TL
85 $pending_deletions->{$key} = {
86 force => $force ? 1 : 0,
87 };
88 }
89
90 return $pending_deletions;
810ee088
OB
91}
92
93sub print_pending_delete {
94 my ($class, $delete_hash) = @_;
51088c75
TL
95
96 my $render_key = sub {
97 my $key = shift;
98 $key = "!$key" if $delete_hash->{$key}->{force};
99 return $key;
100 };
101
6a6ad855 102 join (',', map { $render_key->($_) } sort keys %$delete_hash);
810ee088
OB
103}
104
105sub add_to_pending_delete {
106 my ($class, $conf, $key, $force) = @_;
107
51e827b8
TL
108 $conf->{pending} //= {};
109 my $pending = $conf->{pending};
110 my $pending_delete_hash = $class->parse_pending_delete($pending->{delete});
111
112 $pending_delete_hash->{$key} = { force => $force };
113
114 $pending->{delete} = $class->print_pending_delete($pending_delete_hash);
115
116 return $conf;
810ee088
OB
117}
118
119sub remove_from_pending_delete {
120 my ($class, $conf, $key) = @_;
121
464a42c4
TL
122 my $pending = $conf->{pending};
123 my $pending_delete_hash = $class->parse_pending_delete($pending->{delete});
124
125 return $conf if ! exists $pending_delete_hash->{$key};
126
810ee088
OB
127 delete $pending_delete_hash->{$key};
128
129 if (%$pending_delete_hash) {
464a42c4 130 $pending->{delete} = $class->print_pending_delete($pending_delete_hash);
810ee088 131 } else {
464a42c4 132 delete $pending->{delete};
810ee088 133 }
464a42c4
TL
134
135 return $conf;
810ee088
OB
136}
137
138sub cleanup_pending {
139 my ($class, $conf) = @_;
140
c24919a9 141 my $pending = $conf->{pending};
810ee088
OB
142 # remove pending changes when nothing changed
143 my $changes;
144 foreach my $opt (keys %{$conf->{pending}}) {
145 next if $opt eq 'delete'; # just to be sure
9420142c 146 if (defined($conf->{$opt}) && ($pending->{$opt} eq $conf->{$opt})) {
810ee088 147 $changes = 1;
c24919a9 148 delete $pending->{$opt};
810ee088
OB
149 }
150 }
151
c24919a9 152 my $current_delete_hash = $class->parse_pending_delete($pending->{delete});
810ee088 153 my $pending_delete_hash = {};
c24919a9 154 for my $opt (keys %$current_delete_hash) {
810ee088 155 if (defined($conf->{$opt})) {
c24919a9 156 $pending_delete_hash->{$opt} = $current_delete_hash->{$opt};
810ee088
OB
157 } else {
158 $changes = 1;
159 }
160 }
161
162 if (%$pending_delete_hash) {
c24919a9 163 $pending->{delete} = $class->print_pending_delete($pending_delete_hash);
810ee088 164 } else {
c24919a9 165 delete $pending->{delete};
810ee088
OB
166 }
167
168 return $changes;
169}
170
866f5834
OB
171sub get_partial_fast_plug_option {
172 my ($class) = @_;
173
174 die "abstract method - implement me ";
175}
176
177sub partial_fast_plug {
178 my ($class, $conf, $opt) = @_;
179
180 my $partial_fast_plug_option = $class->get_partial_fast_plug_option();
47d7954c
TL
181 return 0 if !$partial_fast_plug_option->{$opt};
182
866f5834
OB
183 my $format = $partial_fast_plug_option->{$opt}->{fmt};
184 my $fast_pluggable = $partial_fast_plug_option->{$opt}->{properties};
185
186 my $configured = {};
187 if (exists($conf->{$opt})) {
188 $configured = PVE::JSONSchema::parse_property_string($format, $conf->{$opt});
189 }
190 my $pending = PVE::JSONSchema::parse_property_string($format, $conf->{pending}->{$opt});
191
192 my $changes = 0;
193
194 # merge configured and pending opts to iterate
195 my @all_keys = keys %{{ %$pending, %$configured }};
196
197 foreach my $subopt (@all_keys) {
198 my $type = $format->{$subopt}->{type};
67b3581e 199 if (typesafe_ne($configured->{$subopt}, $pending->{$subopt}, $type)) {
866f5834
OB
200 if ($fast_pluggable->{$subopt}) {
201 $configured->{$subopt} = $pending->{$subopt};
202 $changes = 1
203 }
204 }
205 }
206
207 # if there're no keys in $configured (after merge) there shouldn't be anything to change
208 if (keys %$configured) {
209 $conf->{$opt} = PVE::JSONSchema::print_property_string($configured, $format);
210 }
211
212 return $changes;
213}
214
215
61264e82
OB
216sub load_snapshot_config {
217 my ($class, $vmid, $snapname) = @_;
218
219 my $conf = $class->load_config($vmid);
220
221 my $snapshot = $conf->{snapshots}->{$snapname};
222 die "snapshot '$snapname' does not exist\n" if !defined($snapshot);
223
224 $snapshot->{digest} = $conf->{digest};
225
226 return $snapshot;
227
228}
229
230sub load_current_config {
231 my ($class, $vmid, $current) = @_;
232
233 my $conf = $class->load_config($vmid);
234
235 # take pending changes in
236 if (!$current) {
237 foreach my $opt (keys %{$conf->{pending}}) {
238 next if $opt eq 'delete';
239 my $value = $conf->{pending}->{$opt};
240 next if ref($value); # just to be sure
241 $conf->{$opt} = $value;
242 }
243 my $pending_delete_hash = $class->parse_pending_delete($conf->{pending}->{delete});
244 foreach my $opt (keys %$pending_delete_hash) {
245 delete $conf->{$opt} if $conf->{$opt};
246 }
247 }
248
249 delete $conf->{snapshots};
250 delete $conf->{pending};
251
252 return $conf;
253}
254
cbbb06a5 255sub create_and_lock_config {
fde98d5e 256 my ($class, $vmid, $allow_existing, $lock) = @_;
cbbb06a5
TL
257
258 $class->lock_config_full($vmid, 5, sub {
259 PVE::Cluster::check_vmid_unused($vmid, $allow_existing);
260
261 my $conf = eval { $class->load_config($vmid) } || {};
262 $class->check_lock($conf);
fde98d5e 263 $conf->{lock} = $lock // 'create';
cbbb06a5
TL
264 $class->write_config($vmid, $conf);
265 });
266}
267
ab44df53 268# destroys configuration, only applicable for configs owned by the callers node.
1aa76f2f
TL
269# dies if removal fails, e.g., when inquorate.
270sub destroy_config {
271 my ($class, $vmid) = @_;
272
273 my $config_fn = $class->config_file($vmid, $nodename);
274 unlink $config_fn or die "failed to remove config file: $!\n";
275}
276
65906123
FE
277# moves configuration owned by calling node to the target node.
278# dies if renaming fails.
0eec698f
TL
279# NOTE: in PVE a node owns the config (hard requirement), so only the owning
280# node may move the config to another node, which then becomes the new owner.
65906123
FE
281sub move_config_to_node {
282 my ($class, $vmid, $target_node) = @_;
283
284 my $config_fn = $class->config_file($vmid);
285 my $new_config_fn = $class->config_file($vmid, $target_node);
286
287 rename($config_fn, $new_config_fn)
288 or die "failed to move config file to node '$target_node': $!\n";
289}
290
9cdd4400
FG
291my $lock_file_full_wrapper = sub {
292 my ($class, $vmid, $timeout, $shared, $realcode, @param) = @_;
58a3c91c
FG
293
294 my $filename = $class->config_file_lock($vmid);
295
97b9ccec 296 # make sure configuration file is up-to-date
9cdd4400 297 my $code = sub {
97b9ccec 298 PVE::Cluster::cfs_update();
9cdd4400 299 $realcode->(@_);
97b9ccec
FE
300 };
301
9cdd4400 302 my $res = lock_file_full($filename, $timeout, $shared, $code, @param);
58a3c91c
FG
303
304 die $@ if $@;
305
306 return $res;
9cdd4400
FG
307};
308
309# Lock config file using non-exclusive ("read") flock, run $code with @param, unlock config file.
310# $timeout is the maximum time to acquire the flock
311sub lock_config_shared {
312 my ($class, $vmid, $timeout, $code, @param) = @_;
313
314 return $lock_file_full_wrapper->($class, $vmid, $timeout, 1, $code, @param);
58a3c91c
FG
315}
316
9cdd4400
FG
317# Lock config file using flock, run $code with @param, unlock config file.
318# $timeout is the maximum time to acquire the flock
319sub lock_config_full {
320 my ($class, $vmid, $timeout, $code, @param) = @_;
321
322 return $lock_file_full_wrapper->($class, $vmid, $timeout, 0, $code, @param);
323}
324
325
58a3c91c
FG
326# Lock config file using flock, run $code with @param, unlock config file.
327sub lock_config {
328 my ($class, $vmid, $code, @param) = @_;
329
330 return $class->lock_config_full($vmid, 10, $code, @param);
331}
332
333# Checks whether the config is locked with the lock parameter
334sub check_lock {
335 my ($class, $conf) = @_;
336
337 die $class->guest_type()." is locked ($conf->{lock})\n" if $conf->{lock};
338}
339
340# Returns whether the config is locked with the lock parameter, also checks
341# whether the lock value is correct if the optional $lock is set.
342sub has_lock {
343 my ($class, $conf, $lock) = @_;
344
345 return $conf->{lock} && (!defined($lock) || $lock eq $conf->{lock});
346}
347
348# Sets the lock parameter for this VM/CT's config to $lock.
349sub set_lock {
350 my ($class, $vmid, $lock) = @_;
351
352 my $conf;
353 $class->lock_config($vmid, sub {
354 $conf = $class->load_config($vmid);
355 $class->check_lock($conf);
356 $conf->{lock} = $lock;
357 $class->write_config($vmid, $conf);
358 });
359 return $conf;
360}
361
362# Removes the lock parameter for this VM/CT's config, also checks whether
363# the lock value is correct if the optional $lock is set.
364sub remove_lock {
365 my ($class, $vmid, $lock) = @_;
366
367 $class->lock_config($vmid, sub {
368 my $conf = $class->load_config($vmid);
369 if (!$conf->{lock}) {
370 my $lockstring = defined($lock) ? "'$lock' " : "any";
371 die "no lock found trying to remove $lockstring lock\n";
372 } elsif (defined($lock) && $conf->{lock} ne $lock) {
373 die "found lock '$conf->{lock}' trying to remove '$lock' lock\n";
374 }
375 delete $conf->{lock};
376 $class->write_config($vmid, $conf);
377 });
378}
379
380# Checks whether protection mode is enabled for this VM/CT.
381sub check_protection {
382 my ($class, $conf, $err_msg) = @_;
383
384 if ($conf->{protection}) {
385 die "$err_msg - protection mode enabled\n";
386 }
387}
388
4e6382ab
FE
389# Returns a list of keys where used volumes can be located
390sub valid_volume_keys {
391 my ($class, $reverse) = @_;
392
393 die "implement me - abstract method\n";
394}
395
396# Returns a hash with the information from $volume_string
397# $key is used to determine the format of the string
398sub parse_volume {
399 my ($class, $key, $volume_string, $noerr) = @_;
400
401 die "implement me - abstract method\n";
402}
403
404# Returns a string with the information from $volume
405# $key is used to determine the format of the string
406sub print_volume {
407 my ($class, $key, $volume) = @_;
408
409 die "implement me - abstract method\n";
410}
411
412# The key under which the volume ID is located in volume hashes
413sub volid_key {
414 my ($class) = @_;
415
416 die "implement me - abstract method\n";
417}
418
58a3c91c
FG
419# Adds an unused volume to $config, if possible.
420sub add_unused_volume {
421 my ($class, $config, $volid) = @_;
422
423 my $key;
424 for (my $ind = $class->__config_max_unused_disks() - 1; $ind >= 0; $ind--) {
425 my $test = "unused$ind";
426 if (my $vid = $config->{$test}) {
427 return if $vid eq $volid; # do not add duplicates
428 } else {
429 $key = $test;
430 }
431 }
432
433 die "Too many unused volumes - please delete them first.\n" if !$key;
434
435 $config->{$key} = $volid;
436
437 return $key;
438}
439
8db01440
FE
440# Iterate over all unused volumes, calling $func for each key/value pair
441# with additional parameters @param.
442sub foreach_unused_volume {
443 my ($class, $conf, $func, @param) = @_;
444
445 foreach my $key (keys %{$conf}) {
446 if ($key =~ m/^unused\d+$/) {
447 my $volume = $class->parse_volume($key, $conf->{$key});
448 $func->($key, $volume, @param);
449 }
450 }
451}
452
261d47a4
FE
453# Iterate over all configured volumes, calling $func for each key/value pair
454# with additional parameters @param.
455# By default, unused volumes and specials like vmstate are excluded.
456# Options: reverse - reverses the order for the iteration
457# include_unused - also iterate over unused volumes
458# extra_keys - an array of extra keys to use for the iteration
459sub foreach_volume_full {
460 my ($class, $conf, $opts, $func, @param) = @_;
461
462 die "'reverse' iteration only supported for default keys\n"
463 if $opts->{reverse} && ($opts->{extra_keys} || $opts->{include_unused});
464
465 my @keys = $class->valid_volume_keys($opts->{reverse});
466 push @keys, @{$opts->{extra_keys}} if $opts->{extra_keys};
467
468 foreach my $key (@keys) {
469 my $volume_string = $conf->{$key};
470 next if !defined($volume_string);
471
472 my $volume = $class->parse_volume($key, $volume_string, 1);
473 next if !defined($volume);
474
475 $func->($key, $volume, @param);
476 }
477
478 $class->foreach_unused_volume($conf, $func, @param) if $opts->{include_unused};
479}
480
481sub foreach_volume {
482 my ($class, $conf, $func, @param) = @_;
483
484 return $class->foreach_volume_full($conf, undef, $func, @param);
485}
486
95a9508e
FE
487# $volume_map is a hash of 'old_volid' => 'new_volid' pairs.
488# This method replaces 'old_volid' by 'new_volid' throughout
489# the config including snapshots and unused and vmstate volumes
490sub update_volume_ids {
491 my ($class, $conf, $volume_map) = @_;
492
493 my $volid_key = $class->volid_key();
494
495 my $do_replace = sub {
496 my ($key, $volume, $current_section) = @_;
497
498 my $old_volid = $volume->{$volid_key};
499 if (my $new_volid = $volume_map->{$old_volid}) {
500 $volume->{$volid_key} = $new_volid;
501 $current_section->{$key} = $class->print_volume($key, $volume);
502 }
503 };
504
505 my $opts = {
506 'include_unused' => 1,
507 'extra_keys' => ['vmstate'],
508 };
509
510 $class->foreach_volume_full($conf, $opts, $do_replace, $conf);
511 foreach my $snap (keys %{$conf->{snapshots}}) {
512 my $snap_conf = $conf->{snapshots}->{$snap};
513 $class->foreach_volume_full($snap_conf, $opts, $do_replace, $snap_conf);
514 }
515}
516
58a3c91c
FG
517# Returns whether the template parameter is set in $conf.
518sub is_template {
519 my ($class, $conf) = @_;
520
521 return 1 if defined $conf->{template} && $conf->{template} == 1;
522}
523
ab44df53 524# Checks whether $feature is available for the referenced volumes in $conf.
58a3c91c
FG
525# Note: depending on the parameters, some volumes may be skipped!
526sub has_feature {
527 my ($class, $feature, $conf, $storecfg, $snapname, $running, $backup_only) = @_;
528 die "implement me - abstract method\n";
529}
530
3f85b14d
DM
531# get all replicatable volume (hash $res->{$volid} = 1)
532# $cleanup: for cleanup - simply ignores volumes without replicate feature
533# $norerr: never raise exceptions - return undef instead
534sub get_replicatable_volumes {
54b79ff5 535 my ($class, $storecfg, $vmid, $conf, $cleanup, $noerr) = @_;
3f85b14d
DM
536
537 die "implement me - abstract method\n";
538}
539
1245ad85
TL
540# Returns all the guests volumes which would be included in a vzdump job
541# Return Format (array-ref with hash-refs as elements):
b2a2affa
AL
542# [
543# {
a8878e5e
AL
544# key, key in the config, e.g. mp0, scsi0,...
545# included, boolean
546# reason, string
547# volume_config volume object as returned from foreach_volume()
1245ad85 548# },
b2a2affa
AL
549# ]
550sub get_backup_volumes {
551 my ($class, $conf) = @_;
552
553 die "implement me - abstract method\n";
554}
555
58a3c91c
FG
556# Internal snapshots
557
558# NOTE: Snapshot create/delete involves several non-atomic
559# actions, and can take a long time.
560# So we try to avoid locking the file and use the 'lock' variable
561# inside the config file instead.
562
563# Save the vmstate (RAM).
564sub __snapshot_save_vmstate {
565 my ($class, $vmid, $conf, $snapname, $storecfg) = @_;
566 die "implement me - abstract method\n";
567}
568
569# Check whether the VM/CT is running.
570sub __snapshot_check_running {
571 my ($class, $vmid) = @_;
572 die "implement me - abstract method\n";
573}
574
575# Check whether we need to freeze the VM/CT
576sub __snapshot_check_freeze_needed {
577 my ($sself, $vmid, $config, $save_vmstate) = @_;
578 die "implement me - abstract method\n";
579}
580
581# Freeze or unfreeze the VM/CT.
582sub __snapshot_freeze {
583 my ($class, $vmid, $unfreeze) = @_;
584
585 die "abstract method - implement me\n";
586}
587
588# Code run before and after creating all the volume snapshots
589# base: noop
590sub __snapshot_create_vol_snapshots_hook {
591 my ($class, $vmid, $snap, $running, $hook) = @_;
592
593 return;
594}
595
596# Create the volume snapshots for the VM/CT.
597sub __snapshot_create_vol_snapshot {
598 my ($class, $vmid, $vs, $volume, $snapname) = @_;
599
600 die "abstract method - implement me\n";
601}
602
603# Remove a drive from the snapshot config.
604sub __snapshot_delete_remove_drive {
605 my ($class, $snap, $drive) = @_;
606
607 die "abstract method - implement me\n";
608}
609
610# Delete the vmstate file/drive
611sub __snapshot_delete_vmstate_file {
612 my ($class, $snap, $force) = @_;
613
614 die "abstract method - implement me\n";
615}
616
617# Delete a volume snapshot
618sub __snapshot_delete_vol_snapshot {
619 my ($class, $vmid, $vs, $volume, $snapname) = @_;
620
621 die "abstract method - implement me\n";
622}
623
3fa4ce45
DC
624# called during rollback prepare, and between config rollback and starting guest
625# can change config, e.g. for vmgenid
626# $data is shared across calls and passed to vm_start
627sub __snapshot_rollback_hook {
628 my ($class, $vmid, $conf, $snap, $prepare, $data) = @_;
629
630 return;
631}
632
58a3c91c
FG
633# Checks whether a volume snapshot is possible for this volume.
634sub __snapshot_rollback_vol_possible {
635 my ($class, $volume, $snapname) = @_;
636
637 die "abstract method - implement me\n";
638}
639
640# Rolls back this volume.
641sub __snapshot_rollback_vol_rollback {
642 my ($class, $volume, $snapname) = @_;
643
644 die "abstract method - implement me\n";
645}
646
647# Stops the VM/CT for a rollback.
648sub __snapshot_rollback_vm_stop {
649 my ($class, $vmid) = @_;
650
651 die "abstract method - implement me\n";
652}
653
654# Start the VM/CT after a rollback with restored vmstate.
655sub __snapshot_rollback_vm_start {
3fa4ce45 656 my ($class, $vmid, $vmstate, $data);
58a3c91c
FG
657
658 die "abstract method - implement me\n";
659}
660
661# Get list of volume IDs which are referenced in $conf, but not in $snap.
662sub __snapshot_rollback_get_unused {
663 my ($class, $conf, $snap) = @_;
664
665 die "abstract method - implement me\n";
666}
667
58a3c91c
FG
668# Copy the current config $source to the snapshot config $dest
669sub __snapshot_copy_config {
670 my ($class, $source, $dest) = @_;
671
672 foreach my $k (keys %$source) {
673 next if $k eq 'snapshots';
674 next if $k eq 'snapstate';
675 next if $k eq 'snaptime';
676 next if $k eq 'vmstate';
677 next if $k eq 'lock';
678 next if $k eq 'digest';
679 next if $k eq 'description';
680 next if $k =~ m/^unused\d+$/;
681
682 $dest->{$k} = $source->{$k};
683 }
684};
685
686# Apply the snapshot config $snap to the config $conf (rollback)
687sub __snapshot_apply_config {
688 my ($class, $conf, $snap) = @_;
689
690 # copy snapshot list
691 my $newconf = {
692 snapshots => $conf->{snapshots},
693 };
694
eb74d483 695 # keep description and list of unused disks
58a3c91c 696 foreach my $k (keys %$conf) {
eb74d483 697 next if !($k =~ m/^unused\d+$/ || $k eq 'description');
38532f70 698
58a3c91c
FG
699 $newconf->{$k} = $conf->{$k};
700 }
701
702 $class->__snapshot_copy_config($snap, $newconf);
703
704 return $newconf;
705}
706
707# Prepares the configuration for snapshotting.
708sub __snapshot_prepare {
709 my ($class, $vmid, $snapname, $save_vmstate, $comment) = @_;
710
711 my $snap;
712
713 my $updatefn = sub {
714
715 my $conf = $class->load_config($vmid);
716
717 die "you can't take a snapshot if it's a template\n"
718 if $class->is_template($conf);
719
720 $class->check_lock($conf);
721
722 $conf->{lock} = 'snapshot';
723
685a524e
OB
724 my $snapshots = $conf->{snapshots};
725
58a3c91c 726 die "snapshot name '$snapname' already used\n"
685a524e 727 if defined($snapshots->{$snapname});
58a3c91c
FG
728
729 my $storecfg = PVE::Storage::config();
730 die "snapshot feature is not available\n"
731 if !$class->has_feature('snapshot', $conf, $storecfg, undef, undef, $snapname eq 'vzdump');
732
685a524e
OB
733 foreach my $existing_snapshot (keys %$snapshots) {
734 my $parent_name = $snapshots->{$existing_snapshot}->{parent} // '';
735 delete $snapshots->{$existing_snapshot}->{parent} if $snapname eq $parent_name;
736 }
737
738 $snap = $snapshots->{$snapname} = {};
58a3c91c
FG
739
740 if ($save_vmstate && $class->__snapshot_check_running($vmid)) {
741 $class->__snapshot_save_vmstate($vmid, $conf, $snapname, $storecfg);
742 }
743
744 $class->__snapshot_copy_config($conf, $snap);
745
746 $snap->{snapstate} = "prepare";
747 $snap->{snaptime} = time();
748 $snap->{description} = $comment if $comment;
749
750 $class->write_config($vmid, $conf);
751 };
752
753 $class->lock_config($vmid, $updatefn);
754
755 return $snap;
756}
757
758# Commits the configuration after snapshotting.
759sub __snapshot_commit {
760 my ($class, $vmid, $snapname) = @_;
761
762 my $updatefn = sub {
763
764 my $conf = $class->load_config($vmid);
765
766 die "missing snapshot lock\n"
767 if !($conf->{lock} && $conf->{lock} eq 'snapshot');
768
769 my $snap = $conf->{snapshots}->{$snapname};
770 die "snapshot '$snapname' does not exist\n" if !defined($snap);
771
772 die "wrong snapshot state\n"
773 if !($snap->{snapstate} && $snap->{snapstate} eq "prepare");
774
775 delete $snap->{snapstate};
776 delete $conf->{lock};
777
778 $conf->{parent} = $snapname;
779
780 $class->write_config($vmid, $conf);
781 };
782
783 $class->lock_config($vmid, $updatefn);
784}
785
786# Creates a snapshot for the VM/CT.
787sub snapshot_create {
788 my ($class, $vmid, $snapname, $save_vmstate, $comment) = @_;
789
790 my $snap = $class->__snapshot_prepare($vmid, $snapname, $save_vmstate, $comment);
791
792 $save_vmstate = 0 if !$snap->{vmstate};
793
794 my $conf = $class->load_config($vmid);
795
796 my ($running, $freezefs) = $class->__snapshot_check_freeze_needed($vmid, $conf, $snap->{vmstate});
797
798 my $drivehash = {};
799
800 eval {
801 if ($freezefs) {
802 $class->__snapshot_freeze($vmid, 0);
803 }
804
805 $class->__snapshot_create_vol_snapshots_hook($vmid, $snap, $running, "before");
806
261d47a4 807 $class->foreach_volume($snap, sub {
58a3c91c
FG
808 my ($vs, $volume) = @_;
809
810 $class->__snapshot_create_vol_snapshot($vmid, $vs, $volume, $snapname);
811 $drivehash->{$vs} = 1;
812 });
813 };
814 my $err = $@;
815
816 if ($running) {
817 $class->__snapshot_create_vol_snapshots_hook($vmid, $snap, $running, "after");
818 if ($freezefs) {
819 $class->__snapshot_freeze($vmid, 1);
820 }
821 $class->__snapshot_create_vol_snapshots_hook($vmid, $snap, $running, "after-unfreeze");
822 }
823
824 if ($err) {
825 warn "snapshot create failed: starting cleanup\n";
826 eval { $class->snapshot_delete($vmid, $snapname, 1, $drivehash); };
827 warn "$@" if $@;
828 die "$err\n";
829 }
830
831 $class->__snapshot_commit($vmid, $snapname);
832}
833
602ca77c
FE
834# Check if the snapshot might still be needed by a replication job.
835my $snapshot_delete_assert_not_needed_by_replication = sub {
836 my ($class, $vmid, $conf, $snap, $snapname) = @_;
837
838 my $repl_conf = PVE::ReplicationConfig->new();
839 return if !$repl_conf->check_for_existing_jobs($vmid, 1);
840
841 my $storecfg = PVE::Storage::config();
842
843 # Current config's volumes are relevant for replication.
844 my $volumes = $class->get_replicatable_volumes($storecfg, $vmid, $conf, 1);
845
846 my $replication_jobs = $repl_conf->list_guests_local_replication_jobs($vmid);
847
848 $class->foreach_volume($snap, sub {
849 my ($vs, $volume) = @_;
850
851 my $volid_key = $class->volid_key();
852 my $volid = $volume->{$volid_key};
853
854 return if !$volumes->{$volid};
855
2511f525 856 my $snapshots = PVE::Storage::volume_snapshot_info($storecfg, $volid);
602ca77c
FE
857
858 for my $job ($replication_jobs->@*) {
859 my $jobid = $job->{id};
860
861 my @jobs_snapshots = grep {
862 PVE::Replication::is_replication_snapshot($_, $jobid)
2511f525 863 } keys $snapshots->%*;
602ca77c
FE
864
865 next if scalar(@jobs_snapshots) > 0;
866
867 die "snapshot '$snapname' needed by replication job '$jobid' - run replication first\n";
868 }
869 });
870};
871
58a3c91c
FG
872# Deletes a snapshot.
873# Note: $drivehash is only set when called from snapshot_create.
874sub snapshot_delete {
875 my ($class, $vmid, $snapname, $force, $drivehash) = @_;
876
877 my $prepare = 1;
878
58a3c91c
FG
879 my $unused = [];
880
4c3144ea
AA
881 my $conf = $class->load_config($vmid);
882 my $snap = $conf->{snapshots}->{$snapname};
883
884 die "snapshot '$snapname' does not exist\n" if !defined($snap);
885
602ca77c
FE
886 $snapshot_delete_assert_not_needed_by_replication->($class, $vmid, $conf, $snap, $snapname)
887 if !$drivehash && !$force;
888
58a3c91c
FG
889 $class->set_lock($vmid, 'snapshot-delete')
890 if (!$drivehash); # doesn't already have a 'snapshot' lock
891
990d9675
FG
892 my $expected_lock = $drivehash ? 'snapshot' : 'snapshot-delete';
893
894 my $ensure_correct_lock = sub {
895 my ($conf) = @_;
896
897 die "encountered invalid lock, expected '$expected_lock'\n"
898 if !$class->has_lock($conf, $expected_lock);
899 };
900
58a3c91c
FG
901 my $unlink_parent = sub {
902 my ($confref, $new_parent) = @_;
903
904 if ($confref->{parent} && $confref->{parent} eq $snapname) {
905 if ($new_parent) {
906 $confref->{parent} = $new_parent;
907 } else {
908 delete $confref->{parent};
909 }
910 }
911 };
912
913 my $remove_drive = sub {
914 my ($drive) = @_;
915
916 my $conf = $class->load_config($vmid);
990d9675
FG
917 $ensure_correct_lock->($conf);
918
58a3c91c
FG
919 $snap = $conf->{snapshots}->{$snapname};
920 die "snapshot '$snapname' does not exist\n" if !defined($snap);
921
922 $class->__snapshot_delete_remove_drive($snap, $drive);
923
924 $class->write_config($vmid, $conf);
925 };
926
927 #prepare
928 $class->lock_config($vmid, sub {
929 my $conf = $class->load_config($vmid);
990d9675 930 $ensure_correct_lock->($conf);
58a3c91c
FG
931
932 die "you can't delete a snapshot if vm is a template\n"
933 if $class->is_template($conf);
934
935 $snap = $conf->{snapshots}->{$snapname};
936 die "snapshot '$snapname' does not exist\n" if !defined($snap);
937
938 $snap->{snapstate} = 'delete';
939
940 $class->write_config($vmid, $conf);
941 });
942
943 # now remove vmstate file
944 if ($snap->{vmstate}) {
945 $class->__snapshot_delete_vmstate_file($snap, $force);
946
947 # save changes (remove vmstate from snapshot)
948 $class->lock_config($vmid, $remove_drive, 'vmstate') if !$force;
949 };
950
951 # now remove all volume snapshots
261d47a4 952 $class->foreach_volume($snap, sub {
58a3c91c
FG
953 my ($vs, $volume) = @_;
954
955 return if $snapname eq 'vzdump' && $vs ne 'rootfs' && !$volume->{backup};
956 if (!$drivehash || $drivehash->{$vs}) {
957 eval { $class->__snapshot_delete_vol_snapshot($vmid, $vs, $volume, $snapname, $unused); };
958 if (my $err = $@) {
959 die $err if !$force;
960 warn $err;
961 }
962 }
963
964 # save changes (remove drive from snapshot)
965 $class->lock_config($vmid, $remove_drive, $vs) if !$force;
966 });
967
968 # now cleanup config
969 $class->lock_config($vmid, sub {
970 my $conf = $class->load_config($vmid);
990d9675
FG
971 $ensure_correct_lock->($conf);
972
58a3c91c
FG
973 $snap = $conf->{snapshots}->{$snapname};
974 die "snapshot '$snapname' does not exist\n" if !defined($snap);
975
976 # remove parent refs
977 &$unlink_parent($conf, $snap->{parent});
978 foreach my $sn (keys %{$conf->{snapshots}}) {
979 next if $sn eq $snapname;
980 &$unlink_parent($conf->{snapshots}->{$sn}, $snap->{parent});
981 }
982
983
984 delete $conf->{snapshots}->{$snapname};
985 delete $conf->{lock};
986 foreach my $volid (@$unused) {
987 $class->add_unused_volume($conf, $volid);
988 }
989
990 $class->write_config($vmid, $conf);
991 });
992}
993
a9bc9b3c
FE
994# Remove replication snapshots to make a rollback possible.
995my $rollback_remove_replication_snapshots = sub {
45c0b755 996 my ($class, $vmid, $snap, $snapname) = @_;
a9bc9b3c
FE
997
998 my $storecfg = PVE::Storage::config();
999
1000 my $repl_conf = PVE::ReplicationConfig->new();
1001 return if !$repl_conf->check_for_existing_jobs($vmid, 1);
1002
1003 my $volumes = $class->get_replicatable_volumes($storecfg, $vmid, $snap, 1);
1004
45c0b755 1005 # For these, all replication snapshots need to be removed for backwards compatibility.
a9bc9b3c 1006 my $volids = [];
45c0b755
FE
1007
1008 # For these, we know more and can remove only the required replication snapshots.
1009 my $blocking_snapshots = {};
1010
1011 # filter by what we actually iterate over below (excludes vmstate!)
a9bc9b3c
FE
1012 $class->foreach_volume($snap, sub {
1013 my ($vs, $volume) = @_;
1014
1015 my $volid_key = $class->volid_key();
1016 my $volid = $volume->{$volid_key};
1017
45c0b755
FE
1018 return if !$volumes->{$volid};
1019
1020 my $blockers = [];
1021 eval { $class->__snapshot_rollback_vol_possible($volume, $snapname, $blockers); };
1022 if (my $err = $@) {
1023 # FIXME die instead, once $blockers is required by the storage plugin API
1024 # and the guest plugins are required to be new enough to support it too.
1025 # Currently, it's not possible to distinguish between blockers being empty
1026 # because the plugin is old versus because there is a different error.
1027 if (scalar($blockers->@*) == 0) {
1028 push @{$volids}, $volid;
1029 return;
1030 }
1031
1032 for my $blocker ($blockers->@*) {
1033 die $err if !PVE::Replication::is_replication_snapshot($blocker);
1034 }
1035
1036 $blocking_snapshots->{$volid} = $blockers;
1037 }
a9bc9b3c
FE
1038 });
1039
45c0b755
FE
1040 my $removed_repl_snapshot;
1041 for my $volid (sort keys $blocking_snapshots->%*) {
1042 my $blockers = $blocking_snapshots->{$volid};
1043
1044 for my $blocker ($blockers->@*) {
1045 warn "WARN: removing replication snapshot '$volid\@$blocker'\n";
1046 $removed_repl_snapshot = 1;
1047 eval { PVE::Storage::volume_snapshot_delete($storecfg, $volid, $blocker); };
1048 die $@ if $@;
1049 }
1050 }
1051 warn "WARN: you shouldn't remove '$snapname' before running the next replication!\n"
1052 if $removed_repl_snapshot;
1053
1054 # Need to keep using a hammer for backwards compatibility...
a9bc9b3c
FE
1055 # remove all local replication snapshots (jobid => undef)
1056 my $logfunc = sub { my $line = shift; chomp $line; print "$line\n"; };
1057 PVE::Replication::prepare($storecfg, $volids, undef, 1, undef, $logfunc);
1058};
1059
58a3c91c
FG
1060# Rolls back to a given snapshot.
1061sub snapshot_rollback {
1062 my ($class, $vmid, $snapname) = @_;
1063
1064 my $prepare = 1;
1065
82a04857 1066 my $data = {};
58a3c91c
FG
1067
1068 my $get_snapshot_config = sub {
82a04857 1069 my ($conf) = @_;
58a3c91c
FG
1070
1071 die "you can't rollback if vm is a template\n" if $class->is_template($conf);
1072
1073 my $res = $conf->{snapshots}->{$snapname};
1074
1075 die "snapshot '$snapname' does not exist\n" if !defined($res);
1076
1077 return $res;
1078 };
1079
82a04857 1080 my $snap;
3fa4ce45 1081
58a3c91c 1082 my $updatefn = sub {
82a04857
FG
1083 my $conf = $class->load_config($vmid);
1084 $snap = $get_snapshot_config->($conf);
58a3c91c 1085
82a04857 1086 if ($prepare) {
45c0b755 1087 $rollback_remove_replication_snapshots->($class, $vmid, $snap, $snapname);
82a04857
FG
1088
1089 $class->foreach_volume($snap, sub {
1090 my ($vs, $volume) = @_;
58a3c91c 1091
82a04857
FG
1092 $class->__snapshot_rollback_vol_possible($volume, $snapname);
1093 });
1094 }
58a3c91c
FG
1095
1096 die "unable to rollback to incomplete snapshot (snapstate = $snap->{snapstate})\n"
1097 if $snap->{snapstate};
1098
1099 if ($prepare) {
1100 $class->check_lock($conf);
1101 $class->__snapshot_rollback_vm_stop($vmid);
1102 }
1103
1104 die "unable to rollback vm $vmid: vm is running\n"
1105 if $class->__snapshot_check_running($vmid);
1106
1107 if ($prepare) {
1108 $conf->{lock} = 'rollback';
1109 } else {
1110 die "got wrong lock\n" if !($conf->{lock} && $conf->{lock} eq 'rollback');
1111 delete $conf->{lock};
58a3c91c 1112
58a3c91c
FG
1113 my $unused = $class->__snapshot_rollback_get_unused($conf, $snap);
1114
1115 foreach my $volid (@$unused) {
1116 $class->add_unused_volume($conf, $volid);
1117 }
1118
58a3c91c
FG
1119 # copy snapshot config to current config
1120 $conf = $class->__snapshot_apply_config($conf, $snap);
1121 $conf->{parent} = $snapname;
58a3c91c
FG
1122 }
1123
3fa4ce45
DC
1124 $class->__snapshot_rollback_hook($vmid, $conf, $snap, $prepare, $data);
1125
58a3c91c
FG
1126 $class->write_config($vmid, $conf);
1127
1128 if (!$prepare && $snap->{vmstate}) {
3fa4ce45 1129 $class->__snapshot_rollback_vm_start($vmid, $snap->{vmstate}, $data);
58a3c91c
FG
1130 }
1131 };
1132
1133 $class->lock_config($vmid, $updatefn);
1134
261d47a4 1135 $class->foreach_volume($snap, sub {
58a3c91c
FG
1136 my ($vs, $volume) = @_;
1137
1138 $class->__snapshot_rollback_vol_rollback($volume, $snapname);
1139 });
1140
1141 $prepare = 0;
1142 $class->lock_config($vmid, $updatefn);
1143}
1144
eb50bb61
RV
1145# bash completion helper
1146
90fba9cd
WB
1147sub snapshot_list {
1148 my ($class, $vmid) = @_;
eb50bb61 1149
90fba9cd
WB
1150 my $snapshot = eval {
1151 my $conf = $class->load_config($vmid);
1152 my $snapshots = $conf->{snapshots} || [];
1153 [ sort keys %$snapshots ]
1154 } || [];
eb50bb61
RV
1155
1156 return $snapshot;
1157}
1158
58a3c91c 11591;