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 my $query_backup_status_loop = sub {
257 my ($self, $vmid, $job_uuid) = @_;
259 my $starttime = time ();
260 my $last_time = $starttime;
261 my ($last_percent, $last_total, $last_zero, $last_transferred) = (-1, 0, 0, 0);
265 my ($mb, $delta) = @_;
266 return ($mb > 0) ?
int(($mb / $delta) / (1000 * 1000)) : 0;
270 my $status = mon_cmd
($vmid, 'query-backup');
272 my $total = $status->{total
} || 0;
273 $transferred = $status->{transferred
} || 0;
274 my $percent = $total ?
int(($transferred * 100)/$total) : 0;
275 my $zero = $status->{'zero-bytes'} || 0;
276 my $zero_per = $total ?
int(($zero * 100)/$total) : 0;
278 die "got unexpected uuid\n" if !$status->{uuid
} || ($status->{uuid
} ne $job_uuid);
281 my $duration = $ctime - $starttime;
283 my $rbytes = $transferred - $last_transferred;
284 my $wbytes = $rbytes - ($zero - $last_zero);
286 my $timediff = ($ctime - $last_time) || 1; # fixme
287 my $mbps_read = $get_mbps->($rbytes, $timediff);
288 my $mbps_write = $get_mbps->($wbytes, $timediff);
290 my $statusline = "status: $percent% ($transferred/$total), sparse ${zero_per}% ($zero), duration $duration, read/write $mbps_read/$mbps_write MB/s";
292 my $res = $status->{status
} || 'unknown';
293 if ($res ne 'active') {
294 $self->loginfo($statusline);
295 if ($res ne 'done') {
296 die (($status->{errmsg
} || "unknown error") . "\n") if $res eq 'error';
297 die "got unexpected status '$res'\n";
298 } elsif ($total != $transferred) {
299 $self->loginfo("backup was done incrementally");
303 if ($percent != $last_percent && ($timediff > 2)) {
304 $self->loginfo($statusline);
305 $last_percent = $percent;
306 $last_total = $total if $total;
307 $last_zero = $zero if $zero;
308 $last_transferred = $transferred if $transferred;
314 my $duration = time() - $starttime;
315 if ($transferred && $duration) {
316 my $mb = int($transferred / (1000 * 1000));
317 my $mbps = $get_mbps->($transferred, $duration);
318 $self->loginfo("transferred $mb MB in $duration seconds ($mbps MB/s)");
323 my ($self, $task, $vmid) = @_;
325 my $conffile = "$task->{tmpdir}/qemu-server.conf";
326 my $firewall = "$task->{tmpdir}/qemu-server.fw";
328 my $opts = $self->{vzdump
}->{opts
};
329 my $scfg = $opts->{scfg
};
331 my $starttime = time();
333 my $server = $scfg->{server
};
334 my $datastore = $scfg->{datastore
};
335 my $username = $scfg->{username
} // 'root@pam';
336 my $fingerprint = $scfg->{fingerprint
};
338 my $repo = "$username\@$server:$datastore";
339 my $password = PVE
::Storage
::PBSPlugin
::pbs_get_password
($scfg, $opts->{storage
});
341 my $diskcount = scalar(@{$task->{disks
}});
342 if (PVE
::QemuConfig-
>is_template($self->{vmlist
}->{$vmid}) || !$diskcount) {
344 foreach my $di (@{$task->{disks
}}) {
345 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
346 push @pathlist, "$di->{qmdevice}.img:$di->{path}";
348 die "implement me (type $di->{type})";
353 $self->loginfo("backup contains no disks");
356 local $ENV{PBS_PASSWORD
} = $password;
357 local $ENV{PBS_FINGERPRINT
} = $fingerprint if defined($fingerprint);
359 '/usr/bin/proxmox-backup-client',
361 '--repository', $repo,
362 '--backup-type', 'vm',
363 '--backup-id', "$vmid",
364 '--backup-time', $task->{backup_time
},
367 push @$cmd, "qemu-server.conf:$conffile";
368 push @$cmd, "fw.conf:$firewall" if -e
$firewall;
369 push @$cmd, @pathlist if scalar(@pathlist);
371 $self->loginfo("starting template backup");
372 $self->loginfo(join(' ', @$cmd));
379 # get list early so we die on unkown drive types before doing anything
380 my $devlist = _get_task_devlist
($task);
382 $self->enforce_vm_running_for_backup($vmid);
386 $SIG{INT
} = $SIG{TERM
} = $SIG{QUIT
} = $SIG{HUP
} = $SIG{PIPE
} = sub {
387 die "interrupted by signal\n";
390 my $fs_frozen = $self->qga_fs_freeze($task, $vmid);
394 'backup-file' => $repo,
395 'backup-id' => "$vmid",
396 'backup-time' => $task->{backup_time
},
397 password
=> $password,
399 'config-file' => $conffile,
400 incremental
=> JSON
::true
,
402 $params->{fingerprint
} = $fingerprint if defined($fingerprint);
403 $params->{'firewall-file'} = $firewall if -e
$firewall;
405 $params->{timeout
} = 60; # give some time to connect to the backup server
407 my $res = eval { mon_cmd
($vmid, "backup", %$params) };
409 $backup_job_uuid = $res->{UUID
} if $res;
412 $self->qga_fs_thaw($vmid);
415 die $qmperr if $qmperr;
416 die "got no uuid for backup task\n" if !defined($backup_job_uuid);
418 $self->loginfo("started backup task '$backup_job_uuid'");
420 $self->resume_vm_after_job_start($task, $vmid);
422 $query_backup_status_loop->($self, $vmid, $backup_job_uuid);
427 $self->mon_backup_cancel($vmid) if defined($backup_job_uuid);
429 $self->restore_vm_power_state($vmid);
434 my $fork_compressor_pipe = sub {
435 my ($self, $comp, $outfileno) = @_;
437 my @pipefd = POSIX
::pipe();
439 die "unable to fork worker - $!" if !defined($cpid) || $cpid < 0;
442 POSIX
::close($pipefd[1]);
444 my $fd = fileno(STDIN
);
446 POSIX
::close(0) if $fd != 0;
447 die "unable to redirect STDIN - $!"
448 if !open(STDIN
, "<&", $pipefd[0]);
451 $fd = fileno(STDOUT
);
453 POSIX
::close (1) if $fd != 1;
455 die "unable to redirect STDOUT - $!"
456 if !open(STDOUT
, ">&", $outfileno);
459 die "fork compressor '$comp' failed\n";
468 POSIX
::close($pipefd[0]);
469 $outfileno = $pipefd[1];
472 return ($cpid, $outfileno);
476 my ($self, $task, $vmid, $filename, $comp) = @_;
478 my $conffile = "$task->{tmpdir}/qemu-server.conf";
479 my $firewall = "$task->{tmpdir}/qemu-server.fw";
481 my $opts = $self->{vzdump
}->{opts
};
483 my $starttime = time();
486 if ($opts->{bwlimit
}) {
487 $speed = $opts->{bwlimit
}*1024;
490 my $diskcount = scalar(@{$task->{disks
}});
491 if (PVE
::QemuConfig-
>is_template($self->{vmlist
}->{$vmid}) || !$diskcount) {
493 foreach my $di (@{$task->{disks
}}) {
494 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
495 push @pathlist, "$di->{qmdevice}=$di->{path}";
502 $self->loginfo("backup contains no disks");
507 $outcmd = "exec:$comp";
509 $outcmd = "exec:cat";
512 $outcmd .= " > $filename" if !$opts->{stdout
};
514 my $cmd = ['/usr/bin/vma', 'create', '-v', '-c', $conffile];
515 push @$cmd, '-c', $firewall if -e
$firewall;
516 push @$cmd, $outcmd, @pathlist;
518 $self->loginfo("starting template backup");
519 $self->loginfo(join(' ', @$cmd));
521 if ($opts->{stdout
}) {
522 $self->cmd($cmd, output
=> ">&" . fileno($opts->{stdout
}));
530 my $devlist = _get_task_devlist
($task);
532 $self->enforce_vm_running_for_backup($vmid);
538 $SIG{INT
} = $SIG{TERM
} = $SIG{QUIT
} = $SIG{HUP
} = $SIG{PIPE
} = sub {
539 die "interrupted by signal\n";
543 if ($opts->{stdout
}) {
544 $outfh = $opts->{stdout
};
546 $outfh = IO
::File-
>new($filename, "w") ||
547 die "unable to open file '$filename' - $!\n";
549 my $outfileno = fileno($outfh);
552 ($cpid, $outfileno) = $fork_compressor_pipe->($self, $comp, $outfileno);
555 my $qmpclient = PVE
::QMPClient-
>new();
556 my $backup_cb = sub {
557 my ($vmid, $resp) = @_;
558 $backup_job_uuid = $resp->{return}->{UUID
};
560 my $add_fd_cb = sub {
561 my ($vmid, $resp) = @_;
564 'backup-file' => "/dev/fdname/backup",
566 'config-file' => $conffile,
569 $params->{'firewall-file'} = $firewall if -e
$firewall;
571 $qmpclient->queue_cmd($vmid, $backup_cb, 'backup', %$params);
574 $qmpclient->queue_cmd($vmid, $add_fd_cb, 'getfd', fd
=> $outfileno, fdname
=> "backup");
576 my $fs_frozen = $self->qga_fs_freeze($task, $vmid);
578 eval { $qmpclient->queue_execute(30) };
582 $self->qga_fs_thaw($vmid);
585 die $qmperr if $qmperr;
586 die $qmpclient->{errors
}->{$vmid} if $qmpclient->{errors
}->{$vmid};
589 POSIX
::close($outfileno) == 0 ||
590 die "close output file handle failed\n";
593 die "got no uuid for backup task\n" if !defined($backup_job_uuid);
595 $self->loginfo("started backup task '$backup_job_uuid'");
597 $self->resume_vm_after_job_start($task, $vmid);
599 $query_backup_status_loop->($self, $vmid, $backup_job_uuid);
604 $self->mon_backup_cancel($vmid) if defined($backup_job_uuid);
607 $self->restore_vm_power_state($vmid);
617 if ($cpid && (waitpid($cpid, 0) > 0)) {
620 my $signal = $stat & 127;
621 if ($ec || $signal) {
622 die "$comp failed - wrong exit status $ec" .
623 ($signal ?
" (signal $signal)\n" : "\n");
628 sub _get_task_devlist
{
632 foreach my $di (@{$task->{disks
}}) {
633 if ($di->{type
} eq 'block' || $di->{type
} eq 'file') {
634 $devlist .= ',' if $devlist;
635 $devlist .= $di->{qmdevice
};
637 die "implement me (type '$di->{type}')";
644 my ($self, $task, $vmid) = @_;
645 return if !$self->{vmlist
}->{$vmid}->{agent
} || $task->{mode
} eq 'stop' || !$self->{vm_was_running
};
647 if (!PVE
::QemuServer
::qga_check_running
($vmid, 1)) {
648 $self->loginfo("skipping guest-agent 'fs-freeze', agent configured but not running?");
652 $self->loginfo("issuing guest-agent 'fs-freeze' command");
653 eval { mon_cmd
($vmid, "guest-fsfreeze-freeze") };
654 $self->logerr($@) if $@;
656 return 1; # even on mon command error, ensure we always thaw again
659 # only call if fs_freeze return 1
661 my ($self, $vmid) = @_;
663 $self->loginfo("issuing guest-agent 'fs-thaw' command");
664 eval { mon_cmd
($vmid, "guest-fsfreeze-thaw") };
665 $self->logerr($@) if $@;
668 # we need a running QEMU/KVM process for backup, starts a paused (prelaunch)
669 # one if VM isn't already running
670 sub enforce_vm_running_for_backup
{
671 my ($self, $vmid) = @_;
673 if (PVE
::QemuServer
::check_running
($vmid)) {
674 $self->{vm_was_running
} = 1;
679 $self->loginfo("starting kvm to execute backup task");
680 # start with skiplock
685 PVE
::QemuServer
::vm_start
($self->{storecfg
}, $vmid, $params);
690 # resume VM againe once we got in a clear state (stop mode backup of running VM)
691 sub resume_vm_after_job_start
{
692 my ($self, $task, $vmid) = @_;
694 return if !$self->{vm_was_running
};
696 if (my $stoptime = $task->{vmstoptime
}) {
697 my $delay = time() - $task->{vmstoptime
};
698 $task->{vmstoptime
} = undef; # avoid printing 'online after ..' twice
699 $self->loginfo("resuming VM again after $delay seconds");
701 $self->loginfo("resuming VM again");
703 mon_cmd
($vmid, 'cont');
706 # stop again if VM was not running before
707 sub restore_vm_power_state
{
708 my ($self, $vmid) = @_;
710 # we always let VMs keep running
711 return if $self->{vm_was_running
};
714 my $resp = mon_cmd
($vmid, 'query-status');
715 my $status = $resp && $resp->{status
} ?
$resp->{status
} : 'unknown';
716 if ($status eq 'prelaunch') {
717 $self->loginfo("stopping kvm after backup task");
718 PVE
::QemuServer
::vm_stop
($self->{storecfg
}, $vmid, 1);
720 $self->loginfo("kvm status changed after backup ('$status') - keep VM running");
726 sub mon_backup_cancel
{
727 my ($self, $vmid) = @_;
729 $self->loginfo("aborting backup job");
730 eval { mon_cmd
($vmid, 'backup-cancel') };
731 $self->logerr($@) if $@;
735 my ($self, $task, $vmid) = @_;
741 my ($self, $task, $vmid) = @_;