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 my $backup_volumes = PVE
::QemuConfig-
>get_backup_volumes($conf);
74 foreach my $volume (@{$backup_volumes}) {
75 my $name = $volume->{key
};
76 my $volume_config = $volume->{volume_config
};
77 my $volid = $volume_config->{file
};
79 if (!$volume->{included
}) {
80 $self->loginfo("exclude disk '$name' '$volid' ($volume->{reason})");
82 } elsif ($self->{vm_was_running
} && $volume_config->{iothread
}) {
83 if (!PVE
::QemuServer
::Machine
::runs_at_least_qemu_version
($vmid, 4, 0, 1)) {
84 die "disk '$name' '$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";
88 my $log = "include disk '$name' '$volid'";
89 if (defined(my $size = $volume_config->{size
})) {
90 my $readable_size = PVE
::JSONSchema
::format_size
($size);
91 $log .= " $readable_size";
96 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
97 push @$vollist, $volid if $storeid;
98 $drivehash->{$name} = $volume->{volume_config
};
101 PVE
::Storage
::activate_volumes
($self->{storecfg
}, $vollist);
103 foreach my $ds (sort keys %$drivehash) {
104 my $drive = $drivehash->{$ds};
106 my $volid = $drive->{file
};
107 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
111 $path = PVE
::Storage
::path
($self->{storecfg
}, $volid);
115 my ($size, $format) = eval { PVE
::Storage
::volume_size_info
($self->{storecfg
}, $volid, 5) };
116 die "no such volume '$volid'\n" if $@;
124 qmdevice
=> "drive-$ds",
128 $diskinfo->{type
} = 'block';
130 $diskinfo->{type
} = 'file';
133 push @{$task->{disks
}}, $diskinfo;
138 my ($self, $vmid) = @_;
140 my $running = PVE
::QemuServer
::check_running
($vmid) ?
1 : 0;
142 return wantarray ?
($running, $running ?
'running' : 'stopped') : $running;
146 my ($self, $vmid) = @_;
148 PVE
::QemuConfig-
>set_lock($vmid, 'backup');
152 my ($self, $vmid) = @_;
154 PVE
::QemuConfig-
>remove_lock($vmid, 'backup');
158 my ($self, $task, $vmid) = @_;
160 my $opts = $self->{vzdump
}->{opts
};
162 my $wait = $opts->{stopwait
} * 60;
163 # send shutdown and wait
164 $self->cmd ("qm shutdown $vmid --skiplock --keepActive --timeout $wait");
168 my ($self, $task, $vmid) = @_;
170 $self->cmd ("qm start $vmid --skiplock");
174 my ($self, $task, $vmid) = @_;
176 $self->cmd ("qm suspend $vmid --skiplock");
180 my ($self, $task, $vmid) = @_;
182 $self->cmd ("qm resume $vmid --skiplock");
186 my ($self, $task, $vmid) = @_;
188 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
190 my $outfile = "$task->{tmpdir}/qemu-server.conf";
191 my $firewall_src = "/etc/pve/firewall/$vmid.fw";
192 my $firewall_dest = "$task->{tmpdir}/qemu-server.fw";
194 my $outfd = IO
::File-
>new (">$outfile") ||
195 die "unable to open '$outfile'";
196 my $conffd = IO
::File-
>new ($conffile, 'r') ||
197 die "unable open '$conffile'";
201 while (defined (my $line = <$conffd>)) {
202 next if $line =~ m/^\#vzdump\#/; # just to be sure
203 next if $line =~ m/^\#qmdump\#/; # just to be sure
204 if ($line =~ m/^\[(.*)\]\s*$/) {
205 if ($1 =~ m/PENDING/i) {
211 next if $found_snapshot || $found_pending; # skip all snapshots and pending changes config data
213 if ($line =~ m/^unused\d+:\s*(\S+)\s*/) {
214 $self->loginfo("skip unused drive '$1' (not included into backup)");
217 next if $line =~ m/^lock:/ || $line =~ m/^parent:/;
222 foreach my $di (@{$task->{disks
}}) {
223 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
224 my $storeid = $di->{storeid
} || '';
225 my $format = $di->{format
} || '';
226 print $outfd "#qmdump#map:$di->{virtdev}:$di->{qmdevice}:$storeid:$format:\n";
228 die "internal error";
232 if ($found_snapshot) {
233 $self->loginfo("snapshots found (not included into backup)");
235 if ($found_pending) {
236 $self->loginfo("pending configuration changes found (not included into backup)");
239 PVE
::Tools
::file_copy
($firewall_src, $firewall_dest) if -f
$firewall_src;
243 my ($self, $task, $vmid, $filename, $comp) = @_;
245 my $opts = $self->{vzdump
}->{opts
};
246 my $scfg = $opts->{scfg
};
248 if ($self->{vzdump
}->{opts
}->{pbs
}) {
249 $self->archive_pbs($task, $vmid);
251 $self->archive_vma($task, $vmid, $filename, $comp);
255 my $query_backup_status_loop = sub {
256 my ($self, $vmid, $job_uuid) = @_;
258 my $starttime = time ();
259 my $last_time = $starttime;
260 my ($last_percent, $last_total, $last_zero, $last_transferred) = (-1, 0, 0, 0);
264 my ($mb, $delta) = @_;
265 return ($mb > 0) ?
int(($mb / $delta) / (1000 * 1000)) : 0;
269 my $status = mon_cmd
($vmid, 'query-backup');
271 my $total = $status->{total
} || 0;
272 $transferred = $status->{transferred
} || 0;
273 my $percent = $total ?
int(($transferred * 100)/$total) : 0;
274 my $zero = $status->{'zero-bytes'} || 0;
275 my $zero_per = $total ?
int(($zero * 100)/$total) : 0;
277 die "got unexpected uuid\n" if !$status->{uuid
} || ($status->{uuid
} ne $job_uuid);
280 my $duration = $ctime - $starttime;
282 my $rbytes = $transferred - $last_transferred;
283 my $wbytes = $rbytes - ($zero - $last_zero);
285 my $timediff = ($ctime - $last_time) || 1; # fixme
286 my $mbps_read = $get_mbps->($rbytes, $timediff);
287 my $mbps_write = $get_mbps->($wbytes, $timediff);
289 my $statusline = "status: $percent% ($transferred/$total), sparse ${zero_per}% ($zero), duration $duration, read/write $mbps_read/$mbps_write MB/s";
291 my $res = $status->{status
} || 'unknown';
292 if ($res ne 'active') {
293 $self->loginfo($statusline);
294 if ($res ne 'done') {
295 die (($status->{errmsg
} || "unknown error") . "\n") if $res eq 'error';
296 die "got unexpected status '$res'\n";
297 } elsif ($total != $transferred) {
298 die "got wrong number of transfered bytes ($total != $transferred)\n";
302 if ($percent != $last_percent && ($timediff > 2)) {
303 $self->loginfo($statusline);
304 $last_percent = $percent;
305 $last_total = $total if $total;
306 $last_zero = $zero if $zero;
307 $last_transferred = $transferred if $transferred;
313 my $duration = time() - $starttime;
314 if ($transferred && $duration) {
315 my $mb = int($transferred / (1000 * 1000));
316 my $mbps = $get_mbps->($transferred, $duration);
317 $self->loginfo("transferred $mb MB in $duration seconds ($mbps MB/s)");
322 my ($self, $task, $vmid) = @_;
324 my $conffile = "$task->{tmpdir}/qemu-server.conf";
325 my $firewall = "$task->{tmpdir}/qemu-server.fw";
327 my $opts = $self->{vzdump
}->{opts
};
328 my $scfg = $opts->{scfg
};
330 my $starttime = time();
332 my $server = $scfg->{server
};
333 my $datastore = $scfg->{datastore
};
334 my $username = $scfg->{username
} // 'root@pam';
335 my $fingerprint = $scfg->{fingerprint
};
337 my $repo = "$username\@$server:$datastore";
338 my $password = PVE
::Storage
::PBSPlugin
::pbs_get_password
($scfg, $opts->{storage
});
340 my $diskcount = scalar(@{$task->{disks
}});
341 if (PVE
::QemuConfig-
>is_template($self->{vmlist
}->{$vmid}) || !$diskcount) {
343 foreach my $di (@{$task->{disks
}}) {
344 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
345 push @pathlist, "$di->{qmdevice}.img:$di->{path}";
347 die "implement me (type $di->{type})";
352 $self->loginfo("backup contains no disks");
355 local $ENV{PBS_PASSWORD
} = $password;
356 local $ENV{PBS_FINGERPRINT
} = $fingerprint if defined($fingerprint);
358 '/usr/bin/proxmox-backup-client',
360 '--repository', $repo,
361 '--backup-type', 'vm',
362 '--backup-id', "$vmid",
363 '--backup-time', $task->{backup_time
},
366 push @$cmd, "qemu-server.conf:$conffile";
367 push @$cmd, "fw.conf:$firewall" if -e
$firewall;
368 push @$cmd, @pathlist if scalar(@pathlist);
370 $self->loginfo("starting template backup");
371 $self->loginfo(join(' ', @$cmd));
378 # get list early so we die on unkown drive types before doing anything
379 my $devlist = _get_task_devlist
($task);
381 $self->enforce_vm_running_for_backup($vmid);
385 $SIG{INT
} = $SIG{TERM
} = $SIG{QUIT
} = $SIG{HUP
} = $SIG{PIPE
} = sub {
386 die "interrupted by signal\n";
389 my $fs_frozen = $self->qga_fs_freeze($task, $vmid);
393 'backup-file' => $repo,
394 'backup-id' => "$vmid",
395 'backup-time' => $task->{backup_time
},
396 password
=> $password,
398 'config-file' => $conffile,
400 $params->{fingerprint
} = $fingerprint if defined($fingerprint);
401 $params->{'firewall-file'} = $firewall if -e
$firewall;
403 $params->{timeout
} = 60; # give some time to connect to the backup server
405 my $res = eval { mon_cmd
($vmid, "backup", %$params) };
407 $backup_job_uuid = $res->{UUID
} if $res;
410 $self->qga_fs_thaw($vmid);
413 die $qmperr if $qmperr;
414 die "got no uuid for backup task\n" if !defined($backup_job_uuid);
416 $self->loginfo("started backup task '$backup_job_uuid'");
418 $self->resume_vm_after_job_start($task, $vmid);
420 $query_backup_status_loop->($self, $vmid, $backup_job_uuid);
425 $self->mon_backup_cancel($vmid) if defined($backup_job_uuid);
427 $self->restore_vm_power_state($vmid);
432 my $fork_compressor_pipe = sub {
433 my ($self, $comp, $outfileno) = @_;
435 my @pipefd = POSIX
::pipe();
437 die "unable to fork worker - $!" if !defined($cpid) || $cpid < 0;
440 POSIX
::close($pipefd[1]);
442 my $fd = fileno(STDIN
);
444 POSIX
::close(0) if $fd != 0;
445 die "unable to redirect STDIN - $!"
446 if !open(STDIN
, "<&", $pipefd[0]);
449 $fd = fileno(STDOUT
);
451 POSIX
::close (1) if $fd != 1;
453 die "unable to redirect STDOUT - $!"
454 if !open(STDOUT
, ">&", $outfileno);
457 die "fork compressor '$comp' failed\n";
466 POSIX
::close($pipefd[0]);
467 $outfileno = $pipefd[1];
470 return ($cpid, $outfileno);
474 my ($self, $task, $vmid, $filename, $comp) = @_;
476 my $conffile = "$task->{tmpdir}/qemu-server.conf";
477 my $firewall = "$task->{tmpdir}/qemu-server.fw";
479 my $opts = $self->{vzdump
}->{opts
};
481 my $starttime = time();
484 if ($opts->{bwlimit
}) {
485 $speed = $opts->{bwlimit
}*1024;
488 my $diskcount = scalar(@{$task->{disks
}});
489 if (PVE
::QemuConfig-
>is_template($self->{vmlist
}->{$vmid}) || !$diskcount) {
491 foreach my $di (@{$task->{disks
}}) {
492 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
493 push @pathlist, "$di->{qmdevice}=$di->{path}";
500 $self->loginfo("backup contains no disks");
505 $outcmd = "exec:$comp";
507 $outcmd = "exec:cat";
510 $outcmd .= " > $filename" if !$opts->{stdout
};
512 my $cmd = ['/usr/bin/vma', 'create', '-v', '-c', $conffile];
513 push @$cmd, '-c', $firewall if -e
$firewall;
514 push @$cmd, $outcmd, @pathlist;
516 $self->loginfo("starting template backup");
517 $self->loginfo(join(' ', @$cmd));
519 if ($opts->{stdout
}) {
520 $self->cmd($cmd, output
=> ">&" . fileno($opts->{stdout
}));
528 my $devlist = _get_task_devlist
($task);
530 $self->enforce_vm_running_for_backup($vmid);
536 $SIG{INT
} = $SIG{TERM
} = $SIG{QUIT
} = $SIG{HUP
} = $SIG{PIPE
} = sub {
537 die "interrupted by signal\n";
541 if ($opts->{stdout
}) {
542 $outfh = $opts->{stdout
};
544 $outfh = IO
::File-
>new($filename, "w") ||
545 die "unable to open file '$filename' - $!\n";
547 my $outfileno = fileno($outfh);
550 ($cpid, $outfileno) = $fork_compressor_pipe->($self, $comp, $outfileno);
553 my $qmpclient = PVE
::QMPClient-
>new();
554 my $backup_cb = sub {
555 my ($vmid, $resp) = @_;
556 $backup_job_uuid = $resp->{return}->{UUID
};
558 my $add_fd_cb = sub {
559 my ($vmid, $resp) = @_;
562 'backup-file' => "/dev/fdname/backup",
564 'config-file' => $conffile,
567 $params->{'firewall-file'} = $firewall if -e
$firewall;
569 $qmpclient->queue_cmd($vmid, $backup_cb, 'backup', %$params);
572 $qmpclient->queue_cmd($vmid, $add_fd_cb, 'getfd', fd
=> $outfileno, fdname
=> "backup");
574 my $fs_frozen = $self->qga_fs_freeze($task, $vmid);
576 eval { $qmpclient->queue_execute(30) };
580 $self->qga_fs_thaw($vmid);
583 die $qmperr if $qmperr;
584 die $qmpclient->{errors
}->{$vmid} if $qmpclient->{errors
}->{$vmid};
587 POSIX
::close($outfileno) == 0 ||
588 die "close output file handle failed\n";
591 die "got no uuid for backup task\n" if !defined($backup_job_uuid);
593 $self->loginfo("started backup task '$backup_job_uuid'");
595 $self->resume_vm_after_job_start($task, $vmid);
597 $query_backup_status_loop->($self, $vmid, $backup_job_uuid);
602 $self->mon_backup_cancel($vmid) if defined($backup_job_uuid);
605 $self->restore_vm_power_state($vmid);
615 if ($cpid && (waitpid($cpid, 0) > 0)) {
618 my $signal = $stat & 127;
619 if ($ec || $signal) {
620 die "$comp failed - wrong exit status $ec" .
621 ($signal ?
" (signal $signal)\n" : "\n");
626 sub _get_task_devlist
{
630 foreach my $di (@{$task->{disks
}}) {
631 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
632 $devlist .= ',' if $devlist;
633 $devlist .= $di->{qmdevice
};
635 die "implement me (type '$di->{type}')";
642 my ($self, $task, $vmid) = @_;
643 return if !$self->{vmlist
}->{$vmid}->{agent
} || $task->{mode
} eq 'stop' || !$self->{vm_was_running
};
645 if (!PVE
::QemuServer
::qga_check_running
($vmid, 1)) {
646 $self->loginfo("skipping guest-agent 'fs-freeze', agent configured but not running?");
650 $self->loginfo("issuing guest-agent 'fs-freeze' command");
651 eval { mon_cmd
($vmid, "guest-fsfreeze-freeze") };
652 $self->logerr($@) if $@;
654 return 1; # even on mon command error, ensure we always thaw again
657 # only call if fs_freeze return 1
659 my ($self, $vmid) = @_;
661 $self->loginfo("issuing guest-agent 'fs-thaw' command");
662 eval { mon_cmd
($vmid, "guest-fsfreeze-thaw") };
663 $self->logerr($@) if $@;
666 # we need a running QEMU/KVM process for backup, starts a paused (prelaunch)
667 # one if VM isn't already running
668 sub enforce_vm_running_for_backup
{
669 my ($self, $vmid) = @_;
671 if (PVE
::QemuServer
::check_running
($vmid)) {
672 $self->{vm_was_running
} = 1;
677 $self->loginfo("starting kvm to execute backup task");
678 # start with skiplock
683 PVE
::QemuServer
::vm_start
($self->{storecfg
}, $vmid, $params);
688 # resume VM againe once we got in a clear state (stop mode backup of running VM)
689 sub resume_vm_after_job_start
{
690 my ($self, $task, $vmid) = @_;
692 return if !$self->{vm_was_running
};
694 if (my $stoptime = $task->{vmstoptime
}) {
695 my $delay = time() - $task->{vmstoptime
};
696 $task->{vmstoptime
} = undef; # avoid printing 'online after ..' twice
697 $self->loginfo("resuming VM again after $delay seconds");
699 $self->loginfo("resuming VM again");
701 mon_cmd
($vmid, 'cont');
704 # stop again if VM was not running before
705 sub restore_vm_power_state
{
706 my ($self, $vmid) = @_;
708 # we always let VMs keep running
709 return if $self->{vm_was_running
};
712 my $resp = mon_cmd
($vmid, 'query-status');
713 my $status = $resp && $resp->{status
} ?
$resp->{status
} : 'unknown';
714 if ($status eq 'prelaunch') {
715 $self->loginfo("stopping kvm after backup task");
716 PVE
::QemuServer
::vm_stop
($self->{storecfg
}, $vmid, 1);
718 $self->loginfo("kvm status changed after backup ('$status') - keep VM running");
724 sub mon_backup_cancel
{
725 my ($self, $vmid) = @_;
727 $self->loginfo("aborting backup job");
728 eval { mon_cmd
($vmid, 'backup-cancel') };
729 $self->logerr($@) if $@;
733 my ($self, $task, $vmid) = @_;
739 my ($self, $task, $vmid) = @_;