]> git.proxmox.com Git - pve-guest-common.git/blame - src/PVE/Replication.pm
vzdump: avoid declaring whole PBS change-detection mode as experimental
[pve-guest-common.git] / src / PVE / Replication.pm
CommitLineData
a6538c1e
DM
1package PVE::Replication;
2
3use warnings;
4use strict;
5use Data::Dumper;
6use JSON;
7use Time::HiRes qw(gettimeofday tv_interval);
93c3695b 8use POSIX qw(strftime);
a6538c1e
DM
9
10use PVE::INotify;
11use PVE::ProcFSTools;
12use PVE::Tools;
13use PVE::Cluster;
96c08a9d 14use PVE::DataCenterConfig;
a6538c1e
DM
15use PVE::Storage;
16use PVE::GuestHelpers;
17use PVE::ReplicationConfig;
18use PVE::ReplicationState;
0c85474f 19use PVE::SSHInfo;
a6538c1e
DM
20
21
22# regression tests should overwrite this
23sub get_log_time {
24
93c3695b 25 return strftime("%F %H:%M:%S", localtime);
a6538c1e
DM
26}
27
e4f63016
DM
28# Find common base replication snapshot, available on local and remote side.
29# Note: this also removes stale replication snapshots
30sub find_common_replication_snapshot {
c05dc937
FE
31 my ($ssh_info, $jobid, $vmid, $storecfg, $volumes, $storeid_list, $last_sync, $guest_conf, $logfunc) = @_;
32
33 my $parent_snapname = $guest_conf->{parent};
b20bf9bf 34 my $conf_snapshots = $guest_conf->{snapshots};
e4f63016
DM
35
36 my $last_sync_snapname =
37 PVE::ReplicationState::replication_snapshot_name($jobid, $last_sync);
38
4c1bd502 39 my $local_snapshots =
fbbeb872 40 prepare($storecfg, $volumes, $jobid, $last_sync, $parent_snapname, $logfunc);
e4f63016
DM
41
42 # prepare remote side
43 my $remote_snapshots = remote_prepare_local_job(
fbbeb872
FE
44 $ssh_info,
45 $jobid,
46 $vmid,
47 $volumes,
48 $storeid_list,
49 $last_sync,
50 $parent_snapname,
51 0,
52 $logfunc,
53 );
e4f63016
DM
54
55 my $base_snapshots = {};
f657b6ab 56 my @missing_snapshots = ();
e4f63016
DM
57
58 foreach my $volid (@$volumes) {
4c1bd502 59 my $local_info = $local_snapshots->{$volid};
b20bf9bf
FE
60 my $remote_info = $remote_snapshots->{$volid};
61
62 if (defined($local_info) && defined($remote_info)) {
63 my $common_snapshot = sub {
64 my ($snap) = @_;
65
66 return 0 if !$local_info->{$snap} || !$remote_info->{$snap};
67
68 # Check for ID if remote side supports it already.
69 return $local_info->{$snap}->{id} eq $remote_info->{$snap}->{id}
70 if ref($remote_info->{$snap}) eq 'HASH';
71
72 return 1;
73 };
74
75 if ($common_snapshot->($last_sync_snapname)) {
e4f63016 76 $base_snapshots->{$volid} = $last_sync_snapname;
b20bf9bf 77 } elsif (defined($parent_snapname) && $common_snapshot->($parent_snapname)) {
e4f63016 78 $base_snapshots->{$volid} = $parent_snapname;
8d1cd443 79 } else {
84fc20aa 80 my $most_recent = [0, undef];
b20bf9bf
FE
81 for my $snapshot (keys $local_info->%*) {
82 next if !$common_snapshot->($snapshot);
83 next if !$conf_snapshots->{$snapshot} && !is_replication_snapshot($snapshot);
84fc20aa 84
b20bf9bf 85 my $timestamp = $local_info->{$snapshot}->{timestamp};
84fc20aa 86
b20bf9bf 87 $most_recent = [$timestamp, $snapshot] if $timestamp > $most_recent->[0];
84fc20aa
FE
88 }
89
90 if ($most_recent->[1]) {
91 $base_snapshots->{$volid} = $most_recent->[1];
92 next;
d5b277dc 93 }
8d1cd443 94
f657b6ab 95 push @missing_snapshots, $volid if !defined($base_snapshots->{$volid});
e4f63016
DM
96 }
97 }
98 }
99
f657b6ab
FE
100 if (scalar(@missing_snapshots) > 0) {
101 # There exist volumes without common base snapshot on the remote side.
102 # Trying to (do a full) sync won't work, so die early with a clean error.
103 my $volume_string = join(',', @missing_snapshots);
104 die "No common base snapshot on volume(s) $volume_string\nPlease remove the problematic " .
105 "volume(s) from the replication target or delete and re-create the whole job $jobid\n";
106 }
107
4c1bd502 108 return ($base_snapshots, $local_snapshots, $last_sync_snapname);
e4f63016
DM
109}
110
a6538c1e
DM
111sub remote_prepare_local_job {
112 my ($ssh_info, $jobid, $vmid, $volumes, $storeid_list, $last_sync, $parent_snapname, $force, $logfunc) = @_;
113
0c85474f 114 my $ssh_cmd = PVE::SSHInfo::ssh_info_to_command($ssh_info);
a6538c1e
DM
115 my $cmd = [@$ssh_cmd, '--', 'pvesr', 'prepare-local-job', $jobid];
116 push @$cmd, '--scan', join(',', @$storeid_list) if scalar(@$storeid_list);
117 push @$cmd, @$volumes if scalar(@$volumes);
118
119 push @$cmd, '--last_sync', $last_sync;
120 push @$cmd, '--parent_snapname', $parent_snapname
121 if $parent_snapname;
122 push @$cmd, '--force' if $force;
123
124 my $remote_snapshots;
125
126 my $parser = sub {
127 my $line = shift;
128 $remote_snapshots = JSON::decode_json($line);
129 };
130
131 my $logger = sub {
132 my $line = shift;
133 chomp $line;
134 $logfunc->("(remote_prepare_local_job) $line");
135 };
136
137 PVE::Tools::run_command($cmd, outfunc => $parser, errfunc => $logger);
138
139 die "prepare remote node failed - no result\n"
140 if !defined($remote_snapshots);
141
142 return $remote_snapshots;
143}
144
145sub remote_finalize_local_job {
146 my ($ssh_info, $jobid, $vmid, $volumes, $last_sync, $logfunc) = @_;
147
0c85474f 148 my $ssh_cmd = PVE::SSHInfo::ssh_info_to_command($ssh_info);
a6538c1e
DM
149 my $cmd = [@$ssh_cmd, '--', 'pvesr', 'finalize-local-job', $jobid,
150 @$volumes, '--last_sync', $last_sync];
151
152 my $logger = sub {
153 my $line = shift;
154 chomp $line;
155 $logfunc->("(remote_finalize_local_job) $line");
156 };
157
158 PVE::Tools::run_command($cmd, outfunc => $logger, errfunc => $logger);
159}
160
c0b29481
FE
161# Finds all local snapshots and removes replication snapshots not matching $last_sync after checking
162# that it is present. Use last_sync=0 (or undef) to prevent removal (useful if VM was stolen). Use
163# last_sync=1 to remove all replication snapshots (limited to job if specified).
a6538c1e
DM
164sub prepare {
165 my ($storecfg, $volids, $jobid, $last_sync, $parent_snapname, $logfunc) = @_;
166
167 $last_sync //= 0;
168
b499eccb
DM
169 my ($prefix, $snapname);
170
171 if (defined($jobid)) {
172 ($prefix, $snapname) = PVE::ReplicationState::replication_snapshot_name($jobid, $last_sync);
173 } else {
174 $prefix = '__replicate_';
175 }
a6538c1e 176
4c1bd502 177 my $local_snapshots = {};
a6538c1e
DM
178 my $cleaned_replicated_volumes = {};
179 foreach my $volid (@$volids) {
a6f5b358
FE
180 $local_snapshots->{$volid} = {};
181
3200c404 182 my $info = PVE::Storage::volume_snapshot_info($storecfg, $volid);
c0b29481
FE
183
184 my $removal_ok = !defined($snapname) || $info->{$snapname};
185 $removal_ok = 0 if $last_sync == 0; # last_sync=0 if the VM was stolen, don't remove!
186 $removal_ok = 1 if $last_sync == 1; # last_sync=1 is a special value used to remove all
18b6c8d1
FE
187
188 # check if it's a replication snapshot with the same $prefix but not the $last_sync one
189 my $potentially_stale = sub {
190 my ($snap) = @_;
191
192 return 0 if defined($snapname) && $snap eq $snapname;
193 return 0 if defined($parent_snapname) && $snap eq $parent_snapname;
194 return $snap =~ m/^\Q$prefix\E/;
195 };
196
c0b29481 197 $logfunc->("expected snapshot $snapname not present for $volid, not removing others")
18b6c8d1 198 if !$removal_ok && $last_sync > 1 && grep { $potentially_stale->($_) } keys $info->%*;
c0b29481 199
3200c404 200 for my $snap (keys $info->%*) {
18b6c8d1 201 if ($potentially_stale->($snap) && $removal_ok) {
244583a4
FE
202 $logfunc->("delete stale replication snapshot '$snap' on $volid");
203 eval {
204 PVE::Storage::volume_snapshot_delete($storecfg, $volid, $snap);
205 $cleaned_replicated_volumes->{$volid} = 1;
206 };
207
208 # If deleting the snapshot fails, we can not be sure if it was due to an error or a timeout.
209 # The likelihood that the delete has worked out is high at a timeout.
210 # If it really fails, it will try to remove on the next run.
211 if (my $err = $@) {
212 # warn is for syslog/journal.
213 warn $err;
214
215 # logfunc will written in replication log.
216 $logfunc->("delete stale replication snapshot error: $err");
edd61f2b 217 }
8d1cd443 218 } else {
4c1bd502 219 $local_snapshots->{$volid}->{$snap} = $info->{$snap};
a6538c1e
DM
220 }
221 }
222 }
223
4c1bd502 224 return wantarray ? ($local_snapshots, $cleaned_replicated_volumes) : $local_snapshots;
a6538c1e
DM
225}
226
227sub replicate_volume {
aa0d516f 228 my ($ssh_info, $storecfg, $volid, $base_snapshot, $sync_snapname, $rate, $insecure, $logfunc) = @_;
a6538c1e
DM
229
230 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
231
45b4c97f
TL
232 my $ratelimit_bps = $rate ? int(1000000 * $rate) : undef;
233
36cff886
FE
234 my $opts = {
235 'target_volname' => $volname,
236 'base_snapshot' => $base_snapshot,
237 'snapshot' => $sync_snapname,
238 'ratelimit_bps' => $ratelimit_bps,
239 'insecure' => $insecure,
240 'with_snapshots' => 1,
241 };
242
243 PVE::Storage::storage_migrate($storecfg, $volid, $ssh_info, $storeid, $opts, $logfunc);
a6538c1e
DM
244}
245
246
247sub replicate {
248 my ($guest_class, $jobcfg, $state, $start_time, $logfunc) = @_;
249
250 my $local_node = PVE::INotify::nodename();
251
252 die "not implemented - internal error" if $jobcfg->{type} ne 'local';
253
254 my $dc_conf = PVE::Cluster::cfs_read_file('datacenter.cfg');
255
256 my $migration_network;
257 my $migration_type = 'secure';
258 if (my $mc = $dc_conf->{migration}) {
259 $migration_network = $mc->{network};
260 $migration_type = $mc->{type} if defined($mc->{type});
261 }
262
263 my $jobid = $jobcfg->{id};
264 my $storecfg = PVE::Storage::config();
265 my $last_sync = $state->{last_sync};
266
267 die "start time before last sync ($start_time <= $last_sync) - abort sync\n"
268 if $start_time <= $last_sync;
269
270 my $vmid = $jobcfg->{guest};
a6538c1e
DM
271
272 my $conf = $guest_class->load_config($vmid);
273 my ($running, $freezefs) = $guest_class->__snapshot_check_freeze_needed($vmid, $conf, 0);
c324e907 274 my $volumes = $guest_class->get_replicatable_volumes($storecfg, $vmid, $conf, defined($jobcfg->{remove_job}));
a6538c1e
DM
275
276 my $sorted_volids = [ sort keys %$volumes ];
277
278 $running //= 0; # to avoid undef warnings from logfunc
279
6358ffe1
DM
280 my $guest_name = $guest_class->guest_type() . ' ' . $vmid;
281
282 $logfunc->("guest => $guest_name, running => $running");
a6538c1e
DM
283 $logfunc->("volumes => " . join(',', @$sorted_volids));
284
01856537
FE
285 # filter out left-over non-existing/removed storages - avoids error on target
286 $state->{storeid_list} = [ grep { $storecfg->{ids}->{$_} } $state->{storeid_list}->@* ];
287
a6538c1e
DM
288 if (my $remove_job = $jobcfg->{remove_job}) {
289
290 $logfunc->("start job removal - mode '${remove_job}'");
291
292 if ($remove_job eq 'full' && $jobcfg->{target} ne $local_node) {
293 # remove all remote volumes
d869a19c 294 my @store_list = map { (PVE::Storage::parse_volume_id($_))[0] } @$sorted_volids;
1e6416f1 295 push @store_list, @{$state->{storeid_list}};
d869a19c
WL
296
297 my %hash = map { $_ => 1 } @store_list;
298
0c85474f 299 my $ssh_info = PVE::SSHInfo::get_ssh_info($jobcfg->{target});
d869a19c 300 remote_prepare_local_job($ssh_info, $jobid, $vmid, [], [ keys %hash ], 1, undef, 1, $logfunc);
a6538c1e
DM
301
302 }
303 # remove all local replication snapshots (lastsync => 0)
a1dfeff3 304 prepare($storecfg, $sorted_volids, $jobid, 1, undef, $logfunc);
a6538c1e
DM
305
306 PVE::ReplicationConfig::delete_job($jobid); # update config
307 $logfunc->("job removed");
308
5899ebbd 309 return undef;
a6538c1e
DM
310 }
311
0c85474f 312 my $ssh_info = PVE::SSHInfo::get_ssh_info($jobcfg->{target}, $migration_network);
a6538c1e 313
4c1bd502 314 my ($base_snapshots, $local_snapshots, $last_sync_snapname) = find_common_replication_snapshot(
c05dc937 315 $ssh_info, $jobid, $vmid, $storecfg, $sorted_volids, $state->{storeid_list}, $last_sync, $conf, $logfunc);
a6538c1e
DM
316
317 my $storeid_hash = {};
318 foreach my $volid (@$sorted_volids) {
319 my ($storeid) = PVE::Storage::parse_volume_id($volid);
320 $storeid_hash->{$storeid} = 1;
321 }
322 $state->{storeid_list} = [ sort keys %$storeid_hash ];
323
324 # freeze filesystem for data consistency
325 if ($freezefs) {
326 $logfunc->("freeze guest filesystem");
327 $guest_class->__snapshot_freeze($vmid, 0);
328 }
329
330 # make snapshot of all volumes
e4f63016
DM
331 my $sync_snapname =
332 PVE::ReplicationState::replication_snapshot_name($jobid, $start_time);
333
a6538c1e
DM
334 my $replicate_snapshots = {};
335 eval {
336 foreach my $volid (@$sorted_volids) {
337 $logfunc->("create snapshot '${sync_snapname}' on $volid");
338 PVE::Storage::volume_snapshot($storecfg, $volid, $sync_snapname);
45c35535 339 $replicate_snapshots->{$volid}->{$sync_snapname} = 1;
a6538c1e
DM
340 }
341 };
342 my $err = $@;
343
5e93f430 344 # thaw immediately
a6538c1e 345 if ($freezefs) {
5e93f430 346 $logfunc->("thaw guest filesystem");
a6538c1e
DM
347 $guest_class->__snapshot_freeze($vmid, 1);
348 }
349
350 my $cleanup_local_snapshots = sub {
351 my ($volid_hash, $snapname) = @_;
352 foreach my $volid (sort keys %$volid_hash) {
45c35535 353 next if !$volid_hash->{$volid}->{$snapname};
a6538c1e
DM
354 $logfunc->("delete previous replication snapshot '$snapname' on $volid");
355 eval { PVE::Storage::volume_snapshot_delete($storecfg, $volid, $snapname); };
356 warn $@ if $@;
357 }
358 };
359
360 if ($err) {
361 $cleanup_local_snapshots->($replicate_snapshots, $sync_snapname); # try to cleanup
362 die $err;
363 }
364
365 eval {
366
367 my $rate = $jobcfg->{rate};
368 my $insecure = $migration_type eq 'insecure';
369
e90f586a
TL
370 $logfunc->("using $migration_type transmission, rate limit: "
371 . ($rate ? "$rate MByte/s" : "none"));
372
a6538c1e
DM
373 foreach my $volid (@$sorted_volids) {
374 my $base_snapname;
375
e4f63016
DM
376 if (defined($base_snapname = $base_snapshots->{$volid})) {
377 $logfunc->("incremental sync '$volid' ($base_snapname => $sync_snapname)");
378 } else {
379 $logfunc->("full sync '$volid' ($sync_snapname)");
a6538c1e
DM
380 }
381
aa0d516f 382 replicate_volume($ssh_info, $storecfg, $volid, $base_snapname, $sync_snapname, $rate, $insecure, $logfunc);
a6538c1e
DM
383 }
384 };
a6538c1e 385
edd61f2b 386 if ($err = $@) {
a6538c1e
DM
387 $cleanup_local_snapshots->($replicate_snapshots, $sync_snapname); # try to cleanup
388 # we do not cleanup the remote side here - this is done in
389 # next run of prepare_local_job
390 die $err;
391 }
392
ff574bf8
FE
393 # Ensure that new sync is recorded before removing old replication snapshots.
394 PVE::ReplicationState::record_sync_end($jobcfg, $state, $start_time);
395
a6538c1e 396 # remove old snapshots because they are no longer needed
4c1bd502 397 $cleanup_local_snapshots->($local_snapshots, $last_sync_snapname);
a6538c1e 398
ce22af08
WL
399 eval {
400 remote_finalize_local_job($ssh_info, $jobid, $vmid, $sorted_volids, $start_time, $logfunc);
401 };
a6538c1e 402
ce22af08
WL
403 # old snapshots will removed by next run from prepare_local_job.
404 if ($err = $@) {
405 # warn is for syslog/journal.
406 warn $err;
407
408 # logfunc will written in replication log.
c1797f7a 409 $logfunc->("delete stale replication snapshot error: $err");
ce22af08 410 }
5899ebbd
DM
411
412 return $volumes;
a6538c1e
DM
413}
414
415my $run_replication_nolock = sub {
ac02a68e 416 my ($guest_class, $jobcfg, $iteration, $start_time, $logfunc, $verbose) = @_;
a6538c1e
DM
417
418 my $jobid = $jobcfg->{id};
419
5899ebbd
DM
420 my $volumes;
421
ab44df53 422 # we normally write errors into the state file,
a6538c1e
DM
423 # but we also catch unexpected errors and log them to syslog
424 # (for examply when there are problems writing the state file)
a6538c1e 425
ac02a68e
WL
426 my $state = PVE::ReplicationState::read_job_state($jobcfg);
427
428 PVE::ReplicationState::record_job_start($jobcfg, $state, $start_time, $iteration);
a6538c1e 429
ac02a68e 430 my $t0 = [gettimeofday];
a6538c1e 431
ac02a68e
WL
432 mkdir $PVE::ReplicationState::replicate_logdir;
433 my $logfile = PVE::ReplicationState::job_logfile_name($jobid);
434 open(my $logfd, '>', $logfile) ||
435 die "unable to open replication log '$logfile' - $!\n";
a6538c1e 436
ac02a68e
WL
437 my $logfunc_wrapper = sub {
438 my ($msg) = @_;
a6538c1e 439
ac02a68e
WL
440 my $ctime = get_log_time();
441 print $logfd "$ctime $jobid: $msg\n";
442 if ($logfunc) {
443 if ($verbose) {
444 $logfunc->("$ctime $jobid: $msg");
445 } else {
446 $logfunc->($msg);
3ec43aaf 447 }
ac02a68e
WL
448 }
449 };
a6538c1e 450
ac02a68e 451 $logfunc_wrapper->("start replication job");
a6538c1e 452
ac02a68e
WL
453 eval {
454 $volumes = replicate($guest_class, $jobcfg, $state, $start_time, $logfunc_wrapper);
455 };
456 my $err = $@;
a6538c1e 457
ac02a68e
WL
458 if ($err) {
459 my $msg = "end replication job with error: $err";
460 chomp $msg;
461 $logfunc_wrapper->($msg);
462 } else {
463 $logfunc_wrapper->("end replication job");
464 }
a6538c1e 465
ac02a68e 466 PVE::ReplicationState::record_job_end($jobcfg, $state, $start_time, tv_interval($t0), $err);
c17dcb3e 467
ac02a68e 468 close($logfd);
1b82f171 469
ac02a68e 470 die $err if $err;
5899ebbd
DM
471
472 return $volumes;
a6538c1e
DM
473};
474
475sub run_replication {
ac02a68e 476 my ($guest_class, $jobcfg, $iteration, $start_time, $logfunc, $verbose) = @_;
a6538c1e 477
5899ebbd
DM
478 my $volumes;
479
ac02a68e
WL
480 my $timeout = 2; # do not wait too long - we repeat periodically anyways
481 $volumes = PVE::GuestHelpers::guest_migration_lock(
482 $jobcfg->{guest}, $timeout, $run_replication_nolock,
483 $guest_class, $jobcfg, $iteration, $start_time, $logfunc, $verbose);
484
5899ebbd 485 return $volumes;
a6538c1e
DM
486}
487
45c0b755 488sub is_replication_snapshot {
602ca77c
FE
489 my ($snapshot_name, $jobid) = @_;
490
491 if (defined($jobid)) {
492 return $snapshot_name =~ m/^__replicate_\Q$jobid\E/ ? 1 : 0;
493 }
45c0b755
FE
494
495 return $snapshot_name =~ m/^__replicate_/ ? 1 : 0;
496}
497
a6538c1e 4981;