1 package PVE
::VZDump
::QemuServer
;
11 use PVE
::Cluster
qw(cfs_read_file);
16 use PVE
::Storage
::Plugin
;
17 use PVE
::Storage
::PBSPlugin
;
23 use PVE
::QemuServer
::Machine
;
24 use PVE
::QemuServer
::Monitor
qw(mon_cmd);
26 use base qw
(PVE
::VZDump
::Plugin
);
29 my ($class, $vzdump) = @_;
31 PVE
::VZDump
::check_bin
('qm');
33 my $self = bless { vzdump
=> $vzdump }, $class;
35 $self->{vmlist
} = PVE
::QemuServer
::vzlist
();
36 $self->{storecfg
} = PVE
::Storage
::config
();
47 return [ keys %{$self->{vmlist
}} ];
51 my ($self, $task, $vmid, $mode) = @_;
55 my $conf = $self->{vmlist
}->{$vmid} = PVE
::QemuConfig-
>load_config($vmid);
57 $self->loginfo("VM Name: $conf->{name}")
58 if defined($conf->{name
});
60 $self->{vm_was_running
} = 1;
61 if (!PVE
::QemuServer
::check_running
($vmid)) {
62 $self->{vm_was_running
} = 0;
65 $task->{hostname
} = $conf->{name
};
67 my $hostname = PVE
::INotify
::nodename
();
71 PVE
::QemuServer
::foreach_drive
($conf, sub {
72 my ($ds, $drive) = @_;
74 return if PVE
::QemuServer
::drive_is_cdrom
($drive);
76 my $volid = $drive->{file
};
78 if (defined($drive->{backup
}) && !$drive->{backup
}) {
79 $self->loginfo("exclude disk '$ds' '$volid' (backup=no)");
81 } elsif ($self->{vm_was_running
} && $drive->{iothread
}) {
82 if (!PVE
::QemuServer
::Machine
::runs_at_least_qemu_version
($vmid, 4, 0, 1)) {
83 die "disk '$ds' '$volid' (iothread=on) can't use backup feature with running QEMU " .
84 "version < 4.0.1! Either set backup=no for this drive or upgrade QEMU and restart VM\n";
86 } elsif ($ds =~ m/^efidisk/ && (!defined($conf->{bios
}) || $conf->{bios
} ne 'ovmf')) {
87 $self->loginfo("excluding '$ds' (efidisks can only be backed up when BIOS is set to 'ovmf')");
90 my $log = "include disk '$ds' '$volid'";
91 if (defined $drive->{size
}) {
92 my $readable_size = PVE
::JSONSchema
::format_size
($drive->{size
});
93 $log .= " $readable_size";
98 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
99 push @$vollist, $volid if $storeid;
100 $drivehash->{$ds} = $drive;
103 PVE
::Storage
::activate_volumes
($self->{storecfg
}, $vollist);
105 foreach my $ds (sort keys %$drivehash) {
106 my $drive = $drivehash->{$ds};
108 my $volid = $drive->{file
};
109 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
113 $path = PVE
::Storage
::path
($self->{storecfg
}, $volid);
117 my ($size, $format) = eval { PVE
::Storage
::volume_size_info
($self->{storecfg
}, $volid, 5) };
118 die "no such volume '$volid'\n" if $@;
126 qmdevice
=> "drive-$ds",
130 $diskinfo->{type
} = 'block';
132 $diskinfo->{type
} = 'file';
135 push @{$task->{disks
}}, $diskinfo;
140 my ($self, $vmid) = @_;
142 my $running = PVE
::QemuServer
::check_running
($vmid) ?
1 : 0;
144 return wantarray ?
($running, $running ?
'running' : 'stopped') : $running;
148 my ($self, $vmid) = @_;
150 PVE
::QemuConfig-
>set_lock($vmid, 'backup');
154 my ($self, $vmid) = @_;
156 PVE
::QemuConfig-
>remove_lock($vmid, 'backup');
160 my ($self, $task, $vmid) = @_;
162 my $opts = $self->{vzdump
}->{opts
};
164 my $wait = $opts->{stopwait
} * 60;
165 # send shutdown and wait
166 $self->cmd ("qm shutdown $vmid --skiplock --keepActive --timeout $wait");
170 my ($self, $task, $vmid) = @_;
172 $self->cmd ("qm start $vmid --skiplock");
176 my ($self, $task, $vmid) = @_;
178 $self->cmd ("qm suspend $vmid --skiplock");
182 my ($self, $task, $vmid) = @_;
184 $self->cmd ("qm resume $vmid --skiplock");
188 my ($self, $task, $vmid) = @_;
190 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
192 my $outfile = "$task->{tmpdir}/qemu-server.conf";
193 my $firewall_src = "/etc/pve/firewall/$vmid.fw";
194 my $firewall_dest = "$task->{tmpdir}/qemu-server.fw";
196 my $outfd = IO
::File-
>new (">$outfile") ||
197 die "unable to open '$outfile'";
198 my $conffd = IO
::File-
>new ($conffile, 'r') ||
199 die "unable open '$conffile'";
203 while (defined (my $line = <$conffd>)) {
204 next if $line =~ m/^\#vzdump\#/; # just to be sure
205 next if $line =~ m/^\#qmdump\#/; # just to be sure
206 if ($line =~ m/^\[(.*)\]\s*$/) {
207 if ($1 =~ m/PENDING/i) {
212 next; # skip all snapshots and pending changes config data
215 if ($line =~ m/^unused\d+:\s*(\S+)\s*/) {
216 $self->loginfo("skip unused drive '$1' (not included into backup)");
219 next if $line =~ m/^lock:/ || $line =~ m/^parent:/;
224 foreach my $di (@{$task->{disks
}}) {
225 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
226 my $storeid = $di->{storeid
} || '';
227 my $format = $di->{format
} || '';
228 print $outfd "#qmdump#map:$di->{virtdev}:$di->{qmdevice}:$storeid:$format:\n";
230 die "internal error";
234 if ($found_snapshot) {
235 $self->loginfo("snapshots found (not included into backup)");
237 if ($found_pending) {
238 $self->loginfo("pending configuration changes found (not included into backup)");
241 PVE
::Tools
::file_copy
($firewall_src, $firewall_dest) if -f
$firewall_src;
245 my ($self, $task, $vmid, $filename, $comp) = @_;
247 my $opts = $self->{vzdump
}->{opts
};
248 my $scfg = $opts->{scfg
};
250 if ($scfg->{type
} eq 'pbs') {
251 $self->archive_pbs($task, $vmid);
253 $self->archive_vma($task, $vmid, $filename, $comp);
257 my $query_backup_status_loop = sub {
258 my ($self, $vmid, $job_uuid) = @_;
260 my $starttime = time ();
261 my $last_time = $starttime;
262 my ($last_percent, $last_total, $last_zero, $last_transferred) = (-1, 0, 0, 0);
266 my ($mb, $delta) = @_;
267 return ($mb > 0) ?
int(($mb / $delta) / (1000 * 1000)) : 0;
271 my $status = mon_cmd
($vmid, 'query-backup');
273 my $total = $status->{total
} || 0;
274 $transferred = $status->{transferred
} || 0;
275 my $percent = $total ?
int(($transferred * 100)/$total) : 0;
276 my $zero = $status->{'zero-bytes'} || 0;
277 my $zero_per = $total ?
int(($zero * 100)/$total) : 0;
279 die "got unexpected uuid\n" if !$status->{uuid
} || ($status->{uuid
} ne $job_uuid);
282 my $duration = $ctime - $starttime;
284 my $rbytes = $transferred - $last_transferred;
285 my $wbytes = $rbytes - ($zero - $last_zero);
287 my $timediff = ($ctime - $last_time) || 1; # fixme
288 my $mbps_read = $get_mbps->($rbytes, $timediff);
289 my $mbps_write = $get_mbps->($wbytes, $timediff);
291 my $statusline = "status: $percent% ($transferred/$total), sparse ${zero_per}% ($zero), duration $duration, read/write $mbps_read/$mbps_write MB/s";
293 my $res = $status->{status
} || 'unknown';
294 if ($res ne 'active') {
295 $self->loginfo($statusline);
296 if ($res ne 'done') {
297 die (($status->{errmsg
} || "unknown error") . "\n") if $res eq 'error';
298 die "got unexpected status '$res'\n";
299 } elsif ($total != $transferred) {
300 die "got wrong number of transfered bytes ($total != $transferred)\n";
304 if ($percent != $last_percent && ($timediff > 2)) {
305 $self->loginfo($statusline);
306 $last_percent = $percent;
307 $last_total = $total if $total;
308 $last_zero = $zero if $zero;
309 $last_transferred = $transferred if $transferred;
315 my $duration = time() - $starttime;
316 if ($transferred && $duration) {
317 my $mb = int($transferred / (1000 * 1000));
318 my $mbps = $get_mbps->($transferred, $duration);
319 $self->loginfo("transferred $mb MB in $duration seconds ($mbps MB/s)");
324 my ($self, $task, $vmid) = @_;
326 my $conffile = "$task->{tmpdir}/qemu-server.conf";
327 my $firewall = "$task->{tmpdir}/qemu-server.fw";
329 my $opts = $self->{vzdump
}->{opts
};
331 my $scfg = $opts->{scfg
};
333 my $starttime = time();
335 my $diskcount = scalar(@{$task->{disks
}});
337 my $server = $scfg->{server
};
338 my $datastore = $scfg->{datastore
};
339 my $username = $scfg->{username
} // 'root@pam';
340 my $fingerprint = $scfg->{fingerprint
};
342 my $repo = "$username\@$server:$datastore";
343 my $password = PVE
::Storage
::PBSPlugin
::pbs_get_password
($scfg, $opts->{storage
});
345 if (PVE
::QemuConfig-
>is_template($self->{vmlist
}->{$vmid}) || !$diskcount) {
347 foreach my $di (@{$task->{disks
}}) {
348 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
349 push @pathlist, "$di->{qmdevice}.img:$di->{path}";
356 $self->loginfo("backup contains no disks");
359 local $ENV{PBS_PASSWORD
} = $password;
361 '/usr/bin/proxmox-backup-client',
363 '--repository', $repo,
364 '--backup-type', 'vm',
365 '--backup-id', "$vmid",
366 '--backup-time', $task->{backup_time
},
369 push @$cmd, '--fingerprint', $fingerprint if defined($fingerprint);
371 push @$cmd, "qemu-server.conf:$conffile";
372 push @$cmd, "fw.conf:$firewall" if -e
$firewall;
373 push @$cmd, @pathlist if scalar(@pathlist);
375 $self->loginfo("starting template backup");
376 $self->loginfo(join(' ', @$cmd));
383 # get list early so we die on unkown drive types before doing anything
384 my $devlist = _get_task_devlist
($task);
386 my ($stop_after_backup, $resume_on_backup) = $self->handle_vm_powerstate($vmid);
387 $self->enforce_vm_running_for_backup($vmid);
391 my $interrupt_msg = "interrupted by signal\n";
393 $SIG{INT
} = $SIG{TERM
} = $SIG{QUIT
} = $SIG{HUP
} = $SIG{PIPE
} = sub {
397 my $fs_frozen = $self->qga_fs_freeze($vmid);
403 'backup-file' => $repo,
404 'backup-id' => "$vmid",
405 'backup-time' => $task->{backup_time
},
406 password
=> $password,
408 'config-file' => $conffile,
410 $params->{fingerprint
} = $fingerprint if defined($fingerprint);
411 $params->{'firewall-file'} = $firewall if -e
$firewall;
412 my $res = mon_cmd
($vmid, "backup", %$params);
413 $backup_job_uuid = $res->{UUID
};
419 $self->qga_fs_thaw($vmid);
422 die $qmperr if $qmperr;
423 die "got no uuid for backup task\n" if !defined($backup_job_uuid);
425 $self->loginfo("started backup task '$backup_job_uuid'");
427 $self->resume_vm_after_job_start($task, $vmid);
429 $query_backup_status_loop->($self, $vmid, $backup_job_uuid);
434 $self->mon_backup_cancel($vmid) if defined($backup_job_uuid);
436 $self->restore_vm_power_state($vmid);
441 my $fork_compressor_pipe = sub {
442 my ($self, $comp, $outfileno) = @_;
444 my @pipefd = POSIX
::pipe();
446 die "unable to fork worker - $!" if !defined($cpid) || $cpid < 0;
449 POSIX
::close($pipefd[1]);
451 my $fd = fileno(STDIN
);
453 POSIX
::close(0) if $fd != 0;
454 die "unable to redirect STDIN - $!"
455 if !open(STDIN
, "<&", $pipefd[0]);
458 $fd = fileno(STDOUT
);
460 POSIX
::close (1) if $fd != 1;
462 die "unable to redirect STDOUT - $!"
463 if !open(STDOUT
, ">&", $outfileno);
466 die "fork compressor '$comp' failed\n";
475 POSIX
::close($pipefd[0]);
476 $outfileno = $pipefd[1];
479 return ($cpid, $outfileno);
483 my ($self, $task, $vmid, $filename, $comp) = @_;
485 my $conffile = "$task->{tmpdir}/qemu-server.conf";
486 my $firewall = "$task->{tmpdir}/qemu-server.fw";
488 my $opts = $self->{vzdump
}->{opts
};
490 my $starttime = time();
493 if ($opts->{bwlimit
}) {
494 $speed = $opts->{bwlimit
}*1024;
497 my $diskcount = scalar(@{$task->{disks
}});
499 if (PVE
::QemuConfig-
>is_template($self->{vmlist
}->{$vmid}) || !$diskcount) {
501 foreach my $di (@{$task->{disks
}}) {
502 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
503 push @pathlist, "$di->{qmdevice}=$di->{path}";
510 $self->loginfo("backup contains no disks");
515 $outcmd = "exec:$comp";
517 $outcmd = "exec:cat";
520 $outcmd .= " > $filename" if !$opts->{stdout
};
522 my $cmd = ['/usr/bin/vma', 'create', '-v', '-c', $conffile];
523 push @$cmd, '-c', $firewall if -e
$firewall;
524 push @$cmd, $outcmd, @pathlist;
526 $self->loginfo("starting template backup");
527 $self->loginfo(join(' ', @$cmd));
529 if ($opts->{stdout
}) {
530 $self->cmd($cmd, output
=> ">&=" . fileno($opts->{stdout
}));
538 my $devlist = _get_task_devlist
($task);
540 $self->enforce_vm_running_for_backup($vmid);
545 my $interrupt_msg = "interrupted by signal\n";
547 $SIG{INT
} = $SIG{TERM
} = $SIG{QUIT
} = $SIG{HUP
} = $SIG{PIPE
} = sub {
551 my $qmpclient = PVE
::QMPClient-
>new();
553 my $backup_cb = sub {
554 my ($vmid, $resp) = @_;
555 $backup_job_uuid = $resp->{return}->{UUID
};
559 if ($opts->{stdout
}) {
560 $outfh = $opts->{stdout
};
562 $outfh = IO
::File-
>new($filename, "w") ||
563 die "unable to open file '$filename' - $!\n";
565 my $outfileno = fileno($outfh);
568 ($cpid, $outfileno) = $fork_compressor_pipe->($self, $comp, $outfileno);
571 my $add_fd_cb = sub {
572 my ($vmid, $resp) = @_;
575 'backup-file' => "/dev/fdname/backup",
577 'config-file' => $conffile,
581 $params->{'firewall-file'} = $firewall if -e
$firewall;
582 $qmpclient->queue_cmd($vmid, $backup_cb, 'backup', %$params);
585 $qmpclient->queue_cmd($vmid, $add_fd_cb, 'getfd',
586 fd
=> $outfileno, fdname
=> "backup");
588 my $fs_frozen = $self->qga_fs_freeze($vmid);
590 eval { $qmpclient->queue_execute(30) };
594 $self->qga_fs_thaw($vmid);
596 die $qmperr if $qmperr;
597 die $qmpclient->{errors
}->{$vmid} if $qmpclient->{errors
}->{$vmid};
600 POSIX
::close($outfileno) == 0 ||
601 die "close output file handle failed\n";
604 die "got no uuid for backup task\n" if !defined($backup_job_uuid);
606 $self->loginfo("started backup task '$backup_job_uuid'");
608 $self->resume_vm_after_job_start($task, $vmid);
610 $query_backup_status_loop->($self, $vmid, $backup_job_uuid);
615 $self->mon_backup_cancel($vmid) if defined($backup_job_uuid);
618 $self->restore_vm_power_state($vmid);
628 if ($cpid && (waitpid($cpid, 0) > 0)) {
631 my $signal = $stat & 127;
632 if ($ec || $signal) {
633 die "$comp failed - wrong exit status $ec" .
634 ($signal ?
" (signal $signal)\n" : "\n");
639 sub _get_task_devlist
{
643 foreach my $di (@{$task->{disks
}}) {
644 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
645 $devlist .= ',' if $devlist;
646 $devlist .= $di->{qmdevice
};
648 die "implement me (type '$di->{type}')";
655 my ($self, $vmid) = @_;
656 return if !$self->{vmlist
}->{$vmid}->{agent
} || !$self->{vm_was_running
};
658 if (!PVE
::QemuServer
::qga_check_running
($vmid, 1)) {
659 $self->loginfo("skipping guest-agent 'fs-freeze', agent configured but not running?");
663 $self->loginfo("issuing guest-agent 'fs-freeze' command");
664 eval { mon_cmd
($vmid, "guest-fsfreeze-freeze") };
665 $self->logerr($@) if $@;
667 return 1; # even on mon command error, ensure we always thaw again
670 # only call if fs_freeze return 1
672 my ($self, $vmid) = @_;
674 $self->loginfo("issuing guest-agent 'fs-thaw' command");
675 eval { mon_cmd
($vmid, "guest-fsfreeze-thaw") };
676 $self->logerr($@) if $@;
679 # we need a running QEMU/KVM process for backup, starts a paused (prelaunch)
680 # one if VM isn't already running
681 sub enforce_vm_running_for_backup
{
682 my ($self, $vmid) = @_;
684 if (PVE
::QemuServer
::check_running
($vmid)) {
685 $self->{vm_was_running
} = 1;
690 $self->loginfo("starting kvm to execute backup task");
691 # start with skiplock
692 PVE
::QemuServer
::vm_start
($self->{storecfg
}, $vmid, undef, 1, undef, 1);
697 # resume VM againe once we got in a clear state (stop mode backup of running VM)
698 sub resume_vm_after_job_start
{
699 my ($self, $task, $vmid) = @_;
701 return if !$self->{vm_was_running
};
703 if (my $stoptime = $task->{vmstoptime
}) {
704 my $delay = time() - $task->{vmstoptime
};
705 $task->{vmstoptime
} = undef; # avoid printing 'online after ..' twice
706 $self->loginfo("resuming VM again after $delay seconds");
708 $self->loginfo("resuming VM again");
710 mon_cmd
($vmid, 'cont');
713 # stop again if VM was not running before
714 sub restore_vm_power_state
{
715 my ($self, $vmid) = @_;
717 # we always let VMs keep running
718 return if $self->{vm_was_running
};
721 my $resp = mon_cmd
($vmid, 'query-status');
722 my $status = $resp && $resp->{status
} ?
$resp->{status
} : 'unknown';
723 if ($status eq 'prelaunch') {
724 $self->loginfo("stopping kvm after backup task");
725 PVE
::QemuServer
::vm_stop
($self->{storecfg
}, $vmid, 1);
727 $self->loginfo("kvm status changed after backup ('$status') - keep VM running");
733 sub mon_backup_cancel
{
734 my ($self, $vmid) = @_;
736 $self->loginfo("aborting backup job");
737 eval { mon_cmd
($vmid, 'backup-cancel') };
738 $self->logerr($@) if $@;
742 my ($self, $task, $vmid) = @_;
748 my ($self, $task, $vmid) = @_;