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>
10 block/meson.build | 5 +
11 block/monitor/block-hmp-cmds.c | 33 ++
13 hmp-commands-info.hx | 13 +
14 hmp-commands.hx | 29 +
15 include/block/block_int.h | 2 +-
16 include/monitor/hmp.h | 3 +
18 monitor/hmp-cmds.c | 44 ++
19 proxmox-backup-client.c | 176 ++++++
20 proxmox-backup-client.h | 59 ++
21 pve-backup.c | 959 +++++++++++++++++++++++++++++++++
22 qapi/block-core.json | 109 ++++
23 qapi/common.json | 13 +
24 qapi/machine.json | 15 +-
25 15 files changed, 1448 insertions(+), 14 deletions(-)
26 create mode 100644 proxmox-backup-client.c
27 create mode 100644 proxmox-backup-client.h
28 create mode 100644 pve-backup.c
30 diff --git a/block/meson.build b/block/meson.build
31 index 12797a5ca3..500d2bf5b3 100644
32 --- a/block/meson.build
33 +++ b/block/meson.build
34 @@ -45,6 +45,11 @@ block_ss.add(files(
35 ), zstd, zlib, gnutls)
37 block_ss.add(files('../vma-writer.c'), libuuid)
39 + '../proxmox-backup-client.c',
41 +), libproxmox_backup_qemu)
44 softmmu_ss.add(when: 'CONFIG_TCG', if_true: files('blkreplay.c'))
46 diff --git a/block/monitor/block-hmp-cmds.c b/block/monitor/block-hmp-cmds.c
47 index ebf1033f31..fc71740026 100644
48 --- a/block/monitor/block-hmp-cmds.c
49 +++ b/block/monitor/block-hmp-cmds.c
50 @@ -1004,3 +1004,36 @@ void hmp_info_snapshots(Monitor *mon, const QDict *qdict)
52 g_free(global_snapshots);
55 +void hmp_backup_cancel(Monitor *mon, const QDict *qdict)
57 + Error *error = NULL;
59 + qmp_backup_cancel(&error);
61 + hmp_handle_error(mon, error);
64 +void hmp_backup(Monitor *mon, const QDict *qdict)
66 + Error *error = NULL;
68 + int dir = qdict_get_try_bool(qdict, "directory", 0);
69 + const char *backup_file = qdict_get_str(qdict, "backupfile");
70 + const char *devlist = qdict_get_try_str(qdict, "devlist");
71 + int64_t speed = qdict_get_try_int(qdict, "speed", 0);
75 + false, NULL, // PBS password
76 + false, NULL, // PBS keyfile
77 + false, NULL, // PBS key_password
78 + false, NULL, // PBS fingerprint
79 + false, NULL, // PBS backup-id
80 + false, 0, // PBS backup-time
81 + true, dir ? BACKUP_FORMAT_DIR : BACKUP_FORMAT_VMA,
82 + false, NULL, false, NULL, !!devlist,
83 + devlist, qdict_haskey(qdict, "speed"), speed, &error);
85 + hmp_handle_error(mon, error);
87 diff --git a/blockdev.c b/blockdev.c
88 index 9cab29e567..5c23744346 100644
92 #include "hw/block/block.h"
93 #include "block/blockjob.h"
94 #include "block/qdict.h"
95 +#include "block/blockjob_int.h"
96 #include "block/throttle-groups.h"
97 #include "monitor/monitor.h"
98 #include "qemu/error-report.h"
99 diff --git a/hmp-commands-info.hx b/hmp-commands-info.hx
100 index c72db5f666..be4d252b8e 100644
101 --- a/hmp-commands-info.hx
102 +++ b/hmp-commands-info.hx
103 @@ -513,6 +513,19 @@ SRST
111 + .help = "show backup status",
112 + .cmd = hmp_info_backup,
117 + Show backup status.
120 #if defined(CONFIG_SLIRP)
123 diff --git a/hmp-commands.hx b/hmp-commands.hx
124 index 0b9d526937..a7bd174e5a 100644
125 --- a/hmp-commands.hx
126 +++ b/hmp-commands.hx
127 @@ -99,6 +99,35 @@ ERST
130 Copy data from a backing file into a block device.
135 + .args_type = "directory:-d,backupfile:s,speed:o?,devlist:s?",
136 + .params = "[-d] backupfile [speed [devlist]]",
137 + .help = "create a VM Backup."
138 + "\n\t\t\t Use -d to dump data into a directory instead"
139 + "\n\t\t\t of using VMA format.",
145 + Create a VM backup.
149 + .name = "backup_cancel",
152 + .help = "cancel the current VM backup",
153 + .cmd = hmp_backup_cancel,
158 + Cancel the current VM backup.
163 diff --git a/include/block/block_int.h b/include/block/block_int.h
164 index bd88198792..03eec075e1 100644
165 --- a/include/block/block_int.h
166 +++ b/include/block/block_int.h
169 typedef int BackupDumpFunc(void *opaque, uint64_t offset, uint64_t bytes, const void *buf);
171 -BlockDriverState *bdrv_backuo_dump_create(
172 +BlockDriverState *bdrv_backup_dump_create(
173 int dump_cb_block_size,
175 BackupDumpFunc *dump_cb,
176 diff --git a/include/monitor/hmp.h b/include/monitor/hmp.h
177 index e287e071d8..1468530adf 100644
178 --- a/include/monitor/hmp.h
179 +++ b/include/monitor/hmp.h
180 @@ -29,6 +29,7 @@ void hmp_info_savevm(Monitor *mon, const QDict *qdict);
181 void hmp_info_migrate(Monitor *mon, const QDict *qdict);
182 void hmp_info_migrate_capabilities(Monitor *mon, const QDict *qdict);
183 void hmp_info_migrate_parameters(Monitor *mon, const QDict *qdict);
184 +void hmp_info_backup(Monitor *mon, const QDict *qdict);
185 void hmp_info_cpus(Monitor *mon, const QDict *qdict);
186 void hmp_info_vnc(Monitor *mon, const QDict *qdict);
187 void hmp_info_spice(Monitor *mon, const QDict *qdict);
188 @@ -72,6 +73,8 @@ void hmp_x_colo_lost_heartbeat(Monitor *mon, const QDict *qdict);
189 void hmp_set_password(Monitor *mon, const QDict *qdict);
190 void hmp_expire_password(Monitor *mon, const QDict *qdict);
191 void hmp_change(Monitor *mon, const QDict *qdict);
192 +void hmp_backup(Monitor *mon, const QDict *qdict);
193 +void hmp_backup_cancel(Monitor *mon, const QDict *qdict);
194 void hmp_migrate(Monitor *mon, const QDict *qdict);
195 void hmp_device_add(Monitor *mon, const QDict *qdict);
196 void hmp_device_del(Monitor *mon, const QDict *qdict);
197 diff --git a/meson.build b/meson.build
198 index 7db08406bd..b4a0f7d314 100644
201 @@ -946,6 +946,7 @@ keyutils = dependency('libkeyutils', required: false,
202 has_gettid = cc.has_function('gettid')
204 libuuid = cc.find_library('uuid', required: true)
205 +libproxmox_backup_qemu = cc.find_library('proxmox_backup_qemu', required: true)
209 diff --git a/monitor/hmp-cmds.c b/monitor/hmp-cmds.c
210 index 948c9d9ff8..65f9148118 100644
211 --- a/monitor/hmp-cmds.c
212 +++ b/monitor/hmp-cmds.c
213 @@ -195,6 +195,50 @@ void hmp_info_mice(Monitor *mon, const QDict *qdict)
214 qapi_free_MouseInfoList(mice_list);
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->has_status) {
229 + if (info->has_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->has_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 static char *SocketAddress_to_str(SocketAddress *addr)
263 switch (addr->type) {
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..66868dec14
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/blockjob.h"
525 +#include "qapi/qapi-commands-block.h"
526 +#include "qapi/qmp/qerror.h"
528 +/* PVE backup state and related function */
531 + * Note: A resume from a qemu_coroutine_yield can happen in a different thread,
532 + * so you may not use normal mutexes within coroutines:
534 + * ---bad-example---
535 + * qemu_rec_mutex_lock(lock)
537 + * qemu_coroutine_yield() // wait for something
538 + * // we are now inside a different thread
539 + * qemu_rec_mutex_unlock(lock) // Crash - wrong thread!!
540 + * ---end-bad-example--
542 + * ==> Always use CoMutext inside coroutines.
543 + * ==> Never acquire/release AioContext withing coroutines (because that use QemuRecMutex)
547 +static struct PVEBackupState {
549 + // Everithing accessed from qmp_backup_query command is protected using lock
558 + size_t transferred;
563 + ProxmoxBackupHandle *pbs;
565 + QemuMutex backup_mutex;
566 + CoMutex dump_callback_mutex;
569 +static void pvebackup_init(void)
571 + qemu_mutex_init(&backup_state.stat.lock);
572 + qemu_mutex_init(&backup_state.backup_mutex);
573 + qemu_co_mutex_init(&backup_state.dump_callback_mutex);
576 +// initialize PVEBackupState at startup
577 +opts_init(pvebackup_init);
579 +typedef struct PVEBackupDevInfo {
580 + BlockDriverState *bs;
584 + char targetfile[PATH_MAX];
585 + BlockDriverState *target;
588 +static void pvebackup_run_next_job(void);
591 +lookup_active_block_job(PVEBackupDevInfo *di)
593 + if (!di->completed && di->bs) {
594 + for (BlockJob *job = block_job_next(NULL); job; job = block_job_next(job)) {
595 + if (job->job.driver->job_type != JOB_TYPE_BACKUP) {
599 + BackupBlockJob *bjob = container_of(job, BackupBlockJob, common);
600 + if (bjob && bjob->source_bs == di->bs) {
608 +static void pvebackup_propagate_error(Error *err)
610 + qemu_mutex_lock(&backup_state.stat.lock);
611 + error_propagate(&backup_state.stat.error, err);
612 + qemu_mutex_unlock(&backup_state.stat.lock);
615 +static bool pvebackup_error_or_canceled(void)
617 + qemu_mutex_lock(&backup_state.stat.lock);
618 + bool error_or_canceled = !!backup_state.stat.error;
619 + qemu_mutex_unlock(&backup_state.stat.lock);
621 + return error_or_canceled;
624 +static void pvebackup_add_transfered_bytes(size_t transferred, size_t zero_bytes)
626 + qemu_mutex_lock(&backup_state.stat.lock);
627 + backup_state.stat.zero_bytes += zero_bytes;
628 + backup_state.stat.transferred += transferred;
629 + qemu_mutex_unlock(&backup_state.stat.lock);
632 +// This may get called from multiple coroutines in multiple io-threads
633 +// Note1: this may get called after job_cancel()
634 +static int coroutine_fn
635 +pvebackup_co_dump_pbs_cb(
641 + assert(qemu_in_coroutine());
643 + const uint64_t size = bytes;
644 + const unsigned char *buf = pbuf;
645 + PVEBackupDevInfo *di = opaque;
647 + assert(backup_state.pbs);
649 + Error *local_err = NULL;
652 + qemu_co_mutex_lock(&backup_state.dump_callback_mutex);
654 + // avoid deadlock if job is cancelled
655 + if (pvebackup_error_or_canceled()) {
656 + qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
660 + pbs_res = proxmox_backup_co_write_data(backup_state.pbs, di->dev_id, buf, start, size, &local_err);
661 + qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
664 + pvebackup_propagate_error(local_err);
667 + pvebackup_add_transfered_bytes(size, !buf ? size : 0);
673 +// This may get called from multiple coroutines in multiple io-threads
674 +static int coroutine_fn
675 +pvebackup_co_dump_vma_cb(
681 + assert(qemu_in_coroutine());
683 + const uint64_t size = bytes;
684 + const unsigned char *buf = pbuf;
685 + PVEBackupDevInfo *di = opaque;
689 + assert(backup_state.vmaw);
691 + uint64_t remaining = size;
693 + uint64_t cluster_num = start / VMA_CLUSTER_SIZE;
694 + if ((cluster_num * VMA_CLUSTER_SIZE) != start) {
695 + Error *local_err = NULL;
696 + error_setg(&local_err,
697 + "got unaligned write inside backup dump "
698 + "callback (sector %ld)", start);
699 + pvebackup_propagate_error(local_err);
700 + return -1; // not aligned to cluster size
703 + while (remaining > 0) {
704 + qemu_co_mutex_lock(&backup_state.dump_callback_mutex);
705 + // avoid deadlock if job is cancelled
706 + if (pvebackup_error_or_canceled()) {
707 + qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
711 + size_t zero_bytes = 0;
712 + ret = vma_writer_write(backup_state.vmaw, di->dev_id, cluster_num, buf, &zero_bytes);
713 + qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
717 + buf += VMA_CLUSTER_SIZE;
720 + Error *local_err = NULL;
721 + vma_writer_error_propagate(backup_state.vmaw, &local_err);
722 + pvebackup_propagate_error(local_err);
725 + if (remaining >= VMA_CLUSTER_SIZE) {
726 + assert(ret == VMA_CLUSTER_SIZE);
727 + pvebackup_add_transfered_bytes(VMA_CLUSTER_SIZE, zero_bytes);
728 + remaining -= VMA_CLUSTER_SIZE;
730 + assert(ret == remaining);
731 + pvebackup_add_transfered_bytes(remaining, zero_bytes);
740 +// assumes the caller holds backup_mutex
741 +static void coroutine_fn pvebackup_co_cleanup(void *unused)
743 + assert(qemu_in_coroutine());
745 + qemu_mutex_lock(&backup_state.stat.lock);
746 + backup_state.stat.end_time = time(NULL);
747 + qemu_mutex_unlock(&backup_state.stat.lock);
749 + if (backup_state.vmaw) {
750 + Error *local_err = NULL;
751 + vma_writer_close(backup_state.vmaw, &local_err);
753 + if (local_err != NULL) {
754 + pvebackup_propagate_error(local_err);
757 + backup_state.vmaw = NULL;
760 + if (backup_state.pbs) {
761 + if (!pvebackup_error_or_canceled()) {
762 + Error *local_err = NULL;
763 + proxmox_backup_co_finish(backup_state.pbs, &local_err);
764 + if (local_err != NULL) {
765 + pvebackup_propagate_error(local_err);
769 + proxmox_backup_disconnect(backup_state.pbs);
770 + backup_state.pbs = NULL;
773 + g_list_free(backup_state.di_list);
774 + backup_state.di_list = NULL;
777 +// assumes the caller holds backup_mutex
778 +static void coroutine_fn pvebackup_complete_stream(void *opaque)
780 + PVEBackupDevInfo *di = opaque;
782 + bool error_or_canceled = pvebackup_error_or_canceled();
784 + if (backup_state.vmaw) {
785 + vma_writer_close_stream(backup_state.vmaw, di->dev_id);
788 + if (backup_state.pbs && !error_or_canceled) {
789 + Error *local_err = NULL;
790 + proxmox_backup_co_close_image(backup_state.pbs, di->dev_id, &local_err);
791 + if (local_err != NULL) {
792 + pvebackup_propagate_error(local_err);
797 +static void pvebackup_complete_cb(void *opaque, int ret)
799 + assert(!qemu_in_coroutine());
801 + PVEBackupDevInfo *di = opaque;
803 + qemu_mutex_lock(&backup_state.backup_mutex);
805 + di->completed = true;
808 + Error *local_err = NULL;
809 + error_setg(&local_err, "job failed with err %d - %s", ret, strerror(-ret));
810 + pvebackup_propagate_error(local_err);
815 + assert(di->target == NULL);
817 + block_on_coroutine_fn(pvebackup_complete_stream, di);
819 + // remove self from job queue
820 + backup_state.di_list = g_list_remove(backup_state.di_list, di);
824 + qemu_mutex_unlock(&backup_state.backup_mutex);
826 + pvebackup_run_next_job();
829 +static void pvebackup_cancel(void)
831 + assert(!qemu_in_coroutine());
833 + Error *cancel_err = NULL;
834 + error_setg(&cancel_err, "backup canceled");
835 + pvebackup_propagate_error(cancel_err);
837 + qemu_mutex_lock(&backup_state.backup_mutex);
839 + if (backup_state.vmaw) {
840 + /* make sure vma writer does not block anymore */
841 + vma_writer_set_error(backup_state.vmaw, "backup canceled");
844 + if (backup_state.pbs) {
845 + proxmox_backup_abort(backup_state.pbs, "backup canceled");
848 + qemu_mutex_unlock(&backup_state.backup_mutex);
852 + BlockJob *next_job = NULL;
854 + qemu_mutex_lock(&backup_state.backup_mutex);
856 + GList *l = backup_state.di_list;
858 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
859 + l = g_list_next(l);
861 + BlockJob *job = lookup_active_block_job(di);
868 + qemu_mutex_unlock(&backup_state.backup_mutex);
871 + AioContext *aio_context = next_job->job.aio_context;
872 + aio_context_acquire(aio_context);
873 + job_cancel_sync(&next_job->job);
874 + aio_context_release(aio_context);
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(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 + AioContext *aio_context = job->job.aio_context;
955 + aio_context_acquire(aio_context);
957 + if (job_should_pause(&job->job)) {
958 + bool error_or_canceled = pvebackup_error_or_canceled();
959 + if (error_or_canceled) {
960 + job_cancel_sync(&job->job);
962 + job_resume(&job->job);
965 + aio_context_release(aio_context);
970 + block_on_coroutine_fn(pvebackup_co_cleanup, NULL); // no more jobs, run cleanup
972 + qemu_mutex_unlock(&backup_state.backup_mutex);
975 +static bool create_backup_jobs(void) {
977 + assert(!qemu_in_coroutine());
979 + Error *local_err = NULL;
981 + BackupPerf perf = { .max_workers = 16 };
983 + /* create and start all jobs (paused state) */
984 + GList *l = backup_state.di_list;
986 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
987 + l = g_list_next(l);
989 + assert(di->target != NULL);
991 + AioContext *aio_context = bdrv_get_aio_context(di->bs);
992 + aio_context_acquire(aio_context);
994 + BlockJob *job = backup_job_create(
995 + NULL, di->bs, di->target, backup_state.speed, MIRROR_SYNC_MODE_FULL, NULL,
996 + BITMAP_SYNC_MODE_NEVER, false, NULL, &perf, BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
997 + JOB_DEFAULT, pvebackup_complete_cb, di, NULL, &local_err);
999 + aio_context_release(aio_context);
1001 + if (!job || local_err != NULL) {
1002 + Error *create_job_err = NULL;
1003 + error_setg(&create_job_err, "backup_job_create failed: %s",
1004 + local_err ? error_get_pretty(local_err) : "null");
1006 + pvebackup_propagate_error(create_job_err);
1009 + job_start(&job->job);
1011 + bdrv_unref(di->target);
1012 + di->target = NULL;
1015 + bool errors = pvebackup_error_or_canceled();
1018 + l = backup_state.di_list;
1020 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
1021 + l = g_list_next(l);
1024 + bdrv_unref(di->target);
1025 + di->target = NULL;
1033 +typedef struct QmpBackupTask {
1034 + const char *backup_file;
1035 + bool has_password;
1036 + const char *password;
1038 + const char *keyfile;
1039 + bool has_key_password;
1040 + const char *key_password;
1041 + bool has_backup_id;
1042 + const char *backup_id;
1043 + bool has_backup_time;
1044 + const char *fingerprint;
1045 + bool has_fingerprint;
1046 + int64_t backup_time;
1048 + BackupFormat format;
1049 + bool has_config_file;
1050 + const char *config_file;
1051 + bool has_firewall_file;
1052 + const char *firewall_file;
1054 + const char *devlist;
1061 +// assumes the caller holds backup_mutex
1062 +static void coroutine_fn pvebackup_co_prepare(void *opaque)
1064 + assert(qemu_in_coroutine());
1066 + QmpBackupTask *task = opaque;
1068 + task->result = NULL; // just to be sure
1070 + BlockBackend *blk;
1071 + BlockDriverState *bs = NULL;
1072 + const char *backup_dir = NULL;
1073 + Error *local_err = NULL;
1075 + VmaWriter *vmaw = NULL;
1076 + ProxmoxBackupHandle *pbs = NULL;
1077 + gchar **devs = NULL;
1078 + GList *di_list = NULL;
1080 + UuidInfo *uuid_info;
1082 + const char *config_name = "qemu-server.conf";
1083 + const char *firewall_name = "qemu-server.fw";
1085 + if (backup_state.di_list) {
1086 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
1087 + "previous backup not finished");
1091 + /* Todo: try to auto-detect format based on file name */
1092 + BackupFormat format = task->has_format ? task->format : BACKUP_FORMAT_VMA;
1094 + if (task->has_devlist) {
1095 + devs = g_strsplit_set(task->devlist, ",;:", -1);
1099 + blk = blk_by_name(*d);
1102 + if (!bdrv_is_inserted(bs)) {
1103 + error_setg(task->errp, QERR_DEVICE_HAS_NO_MEDIUM, *d);
1106 + PVEBackupDevInfo *di = g_new0(PVEBackupDevInfo, 1);
1108 + di_list = g_list_append(di_list, di);
1110 + error_set(task->errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1111 + "Device '%s' not found", *d);
1118 + BdrvNextIterator it;
1121 + for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
1122 + if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
1126 + PVEBackupDevInfo *di = g_new0(PVEBackupDevInfo, 1);
1128 + di_list = g_list_append(di_list, di);
1133 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "empty device list");
1141 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
1142 + l = g_list_next(l);
1143 + if (bdrv_op_is_blocked(di->bs, BLOCK_OP_TYPE_BACKUP_SOURCE, task->errp)) {
1147 + ssize_t size = bdrv_getlength(di->bs);
1149 + error_setg_errno(task->errp, -di->size, "bdrv_getlength failed");
1156 + uuid_generate(uuid);
1158 + if (format == BACKUP_FORMAT_PBS) {
1159 + if (!task->has_password) {
1160 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "missing parameter 'password'");
1163 + if (!task->has_backup_id) {
1164 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "missing parameter 'backup-id'");
1167 + if (!task->has_backup_time) {
1168 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "missing parameter 'backup-time'");
1172 + int dump_cb_block_size = PROXMOX_BACKUP_DEFAULT_CHUNK_SIZE; // Hardcoded (4M)
1173 + firewall_name = "fw.conf";
1175 + char *pbs_err = NULL;
1176 + pbs = proxmox_backup_new(
1177 + task->backup_file,
1179 + task->backup_time,
1180 + dump_cb_block_size,
1181 + task->has_password ? task->password : NULL,
1182 + task->has_keyfile ? task->keyfile : NULL,
1183 + task->has_key_password ? task->key_password : NULL,
1184 + task->has_fingerprint ? task->fingerprint : NULL,
1188 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
1189 + "proxmox_backup_new failed: %s", pbs_err);
1190 + proxmox_backup_free_error(pbs_err);
1194 + if (proxmox_backup_co_connect(pbs, task->errp) < 0)
1197 + /* register all devices */
1200 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
1201 + l = g_list_next(l);
1203 + const char *devname = bdrv_get_device_name(di->bs);
1205 + int dev_id = proxmox_backup_co_register_image(pbs, devname, di->size, task->errp);
1209 + if (!(di->target = bdrv_backup_dump_create(dump_cb_block_size, di->size, pvebackup_co_dump_pbs_cb, di, task->errp))) {
1213 + di->dev_id = dev_id;
1215 + } else if (format == BACKUP_FORMAT_VMA) {
1216 + vmaw = vma_writer_create(task->backup_file, uuid, &local_err);
1219 + error_propagate(task->errp, local_err);
1224 + /* register all devices for vma writer */
1227 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
1228 + l = g_list_next(l);
1230 + if (!(di->target = bdrv_backup_dump_create(VMA_CLUSTER_SIZE, di->size, pvebackup_co_dump_vma_cb, di, task->errp))) {
1234 + const char *devname = bdrv_get_device_name(di->bs);
1235 + di->dev_id = vma_writer_register_stream(vmaw, devname, di->size);
1236 + if (di->dev_id <= 0) {
1237 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
1238 + "register_stream failed");
1242 + } else if (format == BACKUP_FORMAT_DIR) {
1243 + if (mkdir(task->backup_file, 0640) != 0) {
1244 + error_setg_errno(task->errp, errno, "can't create directory '%s'\n",
1245 + task->backup_file);
1248 + backup_dir = task->backup_file;
1252 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
1253 + l = g_list_next(l);
1255 + const char *devname = bdrv_get_device_name(di->bs);
1256 + snprintf(di->targetfile, PATH_MAX, "%s/%s.raw", backup_dir, devname);
1258 + int flags = BDRV_O_RDWR;
1259 + bdrv_img_create(di->targetfile, "raw", NULL, NULL, NULL,
1260 + di->size, flags, false, &local_err);
1262 + error_propagate(task->errp, local_err);
1266 + di->target = bdrv_open(di->targetfile, NULL, NULL, flags, &local_err);
1267 + if (!di->target) {
1268 + error_propagate(task->errp, local_err);
1273 + error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "unknown backup format");
1278 + /* add configuration file to archive */
1279 + if (task->has_config_file) {
1280 + if (pvebackup_co_add_config(task->config_file, config_name, format, backup_dir,
1281 + vmaw, pbs, task->errp) != 0) {
1286 + /* add firewall file to archive */
1287 + if (task->has_firewall_file) {
1288 + if (pvebackup_co_add_config(task->firewall_file, firewall_name, format, backup_dir,
1289 + vmaw, pbs, task->errp) != 0) {
1293 + /* initialize global backup_state now */
1295 + qemu_mutex_lock(&backup_state.stat.lock);
1297 + if (backup_state.stat.error) {
1298 + error_free(backup_state.stat.error);
1299 + backup_state.stat.error = NULL;
1302 + backup_state.stat.start_time = time(NULL);
1303 + backup_state.stat.end_time = 0;
1305 + if (backup_state.stat.backup_file) {
1306 + g_free(backup_state.stat.backup_file);
1308 + backup_state.stat.backup_file = g_strdup(task->backup_file);
1310 + uuid_copy(backup_state.stat.uuid, uuid);
1311 + uuid_unparse_lower(uuid, backup_state.stat.uuid_str);
1312 + char *uuid_str = g_strdup(backup_state.stat.uuid_str);
1314 + backup_state.stat.total = total;
1315 + backup_state.stat.transferred = 0;
1316 + backup_state.stat.zero_bytes = 0;
1318 + qemu_mutex_unlock(&backup_state.stat.lock);
1320 + backup_state.speed = (task->has_speed && task->speed > 0) ? task->speed : 0;
1322 + backup_state.vmaw = vmaw;
1323 + backup_state.pbs = pbs;
1325 + backup_state.di_list = di_list;
1327 + uuid_info = g_malloc0(sizeof(*uuid_info));
1328 + uuid_info->UUID = uuid_str;
1330 + task->result = uuid_info;
1337 + PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
1338 + l = g_list_next(l);
1341 + bdrv_unref(di->target);
1344 + if (di->targetfile[0]) {
1345 + unlink(di->targetfile);
1349 + g_list_free(di_list);
1356 + Error *err = NULL;
1357 + vma_writer_close(vmaw, &err);
1358 + unlink(task->backup_file);
1362 + proxmox_backup_disconnect(pbs);
1366 + rmdir(backup_dir);
1369 + task->result = NULL;
1373 +UuidInfo *qmp_backup(
1374 + const char *backup_file,
1375 + bool has_password, const char *password,
1376 + bool has_keyfile, const char *keyfile,
1377 + bool has_key_password, const char *key_password,
1378 + bool has_fingerprint, const char *fingerprint,
1379 + bool has_backup_id, const char *backup_id,
1380 + bool has_backup_time, int64_t backup_time,
1381 + bool has_format, BackupFormat format,
1382 + bool has_config_file, const char *config_file,
1383 + bool has_firewall_file, const char *firewall_file,
1384 + bool has_devlist, const char *devlist,
1385 + bool has_speed, int64_t speed, Error **errp)
1387 + QmpBackupTask task = {
1388 + .backup_file = backup_file,
1389 + .has_password = has_password,
1390 + .password = password,
1391 + .has_key_password = has_key_password,
1392 + .key_password = key_password,
1393 + .has_fingerprint = has_fingerprint,
1394 + .fingerprint = fingerprint,
1395 + .has_backup_id = has_backup_id,
1396 + .backup_id = backup_id,
1397 + .has_backup_time = has_backup_time,
1398 + .backup_time = backup_time,
1399 + .has_format = has_format,
1401 + .has_config_file = has_config_file,
1402 + .config_file = config_file,
1403 + .has_firewall_file = has_firewall_file,
1404 + .firewall_file = firewall_file,
1405 + .has_devlist = has_devlist,
1406 + .devlist = devlist,
1407 + .has_speed = has_speed,
1412 + qemu_mutex_lock(&backup_state.backup_mutex);
1414 + block_on_coroutine_fn(pvebackup_co_prepare, &task);
1416 + if (*errp == NULL) {
1417 + create_backup_jobs();
1418 + qemu_mutex_unlock(&backup_state.backup_mutex);
1419 + pvebackup_run_next_job();
1421 + qemu_mutex_unlock(&backup_state.backup_mutex);
1424 + return task.result;
1427 +BackupStatus *qmp_query_backup(Error **errp)
1429 + BackupStatus *info = g_malloc0(sizeof(*info));
1431 + qemu_mutex_lock(&backup_state.stat.lock);
1433 + if (!backup_state.stat.start_time) {
1434 + /* not started, return {} */
1435 + qemu_mutex_unlock(&backup_state.stat.lock);
1439 + info->has_status = true;
1440 + info->has_start_time = true;
1441 + info->start_time = backup_state.stat.start_time;
1443 + if (backup_state.stat.backup_file) {
1444 + info->has_backup_file = true;
1445 + info->backup_file = g_strdup(backup_state.stat.backup_file);
1448 + info->has_uuid = true;
1449 + info->uuid = g_strdup(backup_state.stat.uuid_str);
1451 + if (backup_state.stat.end_time) {
1452 + if (backup_state.stat.error) {
1453 + info->status = g_strdup("error");
1454 + info->has_errmsg = true;
1455 + info->errmsg = g_strdup(error_get_pretty(backup_state.stat.error));
1457 + info->status = g_strdup("done");
1459 + info->has_end_time = true;
1460 + info->end_time = backup_state.stat.end_time;
1462 + info->status = g_strdup("active");
1465 + info->has_total = true;
1466 + info->total = backup_state.stat.total;
1467 + info->has_zero_bytes = true;
1468 + info->zero_bytes = backup_state.stat.zero_bytes;
1469 + info->has_transferred = true;
1470 + info->transferred = backup_state.stat.transferred;
1472 + qemu_mutex_unlock(&backup_state.stat.lock);
1476 diff --git a/qapi/block-core.json b/qapi/block-core.json
1477 index 46b14cdf67..890fc9dede 100644
1478 --- a/qapi/block-core.json
1479 +++ b/qapi/block-core.json
1480 @@ -683,6 +683,115 @@
1481 { 'command': 'query-block', 'returns': ['BlockInfo'] }
1487 +# Detailed backup status.
1489 +# @status: string describing the current backup status.
1490 +# This can be 'active', 'done', 'error'. If this field is not
1491 +# returned, no backup process has been initiated
1493 +# @errmsg: error message (only returned if status is 'error')
1495 +# @total: total amount of bytes involved in the backup process
1497 +# @transferred: amount of bytes already backed up.
1499 +# @zero-bytes: amount of 'zero' bytes detected.
1501 +# @start-time: time (epoch) when backup job started.
1503 +# @end-time: time (epoch) when backup job finished.
1505 +# @backup-file: backup file name
1507 +# @uuid: uuid for this backup job
1510 +{ 'struct': 'BackupStatus',
1511 + 'data': {'*status': 'str', '*errmsg': 'str', '*total': 'int',
1512 + '*transferred': 'int', '*zero-bytes': 'int',
1513 + '*start-time': 'int', '*end-time': 'int',
1514 + '*backup-file': 'str', '*uuid': 'str' } }
1519 +# An enumeration of supported backup formats.
1521 +# @vma: Proxmox vma backup format
1523 +{ 'enum': 'BackupFormat',
1524 + 'data': [ 'vma', 'dir', 'pbs' ] }
1529 +# Starts a VM backup.
1531 +# @backup-file: the backup file name
1533 +# @format: format of the backup file
1535 +# @config-file: a configuration file to include into
1536 +# the backup archive.
1538 +# @speed: the maximum speed, in bytes per second
1540 +# @devlist: list of block device names (separated by ',', ';'
1541 +# or ':'). By default the backup includes all writable block devices.
1543 +# @password: backup server passsword (required for format 'pbs')
1545 +# @keyfile: keyfile used for encryption (optional for format 'pbs')
1547 +# @key-password: password for keyfile (optional for format 'pbs')
1549 +# @fingerprint: server cert fingerprint (optional for format 'pbs')
1551 +# @backup-id: backup ID (required for format 'pbs')
1553 +# @backup-time: backup timestamp (Unix epoch, required for format 'pbs')
1555 +# Returns: the uuid of the backup job
1558 +{ 'command': 'backup', 'data': { 'backup-file': 'str',
1559 + '*password': 'str',
1560 + '*keyfile': 'str',
1561 + '*key-password': 'str',
1562 + '*fingerprint': 'str',
1563 + '*backup-id': 'str',
1564 + '*backup-time': 'int',
1565 + '*format': 'BackupFormat',
1566 + '*config-file': 'str',
1567 + '*firewall-file': 'str',
1568 + '*devlist': 'str', '*speed': 'int' },
1569 + 'returns': 'UuidInfo' }
1574 +# Returns information about current/last backup task.
1576 +# Returns: @BackupStatus
1579 +{ 'command': 'query-backup', 'returns': 'BackupStatus' }
1584 +# Cancel the current executing backup process.
1586 +# Returns: nothing on success
1588 +# Notes: This command succeeds even if there is no backup process running.
1591 +{ 'command': 'backup-cancel' }
1594 # @BlockDeviceTimedStats:
1596 diff --git a/qapi/common.json b/qapi/common.json
1597 index 7c976296f0..0690b07903 100644
1598 --- a/qapi/common.json
1599 +++ b/qapi/common.json
1600 @@ -197,3 +197,16 @@
1601 { 'enum': 'GrabToggleKeys',
1602 'data': [ 'ctrl-ctrl', 'alt-alt', 'shift-shift','meta-meta', 'scrolllock',
1603 'ctrl-scrolllock' ] }
1608 +# Guest UUID information (Universally Unique Identifier).
1610 +# @UUID: the UUID of the guest
1614 +# Notes: If no UUID was specified for the guest, a null UUID is returned.
1616 +{ 'struct': 'UuidInfo', 'data': {'UUID': 'str'} }
1617 diff --git a/qapi/machine.json b/qapi/machine.json
1618 index 7f5ba02c95..9923098e40 100644
1619 --- a/qapi/machine.json
1620 +++ b/qapi/machine.json
1622 # This work is licensed under the terms of the GNU GPL, version 2 or later.
1623 # See the COPYING file in the top-level directory.
1625 +{ 'include': 'common.json' }
1630 @@ -229,19 +231,6 @@
1632 { 'command': 'query-target', 'returns': 'TargetInfo' }
1637 -# Guest UUID information (Universally Unique Identifier).
1639 -# @UUID: the UUID of the guest
1643 -# Notes: If no UUID was specified for the guest, a null UUID is returned.
1645 -{ 'struct': 'UuidInfo', 'data': {'UUID': 'str'} }