1 From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
2 From: Dietmar Maurer <dietmar@proxmox.com>
3 Date: Mon, 6 Apr 2020 12:16:59 +0200
4 Subject: [PATCH] PVE-Backup: proxmox backup patches for qemu
6 Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
7 [PVE-Backup: avoid coroutines to fix AIO freeze, cleanups]
8 Signed-off-by: Stefan Reiter <s.reiter@proxmox.com>
9 Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
10 [FE: add new force parameter to job_cancel_sync calls
11 adapt for new job lock mechanism replacing AioContext locks
12 adapt to QAPI changes]
13 Signed-off-by: Fiona Ebner <f.ebner@proxmox.com>
15 block/meson.build | 5 +
16 block/monitor/block-hmp-cmds.c | 33 ++
18 hmp-commands-info.hx | 14 +
19 hmp-commands.hx | 29 +
20 include/monitor/hmp.h | 3 +
22 monitor/hmp-cmds.c | 45 ++
23 proxmox-backup-client.c | 176 +++++++
24 proxmox-backup-client.h | 59 +++
25 pve-backup.c | 938 +++++++++++++++++++++++++++++++++
26 qapi/block-core.json | 109 ++++
27 qapi/common.json | 13 +
28 qapi/machine.json | 15 +-
29 14 files changed, 1428 insertions(+), 13 deletions(-)
30 create mode 100644 proxmox-backup-client.c
31 create mode 100644 proxmox-backup-client.h
32 create mode 100644 pve-backup.c
34 diff --git a/block/meson.build b/block/meson.build
35 index f580f95395..5bcebb934b 100644
36 --- a/block/meson.build
37 +++ b/block/meson.build
38 @@ -49,6 +49,11 @@ block_ss.add(files(
39 ), zstd, zlib, gnutls)
41 block_ss.add(files('../vma-writer.c'), libuuid)
43 + '../proxmox-backup-client.c',
45 +), libproxmox_backup_qemu)
48 softmmu_ss.add(when: 'CONFIG_TCG', if_true: files('blkreplay.c'))
49 softmmu_ss.add(files('block-ram-registrar.c'))
50 diff --git a/block/monitor/block-hmp-cmds.c b/block/monitor/block-hmp-cmds.c
51 index ca2599de44..d50e99df26 100644
52 --- a/block/monitor/block-hmp-cmds.c
53 +++ b/block/monitor/block-hmp-cmds.c
54 @@ -1029,3 +1029,36 @@ void hmp_change_medium(Monitor *mon, const char *device, const char *target,
55 qmp_blockdev_change_medium(device, NULL, target, arg, true, force,
56 !!read_only, read_only_mode, errp);
59 +void hmp_backup_cancel(Monitor *mon, const QDict *qdict)
61 + Error *error = NULL;
63 + qmp_backup_cancel(&error);
65 + hmp_handle_error(mon, error);
68 +void hmp_backup(Monitor *mon, const QDict *qdict)
70 + Error *error = NULL;
72 + int dir = qdict_get_try_bool(qdict, "directory", 0);
73 + const char *backup_file = qdict_get_str(qdict, "backupfile");
74 + const char *devlist = qdict_get_try_str(qdict, "devlist");
75 + int64_t speed = qdict_get_try_int(qdict, "speed", 0);
79 + NULL, // PBS password
80 + NULL, // PBS keyfile
81 + NULL, // PBS key_password
82 + NULL, // PBS fingerprint
83 + NULL, // PBS backup-id
84 + false, 0, // PBS backup-time
85 + true, dir ? BACKUP_FORMAT_DIR : BACKUP_FORMAT_VMA,
87 + devlist, qdict_haskey(qdict, "speed"), speed, &error);
89 + hmp_handle_error(mon, error);
91 diff --git a/blockdev.c b/blockdev.c
92 index 9a010f3a86..b9505c95d3 100644
96 #include "block/blockjob.h"
97 #include "block/dirty-bitmap.h"
98 #include "block/qdict.h"
99 +#include "block/blockjob_int.h"
100 #include "block/throttle-groups.h"
101 #include "monitor/monitor.h"
102 #include "qemu/error-report.h"
103 diff --git a/hmp-commands-info.hx b/hmp-commands-info.hx
104 index a166bff3d5..4b75966c2e 100644
105 --- a/hmp-commands-info.hx
106 +++ b/hmp-commands-info.hx
107 @@ -486,6 +486,20 @@ SRST
108 Show the current VM UUID.
116 + .help = "show backup status",
117 + .cmd = hmp_info_backup,
122 + Show backup status.
125 #if defined(CONFIG_SLIRP)
128 diff --git a/hmp-commands.hx b/hmp-commands.hx
129 index b66d7fc4ab..9b6b8e2e9c 100644
130 --- a/hmp-commands.hx
131 +++ b/hmp-commands.hx
132 @@ -101,6 +101,35 @@ ERST
135 Copy data from a backing file into a block device.
140 + .args_type = "directory:-d,backupfile:s,speed:o?,devlist:s?",
141 + .params = "[-d] backupfile [speed [devlist]]",
142 + .help = "create a VM Backup."
143 + "\n\t\t\t Use -d to dump data into a directory instead"
144 + "\n\t\t\t of using VMA format.",
150 + Create a VM backup.
154 + .name = "backup_cancel",
157 + .help = "cancel the current VM backup",
158 + .cmd = hmp_backup_cancel,
163 + Cancel the current VM backup.
168 diff --git a/include/monitor/hmp.h b/include/monitor/hmp.h
169 index c012bad741..2e504db706 100644
170 --- a/include/monitor/hmp.h
171 +++ b/include/monitor/hmp.h
172 @@ -32,6 +32,7 @@ void hmp_info_savevm(Monitor *mon, const QDict *qdict);
173 void hmp_info_migrate(Monitor *mon, const QDict *qdict);
174 void hmp_info_migrate_capabilities(Monitor *mon, const QDict *qdict);
175 void hmp_info_migrate_parameters(Monitor *mon, const QDict *qdict);
176 +void hmp_info_backup(Monitor *mon, const QDict *qdict);
177 void hmp_info_cpus(Monitor *mon, const QDict *qdict);
178 void hmp_info_vnc(Monitor *mon, const QDict *qdict);
179 void hmp_info_spice(Monitor *mon, const QDict *qdict);
180 @@ -84,6 +85,8 @@ void hmp_change_vnc(Monitor *mon, const char *device, const char *target,
181 void hmp_change_medium(Monitor *mon, const char *device, const char *target,
182 const char *arg, const char *read_only, bool force,
184 +void hmp_backup(Monitor *mon, const QDict *qdict);
185 +void hmp_backup_cancel(Monitor *mon, const QDict *qdict);
186 void hmp_migrate(Monitor *mon, const QDict *qdict);
187 void hmp_device_add(Monitor *mon, const QDict *qdict);
188 void hmp_device_del(Monitor *mon, const QDict *qdict);
189 diff --git a/meson.build b/meson.build
190 index 603cdb97bb..d307d8eabf 100644
193 @@ -1528,6 +1528,7 @@ keyutils = dependency('libkeyutils', required: false,
194 has_gettid = cc.has_function('gettid')
196 libuuid = cc.find_library('uuid', required: true)
197 +libproxmox_backup_qemu = cc.find_library('proxmox_backup_qemu', required: true)
200 selinux = dependency('libselinux',
201 diff --git a/monitor/hmp-cmds.c b/monitor/hmp-cmds.c
202 index 435f9334f9..9e1bd57aeb 100644
203 --- a/monitor/hmp-cmds.c
204 +++ b/monitor/hmp-cmds.c
206 #include "qemu/help_option.h"
207 #include "monitor/monitor-internal.h"
208 #include "qapi/error.h"
209 +#include "qapi/qapi-commands-block-core.h"
210 #include "qapi/qapi-commands-control.h"
211 #include "qapi/qapi-commands-migration.h"
212 #include "qapi/qapi-commands-misc.h"
213 @@ -144,6 +145,50 @@ void hmp_sync_profile(Monitor *mon, const QDict *qdict)
217 +void hmp_info_backup(Monitor *mon, const QDict *qdict)
219 + BackupStatus *info;
221 + info = qmp_query_backup(NULL);
224 + monitor_printf(mon, "Backup status: not initialized\n");
228 + if (info->status) {
229 + if (info->errmsg) {
230 + monitor_printf(mon, "Backup status: %s - %s\n",
231 + info->status, info->errmsg);
233 + monitor_printf(mon, "Backup status: %s\n", info->status);
237 + if (info->backup_file) {
238 + monitor_printf(mon, "Start time: %s", ctime(&info->start_time));
239 + if (info->end_time) {
240 + monitor_printf(mon, "End time: %s", ctime(&info->end_time));
243 + int per = (info->has_total && info->total &&
244 + info->has_transferred && info->transferred) ?
245 + (info->transferred * 100)/info->total : 0;
246 + int zero_per = (info->has_total && info->total &&
247 + info->has_zero_bytes && info->zero_bytes) ?
248 + (info->zero_bytes * 100)/info->total : 0;
249 + monitor_printf(mon, "Backup file: %s\n", info->backup_file);
250 + monitor_printf(mon, "Backup uuid: %s\n", info->uuid);
251 + monitor_printf(mon, "Total size: %zd\n", info->total);
252 + monitor_printf(mon, "Transferred bytes: %zd (%d%%)\n",
253 + info->transferred, per);
254 + monitor_printf(mon, "Zero bytes: %zd (%d%%)\n",
255 + info->zero_bytes, zero_per);
258 + qapi_free_BackupStatus(info);
261 void hmp_exit_preconfig(Monitor *mon, const QDict *qdict)
264 diff --git a/proxmox-backup-client.c b/proxmox-backup-client.c
266 index 0000000000..a8f6653a81
268 +++ b/proxmox-backup-client.c
270 +#include "proxmox-backup-client.h"
271 +#include "qemu/main-loop.h"
272 +#include "block/aio-wait.h"
273 +#include "qapi/error.h"
275 +/* Proxmox Backup Server client bindings using coroutines */
277 +typedef struct BlockOnCoroutineWrapper {
279 + CoroutineEntry *entry;
282 +} BlockOnCoroutineWrapper;
284 +static void coroutine_fn block_on_coroutine_wrapper(void *opaque)
286 + BlockOnCoroutineWrapper *wrapper = opaque;
287 + wrapper->entry(wrapper->entry_arg);
288 + wrapper->finished = true;
292 +void block_on_coroutine_fn(CoroutineEntry *entry, void *entry_arg)
294 + assert(!qemu_in_coroutine());
296 + AioContext *ctx = qemu_get_current_aio_context();
297 + BlockOnCoroutineWrapper wrapper = {
300 + .entry_arg = entry_arg,
303 + Coroutine *wrapper_co = qemu_coroutine_create(block_on_coroutine_wrapper, &wrapper);
304 + aio_co_enter(ctx, wrapper_co);
305 + AIO_WAIT_WHILE(ctx, !wrapper.finished);
308 +// This is called from another thread, so we use aio_co_schedule()
309 +static void proxmox_backup_schedule_wake(void *data) {
310 + CoCtxData *waker = (CoCtxData *)data;
311 + aio_co_schedule(waker->ctx, waker->co);
315 +proxmox_backup_co_connect(ProxmoxBackupHandle *pbs, Error **errp)
317 + Coroutine *co = qemu_coroutine_self();
318 + AioContext *ctx = qemu_get_current_aio_context();
319 + CoCtxData waker = { .co = co, .ctx = ctx };
320 + char *pbs_err = NULL;
323 + proxmox_backup_connect_async(pbs, proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
324 + qemu_coroutine_yield();
326 + if (errp) error_setg(errp, "backup connect failed: %s", pbs_err ? pbs_err : "unknown error");
327 + if (pbs_err) proxmox_backup_free_error(pbs_err);
333 +proxmox_backup_co_add_config(
334 + ProxmoxBackupHandle *pbs,
336 + const uint8_t *data,
340 + Coroutine *co = qemu_coroutine_self();
341 + AioContext *ctx = qemu_get_current_aio_context();
342 + CoCtxData waker = { .co = co, .ctx = ctx };
343 + char *pbs_err = NULL;
346 + proxmox_backup_add_config_async(
347 + pbs, name, data, size ,proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
348 + qemu_coroutine_yield();
350 + if (errp) error_setg(errp, "backup add_config %s failed: %s", name, pbs_err ? pbs_err : "unknown error");
351 + if (pbs_err) proxmox_backup_free_error(pbs_err);
357 +proxmox_backup_co_register_image(
358 + ProxmoxBackupHandle *pbs,
359 + const char *device_name,
363 + Coroutine *co = qemu_coroutine_self();
364 + AioContext *ctx = qemu_get_current_aio_context();
365 + CoCtxData waker = { .co = co, .ctx = ctx };
366 + char *pbs_err = NULL;
369 + proxmox_backup_register_image_async(
370 + pbs, device_name, size ,proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
371 + qemu_coroutine_yield();
373 + if (errp) error_setg(errp, "backup register image failed: %s", pbs_err ? pbs_err : "unknown error");
374 + if (pbs_err) proxmox_backup_free_error(pbs_err);
380 +proxmox_backup_co_finish(
381 + ProxmoxBackupHandle *pbs,
384 + Coroutine *co = qemu_coroutine_self();
385 + AioContext *ctx = qemu_get_current_aio_context();
386 + CoCtxData waker = { .co = co, .ctx = ctx };
387 + char *pbs_err = NULL;
390 + proxmox_backup_finish_async(
391 + pbs, proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
392 + qemu_coroutine_yield();
394 + if (errp) error_setg(errp, "backup finish failed: %s", pbs_err ? pbs_err : "unknown error");
395 + if (pbs_err) proxmox_backup_free_error(pbs_err);
401 +proxmox_backup_co_close_image(
402 + ProxmoxBackupHandle *pbs,
406 + Coroutine *co = qemu_coroutine_self();
407 + AioContext *ctx = qemu_get_current_aio_context();
408 + CoCtxData waker = { .co = co, .ctx = ctx };
409 + char *pbs_err = NULL;
412 + proxmox_backup_close_image_async(
413 + pbs, dev_id, proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
414 + qemu_coroutine_yield();
416 + if (errp) error_setg(errp, "backup close image failed: %s", pbs_err ? pbs_err : "unknown error");
417 + if (pbs_err) proxmox_backup_free_error(pbs_err);
423 +proxmox_backup_co_write_data(
424 + ProxmoxBackupHandle *pbs,
426 + const uint8_t *data,
431 + Coroutine *co = qemu_coroutine_self();
432 + AioContext *ctx = qemu_get_current_aio_context();
433 + CoCtxData waker = { .co = co, .ctx = ctx };
434 + char *pbs_err = NULL;
437 + proxmox_backup_write_data_async(
438 + pbs, dev_id, data, offset, size, proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
439 + qemu_coroutine_yield();
441 + if (errp) error_setg(errp, "backup write data failed: %s", pbs_err ? pbs_err : "unknown error");
442 + if (pbs_err) proxmox_backup_free_error(pbs_err);
446 diff --git a/proxmox-backup-client.h b/proxmox-backup-client.h
448 index 0000000000..1dda8b7d8f
450 +++ b/proxmox-backup-client.h
452 +#ifndef PROXMOX_BACKUP_CLIENT_H
453 +#define PROXMOX_BACKUP_CLIENT_H
455 +#include "qemu/osdep.h"
456 +#include "qemu/coroutine.h"
457 +#include "proxmox-backup-qemu.h"
459 +typedef struct CoCtxData {
465 +// FIXME: Remove once coroutines are supported for QMP
466 +void block_on_coroutine_fn(CoroutineEntry *entry, void *entry_arg);
469 +proxmox_backup_co_connect(
470 + ProxmoxBackupHandle *pbs,
474 +proxmox_backup_co_add_config(
475 + ProxmoxBackupHandle *pbs,
477 + const uint8_t *data,
482 +proxmox_backup_co_register_image(
483 + ProxmoxBackupHandle *pbs,
484 + const char *device_name,
490 +proxmox_backup_co_finish(
491 + ProxmoxBackupHandle *pbs,
495 +proxmox_backup_co_close_image(
496 + ProxmoxBackupHandle *pbs,
501 +proxmox_backup_co_write_data(
502 + ProxmoxBackupHandle *pbs,
504 + const uint8_t *data,
510 +#endif /* PROXMOX_BACKUP_CLIENT_H */
511 diff --git a/pve-backup.c b/pve-backup.c
513 index 0000000000..f77892a509
517 +#include "proxmox-backup-client.h"
520 +#include "qemu/osdep.h"
521 +#include "qemu/module.h"
522 +#include "sysemu/block-backend.h"
523 +#include "sysemu/blockdev.h"
524 +#include "block/block_int-global-state.h"
525 +#include "block/blockjob.h"
526 +#include "qapi/qapi-commands-block.h"
527 +#include "qapi/qmp/qerror.h"
529 +/* PVE backup state and related function */
532 + * Note: A resume from a qemu_coroutine_yield can happen in a different thread,
533 + * so you may not use normal mutexes within coroutines:
535 + * ---bad-example---
536 + * qemu_rec_mutex_lock(lock)
538 + * qemu_coroutine_yield() // wait for something
539 + * // we are now inside a different thread
540 + * qemu_rec_mutex_unlock(lock) // Crash - wrong thread!!
541 + * ---end-bad-example--
543 + * ==> Always use CoMutext inside coroutines.
544 + * ==> Never acquire/release AioContext withing coroutines (because that use QemuRecMutex)
548 +static struct PVEBackupState {
550 + // Everithing accessed from qmp_backup_query command is protected using lock
559 + size_t transferred;
564 + ProxmoxBackupHandle *pbs;
566 + QemuMutex backup_mutex;
567 + CoMutex dump_callback_mutex;
570 +static void pvebackup_init(void)
572 + qemu_mutex_init(&backup_state.stat.lock);
573 + qemu_mutex_init(&backup_state.backup_mutex);
574 + qemu_co_mutex_init(&backup_state.dump_callback_mutex);
577 +// initialize PVEBackupState at startup
578 +opts_init(pvebackup_init);
580 +typedef struct PVEBackupDevInfo {
581 + BlockDriverState *bs;
585 + char targetfile[PATH_MAX];
586 + BlockDriverState *target;
589 +static void pvebackup_run_next_job(void);
592 +lookup_active_block_job(PVEBackupDevInfo *di)
594 + if (!di->completed && di->bs) {
595 + WITH_JOB_LOCK_GUARD() {
596 + for (BlockJob *job = block_job_next_locked(NULL); job; job = block_job_next_locked(job)) {
597 + if (job->job.driver->job_type != JOB_TYPE_BACKUP) {
601 + BackupBlockJob *bjob = container_of(job, BackupBlockJob, common);
602 + if (bjob && bjob->source_bs == di->bs) {
611 +static void pvebackup_propagate_error(Error *err)
613 + qemu_mutex_lock(&backup_state.stat.lock);
614 + error_propagate(&backup_state.stat.error, err);
615 + qemu_mutex_unlock(&backup_state.stat.lock);
618 +static bool pvebackup_error_or_canceled(void)
620 + qemu_mutex_lock(&backup_state.stat.lock);
621 + bool error_or_canceled = !!backup_state.stat.error;
622 + qemu_mutex_unlock(&backup_state.stat.lock);
624 + return error_or_canceled;
627 +static void pvebackup_add_transfered_bytes(size_t transferred, size_t zero_bytes)
629 + qemu_mutex_lock(&backup_state.stat.lock);
630 + backup_state.stat.zero_bytes += zero_bytes;
631 + backup_state.stat.transferred += transferred;
632 + qemu_mutex_unlock(&backup_state.stat.lock);
635 +// This may get called from multiple coroutines in multiple io-threads
636 +// Note1: this may get called after job_cancel()
637 +static int coroutine_fn
638 +pvebackup_co_dump_pbs_cb(
644 + assert(qemu_in_coroutine());
646 + const uint64_t size = bytes;
647 + const unsigned char *buf = pbuf;
648 + PVEBackupDevInfo *di = opaque;
650 + assert(backup_state.pbs);
652 + Error *local_err = NULL;
655 + qemu_co_mutex_lock(&backup_state.dump_callback_mutex);
657 + // avoid deadlock if job is cancelled
658 + if (pvebackup_error_or_canceled()) {
659 + qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
663 + pbs_res = proxmox_backup_co_write_data(backup_state.pbs, di->dev_id, buf, start, size, &local_err);
664 + qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
667 + pvebackup_propagate_error(local_err);
670 + pvebackup_add_transfered_bytes(size, !buf ? size : 0);
676 +// This may get called from multiple coroutines in multiple io-threads
677 +static int coroutine_fn
678 +pvebackup_co_dump_vma_cb(
684 + assert(qemu_in_coroutine());
686 + const uint64_t size = bytes;
687 + const unsigned char *buf = pbuf;
688 + PVEBackupDevInfo *di = opaque;
692 + assert(backup_state.vmaw);
694 + uint64_t remaining = size;
696 + uint64_t cluster_num = start / VMA_CLUSTER_SIZE;
697 + if ((cluster_num * VMA_CLUSTER_SIZE) != start) {
698 + Error *local_err = NULL;
699 + error_setg(&local_err,
700 + "got unaligned write inside backup dump "
701 + "callback (sector %ld)", start);
702 + pvebackup_propagate_error(local_err);
703 + return -1; // not aligned to cluster size
706 + while (remaining > 0) {
707 + qemu_co_mutex_lock(&backup_state.dump_callback_mutex);
708 + // avoid deadlock if job is cancelled
709 + if (pvebackup_error_or_canceled()) {
710 + qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
714 + size_t zero_bytes = 0;
715 + ret = vma_writer_write(backup_state.vmaw, di->dev_id, cluster_num, buf, &zero_bytes);
716 + qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
720 + buf += VMA_CLUSTER_SIZE;
723 + Error *local_err = NULL;
724 + vma_writer_error_propagate(backup_state.vmaw, &local_err);
725 + pvebackup_propagate_error(local_err);
728 + if (remaining >= VMA_CLUSTER_SIZE) {
729 + assert(ret == VMA_CLUSTER_SIZE);
730 + pvebackup_add_transfered_bytes(VMA_CLUSTER_SIZE, zero_bytes);
731 + remaining -= VMA_CLUSTER_SIZE;
733 + assert(ret == remaining);
734 + pvebackup_add_transfered_bytes(remaining, zero_bytes);
743 +// assumes the caller holds backup_mutex
744 +static void coroutine_fn pvebackup_co_cleanup(void *unused)
746 + assert(qemu_in_coroutine());
748 + qemu_mutex_lock(&backup_state.stat.lock);
749 + backup_state.stat.end_time = time(NULL);
750 + qemu_mutex_unlock(&backup_state.stat.lock);
752 + if (backup_state.vmaw) {
753 + Error *local_err = NULL;
754 + vma_writer_close(backup_state.vmaw, &local_err);
756 + if (local_err != NULL) {
757 + pvebackup_propagate_error(local_err);
760 + backup_state.vmaw = NULL;
763 + if (backup_state.pbs) {
764 + if (!pvebackup_error_or_canceled()) {
765 + Error *local_err = NULL;
766 + proxmox_backup_co_finish(backup_state.pbs, &local_err);
767 + if (local_err != NULL) {
768 + pvebackup_propagate_error(local_err);
772 + proxmox_backup_disconnect(backup_state.pbs);
773 + backup_state.pbs = NULL;
776 + g_list_free(backup_state.di_list);
777 + backup_state.di_list = NULL;
780 +// assumes the caller holds backup_mutex
781 +static void coroutine_fn pvebackup_complete_stream(void *opaque)
783 + PVEBackupDevInfo *di = opaque;
785 + bool error_or_canceled = pvebackup_error_or_canceled();
787 + if (backup_state.vmaw) {
788 + vma_writer_close_stream(backup_state.vmaw, di->dev_id);
791 + if (backup_state.pbs && !error_or_canceled) {
792 + Error *local_err = NULL;
793 + proxmox_backup_co_close_image(backup_state.pbs, di->dev_id, &local_err);
794 + if (local_err != NULL) {
795 + pvebackup_propagate_error(local_err);
800 +static void pvebackup_complete_cb(void *opaque, int ret)
802 + assert(!qemu_in_coroutine());
804 + PVEBackupDevInfo *di = opaque;
806 + qemu_mutex_lock(&backup_state.backup_mutex);
808 + di->completed = true;
811 + Error *local_err = NULL;
812 + error_setg(&local_err, "job failed with err %d - %s", ret, strerror(-ret));
813 + pvebackup_propagate_error(local_err);
818 + assert(di->target == NULL);
820 + block_on_coroutine_fn(pvebackup_complete_stream, di);
822 + // remove self from job queue
823 + backup_state.di_list = g_list_remove(backup_state.di_list, di);
827 + qemu_mutex_unlock(&backup_state.backup_mutex);
829 + pvebackup_run_next_job();
832 +static void pvebackup_cancel(void)
834 + assert(!qemu_in_coroutine());
836 + Error *cancel_err = NULL;
837 + error_setg(&cancel_err, "backup canceled");
838 + pvebackup_propagate_error(cancel_err);
840 + qemu_mutex_lock(&backup_state.backup_mutex);
842 + if (backup_state.vmaw) {
843 + /* make sure vma writer does not block anymore */
844 + vma_writer_set_error(backup_state.vmaw, "backup canceled");
847 + if (backup_state.pbs) {
848 + proxmox_backup_abort(backup_state.pbs, "backup canceled");
851 + qemu_mutex_unlock(&backup_state.backup_mutex);
855 + BlockJob *next_job = NULL;
857 + qemu_mutex_lock(&backup_state.backup_mutex);
859 + GList *l = backup_state.di_list;
861 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
862 + l = g_list_next(l);
864 + BlockJob *job = lookup_active_block_job(di);
871 + qemu_mutex_unlock(&backup_state.backup_mutex);
874 + job_cancel_sync(&next_job->job, true);
881 +void qmp_backup_cancel(Error **errp)
883 + pvebackup_cancel();
886 +// assumes the caller holds backup_mutex
887 +static int coroutine_fn pvebackup_co_add_config(
890 + BackupFormat format,
891 + const char *backup_dir,
893 + ProxmoxBackupHandle *pbs,
898 + char *cdata = NULL;
900 + GError *err = NULL;
901 + if (!g_file_get_contents(file, &cdata, &clen, &err)) {
902 + error_setg(errp, "unable to read file '%s'", file);
906 + char *basename = g_path_get_basename(file);
907 + if (name == NULL) name = basename;
909 + if (format == BACKUP_FORMAT_VMA) {
910 + if (vma_writer_add_config(vmaw, name, cdata, clen) != 0) {
911 + error_setg(errp, "unable to add %s config data to vma archive", file);
914 + } else if (format == BACKUP_FORMAT_PBS) {
915 + if (proxmox_backup_co_add_config(pbs, name, (unsigned char *)cdata, clen, errp) < 0)
917 + } else if (format == BACKUP_FORMAT_DIR) {
918 + char config_path[PATH_MAX];
919 + snprintf(config_path, PATH_MAX, "%s/%s", backup_dir, name);
920 + if (!g_file_set_contents(config_path, cdata, clen, &err)) {
921 + error_setg(errp, "unable to write config file '%s'", config_path);
936 +bool job_should_pause_locked(Job *job);
938 +static void pvebackup_run_next_job(void)
940 + assert(!qemu_in_coroutine());
942 + qemu_mutex_lock(&backup_state.backup_mutex);
944 + GList *l = backup_state.di_list;
946 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
947 + l = g_list_next(l);
949 + BlockJob *job = lookup_active_block_job(di);
952 + qemu_mutex_unlock(&backup_state.backup_mutex);
954 + WITH_JOB_LOCK_GUARD() {
955 + if (job_should_pause_locked(&job->job)) {
956 + bool error_or_canceled = pvebackup_error_or_canceled();
957 + if (error_or_canceled) {
958 + job_cancel_sync_locked(&job->job, true);
960 + job_resume_locked(&job->job);
968 + block_on_coroutine_fn(pvebackup_co_cleanup, NULL); // no more jobs, run cleanup
970 + qemu_mutex_unlock(&backup_state.backup_mutex);
973 +static bool create_backup_jobs(void) {
975 + assert(!qemu_in_coroutine());
977 + Error *local_err = NULL;
979 + BackupPerf perf = { .max_workers = 16 };
981 + /* create and start all jobs (paused state) */
982 + GList *l = backup_state.di_list;
984 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
985 + l = g_list_next(l);
987 + assert(di->target != NULL);
989 + AioContext *aio_context = bdrv_get_aio_context(di->bs);
990 + aio_context_acquire(aio_context);
992 + BlockJob *job = backup_job_create(
993 + NULL, di->bs, di->target, backup_state.speed, MIRROR_SYNC_MODE_FULL, NULL,
994 + BITMAP_SYNC_MODE_NEVER, false, NULL, &perf, BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
995 + JOB_DEFAULT, pvebackup_complete_cb, di, NULL, &local_err);
997 + aio_context_release(aio_context);
999 + if (!job || local_err != NULL) {
1000 + Error *create_job_err = NULL;
1001 + error_setg(&create_job_err, "backup_job_create failed: %s",
1002 + local_err ? error_get_pretty(local_err) : "null");
1004 + pvebackup_propagate_error(create_job_err);
1007 + job_start(&job->job);
1009 + bdrv_unref(di->target);
1010 + di->target = NULL;
1013 + bool errors = pvebackup_error_or_canceled();
1016 + l = backup_state.di_list;
1018 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
1019 + l = g_list_next(l);
1022 + bdrv_unref(di->target);
1023 + di->target = NULL;
1031 +typedef struct QmpBackupTask {
1032 + const char *backup_file;
1033 + const char *password;
1034 + const char *keyfile;
1035 + const char *key_password;
1036 + const char *backup_id;
1037 + bool has_backup_time;
1038 + const char *fingerprint;
1039 + int64_t backup_time;
1041 + BackupFormat format;
1042 + const char *config_file;
1043 + const char *firewall_file;
1044 + const char *devlist;
1051 +// assumes the caller holds backup_mutex
1052 +static void coroutine_fn pvebackup_co_prepare(void *opaque)
1054 + assert(qemu_in_coroutine());
1056 + QmpBackupTask *task = opaque;
1058 + task->result = NULL; // just to be sure
1060 + BlockBackend *blk;
1061 + BlockDriverState *bs = NULL;
1062 + const char *backup_dir = NULL;
1063 + Error *local_err = NULL;
1065 + VmaWriter *vmaw = NULL;
1066 + ProxmoxBackupHandle *pbs = NULL;
1067 + gchar **devs = NULL;
1068 + GList *di_list = NULL;
1070 + UuidInfo *uuid_info;
1072 + const char *config_name = "qemu-server.conf";
1073 + const char *firewall_name = "qemu-server.fw";
1075 + if (backup_state.di_list) {
1076 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
1077 + "previous backup not finished");
1081 + /* Todo: try to auto-detect format based on file name */
1082 + BackupFormat format = task->has_format ? task->format : BACKUP_FORMAT_VMA;
1084 + if (task->devlist) {
1085 + devs = g_strsplit_set(task->devlist, ",;:", -1);
1089 + blk = blk_by_name(*d);
1092 + if (!bdrv_is_inserted(bs)) {
1093 + error_setg(task->errp, QERR_DEVICE_HAS_NO_MEDIUM, *d);
1096 + PVEBackupDevInfo *di = g_new0(PVEBackupDevInfo, 1);
1098 + di_list = g_list_append(di_list, di);
1100 + error_set(task->errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1101 + "Device '%s' not found", *d);
1108 + BdrvNextIterator it;
1111 + for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
1112 + if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
1116 + PVEBackupDevInfo *di = g_new0(PVEBackupDevInfo, 1);
1118 + di_list = g_list_append(di_list, di);
1123 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "empty device list");
1131 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
1132 + l = g_list_next(l);
1133 + if (bdrv_op_is_blocked(di->bs, BLOCK_OP_TYPE_BACKUP_SOURCE, task->errp)) {
1137 + ssize_t size = bdrv_getlength(di->bs);
1139 + error_setg_errno(task->errp, -size, "bdrv_getlength failed");
1146 + uuid_generate(uuid);
1148 + if (format == BACKUP_FORMAT_PBS) {
1149 + if (!task->password) {
1150 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "missing parameter 'password'");
1153 + if (!task->backup_id) {
1154 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "missing parameter 'backup-id'");
1157 + if (!task->has_backup_time) {
1158 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "missing parameter 'backup-time'");
1162 + int dump_cb_block_size = PROXMOX_BACKUP_DEFAULT_CHUNK_SIZE; // Hardcoded (4M)
1163 + firewall_name = "fw.conf";
1165 + char *pbs_err = NULL;
1166 + pbs = proxmox_backup_new(
1167 + task->backup_file,
1169 + task->backup_time,
1170 + dump_cb_block_size,
1173 + task->key_password,
1174 + task->fingerprint,
1178 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
1179 + "proxmox_backup_new failed: %s", pbs_err);
1180 + proxmox_backup_free_error(pbs_err);
1184 + if (proxmox_backup_co_connect(pbs, task->errp) < 0)
1187 + /* register all devices */
1190 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
1191 + l = g_list_next(l);
1193 + const char *devname = bdrv_get_device_name(di->bs);
1195 + int dev_id = proxmox_backup_co_register_image(pbs, devname, di->size, task->errp);
1199 + if (!(di->target = bdrv_backup_dump_create(dump_cb_block_size, di->size, pvebackup_co_dump_pbs_cb, di, task->errp))) {
1203 + di->dev_id = dev_id;
1205 + } else if (format == BACKUP_FORMAT_VMA) {
1206 + vmaw = vma_writer_create(task->backup_file, uuid, &local_err);
1209 + error_propagate(task->errp, local_err);
1214 + /* register all devices for vma writer */
1217 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
1218 + l = g_list_next(l);
1220 + if (!(di->target = bdrv_backup_dump_create(VMA_CLUSTER_SIZE, di->size, pvebackup_co_dump_vma_cb, di, task->errp))) {
1224 + const char *devname = bdrv_get_device_name(di->bs);
1225 + di->dev_id = vma_writer_register_stream(vmaw, devname, di->size);
1226 + if (di->dev_id <= 0) {
1227 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
1228 + "register_stream failed");
1232 + } else if (format == BACKUP_FORMAT_DIR) {
1233 + if (mkdir(task->backup_file, 0640) != 0) {
1234 + error_setg_errno(task->errp, errno, "can't create directory '%s'\n",
1235 + task->backup_file);
1238 + backup_dir = task->backup_file;
1242 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
1243 + l = g_list_next(l);
1245 + const char *devname = bdrv_get_device_name(di->bs);
1246 + snprintf(di->targetfile, PATH_MAX, "%s/%s.raw", backup_dir, devname);
1248 + int flags = BDRV_O_RDWR;
1249 + bdrv_img_create(di->targetfile, "raw", NULL, NULL, NULL,
1250 + di->size, flags, false, &local_err);
1252 + error_propagate(task->errp, local_err);
1256 + di->target = bdrv_co_open(di->targetfile, NULL, NULL, flags, &local_err);
1257 + if (!di->target) {
1258 + error_propagate(task->errp, local_err);
1263 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "unknown backup format");
1268 + /* add configuration file to archive */
1269 + if (task->config_file) {
1270 + if (pvebackup_co_add_config(task->config_file, config_name, format, backup_dir,
1271 + vmaw, pbs, task->errp) != 0) {
1276 + /* add firewall file to archive */
1277 + if (task->firewall_file) {
1278 + if (pvebackup_co_add_config(task->firewall_file, firewall_name, format, backup_dir,
1279 + vmaw, pbs, task->errp) != 0) {
1283 + /* initialize global backup_state now */
1285 + qemu_mutex_lock(&backup_state.stat.lock);
1287 + if (backup_state.stat.error) {
1288 + error_free(backup_state.stat.error);
1289 + backup_state.stat.error = NULL;
1292 + backup_state.stat.start_time = time(NULL);
1293 + backup_state.stat.end_time = 0;
1295 + if (backup_state.stat.backup_file) {
1296 + g_free(backup_state.stat.backup_file);
1298 + backup_state.stat.backup_file = g_strdup(task->backup_file);
1300 + uuid_copy(backup_state.stat.uuid, uuid);
1301 + uuid_unparse_lower(uuid, backup_state.stat.uuid_str);
1302 + char *uuid_str = g_strdup(backup_state.stat.uuid_str);
1304 + backup_state.stat.total = total;
1305 + backup_state.stat.transferred = 0;
1306 + backup_state.stat.zero_bytes = 0;
1308 + qemu_mutex_unlock(&backup_state.stat.lock);
1310 + backup_state.speed = (task->has_speed && task->speed > 0) ? task->speed : 0;
1312 + backup_state.vmaw = vmaw;
1313 + backup_state.pbs = pbs;
1315 + backup_state.di_list = di_list;
1317 + uuid_info = g_malloc0(sizeof(*uuid_info));
1318 + uuid_info->UUID = uuid_str;
1320 + task->result = uuid_info;
1327 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
1328 + l = g_list_next(l);
1331 + bdrv_co_unref(di->target);
1334 + if (di->targetfile[0]) {
1335 + unlink(di->targetfile);
1339 + g_list_free(di_list);
1346 + Error *err = NULL;
1347 + vma_writer_close(vmaw, &err);
1348 + unlink(task->backup_file);
1352 + proxmox_backup_disconnect(pbs);
1356 + rmdir(backup_dir);
1359 + task->result = NULL;
1363 +UuidInfo *qmp_backup(
1364 + const char *backup_file,
1365 + const char *password,
1366 + const char *keyfile,
1367 + const char *key_password,
1368 + const char *fingerprint,
1369 + const char *backup_id,
1370 + bool has_backup_time, int64_t backup_time,
1371 + bool has_format, BackupFormat format,
1372 + const char *config_file,
1373 + const char *firewall_file,
1374 + const char *devlist,
1375 + bool has_speed, int64_t speed, Error **errp)
1377 + QmpBackupTask task = {
1378 + .backup_file = backup_file,
1379 + .password = password,
1380 + .key_password = key_password,
1381 + .fingerprint = fingerprint,
1382 + .backup_id = backup_id,
1383 + .has_backup_time = has_backup_time,
1384 + .backup_time = backup_time,
1385 + .has_format = has_format,
1387 + .config_file = config_file,
1388 + .firewall_file = firewall_file,
1389 + .devlist = devlist,
1390 + .has_speed = has_speed,
1395 + qemu_mutex_lock(&backup_state.backup_mutex);
1397 + block_on_coroutine_fn(pvebackup_co_prepare, &task);
1399 + if (*errp == NULL) {
1400 + create_backup_jobs();
1401 + qemu_mutex_unlock(&backup_state.backup_mutex);
1402 + pvebackup_run_next_job();
1404 + qemu_mutex_unlock(&backup_state.backup_mutex);
1407 + return task.result;
1410 +BackupStatus *qmp_query_backup(Error **errp)
1412 + BackupStatus *info = g_malloc0(sizeof(*info));
1414 + qemu_mutex_lock(&backup_state.stat.lock);
1416 + if (!backup_state.stat.start_time) {
1417 + /* not started, return {} */
1418 + qemu_mutex_unlock(&backup_state.stat.lock);
1422 + info->has_start_time = true;
1423 + info->start_time = backup_state.stat.start_time;
1425 + if (backup_state.stat.backup_file) {
1426 + info->backup_file = g_strdup(backup_state.stat.backup_file);
1429 + info->uuid = g_strdup(backup_state.stat.uuid_str);
1431 + if (backup_state.stat.end_time) {
1432 + if (backup_state.stat.error) {
1433 + info->status = g_strdup("error");
1434 + info->errmsg = g_strdup(error_get_pretty(backup_state.stat.error));
1436 + info->status = g_strdup("done");
1438 + info->has_end_time = true;
1439 + info->end_time = backup_state.stat.end_time;
1441 + info->status = g_strdup("active");
1444 + info->has_total = true;
1445 + info->total = backup_state.stat.total;
1446 + info->has_zero_bytes = true;
1447 + info->zero_bytes = backup_state.stat.zero_bytes;
1448 + info->has_transferred = true;
1449 + info->transferred = backup_state.stat.transferred;
1451 + qemu_mutex_unlock(&backup_state.stat.lock);
1455 diff --git a/qapi/block-core.json b/qapi/block-core.json
1456 index 542add004b..16fb4c5ea0 100644
1457 --- a/qapi/block-core.json
1458 +++ b/qapi/block-core.json
1459 @@ -835,6 +835,115 @@
1460 { 'command': 'query-block', 'returns': ['BlockInfo'],
1461 'allow-preconfig': true }
1466 +# Detailed backup status.
1468 +# @status: string describing the current backup status.
1469 +# This can be 'active', 'done', 'error'. If this field is not
1470 +# returned, no backup process has been initiated
1472 +# @errmsg: error message (only returned if status is 'error')
1474 +# @total: total amount of bytes involved in the backup process
1476 +# @transferred: amount of bytes already backed up.
1478 +# @zero-bytes: amount of 'zero' bytes detected.
1480 +# @start-time: time (epoch) when backup job started.
1482 +# @end-time: time (epoch) when backup job finished.
1484 +# @backup-file: backup file name
1486 +# @uuid: uuid for this backup job
1489 +{ 'struct': 'BackupStatus',
1490 + 'data': {'*status': 'str', '*errmsg': 'str', '*total': 'int',
1491 + '*transferred': 'int', '*zero-bytes': 'int',
1492 + '*start-time': 'int', '*end-time': 'int',
1493 + '*backup-file': 'str', '*uuid': 'str' } }
1498 +# An enumeration of supported backup formats.
1500 +# @vma: Proxmox vma backup format
1502 +{ 'enum': 'BackupFormat',
1503 + 'data': [ 'vma', 'dir', 'pbs' ] }
1508 +# Starts a VM backup.
1510 +# @backup-file: the backup file name
1512 +# @format: format of the backup file
1514 +# @config-file: a configuration file to include into
1515 +# the backup archive.
1517 +# @speed: the maximum speed, in bytes per second
1519 +# @devlist: list of block device names (separated by ',', ';'
1520 +# or ':'). By default the backup includes all writable block devices.
1522 +# @password: backup server passsword (required for format 'pbs')
1524 +# @keyfile: keyfile used for encryption (optional for format 'pbs')
1526 +# @key-password: password for keyfile (optional for format 'pbs')
1528 +# @fingerprint: server cert fingerprint (optional for format 'pbs')
1530 +# @backup-id: backup ID (required for format 'pbs')
1532 +# @backup-time: backup timestamp (Unix epoch, required for format 'pbs')
1534 +# Returns: the uuid of the backup job
1537 +{ 'command': 'backup', 'data': { 'backup-file': 'str',
1538 + '*password': 'str',
1539 + '*keyfile': 'str',
1540 + '*key-password': 'str',
1541 + '*fingerprint': 'str',
1542 + '*backup-id': 'str',
1543 + '*backup-time': 'int',
1544 + '*format': 'BackupFormat',
1545 + '*config-file': 'str',
1546 + '*firewall-file': 'str',
1547 + '*devlist': 'str', '*speed': 'int' },
1548 + 'returns': 'UuidInfo' }
1553 +# Returns information about current/last backup task.
1555 +# Returns: @BackupStatus
1558 +{ 'command': 'query-backup', 'returns': 'BackupStatus' }
1563 +# Cancel the current executing backup process.
1565 +# Returns: nothing on success
1567 +# Notes: This command succeeds even if there is no backup process running.
1570 +{ 'command': 'backup-cancel' }
1573 # @BlockDeviceTimedStats:
1575 diff --git a/qapi/common.json b/qapi/common.json
1576 index 356db3f670..aae8a3b682 100644
1577 --- a/qapi/common.json
1578 +++ b/qapi/common.json
1579 @@ -206,3 +206,16 @@
1581 { 'struct': 'HumanReadableText',
1582 'data': { 'human-readable-text': 'str' } }
1587 +# Guest UUID information (Universally Unique Identifier).
1589 +# @UUID: the UUID of the guest
1593 +# Notes: If no UUID was specified for the guest, a null UUID is returned.
1595 +{ 'struct': 'UuidInfo', 'data': {'UUID': 'str'} }
1596 diff --git a/qapi/machine.json b/qapi/machine.json
1597 index 47f3facdb2..46760978ae 100644
1598 --- a/qapi/machine.json
1599 +++ b/qapi/machine.json
1601 # This work is licensed under the terms of the GNU GPL, version 2 or later.
1602 # See the COPYING file in the top-level directory.
1604 +{ 'include': 'common.json' }
1609 @@ -228,19 +230,6 @@
1611 { 'command': 'query-target', 'returns': 'TargetInfo' }
1616 -# Guest UUID information (Universally Unique Identifier).
1618 -# @UUID: the UUID of the guest
1622 -# Notes: If no UUID was specified for the guest, a null UUID is returned.
1624 -{ 'struct': 'UuidInfo', 'data': {'UUID': 'str'} }