1 package PVE
::VZDump
::QemuServer
;
12 use PVE
::Cluster
qw(cfs_read_file);
17 use PVE
::Storage
::Plugin
;
18 use PVE
::Storage
::PBSPlugin
;
25 use PVE
::QemuServer
::Machine
;
26 use PVE
::QemuServer
::Monitor
qw(mon_cmd);
28 use base qw
(PVE
::VZDump
::Plugin
);
31 my ($class, $vzdump) = @_;
33 PVE
::VZDump
::check_bin
('qm');
35 my $self = bless { vzdump
=> $vzdump }, $class;
37 $self->{vmlist
} = PVE
::QemuServer
::vzlist
();
38 $self->{storecfg
} = PVE
::Storage
::config
();
49 return [ keys %{$self->{vmlist
}} ];
53 my ($self, $task, $vmid, $mode) = @_;
57 my $conf = $self->{vmlist
}->{$vmid} = PVE
::QemuConfig-
>load_config($vmid);
59 $self->loginfo("VM Name: $conf->{name}")
60 if defined($conf->{name
});
62 $self->{vm_was_running
} = 1;
63 if (!PVE
::QemuServer
::check_running
($vmid)) {
64 $self->{vm_was_running
} = 0;
67 $task->{hostname
} = $conf->{name
};
69 my $hostname = PVE
::INotify
::nodename
();
73 my $backup_volumes = PVE
::QemuConfig-
>get_backup_volumes($conf);
75 foreach my $volume (@{$backup_volumes}) {
76 my $name = $volume->{key
};
77 my $volume_config = $volume->{volume_config
};
78 my $volid = $volume_config->{file
};
80 if (!$volume->{included
}) {
81 $self->loginfo("exclude disk '$name' '$volid' ($volume->{reason})");
83 } elsif ($self->{vm_was_running
} && $volume_config->{iothread
}) {
84 if (!PVE
::QemuServer
::Machine
::runs_at_least_qemu_version
($vmid, 4, 0, 1)) {
85 die "disk '$name' '$volid' (iothread=on) can't use backup feature with running QEMU " .
86 "version < 4.0.1! Either set backup=no for this drive or upgrade QEMU and restart VM\n";
89 my $log = "include disk '$name' '$volid'";
90 if (defined(my $size = $volume_config->{size
})) {
91 my $readable_size = PVE
::JSONSchema
::format_size
($size);
92 $log .= " $readable_size";
97 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
98 push @$vollist, $volid if $storeid;
99 $drivehash->{$name} = $volume->{volume_config
};
102 PVE
::Storage
::activate_volumes
($self->{storecfg
}, $vollist);
104 foreach my $ds (sort keys %$drivehash) {
105 my $drive = $drivehash->{$ds};
107 my $volid = $drive->{file
};
108 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
112 $path = PVE
::Storage
::path
($self->{storecfg
}, $volid);
116 my ($size, $format) = eval { PVE
::Storage
::volume_size_info
($self->{storecfg
}, $volid, 5) };
117 die "no such volume '$volid'\n" if $@;
125 qmdevice
=> "drive-$ds",
129 $diskinfo->{type
} = 'block';
131 $diskinfo->{type
} = 'file';
134 push @{$task->{disks
}}, $diskinfo;
139 my ($self, $vmid) = @_;
141 my $running = PVE
::QemuServer
::check_running
($vmid) ?
1 : 0;
143 return wantarray ?
($running, $running ?
'running' : 'stopped') : $running;
147 my ($self, $vmid) = @_;
149 PVE
::QemuConfig-
>set_lock($vmid, 'backup');
153 my ($self, $vmid) = @_;
155 PVE
::QemuConfig-
>remove_lock($vmid, 'backup');
159 my ($self, $task, $vmid) = @_;
161 my $opts = $self->{vzdump
}->{opts
};
163 my $wait = $opts->{stopwait
} * 60;
164 # send shutdown and wait
165 $self->cmd ("qm shutdown $vmid --skiplock --keepActive --timeout $wait");
169 my ($self, $task, $vmid) = @_;
171 $self->cmd ("qm start $vmid --skiplock");
175 my ($self, $task, $vmid) = @_;
177 $self->cmd ("qm suspend $vmid --skiplock");
181 my ($self, $task, $vmid) = @_;
183 $self->cmd ("qm resume $vmid --skiplock");
187 my ($self, $task, $vmid) = @_;
189 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
191 my $outfile = "$task->{tmpdir}/qemu-server.conf";
192 my $firewall_src = "/etc/pve/firewall/$vmid.fw";
193 my $firewall_dest = "$task->{tmpdir}/qemu-server.fw";
195 my $outfd = IO
::File-
>new (">$outfile") ||
196 die "unable to open '$outfile'";
197 my $conffd = IO
::File-
>new ($conffile, 'r') ||
198 die "unable open '$conffile'";
202 while (defined (my $line = <$conffd>)) {
203 next if $line =~ m/^\#vzdump\#/; # just to be sure
204 next if $line =~ m/^\#qmdump\#/; # just to be sure
205 if ($line =~ m/^\[(.*)\]\s*$/) {
206 if ($1 =~ m/PENDING/i) {
212 next if $found_snapshot || $found_pending; # skip all snapshots and pending changes config data
214 if ($line =~ m/^unused\d+:\s*(\S+)\s*/) {
215 $self->loginfo("skip unused drive '$1' (not included into backup)");
218 next if $line =~ m/^lock:/ || $line =~ m/^parent:/;
223 foreach my $di (@{$task->{disks
}}) {
224 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
225 my $storeid = $di->{storeid
} || '';
226 my $format = $di->{format
} || '';
227 print $outfd "#qmdump#map:$di->{virtdev}:$di->{qmdevice}:$storeid:$format:\n";
229 die "internal error";
233 if ($found_snapshot) {
234 $self->loginfo("snapshots found (not included into backup)");
236 if ($found_pending) {
237 $self->loginfo("pending configuration changes found (not included into backup)");
240 PVE
::Tools
::file_copy
($firewall_src, $firewall_dest) if -f
$firewall_src;
244 my ($self, $task, $vmid, $filename, $comp) = @_;
246 my $opts = $self->{vzdump
}->{opts
};
247 my $scfg = $opts->{scfg
};
249 if ($self->{vzdump
}->{opts
}->{pbs
}) {
250 $self->archive_pbs($task, $vmid);
252 $self->archive_vma($task, $vmid, $filename, $comp);
256 # number, [precision=1]
258 return sprintf( "%." . ( $_[1] || 1 ) . "f", $_[0] );
261 my ($bytes, $precission) = @_;
263 return $num2str->($bytes, $precission) . ' B' if $bytes < 1024;
264 my $kb = $bytes/1024;
266 return $num2str->($kb, $precission) . " KiB" if $kb < 1024;
269 return $num2str->($mb, $precission) . " MiB" if $mb < 1024;
272 return $num2str->($gb, $precission) . " GiB" if $gb < 1024;
275 return $num2str->($tb, $precission) . " TiB";
278 my $query_backup_status_loop = sub {
279 my ($self, $vmid, $job_uuid) = @_;
281 my $starttime = time ();
282 my $last_time = $starttime;
283 my ($last_percent, $last_total, $last_target, $last_zero, $last_transferred) = (-1, 0, 0, 0, 0);
284 my ($transferred, $reused);
288 my ($mb, $delta) = @_;
289 return "0 B/s" if $mb <= 0;
290 my $bw = int(($mb / $delta));
291 return bytes_to_human
($bw) . "/s";
295 my $status = mon_cmd
($vmid, 'query-backup');
297 my $total = $status->{total
} || 0;
298 my $dirty = $status->{dirty
};
299 my $target = (defined($dirty) && $dirty < $total) ?
$dirty : $total;
300 $transferred = $status->{transferred
} || 0;
301 $reused = $status->{reused
};
302 my $percent = $target ?
int(($transferred * 100)/$target) : 0;
303 my $zero = $status->{'zero-bytes'} || 0;
305 die "got unexpected uuid\n" if !$status->{uuid
} || ($status->{uuid
} ne $job_uuid);
308 my $duration = $ctime - $starttime;
310 my $rbytes = $transferred - $last_transferred;
311 my $wbytes = $rbytes - ($zero - $last_zero);
313 my $timediff = ($ctime - $last_time) || 1; # fixme
314 my $mbps_read = $get_mbps->($rbytes, $timediff);
315 my $mbps_write = $get_mbps->($wbytes, $timediff);
316 my $target_h = bytes_to_human
($target);
317 my $transferred_h = bytes_to_human
($transferred);
319 if ($first_round && $target != $total) {
320 my $total_h = bytes_to_human
($total);
321 $self->loginfo("using fast incremental mode (dirty-bitmap), $target_h dirty of $total_h total");
324 my $statusline = "status: $percent% ($transferred_h of $target_h), duration $duration"
325 .", read: $mbps_read, write: $mbps_write";
327 my $res = $status->{status
} || 'unknown';
328 if ($res ne 'active') {
329 $self->loginfo($statusline);
330 if ($res ne 'done') {
331 die (($status->{errmsg
} || "unknown error") . "\n") if $res eq 'error';
332 die "got unexpected status '$res'\n";
334 $last_target = $target if $target;
335 $last_total = $total if $total;
336 $last_zero = $zero if $zero;
337 $last_transferred = $transferred if $transferred;
340 if ($percent != $last_percent && ($timediff > 2)) {
341 $self->loginfo($statusline);
342 $last_percent = $percent;
343 $last_target = $target if $target;
344 $last_total = $total if $total;
345 $last_zero = $zero if $zero;
346 $last_transferred = $transferred if $transferred;
353 my $duration = time() - $starttime;
354 if ($transferred && $duration) {
355 my $transferred_h = bytes_to_human
($transferred, 2);
356 my $mbps = $get_mbps->($transferred, $duration);
358 my $reused_h = bytes_to_human
($reused, 2);
359 my $reuse_per = int($reused * 100 / $last_total);
360 $self->loginfo("backup was done incrementally, reused $reused_h (${reuse_per}%)");
362 $self->loginfo("transferred $transferred_h in $duration seconds ($mbps)");
366 my $zero_per = $last_target ?
int(($last_zero * 100)/$last_target) : 0;
367 my $zero_h = bytes_to_human
($last_zero, 2);
368 $self->loginfo("Backup is sparse: ${zero_per}% ($zero_h) zero data");
372 total
=> $last_total,
378 my ($self, $task, $vmid) = @_;
380 my $conffile = "$task->{tmpdir}/qemu-server.conf";
381 my $firewall = "$task->{tmpdir}/qemu-server.fw";
383 my $opts = $self->{vzdump
}->{opts
};
384 my $scfg = $opts->{scfg
};
386 my $starttime = time();
388 my $server = $scfg->{server
};
389 my $datastore = $scfg->{datastore
};
390 my $username = $scfg->{username
} // 'root@pam';
391 my $fingerprint = $scfg->{fingerprint
};
393 my $repo = "$username\@$server:$datastore";
394 my $password = PVE
::Storage
::PBSPlugin
::pbs_get_password
($scfg, $opts->{storage
});
395 my $keyfile = PVE
::Storage
::PBSPlugin
::pbs_encryption_key_file_name
($scfg, $opts->{storage
});
397 my $diskcount = scalar(@{$task->{disks
}});
398 if (PVE
::QemuConfig-
>is_template($self->{vmlist
}->{$vmid}) || !$diskcount) {
400 # FIXME: accumulate disk sizes to use for backup job (email) log
401 foreach my $di (@{$task->{disks
}}) {
402 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
403 push @pathlist, "$di->{qmdevice}.img:$di->{path}";
405 die "implement me (type $di->{type})";
410 $self->loginfo("backup contains no disks");
413 local $ENV{PBS_PASSWORD
} = $password;
414 local $ENV{PBS_FINGERPRINT
} = $fingerprint if defined($fingerprint);
416 '/usr/bin/proxmox-backup-client',
418 '--repository', $repo,
419 '--backup-type', 'vm',
420 '--backup-id', "$vmid",
421 '--backup-time', $task->{backup_time
},
424 push @$cmd, "qemu-server.conf:$conffile";
425 push @$cmd, "fw.conf:$firewall" if -e
$firewall;
426 push @$cmd, @pathlist if scalar(@pathlist);
428 $self->loginfo("starting template backup");
429 $self->loginfo(join(' ', @$cmd));
436 # get list early so we die on unkown drive types before doing anything
437 my $devlist = _get_task_devlist
($task);
439 $self->enforce_vm_running_for_backup($vmid);
443 $SIG{INT
} = $SIG{TERM
} = $SIG{QUIT
} = $SIG{HUP
} = $SIG{PIPE
} = sub {
444 die "interrupted by signal\n";
447 my $qemu_support = eval { mon_cmd
($vmid, "query-proxmox-support") };
448 if (!$qemu_support) {
449 die "PBS backups are not supported by the running QEMU version. Please make "
450 . "sure you've installed the latest version and the VM has been restarted.\n";
453 my $fs_frozen = $self->qga_fs_freeze($task, $vmid);
457 'backup-file' => $repo,
458 'backup-id' => "$vmid",
459 'backup-time' => $task->{backup_time
},
460 password
=> $password,
462 'config-file' => $conffile,
464 $params->{fingerprint
} = $fingerprint if defined($fingerprint);
465 $params->{'firewall-file'} = $firewall if -e
$firewall;
467 $self->loginfo("enabling encryption");
468 $params->{keyfile
} = $keyfile;
469 $params->{encrypt
} = JSON
::true
;
471 $params->{encrypt
} = JSON
::false
;
474 $params->{'use-dirty-bitmap'} = JSON
::true
if $qemu_support->{'pbs-dirty-bitmap'};
476 $params->{timeout
} = 60; # give some time to connect to the backup server
478 my $res = eval { mon_cmd
($vmid, "backup", %$params) };
480 $backup_job_uuid = $res->{UUID
} if $res;
483 $self->qga_fs_thaw($vmid);
486 die $qmperr if $qmperr;
487 die "got no uuid for backup task\n" if !defined($backup_job_uuid);
489 $self->loginfo("started backup task '$backup_job_uuid'");
491 $self->resume_vm_after_job_start($task, $vmid);
493 my $stat = $query_backup_status_loop->($self, $vmid, $backup_job_uuid);
494 $task->{size
} = $stat->{total
};
499 $self->mon_backup_cancel($vmid) if defined($backup_job_uuid);
501 $self->restore_vm_power_state($vmid);
506 my $fork_compressor_pipe = sub {
507 my ($self, $comp, $outfileno) = @_;
509 my @pipefd = POSIX
::pipe();
511 die "unable to fork worker - $!" if !defined($cpid) || $cpid < 0;
514 POSIX
::close($pipefd[1]);
516 my $fd = fileno(STDIN
);
518 POSIX
::close(0) if $fd != 0;
519 die "unable to redirect STDIN - $!"
520 if !open(STDIN
, "<&", $pipefd[0]);
523 $fd = fileno(STDOUT
);
525 POSIX
::close (1) if $fd != 1;
527 die "unable to redirect STDOUT - $!"
528 if !open(STDOUT
, ">&", $outfileno);
531 die "fork compressor '$comp' failed\n";
540 POSIX
::close($pipefd[0]);
541 $outfileno = $pipefd[1];
544 return ($cpid, $outfileno);
548 my ($self, $task, $vmid, $filename, $comp) = @_;
550 my $conffile = "$task->{tmpdir}/qemu-server.conf";
551 my $firewall = "$task->{tmpdir}/qemu-server.fw";
553 my $opts = $self->{vzdump
}->{opts
};
555 my $starttime = time();
558 if ($opts->{bwlimit
}) {
559 $speed = $opts->{bwlimit
}*1024;
562 my $diskcount = scalar(@{$task->{disks
}});
563 if (PVE
::QemuConfig-
>is_template($self->{vmlist
}->{$vmid}) || !$diskcount) {
565 foreach my $di (@{$task->{disks
}}) {
566 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
567 push @pathlist, "$di->{qmdevice}=$di->{path}";
574 $self->loginfo("backup contains no disks");
579 $outcmd = "exec:$comp";
581 $outcmd = "exec:cat";
584 $outcmd .= " > $filename" if !$opts->{stdout
};
586 my $cmd = ['/usr/bin/vma', 'create', '-v', '-c', $conffile];
587 push @$cmd, '-c', $firewall if -e
$firewall;
588 push @$cmd, $outcmd, @pathlist;
590 $self->loginfo("starting template backup");
591 $self->loginfo(join(' ', @$cmd));
593 if ($opts->{stdout
}) {
594 $self->cmd($cmd, output
=> ">&" . fileno($opts->{stdout
}));
602 my $devlist = _get_task_devlist
($task);
604 $self->enforce_vm_running_for_backup($vmid);
610 $SIG{INT
} = $SIG{TERM
} = $SIG{QUIT
} = $SIG{HUP
} = $SIG{PIPE
} = sub {
611 die "interrupted by signal\n";
615 if ($opts->{stdout
}) {
616 $outfh = $opts->{stdout
};
618 $outfh = IO
::File-
>new($filename, "w") ||
619 die "unable to open file '$filename' - $!\n";
621 my $outfileno = fileno($outfh);
624 ($cpid, $outfileno) = $fork_compressor_pipe->($self, $comp, $outfileno);
627 my $qmpclient = PVE
::QMPClient-
>new();
628 my $backup_cb = sub {
629 my ($vmid, $resp) = @_;
630 $backup_job_uuid = $resp->{return}->{UUID
};
632 my $add_fd_cb = sub {
633 my ($vmid, $resp) = @_;
636 'backup-file' => "/dev/fdname/backup",
638 'config-file' => $conffile,
641 $params->{'firewall-file'} = $firewall if -e
$firewall;
643 $qmpclient->queue_cmd($vmid, $backup_cb, 'backup', %$params);
646 $qmpclient->queue_cmd($vmid, $add_fd_cb, 'getfd', fd
=> $outfileno, fdname
=> "backup");
648 my $fs_frozen = $self->qga_fs_freeze($task, $vmid);
650 eval { $qmpclient->queue_execute(30) };
654 $self->qga_fs_thaw($vmid);
657 die $qmperr if $qmperr;
658 die $qmpclient->{errors
}->{$vmid} if $qmpclient->{errors
}->{$vmid};
661 POSIX
::close($outfileno) == 0 ||
662 die "close output file handle failed\n";
665 die "got no uuid for backup task\n" if !defined($backup_job_uuid);
667 $self->loginfo("started backup task '$backup_job_uuid'");
669 $self->resume_vm_after_job_start($task, $vmid);
671 $query_backup_status_loop->($self, $vmid, $backup_job_uuid);
676 $self->mon_backup_cancel($vmid) if defined($backup_job_uuid);
679 $self->restore_vm_power_state($vmid);
689 if ($cpid && (waitpid($cpid, 0) > 0)) {
692 my $signal = $stat & 127;
693 if ($ec || $signal) {
694 die "$comp failed - wrong exit status $ec" .
695 ($signal ?
" (signal $signal)\n" : "\n");
700 sub _get_task_devlist
{
704 foreach my $di (@{$task->{disks
}}) {
705 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
706 $devlist .= ',' if $devlist;
707 $devlist .= $di->{qmdevice
};
709 die "implement me (type '$di->{type}')";
716 my ($self, $task, $vmid) = @_;
717 return if !$self->{vmlist
}->{$vmid}->{agent
} || $task->{mode
} eq 'stop' || !$self->{vm_was_running
};
719 if (!PVE
::QemuServer
::qga_check_running
($vmid, 1)) {
720 $self->loginfo("skipping guest-agent 'fs-freeze', agent configured but not running?");
724 $self->loginfo("issuing guest-agent 'fs-freeze' command");
725 eval { mon_cmd
($vmid, "guest-fsfreeze-freeze") };
726 $self->logerr($@) if $@;
728 return 1; # even on mon command error, ensure we always thaw again
731 # only call if fs_freeze return 1
733 my ($self, $vmid) = @_;
735 $self->loginfo("issuing guest-agent 'fs-thaw' command");
736 eval { mon_cmd
($vmid, "guest-fsfreeze-thaw") };
737 $self->logerr($@) if $@;
740 # we need a running QEMU/KVM process for backup, starts a paused (prelaunch)
741 # one if VM isn't already running
742 sub enforce_vm_running_for_backup
{
743 my ($self, $vmid) = @_;
745 if (PVE
::QemuServer
::check_running
($vmid)) {
746 $self->{vm_was_running
} = 1;
751 $self->loginfo("starting kvm to execute backup task");
752 # start with skiplock
757 PVE
::QemuServer
::vm_start
($self->{storecfg
}, $vmid, $params);
762 # resume VM againe once we got in a clear state (stop mode backup of running VM)
763 sub resume_vm_after_job_start
{
764 my ($self, $task, $vmid) = @_;
766 return if !$self->{vm_was_running
};
768 if (my $stoptime = $task->{vmstoptime
}) {
769 my $delay = time() - $task->{vmstoptime
};
770 $task->{vmstoptime
} = undef; # avoid printing 'online after ..' twice
771 $self->loginfo("resuming VM again after $delay seconds");
773 $self->loginfo("resuming VM again");
775 mon_cmd
($vmid, 'cont');
778 # stop again if VM was not running before
779 sub restore_vm_power_state
{
780 my ($self, $vmid) = @_;
782 # we always let VMs keep running
783 return if $self->{vm_was_running
};
786 my $resp = mon_cmd
($vmid, 'query-status');
787 my $status = $resp && $resp->{status
} ?
$resp->{status
} : 'unknown';
788 if ($status eq 'prelaunch') {
789 $self->loginfo("stopping kvm after backup task");
790 PVE
::QemuServer
::vm_stop
($self->{storecfg
}, $vmid, 1);
792 $self->loginfo("kvm status changed after backup ('$status') - keep VM running");
798 sub mon_backup_cancel
{
799 my ($self, $vmid) = @_;
801 $self->loginfo("aborting backup job");
802 eval { mon_cmd
($vmid, 'backup-cancel') };
803 $self->logerr($@) if $@;
807 my ($self, $task, $vmid) = @_;
813 my ($self, $task, $vmid) = @_;