QEMU Guest Agent (virtagent) v7
PATCH 3/3 QEMU Guest Agent (virtagent) v7
This is Set 3/3 of the QAPI+QGA patchsets.
These patches apply on top of qapi-backport-set2-v6, and can also be obtained from:git://repo.or.cz/qemu/mdroth.git qapi-backport-set3-v7
(Set1+2 are a backport of some of the QAPI-related work from Anthony's glib tree. The main goal is to get the basic code generation infrastructure in place so that it can be used by the guest agent to implement a QMP-like guest interface, and so that future work regarding the QMP conversion to QAPI can be decoupled from the infrastructure bits. Set3 is the Qemu Guest Agent (virtagent), rebased on the new code QAPI code generation infrastructure. This is the first user of QAPI, QMP will follow.)
___
CHANGES SINCE V6:
- Made "/dev/virtio-ports/org.qemu.guest_agent.0" default device path for agent
- Consolidated uneeded fcntl() calls into qemu_open()
- JSON/QMP parse errors now propagated to client
- Replaced non-assertion uses of g_error() with exit()
- Added guest-file-flush
- Removed limit on max read size for guest-file-read
- 'count' parameters to guest-file-read/guest-file-write are now optional (default to 4KB and size of provided buffer, base64-decoded, respectively)
- Removed redundant 'file_' and 'shutdown_' prefixes from guest-file-*/guest-shutdown commands, switched to "-" in place of "_" in parameter names, renamed guest-file-read's "buf" param to "buf-b64" and guest-file-write's "data_b64" param to "buf-b64" for consistency.
- guest-fsfreeze-freeze now returns error objects on error rather as part of it's integer return values, and on error will unfreeze previously frozen filesystems.
- GUEST_FSFREEZE_STATUS_INPROGRESS removed, GUEST_FSFREEZE_STATUS_ERROR now serves the explicit purpose of noting a failure to find a previously mounted filesytem/directory after initial freeze, or failure to unfreeze 1 or more filesystems.
- -c/--channel option to qemu-ga is now -m/--method
CHANGES SINCE V5:
- switched to using qemu malloc/list functions where possible
- removed unused proxy_path field in struct GAState
- pid file now opened write-only, removed lockf() in favor of O_EXCL, added SIGINT/SIGTERM signal handlers to handle cleanup
- cleaned up error-handling, switched to asserts where appropriate, removed unecessary gotos and NULL checks for qemu_free()/qobject_decref()
- refactored send_payload() using helper functions
- fixed improper handling of pidfile fd==0
- changed guest-shutdown's "shutdown_mode" param to "mode"
- switched to using kernel-generated FDs for guest-file-open rather than an autoincrement value
- add maximum chunk size of guest-file-read/guest-file-write
- added checks to avoid guest-file-write from writing data beyond the provided data buffer
- made logging best-effort, removed handling of failures to log as errors
- guest-shutdown exec errors now logged to guest syslog, clarified shutdown's asynchronous, no gauruntee nature in schema.
CHANGES SINCE V4:
- Removed timeout mechanism via worker thread/pthread_cancel due to potential memory leak. Will re-introduce guest-side timeout support in future version.
- Fixed up fsfreeze code to use enums specified within the guest agent's qapi schema.
- Fixed memory leak due to a log statement, and added missing cleanup functions for heap-allocated g_error objects.
- Made "mode" param to guest-file-open optional, defaults to "r" (read-only)
CHANGES SINCE V3:
- Fixed error-handling issues in fsfreeze commands leading to certain mounted directories causing freeze/thaw operations to fail
- Added cleanup hook to thaw filesystems on graceful guest agent exit
- Removed unused enum values and added additional details to schema documentation
- Fixed build issue that was missed due to deprecated files in source tree, removed unused includes
CHANGES SINCE V2:
- Rebased on new QAPI code generation framework
- Dropped ability for QMP to act as a proxy for the guest agent, will be added when new QMP server is backported from Anthony's glib tree
- Replaced negotiation/control events with a simple 2-way handshake implemented by a standard RPC (guest-sync)
- Removed enforcement of "pristine" sessions, state is now global/persistant across multiple clients/connections
- Fixed segfault in logging code
- Added Jes' filesystem freeze patches
- General cleanups
CHANGES SINCE V1:
- Added guest agent worker thread to execute RPCs in the guest. With this in place we have a reliable timeout mechanism for hung commands, currently set at 30 seconds.
- Add framework for registering init/cleanup routines for stateful RPCs to clean up after themselves after a timeout.
- Added the following RPCs: guest-file-{open,close,read,write,seek}, guest-shutdown, guest-info, and removed stubs for guest-view-file (now deprecated)
- Added GUEST_AGENT_UP/GUEST_AGENT_DOWN QMP events
- Switched to a TCP-style host-initiated 3-way handshake for channel negotiation, this simplifies client negotiation/interaction over the wire
- Added configurable log level/log file/pid file options for guest agent
- Various fixes for bugs/memory leaks and checkpatch.pl fixups
ISSUES/TODOS:
- Add unit tests for guest agent wire protocol
OVERVIEW
For a better overview of what these patches are meant to accomplish, please reference the RFC for virtagent:
http://comments.gmane.org/gmane.comp.emulators.qemu/96096
These patches integrate the previous virtagent guest agent work directly in QAPI/QMP to leverage it's auto-generated marshalling code. This has numerous benefits:
- addresses previous concerns over relying on external libraries to handle data encapsulation
- reduces the need for manual unmarshalling of requests/responses, which makes adding new RPCs much safer/less error-prone, as well as cutting down on redundant code
- QAPI documentation aligns completely with guest-side RPC implementation
- is Just Better (TM)
BUILD/USAGE
build:
./configure --target-list=x86_64-softmmu make
make qemu-ga #should be built on|for target guest
start guest:
qemu \
-drive file=/home/mdroth/vm/rhel6_64_base.raw,snapshot=off,if=virtio \
-net nic,model=virtio,macaddr=52:54:00:12:34:00 \
-net tap,script=/etc/qemu-ifup \
-vnc :1 -m 1024 --enable-kvm \
-chardev socket,path=/tmp/qga.sock,server,nowait,id=qga0 \
-device virtio-serial \
-device virtserialport,chardev=qga0,name=org.qemu.guest_agent.0"
use guest agent:
./qemu-ga -h
./qemu-ga -m virtio-serial -p /dev/virtio-ports/org.qemu.guest_agent.0
start/use qmp:
mdroth@illuin:~$ sudo socat unix-connect:/tmp/qga.sock readline
{"execute":"guest-sync", "arguments":{"id":1234}}
{"return": 1234} {"execute":"guest-ping"}
{"return": {}}
{"execute": "guest-info"}
{"return": {"version": "1.0"}}
// write "hello world!\n" to /tmp/testqga
{"execute":"guest-file-open", "arguments":{"path":"/tmp/testqga","mode":"w+"}} {"return": 0}
{"execute":"guest-file-write", "arguments":{"handle":0,"buf-b64":"aGVsbG8gd29ybGQhCg=="}} {"return": {"count": 13, "eof": false}}
{"execute":"guest-file-close", "arguments":{"handle":0}}
{"return": {}}
// read back the "hello world!\n" from /tmp/testqga {"execute":"guest-file-open", "arguments":{"path":"/tmp/testqga","mode":"r"}} {"return": 1}
{"execute":"guest-file-read", "arguments":{"handle":1,"count":1024}} {"return": {"buf-b64": "aGVsbG8gd29ybGQhCg==", "count": 13, "eof": true}} {"execute":"guest-file-close","arguments":{"handle":1}} {"return": {}}
Makefile | 25 ++- configure | 1 + qapi-schema-guest.json | 217 +++++++++++++ qemu-ga.c | 671 +++++++++++++++++++++++++++++++++++++++ qerror.c | 13 + qerror.h | 6 + qga/guest-agent-command-state.c | 73 +++++ qga/guest-agent-commands.c | 512 +++++++++++++++++++++++++++++ qga/guest-agent-core.h | 31 ++ 9 files changed, 1544 insertions(+), 5 deletions(-)
PATCH v7 1/4 qerror: add QERR_JSON_PARSE_ERROR to qerror.c
Missing from previous addition of error to qerror.h. Needed for qerror_format() and friends.
--- qerror.c | 5 +++++ 1 files changed, 5 insertions(+), 0 deletions(-)
qerror.c +5 -0
@@ -141,6 +141,11 @@ static const QErrorStringTable qerror_table[] = { .desc = "Invalid JSON syntax", }, { + .error_fmt = QERR_JSON_PARSE_ERROR, + .desc = "JSON parse error, %(message)", + + }, + { .error_fmt = QERR_KVM_MISSING_CAP, .desc = "Using KVM without %(capability), %(feature) unavailable", },
Signature · 1 line
1.7.0.4
PATCH v7 2/4 guest agent: command state class
In reply to Michael Roth--- Makefile | 4 ++- configure | 1 + qga/guest-agent-command-state.c | 73 +++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 25 +++++++++++++ 4 files changed, 102 insertions(+), 1 deletions(-) create mode 100644 qga/guest-agent-command-state.c create mode 100644 qga/guest-agent-core.h
Makefile +3 -1
@@ -181,6 +181,8 @@ test-visitor: test-visitor.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o $ test-qmp-commands.o: $(addprefix $(qapi-dir)/, test-qapi-types.c test-qapi-types.h test-qapi-visit.c test-qapi-visit.h test-qmp-marshal.c test-qmp-commands.h) test-qmp-commands: test-qmp-commands.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o $(qapi-obj-y) error.o osdep.o qemu-malloc.o $(oslib-obj-y) qjson.o json-streamer.o json-lexer.o json-parser.o qerror.o qemu-error.o qemu-tool.o $(qapi-dir)/test-qapi-visit.o $(qapi-dir)/test-qapi-types.o $(qapi-dir)/test-qmp-marshal.o module.o +QGALIB=qga/guest-agent-command-state.o + QEMULIBS=libhw32 libhw64 libuser libdis libdis-user clean:
@@ -189,7 +191,7 @@ clean: rm -f qemu-options.def rm -f *.o *.d *.a *.lo $(TOOLS) TAGS cscope.* *.pod *~ */*~ rm -Rf .libs - rm -f slirp/*.o slirp/*.d audio/*.o audio/*.d block/*.o block/*.d net/*.o net/*.d fsdev/*.o fsdev/*.d ui/*.o ui/*.d qapi/*.o qapi/*.d + rm -f slirp/*.o slirp/*.d audio/*.o audio/*.d block/*.o block/*.d net/*.o net/*.d fsdev/*.o fsdev/*.d ui/*.o ui/*.d qapi/*.o qapi/*.d qga/*.o qga/*.d rm -f qemu-img-cmds.h rm -f trace.c trace.h trace.c-timestamp trace.h-timestamp rm -f trace-dtrace.dtrace trace-dtrace.dtrace-timestamp
configure +1 -0
@@ -3487,6 +3487,7 @@ DIRS="$DIRS pc-bios/spapr-rtas" DIRS="$DIRS roms/seabios roms/vgabios" DIRS="$DIRS fsdev ui" DIRS="$DIRS qapi" +DIRS="$DIRS qga" FILES="Makefile tests/Makefile" FILES="$FILES tests/cris/Makefile tests/cris/.gdbinit" FILES="$FILES pc-bios/optionrom/Makefile pc-bios/keymaps"
qga/guest-agent-command-state.c new file +73 -0
73 lines not on this page · raw message
qga/guest-agent-core.h new file +25 -0
@@ -0,0 +1,25 @@ +/* +* QEMU Guest Agent core declarations +* +* Copyright IBM Corp. 2011 +* +* Authors: +* Adam Litke <[email protected]> +* Michael Roth <[email protected]> +* +* This work is licensed under the terms of the GNU GPL, version 2 or later. +* See the COPYING file in the top-level directory. +*/ +#include "qapi/qmp-core.h" +#include "qemu-common.h" + +#define QGA_VERSION "1.0" + +typedef struct GACommandState GACommandState ; + +void ga_command_state_add (GACommandState *cs, +void (*init)(void ), +void (*cleanup)(void )); +void ga_command_state_init_all (GACommandState *cs); +void ga_command_state_cleanup_all (GACommandState *cs); +GACommandState *ga_command_state_new (void );
Signature · 1 line
1.7.0.4
PATCH v7 3/4 guest agent: qemu-ga daemon
In reply to Michael RothThis is the actual guest daemon, it listens for requests over a virtio-serial/isa-serial/unix socket channel and routes them through to dispatch routines, and writes the results back to the channel in a manner similar to QMP.
A shorthand invocation:
qemu-ga -d
Is equivalent to:
qemu-ga -m virtio-serial -p /dev/virtio-ports/org.qemu.guest_agent.0 \
-f /var/run/qemu-guest-agent.pid -d--- Makefile | 10 +- qemu-ga.c | 667 ++++++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 4 + 3 files changed, 677 insertions(+), 4 deletions(-) create mode 100644 qemu-ga.c
Makefile +6 -4
@@ -140,7 +140,7 @@ endif ###################################################################### qemu-img.o: qemu-img-cmds.h -qemu-img.o qemu-tool.o qemu-nbd.o qemu-io.o cmd.o: $(GENERATED_HEADERS) +qemu-img.o qemu-tool.o qemu-nbd.o qemu-io.o cmd.o qemu-ga.o: $(GENERATED_HEADERS) qemu-img$(EXESUF): qemu-img.o qemu-tool.o qemu-error.o $(oslib-obj-y) $(trace-obj-y) $(block-obj-y) $(qobject-obj-y) $(version-obj-y) qemu-timer-common.o
@@ -163,7 +163,7 @@ check-qfloat: check-qfloat.o qfloat.o $(CHECK_PROG_DEPS) check-qjson: check-qjson.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o qjson.o json-streamer.o json-lexer.o json-parser.o error.o qerror.o qemu-error.o $(CHECK_PROG_DEPS) qapi-dir := qapi-generated -$(qapi-obj-y) test-visitor.o test-qmp-commands.o: QEMU_CFLAGS += -I $(qapi-dir) +$(qapi-obj-y) test-visitor.o test-qmp-commands.o qemu-ga$(EXESUF): QEMU_CFLAGS += -I $(qapi-dir) $(qapi-dir)/test-qapi-types.c: $(qapi-dir)/test-qapi-types.h $(qapi-dir)/test-qapi-types.h: $(SRC_PATH)/qapi-schema-test.json $(SRC_PATH)/scripts/qapi-types.py
@@ -183,13 +183,15 @@ test-qmp-commands: test-qmp-commands.o qfloat.o qint.o qdict.o qstring.o qlist.o QGALIB=qga/guest-agent-command-state.o +qemu-ga$(EXESUF): qemu-ga.o $(QGALIB) qemu-tool.o qemu-error.o error.o $(oslib-obj-y) $(trace-obj-y) $(block-obj-y) $(qobject-obj-y) $(version-obj-y) $(qapi-obj-y) qemu-timer-common.o qemu-sockets.o module.o qapi/qmp-dispatch.o qapi/qmp-registry.o + QEMULIBS=libhw32 libhw64 libuser libdis libdis-user clean: # avoid old build problems by removing potentially incorrect old files rm -f config.mak op-i386.h opc-i386.h gen-op-i386.h op-arm.h opc-arm.h gen-op-arm.h rm -f qemu-options.def - rm -f *.o *.d *.a *.lo $(TOOLS) TAGS cscope.* *.pod *~ */*~ + rm -f *.o *.d *.a *.lo $(TOOLS) qemu-ga TAGS cscope.* *.pod *~ */*~ rm -Rf .libs rm -f slirp/*.o slirp/*.d audio/*.o audio/*.d block/*.o block/*.d net/*.o net/*.d fsdev/*.o fsdev/*.d ui/*.o ui/*.d qapi/*.o qapi/*.d qga/*.o qga/*.d rm -f qemu-img-cmds.h
@@ -385,4 +387,4 @@ tarbin: $(mandir)/man8/qemu-nbd.8 # Include automatically generated dependency files --include $(wildcard *.d audio/*.d slirp/*.d block/*.d net/*.d ui/*.d qapi/*.d) +-include $(wildcard *.d audio/*.d slirp/*.d block/*.d net/*.d ui/*.d qapi/*.d qga/*.d)
qemu-ga.c new file +667 -0
667 lines not on this page · raw message
qga/guest-agent-core.h +4 -0
@@ -15,6 +15,7 @@#define QGA_VERSION "1.0" +typedef struct GAState GAState ;typedef struct GACommandState GACommandState ; void ga_command_state_add(GACommandState *cs,
@@ -23,3 +24,6 @@ void ga_command_state_add(GACommandState *cs,void ga_command_state_init_all (GACommandState *cs);void ga_command_state_cleanup_all (GACommandState *cs);GACommandState *ga_command_state_new (void ); +bool ga_logging_enabled (GAState *s); +void ga_disable_logging (GAState *s); +void ga_enable_logging (GAState *s);
Signature · 1 line
1.7.0.4
PATCH v7 4/4 guest agent: add guest agent RPCs/commands
In reply to Michael RothThis adds the initial set of QMP/QAPI commands provided by the guest agent:
guest-sync
guest-ping
guest-info
guest-shutdown
guest-file-open
guest-file-read
guest-file-write
guest-file-seek
guest-file-flush
guest-file-close
guest-fsfreeze-freeze
guest-fsfreeze-thaw
guest-fsfreeze-status
The input/output specification for these commands are documented in the schema.
Example usage:
host:
qemu -device virtio-serial \
-chardev socket,path=/tmp/vs0.sock,server,nowait,id=qga0 \
-device virtserialport,chardev=qga0,name=org.qemu.quest_agent.0
...echo "{'execute':'guest-info'}" | socat stdio unix-connect:/tmp/qga0.sock
guest:
qemu-ga -m virtio-serial -p /dev/virtio-ports/org.qemu.guest_agent.0 \
-p /var/run/qemu-guest-agent.pid -d--- Makefile | 15 ++- qapi-schema-guest.json | 217 +++++++++++++++++++ qemu-ga.c | 4 + qerror.c | 8 + qerror.h | 6 + qga/guest-agent-commands.c | 512 ++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 2 + 7 files changed, 762 insertions(+), 2 deletions(-) create mode 100644 qapi-schema-guest.json create mode 100644 qga/guest-agent-commands.c
Makefile +13 -2
@@ -175,15 +175,26 @@ $(qapi-dir)/test-qmp-commands.h: $(qapi-dir)/test-qmp-marshal.c $(qapi-dir)/test-qmp-marshal.c: $(SRC_PATH)/qapi-schema-test.json $(SRC_PATH)/scripts/qapi-commands.py $(call quiet-command,python $(SRC_PATH)/scripts/qapi-commands.py -o "$(qapi-dir)" -p "test-" < $<, " GEN $@") +$(qapi-dir)/qga-qapi-types.c: $(qapi-dir)/qga-qapi-types.h +$(qapi-dir)/qga-qapi-types.h: $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-types.py + $(call quiet-command,python $(SRC_PATH)/scripts/qapi-types.py -o "$(qapi-dir)" -p "qga-" < $<, " GEN $@") +$(qapi-dir)/qga-qapi-visit.c: $(qapi-dir)/qga-qapi-visit.h +$(qapi-dir)/qga-qapi-visit.h: $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-visit.py + $(call quiet-command,python $(SRC_PATH)/scripts/qapi-visit.py -o "$(qapi-dir)" -p "qga-" < $<, " GEN $@") +$(qapi-dir)/qga-qmp-marshal.c: $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-commands.py + $(call quiet-command,python $(SRC_PATH)/scripts/qapi-commands.py -o "$(qapi-dir)" -p "qga-" < $<, " GEN $@") + test-visitor.o: $(addprefix $(qapi-dir)/, test-qapi-types.c test-qapi-types.h test-qapi-visit.c test-qapi-visit.h) test-visitor: test-visitor.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o $(qapi-obj-y) error.o osdep.o qemu-malloc.o $(oslib-obj-y) qjson.o json-streamer.o json-lexer.o json-parser.o qerror.o qemu-error.o qemu-tool.o $(qapi-dir)/test-qapi-visit.o $(qapi-dir)/test-qapi-types.o test-qmp-commands.o: $(addprefix $(qapi-dir)/, test-qapi-types.c test-qapi-types.h test-qapi-visit.c test-qapi-visit.h test-qmp-marshal.c test-qmp-commands.h) test-qmp-commands: test-qmp-commands.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o $(qapi-obj-y) error.o osdep.o qemu-malloc.o $(oslib-obj-y) qjson.o json-streamer.o json-lexer.o json-parser.o qerror.o qemu-error.o qemu-tool.o $(qapi-dir)/test-qapi-visit.o $(qapi-dir)/test-qapi-types.o $(qapi-dir)/test-qmp-marshal.o module.o -QGALIB=qga/guest-agent-command-state.o +QGALIB=qga/guest-agent-command-state.o qga/guest-agent-commands.o + +qemu-ga.o: $(qapi-dir)/qga-qapi-types.c $(qapi-dir)/qga-qapi-types.h $(qapi-dir)/qga-qapi-visit.c $(qapi-dir)/qga-qmp-marshal.c -qemu-ga$(EXESUF): qemu-ga.o $(QGALIB) qemu-tool.o qemu-error.o error.o $(oslib-obj-y) $(trace-obj-y) $(block-obj-y) $(qobject-obj-y) $(version-obj-y) $(qapi-obj-y) qemu-timer-common.o qemu-sockets.o module.o qapi/qmp-dispatch.o qapi/qmp-registry.o +qemu-ga$(EXESUF): qemu-ga.o $(QGALIB) qemu-tool.o qemu-error.o error.o $(oslib-obj-y) $(trace-obj-y) $(block-obj-y) $(qobject-obj-y) $(version-obj-y) $(qapi-obj-y) qemu-timer-common.o qemu-sockets.o module.o qapi/qmp-dispatch.o qapi/qmp-registry.o $(qapi-dir)/qga-qapi-visit.o $(qapi-dir)/qga-qapi-types.o $(qapi-dir)/qga-qmp-marshal.o QEMULIBS=libhw32 libhw64 libuser libdis libdis-user
qapi-schema-guest.json new file +217 -0
217 lines not on this page · raw message
qemu-ga.c +4 -0
@@ -653,6 +653,9 @@ int main(int argc, char **argv)g_log_set_default_handler (ga_log, s);g_log_set_fatal_mask (NULL ,G_LOG_LEVEL_ERROR ); s->logging_enabled = true; + s->command_state =ga_command_state_new (); +ga_command_state_init (s, s->command_state); +ga_command_state_init_all (s->command_state); ga_state = s;module_call_init (MODULE_INIT_QAPI );
@@ -661,6 +664,7 @@ int main(int argc, char **argv)g_main_loop_run (ga_state->main_loop); +ga_command_state_cleanup_all (ga_state->command_state);unlink (pidfile);return 0 ;
qerror.c +8 -0
@@ -218,6 +218,14 @@ static const QErrorStringTable qerror_table[] = { .error_fmt = QERR_VNC_SERVER_FAILED, .desc = "Could not start VNC server on %(target)", }, + { + .error_fmt = QERR_QGA_LOGGING_FAILED, + .desc = "Guest agent failed to log non-optional log statement", + }, + { + .error_fmt = QERR_QGA_COMMAND_FAILED, + .desc = "Guest agent command failed, error was '%(message)'", + }, {} };
qerror.h +6 -0
@@ -184,4 +184,10 @@ QError *qobject_to_qerror(const QObject *obj);#define QERR_FEATURE_DISABLED \ "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }" +#define QERR_QGA_LOGGING_FAILED \ + "{ 'class': 'QgaLoggingFailed', 'data': {} }" + +#define QERR_QGA_COMMAND_FAILED \ + "{ 'class': 'QgaCommandFailed', 'data': { 'message': %s } }" +#endif /* QERROR_H */
qga/guest-agent-commands.c new file +512 -0
512 lines not on this page · raw message
qga/guest-agent-core.h +2 -0
@@ -14,10 +14,12 @@#include "qemu-common.h" #define QGA_VERSION "1.0" +#define QGA_READ_COUNT_DEFAULT 4 << 10typedef struct GAState GAState ;typedef struct GACommandState GACommandState ; +void ga_command_state_init (GAState *s,GACommandState *cs);void ga_command_state_add (GACommandState *cs,void (*init)(void ),void (*cleanup)(void ));
Signature · 1 line
1.7.0.4
Re: [Qemu-devel] [PATCH v7 4/4] guest agent: add guest agent RPCs/commands
Quoted 133 lines · On Thu, 14 Jul 2011 15:00:34 -0500 Michael Roth <[email protected]>…
This adds the initial set of QMP/QAPI commands provided by the guest agent:
guest-sync
guest-ping
guest-info
guest-shutdown
guest-file-open
guest-file-read
guest-file-write
guest-file-seek
guest-file-flush
guest-file-close
guest-fsfreeze-freeze
guest-fsfreeze-thaw
guest-fsfreeze-statusThe input/output specification for these commands are documented in the schema.
Example usage:
host: qemu -device virtio-serial \ -chardev socket,path=/tmp/vs0.sock,server,nowait,id=qga0 \ -device virtserialport,chardev=qga0,name=org.qemu.quest_agent.0 ...echo "{'execute':'guest-info'}" | socat stdio unix-connect:/tmp/qga0.sock
guest: qemu-ga -m virtio-serial -p /dev/virtio-ports/org.qemu.guest_agent.0 \ -p /var/run/qemu-guest-agent.pid -dSigned-off-by Michael Roth <[email protected]>--- Makefile | 15 ++- qapi-schema-guest.json | 217 +++++++++++++++++++ qemu-ga.c | 4 + qerror.c | 8 + qerror.h | 6 + qga/guest-agent-commands.c | 512 ++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 2 + 7 files changed, 762 insertions(+), 2 deletions(-) create mode 100644 qapi-schema-guest.json create mode 100644 qga/guest-agent-commands.cMakefile +13
-2@@ -175,15 +175,26 @@ $(qapi-dir)/test-qmp-commands.h: $(qapi-dir)/test-qmp-marshal.c $(qapi-dir)/test-qmp-marshal.c: $(SRC_PATH)/qapi-schema-test.json $(SRC_PATH)/scripts/qapi-commands.py $(call quiet-command,python $(SRC_PATH)/scripts/qapi-commands.py -o "$(qapi-dir)" -p "test-" < $<, " GEN $@") +$(qapi-dir)/qga-qapi-types.c: $(qapi-dir)/qga-qapi-types.h +$(qapi-dir)/qga-qapi-types.h: $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-types.py + $(call quiet-command,python $(SRC_PATH)/scripts/qapi-types.py -o "$(qapi-dir)" -p "qga-" < $<, " GEN $@") +$(qapi-dir)/qga-qapi-visit.c: $(qapi-dir)/qga-qapi-visit.h +$(qapi-dir)/qga-qapi-visit.h: $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-visit.py + $(call quiet-command,python $(SRC_PATH)/scripts/qapi-visit.py -o "$(qapi-dir)" -p "qga-" < $<, " GEN $@") +$(qapi-dir)/qga-qmp-marshal.c: $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-commands.py + $(call quiet-command,python $(SRC_PATH)/scripts/qapi-commands.py -o "$(qapi-dir)" -p "qga-" < $<, " GEN $@") + test-visitor.o: $(addprefix $(qapi-dir)/, test-qapi-types.c test-qapi-types.h test-qapi-visit.c test-qapi-visit.h) test-visitor: test-visitor.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o $(qapi-obj-y) error.o osdep.o qemu-malloc.o $(oslib-obj-y) qjson.o json-streamer.o json-lexer.o json-parser.o qerror.o qemu-error.o qemu-tool.o $(qapi-dir)/test-qapi-visit.o $(qapi-dir)/test-qapi-types.o test-qmp-commands.o: $(addprefix $(qapi-dir)/, test-qapi-types.c test-qapi-types.h test-qapi-visit.c test-qapi-visit.h test-qmp-marshal.c test-qmp-commands.h) test-qmp-commands: test-qmp-commands.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o $(qapi-obj-y) error.o osdep.o qemu-malloc.o $(oslib-obj-y) qjson.o json-streamer.o json-lexer.o json-parser.o qerror.o qemu-error.o qemu-tool.o $(qapi-dir)/test-qapi-visit.o $(qapi-dir)/test-qapi-types.o $(qapi-dir)/test-qmp-marshal.o module.o -QGALIB=qga/guest-agent-command-state.o +QGALIB=qga/guest-agent-command-state.o qga/guest-agent-commands.o + +qemu-ga.o: $(qapi-dir)/qga-qapi-types.c $(qapi-dir)/qga-qapi-types.h $(qapi-dir)/qga-qapi-visit.c $(qapi-dir)/qga-qmp-marshal.c -qemu-ga$(EXESUF): qemu-ga.o $(QGALIB) qemu-tool.o qemu-error.o error.o $(oslib-obj-y) $(trace-obj-y) $(block-obj-y) $(qobject-obj-y) $(version-obj-y) $(qapi-obj-y) qemu-timer-common.o qemu-sockets.o module.o qapi/qmp-dispatch.o qapi/qmp-registry.o +qemu-ga$(EXESUF): qemu-ga.o $(QGALIB) qemu-tool.o qemu-error.o error.o $(oslib-obj-y) $(trace-obj-y) $(block-obj-y) $(qobject-obj-y) $(version-obj-y) $(qapi-obj-y) qemu-timer-common.o qemu-sockets.o module.o qapi/qmp-dispatch.o qapi/qmp-registry.o $(qapi-dir)/qga-qapi-visit.o $(qapi-dir)/qga-qapi-types.o $(qapi-dir)/qga-qmp-marshal.o QEMULIBS=libhw32 libhw64 libuser libdis libdis-userqapi-schema-guest.json new file +47
-0@@ -0,0 +1,217 @@ +# *-*- Mode: Python -*-* + +## +# @guest-sync: +# +# Echo back a unique integer value +# +# This is used by clients talking to the guest agent over the +# wire to ensure the stream is in sync and doesn't contain stale +# data from previous client. All guest agent responses should be +# ignored until the provided unique integer value is returned, +# and it is up to the client to handle stale whole or +# partially-delivered JSON text in such a way that this response +# can be obtained. +# +# Such clients should also preceed this command +# with a 0xFF byte to make such the guest agent flushes any +# partially read JSON data from a previous session. +# +# @id: randomly generated 64-bit integer +# +# Returns: The unique integer id passed in by the client +# +# Since: 0.15.0 +## +{ 'command': 'guest-sync' + 'data': { 'id': 'int' }, + 'returns': 'int' } + +## +# @guest-ping: +# +# Ping the guest agent, a non-error return implies success +# +# Since: 0.15.0 +## +{ 'command': 'guest-ping' } + +## +# @guest-info: +# +# Get some information about the guest agent. +# +# Since: 0.15.0 +## +{ 'type': 'GuestAgentInfo', 'data': {'version': 'str'} } +{ 'command': 'guest-info',
qapi-schema-guest.json line 57
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+ 'returns': 'GuestAgentInfo' } + +## +# @guest-shutdown: +# +# Initiate guest-activated shutdown. Note: this is an asynchronous +# shutdown request, with no guaruntee of successful shutdown. Errors +# will be logged to guest's syslog. +# +# @mode: #optional "halt", "powerdown", or "reboot" (default)
I'd choose 'powerdown' as the default.
Quoted 22 lines
qapi-schema-guest.json new file +22
-0+# +# Returns: Nothing on success +# +# Since: 0.15.0 +## +{ 'command': 'guest-shutdown', 'data': { '*mode': 'str' } } + +## +# @guest-file-open: +# +# Open a file in the guest and retrieve a file handle for it +# +# @filepath: Full path to the file in the guest to open. +# +# @mode: #optional open mode, as per fopen(), "r" is the default. +# +# Returns: Guest file handle on success. +# +# Since: 0.15.0 +## +{ 'command': 'guest-file-open', + 'data': { 'path': 'str', '*mode': 'str' },
qapi-schema-guest.json line 89
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+ 'returns': 'int' } + +## +# @guest-file-close: +# +# Close an open file in the guest +# +# @handle: filehandle returned by guest-file-open +# +# Returns: Nothing on success.
fclose() can fail, sorry for not seeing this before.
Quoted 8 lines
qapi-schema-guest.json new file +8
-0+# +# Since: 0.15.0 +## +{ 'command': 'guest-file-close', + 'data': { 'handle': 'int' } } + +## +# @guest-file-read:
qapi-schema-guest.json line 107
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+# +# Read from an open file in the guest. Data will be base64-encoded +# +# @handle: filehandle returned by guest-file-open +# +# @count: #optional maximum number of bytes to read (default is 4KB) +# +# Returns: GuestFileRead on success. Note: count is number of bytes read +# *before* base64 encoding +# bytes read.
unneeded line break.
Quoted 13 lines
qapi-schema-guest.json new file +13
-0+# +# Since: 0.15.0 +## +{ 'type': 'GuestFileRead', + 'data': { 'count': 'int', 'buf-b64': 'str', 'eof': 'bool' } } + +{ 'command': 'guest-file-read', + 'data': { 'handle': 'int', '*count': 'int' }, + 'returns': 'GuestFileRead' } + +## +# @guest-file-write: +#
qapi-schema-guest.json line 130
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+# Write to an open file in the guest. +# +# @handle: filehandle returned by guest-file-open +# +# @buf-b64: base64-encoded string representing data to be written +# +# @count: #optional bytes to write (actual bytes, after base64-decode), +# default is all content in buf-b64 buffer after base64 decoding +# +# Returns: GuestFileWrite on success. Note: count is the number of
number of?
Quoted 50 lines
qapi-schema-guest.json new file +50
-0+# +# Since: 0.15.0 +## +{ 'type': 'GuestFileWrite', + 'data': { 'count': 'int', 'eof': 'bool' } } +{ 'command': 'guest-file-write', + 'data': { 'handle': 'int', 'buf-b64': 'str', '*count': 'int' }, + 'returns': 'GuestFileWrite' } + +## +# @guest-file-seek: +# +# Seek to a position in the file, as with fseek(), and return the +# current file position afterward. Also encapsulates ftell()'s +# functionality, just Set offset=0, whence=SEEK_CUR. +# +# @handle: filehandle returned by guest-file-open +# +# @offset: bytes to skip over in the file stream +# +# @whence: SEEK_SET, SEEK_CUR, or SEEK_END, as with fseek() +# +# Returns: GuestFileSeek on success. +# +# Since: 0.15.0 +## +{ 'type': 'GuestFileSeek', + 'data': { 'position': 'int', 'eof': 'bool' } } + +{ 'command': 'guest-file-seek', + 'data': { 'handle': 'int', 'offset': 'int', 'whence': 'int' }, + 'returns': 'GuestFileSeek' } + +## +# @guest-file-flush: +# +# Write file changes bufferred in userspace to disk/kernel buffers +# +# @handle: filehandle returned by guest-file-open +# +# Returns: Nothing on success. +# +# Since: 0.15.0 +## +{ 'command': 'guest-file-flush', + 'data': { 'handle': 'int' } } + +## +# @guest-fsfreeze-status: +#
qapi-schema-guest.json line 190
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+# Get guest fsfreeze state. error state indicates failure to thaw 1 or more +# previously frozen filesystems, or failure to open a previously cached +# filesytem (filesystem unmounted/directory changes, etc). +# +# Returns: GuestFsfreezeStatus (of the form "GUEST_FSFREEZE_STATUS_<STATUS>") +# +# Since: 0.15.0 +## +{ 'enum': 'GuestFsfreezeStatus', + 'data': [ 'thawed', 'frozen', 'error' ] }
I'd expect the status to be just that and not the plain enum string name.
Quoted 228 lines
qapi-schema-guest.json new file +27
-0+{ 'command': 'guest-fsfreeze-status', + 'returns': 'GuestFsfreezeStatus' } + +## +# @guest-fsfreeze-freeze: +# +# Sync and freeze all non-network guest filesystems +# +# Returns: Number of file systems frozen on success +# +# Since: 0.15.0 +## +{ 'command': 'guest-fsfreeze-freeze', + 'returns': 'int' } + +## +# @guest-fsfreeze-thaw: +# +# Unfreeze frozen guest fileystems +# +# Returns: Number of file systems thawed +# If error, -1 (unknown error) or -errno +# +# Since: 0.15.0 +## +{ 'command': 'guest-fsfreeze-thaw', + 'returns': 'int' }qemu-ga.c +4
-0@@ -653,6 +653,9 @@ int main(int argc, char **argv)g_log_set_default_handler (ga_log, s);g_log_set_fatal_mask (NULL ,G_LOG_LEVEL_ERROR ); s->logging_enabled = true; + s->command_state =ga_command_state_new (); +ga_command_state_init (s, s->command_state); +ga_command_state_init_all (s->command_state); ga_state = s;module_call_init (MODULE_INIT_QAPI );@@ -661,6 +664,7 @@ int main(int argc, char **argv)g_main_loop_run (ga_state->main_loop); +ga_command_state_cleanup_all (ga_state->command_state);unlink (pidfile);return 0 ;qerror.c +8
-0@@ -218,6 +218,14 @@ static const QErrorStringTable qerror_table[] = { .error_fmt = QERR_VNC_SERVER_FAILED, .desc = "Could not start VNC server on %(target)", }, + { + .error_fmt = QERR_QGA_LOGGING_FAILED, + .desc = "Guest agent failed to log non-optional log statement", + }, + { + .error_fmt = QERR_QGA_COMMAND_FAILED, + .desc = "Guest agent command failed, error was '%(message)'", + }, {} };qerror.h +6
-0@@ -184,4 +184,10 @@ QError *qobject_to_qerror(const QObject *obj);#define QERR_FEATURE_DISABLED \ "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }" +#define QERR_QGA_LOGGING_FAILED \ + "{ 'class': 'QgaLoggingFailed', 'data': {} }" + +#define QERR_QGA_COMMAND_FAILED \ + "{ 'class': 'QgaCommandFailed', 'data': { 'message': %s } }" +#endif /* QERROR_H */ qga/guest-agent-commands.c new file +139
-0@@ -0,0 +1,512 @@ +/* +* QEMU Guest Agent commands +* +* Copyright IBM Corp. 2011 +* +* Authors: +* Michael Roth <[email protected]> +* +* This work is licensed under the terms of the GNU GPL, version 2 or later. +* See the COPYING file in the top-level directory. +*/ + +#include <glib.h> +#include <mntent.h> +#include <sys/types.h> +#include <sys/ioctl.h> +#include <linux/fs.h> +#include "qga/guest-agent-core.h" +#include "qga-qmp-commands.h" +#include "qerror.h" +#include "qemu-queue.h" + +static GAState *ga_state; + +static void disable_logging (void ) +{ +ga_disable_logging (ga_state); +} + +static void enable_logging (void ) +{ +ga_enable_logging (ga_state); +} + +/* Note: in some situations, like with the fsfreeze, logging may be +* temporarilly disabled. if it is necessary that a command be able +* to log for accounting purposes, check ga_logging_enabled() beforehand, +* and use the QERR_QGA_LOGGING_DISABLED to generate an error +*/ +static void slog (const char *fmt, ...) +{ +va_list ap; + +va_start (ap, fmt); +g_logv ("syslog" ,G_LOG_LEVEL_INFO , fmt, ap); +va_end (ap); +} + +int64_t qmp_guest_sync (int64_t id,Error **errp) +{ +return id; +} + +void qmp_guest_ping (Error **err) +{ +slog ("guest-ping called" ); +} + +struct GuestAgentInfo *qmp_guest_info (Error **err) +{ +GuestAgentInfo *info =qemu_mallocz (sizeof (GuestAgentInfo)); + + info->version =g_strdup (QGA_VERSION ); + +return info; +} + +void qmp_guest_shutdown (bool has_mode,const char *mode,Error **err) +{ +int ret; +const char *shutdown_flag; + +slog ("guest-shutdown called, mode: %s" , mode); +if (!has_mode ||strcmp (mode,"reboot" ) ==0 ) { + shutdown_flag ="-r" ; + }else if (strcmp (mode,"halt" ) ==0 ) { + shutdown_flag ="-H" ; + }else if (strcmp (mode,"powerdown" ) ==0 ) { + shutdown_flag ="-P" ; + }else { +error_set (err,QERR_INVALID_PARAMETER_VALUE ,"mode" , +"halt|powerdown|reboot" ); +return ; + } + + ret =fork (); +if (ret ==0 ) { +/* child, start the shutdown */ +setsid (); +fclose (stdin); +fclose (stdout); +fclose (stderr); + + ret =execl ("/sbin/shutdown" ,"shutdown" , shutdown_flag,"+0" , +"hypervisor initiated shutdown" , (char *)NULL ); +if (ret) { +slog ("guest-shutdown failed: %s" ,strerror (errno)); + } +exit (!!ret); + }else if (ret <0 ) { +error_set (err,QERR_UNDEFINED_ERROR ); + } +} + +typedef struct GuestFileHandle { +uint64_t id; +FILE *fh; +QTAILQ_ENTRY (GuestFileHandle) next; +}GuestFileHandle ; + +static struct { + QTAILQ_HEAD(, GuestFileHandle) filehandles; +} guest_file_state; + +static void guest_file_handle_add (FILE *fh) +{ +GuestFileHandle *gfh; + + gfh =qemu_mallocz (sizeof (GuestFileHandle)); + gfh->id =fileno (fh); + gfh->fh = fh; +QTAILQ_INSERT_TAIL (&guest_file_state.filehandles, gfh, next); +} + +static GuestFileHandle *guest_file_handle_find (int64_t id) +{ +GuestFileHandle *gfh; + + QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) + { +if (gfh->id == id) { +return gfh; + } + } + +return NULL ; +} + +int64_t qmp_guest_file_open (const char *path,bool has_mode,const char *mode,Error **err)
qga/guest-agent-commands.c line 149
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+{ +FILE *fh; +int fd; +int64_t ret =-1 ; + +if (!has_mode) { + mode ="r" ; + } +slog ("guest-file-open called, filepath: %s, mode: %s" , path, mode); + fh =fopen (path, mode);
I think it's good to check if 'mode' is valid. Linux libc seems to handle this correctly, but I don't know if other unices will do.
Quoted 23 lines
qga/guest-agent-commands.c new file +23
-0+if (!fh) { +error_set (err,QERR_OPEN_FILE_FAILED , path); +return -1 ; + } + +/* set fd non-blocking to avoid common use cases (like reading from a +* named pipe) from hanging the agent +*/ + fd =fileno (fh); + ret =fcntl (fd,F_GETFL ); + ret =fcntl (fd,F_SETFL , ret |O_NONBLOCK ); +if (ret ==-1 ) { +error_set (err,QERR_OPEN_FILE_FAILED , path); +fclose (fh); +return -1 ; + } + +guest_file_handle_add (fh); +slog ("guest-file-open, handle: %d" , fd); +return fd; +} + +void qmp_guest_file_close (int64_t handle,Error **err)
qga/guest-agent-commands.c line 182
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+{ +GuestFileHandle *gfh =guest_file_handle_find (handle); + +slog ("guest-file-close called, handle: %ld" , handle); +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"handle" ); +return ; + } + +fclose (gfh->fh);
As I said above, this can fail.
Quoted 14 lines
qga/guest-agent-commands.c new file +14
-0+QTAILQ_REMOVE (&guest_file_state.filehandles, gfh, next); +qemu_free (gfh); +} + +struct GuestFileRead *qmp_guest_file_read (int64_t handle,bool has_count, +int64_t count,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (handle); +GuestFileRead *read_data =NULL ; +guchar *buf; +FILE *fh; +size_t read_count; + +if (!gfh) {
qga/guest-agent-commands.c line 206
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+error_set (err,QERR_FD_NOT_FOUND ,"handle" ); +return NULL ; + } + +if (!has_count) { + count =QGA_READ_COUNT_DEFAULT ; + }else if (count <0 ) { +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + }
As I said in my past review, I think it's a good idea to limit 'count' to the file size.
qga/guest-agent-commands.c line 216
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ + fh = gfh->fh; + buf =qemu_mallocz (count+1 ); + read_count =fread (buf,1 , count, fh); +if (ferror (fh)) { +slog ("guest-file-read failed, handle: %ld" , handle); +error_set (err,QERR_QGA_COMMAND_FAILED ,"fread() failed" ); + }else { + buf[read_count] =0 ; + read_data =qemu_mallocz (sizeof (GuestFileRead) +1 );
Why +1?
Quoted 120 lines
qga/guest-agent-commands.c new file +120
-0+ read_data->count = read_count; + read_data->eof =feof (fh); +if (read_count) { + read_data->buf_b64 =g_base64_encode (buf, read_count); + } + } +qemu_free (buf); +clearerr (fh); + +return read_data; +} + +GuestFileWrite *qmp_guest_file_write (int64_t handle,const char *buf_b64, +bool has_count,int64_t count,Error **err) +{ +GuestFileWrite *write_data =NULL ; +guchar *buf; +gsize buf_len; +int write_count; +GuestFileHandle *gfh =guest_file_handle_find (handle); +FILE *fh; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"handle" ); +return NULL ; + } + + fh = gfh->fh; + buf =g_base64_decode (buf_b64, &buf_len); + +if (!has_count) { + count = buf_len; + }else if (count <0 || count > buf_len) { +qemu_free (buf); +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + } + + write_count =fwrite (buf,1 , count, fh); +if (ferror (fh)) { +slog ("guest-file-write failed, handle: %ld" , handle); +error_set (err,QERR_QGA_COMMAND_FAILED ,"fwrite() error" ); + }else { + write_data =qemu_mallocz (sizeof (GuestFileWrite)); + write_data->count = write_count; + write_data->eof =feof (fh); + } +qemu_free (buf); +clearerr (fh); + +return write_data; +} + +struct GuestFileSeek *qmp_guest_file_seek (int64_t handle,int64_t offset, +int64_t whence,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (handle); +GuestFileSeek *seek_data =NULL ; +FILE *fh; +int ret; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"handle" ); +return NULL ; + } + + fh = gfh->fh; + ret =fseek (fh, offset, whence); +if (ret ==-1 ) { +error_set (err,QERR_QGA_COMMAND_FAILED ,strerror (errno)); + }else { + seek_data =qemu_mallocz (sizeof (GuestFileRead)); + seek_data->position =ftell (fh); + seek_data->eof =feof (fh); + } +clearerr (fh); + +return seek_data; +} + +void qmp_guest_file_flush (int64_t handle,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (handle); +FILE *fh; +int ret; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"handle" ); +return ; + } + + fh = gfh->fh; + ret =fflush (fh); +if (ret ==EOF ) { +error_set (err,QERR_QGA_COMMAND_FAILED ,strerror (errno)); + } +} + +static void guest_file_init (void ) +{ +QTAILQ_INIT (&guest_file_state.filehandles); +} + +typedef struct GuestFsfreezeMount { +char *dirname; +char *devtype; +QTAILQ_ENTRY (GuestFsfreezeMount) next; +}GuestFsfreezeMount ; + +struct { +GuestFsfreezeStatus status; + QTAILQ_HEAD(, GuestFsfreezeMount) mount_list; +} guest_fsfreeze_state; + +/* +* Walk the mount table and build a list of local file systems +*/ +static int guest_fsfreeze_build_mount_list (void ) +{ +struct mntent *ment;
qga/guest-agent-commands.c line 346
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+GuestFsfreezeMount *mount, *temp; +char const *mtab =MOUNTED ; +FILE *fp; + + QTAILQ_FOREACH_SAFE(mount, &guest_fsfreeze_state.mount_list, next, temp) { +QTAILQ_REMOVE (&guest_fsfreeze_state.mount_list, mount, next); +qemu_free (mount->dirname); +qemu_free (mount->devtype); +qemu_free (mount); + }
Why is this needed? Shouldn't this be done on qmp_guest_fsfreeze_thaw()?
Quoted 183 lines
qga/guest-agent-commands.c new file +166
-0+ + fp =setmntent (mtab,"r" ); +if (!fp) { +g_warning ("fsfreeze: unable to read mtab" ); +return -1 ; + } + +while ((ment =getmntent (fp))) { +/* +* An entry which device name doesn't start with a '/' is +* either a dummy file system or a network file system. +* Add special handling for smbfs and cifs as is done by +* coreutils as well. +*/ +if ((ment->mnt_fsname[0 ] !='/' ) || + (strcmp (ment->mnt_type,"smbfs" ) ==0 ) || + (strcmp (ment->mnt_type,"cifs" ) ==0 )) { +continue ; + } + + mount =qemu_mallocz (sizeof (GuestFsfreezeMount)); + mount->dirname =qemu_strdup (ment->mnt_dir); + mount->devtype =qemu_strdup (ment->mnt_type); + +QTAILQ_INSERT_TAIL (&guest_fsfreeze_state.mount_list, mount, next); + } + +endmntent (fp); + +return 0 ; +} + +/* +* Return status of freeze/thaw +*/ +GuestFsfreezeStatus qmp_guest_fsfreeze_status (Error **err) +{ +return guest_fsfreeze_state.status; +} + +/* +* Walk list of mounted file systems in the guest, and freeze the ones which +* are real local file systems. +*/ +int64_t qmp_guest_fsfreeze_freeze (Error **err) +{ +int ret =0 , i =0 ; +struct GuestFsfreezeMount *mount, *temp; +int fd; +char err_msg[512 ]; + +slog ("guest-fsfreeze called" ); + +if (guest_fsfreeze_state.status ==GUEST_FSFREEZE_STATUS_FROZEN ) { +return 0 ; + } + + ret =guest_fsfreeze_build_mount_list (); +if (ret <0 ) { +return ret; + } + +/* cannot risk guest agent blocking itself on a write in this state */ +disable_logging (); + + QTAILQ_FOREACH_SAFE(mount, &guest_fsfreeze_state.mount_list, next, temp) { + fd =qemu_open (mount->dirname,O_RDONLY ); +if (fd ==-1 ) { +sprintf (err_msg,"failed to open %s, %s" , mount->dirname,strerror (errno)); +error_set (err,QERR_QGA_COMMAND_FAILED , err_msg); + goto error; + } + +/* we try to cull filesytems we know won't work in advance, but other +* filesytems may not implement fsfreeze for less obvious reasons. +* these will report EOPNOTSUPP, so we simply ignore them. when +* thawing, these filesystems will return an EINVAL instead, due to +* not being in a frozen state. Other filesystem-specific +* errors may result in EINVAL, however, so the user should check the +* number * of filesystems returned here against those returned by the +* thaw operation to determine whether everything completed +* successfully +*/ + ret =ioctl (fd,FIFREEZE ); +if (ret <0 && errno !=EOPNOTSUPP ) { +sprintf (err_msg,"failed to freeze %s, %s" , mount->dirname,strerror (errno)); +error_set (err,QERR_QGA_COMMAND_FAILED , err_msg); +close (fd); + goto error; + } +close (fd); + + i++; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_FROZEN ; +return i; + +error: +if (i >0 ) { +qmp_guest_fsfreeze_thaw (NULL ); + } +return 0 ; +} + +/* +* Walk list of frozen file systems in the guest, and thaw them. +*/ +int64_t qmp_guest_fsfreeze_thaw (Error **err) +{ +int ret; +GuestFsfreezeMount *mount, *temp; +int fd, i =0 ; +bool has_error = false; + + QTAILQ_FOREACH_SAFE(mount, &guest_fsfreeze_state.mount_list, next, temp) { + fd =qemu_open (mount->dirname,O_RDONLY ); +if (fd ==-1 ) { + has_error = true; +continue ; + } + ret =ioctl (fd,FITHAW ); +if (ret <0 && errno !=EOPNOTSUPP && errno !=EINVAL ) { + has_error = true; +close (fd); +continue ; + } +close (fd); + i++; + } + +if (has_error) { + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_ERROR ; + }else { + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_THAWED ; + } +enable_logging (); +return i; +} + +static void guest_fsfreeze_init (void ) +{ + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_THAWED ; +QTAILQ_INIT (&guest_fsfreeze_state.mount_list); +} + +static void guest_fsfreeze_cleanup (void ) +{ +int64_t ret; +Error *err =NULL ; + +if (guest_fsfreeze_state.status ==GUEST_FSFREEZE_STATUS_FROZEN ) { + ret =qmp_guest_fsfreeze_thaw (&err); +if (ret <0 || err) { +slog ("failed to clean up frozen filesystems" ); + } + } +} + +/* register init/cleanup routines for stateful command groups */ +void ga_command_state_init (GAState *s,GACommandState *cs) +{ + ga_state = s; +ga_command_state_add (cs, guest_fsfreeze_init, guest_fsfreeze_cleanup); +ga_command_state_add (cs, guest_file_init,NULL ); +}qga/guest-agent-core.h +2
-0@@ -14,10 +14,12 @@#include "qemu-common.h" #define QGA_VERSION "1.0" +#define QGA_READ_COUNT_DEFAULT 4 << 10typedef struct GAState GAState ;typedef struct GACommandState GACommandState ; +void ga_command_state_init (GAState *s,GACommandState *cs);void ga_command_state_add (GACommandState *cs,void (*init)(void ),void (*cleanup)(void ));
Re: [Qemu-devel] [PATCH v7 4/4] guest agent: add guest agent RPCs/commands
Quoted 140 lines · Luiz Capitulino
Quoted 137 lines · On Thu, 14 Jul 2011 15:00:34 -0500 Michael Roth<[email protected]>…
This adds the initial set of QMP/QAPI commands provided by the guest agent:
guest-sync
guest-ping
guest-info
guest-shutdown
guest-file-open
guest-file-read
guest-file-write
guest-file-seek
guest-file-flush
guest-file-close
guest-fsfreeze-freeze
guest-fsfreeze-thaw
guest-fsfreeze-statusThe input/output specification for these commands are documented in the schema.
Example usage:
host: qemu -device virtio-serial \ -chardev socket,path=/tmp/vs0.sock,server,nowait,id=qga0 \ -device virtserialport,chardev=qga0,name=org.qemu.quest_agent.0 ...echo "{'execute':'guest-info'}" | socat stdio unix-connect:/tmp/qga0.sock
guest: qemu-ga -m virtio-serial -p /dev/virtio-ports/org.qemu.guest_agent.0 \ -p /var/run/qemu-guest-agent.pid -dSigned-off-by Michael Roth<[email protected]>--- Makefile | 15 ++- qapi-schema-guest.json | 217 +++++++++++++++++++ qemu-ga.c | 4 + qerror.c | 8 + qerror.h | 6 + qga/guest-agent-commands.c | 512 ++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 2 + 7 files changed, 762 insertions(+), 2 deletions(-)create mode 100644 qapi-schema-guest.json
create mode 100644qga/guest-agent-commands.cMakefile +13
-2@@ -175,15 +175,26 @@ $(qapi-dir)/test-qmp-commands.h: $(qapi-dir)/test-qmp-marshal.c $(qapi-dir)/test-qmp-marshal.c: $(SRC_PATH)/qapi-schema-test.json $(SRC_PATH)/scripts/qapi-commands.py $(call quiet-command,python $(SRC_PATH)/scripts/qapi-commands.py -o "$(qapi-dir)" -p "test-"< $<, " GEN $@") +$(qapi-dir)/qga-qapi-types.c: $(qapi-dir)/qga-qapi-types.h +$(qapi-dir)/qga-qapi-types.h: $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-types.py + $(call quiet-command,python $(SRC_PATH)/scripts/qapi-types.py -o "$(qapi-dir)" -p "qga-"< $<, " GEN $@") +$(qapi-dir)/qga-qapi-visit.c: $(qapi-dir)/qga-qapi-visit.h +$(qapi-dir)/qga-qapi-visit.h: $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-visit.py + $(call quiet-command,python $(SRC_PATH)/scripts/qapi-visit.py -o "$(qapi-dir)" -p "qga-"< $<, " GEN $@") +$(qapi-dir)/qga-qmp-marshal.c: $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-commands.py + $(call quiet-command,python $(SRC_PATH)/scripts/qapi-commands.py -o "$(qapi-dir)" -p "qga-"< $<, " GEN $@") + test-visitor.o: $(addprefix $(qapi-dir)/, test-qapi-types.c test-qapi-types.h test-qapi-visit.c test-qapi-visit.h) test-visitor: test-visitor.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o $(qapi-obj-y) error.o osdep.o qemu-malloc.o $(oslib-obj-y) qjson.o json-streamer.o json-lexer.o json-parser.o qerror.o qemu-error.o qemu-tool.o $(qapi-dir)/test-qapi-visit.o $(qapi-dir)/test-qapi-types.o test-qmp-commands.o: $(addprefix $(qapi-dir)/, test-qapi-types.c test-qapi-types.h test-qapi-visit.c test-qapi-visit.h test-qmp-marshal.c test-qmp-commands.h) test-qmp-commands: test-qmp-commands.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o $(qapi-obj-y) error.o osdep.o qemu-malloc.o $(oslib-obj-y) qjson.o json-streamer.o json-lexer.o json-parser.o qerror.o qemu-error.o qemu-tool.o $(qapi-dir)/test-qapi-visit.o $(qapi-dir)/test-qapi-types.o $(qapi-dir)/test-qmp-marshal.o module.o -QGALIB=qga/guest-agent-command-state.o +QGALIB=qga/guest-agent-command-state.o qga/guest-agent-commands.o + +qemu-ga.o: $(qapi-dir)/qga-qapi-types.c $(qapi-dir)/qga-qapi-types.h $(qapi-dir)/qga-qapi-visit.c $(qapi-dir)/qga-qmp-marshal.c -qemu-ga$(EXESUF): qemu-ga.o $(QGALIB) qemu-tool.o qemu-error.o error.o $(oslib-obj-y) $(trace-obj-y) $(block-obj-y) $(qobject-obj-y) $(version-obj-y) $(qapi-obj-y) qemu-timer-common.o qemu-sockets.o module.o qapi/qmp-dispatch.o qapi/qmp-registry.o +qemu-ga$(EXESUF): qemu-ga.o $(QGALIB) qemu-tool.o qemu-error.o error.o $(oslib-obj-y) $(trace-obj-y) $(block-obj-y) $(qobject-obj-y) $(version-obj-y) $(qapi-obj-y) qemu-timer-common.o qemu-sockets.o module.o qapi/qmp-dispatch.o qapi/qmp-registry.o $(qapi-dir)/qga-qapi-visit.o $(qapi-dir)/qga-qapi-types.o $(qapi-dir)/qga-qmp-marshal.o QEMULIBS=libhw32 libhw64 libuser libdis libdis-userqapi-schema-guest.json new file +51
-0@@ -0,0 +1,217 @@ +# *-*- Mode: Python -*-* + +## +# @guest-sync: +# +# Echo back a unique integer value +# +# This is used by clients talking to the guest agent over the +# wire to ensure the stream is in sync and doesn't contain stale +# data from previous client. All guest agent responses should be +# ignored until the provided unique integer value is returned, +# and it is up to the client to handle stale whole or +# partially-delivered JSON text in such a way that this response +# can be obtained. +# +# Such clients should also preceed this command +# with a 0xFF byte to make such the guest agent flushes any +# partially read JSON data from a previous session. +# +# @id: randomly generated 64-bit integer +# +# Returns: The unique integer id passed in by the client +# +# Since: 0.15.0 +## +{ 'command': 'guest-sync' + 'data': { 'id': 'int' }, + 'returns': 'int' } + +## +# @guest-ping: +# +# Ping the guest agent, a non-error return implies success +# +# Since: 0.15.0 +## +{ 'command': 'guest-ping' } + +## +# @guest-info: +# +# Get some information about the guest agent. +# +# Since: 0.15.0 +## +{ 'type': 'GuestAgentInfo', 'data': {'version': 'str'} } +{ 'command': 'guest-info', + 'returns': 'GuestAgentInfo' } + +## +# @guest-shutdown:
Quoted 9 lines
qapi-schema-guest.json line 57
Quoted 6 lines
qapi-schema-guest.json new file +6
-0+# +# Initiate guest-activated shutdown. Note: this is an asynchronous +# shutdown request, with no guaruntee of successful shutdown. Errors +# will be logged to guest's syslog. +# +# @mode: #optional "halt", "powerdown", or "reboot" (default)I'd choose 'powerdown' as the default.
Yup, meant to change this sorry.
Quoted 26 lines
Quoted 26 lines
qapi-schema-guest.json new file +26
-0+# +# Returns: Nothing on success +# +# Since: 0.15.0 +## +{ 'command': 'guest-shutdown', 'data': { '*mode': 'str' } } + +## +# @guest-file-open: +# +# Open a file in the guest and retrieve a file handle for it +# +# @filepath: Full path to the file in the guest to open. +# +# @mode: #optional open mode, as per fopen(), "r" is the default. +# +# Returns: Guest file handle on success. +# +# Since: 0.15.0 +## +{ 'command': 'guest-file-open', + 'data': { 'path': 'str', '*mode': 'str' }, + 'returns': 'int' } + +## +# @guest-file-close:
Quoted 9 lines
qapi-schema-guest.json line 89
Quoted 6 lines
qapi-schema-guest.json new file +6
-0+# +# Close an open file in the guest +# +# @handle: filehandle returned by guest-file-open +# +# Returns: Nothing on success.
fclose()can fail, sorry for not seeing this before.
I'll add checks for this.
Quoted 38 lines
Quoted 8 lines
qapi-schema-guest.json new file +8
-0+# +# Since: 0.15.0 +## +{ 'command': 'guest-file-close', + 'data': { 'handle': 'int' } } + +## +# @guest-file-read:qapi-schema-guest.json line 107
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+# +# Read from an open file in the guest. Data will be base64-encoded +# +# @handle: filehandle returned by guest-file-open +# +# @count: #optional maximum number of bytes to read (default is 4KB) +# +# Returns: GuestFileRead on success. Note: count is number of bytes read +# *before* base64 encoding +# bytes read.unneeded line break.
Quoted 17 lines
qapi-schema-guest.json new file +17
-0+# +# Since: 0.15.0 +## +{ 'type': 'GuestFileRead', + 'data': { 'count': 'int', 'buf-b64': 'str', 'eof': 'bool' } } + +{ 'command': 'guest-file-read', + 'data': { 'handle': 'int', '*count': 'int' }, + 'returns': 'GuestFileRead' } + +## +# @guest-file-write: +# +# Write to an open file in the guest. +# +# @handle: filehandle returned by guest-file-open +#
Quoted 9 lines
qapi-schema-guest.json line 130
Quoted 6 lines
qapi-schema-guest.json new file +6
-0+# @buf-b64: base64-encoded string representing data to be written +# +# @count: #optional bytes to write (actual bytes, after base64-decode), +# default is all content in buf-b64 buffer after base64 decoding +# +# Returns: GuestFileWrite on success. Note: count is the number ofnumber of?
number of bytes base64-decoded bytes written. must've gotten distracted :)
Quoted 54 lines
Quoted 54 lines
qapi-schema-guest.json new file +54
-0+# +# Since: 0.15.0 +## +{ 'type': 'GuestFileWrite', + 'data': { 'count': 'int', 'eof': 'bool' } } +{ 'command': 'guest-file-write', + 'data': { 'handle': 'int', 'buf-b64': 'str', '*count': 'int' }, + 'returns': 'GuestFileWrite' } + +## +# @guest-file-seek: +# +# Seek to a position in the file, as with fseek(), and return the +# current file position afterward. Also encapsulates ftell()'s +# functionality, just Set offset=0, whence=SEEK_CUR. +# +# @handle: filehandle returned by guest-file-open +# +# @offset: bytes to skip over in the file stream +# +# @whence: SEEK_SET, SEEK_CUR, or SEEK_END, as with fseek() +# +# Returns: GuestFileSeek on success. +# +# Since: 0.15.0 +## +{ 'type': 'GuestFileSeek', + 'data': { 'position': 'int', 'eof': 'bool' } } + +{ 'command': 'guest-file-seek', + 'data': { 'handle': 'int', 'offset': 'int', 'whence': 'int' }, + 'returns': 'GuestFileSeek' } + +## +# @guest-file-flush: +# +# Write file changes bufferred in userspace to disk/kernel buffers +# +# @handle: filehandle returned by guest-file-open +# +# Returns: Nothing on success. +# +# Since: 0.15.0 +## +{ 'command': 'guest-file-flush', + 'data': { 'handle': 'int' } } + +## +# @guest-fsfreeze-status: +# +# Get guest fsfreeze state. error state indicates failure to thaw 1 or more +# previously frozen filesystems, or failure to open a previously cached +# filesytem (filesystem unmounted/directory changes, etc). +#
Quoted 9 lines
qapi-schema-guest.json line 190
Quoted 6 lines
qapi-schema-guest.json new file +6
-0+# Returns: GuestFsfreezeStatus (of the form "GUEST_FSFREEZE_STATUS_<STATUS>") +# +# Since: 0.15.0 +## +{ 'enum': 'GuestFsfreezeStatus', + 'data': [ 'thawed', 'frozen', 'error' ] }I'd expect the status to be just that and not the plain enum string name.
I like the extra verbosity for enums but I guess the schema/command/field tell you that anyway so I guess it's somewhat redundant. Will change.
Quoted 233 lines
Quoted 233 lines
qapi-schema-guest.json new file +27
-0+{ 'command': 'guest-fsfreeze-status', + 'returns': 'GuestFsfreezeStatus' } + +## +# @guest-fsfreeze-freeze: +# +# Sync and freeze all non-network guest filesystems +# +# Returns: Number of file systems frozen on success +# +# Since: 0.15.0 +## +{ 'command': 'guest-fsfreeze-freeze', + 'returns': 'int' } + +## +# @guest-fsfreeze-thaw: +# +# Unfreeze frozen guest fileystems +# +# Returns: Number of file systems thawed +# If error, -1 (unknown error) or -errno +# +# Since: 0.15.0 +## +{ 'command': 'guest-fsfreeze-thaw', + 'returns': 'int' }qemu-ga.c +4
-0@@ -653,6 +653,9 @@ int main(int argc, char **argv)g_log_set_default_handler (ga_log, s);g_log_set_fatal_mask (NULL ,G_LOG_LEVEL_ERROR ); s->logging_enabled = true; + s->command_state =ga_command_state_new (); +ga_command_state_init (s, s->command_state); +ga_command_state_init_all (s->command_state); ga_state = s;module_call_init (MODULE_INIT_QAPI );@@ -661,6 +664,7 @@ int main(int argc, char **argv)g_main_loop_run (ga_state->main_loop); +ga_command_state_cleanup_all (ga_state->command_state);unlink (pidfile);return 0 ;qerror.c +8
-0@@ -218,6 +218,14 @@ static const QErrorStringTable qerror_table[] = { .error_fmt = QERR_VNC_SERVER_FAILED, .desc = "Could not start VNC server on %(target)", }, + { + .error_fmt = QERR_QGA_LOGGING_FAILED, + .desc = "Guest agent failed to log non-optional log statement", + }, + { + .error_fmt = QERR_QGA_COMMAND_FAILED, + .desc = "Guest agent command failed, error was '%(message)'", + }, {} };qerror.h +6
-0@@ -184,4 +184,10 @@ QError *qobject_to_qerror(const QObject *obj);#define QERR_FEATURE_DISABLED \ "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }" +#define QERR_QGA_LOGGING_FAILED \ + "{ 'class': 'QgaLoggingFailed', 'data': {} }" + +#define QERR_QGA_COMMAND_FAILED \ + "{ 'class': 'QgaCommandFailed', 'data': { 'message': %s } }" +#endif /* QERROR_H */ qga/guest-agent-commands.c new file +144
-0@@ -0,0 +1,512 @@ +/* +* QEMU Guest Agent commands +* +* Copyright IBM Corp. 2011 +* +* Authors: +* Michael Roth<[email protected]> +* +* This work is licensed under the terms of the GNU GPL, version 2 or later. +* See the COPYING file in the top-level directory. +*/ + +#include <glib.h> +#include <mntent.h> +#include <sys/types.h> +#include <sys/ioctl.h> +#include <linux/fs.h> +#include "qga/guest-agent-core.h" +#include "qga-qmp-commands.h" +#include "qerror.h" +#include "qemu-queue.h" + +static GAState *ga_state; + +static void disable_logging (void ) +{ +ga_disable_logging (ga_state); +} + +static void enable_logging (void ) +{ +ga_enable_logging (ga_state); +} + +/* Note: in some situations, like with the fsfreeze, logging may be +* temporarilly disabled. if it is necessary that a command be able +* to log for accounting purposes, check ga_logging_enabled() beforehand, +* and use the QERR_QGA_LOGGING_DISABLED to generate an error +*/ +static void slog (const char *fmt, ...) +{ +va_list ap; + +va_start (ap, fmt); +g_logv ("syslog" ,G_LOG_LEVEL_INFO , fmt, ap); +va_end (ap); +} + +int64_t qmp_guest_sync (int64_t id,Error **errp) +{ +return id; +} + +void qmp_guest_ping (Error **err) +{ +slog ("guest-ping called" ); +} + +struct GuestAgentInfo *qmp_guest_info (Error **err) +{ +GuestAgentInfo *info =qemu_mallocz (sizeof (GuestAgentInfo)); + + info->version =g_strdup (QGA_VERSION ); + +return info; +} + +void qmp_guest_shutdown (bool has_mode,const char *mode,Error **err) +{ +int ret; +const char *shutdown_flag; + +slog ("guest-shutdown called, mode: %s" , mode); +if (!has_mode ||strcmp (mode,"reboot" ) ==0 ) { + shutdown_flag ="-r" ; + }else if (strcmp (mode,"halt" ) ==0 ) { + shutdown_flag ="-H" ; + }else if (strcmp (mode,"powerdown" ) ==0 ) { + shutdown_flag ="-P" ; + }else { +error_set (err,QERR_INVALID_PARAMETER_VALUE ,"mode" , +"halt|powerdown|reboot" ); +return ; + } + + ret =fork (); +if (ret ==0 ) { +/* child, start the shutdown */ +setsid (); +fclose (stdin); +fclose (stdout); +fclose (stderr); + + ret =execl ("/sbin/shutdown" ,"shutdown" , shutdown_flag,"+0" , +"hypervisor initiated shutdown" , (char *)NULL ); +if (ret) { +slog ("guest-shutdown failed: %s" ,strerror (errno)); + } +exit (!!ret); + }else if (ret<0 ) { +error_set (err,QERR_UNDEFINED_ERROR ); + } +} + +typedef struct GuestFileHandle { +uint64_t id; +FILE *fh; +QTAILQ_ENTRY (GuestFileHandle) next; +}GuestFileHandle ; + +static struct { + QTAILQ_HEAD(, GuestFileHandle) filehandles; +} guest_file_state; + +static void guest_file_handle_add (FILE *fh) +{ +GuestFileHandle *gfh; + + gfh =qemu_mallocz (sizeof (GuestFileHandle)); + gfh->id =fileno (fh); + gfh->fh = fh; +QTAILQ_INSERT_TAIL (&guest_file_state.filehandles, gfh, next); +} + +static GuestFileHandle *guest_file_handle_find (int64_t id) +{ +GuestFileHandle *gfh; + + QTAILQ_FOREACH(gfh,&guest_file_state.filehandles, next) + { +if (gfh->id == id) { +return gfh; + } + } + +return NULL ; +} + +int64_t qmp_guest_file_open (const char *path,bool has_mode,const char *mode,Error **err) +{ +FILE *fh; +int fd; +int64_t ret =-1 ; +
Quoted 9 lines
qga/guest-agent-commands.c line 149
Quoted 5 lines
qga/guest-agent-commands.c new file +5
-0+if (!has_mode) { + mode ="r" ; + } +slog ("guest-file-open called, filepath: %s, mode: %s" , path, mode); + fh =fopen (path, mode);I think it's good to check if 'mode' is valid. Linux libc seems to handle this correctly, but I don't know if other unices will do.
I think it's okay to apply the "let them blow their guest up" methodology we adopted for guest-read-file here as well, since the client theoretically knows the guest better.
Quoted 55 lines
Quoted 23 lines
qga/guest-agent-commands.c new file +23
-0+if (!fh) { +error_set (err,QERR_OPEN_FILE_FAILED , path); +return -1 ; + } + +/* set fd non-blocking to avoid common use cases (like reading from a +* named pipe) from hanging the agent +*/ + fd =fileno (fh); + ret =fcntl (fd,F_GETFL ); + ret =fcntl (fd,F_SETFL , ret |O_NONBLOCK ); +if (ret ==-1 ) { +error_set (err,QERR_OPEN_FILE_FAILED , path); +fclose (fh); +return -1 ; + } + +guest_file_handle_add (fh); +slog ("guest-file-open, handle: %d" , fd); +return fd; +} + +void qmp_guest_file_close (int64_t handle,Error **err)qga/guest-agent-commands.c line 182
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+{ +GuestFileHandle *gfh =guest_file_handle_find (handle); + +slog ("guest-file-close called, handle: %ld" , handle); +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"handle" ); +return ; + } + +fclose (gfh->fh);As I said above, this can fail.
Quoted 19 lines
qga/guest-agent-commands.c new file +19
-0+QTAILQ_REMOVE (&guest_file_state.filehandles, gfh, next); +qemu_free (gfh); +} + +struct GuestFileRead *qmp_guest_file_read (int64_t handle,bool has_count, +int64_t count,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (handle); +GuestFileRead *read_data =NULL ; +guchar *buf; +FILE *fh; +size_t read_count; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"handle" ); +return NULL ; + } + +if (!has_count) {
Quoted 9 lines
qga/guest-agent-commands.c line 206
Quoted 5 lines
qga/guest-agent-commands.c new file +5
-0+ count =QGA_READ_COUNT_DEFAULT ; + }else if (count<0 ) { +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + }As I said in my past review, I think it's a good idea to limit 'count' to the file size.
I guess I misunderstood. I suggested we drop both the idea of limiting to a QGA_READ_COUNT_MAX as well as limiting to filesize and thought we were in agreement in letting the client blow up their guest with huge mallocs if they were so inclined. And if they find themselves in that situation they're misusing the interface anyway since there's a token size limit of 64MB (which reminds me I need to add a note about that in the schema/docs) which would've bit them if their malloc didn't cause any problems.
If you'd still like to do it this way, I don't think fstat() would work since it wouldn't reflect updates from fwrite() until an fflush()/fclose(). And if we're gonna bother with this we should also be more correct and limit to amount of bytes left in the stream. I think something like this would do it:
cur_pos = ftell(fh);fseek(fh, 0, SEEK_END);last_pos = ftell(fh);fseek(fh, cur_pos, SEEK_SET);
remaining = last_pos - cur_pos
count = (count > remaining) ? remaining : count;
And we'd need to do it on every call to guest-file-read.
Quoted 11 lines
qga/guest-agent-commands.c line 216
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ + fh = gfh->fh; + buf =qemu_mallocz (count+1 ); + read_count =fread (buf,1 , count, fh); +if (ferror (fh)) { +slog ("guest-file-read failed, handle: %ld" , handle); +error_set (err,QERR_QGA_COMMAND_FAILED ,"fread() failed" ); + }else { + buf[read_count] =0 ; + read_data =qemu_mallocz (sizeof (GuestFileRead) +1 );
Quoted 2 lines
Why +1?
ehhh...no idea. Must've added that erroneously when I was fixing a buf overflow with 'buf = qemu_mallocz(count);'. Will fix.
Quoted 124 lines
Quoted 124 lines
qga/guest-agent-commands.c new file +124
-0+ read_data->count = read_count; + read_data->eof =feof (fh); +if (read_count) { + read_data->buf_b64 =g_base64_encode (buf, read_count); + } + } +qemu_free (buf); +clearerr (fh); + +return read_data; +} + +GuestFileWrite *qmp_guest_file_write (int64_t handle,const char *buf_b64, +bool has_count,int64_t count,Error **err) +{ +GuestFileWrite *write_data =NULL ; +guchar *buf; +gsize buf_len; +int write_count; +GuestFileHandle *gfh =guest_file_handle_find (handle); +FILE *fh; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"handle" ); +return NULL ; + } + + fh = gfh->fh; + buf =g_base64_decode (buf_b64,&buf_len); + +if (!has_count) { + count = buf_len; + }else if (count<0 || count> buf_len) { +qemu_free (buf); +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + } + + write_count =fwrite (buf,1 , count, fh); +if (ferror (fh)) { +slog ("guest-file-write failed, handle: %ld" , handle); +error_set (err,QERR_QGA_COMMAND_FAILED ,"fwrite() error" ); + }else { + write_data =qemu_mallocz (sizeof (GuestFileWrite)); + write_data->count = write_count; + write_data->eof =feof (fh); + } +qemu_free (buf); +clearerr (fh); + +return write_data; +} + +struct GuestFileSeek *qmp_guest_file_seek (int64_t handle,int64_t offset, +int64_t whence,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (handle); +GuestFileSeek *seek_data =NULL ; +FILE *fh; +int ret; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"handle" ); +return NULL ; + } + + fh = gfh->fh; + ret =fseek (fh, offset, whence); +if (ret ==-1 ) { +error_set (err,QERR_QGA_COMMAND_FAILED ,strerror (errno)); + }else { + seek_data =qemu_mallocz (sizeof (GuestFileRead)); + seek_data->position =ftell (fh); + seek_data->eof =feof (fh); + } +clearerr (fh); + +return seek_data; +} + +void qmp_guest_file_flush (int64_t handle,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (handle); +FILE *fh; +int ret; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"handle" ); +return ; + } + + fh = gfh->fh; + ret =fflush (fh); +if (ret ==EOF ) { +error_set (err,QERR_QGA_COMMAND_FAILED ,strerror (errno)); + } +} + +static void guest_file_init (void ) +{ +QTAILQ_INIT (&guest_file_state.filehandles); +} + +typedef struct GuestFsfreezeMount { +char *dirname; +char *devtype; +QTAILQ_ENTRY (GuestFsfreezeMount) next; +}GuestFsfreezeMount ; + +struct { +GuestFsfreezeStatus status; + QTAILQ_HEAD(, GuestFsfreezeMount) mount_list; +} guest_fsfreeze_state; + +/* +* Walk the mount table and build a list of local file systems +*/ +static int guest_fsfreeze_build_mount_list (void ) +{ +struct mntent *ment; +GuestFsfreezeMount *mount, *temp; +char const *mtab =MOUNTED ; +FILE *fp; +
Quoted 9 lines
qga/guest-agent-commands.c line 346
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+ QTAILQ_FOREACH_SAFE(mount,&guest_fsfreeze_state.mount_list, next, temp) { +QTAILQ_REMOVE (&guest_fsfreeze_state.mount_list, mount, next); +qemu_free (mount->dirname); +qemu_free (mount->devtype); +qemu_free (mount); + }Why is this needed? Shouldn't this be done on
qmp_guest_fsfreeze_thaw()?
Thaw might leave them in an error state, and the only recourse might be to retry the thaw on the cached mount list after manual intervening on the guest. So the list needs to stick around else we'd have to rebuild it in thaw, which means it may not be in sync with the list we were using when doing the initial freeze.
Quoted 184 lines
Quoted 183 lines
qga/guest-agent-commands.c new file +166
-0+ + fp =setmntent (mtab,"r" ); +if (!fp) { +g_warning ("fsfreeze: unable to read mtab" ); +return -1 ; + } + +while ((ment =getmntent (fp))) { +/* +* An entry which device name doesn't start with a '/' is +* either a dummy file system or a network file system. +* Add special handling for smbfs and cifs as is done by +* coreutils as well. +*/ +if ((ment->mnt_fsname[0 ] !='/' ) || + (strcmp (ment->mnt_type,"smbfs" ) ==0 ) || + (strcmp (ment->mnt_type,"cifs" ) ==0 )) { +continue ; + } + + mount =qemu_mallocz (sizeof (GuestFsfreezeMount)); + mount->dirname =qemu_strdup (ment->mnt_dir); + mount->devtype =qemu_strdup (ment->mnt_type); + +QTAILQ_INSERT_TAIL (&guest_fsfreeze_state.mount_list, mount, next); + } + +endmntent (fp); + +return 0 ; +} + +/* +* Return status of freeze/thaw +*/ +GuestFsfreezeStatus qmp_guest_fsfreeze_status (Error **err) +{ +return guest_fsfreeze_state.status; +} + +/* +* Walk list of mounted file systems in the guest, and freeze the ones which +* are real local file systems. +*/ +int64_t qmp_guest_fsfreeze_freeze (Error **err) +{ +int ret =0 , i =0 ; +struct GuestFsfreezeMount *mount, *temp; +int fd; +char err_msg[512 ]; + +slog ("guest-fsfreeze called" ); + +if (guest_fsfreeze_state.status ==GUEST_FSFREEZE_STATUS_FROZEN ) { +return 0 ; + } + + ret =guest_fsfreeze_build_mount_list (); +if (ret<0 ) { +return ret; + } + +/* cannot risk guest agent blocking itself on a write in this state */ +disable_logging (); + + QTAILQ_FOREACH_SAFE(mount,&guest_fsfreeze_state.mount_list, next, temp) { + fd =qemu_open (mount->dirname,O_RDONLY ); +if (fd ==-1 ) { +sprintf (err_msg,"failed to open %s, %s" , mount->dirname,strerror (errno)); +error_set (err,QERR_QGA_COMMAND_FAILED , err_msg); + goto error; + } + +/* we try to cull filesytems we know won't work in advance, but other +* filesytems may not implement fsfreeze for less obvious reasons. +* these will report EOPNOTSUPP, so we simply ignore them. when +* thawing, these filesystems will return an EINVAL instead, due to +* not being in a frozen state. Other filesystem-specific +* errors may result in EINVAL, however, so the user should check the +* number * of filesystems returned here against those returned by the +* thaw operation to determine whether everything completed +* successfully +*/ + ret =ioctl (fd,FIFREEZE ); +if (ret<0 && errno !=EOPNOTSUPP ) { +sprintf (err_msg,"failed to freeze %s, %s" , mount->dirname,strerror (errno)); +error_set (err,QERR_QGA_COMMAND_FAILED , err_msg); +close (fd); + goto error; + } +close (fd); + + i++; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_FROZEN ; +return i; + +error: +if (i>0 ) { +qmp_guest_fsfreeze_thaw (NULL ); + } +return 0 ; +} + +/* +* Walk list of frozen file systems in the guest, and thaw them. +*/ +int64_t qmp_guest_fsfreeze_thaw (Error **err) +{ +int ret; +GuestFsfreezeMount *mount, *temp; +int fd, i =0 ; +bool has_error = false; + + QTAILQ_FOREACH_SAFE(mount,&guest_fsfreeze_state.mount_list, next, temp) { + fd =qemu_open (mount->dirname,O_RDONLY ); +if (fd ==-1 ) { + has_error = true; +continue ; + } + ret =ioctl (fd,FITHAW ); +if (ret<0 && errno !=EOPNOTSUPP && errno !=EINVAL ) { + has_error = true; +close (fd); +continue ; + } +close (fd); + i++; + } + +if (has_error) { + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_ERROR ; + }else { + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_THAWED ; + } +enable_logging (); +return i; +} + +static void guest_fsfreeze_init (void ) +{ + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_THAWED ; +QTAILQ_INIT (&guest_fsfreeze_state.mount_list); +} + +static void guest_fsfreeze_cleanup (void ) +{ +int64_t ret; +Error *err =NULL ; + +if (guest_fsfreeze_state.status ==GUEST_FSFREEZE_STATUS_FROZEN ) { + ret =qmp_guest_fsfreeze_thaw (&err); +if (ret<0 || err) { +slog ("failed to clean up frozen filesystems" ); + } + } +} + +/* register init/cleanup routines for stateful command groups */ +void ga_command_state_init (GAState *s,GACommandState *cs) +{ + ga_state = s; +ga_command_state_add (cs, guest_fsfreeze_init, guest_fsfreeze_cleanup); +ga_command_state_add (cs, guest_file_init,NULL ); +}qga/guest-agent-core.h +2
-0@@ -14,10 +14,12 @@#include "qemu-common.h" #define QGA_VERSION "1.0" +#define QGA_READ_COUNT_DEFAULT 4<< 10typedef struct GAState GAState ;typedef struct GACommandState GACommandState ; +void ga_command_state_init (GAState *s,GACommandState *cs);void ga_command_state_add (GACommandState *cs,void (*init)(void ),void (*cleanup)(void ));
Re: [Qemu-devel] [PATCH v7 4/4] guest agent: add guest agent RPCs/commands
Quoted 636 lines · On Fri, 15 Jul 2011 12:21:55 -0500 Michael Roth <[email protected]>…
Quoted 140 lines · Luiz Capitulino
Quoted 137 lines · On Thu, 14 Jul 2011 15:00:34 -0500 Michael Roth<[email protected]>…
This adds the initial set of QMP/QAPI commands provided by the guest agent:
guest-sync
guest-ping
guest-info
guest-shutdown
guest-file-open
guest-file-read
guest-file-write
guest-file-seek
guest-file-flush
guest-file-close
guest-fsfreeze-freeze
guest-fsfreeze-thaw
guest-fsfreeze-statusThe input/output specification for these commands are documented in the schema.
Example usage:
host: qemu -device virtio-serial \ -chardev socket,path=/tmp/vs0.sock,server,nowait,id=qga0 \ -device virtserialport,chardev=qga0,name=org.qemu.quest_agent.0 ...echo "{'execute':'guest-info'}" | socat stdio unix-connect:/tmp/qga0.sock
guest: qemu-ga -m virtio-serial -p /dev/virtio-ports/org.qemu.guest_agent.0 \ -p /var/run/qemu-guest-agent.pid -dSigned-off-by Michael Roth<[email protected]>--- Makefile | 15 ++- qapi-schema-guest.json | 217 +++++++++++++++++++ qemu-ga.c | 4 + qerror.c | 8 + qerror.h | 6 + qga/guest-agent-commands.c | 512 ++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 2 + 7 files changed, 762 insertions(+), 2 deletions(-)create mode 100644 qapi-schema-guest.json
create mode 100644qga/guest-agent-commands.cMakefile +13
-2@@ -175,15 +175,26 @@ $(qapi-dir)/test-qmp-commands.h: $(qapi-dir)/test-qmp-marshal.c $(qapi-dir)/test-qmp-marshal.c: $(SRC_PATH)/qapi-schema-test.json $(SRC_PATH)/scripts/qapi-commands.py $(call quiet-command,python $(SRC_PATH)/scripts/qapi-commands.py -o "$(qapi-dir)" -p "test-"< $<, " GEN $@") +$(qapi-dir)/qga-qapi-types.c: $(qapi-dir)/qga-qapi-types.h +$(qapi-dir)/qga-qapi-types.h: $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-types.py + $(call quiet-command,python $(SRC_PATH)/scripts/qapi-types.py -o "$(qapi-dir)" -p "qga-"< $<, " GEN $@") +$(qapi-dir)/qga-qapi-visit.c: $(qapi-dir)/qga-qapi-visit.h +$(qapi-dir)/qga-qapi-visit.h: $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-visit.py + $(call quiet-command,python $(SRC_PATH)/scripts/qapi-visit.py -o "$(qapi-dir)" -p "qga-"< $<, " GEN $@") +$(qapi-dir)/qga-qmp-marshal.c: $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-commands.py + $(call quiet-command,python $(SRC_PATH)/scripts/qapi-commands.py -o "$(qapi-dir)" -p "qga-"< $<, " GEN $@") + test-visitor.o: $(addprefix $(qapi-dir)/, test-qapi-types.c test-qapi-types.h test-qapi-visit.c test-qapi-visit.h) test-visitor: test-visitor.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o $(qapi-obj-y) error.o osdep.o qemu-malloc.o $(oslib-obj-y) qjson.o json-streamer.o json-lexer.o json-parser.o qerror.o qemu-error.o qemu-tool.o $(qapi-dir)/test-qapi-visit.o $(qapi-dir)/test-qapi-types.o test-qmp-commands.o: $(addprefix $(qapi-dir)/, test-qapi-types.c test-qapi-types.h test-qapi-visit.c test-qapi-visit.h test-qmp-marshal.c test-qmp-commands.h) test-qmp-commands: test-qmp-commands.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o $(qapi-obj-y) error.o osdep.o qemu-malloc.o $(oslib-obj-y) qjson.o json-streamer.o json-lexer.o json-parser.o qerror.o qemu-error.o qemu-tool.o $(qapi-dir)/test-qapi-visit.o $(qapi-dir)/test-qapi-types.o $(qapi-dir)/test-qmp-marshal.o module.o -QGALIB=qga/guest-agent-command-state.o +QGALIB=qga/guest-agent-command-state.o qga/guest-agent-commands.o + +qemu-ga.o: $(qapi-dir)/qga-qapi-types.c $(qapi-dir)/qga-qapi-types.h $(qapi-dir)/qga-qapi-visit.c $(qapi-dir)/qga-qmp-marshal.c -qemu-ga$(EXESUF): qemu-ga.o $(QGALIB) qemu-tool.o qemu-error.o error.o $(oslib-obj-y) $(trace-obj-y) $(block-obj-y) $(qobject-obj-y) $(version-obj-y) $(qapi-obj-y) qemu-timer-common.o qemu-sockets.o module.o qapi/qmp-dispatch.o qapi/qmp-registry.o +qemu-ga$(EXESUF): qemu-ga.o $(QGALIB) qemu-tool.o qemu-error.o error.o $(oslib-obj-y) $(trace-obj-y) $(block-obj-y) $(qobject-obj-y) $(version-obj-y) $(qapi-obj-y) qemu-timer-common.o qemu-sockets.o module.o qapi/qmp-dispatch.o qapi/qmp-registry.o $(qapi-dir)/qga-qapi-visit.o $(qapi-dir)/qga-qapi-types.o $(qapi-dir)/qga-qmp-marshal.o QEMULIBS=libhw32 libhw64 libuser libdis libdis-userqapi-schema-guest.json new file +51
-0@@ -0,0 +1,217 @@ +# *-*- Mode: Python -*-* + +## +# @guest-sync: +# +# Echo back a unique integer value +# +# This is used by clients talking to the guest agent over the +# wire to ensure the stream is in sync and doesn't contain stale +# data from previous client. All guest agent responses should be +# ignored until the provided unique integer value is returned, +# and it is up to the client to handle stale whole or +# partially-delivered JSON text in such a way that this response +# can be obtained. +# +# Such clients should also preceed this command +# with a 0xFF byte to make such the guest agent flushes any +# partially read JSON data from a previous session. +# +# @id: randomly generated 64-bit integer +# +# Returns: The unique integer id passed in by the client +# +# Since: 0.15.0 +## +{ 'command': 'guest-sync' + 'data': { 'id': 'int' }, + 'returns': 'int' } + +## +# @guest-ping: +# +# Ping the guest agent, a non-error return implies success +# +# Since: 0.15.0 +## +{ 'command': 'guest-ping' } + +## +# @guest-info: +# +# Get some information about the guest agent. +# +# Since: 0.15.0 +## +{ 'type': 'GuestAgentInfo', 'data': {'version': 'str'} } +{ 'command': 'guest-info', + 'returns': 'GuestAgentInfo' } + +## +# @guest-shutdown:Quoted 9 lines
qapi-schema-guest.json line 57
Quoted 6 lines
qapi-schema-guest.json new file +6
-0+# +# Initiate guest-activated shutdown. Note: this is an asynchronous +# shutdown request, with no guaruntee of successful shutdown. Errors +# will be logged to guest's syslog. +# +# @mode: #optional "halt", "powerdown", or "reboot" (default)I'd choose 'powerdown' as the default.
Yup, meant to change this sorry.
Quoted 26 lines
Quoted 26 lines
qapi-schema-guest.json new file +26
-0+# +# Returns: Nothing on success +# +# Since: 0.15.0 +## +{ 'command': 'guest-shutdown', 'data': { '*mode': 'str' } } + +## +# @guest-file-open: +# +# Open a file in the guest and retrieve a file handle for it +# +# @filepath: Full path to the file in the guest to open. +# +# @mode: #optional open mode, as per fopen(), "r" is the default. +# +# Returns: Guest file handle on success. +# +# Since: 0.15.0 +## +{ 'command': 'guest-file-open', + 'data': { 'path': 'str', '*mode': 'str' }, + 'returns': 'int' } + +## +# @guest-file-close:Quoted 9 lines
qapi-schema-guest.json line 89
Quoted 6 lines
qapi-schema-guest.json new file +6
-0+# +# Close an open file in the guest +# +# @handle: filehandle returned by guest-file-open +# +# Returns: Nothing on success.
fclose()can fail, sorry for not seeing this before.I'll add checks for this.
Quoted 38 lines
Quoted 8 lines
qapi-schema-guest.json new file +8
-0+# +# Since: 0.15.0 +## +{ 'command': 'guest-file-close', + 'data': { 'handle': 'int' } } + +## +# @guest-file-read:qapi-schema-guest.json line 107
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+# +# Read from an open file in the guest. Data will be base64-encoded +# +# @handle: filehandle returned by guest-file-open +# +# @count: #optional maximum number of bytes to read (default is 4KB) +# +# Returns: GuestFileRead on success. Note: count is number of bytes read +# *before* base64 encoding +# bytes read.unneeded line break.
Quoted 17 lines
qapi-schema-guest.json new file +17
-0+# +# Since: 0.15.0 +## +{ 'type': 'GuestFileRead', + 'data': { 'count': 'int', 'buf-b64': 'str', 'eof': 'bool' } } + +{ 'command': 'guest-file-read', + 'data': { 'handle': 'int', '*count': 'int' }, + 'returns': 'GuestFileRead' } + +## +# @guest-file-write: +# +# Write to an open file in the guest. +# +# @handle: filehandle returned by guest-file-open +#Quoted 9 lines
qapi-schema-guest.json line 130
Quoted 6 lines
qapi-schema-guest.json new file +6
-0+# @buf-b64: base64-encoded string representing data to be written +# +# @count: #optional bytes to write (actual bytes, after base64-decode), +# default is all content in buf-b64 buffer after base64 decoding +# +# Returns: GuestFileWrite on success. Note: count is the number ofnumber of?
number of bytes base64-decoded bytes written. must've gotten distracted :)
Quoted 54 lines
Quoted 54 lines
qapi-schema-guest.json new file +54
-0+# +# Since: 0.15.0 +## +{ 'type': 'GuestFileWrite', + 'data': { 'count': 'int', 'eof': 'bool' } } +{ 'command': 'guest-file-write', + 'data': { 'handle': 'int', 'buf-b64': 'str', '*count': 'int' }, + 'returns': 'GuestFileWrite' } + +## +# @guest-file-seek: +# +# Seek to a position in the file, as with fseek(), and return the +# current file position afterward. Also encapsulates ftell()'s +# functionality, just Set offset=0, whence=SEEK_CUR. +# +# @handle: filehandle returned by guest-file-open +# +# @offset: bytes to skip over in the file stream +# +# @whence: SEEK_SET, SEEK_CUR, or SEEK_END, as with fseek() +# +# Returns: GuestFileSeek on success. +# +# Since: 0.15.0 +## +{ 'type': 'GuestFileSeek', + 'data': { 'position': 'int', 'eof': 'bool' } } + +{ 'command': 'guest-file-seek', + 'data': { 'handle': 'int', 'offset': 'int', 'whence': 'int' }, + 'returns': 'GuestFileSeek' } + +## +# @guest-file-flush: +# +# Write file changes bufferred in userspace to disk/kernel buffers +# +# @handle: filehandle returned by guest-file-open +# +# Returns: Nothing on success. +# +# Since: 0.15.0 +## +{ 'command': 'guest-file-flush', + 'data': { 'handle': 'int' } } + +## +# @guest-fsfreeze-status: +# +# Get guest fsfreeze state. error state indicates failure to thaw 1 or more +# previously frozen filesystems, or failure to open a previously cached +# filesytem (filesystem unmounted/directory changes, etc). +#Quoted 9 lines
qapi-schema-guest.json line 190
Quoted 6 lines
qapi-schema-guest.json new file +6
-0+# Returns: GuestFsfreezeStatus (of the form "GUEST_FSFREEZE_STATUS_<STATUS>") +# +# Since: 0.15.0 +## +{ 'enum': 'GuestFsfreezeStatus', + 'data': [ 'thawed', 'frozen', 'error' ] }I'd expect the status to be just that and not the plain enum string name.
I like the extra verbosity for enums but I guess the schema/command/field tell you that anyway so I guess it's somewhat redundant. Will change.
Quoted 233 lines
Quoted 233 lines
qapi-schema-guest.json new file +27
-0+{ 'command': 'guest-fsfreeze-status', + 'returns': 'GuestFsfreezeStatus' } + +## +# @guest-fsfreeze-freeze: +# +# Sync and freeze all non-network guest filesystems +# +# Returns: Number of file systems frozen on success +# +# Since: 0.15.0 +## +{ 'command': 'guest-fsfreeze-freeze', + 'returns': 'int' } + +## +# @guest-fsfreeze-thaw: +# +# Unfreeze frozen guest fileystems +# +# Returns: Number of file systems thawed +# If error, -1 (unknown error) or -errno +# +# Since: 0.15.0 +## +{ 'command': 'guest-fsfreeze-thaw', + 'returns': 'int' }qemu-ga.c +4
-0@@ -653,6 +653,9 @@ int main(int argc, char **argv)g_log_set_default_handler (ga_log, s);g_log_set_fatal_mask (NULL ,G_LOG_LEVEL_ERROR ); s->logging_enabled = true; + s->command_state =ga_command_state_new (); +ga_command_state_init (s, s->command_state); +ga_command_state_init_all (s->command_state); ga_state = s;module_call_init (MODULE_INIT_QAPI );@@ -661,6 +664,7 @@ int main(int argc, char **argv)g_main_loop_run (ga_state->main_loop); +ga_command_state_cleanup_all (ga_state->command_state);unlink (pidfile);return 0 ;qerror.c +8
-0@@ -218,6 +218,14 @@ static const QErrorStringTable qerror_table[] = { .error_fmt = QERR_VNC_SERVER_FAILED, .desc = "Could not start VNC server on %(target)", }, + { + .error_fmt = QERR_QGA_LOGGING_FAILED, + .desc = "Guest agent failed to log non-optional log statement", + }, + { + .error_fmt = QERR_QGA_COMMAND_FAILED, + .desc = "Guest agent command failed, error was '%(message)'", + }, {} };qerror.h +6
-0@@ -184,4 +184,10 @@ QError *qobject_to_qerror(const QObject *obj);#define QERR_FEATURE_DISABLED \ "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }" +#define QERR_QGA_LOGGING_FAILED \ + "{ 'class': 'QgaLoggingFailed', 'data': {} }" + +#define QERR_QGA_COMMAND_FAILED \ + "{ 'class': 'QgaCommandFailed', 'data': { 'message': %s } }" +#endif /* QERROR_H */ qga/guest-agent-commands.c new file +144
-0@@ -0,0 +1,512 @@ +/* +* QEMU Guest Agent commands +* +* Copyright IBM Corp. 2011 +* +* Authors: +* Michael Roth<[email protected]> +* +* This work is licensed under the terms of the GNU GPL, version 2 or later. +* See the COPYING file in the top-level directory. +*/ + +#include <glib.h> +#include <mntent.h> +#include <sys/types.h> +#include <sys/ioctl.h> +#include <linux/fs.h> +#include "qga/guest-agent-core.h" +#include "qga-qmp-commands.h" +#include "qerror.h" +#include "qemu-queue.h" + +static GAState *ga_state; + +static void disable_logging (void ) +{ +ga_disable_logging (ga_state); +} + +static void enable_logging (void ) +{ +ga_enable_logging (ga_state); +} + +/* Note: in some situations, like with the fsfreeze, logging may be +* temporarilly disabled. if it is necessary that a command be able +* to log for accounting purposes, check ga_logging_enabled() beforehand, +* and use the QERR_QGA_LOGGING_DISABLED to generate an error +*/ +static void slog (const char *fmt, ...) +{ +va_list ap; + +va_start (ap, fmt); +g_logv ("syslog" ,G_LOG_LEVEL_INFO , fmt, ap); +va_end (ap); +} + +int64_t qmp_guest_sync (int64_t id,Error **errp) +{ +return id; +} + +void qmp_guest_ping (Error **err) +{ +slog ("guest-ping called" ); +} + +struct GuestAgentInfo *qmp_guest_info (Error **err) +{ +GuestAgentInfo *info =qemu_mallocz (sizeof (GuestAgentInfo)); + + info->version =g_strdup (QGA_VERSION ); + +return info; +} + +void qmp_guest_shutdown (bool has_mode,const char *mode,Error **err) +{ +int ret; +const char *shutdown_flag; + +slog ("guest-shutdown called, mode: %s" , mode); +if (!has_mode ||strcmp (mode,"reboot" ) ==0 ) { + shutdown_flag ="-r" ; + }else if (strcmp (mode,"halt" ) ==0 ) { + shutdown_flag ="-H" ; + }else if (strcmp (mode,"powerdown" ) ==0 ) { + shutdown_flag ="-P" ; + }else { +error_set (err,QERR_INVALID_PARAMETER_VALUE ,"mode" , +"halt|powerdown|reboot" ); +return ; + } + + ret =fork (); +if (ret ==0 ) { +/* child, start the shutdown */ +setsid (); +fclose (stdin); +fclose (stdout); +fclose (stderr); + + ret =execl ("/sbin/shutdown" ,"shutdown" , shutdown_flag,"+0" , +"hypervisor initiated shutdown" , (char *)NULL ); +if (ret) { +slog ("guest-shutdown failed: %s" ,strerror (errno)); + } +exit (!!ret); + }else if (ret<0 ) { +error_set (err,QERR_UNDEFINED_ERROR ); + } +} + +typedef struct GuestFileHandle { +uint64_t id; +FILE *fh; +QTAILQ_ENTRY (GuestFileHandle) next; +}GuestFileHandle ; + +static struct { + QTAILQ_HEAD(, GuestFileHandle) filehandles; +} guest_file_state; + +static void guest_file_handle_add (FILE *fh) +{ +GuestFileHandle *gfh; + + gfh =qemu_mallocz (sizeof (GuestFileHandle)); + gfh->id =fileno (fh); + gfh->fh = fh; +QTAILQ_INSERT_TAIL (&guest_file_state.filehandles, gfh, next); +} + +static GuestFileHandle *guest_file_handle_find (int64_t id) +{ +GuestFileHandle *gfh; + + QTAILQ_FOREACH(gfh,&guest_file_state.filehandles, next) + { +if (gfh->id == id) { +return gfh; + } + } + +return NULL ; +} + +int64_t qmp_guest_file_open (const char *path,bool has_mode,const char *mode,Error **err) +{ +FILE *fh; +int fd; +int64_t ret =-1 ; +Quoted 9 lines
qga/guest-agent-commands.c line 149
Quoted 5 lines
qga/guest-agent-commands.c new file +5
-0+if (!has_mode) { + mode ="r" ; + } +slog ("guest-file-open called, filepath: %s, mode: %s" , path, mode); + fh =fopen (path, mode);I think it's good to check if 'mode' is valid. Linux libc seems to handle this correctly, but I don't know if other unices will do.
I think it's okay to apply the "let them blow their guest up" methodology we adopted for guest-read-file here as well, since the client theoretically knows the guest better.
Quoted 55 lines
Quoted 23 lines
qga/guest-agent-commands.c new file +23
-0+if (!fh) { +error_set (err,QERR_OPEN_FILE_FAILED , path); +return -1 ; + } + +/* set fd non-blocking to avoid common use cases (like reading from a +* named pipe) from hanging the agent +*/ + fd =fileno (fh); + ret =fcntl (fd,F_GETFL ); + ret =fcntl (fd,F_SETFL , ret |O_NONBLOCK ); +if (ret ==-1 ) { +error_set (err,QERR_OPEN_FILE_FAILED , path); +fclose (fh); +return -1 ; + } + +guest_file_handle_add (fh); +slog ("guest-file-open, handle: %d" , fd); +return fd; +} + +void qmp_guest_file_close (int64_t handle,Error **err)qga/guest-agent-commands.c line 182
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+{ +GuestFileHandle *gfh =guest_file_handle_find (handle); + +slog ("guest-file-close called, handle: %ld" , handle); +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"handle" ); +return ; + } + +fclose (gfh->fh);As I said above, this can fail.
Quoted 19 lines
qga/guest-agent-commands.c new file +19
-0+QTAILQ_REMOVE (&guest_file_state.filehandles, gfh, next); +qemu_free (gfh); +} + +struct GuestFileRead *qmp_guest_file_read (int64_t handle,bool has_count, +int64_t count,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (handle); +GuestFileRead *read_data =NULL ; +guchar *buf; +FILE *fh; +size_t read_count; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"handle" ); +return NULL ; + } + +if (!has_count) {Quoted 9 lines
qga/guest-agent-commands.c line 206
Quoted 5 lines
qga/guest-agent-commands.c new file +5
-0+ count =QGA_READ_COUNT_DEFAULT ; + }else if (count<0 ) { +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + }As I said in my past review, I think it's a good idea to limit 'count' to the file size.
I guess I misunderstood. I suggested we drop both the idea of limiting to a
QGA_READ_COUNT_MAXas well as limiting to filesize and thought we were in agreement in letting the client blow up their guest with huge mallocs if they were so inclined. And if they find themselves in that situation they're misusing the interface anyway since there's a token size limit of 64MB (which reminds me I need to add a note about that in the schema/docs) which would've bit them if their malloc didn't cause any problems.If you'd still like to do it this way, I don't think
fstat()would work since it wouldn't reflect updates fromfwrite()until an fflush()/fclose(). And if we're gonna bother with this we should also be more correct and limit to amount of bytes left in the stream. I think something like this would do it:
Quoted 8 lines
cur_pos= ftell(fh);fseek(fh, 0, SEEK_END);last_pos= ftell(fh);fseek(fh, cur_pos, SEEK_SET);
remaining =last_pos-cur_pos
count = (count > remaining) ? remaining : count;And we'd need to do it on every call to guest-file-read.
I think it's up to the client to do that, that's when the 'you should know what it's doing' saying applies. At the same time, I'm not that strong about that for this first version. If you prefer, we can wait & see if this turns out to be an issue and fix it if it does.
Quoted 151 lines
Quoted 11 lines
qga/guest-agent-commands.c line 216
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ + fh = gfh->fh; + buf =qemu_mallocz (count+1 ); + read_count =fread (buf,1 , count, fh); +if (ferror (fh)) { +slog ("guest-file-read failed, handle: %ld" , handle); +error_set (err,QERR_QGA_COMMAND_FAILED ,"fread() failed" ); + }else { + buf[read_count] =0 ; + read_data =qemu_mallocz (sizeof (GuestFileRead) +1 );Quoted 2 lines
Why +1?
ehhh...no idea. Must've added that erroneously when I was fixing a buf overflow with 'buf =
qemu_mallocz(count);'. Will fix.Quoted 124 lines
Quoted 124 lines
qga/guest-agent-commands.c new file +124
-0+ read_data->count = read_count; + read_data->eof =feof (fh); +if (read_count) { + read_data->buf_b64 =g_base64_encode (buf, read_count); + } + } +qemu_free (buf); +clearerr (fh); + +return read_data; +} + +GuestFileWrite *qmp_guest_file_write (int64_t handle,const char *buf_b64, +bool has_count,int64_t count,Error **err) +{ +GuestFileWrite *write_data =NULL ; +guchar *buf; +gsize buf_len; +int write_count; +GuestFileHandle *gfh =guest_file_handle_find (handle); +FILE *fh; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"handle" ); +return NULL ; + } + + fh = gfh->fh; + buf =g_base64_decode (buf_b64,&buf_len); + +if (!has_count) { + count = buf_len; + }else if (count<0 || count> buf_len) { +qemu_free (buf); +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + } + + write_count =fwrite (buf,1 , count, fh); +if (ferror (fh)) { +slog ("guest-file-write failed, handle: %ld" , handle); +error_set (err,QERR_QGA_COMMAND_FAILED ,"fwrite() error" ); + }else { + write_data =qemu_mallocz (sizeof (GuestFileWrite)); + write_data->count = write_count; + write_data->eof =feof (fh); + } +qemu_free (buf); +clearerr (fh); + +return write_data; +} + +struct GuestFileSeek *qmp_guest_file_seek (int64_t handle,int64_t offset, +int64_t whence,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (handle); +GuestFileSeek *seek_data =NULL ; +FILE *fh; +int ret; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"handle" ); +return NULL ; + } + + fh = gfh->fh; + ret =fseek (fh, offset, whence); +if (ret ==-1 ) { +error_set (err,QERR_QGA_COMMAND_FAILED ,strerror (errno)); + }else { + seek_data =qemu_mallocz (sizeof (GuestFileRead)); + seek_data->position =ftell (fh); + seek_data->eof =feof (fh); + } +clearerr (fh); + +return seek_data; +} + +void qmp_guest_file_flush (int64_t handle,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (handle); +FILE *fh; +int ret; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"handle" ); +return ; + } + + fh = gfh->fh; + ret =fflush (fh); +if (ret ==EOF ) { +error_set (err,QERR_QGA_COMMAND_FAILED ,strerror (errno)); + } +} + +static void guest_file_init (void ) +{ +QTAILQ_INIT (&guest_file_state.filehandles); +} + +typedef struct GuestFsfreezeMount { +char *dirname; +char *devtype; +QTAILQ_ENTRY (GuestFsfreezeMount) next; +}GuestFsfreezeMount ; + +struct { +GuestFsfreezeStatus status; + QTAILQ_HEAD(, GuestFsfreezeMount) mount_list; +} guest_fsfreeze_state; + +/* +* Walk the mount table and build a list of local file systems +*/ +static int guest_fsfreeze_build_mount_list (void ) +{ +struct mntent *ment; +GuestFsfreezeMount *mount, *temp; +char const *mtab =MOUNTED ; +FILE *fp; +Quoted 9 lines
qga/guest-agent-commands.c line 346
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+ QTAILQ_FOREACH_SAFE(mount,&guest_fsfreeze_state.mount_list, next, temp) { +QTAILQ_REMOVE (&guest_fsfreeze_state.mount_list, mount, next); +qemu_free (mount->dirname); +qemu_free (mount->devtype); +qemu_free (mount); + }Why is this needed? Shouldn't this be done on
qmp_guest_fsfreeze_thaw()?
Quoted 5 lines
Thaw might leave them in an error state, and the only recourse might be to retry the thaw on the cached mount list after manual intervening on the guest. So the list needs to stick around else we'd have to rebuild it in thaw, which means it may not be in sync with the list we were using when doing the initial freeze.
Ok.
Quoted 186 lines
Quoted 185 lines
Quoted 184 lines
qga/guest-agent-commands.c new file +166
-0+ + fp =setmntent (mtab,"r" ); +if (!fp) { +g_warning ("fsfreeze: unable to read mtab" ); +return -1 ; + } + +while ((ment =getmntent (fp))) { +/* +* An entry which device name doesn't start with a '/' is +* either a dummy file system or a network file system. +* Add special handling for smbfs and cifs as is done by +* coreutils as well. +*/ +if ((ment->mnt_fsname[0 ] !='/' ) || + (strcmp (ment->mnt_type,"smbfs" ) ==0 ) || + (strcmp (ment->mnt_type,"cifs" ) ==0 )) { +continue ; + } + + mount =qemu_mallocz (sizeof (GuestFsfreezeMount)); + mount->dirname =qemu_strdup (ment->mnt_dir); + mount->devtype =qemu_strdup (ment->mnt_type); + +QTAILQ_INSERT_TAIL (&guest_fsfreeze_state.mount_list, mount, next); + } + +endmntent (fp); + +return 0 ; +} + +/* +* Return status of freeze/thaw +*/ +GuestFsfreezeStatus qmp_guest_fsfreeze_status (Error **err) +{ +return guest_fsfreeze_state.status; +} + +/* +* Walk list of mounted file systems in the guest, and freeze the ones which +* are real local file systems. +*/ +int64_t qmp_guest_fsfreeze_freeze (Error **err) +{ +int ret =0 , i =0 ; +struct GuestFsfreezeMount *mount, *temp; +int fd; +char err_msg[512 ]; + +slog ("guest-fsfreeze called" ); + +if (guest_fsfreeze_state.status ==GUEST_FSFREEZE_STATUS_FROZEN ) { +return 0 ; + } + + ret =guest_fsfreeze_build_mount_list (); +if (ret<0 ) { +return ret; + } + +/* cannot risk guest agent blocking itself on a write in this state */ +disable_logging (); + + QTAILQ_FOREACH_SAFE(mount,&guest_fsfreeze_state.mount_list, next, temp) { + fd =qemu_open (mount->dirname,O_RDONLY ); +if (fd ==-1 ) { +sprintf (err_msg,"failed to open %s, %s" , mount->dirname,strerror (errno)); +error_set (err,QERR_QGA_COMMAND_FAILED , err_msg); + goto error; + } + +/* we try to cull filesytems we know won't work in advance, but other +* filesytems may not implement fsfreeze for less obvious reasons. +* these will report EOPNOTSUPP, so we simply ignore them. when +* thawing, these filesystems will return an EINVAL instead, due to +* not being in a frozen state. Other filesystem-specific +* errors may result in EINVAL, however, so the user should check the +* number * of filesystems returned here against those returned by the +* thaw operation to determine whether everything completed +* successfully +*/ + ret =ioctl (fd,FIFREEZE ); +if (ret<0 && errno !=EOPNOTSUPP ) { +sprintf (err_msg,"failed to freeze %s, %s" , mount->dirname,strerror (errno)); +error_set (err,QERR_QGA_COMMAND_FAILED , err_msg); +close (fd); + goto error; + } +close (fd); + + i++; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_FROZEN ; +return i; + +error: +if (i>0 ) { +qmp_guest_fsfreeze_thaw (NULL ); + } +return 0 ; +} + +/* +* Walk list of frozen file systems in the guest, and thaw them. +*/ +int64_t qmp_guest_fsfreeze_thaw (Error **err) +{ +int ret; +GuestFsfreezeMount *mount, *temp; +int fd, i =0 ; +bool has_error = false; + + QTAILQ_FOREACH_SAFE(mount,&guest_fsfreeze_state.mount_list, next, temp) { + fd =qemu_open (mount->dirname,O_RDONLY ); +if (fd ==-1 ) { + has_error = true; +continue ; + } + ret =ioctl (fd,FITHAW ); +if (ret<0 && errno !=EOPNOTSUPP && errno !=EINVAL ) { + has_error = true; +close (fd); +continue ; + } +close (fd); + i++; + } + +if (has_error) { + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_ERROR ; + }else { + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_THAWED ; + } +enable_logging (); +return i; +} + +static void guest_fsfreeze_init (void ) +{ + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_THAWED ; +QTAILQ_INIT (&guest_fsfreeze_state.mount_list); +} + +static void guest_fsfreeze_cleanup (void ) +{ +int64_t ret; +Error *err =NULL ; + +if (guest_fsfreeze_state.status ==GUEST_FSFREEZE_STATUS_FROZEN ) { + ret =qmp_guest_fsfreeze_thaw (&err); +if (ret<0 || err) { +slog ("failed to clean up frozen filesystems" ); + } + } +} + +/* register init/cleanup routines for stateful command groups */ +void ga_command_state_init (GAState *s,GACommandState *cs) +{ + ga_state = s; +ga_command_state_add (cs, guest_fsfreeze_init, guest_fsfreeze_cleanup); +ga_command_state_add (cs, guest_file_init,NULL ); +}qga/guest-agent-core.h +2
-0@@ -14,10 +14,12 @@#include "qemu-common.h" #define QGA_VERSION "1.0" +#define QGA_READ_COUNT_DEFAULT 4<< 10typedef struct GAState GAState ;typedef struct GACommandState GACommandState ; +void ga_command_state_init (GAState *s,GACommandState *cs);void ga_command_state_add (GACommandState *cs,void (*init)(void ),void (*cleanup)(void ));
Quoted 87 lines · Michael Roth
This is Set 3/3 of the QAPI+QGA patchsets.
These patches apply on top of qapi-backport-set2-v6, and can also be obtained from:
git://repo.or.cz/qemu/mdroth.gitqapi-backport-set3-v7(Set1+2 are a backport of some of the QAPI-related work from Anthony's glib tree. The main goal is to get the basic code generation infrastructure in place so that it can be used by the guest agent to implement a QMP-like guest interface, and so that future work regarding the QMP conversion to QAPI can be decoupled from the infrastructure bits. Set3 is the Qemu Guest Agent (virtagent), rebased on the new code QAPI code generation infrastructure. This is the first user of QAPI, QMP will follow.)
___CHANGES SINCE V6:
- Made "/dev/virtio-ports/org.qemu.guest_agent.0" default device path for agent
- Consolidated uneededfcntl()calls intoqemu_open()
- JSON/QMP parse errors now propagated to client
- Replaced non-assertion uses ofg_error()withexit()
- Added guest-file-flush
- Removed limit on max read size for guest-file-read
- 'count' parameters to guest-file-read/guest-file-write are now optional (default to 4KB and size of provided buffer, base64-decoded, respectively)
- Removed redundant 'file_' and 'shutdown_' prefixes from guest-file-*/guest-shutdown commands, switched to "-" in place of "_" in parameter names, renamed guest-file-read's "buf" param to "buf-b64" and guest-file-write's "data_b64" param to "buf-b64" for consistency.
- guest-fsfreeze-freeze now returns error objects on error rather as part of it's integer return values, and on error will unfreeze previously frozen filesystems.
-GUEST_FSFREEZE_STATUS_INPROGRESSremoved,GUEST_FSFREEZE_STATUS_ERRORnow serves the explicit purpose of noting a failure to find a previously mounted filesytem/directory after initial freeze, or failure to unfreeze 1 or more filesystems.
- -c/--channel option to qemu-ga is now -m/--methodCHANGES SINCE V5:
- switched to using qemu malloc/list functions where possible
- removed unusedproxy_pathfield in struct GAState
- pid file now opened write-only, removedlockf()in favor ofO_EXCL, added SIGINT/SIGTERM signal handlers to handle cleanup
- cleaned up error-handling, switched to asserts where appropriate, removed unecessary gotos and NULL checks for qemu_free()/qobject_decref()
- refactoredsend_payload()using helper functions
- fixed improper handling of pidfile fd==0
- changed guest-shutdown's "shutdown_mode" param to "mode"
- switched to using kernel-generated FDs for guest-file-open rather than an autoincrement value
- add maximum chunk size of guest-file-read/guest-file-write
- added checks to avoid guest-file-write from writing data beyond the provided data buffer
- made logging best-effort, removed handling of failures to log as errors
- guest-shutdown exec errors now logged to guest syslog, clarified shutdown's asynchronous, no gauruntee nature in schema.CHANGES SINCE V4:
- Removed timeout mechanism via worker thread/pthread_cancel due to potential memory leak. Will re-introduce guest-side timeout support in future version.
- Fixed up fsfreeze code to use enums specified within the guest agent's qapi schema.
- Fixed memory leak due to a log statement, and added missing cleanup functions for heap-allocatedg_errorobjects.
- Made "mode" param to guest-file-open optional, defaults to "r" (read-only)CHANGES SINCE V3:
- Fixed error-handling issues in fsfreeze commands leading to certain mounted directories causing freeze/thaw operations to fail
- Added cleanup hook to thaw filesystems on graceful guest agent exit
- Removed unused enum values and added additional details to schema documentation
- Fixed build issue that was missed due to deprecated files in source tree, removed unused includesCHANGES SINCE V2:
- Rebased on new QAPI code generation framework
- Dropped ability for QMP to act as a proxy for the guest agent, will be added when new QMP server is backported from Anthony's glib tree
- Replaced negotiation/control events with a simple 2-way handshake implemented by a standard RPC (guest-sync)
- Removed enforcement of "pristine" sessions, state is now global/persistant across multiple clients/connections
- Fixed segfault in logging code
- Added Jes' filesystem freeze patches
- General cleanupsCHANGES SINCE V1:
- Added guest agent worker thread to execute RPCs in the guest. With this in place we have a reliable timeout mechanism for hung commands, currently set at 30 seconds.
- Add framework for registering init/cleanup routines for stateful RPCs to clean up after themselves after a timeout.
- Added the following RPCs: guest-file-{open,close,read,write,seek}, guest-shutdown, guest-info, and removed stubs for guest-view-file (now deprecated)
- Added GUEST_AGENT_UP/GUEST_AGENT_DOWN QMP events
- Switched to a TCP-style host-initiated 3-way handshake for channel negotiation, this simplifies client negotiation/interaction over the wire
- Added configurable log level/log file/pid file options for guest agent
- Various fixes for bugs/memory leaks and checkpatch.pl fixupsISSUES/TODOS:
- Add unit tests for guest agent wire protocolOVERVIEW
For a better overview of what these patches are meant to accomplish, please reference the RFC for virtagent:
http://comments.gmane.org/gmane.comp.emulators.qemu/96096
These patches integrate the previous virtagent guest agent work directly in QAPI/QMP to leverage it's auto-generated marshalling code. This has numerous benefits:
- addresses previous concerns over relying on external libraries to handle data encapsulation
- reduces the need for manual unmarshalling of requests/responses, which makes adding new RPCs much safer/less error-prone, as well as cutting down on redundant code
- QAPI documentation aligns completely with guest-side RPC implementation
- is Just Better (TM)
Quoted 6 lines
BUILD/USAGE
build:
./configure --target-list=x86_64-softmmu make
make qemu-ga #should be built on|for target guest
HI, Macheal.
Is qemu-ga built in guest? if yes, it will require the guest to set up a gcc environment. Can we make it built on the host?
Quoted 55 lines
start guest:
qemu \
-drive file=/home/mdroth/vm/rhel6_64_base.raw,snapshot=off,if=virtio \
-net nic,model=virtio,macaddr=52:54:00:12:34:00 \
-net tap,script=/etc/qemu-ifup \
-vnc :1 -m 1024 --enable-kvm \
-chardev socket,path=/tmp/qga.sock,server,nowait,id=qga0 \
-device virtio-serial \
-device virtserialport,chardev=qga0,name=org.qemu.guest_agent.0"use guest agent:
./qemu-ga -h
./qemu-ga -m virtio-serial -p/dev/virtio-ports/org.qemu.guest_agent.0start/use qmp:
mdroth@illuin:~$ sudo socat unix-connect:/tmp/qga.sock readline {"execute":"guest-sync", "arguments":{"id":1234}} {"return": 1234}{"execute":"guest-ping"}
{"return": {}}{"execute": "guest-info"}
{"return": {"version": "1.0"}}// write "hello world!\n" to
/tmp/testqga
{"execute":"guest-file-open", "arguments":{"path":"/tmp/testqga","mode":"w+"}} {"return": 0}
{"execute":"guest-file-write", "arguments":{"handle":0,"buf-b64":"aGVsbG8gd29ybGQhCg=="}} {"return": {"count": 13, "eof": false}}
{"execute":"guest-file-close", "arguments":{"handle":0}}
{"return": {}}// read back the "hello world!\n" from
/tmp/testqga{"execute":"guest-file-open", "arguments":{"path":"/tmp/testqga","mode":"r"}} {"return": 1}
{"execute":"guest-file-read", "arguments":{"handle":1,"count":1024}} {"return": {"buf-b64": "aGVsbG8gd29ybGQhCg==", "count": 13, "eof": true}} {"execute":"guest-file-close","arguments":{"handle":1}} {"return": {}}Makefile | 25 ++-
configure | 1 +
qapi-schema-guest.json | 217 +++++++++++++
qemu-ga.c | 671 +++++++++++++++++++++++++++++++++++++++qerror.c| 13 +
qerror.h | 6 +qga/guest-agent-command-state.c| 73 +++++qga/guest-agent-commands.c| 512 +++++++++++++++++++++++++++++qga/guest-agent-core.h| 31 ++9 files changed, 1544 insertions(+), 5 deletions(-)
Signature · 3 lines
Regards, Zhi Yong Wu
Quoted 90 lines · On Fri, 15 Jul 2011 09:15:18 +0800 Zhi Yong Wu <[email protected]> wrote:
Quoted 89 lines · Michael Roth
This is Set 3/3 of the QAPI+QGA patchsets.
These patches apply on top of qapi-backport-set2-v6, and can also be obtained from:
git://repo.or.cz/qemu/mdroth.gitqapi-backport-set3-v7(Set1+2 are a backport of some of the QAPI-related work from Anthony's glib tree. The main goal is to get the basic code generation infrastructure in place so that it can be used by the guest agent to implement a QMP-like guest interface, and so that future work regarding the QMP conversion to QAPI can be decoupled from the infrastructure bits. Set3 is the Qemu Guest Agent (virtagent), rebased on the new code QAPI code generation infrastructure. This is the first user of QAPI, QMP will follow.)
___CHANGES SINCE V6:
- Made "/dev/virtio-ports/org.qemu.guest_agent.0" default device path for agent
- Consolidated uneededfcntl()calls intoqemu_open()
- JSON/QMP parse errors now propagated to client
- Replaced non-assertion uses ofg_error()withexit()
- Added guest-file-flush
- Removed limit on max read size for guest-file-read
- 'count' parameters to guest-file-read/guest-file-write are now optional (default to 4KB and size of provided buffer, base64-decoded, respectively)
- Removed redundant 'file_' and 'shutdown_' prefixes from guest-file-*/guest-shutdown commands, switched to "-" in place of "_" in parameter names, renamed guest-file-read's "buf" param to "buf-b64" and guest-file-write's "data_b64" param to "buf-b64" for consistency.
- guest-fsfreeze-freeze now returns error objects on error rather as part of it's integer return values, and on error will unfreeze previously frozen filesystems.
-GUEST_FSFREEZE_STATUS_INPROGRESSremoved,GUEST_FSFREEZE_STATUS_ERRORnow serves the explicit purpose of noting a failure to find a previously mounted filesytem/directory after initial freeze, or failure to unfreeze 1 or more filesystems.
- -c/--channel option to qemu-ga is now -m/--methodCHANGES SINCE V5:
- switched to using qemu malloc/list functions where possible
- removed unusedproxy_pathfield in struct GAState
- pid file now opened write-only, removedlockf()in favor ofO_EXCL, added SIGINT/SIGTERM signal handlers to handle cleanup
- cleaned up error-handling, switched to asserts where appropriate, removed unecessary gotos and NULL checks for qemu_free()/qobject_decref()
- refactoredsend_payload()using helper functions
- fixed improper handling of pidfile fd==0
- changed guest-shutdown's "shutdown_mode" param to "mode"
- switched to using kernel-generated FDs for guest-file-open rather than an autoincrement value
- add maximum chunk size of guest-file-read/guest-file-write
- added checks to avoid guest-file-write from writing data beyond the provided data buffer
- made logging best-effort, removed handling of failures to log as errors
- guest-shutdown exec errors now logged to guest syslog, clarified shutdown's asynchronous, no gauruntee nature in schema.CHANGES SINCE V4:
- Removed timeout mechanism via worker thread/pthread_cancel due to potential memory leak. Will re-introduce guest-side timeout support in future version.
- Fixed up fsfreeze code to use enums specified within the guest agent's qapi schema.
- Fixed memory leak due to a log statement, and added missing cleanup functions for heap-allocatedg_errorobjects.
- Made "mode" param to guest-file-open optional, defaults to "r" (read-only)CHANGES SINCE V3:
- Fixed error-handling issues in fsfreeze commands leading to certain mounted directories causing freeze/thaw operations to fail
- Added cleanup hook to thaw filesystems on graceful guest agent exit
- Removed unused enum values and added additional details to schema documentation
- Fixed build issue that was missed due to deprecated files in source tree, removed unused includesCHANGES SINCE V2:
- Rebased on new QAPI code generation framework
- Dropped ability for QMP to act as a proxy for the guest agent, will be added when new QMP server is backported from Anthony's glib tree
- Replaced negotiation/control events with a simple 2-way handshake implemented by a standard RPC (guest-sync)
- Removed enforcement of "pristine" sessions, state is now global/persistant across multiple clients/connections
- Fixed segfault in logging code
- Added Jes' filesystem freeze patches
- General cleanupsCHANGES SINCE V1:
- Added guest agent worker thread to execute RPCs in the guest. With this in place we have a reliable timeout mechanism for hung commands, currently set at 30 seconds.
- Add framework for registering init/cleanup routines for stateful RPCs to clean up after themselves after a timeout.
- Added the following RPCs: guest-file-{open,close,read,write,seek}, guest-shutdown, guest-info, and removed stubs for guest-view-file (now deprecated)
- Added GUEST_AGENT_UP/GUEST_AGENT_DOWN QMP events
- Switched to a TCP-style host-initiated 3-way handshake for channel negotiation, this simplifies client negotiation/interaction over the wire
- Added configurable log level/log file/pid file options for guest agent
- Various fixes for bugs/memory leaks and checkpatch.pl fixupsISSUES/TODOS:
- Add unit tests for guest agent wire protocolOVERVIEW
For a better overview of what these patches are meant to accomplish, please reference the RFC for virtagent:
http://comments.gmane.org/gmane.comp.emulators.qemu/96096
These patches integrate the previous virtagent guest agent work directly in QAPI/QMP to leverage it's auto-generated marshalling code. This has numerous benefits:
- addresses previous concerns over relying on external libraries to handle data encapsulation
- reduces the need for manual unmarshalling of requests/responses, which makes adding new RPCs much safer/less error-prone, as well as cutting down on redundant code
- QAPI documentation aligns completely with guest-side RPC implementation
- is Just Better (TM)BUILD/USAGE
Quoted 7 lines
Quoted 4 lines
build:
./configure --target-list=x86_64-softmmu make
make qemu-ga #should be built on|for target guestHI, Macheal.
Is qemu-ga built in guest? if yes, it will require the guest to set up a gcc environment. Can we make it built on the host?
Yes, if the host OS matches the guest OS or if you can cross-compile.
Otherwise I think we'll have to rely on distros making qemu-ga available, and/or use the guest tools iso Michael is planning. Another option would be to compile qemu-ga statically, but this is probably unfeasible.
Quoted 59 lines
Quoted 56 lines
start guest:
qemu \
-drive file=/home/mdroth/vm/rhel6_64_base.raw,snapshot=off,if=virtio \
-net nic,model=virtio,macaddr=52:54:00:12:34:00 \
-net tap,script=/etc/qemu-ifup \
-vnc :1 -m 1024 --enable-kvm \
-chardev socket,path=/tmp/qga.sock,server,nowait,id=qga0 \
-device virtio-serial \
-device virtserialport,chardev=qga0,name=org.qemu.guest_agent.0"use guest agent:
./qemu-ga -h
./qemu-ga -m virtio-serial -p/dev/virtio-ports/org.qemu.guest_agent.0start/use qmp:
mdroth@illuin:~$ sudo socat unix-connect:/tmp/qga.sock readline {"execute":"guest-sync", "arguments":{"id":1234}} {"return": 1234}{"execute":"guest-ping"}
{"return": {}}{"execute": "guest-info"}
{"return": {"version": "1.0"}}// write "hello world!\n" to
/tmp/testqga
{"execute":"guest-file-open", "arguments":{"path":"/tmp/testqga","mode":"w+"}} {"return": 0}
{"execute":"guest-file-write", "arguments":{"handle":0,"buf-b64":"aGVsbG8gd29ybGQhCg=="}} {"return": {"count": 13, "eof": false}}
{"execute":"guest-file-close", "arguments":{"handle":0}}
{"return": {}}// read back the "hello world!\n" from
/tmp/testqga{"execute":"guest-file-open", "arguments":{"path":"/tmp/testqga","mode":"r"}} {"return": 1}
{"execute":"guest-file-read", "arguments":{"handle":1,"count":1024}} {"return": {"buf-b64": "aGVsbG8gd29ybGQhCg==", "count": 13, "eof": true}} {"execute":"guest-file-close","arguments":{"handle":1}} {"return": {}}Makefile | 25 ++-
configure | 1 +
qapi-schema-guest.json | 217 +++++++++++++
qemu-ga.c | 671 +++++++++++++++++++++++++++++++++++++++qerror.c| 13 +
qerror.h | 6 +qga/guest-agent-command-state.c| 73 +++++qga/guest-agent-commands.c| 512 +++++++++++++++++++++++++++++qga/guest-agent-core.h| 31 ++9 files changed, 1544 insertions(+), 5 deletions(-)
Zhi Yong Wu
Tested-byQuoted 101 lines · Luiz Capitulino
Quoted 90 lines · On Fri, 15 Jul 2011 09:15:18 +0800 Zhi Yong Wu <[email protected]> wrote:
Quoted 89 lines · Michael Roth
This is Set 3/3 of the QAPI+QGA patchsets.
These patches apply on top of qapi-backport-set2-v6, and can also be obtained from:
git://repo.or.cz/qemu/mdroth.gitqapi-backport-set3-v7(Set1+2 are a backport of some of the QAPI-related work from Anthony's glib tree. The main goal is to get the basic code generation infrastructure in place so that it can be used by the guest agent to implement a QMP-like guest interface, and so that future work regarding the QMP conversion to QAPI can be decoupled from the infrastructure bits. Set3 is the Qemu Guest Agent (virtagent), rebased on the new code QAPI code generation infrastructure. This is the first user of QAPI, QMP will follow.)
___CHANGES SINCE V6:
- Made "/dev/virtio-ports/org.qemu.guest_agent.0" default device path for agent
- Consolidated uneededfcntl()calls intoqemu_open()
- JSON/QMP parse errors now propagated to client
- Replaced non-assertion uses ofg_error()withexit()
- Added guest-file-flush
- Removed limit on max read size for guest-file-read
- 'count' parameters to guest-file-read/guest-file-write are now optional (default to 4KB and size of provided buffer, base64-decoded, respectively)
- Removed redundant 'file_' and 'shutdown_' prefixes from guest-file-*/guest-shutdown commands, switched to "-" in place of "_" in parameter names, renamed guest-file-read's "buf" param to "buf-b64" and guest-file-write's "data_b64" param to "buf-b64" for consistency.
- guest-fsfreeze-freeze now returns error objects on error rather as part of it's integer return values, and on error will unfreeze previously frozen filesystems.
-GUEST_FSFREEZE_STATUS_INPROGRESSremoved,GUEST_FSFREEZE_STATUS_ERRORnow serves the explicit purpose of noting a failure to find a previously mounted filesytem/directory after initial freeze, or failure to unfreeze 1 or more filesystems.
- -c/--channel option to qemu-ga is now -m/--methodCHANGES SINCE V5:
- switched to using qemu malloc/list functions where possible
- removed unusedproxy_pathfield in struct GAState
- pid file now opened write-only, removedlockf()in favor ofO_EXCL, added SIGINT/SIGTERM signal handlers to handle cleanup
- cleaned up error-handling, switched to asserts where appropriate, removed unecessary gotos and NULL checks for qemu_free()/qobject_decref()
- refactoredsend_payload()using helper functions
- fixed improper handling of pidfile fd==0
- changed guest-shutdown's "shutdown_mode" param to "mode"
- switched to using kernel-generated FDs for guest-file-open rather than an autoincrement value
- add maximum chunk size of guest-file-read/guest-file-write
- added checks to avoid guest-file-write from writing data beyond the provided data buffer
- made logging best-effort, removed handling of failures to log as errors
- guest-shutdown exec errors now logged to guest syslog, clarified shutdown's asynchronous, no gauruntee nature in schema.CHANGES SINCE V4:
- Removed timeout mechanism via worker thread/pthread_cancel due to potential memory leak. Will re-introduce guest-side timeout support in future version.
- Fixed up fsfreeze code to use enums specified within the guest agent's qapi schema.
- Fixed memory leak due to a log statement, and added missing cleanup functions for heap-allocatedg_errorobjects.
- Made "mode" param to guest-file-open optional, defaults to "r" (read-only)CHANGES SINCE V3:
- Fixed error-handling issues in fsfreeze commands leading to certain mounted directories causing freeze/thaw operations to fail
- Added cleanup hook to thaw filesystems on graceful guest agent exit
- Removed unused enum values and added additional details to schema documentation
- Fixed build issue that was missed due to deprecated files in source tree, removed unused includesCHANGES SINCE V2:
- Rebased on new QAPI code generation framework
- Dropped ability for QMP to act as a proxy for the guest agent, will be added when new QMP server is backported from Anthony's glib tree
- Replaced negotiation/control events with a simple 2-way handshake implemented by a standard RPC (guest-sync)
- Removed enforcement of "pristine" sessions, state is now global/persistant across multiple clients/connections
- Fixed segfault in logging code
- Added Jes' filesystem freeze patches
- General cleanupsCHANGES SINCE V1:
- Added guest agent worker thread to execute RPCs in the guest. With this in place we have a reliable timeout mechanism for hung commands, currently set at 30 seconds.
- Add framework for registering init/cleanup routines for stateful RPCs to clean up after themselves after a timeout.
- Added the following RPCs: guest-file-{open,close,read,write,seek}, guest-shutdown, guest-info, and removed stubs for guest-view-file (now deprecated)
- Added GUEST_AGENT_UP/GUEST_AGENT_DOWN QMP events
- Switched to a TCP-style host-initiated 3-way handshake for channel negotiation, this simplifies client negotiation/interaction over the wire
- Added configurable log level/log file/pid file options for guest agent
- Various fixes for bugs/memory leaks and checkpatch.pl fixupsISSUES/TODOS:
- Add unit tests for guest agent wire protocolOVERVIEW
For a better overview of what these patches are meant to accomplish, please reference the RFC for virtagent:
http://comments.gmane.org/gmane.comp.emulators.qemu/96096
These patches integrate the previous virtagent guest agent work directly in QAPI/QMP to leverage it's auto-generated marshalling code. This has numerous benefits:
- addresses previous concerns over relying on external libraries to handle data encapsulation
- reduces the need for manual unmarshalling of requests/responses, which makes adding new RPCs much safer/less error-prone, as well as cutting down on redundant code
- QAPI documentation aligns completely with guest-side RPC implementation
- is Just Better (TM)BUILD/USAGE
Quoted 7 lines
Quoted 4 lines
build:
./configure --target-list=x86_64-softmmu make
make qemu-ga #should be built on|for target guestHI, Macheal.
Is qemu-ga built in guest? if yes, it will require the guest to set up a gcc environment. Can we make it built on the host?
Quoted 48 lines
Yes, if the host OS matches the guest OS or if you can cross-compile.
Otherwise I think we'll have to rely on distros making qemu-ga available, and/or use the guest tools iso Michael is planning. Another option would be to compile qemu-ga statically, but this is probably unfeasible.
Quoted 42 lines
Quoted 42 lines
start guest:
qemu \
-drive file=/home/mdroth/vm/rhel6_64_base.raw,snapshot=off,if=virtio \
-net nic,model=virtio,macaddr=52:54:00:12:34:00 \
-net tap,script=/etc/qemu-ifup \
-vnc :1 -m 1024 --enable-kvm \
-chardev socket,path=/tmp/qga.sock,server,nowait,id=qga0 \
-device virtio-serial \
-device virtserialport,chardev=qga0,name=org.qemu.guest_agent.0"use guest agent:
./qemu-ga -h
./qemu-ga -m virtio-serial -p/dev/virtio-ports/org.qemu.guest_agent.0start/use qmp:
mdroth@illuin:~$ sudo socat unix-connect:/tmp/qga.sock readline {"execute":"guest-sync", "arguments":{"id":1234}} {"return": 1234}{"execute":"guest-ping"}
{"return": {}}{"execute": "guest-info"}
{"return": {"version": "1.0"}}// write "hello world!\n" to
/tmp/testqga
{"execute":"guest-file-open", "arguments":{"path":"/tmp/testqga","mode":"w+"}} {"return": 0}
{"execute":"guest-file-write", "arguments":{"handle":0,"buf-b64":"aGVsbG8gd29ybGQhCg=="}} {"return": {"count": 13, "eof": false}}
{"execute":"guest-file-close", "arguments":{"handle":0}}
{"return": {}}// read back the "hello world!\n" from
/tmp/testqga{"execute":"guest-file-open", "arguments":{"path":"/tmp/testqga","mode":"r"}} {"return": 1}
{"execute":"guest-file-read", "arguments":{"handle":1,"count":1024}} {"return": {"buf-b64": "aGVsbG8gd29ybGQhCg==", "count": 13, "eof": true}} {"execute":"guest-file-close","arguments":{"handle":1}} {"return": {}}
Quoted 19 lines
Quoted 17 lines
Quoted 14 lines
Makefile | 25 ++-
configure | 1 +
qapi-schema-guest.json | 217 +++++++++++++
qemu-ga.c | 671 +++++++++++++++++++++++++++++++++++++++qerror.c| 13 +
qerror.h | 6 +qga/guest-agent-command-state.c| 73 +++++qga/guest-agent-commands.c| 512 +++++++++++++++++++++++++++++qga/guest-agent-core.h| 31 ++9 files changed, 1544 insertions(+), 5 deletions(-)
Signature · 3 lines
Regards, Zhi Yong Wu