1 package PVE
::VZDump
::QemuServer
;
11 use PVE
::Cluster
qw(cfs_read_file);
16 use PVE
::Storage
::Plugin
;
17 use PVE
::Storage
::PBSPlugin
;
24 use PVE
::QemuServer
::Machine
;
25 use PVE
::QemuServer
::Monitor
qw(mon_cmd);
27 use base qw
(PVE
::VZDump
::Plugin
);
30 my ($class, $vzdump) = @_;
32 PVE
::VZDump
::check_bin
('qm');
34 my $self = bless { vzdump
=> $vzdump }, $class;
36 $self->{vmlist
} = PVE
::QemuServer
::vzlist
();
37 $self->{storecfg
} = PVE
::Storage
::config
();
48 return [ keys %{$self->{vmlist
}} ];
52 my ($self, $task, $vmid, $mode) = @_;
56 my $conf = $self->{vmlist
}->{$vmid} = PVE
::QemuConfig-
>load_config($vmid);
58 $self->loginfo("VM Name: $conf->{name}")
59 if defined($conf->{name
});
61 $self->{vm_was_running
} = 1;
62 if (!PVE
::QemuServer
::check_running
($vmid)) {
63 $self->{vm_was_running
} = 0;
66 $task->{hostname
} = $conf->{name
};
68 my $hostname = PVE
::INotify
::nodename
();
72 PVE
::QemuConfig-
>foreach_volume($conf, sub {
73 my ($ds, $drive) = @_;
75 return if PVE
::QemuServer
::drive_is_cdrom
($drive);
77 my $volid = $drive->{file
};
79 if (defined($drive->{backup
}) && !$drive->{backup
}) {
80 $self->loginfo("exclude disk '$ds' '$volid' (backup=no)");
82 } elsif ($self->{vm_was_running
} && $drive->{iothread
}) {
83 if (!PVE
::QemuServer
::Machine
::runs_at_least_qemu_version
($vmid, 4, 0, 1)) {
84 die "disk '$ds' '$volid' (iothread=on) can't use backup feature with running QEMU " .
85 "version < 4.0.1! Either set backup=no for this drive or upgrade QEMU and restart VM\n";
87 } elsif ($ds =~ m/^efidisk/ && (!defined($conf->{bios
}) || $conf->{bios
} ne 'ovmf')) {
88 $self->loginfo("excluding '$ds' (efidisks can only be backed up when BIOS is set to 'ovmf')");
91 my $log = "include disk '$ds' '$volid'";
92 if (defined $drive->{size
}) {
93 my $readable_size = PVE
::JSONSchema
::format_size
($drive->{size
});
94 $log .= " $readable_size";
99 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
100 push @$vollist, $volid if $storeid;
101 $drivehash->{$ds} = $drive;
104 PVE
::Storage
::activate_volumes
($self->{storecfg
}, $vollist);
106 foreach my $ds (sort keys %$drivehash) {
107 my $drive = $drivehash->{$ds};
109 my $volid = $drive->{file
};
110 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
114 $path = PVE
::Storage
::path
($self->{storecfg
}, $volid);
118 my ($size, $format) = eval { PVE
::Storage
::volume_size_info
($self->{storecfg
}, $volid, 5) };
119 die "no such volume '$volid'\n" if $@;
127 qmdevice
=> "drive-$ds",
131 $diskinfo->{type
} = 'block';
133 $diskinfo->{type
} = 'file';
136 push @{$task->{disks
}}, $diskinfo;
141 my ($self, $vmid) = @_;
143 my $running = PVE
::QemuServer
::check_running
($vmid) ?
1 : 0;
145 return wantarray ?
($running, $running ?
'running' : 'stopped') : $running;
149 my ($self, $vmid) = @_;
151 PVE
::QemuConfig-
>set_lock($vmid, 'backup');
155 my ($self, $vmid) = @_;
157 PVE
::QemuConfig-
>remove_lock($vmid, 'backup');
161 my ($self, $task, $vmid) = @_;
163 my $opts = $self->{vzdump
}->{opts
};
165 my $wait = $opts->{stopwait
} * 60;
166 # send shutdown and wait
167 $self->cmd ("qm shutdown $vmid --skiplock --keepActive --timeout $wait");
171 my ($self, $task, $vmid) = @_;
173 $self->cmd ("qm start $vmid --skiplock");
177 my ($self, $task, $vmid) = @_;
179 $self->cmd ("qm suspend $vmid --skiplock");
183 my ($self, $task, $vmid) = @_;
185 $self->cmd ("qm resume $vmid --skiplock");
189 my ($self, $task, $vmid) = @_;
191 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
193 my $outfile = "$task->{tmpdir}/qemu-server.conf";
194 my $firewall_src = "/etc/pve/firewall/$vmid.fw";
195 my $firewall_dest = "$task->{tmpdir}/qemu-server.fw";
197 my $outfd = IO
::File-
>new (">$outfile") ||
198 die "unable to open '$outfile'";
199 my $conffd = IO
::File-
>new ($conffile, 'r') ||
200 die "unable open '$conffile'";
204 while (defined (my $line = <$conffd>)) {
205 next if $line =~ m/^\#vzdump\#/; # just to be sure
206 next if $line =~ m/^\#qmdump\#/; # just to be sure
207 if ($line =~ m/^\[(.*)\]\s*$/) {
208 if ($1 =~ m/PENDING/i) {
214 next if $found_snapshot || $found_pending; # skip all snapshots and pending changes config data
216 if ($line =~ m/^unused\d+:\s*(\S+)\s*/) {
217 $self->loginfo("skip unused drive '$1' (not included into backup)");
220 next if $line =~ m/^lock:/ || $line =~ m/^parent:/;
225 foreach my $di (@{$task->{disks
}}) {
226 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
227 my $storeid = $di->{storeid
} || '';
228 my $format = $di->{format
} || '';
229 print $outfd "#qmdump#map:$di->{virtdev}:$di->{qmdevice}:$storeid:$format:\n";
231 die "internal error";
235 if ($found_snapshot) {
236 $self->loginfo("snapshots found (not included into backup)");
238 if ($found_pending) {
239 $self->loginfo("pending configuration changes found (not included into backup)");
242 PVE
::Tools
::file_copy
($firewall_src, $firewall_dest) if -f
$firewall_src;
246 my ($self, $task, $vmid, $filename, $comp) = @_;
248 my $opts = $self->{vzdump
}->{opts
};
249 my $scfg = $opts->{scfg
};
251 if ($self->{vzdump
}->{opts
}->{pbs
}) {
252 $self->archive_pbs($task, $vmid);
254 $self->archive_vma($task, $vmid, $filename, $comp);
258 my $query_backup_status_loop = sub {
259 my ($self, $vmid, $job_uuid) = @_;
261 my $starttime = time ();
262 my $last_time = $starttime;
263 my ($last_percent, $last_total, $last_zero, $last_transferred) = (-1, 0, 0, 0);
267 my ($mb, $delta) = @_;
268 return ($mb > 0) ?
int(($mb / $delta) / (1000 * 1000)) : 0;
272 my $status = mon_cmd
($vmid, 'query-backup');
274 my $total = $status->{total
} || 0;
275 $transferred = $status->{transferred
} || 0;
276 my $percent = $total ?
int(($transferred * 100)/$total) : 0;
277 my $zero = $status->{'zero-bytes'} || 0;
278 my $zero_per = $total ?
int(($zero * 100)/$total) : 0;
280 die "got unexpected uuid\n" if !$status->{uuid
} || ($status->{uuid
} ne $job_uuid);
283 my $duration = $ctime - $starttime;
285 my $rbytes = $transferred - $last_transferred;
286 my $wbytes = $rbytes - ($zero - $last_zero);
288 my $timediff = ($ctime - $last_time) || 1; # fixme
289 my $mbps_read = $get_mbps->($rbytes, $timediff);
290 my $mbps_write = $get_mbps->($wbytes, $timediff);
292 my $statusline = "status: $percent% ($transferred/$total), sparse ${zero_per}% ($zero), duration $duration, read/write $mbps_read/$mbps_write MB/s";
294 my $res = $status->{status
} || 'unknown';
295 if ($res ne 'active') {
296 $self->loginfo($statusline);
297 if ($res ne 'done') {
298 die (($status->{errmsg
} || "unknown error") . "\n") if $res eq 'error';
299 die "got unexpected status '$res'\n";
300 } elsif ($total != $transferred) {
301 die "got wrong number of transfered bytes ($total != $transferred)\n";
305 if ($percent != $last_percent && ($timediff > 2)) {
306 $self->loginfo($statusline);
307 $last_percent = $percent;
308 $last_total = $total if $total;
309 $last_zero = $zero if $zero;
310 $last_transferred = $transferred if $transferred;
316 my $duration = time() - $starttime;
317 if ($transferred && $duration) {
318 my $mb = int($transferred / (1000 * 1000));
319 my $mbps = $get_mbps->($transferred, $duration);
320 $self->loginfo("transferred $mb MB in $duration seconds ($mbps MB/s)");
325 my ($self, $task, $vmid) = @_;
327 my $conffile = "$task->{tmpdir}/qemu-server.conf";
328 my $firewall = "$task->{tmpdir}/qemu-server.fw";
330 my $opts = $self->{vzdump
}->{opts
};
331 my $scfg = $opts->{scfg
};
333 my $starttime = time();
335 my $server = $scfg->{server
};
336 my $datastore = $scfg->{datastore
};
337 my $username = $scfg->{username
} // 'root@pam';
338 my $fingerprint = $scfg->{fingerprint
};
340 my $repo = "$username\@$server:$datastore";
341 my $password = PVE
::Storage
::PBSPlugin
::pbs_get_password
($scfg, $opts->{storage
});
343 my $diskcount = scalar(@{$task->{disks
}});
344 if (PVE
::QemuConfig-
>is_template($self->{vmlist
}->{$vmid}) || !$diskcount) {
346 foreach my $di (@{$task->{disks
}}) {
347 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
348 push @pathlist, "$di->{qmdevice}.img:$di->{path}";
350 die "implement me (type $di->{type})";
355 $self->loginfo("backup contains no disks");
358 local $ENV{PBS_PASSWORD
} = $password;
359 local $ENV{PBS_FINGERPRINT
} = $fingerprint if defined($fingerprint);
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, "qemu-server.conf:$conffile";
370 push @$cmd, "fw.conf:$firewall" if -e
$firewall;
371 push @$cmd, @pathlist if scalar(@pathlist);
373 $self->loginfo("starting template backup");
374 $self->loginfo(join(' ', @$cmd));
381 # get list early so we die on unkown drive types before doing anything
382 my $devlist = _get_task_devlist
($task);
384 $self->enforce_vm_running_for_backup($vmid);
388 $SIG{INT
} = $SIG{TERM
} = $SIG{QUIT
} = $SIG{HUP
} = $SIG{PIPE
} = sub {
389 die "interrupted by signal\n";
392 my $fs_frozen = $self->qga_fs_freeze($task, $vmid);
396 'backup-file' => $repo,
397 'backup-id' => "$vmid",
398 'backup-time' => $task->{backup_time
},
399 password
=> $password,
401 'config-file' => $conffile,
403 $params->{fingerprint
} = $fingerprint if defined($fingerprint);
404 $params->{'firewall-file'} = $firewall if -e
$firewall;
406 my $res = eval { mon_cmd
($vmid, "backup", %$params) };
408 $backup_job_uuid = $res->{UUID
} if $res;
411 $self->qga_fs_thaw($vmid);
414 die $qmperr if $qmperr;
415 die "got no uuid for backup task\n" if !defined($backup_job_uuid);
417 $self->loginfo("started backup task '$backup_job_uuid'");
419 $self->resume_vm_after_job_start($task, $vmid);
421 $query_backup_status_loop->($self, $vmid, $backup_job_uuid);
426 $self->mon_backup_cancel($vmid) if defined($backup_job_uuid);
428 $self->restore_vm_power_state($vmid);
433 my $fork_compressor_pipe = sub {
434 my ($self, $comp, $outfileno) = @_;
436 my @pipefd = POSIX
::pipe();
438 die "unable to fork worker - $!" if !defined($cpid) || $cpid < 0;
441 POSIX
::close($pipefd[1]);
443 my $fd = fileno(STDIN
);
445 POSIX
::close(0) if $fd != 0;
446 die "unable to redirect STDIN - $!"
447 if !open(STDIN
, "<&", $pipefd[0]);
450 $fd = fileno(STDOUT
);
452 POSIX
::close (1) if $fd != 1;
454 die "unable to redirect STDOUT - $!"
455 if !open(STDOUT
, ">&", $outfileno);
458 die "fork compressor '$comp' failed\n";
467 POSIX
::close($pipefd[0]);
468 $outfileno = $pipefd[1];
471 return ($cpid, $outfileno);
475 my ($self, $task, $vmid, $filename, $comp) = @_;
477 my $conffile = "$task->{tmpdir}/qemu-server.conf";
478 my $firewall = "$task->{tmpdir}/qemu-server.fw";
480 my $opts = $self->{vzdump
}->{opts
};
482 my $starttime = time();
485 if ($opts->{bwlimit
}) {
486 $speed = $opts->{bwlimit
}*1024;
489 my $diskcount = scalar(@{$task->{disks
}});
490 if (PVE
::QemuConfig-
>is_template($self->{vmlist
}->{$vmid}) || !$diskcount) {
492 foreach my $di (@{$task->{disks
}}) {
493 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
494 push @pathlist, "$di->{qmdevice}=$di->{path}";
501 $self->loginfo("backup contains no disks");
506 $outcmd = "exec:$comp";
508 $outcmd = "exec:cat";
511 $outcmd .= " > $filename" if !$opts->{stdout
};
513 my $cmd = ['/usr/bin/vma', 'create', '-v', '-c', $conffile];
514 push @$cmd, '-c', $firewall if -e
$firewall;
515 push @$cmd, $outcmd, @pathlist;
517 $self->loginfo("starting template backup");
518 $self->loginfo(join(' ', @$cmd));
520 if ($opts->{stdout
}) {
521 $self->cmd($cmd, output
=> ">&" . fileno($opts->{stdout
}));
529 my $devlist = _get_task_devlist
($task);
531 $self->enforce_vm_running_for_backup($vmid);
537 $SIG{INT
} = $SIG{TERM
} = $SIG{QUIT
} = $SIG{HUP
} = $SIG{PIPE
} = sub {
538 die "interrupted by signal\n";
542 if ($opts->{stdout
}) {
543 $outfh = $opts->{stdout
};
545 $outfh = IO
::File-
>new($filename, "w") ||
546 die "unable to open file '$filename' - $!\n";
548 my $outfileno = fileno($outfh);
551 ($cpid, $outfileno) = $fork_compressor_pipe->($self, $comp, $outfileno);
554 my $qmpclient = PVE
::QMPClient-
>new();
555 my $backup_cb = sub {
556 my ($vmid, $resp) = @_;
557 $backup_job_uuid = $resp->{return}->{UUID
};
559 my $add_fd_cb = sub {
560 my ($vmid, $resp) = @_;
563 'backup-file' => "/dev/fdname/backup",
565 'config-file' => $conffile,
568 $params->{'firewall-file'} = $firewall if -e
$firewall;
570 $qmpclient->queue_cmd($vmid, $backup_cb, 'backup', %$params);
573 $qmpclient->queue_cmd($vmid, $add_fd_cb, 'getfd', fd
=> $outfileno, fdname
=> "backup");
575 my $fs_frozen = $self->qga_fs_freeze($task, $vmid);
577 eval { $qmpclient->queue_execute(30) };
581 $self->qga_fs_thaw($vmid);
584 die $qmperr if $qmperr;
585 die $qmpclient->{errors
}->{$vmid} if $qmpclient->{errors
}->{$vmid};
588 POSIX
::close($outfileno) == 0 ||
589 die "close output file handle failed\n";
592 die "got no uuid for backup task\n" if !defined($backup_job_uuid);
594 $self->loginfo("started backup task '$backup_job_uuid'");
596 $self->resume_vm_after_job_start($task, $vmid);
598 $query_backup_status_loop->($self, $vmid, $backup_job_uuid);
603 $self->mon_backup_cancel($vmid) if defined($backup_job_uuid);
606 $self->restore_vm_power_state($vmid);
616 if ($cpid && (waitpid($cpid, 0) > 0)) {
619 my $signal = $stat & 127;
620 if ($ec || $signal) {
621 die "$comp failed - wrong exit status $ec" .
622 ($signal ?
" (signal $signal)\n" : "\n");
627 sub _get_task_devlist
{
631 foreach my $di (@{$task->{disks
}}) {
632 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
633 $devlist .= ',' if $devlist;
634 $devlist .= $di->{qmdevice
};
636 die "implement me (type '$di->{type}')";
643 my ($self, $task, $vmid) = @_;
644 return if !$self->{vmlist
}->{$vmid}->{agent
} || $task->{mode
} eq 'stop' || !$self->{vm_was_running
};
646 if (!PVE
::QemuServer
::qga_check_running
($vmid, 1)) {
647 $self->loginfo("skipping guest-agent 'fs-freeze', agent configured but not running?");
651 $self->loginfo("issuing guest-agent 'fs-freeze' command");
652 eval { mon_cmd
($vmid, "guest-fsfreeze-freeze") };
653 $self->logerr($@) if $@;
655 return 1; # even on mon command error, ensure we always thaw again
658 # only call if fs_freeze return 1
660 my ($self, $vmid) = @_;
662 $self->loginfo("issuing guest-agent 'fs-thaw' command");
663 eval { mon_cmd
($vmid, "guest-fsfreeze-thaw") };
664 $self->logerr($@) if $@;
667 # we need a running QEMU/KVM process for backup, starts a paused (prelaunch)
668 # one if VM isn't already running
669 sub enforce_vm_running_for_backup
{
670 my ($self, $vmid) = @_;
672 if (PVE
::QemuServer
::check_running
($vmid)) {
673 $self->{vm_was_running
} = 1;
678 $self->loginfo("starting kvm to execute backup task");
679 # start with skiplock
684 PVE
::QemuServer
::vm_start
($self->{storecfg
}, $vmid, $params);
689 # resume VM againe once we got in a clear state (stop mode backup of running VM)
690 sub resume_vm_after_job_start
{
691 my ($self, $task, $vmid) = @_;
693 return if !$self->{vm_was_running
};
695 if (my $stoptime = $task->{vmstoptime
}) {
696 my $delay = time() - $task->{vmstoptime
};
697 $task->{vmstoptime
} = undef; # avoid printing 'online after ..' twice
698 $self->loginfo("resuming VM again after $delay seconds");
700 $self->loginfo("resuming VM again");
702 mon_cmd
($vmid, 'cont');
705 # stop again if VM was not running before
706 sub restore_vm_power_state
{
707 my ($self, $vmid) = @_;
709 # we always let VMs keep running
710 return if $self->{vm_was_running
};
713 my $resp = mon_cmd
($vmid, 'query-status');
714 my $status = $resp && $resp->{status
} ?
$resp->{status
} : 'unknown';
715 if ($status eq 'prelaunch') {
716 $self->loginfo("stopping kvm after backup task");
717 PVE
::QemuServer
::vm_stop
($self->{storecfg
}, $vmid, 1);
719 $self->loginfo("kvm status changed after backup ('$status') - keep VM running");
725 sub mon_backup_cancel
{
726 my ($self, $vmid) = @_;
728 $self->loginfo("aborting backup job");
729 eval { mon_cmd
($vmid, 'backup-cancel') };
730 $self->logerr($@) if $@;
734 my ($self, $task, $vmid) = @_;
740 my ($self, $task, $vmid) = @_;