QEMU Guest Agent (virtagent) v6
PATCH 3/3 QEMU Guest Agent (virtagent) v6
This is Set 3/3 of the QAPI+QGA patchsets.
These patches apply on top of qapi-backport-set2-v5, and can also be obtained from:git://repo.or.cz/qemu/mdroth.git qapi-backport-set3-v6
(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 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=qga \
-device virtio-serial \
-device virtserialport,chardev=qga,name=qga"
use guest agent:
./qemu-ga -h
./qemu-ga -c virtio-serial -p /dev/virtio-ports/qga
start/use qmp:
mdroth@illuin:~$ sudo socat unix-connect:/tmp/qga.sock readline
{"execute":"guest-sync", "arguments":{"id":1234}}
{"return": 1234} {"execute":"guest-info"}
{"return": {}}
{"execute": "guest-info"}
{"return": {"version": "1.0"}}
{"execute":"guest-file-open", "arguments":{"filepath":"/tmp/testqga","mode":"w+"}}
{"return": 0}
{"execute":"guest-file-write", "arguments":{"filehandle":0,"data_b64":"aGVsbG8gd29ybGQhCg==","count":13}} // writes "hello world!\n" {"return": {"count": 13, "eof": false}}
{"execute":"guest-file-open", "arguments":{"filepath":"/tmp/testqga","mode":"r"}} {"return": 1}
{"execute":"guest-file-read", "arguments":{"filehandle":1,"count":1024}} {"return": {"buf": "aGVsbG8gd29ybGQhCg==", "count": 13, "eof": true}} {"execute":"guest-file-close","arguments":{"filehandle":1}} {"return": {}}
Makefile | 22 +- configure | 1 + qapi-schema-guest.json | 202 +++++++++++++ qemu-ga.c | 631 +++++++++++++++++++++++++++++++++++++++ qerror.c | 4 + qerror.h | 3 + qga/guest-agent-command-state.c | 73 +++++ qga/guest-agent-commands.c | 522 ++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 30 ++ 9 files changed, 1483 insertions(+), 5 deletions(-)
PATCH v6 1/4 guest agent: command state class
--- 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
Re: [Qemu-devel] [PATCH v6 1/4] guest agent: command state class
Quoted 10 lines · On Tue, 5 Jul 2011 08:21:37 -0500 Michael Roth <[email protected]>…
Signed-off-by Michael Roth <[email protected]>--- 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
I'm not sure there's much value in having this as a separate patch, maybe it should be folded in the next one.
Quoted 145 lines
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-timestampconfigure +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@@ -0,0 +1,73 @@ +/* +* QEMU Guest Agent command state interfaces +* +* 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 "qga/guest-agent-core.h" + +struct GACommandState { +GSList *groups; +}; + +typedef struct GACommandGroup { +void (*init)(void ); +void (*cleanup)(void ); +}GACommandGroup ; + +/* handle init/cleanup for stateful guest commands */ + +void ga_command_state_add (GACommandState *cs, +void (*init)(void ), +void (*cleanup)(void )) +{ +GACommandGroup *cg =qemu_mallocz (sizeof (GACommandGroup)); + cg->init = init; + cg->cleanup = cleanup; + cs->groups =g_slist_append (cs->groups, cg); +} + +static void ga_command_group_init (gpointer opaque,gpointer unused) +{ +GACommandGroup *cg = opaque; + +g_assert (cg); +if (cg->init) { + cg->init (); + } +} + +void ga_command_state_init_all (GACommandState *cs) +{ +g_assert (cs); +g_slist_foreach (cs->groups, ga_command_group_init,NULL ); +} + +static void ga_command_group_cleanup (gpointer opaque,gpointer unused) +{ +GACommandGroup *cg = opaque; + +g_assert (cg); +if (cg->cleanup) { + cg->cleanup (); + } +} + +void ga_command_state_cleanup_all (GACommandState *cs) +{ +g_assert (cs); +g_slist_foreach (cs->groups, ga_command_group_cleanup,NULL ); +} + +GACommandState *ga_command_state_new (void ) +{ +GACommandState *cs =qemu_mallocz (sizeof (GACommandState)); + cs->groups =NULL ; +return cs; +}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 );
Re: [Qemu-devel] [PATCH v6 1/4] guest agent: command state class
Quoted 14 lines · Luiz Capitulino
Quoted 10 lines · On Tue, 5 Jul 2011 08:21:37 -0500 Michael Roth<[email protected]>…
Signed-off-by Michael Roth<[email protected]>--- 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.ccreate mode 100644qga/guest-agent-core.h
Quoted 3 lines
I'm not sure there's much value in having this as a separate patch, maybe it should be folded in the next one.
I can, just trying to make it more review-friendly really. Same with breaking out the schema from the command implementations. If needed I can respin a more squashed version when things look ready, but this stuff is pretty simple and modularized so it doesn't seem like a bad idea to pull it out of the meatier patch.
Quoted 146 lines
Quoted 145 lines
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-timestampconfigure +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@@ -0,0 +1,73 @@ +/* +* QEMU Guest Agent command state interfaces +* +* 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 "qga/guest-agent-core.h" + +struct GACommandState { +GSList *groups; +}; + +typedef struct GACommandGroup { +void (*init)(void ); +void (*cleanup)(void ); +}GACommandGroup ; + +/* handle init/cleanup for stateful guest commands */ + +void ga_command_state_add (GACommandState *cs, +void (*init)(void ), +void (*cleanup)(void )) +{ +GACommandGroup *cg =qemu_mallocz (sizeof (GACommandGroup)); + cg->init = init; + cg->cleanup = cleanup; + cs->groups =g_slist_append (cs->groups, cg); +} + +static void ga_command_group_init (gpointer opaque,gpointer unused) +{ +GACommandGroup *cg = opaque; + +g_assert (cg); +if (cg->init) { + cg->init (); + } +} + +void ga_command_state_init_all (GACommandState *cs) +{ +g_assert (cs); +g_slist_foreach (cs->groups, ga_command_group_init,NULL ); +} + +static void ga_command_group_cleanup (gpointer opaque,gpointer unused) +{ +GACommandGroup *cg = opaque; + +g_assert (cg); +if (cg->cleanup) { + cg->cleanup (); + } +} + +void ga_command_state_cleanup_all (GACommandState *cs) +{ +g_assert (cs); +g_slist_foreach (cs->groups, ga_command_group_cleanup,NULL ); +} + +GACommandState *ga_command_state_new (void ) +{ +GACommandState *cs =qemu_mallocz (sizeof (GACommandState)); + cs->groups =NULL ; +return cs; +}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 );
PATCH v6 2/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 -c virtio-serial -p /dev/virtio-ports/org.qemu.guest_agent \
-p /var/run/qemu-guest-agent.pid -d--- Makefile | 10 +- qemu-ga.c | 651 ++++++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 4 + 3 files changed, 661 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 +651 -0
651 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
Re: [Qemu-devel] [PATCH v6 2/4] guest agent: qemu-ga daemon
Doh! Missed a final build test and this little bugger slipped in. Please apply the following patch to fix it, qapi-backport-set3-v6 has been updated accordingly. Thanks to Matsuda Daiki for the catch/patch!
qemu-ga.c renamed from qemu-ga.c.orig +1 -1
@@ -54,7 +54,7 @@ static struct GAState *ga_state;static void quit_handler (int sig) { -g_debug ("recieved signal num %d, quitting" ); +g_debug ("recieved signal num %d, quitting" , sig);if (g_main_loop_is_running (ga_state->main_loop)) {g_main_loop_quit (ga_state->main_loop);
Re: [Qemu-devel] [PATCH v6 2/4] guest agent: qemu-ga daemon
In reply to Michael RothQuoted 5 lines · On Tue, 5 Jul 2011 08:21:38 -0500 Michael Roth <[email protected]>…
This 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.
Quoted 8 lines
A shorthand invocation:
qemu-ga -d
Is equivalent to:
qemu-ga -c virtio-serial -p /dev/virtio-ports/org.qemu.guest_agent \ -p /var/run/qemu-guest-agent.pid -d
I think you meant -f /var/run/qemu-guest-agent.pid
Quoted 297 lines
Signed-off-by Michael Roth <[email protected]>--- Makefile | 10 +- qemu-ga.c | 651 ++++++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 4 + 3 files changed, 661 insertions(+), 4 deletions(-) create mode 100644 qemu-ga.cMakefile +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 +237
-0@@ -0,0 +1,651 @@ +/* +* QEMU Guest Agent +* +* 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 <stdlib.h> +#include <stdio.h> +#include <stdbool.h> +#include <glib.h> +#include <gio/gio.h> +#include <getopt.h> +#include <termios.h> +#include <syslog.h> +#include "qemu_socket.h" +#include "json-streamer.h" +#include "json-parser.h" +#include "qint.h" +#include "qjson.h" +#include "qga/guest-agent-core.h" +#include "module.h" +#include "signal.h" + +#define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent" +#define QGA_PIDFILE_DEFAULT "/var/run/qemu-va.pid" +#define QGA_BAUDRATE_DEFAULT B38400/* for isa-serial channels */ +#define QGA_TIMEOUT_DEFAULT 30*1000/* ms */ + +struct GAState { +JSONMessageParser parser; +GMainLoop *main_loop; +guint conn_id; +GSocket *conn_sock; +GIOChannel *conn_channel; +guint listen_id; +GSocket *listen_sock; +GIOChannel *listen_channel; +const char *path; +const char *method; +bool virtio;/* fastpath to check for virtio to deal with poll() quirks */ +GACommandState *command_state; +GLogLevelFlags log_level; +FILE *log_file; +bool logging_enabled; +}; + +static struct GAState *ga_state; + +static void quit_handler (int sig) +{ +g_debug ("recieved signal num %d, quitting" ); + +if (g_main_loop_is_running (ga_state->main_loop)) { +g_main_loop_quit (ga_state->main_loop); + } +} + +static void register_signal_handlers (void ) +{ +struct sigaction sigact; +int ret; + + sigact.sa_handler = quit_handler; + + ret =sigaction (SIGINT , &sigact,NULL ); +if (ret ==-1 ) { +g_error ("error configuring signal handler: %s" ,strerror (errno)); + } + ret =sigaction (SIGTERM , &sigact,NULL ); +if (ret ==-1 ) { +g_error ("error configuring signal handler: %s" ,strerror (errno)); + } +} + +static void usage (const char *cmd) +{ +printf ( +"Usage: %s -c <channel_opts>\n" +"QEMU Guest Agent %s\n" +"\n" +" -c, --channel channel method: one of unix-connect, virtio-serial, or\n" +" isa-serial (virtio-serial is the default)\n" +" -p, --path channel path (%s is the default for virtio-serial)\n" +" -l, --logfile set logfile path, logs to stderr by default\n" +" -f, --pidfile specify pidfile (default is %s)\n" +" -v, --verbose log extra debugging information\n" +" -V, --version print version information and exit\n" +" -d, --daemonize become a daemon\n" +" -h, --help display this help and exit\n" +"\n" +"Report bugs to <[email protected]>\n" + , cmd,QGA_VERSION ,QGA_VIRTIO_PATH_DEFAULT ,QGA_PIDFILE_DEFAULT ); +} + +static void conn_channel_close (GAState *s); + +static const char *ga_log_level_str (GLogLevelFlags level) +{ +switch (level &G_LOG_LEVEL_MASK ) { +case G_LOG_LEVEL_ERROR : +return "error" ; +case G_LOG_LEVEL_CRITICAL : +return "critical" ; +case G_LOG_LEVEL_WARNING : +return "warning" ; +case G_LOG_LEVEL_MESSAGE : +return "message" ; +case G_LOG_LEVEL_INFO : +return "info" ; +case G_LOG_LEVEL_DEBUG : +return "debug" ; +default : +return "user" ; + } +} + +bool ga_logging_enabled (GAState *s) +{ +return s->logging_enabled; +} + +void ga_disable_logging (GAState *s) +{ + s->logging_enabled = false; +} + +void ga_enable_logging (GAState *s) +{ + s->logging_enabled = true; +} + +static void ga_log (const gchar *domain,GLogLevelFlags level, +const gchar *msg,gpointer opaque) +{ +GAState *s = opaque; +GTimeVal time; +const char *level_str =ga_log_level_str (level); + +if (!ga_logging_enabled (s)) { +return ; + } + + level &=G_LOG_LEVEL_MASK ; +if (g_strcmp0 (domain,"syslog" ) ==0 ) { +syslog (LOG_INFO ,"%s: %s" , level_str, msg); + }else if (level & s->log_level) { +g_get_current_time (&time); +fprintf (s->log_file, +"%lu.%lu: %s: %s\n" , time.tv_sec, time.tv_usec, level_str, msg); +fflush (s->log_file); + } +} + +static void become_daemon (const char *pidfile) +{ +pid_t pid, sid; +int pidfd; +char *pidstr =NULL ; + + pid =fork (); +if (pid <0 ) { +exit (EXIT_FAILURE ); + } +if (pid >0 ) { +exit (EXIT_SUCCESS ); + } + + pidfd =open (pidfile,O_CREAT |O_WRONLY |O_EXCL ,S_IRUSR |S_IWUSR ); +if (pidfd ==-1 ) { +g_error ("Cannot create pid file, %s" ,strerror (errno)); + } + +if (asprintf (&pidstr,"%d" ,getpid ()) ==-1 ) { +g_critical ("Cannot allocate memory" ); + goto fail; + } +if (write (pidfd, pidstr,strlen (pidstr)) !=strlen (pidstr)) { +free (pidstr); +g_critical ("Failed to write pid file" ); + goto fail; + } + +umask (0 ); + sid =setsid (); +if (sid <0 ) { + goto fail; + } +if ((chdir ("/" )) <0 ) { + goto fail; + } + +close (STDIN_FILENO ); +close (STDOUT_FILENO ); +close (STDERR_FILENO ); +free (pidstr); +return ; + +fail: +unlink (pidfile); +g_error ("failed to daemonize" ); +} + +static int conn_channel_send_buf (GIOChannel *channel,const char *buf, +gsize count) +{ +GError *err =NULL ; +gsize written =0 ; +GIOStatus status; + +while (count) { + status =g_io_channel_write_chars (channel, buf, count, &written, &err); +g_debug ("sending data, count: %d" , (int )count); +if (err !=NULL ) { +g_warning ("error sending newline: %s" , err->message); +return err->code; + } +if (status ==G_IO_STATUS_ERROR || status ==G_IO_STATUS_EOF ) { +return -EPIPE ; + } + +if (status ==G_IO_STATUS_NORMAL ) { + count -= written; + } + } + +return 0 ; +} + +static int conn_channel_send_payload (GIOChannel *channel,QObject *payload) +{ +int ret =0 ;
qemu-ga.c line 247
Quoted 10 lines
qemu-ga.c new file +10
-0+const char *buf; +QString *payload_qstr; +GError *err =NULL ; + +g_assert (payload && channel); + + payload_qstr =qobject_to_json (payload); +if (!payload_qstr) { +return -EINVAL ; + }
You can do:
qstring_append_chr(payload_qstr, '\n');
so that you avoid the additional conn_channel_send_buf() call below.
Quoted 51 lines
qemu-ga.c new file +51
-0+ + buf =qstring_get_str (payload_qstr); + ret =conn_channel_send_buf (channel, buf,strlen (buf)); +if (ret) { + goto out_free; + } + + ret =conn_channel_send_buf (channel,"\n" ,1 ); +if (ret) { + goto out_free; + } + +g_io_channel_flush (channel, &err); +if (err !=NULL ) { +g_warning ("error flushing payload: %s" , err->message); + ret = err->code; + goto out_free; + } + +out_free: +QDECREF (payload_qstr); +if (err) { +g_error_free (err); + } +return ret; +} + +static void process_command (GAState *s,QDict *req) +{ +QObject *rsp =NULL ; +int ret; + +g_assert (req); +g_debug ("processing command" ); + rsp =qmp_dispatch (QOBJECT (req)); +if (rsp) { + ret =conn_channel_send_payload (s->conn_channel, rsp); +if (ret) { +g_warning ("error sending payload: %s" ,strerror (ret)); + } +qobject_decref (rsp); + }else { +g_warning ("error getting response" ); + } +} + +/* handle requests/control events coming in over the channel */ +static void process_event (JSONMessageParser *parser,QList *tokens) +{ +GAState *s =container_of (parser, GAState, parser); +QObject *obj;
qemu-ga.c line 308
Quoted 10 lines
qemu-ga.c new file +10
-0+QDict *qdict; +Error *err =NULL ; + +g_assert (s && parser); + +g_debug ("process_event: called" ); + obj =json_parser_parse_err (tokens,NULL , &err); +if (!obj ||qobject_type (obj) !=QTYPE_QDICT ) { +qobject_decref (obj); +g_warning ("failed to parse event" );
No error is returned to the client, is this intended?
qemu-ga.c line 314
Quoted 6 lines
qemu-ga.c new file +6
-0+return ; + } + +if (err) { +error_free (err); +g_warning ("failed to parse event: %s" ,error_get_pretty (err));
Same here.
qemu-ga.c line 325
Quoted 11 lines
qemu-ga.c new file +11
-0+return ; + } + +g_debug ("parse successful" ); + qdict =qobject_to_qdict (obj); +g_assert (qdict); + +/* handle host->guest commands */ +if (qdict_haskey (qdict,"execute" )) { +process_command (s, qdict); + }else {
And here.
Quoted 183 lines
qemu-ga.c new file +183
-0+g_warning ("unrecognized payload format, ignoring" ); + } + +QDECREF (qdict); +} + +static gboolean conn_channel_read (GIOChannel *channel,GIOCondition condition, +gpointer data) +{ +GAState *s = data; +gchar buf[1024 ]; +gsize count; +GError *err =NULL ; +memset (buf,0 ,1024 ); +GIOStatus status =g_io_channel_read_chars (channel, buf,1024 , + &count, &err); +if (err !=NULL ) { +g_warning ("error reading channel: %s" , err->message); +conn_channel_close (s); +g_error_free (err); +return false; + } +switch (status) { +case G_IO_STATUS_ERROR : +g_warning ("problem" ); +return false; +case G_IO_STATUS_NORMAL : +g_debug ("read data, count: %d, data: %s" , (int )count, buf); +json_message_parser_feed (&s->parser, (char *)buf, (int )count); +case G_IO_STATUS_AGAIN : +/* virtio causes us to spin here when no process is attached to +* host-side chardev. sleep a bit to mitigate this +*/ +if (s->virtio) { +usleep (100 *1000 ); + } +return true; +case G_IO_STATUS_EOF : +g_debug ("received EOF" ); +conn_channel_close (s); +if (s->virtio) { +return true; + } +return false; +default : +g_warning ("unknown channel read status, closing" ); +conn_channel_close (s); +return false; + } +return true; +} + +static int conn_channel_add (GAState *s,int fd) +{ +GIOChannel *conn_channel; +guint conn_id; +GError *err =NULL ; + +g_assert (s && !s->conn_channel); + conn_channel =g_io_channel_unix_new (fd); +g_assert (conn_channel); +g_io_channel_set_encoding (conn_channel,NULL , &err); +if (err !=NULL ) { +g_warning ("error setting channel encoding to binary" ); +g_error_free (err); +return -1 ; + } + conn_id =g_io_add_watch (conn_channel,G_IO_IN |G_IO_HUP , + conn_channel_read, s); +if (err !=NULL ) { +g_warning ("error adding io watch: %s" , err->message); +g_error_free (err); +return -1 ; + } + s->conn_channel = conn_channel; + s->conn_id = conn_id; +return 0 ; +} + +static gboolean listen_channel_accept (GIOChannel *channel, +GIOCondition condition,gpointer data) +{ +GAState *s = data; +GError *err =NULL ; +g_assert (channel !=NULL ); +int ret; +bool accepted = false; + + s->conn_sock =g_socket_accept (s->listen_sock,NULL , &err); +if (err !=NULL ) { +g_warning ("error converting fd to gsocket: %s" , err->message); +g_error_free (err); + goto out; + } + ret =conn_channel_add (s,g_socket_get_fd (s->conn_sock)); +if (ret) { +g_warning ("error setting up connection" ); + goto out; + } + accepted = true; + +out: +/* only accept 1 connection at a time */ +return !accepted; +} + +/* start polling for readable events on listen fd, new==true +* indicates we should use the existing s->listen_channel +*/ +static int listen_channel_add (GAState *s,int listen_fd,bool new) +{ +GError *err =NULL ; +guint listen_id; + +if (new) { + s->listen_channel =g_io_channel_unix_new (listen_fd); +if (s->listen_sock) { +g_object_unref (s->listen_sock); + } + s->listen_sock =g_socket_new_from_fd (listen_fd, &err); +if (err !=NULL ) { +g_warning ("error converting fd to gsocket: %s" , err->message); +g_error_free (err); +return -1 ; + } + } + listen_id =g_io_add_watch (s->listen_channel,G_IO_IN , + listen_channel_accept, s); +if (err !=NULL ) { +g_warning ("error adding io watch: %s" , err->message); +g_error_free (err); +return -1 ; + } +return 0 ; +} + +/* cleanup state for closed connection/session, start accepting new +* connections if we're in listening mode +*/ +static void conn_channel_close (GAState *s) +{ +if (strcmp (s->method,"unix-listen" ) ==0 ) { +g_io_channel_shutdown (s->conn_channel, true,NULL ); +g_object_unref (s->conn_sock); + s->conn_sock =NULL ; +listen_channel_add (s,0 , false); + }else if (strcmp (s->method,"virtio-serial" ) ==0 ) { +/* we spin on EOF for virtio-serial, so back off a bit. also, +* dont close the connection in this case, it'll resume normal +* operation when another process connects to host chardev +*/ +usleep (100 *1000 ); + goto out_noclose; + } +g_io_channel_unref (s->conn_channel); + s->conn_channel =NULL ; + s->conn_id =0 ; +out_noclose: +return ; +} + +static void init_guest_agent (GAState *s) +{ +struct termios tio; +int ret, fd; + +if (s->method ==NULL ) { +/* try virtio-serial as our default */ + s->method ="virtio-serial" ; + } + +if (s->path ==NULL ) { +if (strcmp (s->method,"virtio-serial" ) !=0 ) { +g_error ("must specify a path for this channel" ); + } +/* try the default path for the virtio-serial port */ + s->path =QGA_VIRTIO_PATH_DEFAULT ; + } + +if (strcmp (s->method,"virtio-serial" ) ==0 ) { + s->virtio = true; + fd =qemu_open (s->path,O_RDWR ); +if (fd ==-1 ) {
qemu-ga.c line 518
Quoted 10 lines
qemu-ga.c new file +10
-0+g_error ("error opening channel: %s" ,strerror (errno)); + } + ret =fcntl (fd,F_GETFL ); +if (ret <0 ) { +g_error ("error getting channel flags: %s" ,strerror (errno)); + } + ret =fcntl (fd,F_SETFL , ret |O_NONBLOCK |O_ASYNC ); +if (ret <0 ) { +g_error ("error setting channel flags: %s" ,strerror (errno)); + }
Can't O_NONBLOCK and O_ASYNC be set as open() flags?
Quoted 41 lines
qemu-ga.c new file +41
-0+ ret =conn_channel_add (s, fd); +if (ret) { +g_error ("error adding channel to main loop" ); + } + }else if (strcmp (s->method,"isa-serial" ) ==0 ) { + fd =qemu_open (s->path,O_RDWR |O_NOCTTY ); +if (fd ==-1 ) { +g_error ("error opening channel: %s" ,strerror (errno)); + } +tcgetattr (fd, &tio); +/* set up serial port for non-canonical, dumb byte streaming */ + tio.c_iflag &= ~(IGNBRK |BRKINT |IGNPAR |PARMRK |INPCK |ISTRIP | +INLCR |IGNCR |ICRNL |IXON |IXOFF |IXANY | +IMAXBEL ); + tio.c_oflag =0 ; + tio.c_lflag =0 ; + tio.c_cflag |=QGA_BAUDRATE_DEFAULT ; +/* 1 available byte min or reads will block (we'll set non-blocking +* elsewhere, else we have to deal with read()=0 instead) +*/ + tio.c_cc[VMIN ] =1 ; + tio.c_cc[VTIME ] =0 ; +/* flush everything waiting for read/xmit, it's garbage at this point */ +tcflush (fd,TCIFLUSH ); +tcsetattr (fd,TCSANOW , &tio); + ret =conn_channel_add (s, fd); +if (ret) { +g_error ("error adding channel to main loop" ); + } + }else if (strcmp (s->method,"unix-listen" ) ==0 ) { + fd =unix_listen (s->path,NULL ,strlen (s->path)); +if (fd ==-1 ) { +g_error ("error opening path: %s" ,strerror (errno)); + } + ret =listen_channel_add (s, fd, true); +if (ret) { +g_error ("error binding/listening to specified socket" ); + } + }else { +g_error ("unsupported channel method/type: %s" , s->method); + }
qemu-ga.c line 569
Quoted 10 lines
qemu-ga.c new file +10
-0+ +json_message_parser_init (&s->parser, process_event); + s->main_loop =g_main_loop_new (NULL , false); +} + +int main (int argc,char **argv) +{ +const char *sopt ="hVvdc:p:l:f:" ; +const char *method =NULL , *path =NULL , *pidfile =QGA_PIDFILE_DEFAULT ; +struct option lopt[] = {
Can be const.
Quoted 9 lines
qemu-ga.c new file +9
-0+ { "help", 0, NULL, 'h' }, + { "version", 0, NULL, 'V' }, + { "logfile", 0, NULL, 'l' }, + { "pidfile", 0, NULL, 'f' }, + { "verbose", 0, NULL, 'v' }, + { "channel", 0, NULL, 'c' }, + { "path", 0, NULL, 'p' }, + { "daemonize", 0, NULL, 'd' }, + { NULL, 0, NULL, 0 }
qemu-ga.c line 588
Quoted 10 lines
qemu-ga.c new file +10
-0+ }; +int opt_ind =0 , ch, daemonize =0 ; +GLogLevelFlags log_level =G_LOG_LEVEL_ERROR |G_LOG_LEVEL_CRITICAL ; +FILE *log_file = stderr; +GAState *s; + +while ((ch =getopt_long (argc, argv, sopt, lopt, &opt_ind)) !=-1 ) { +switch (ch) { +case 'c' : + method = optarg;
Why don't you call this option 'm' ('method') then?
Quoted 20 lines
qemu-ga.c new file +20
-0+break ; +case 'p' : + path = optarg; +break ; +case 'l' : + log_file =fopen (optarg,"a" ); +if (!log_file) { +g_error ("unable to open specified log file: %s" , +strerror (errno)); + } +break ; +case 'f' : + pidfile = optarg; +break ; +case 'v' : +/* enable all log levels */ + log_level =G_LOG_LEVEL_MASK ; +break ; +case 'V' : +printf ("QEMU Guest Agent %s\n" ,QGA_VERSION );
qemu-ga.c line 618
Quoted 10 lines
qemu-ga.c new file +10
-0+return 0 ; +case 'd' : + daemonize =1 ; +break ; +case 'h' : +usage (argv[0 ]); +return 0 ; +case '?' : +g_error ("Unknown option, try '%s --help' for more information." , + argv[0 ]);
g_error() documentation from:
http://developer.gnome.org/glib/2.29/glib-Message-Logging.html#g-error
Says:
"This function will result in a core dump; don't use it for errors you expect.
Using this function indicates a bug in your program, i.e. an assertion failure."
But I see it's being used beyond assertions.
Quoted 52 lines
qemu-ga.c new file +33
-0+ } + } + +if (daemonize) { +g_debug ("starting daemon" ); +become_daemon (pidfile); + } + +g_type_init (); +g_thread_init (NULL ); + + s =qemu_mallocz (sizeof (GAState)); + s->conn_id =0 ; + s->conn_channel =NULL ; + s->path = path; + s->method = method; + s->log_file = log_file; + s->log_level = log_level; +g_log_set_default_handler (ga_log, s); +g_log_set_fatal_mask (NULL ,G_LOG_LEVEL_ERROR ); + s->logging_enabled = true; + ga_state = s; + +module_call_init (MODULE_INIT_QAPI ); +init_guest_agent (ga_state); +register_signal_handlers (); + +g_main_loop_run (ga_state->main_loop); + +unlink (pidfile); + +return 0 ; +}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);
Re: [Qemu-devel] [PATCH v6 2/4] guest agent: qemu-ga daemon
Quoted 10 lines · Luiz Capitulino
Quoted 7 lines · On Tue, 5 Jul 2011 08:21:38 -0500 Michael Roth<[email protected]>…
This 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:
Quoted 9 lines
Quoted 6 lines
qemu-ga -d
Is equivalent to:
qemu-ga -c virtio-serial -p /dev/virtio-ports/org.qemu.guest_agent \ -p /var/run/qemu-guest-agent.pid -dI think you meant -f
/var/run/qemu-guest-agent.pid
Yup, sorry.
Quoted 310 lines
Quoted 297 lines
Signed-off-by Michael Roth<[email protected]>--- Makefile | 10 +- qemu-ga.c | 651 ++++++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 4 + 3 files changed, 661 insertions(+), 4 deletions(-)create mode 100644
qemu-ga.cMakefile +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 +237
-0@@ -0,0 +1,651 @@ +/* +* QEMU Guest Agent +* +* 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 <stdlib.h> +#include <stdio.h> +#include <stdbool.h> +#include <glib.h> +#include <gio/gio.h> +#include <getopt.h> +#include <termios.h> +#include <syslog.h> +#include "qemu_socket.h" +#include "json-streamer.h" +#include "json-parser.h" +#include "qint.h" +#include "qjson.h" +#include "qga/guest-agent-core.h" +#include "module.h" +#include "signal.h" + +#define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent" +#define QGA_PIDFILE_DEFAULT "/var/run/qemu-va.pid" +#define QGA_BAUDRATE_DEFAULT B38400/* for isa-serial channels */ +#define QGA_TIMEOUT_DEFAULT 30*1000/* ms */ + +struct GAState { +JSONMessageParser parser; +GMainLoop *main_loop; +guint conn_id; +GSocket *conn_sock; +GIOChannel *conn_channel; +guint listen_id; +GSocket *listen_sock; +GIOChannel *listen_channel; +const char *path; +const char *method; +bool virtio;/* fastpath to check for virtio to deal with poll() quirks */ +GACommandState *command_state; +GLogLevelFlags log_level; +FILE *log_file; +bool logging_enabled; +}; + +static struct GAState *ga_state; + +static void quit_handler (int sig) +{ +g_debug ("recieved signal num %d, quitting" ); + +if (g_main_loop_is_running (ga_state->main_loop)) { +g_main_loop_quit (ga_state->main_loop); + } +} + +static void register_signal_handlers (void ) +{ +struct sigaction sigact; +int ret; + + sigact.sa_handler = quit_handler; + + ret =sigaction (SIGINT ,&sigact,NULL ); +if (ret ==-1 ) { +g_error ("error configuring signal handler: %s" ,strerror (errno)); + } + ret =sigaction (SIGTERM ,&sigact,NULL ); +if (ret ==-1 ) { +g_error ("error configuring signal handler: %s" ,strerror (errno)); + } +} + +static void usage (const char *cmd) +{ +printf ( +"Usage: %s -c<channel_opts>\n" +"QEMU Guest Agent %s\n" +"\n" +" -c, --channel channel method: one of unix-connect, virtio-serial, or\n" +" isa-serial (virtio-serial is the default)\n" +" -p, --path channel path (%s is the default for virtio-serial)\n" +" -l, --logfile set logfile path, logs to stderr by default\n" +" -f, --pidfile specify pidfile (default is %s)\n" +" -v, --verbose log extra debugging information\n" +" -V, --version print version information and exit\n" +" -d, --daemonize become a daemon\n" +" -h, --help display this help and exit\n" +"\n" +"Report bugs to<[email protected]>\n" + , cmd,QGA_VERSION ,QGA_VIRTIO_PATH_DEFAULT ,QGA_PIDFILE_DEFAULT ); +} + +static void conn_channel_close (GAState *s); + +static const char *ga_log_level_str (GLogLevelFlags level) +{ +switch (level&G_LOG_LEVEL_MASK ) { +case G_LOG_LEVEL_ERROR : +return "error" ; +case G_LOG_LEVEL_CRITICAL : +return "critical" ; +case G_LOG_LEVEL_WARNING : +return "warning" ; +case G_LOG_LEVEL_MESSAGE : +return "message" ; +case G_LOG_LEVEL_INFO : +return "info" ; +case G_LOG_LEVEL_DEBUG : +return "debug" ; +default : +return "user" ; + } +} + +bool ga_logging_enabled (GAState *s) +{ +return s->logging_enabled; +} + +void ga_disable_logging (GAState *s) +{ + s->logging_enabled = false; +} + +void ga_enable_logging (GAState *s) +{ + s->logging_enabled = true; +} + +static void ga_log (const gchar *domain,GLogLevelFlags level, +const gchar *msg,gpointer opaque) +{ +GAState *s = opaque; +GTimeVal time; +const char *level_str =ga_log_level_str (level); + +if (!ga_logging_enabled (s)) { +return ; + } + + level&=G_LOG_LEVEL_MASK ; +if (g_strcmp0 (domain,"syslog" ) ==0 ) { +syslog (LOG_INFO ,"%s: %s" , level_str, msg); + }else if (level& s->log_level) { +g_get_current_time (&time); +fprintf (s->log_file, +"%lu.%lu: %s: %s\n" , time.tv_sec, time.tv_usec, level_str, msg); +fflush (s->log_file); + } +} + +static void become_daemon (const char *pidfile) +{ +pid_t pid, sid; +int pidfd; +char *pidstr =NULL ; + + pid =fork (); +if (pid<0 ) { +exit (EXIT_FAILURE ); + } +if (pid>0 ) { +exit (EXIT_SUCCESS ); + } + + pidfd =open (pidfile,O_CREAT |O_WRONLY |O_EXCL ,S_IRUSR |S_IWUSR ); +if (pidfd ==-1 ) { +g_error ("Cannot create pid file, %s" ,strerror (errno)); + } + +if (asprintf (&pidstr,"%d" ,getpid ()) ==-1 ) { +g_critical ("Cannot allocate memory" ); + goto fail; + } +if (write (pidfd, pidstr,strlen (pidstr)) !=strlen (pidstr)) { +free (pidstr); +g_critical ("Failed to write pid file" ); + goto fail; + } + +umask (0 ); + sid =setsid (); +if (sid<0 ) { + goto fail; + } +if ((chdir ("/" ))<0 ) { + goto fail; + } + +close (STDIN_FILENO ); +close (STDOUT_FILENO ); +close (STDERR_FILENO ); +free (pidstr); +return ; + +fail: +unlink (pidfile); +g_error ("failed to daemonize" ); +} + +static int conn_channel_send_buf (GIOChannel *channel,const char *buf, +gsize count) +{ +GError *err =NULL ; +gsize written =0 ; +GIOStatus status; + +while (count) { + status =g_io_channel_write_chars (channel, buf, count,&written,&err); +g_debug ("sending data, count: %d" , (int )count); +if (err !=NULL ) { +g_warning ("error sending newline: %s" , err->message); +return err->code; + } +if (status ==G_IO_STATUS_ERROR || status ==G_IO_STATUS_EOF ) { +return -EPIPE ; + } + +if (status ==G_IO_STATUS_NORMAL ) { + count -= written; + } + } + +return 0 ; +} + +static int conn_channel_send_payload (GIOChannel *channel,QObject *payload) +{ +int ret =0 ;qemu-ga.c line 247
Quoted 10 lines
qemu-ga.c new file +10
-0+const char *buf; +QString *payload_qstr; +GError *err =NULL ; + +g_assert (payload&& channel); + + payload_qstr =qobject_to_json (payload); +if (!payload_qstr) { +return -EINVAL ; + }You can do:
Quoted 4 lines
qstring_append_chr(payload_qstr, '\n');so that you avoid the additional
conn_channel_send_buf()call below.
Nice!
Quoted 55 lines
Quoted 55 lines
qemu-ga.c new file +55
-0+ + buf =qstring_get_str (payload_qstr); + ret =conn_channel_send_buf (channel, buf,strlen (buf)); +if (ret) { + goto out_free; + } + + ret =conn_channel_send_buf (channel,"\n" ,1 ); +if (ret) { + goto out_free; + } + +g_io_channel_flush (channel,&err); +if (err !=NULL ) { +g_warning ("error flushing payload: %s" , err->message); + ret = err->code; + goto out_free; + } + +out_free: +QDECREF (payload_qstr); +if (err) { +g_error_free (err); + } +return ret; +} + +static void process_command (GAState *s,QDict *req) +{ +QObject *rsp =NULL ; +int ret; + +g_assert (req); +g_debug ("processing command" ); + rsp =qmp_dispatch (QOBJECT (req)); +if (rsp) { + ret =conn_channel_send_payload (s->conn_channel, rsp); +if (ret) { +g_warning ("error sending payload: %s" ,strerror (ret)); + } +qobject_decref (rsp); + }else { +g_warning ("error getting response" ); + } +} + +/* handle requests/control events coming in over the channel */ +static void process_event (JSONMessageParser *parser,QList *tokens) +{ +GAState *s =container_of (parser, GAState, parser); +QObject *obj; +QDict *qdict; +Error *err =NULL ; + +g_assert (s&& parser);
Quoted 9 lines
qemu-ga.c line 308
Quoted 6 lines
qemu-ga.c new file +6
-0+ +g_debug ("process_event: called" ); + obj =json_parser_parse_err (tokens,NULL ,&err); +if (!obj ||qobject_type (obj) !=QTYPE_QDICT ) { +qobject_decref (obj); +g_warning ("failed to parse event" );No error is returned to the client, is this intended?
Hmm, nope... originally the errors got rolled into the response in qmp_dispatch(). But when I reworked qmp_dispatch() to take a pre-parsed QDict instead of a token list this functionality was lost..
Which makes me wonder if I should move the parsing back into qmp_dispatch()... I'll take a look. But yah, these errors should get returned.
Quoted 293 lines
qemu-ga.c line 314
Quoted 6 lines
qemu-ga.c new file +6
-0+return ; + } + +if (err) { +error_free (err); +g_warning ("failed to parse event: %s" ,error_get_pretty (err));Same here.
qemu-ga.c line 325
Quoted 11 lines
qemu-ga.c new file +11
-0+return ; + } + +g_debug ("parse successful" ); + qdict =qobject_to_qdict (obj); +g_assert (qdict); + +/* handle host->guest commands */ +if (qdict_haskey (qdict,"execute" )) { +process_command (s, qdict); + }else {And here.
Quoted 183 lines
qemu-ga.c new file +183
-0+g_warning ("unrecognized payload format, ignoring" ); + } + +QDECREF (qdict); +} + +static gboolean conn_channel_read (GIOChannel *channel,GIOCondition condition, +gpointer data) +{ +GAState *s = data; +gchar buf[1024 ]; +gsize count; +GError *err =NULL ; +memset (buf,0 ,1024 ); +GIOStatus status =g_io_channel_read_chars (channel, buf,1024 , +&count,&err); +if (err !=NULL ) { +g_warning ("error reading channel: %s" , err->message); +conn_channel_close (s); +g_error_free (err); +return false; + } +switch (status) { +case G_IO_STATUS_ERROR : +g_warning ("problem" ); +return false; +case G_IO_STATUS_NORMAL : +g_debug ("read data, count: %d, data: %s" , (int )count, buf); +json_message_parser_feed (&s->parser, (char *)buf, (int )count); +case G_IO_STATUS_AGAIN : +/* virtio causes us to spin here when no process is attached to +* host-side chardev. sleep a bit to mitigate this +*/ +if (s->virtio) { +usleep (100 *1000 ); + } +return true; +case G_IO_STATUS_EOF : +g_debug ("received EOF" ); +conn_channel_close (s); +if (s->virtio) { +return true; + } +return false; +default : +g_warning ("unknown channel read status, closing" ); +conn_channel_close (s); +return false; + } +return true; +} + +static int conn_channel_add (GAState *s,int fd) +{ +GIOChannel *conn_channel; +guint conn_id; +GError *err =NULL ; + +g_assert (s&& !s->conn_channel); + conn_channel =g_io_channel_unix_new (fd); +g_assert (conn_channel); +g_io_channel_set_encoding (conn_channel,NULL ,&err); +if (err !=NULL ) { +g_warning ("error setting channel encoding to binary" ); +g_error_free (err); +return -1 ; + } + conn_id =g_io_add_watch (conn_channel,G_IO_IN |G_IO_HUP , + conn_channel_read, s); +if (err !=NULL ) { +g_warning ("error adding io watch: %s" , err->message); +g_error_free (err); +return -1 ; + } + s->conn_channel = conn_channel; + s->conn_id = conn_id; +return 0 ; +} + +static gboolean listen_channel_accept (GIOChannel *channel, +GIOCondition condition,gpointer data) +{ +GAState *s = data; +GError *err =NULL ; +g_assert (channel !=NULL ); +int ret; +bool accepted = false; + + s->conn_sock =g_socket_accept (s->listen_sock,NULL ,&err); +if (err !=NULL ) { +g_warning ("error converting fd to gsocket: %s" , err->message); +g_error_free (err); + goto out; + } + ret =conn_channel_add (s,g_socket_get_fd (s->conn_sock)); +if (ret) { +g_warning ("error setting up connection" ); + goto out; + } + accepted = true; + +out: +/* only accept 1 connection at a time */ +return !accepted; +} + +/* start polling for readable events on listen fd, new==true +* indicates we should use the existing s->listen_channel +*/ +static int listen_channel_add (GAState *s,int listen_fd,bool new) +{ +GError *err =NULL ; +guint listen_id; + +if (new) { + s->listen_channel =g_io_channel_unix_new (listen_fd); +if (s->listen_sock) { +g_object_unref (s->listen_sock); + } + s->listen_sock =g_socket_new_from_fd (listen_fd,&err); +if (err !=NULL ) { +g_warning ("error converting fd to gsocket: %s" , err->message); +g_error_free (err); +return -1 ; + } + } + listen_id =g_io_add_watch (s->listen_channel,G_IO_IN , + listen_channel_accept, s); +if (err !=NULL ) { +g_warning ("error adding io watch: %s" , err->message); +g_error_free (err); +return -1 ; + } +return 0 ; +} + +/* cleanup state for closed connection/session, start accepting new +* connections if we're in listening mode +*/ +static void conn_channel_close (GAState *s) +{ +if (strcmp (s->method,"unix-listen" ) ==0 ) { +g_io_channel_shutdown (s->conn_channel, true,NULL ); +g_object_unref (s->conn_sock); + s->conn_sock =NULL ; +listen_channel_add (s,0 , false); + }else if (strcmp (s->method,"virtio-serial" ) ==0 ) { +/* we spin on EOF for virtio-serial, so back off a bit. also, +* dont close the connection in this case, it'll resume normal +* operation when another process connects to host chardev +*/ +usleep (100 *1000 ); + goto out_noclose; + } +g_io_channel_unref (s->conn_channel); + s->conn_channel =NULL ; + s->conn_id =0 ; +out_noclose: +return ; +} + +static void init_guest_agent (GAState *s) +{ +struct termios tio; +int ret, fd; + +if (s->method ==NULL ) { +/* try virtio-serial as our default */ + s->method ="virtio-serial" ; + } + +if (s->path ==NULL ) { +if (strcmp (s->method,"virtio-serial" ) !=0 ) { +g_error ("must specify a path for this channel" ); + } +/* try the default path for the virtio-serial port */ + s->path =QGA_VIRTIO_PATH_DEFAULT ; + } + +if (strcmp (s->method,"virtio-serial" ) ==0 ) { + s->virtio = true; + fd =qemu_open (s->path,O_RDWR ); +if (fd ==-1 ) {qemu-ga.c line 518
Quoted 10 lines
qemu-ga.c new file +10
-0+g_error ("error opening channel: %s" ,strerror (errno)); + } + ret =fcntl (fd,F_GETFL ); +if (ret<0 ) { +g_error ("error getting channel flags: %s" ,strerror (errno)); + } + ret =fcntl (fd,F_SETFL , ret |O_NONBLOCK |O_ASYNC ); +if (ret<0 ) { +g_error ("error setting channel flags: %s" ,strerror (errno)); + }Can't
O_NONBLOCKandO_ASYNCbe set asopen()flags?Quoted 41 lines
qemu-ga.c new file +41
-0+ ret =conn_channel_add (s, fd); +if (ret) { +g_error ("error adding channel to main loop" ); + } + }else if (strcmp (s->method,"isa-serial" ) ==0 ) { + fd =qemu_open (s->path,O_RDWR |O_NOCTTY ); +if (fd ==-1 ) { +g_error ("error opening channel: %s" ,strerror (errno)); + } +tcgetattr (fd,&tio); +/* set up serial port for non-canonical, dumb byte streaming */ + tio.c_iflag&= ~(IGNBRK |BRKINT |IGNPAR |PARMRK |INPCK |ISTRIP | +INLCR |IGNCR |ICRNL |IXON |IXOFF |IXANY | +IMAXBEL ); + tio.c_oflag =0 ; + tio.c_lflag =0 ; + tio.c_cflag |=QGA_BAUDRATE_DEFAULT ; +/* 1 available byte min or reads will block (we'll set non-blocking +* elsewhere, else we have to deal with read()=0 instead) +*/ + tio.c_cc[VMIN ] =1 ; + tio.c_cc[VTIME ] =0 ; +/* flush everything waiting for read/xmit, it's garbage at this point */ +tcflush (fd,TCIFLUSH ); +tcsetattr (fd,TCSANOW ,&tio); + ret =conn_channel_add (s, fd); +if (ret) { +g_error ("error adding channel to main loop" ); + } + }else if (strcmp (s->method,"unix-listen" ) ==0 ) { + fd =unix_listen (s->path,NULL ,strlen (s->path)); +if (fd ==-1 ) { +g_error ("error opening path: %s" ,strerror (errno)); + } + ret =listen_channel_add (s, fd, true); +if (ret) { +g_error ("error binding/listening to specified socket" ); + } + }else { +g_error ("unsupported channel method/type: %s" , s->method); + }qemu-ga.c line 569
Quoted 10 lines
qemu-ga.c new file +10
-0+ +json_message_parser_init (&s->parser, process_event); + s->main_loop =g_main_loop_new (NULL , false); +} + +int main (int argc,char **argv) +{ +const char *sopt ="hVvdc:p:l:f:" ; +const char *method =NULL , *path =NULL , *pidfile =QGA_PIDFILE_DEFAULT ; +struct option lopt[] = {Can be const.
Quoted 9 lines
qemu-ga.c new file +9
-0+ { "help", 0, NULL, 'h' }, + { "version", 0, NULL, 'V' }, + { "logfile", 0, NULL, 'l' }, + { "pidfile", 0, NULL, 'f' }, + { "verbose", 0, NULL, 'v' }, + { "channel", 0, NULL, 'c' }, + { "path", 0, NULL, 'p' }, + { "daemonize", 0, NULL, 'd' }, + { NULL, 0, NULL, 0 }qemu-ga.c line 588
Quoted 10 lines
qemu-ga.c new file +10
-0+ }; +int opt_ind =0 , ch, daemonize =0 ; +GLogLevelFlags log_level =G_LOG_LEVEL_ERROR |G_LOG_LEVEL_CRITICAL ; +FILE *log_file = stderr; +GAState *s; + +while ((ch =getopt_long (argc, argv, sopt, lopt,&opt_ind)) !=-1 ) { +switch (ch) { +case 'c' : + method = optarg;
Quoted 2 lines
Why don't you call this option 'm' ('method') then?
That's probably better.
Quoted 33 lines
Quoted 20 lines
qemu-ga.c new file +20
-0+break ; +case 'p' : + path = optarg; +break ; +case 'l' : + log_file =fopen (optarg,"a" ); +if (!log_file) { +g_error ("unable to open specified log file: %s" , +strerror (errno)); + } +break ; +case 'f' : + pidfile = optarg; +break ; +case 'v' : +/* enable all log levels */ + log_level =G_LOG_LEVEL_MASK ; +break ; +case 'V' : +printf ("QEMU Guest Agent %s\n" ,QGA_VERSION );qemu-ga.c line 618
Quoted 10 lines
qemu-ga.c new file +10
-0+return 0 ; +case 'd' : + daemonize =1 ; +break ; +case 'h' : +usage (argv[0 ]); +return 0 ; +case '?' : +g_error ("Unknown option, try '%s --help' for more information." , + argv[0 ]);
g_error()documentation from:
Quoted 9 lines
http://developer.gnome.org/glib/2.29/glib-Message-Logging.html#g-error
Says:
"This function will result in a core dump; don't use it for errors you expect.
Using this function indicates a bug in your program, i.e. an assertion failure."But I see it's being used beyond assertions.
I've been using it to bail on unrecoverable error states. Might be a bit extreme for unknown options though.
Quoted 53 lines
Quoted 52 lines
qemu-ga.c new file +33
-0+ } + } + +if (daemonize) { +g_debug ("starting daemon" ); +become_daemon (pidfile); + } + +g_type_init (); +g_thread_init (NULL ); + + s =qemu_mallocz (sizeof (GAState)); + s->conn_id =0 ; + s->conn_channel =NULL ; + s->path = path; + s->method = method; + s->log_file = log_file; + s->log_level = log_level; +g_log_set_default_handler (ga_log, s); +g_log_set_fatal_mask (NULL ,G_LOG_LEVEL_ERROR ); + s->logging_enabled = true; + ga_state = s; + +module_call_init (MODULE_INIT_QAPI ); +init_guest_agent (ga_state); +register_signal_handlers (); + +g_main_loop_run (ga_state->main_loop); + +unlink (pidfile); + +return 0 ; +}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);
PATCH v6 3/4 guest agent: add guest agent commands schema file
In reply to Michael Roth--- qapi-schema-guest.json | 204 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 204 insertions(+), 0 deletions(-) create mode 100644 qapi-schema-guest.json
qapi-schema-guest.json new file +204 -0
@@ -0,0 +1,204 @@ +# *-*- 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: +# +# 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: "halt", "powerdown", or "reboot" +# +# 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. +# If @filepath cannot be opened, OpenFileFailed +# +# Since: 0.15.0 +## +{ 'command': 'guest-file-open', + 'data': { 'filepath': 'str', '*mode': 'str' }, + 'returns': 'int' } + +## +# @guest-file-read: +# +# Read from an open file in the guest +# +# @filehandle: filehandle returned by guest-file-open +# +# @count: maximum number of bytes to read +# +# Returns: GuestFileRead on success. +# If @filehandle is not open, OpenFileFailed +# +# Since: 0.15.0 +## +{ 'type': 'GuestFileRead', + 'data': { 'count': 'int', 'buf': 'str', 'eof': 'bool' } } + +{ 'command': 'guest-file-read', + 'data': { 'filehandle': 'int', 'count': 'int' }, + 'returns': 'GuestFileRead' } + +## +# @guest-file-write: +# +# Write to an open file in the guest +# +# @filehandle: filehandle returned by guest-file-open +# +# @data_b64: base64-encoded string representing data to be written +# +# @count: bytes to write (actual bytes, after b64-decode) +# +# Returns: GuestFileWrite on success. +# If @filehandle is not opened, OpenFileFailed +# +# Since: 0.15.0 +## +{ 'type': 'GuestFileWrite', + 'data': { 'count': 'int', 'eof': 'bool' } } +{ 'command': 'guest-file-write', + 'data': { 'filehandle': 'int', 'data_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. +# +# @filehandle: 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. +# If @filehandle is not opened, OpenFileFailed +# +# Since: 0.15.0 +## +{ 'type': 'GuestFileSeek', + 'data': { 'position': 'int', 'eof': 'bool' } } + +{ 'command': 'guest-file-seek', + 'data': { 'filehandle': 'int', 'offset': 'int', 'whence': 'int' }, + 'returns': 'GuestFileSeek' } + +## +# @guest-file-close: +# +# Close an open file in the guest +# +# @filehandle: filehandle returned by guest-file-open +# +# Returns: Nothing on success. +# If @filehandle is not opened, OpenFileFailed +# +# Since: 0.15.0 +## +{ 'command': 'guest-file-close', + 'data': { 'filehandle': 'int' } } + +## +# @guest-fsfreeze-status: +# +# get guest fsfreeze state +# +# Returns: GuestFsfreezeStatus (enumeration starts at 1) +# +# Since: 0.15.0 +## +{ 'enum': 'GuestFsfreezeStatus', + 'data': [ 'thawed', 'inprogress', 'frozen', 'error' ] } +{ 'command': 'guest-fsfreeze-status', + 'returns': 'GuestFsfreezeStatus' } + +## +# @guest-fsfreeze-freeze: +# +# Sync and freeze all non-network guest filesystems +# +# Returns: Number of file systems frozen +# If error, -1 (unknown error) or -errno +# +# 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' }
Signature · 1 line
1.7.0.4
Re: [Qemu-devel] [PATCH v6 3/4] guest agent: add guest agent commands schema file
Quoted 6 lines · On Tue, 5 Jul 2011 08:21:39 -0500 Michael Roth <[email protected]>…
Signed-off-by Michael Roth <[email protected]>--- qapi-schema-guest.json | 204 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 204 insertions(+), 0 deletions(-) create mode 100644 qapi-schema-guest.json
I think this should be folded in the next patch.
More comments below.
Quoted 60 lines
qapi-schema-guest.json new file +53
-0@@ -0,0 +1,204 @@ +# *-*- 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: +# +# Initiate guest-activated shutdown. Note: this is an asynchronous
qapi-schema-guest.json line 63
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+# shutdown request, with no guaruntee of successful shutdown. Errors +# will be logged to guest's syslog. +# +# @mode: "halt", "powerdown", or "reboot" +# +# Returns: Nothing on success +# +# Since: 0.15.0 +## +{ 'command': 'guest-shutdown', 'data': { 'mode': 'str' } }
Shouldn't 'mode' be optional?
Quoted 8 lines
qapi-schema-guest.json new file +8
-0+ +## +# @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. +#
qapi-schema-guest.json line 81
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+# @mode: #optional open mode, as per fopen(), "r" is the default. +# +# Returns: Guest file handle on success. +# If @filepath cannot be opened, OpenFileFailed +# +# Since: 0.15.0 +## +{ 'command': 'guest-file-open', + 'data': { 'filepath': 'str', '*mode': 'str' }, + 'returns': 'int' }
You can use 'file-path'. Actually, I'd use just 'path'.
Quoted 11 lines
qapi-schema-guest.json new file +11
-0+ +## +# @guest-file-read: +# +# Read from an open file in the guest +# +# @filehandle: filehandle returned by guest-file-open +# +# @count: maximum number of bytes to read +# +# Returns: GuestFileRead on success.
qapi-schema-guest.json line 102
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+# If @filehandle is not open, OpenFileFailed +# +# Since: 0.15.0 +## +{ 'type': 'GuestFileRead', + 'data': { 'count': 'int', 'buf': 'str', 'eof': 'bool' } } + +{ 'command': 'guest-file-read', + 'data': { 'filehandle': 'int', 'count': 'int' }, + 'returns': 'GuestFileRead' }
file-handle. Also, we have to say that the returned data is base64-encoded.
Quoted 12 lines
qapi-schema-guest.json new file +12
-0+ +## +# @guest-file-write: +# +# Write to an open file in the guest +# +# @filehandle: filehandle returned by guest-file-open +# +# @data_b64: base64-encoded string representing data to be written +# +# @count: bytes to write (actual bytes, after b64-decode) +#
qapi-schema-guest.json line 124
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+# Returns: GuestFileWrite on success. +# If @filehandle is not opened, OpenFileFailed +# +# Since: 0.15.0 +## +{ 'type': 'GuestFileWrite', + 'data': { 'count': 'int', 'eof': 'bool' } } +{ 'command': 'guest-file-write', + 'data': { 'filehandle': 'int', 'data_b64': 'str', 'count': 'int' }, + 'returns': 'GuestFileWrite' }
data-b64
Quoted 44 lines
qapi-schema-guest.json new file +44
-0+ +## +# @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. +# +# @filehandle: 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. +# If @filehandle is not opened, OpenFileFailed +# +# Since: 0.15.0 +## +{ 'type': 'GuestFileSeek', + 'data': { 'position': 'int', 'eof': 'bool' } } + +{ 'command': 'guest-file-seek', + 'data': { 'filehandle': 'int', 'offset': 'int', 'whence': 'int' }, + 'returns': 'GuestFileSeek' } + +## +# @guest-file-close: +# +# Close an open file in the guest +# +# @filehandle: filehandle returned by guest-file-open +# +# Returns: Nothing on success. +# If @filehandle is not opened, OpenFileFailed +# +# Since: 0.15.0 +## +{ 'command': 'guest-file-close', + 'data': { 'filehandle': 'int' } } + +## +# @guest-fsfreeze-status: +#
qapi-schema-guest.json line 178
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+# get guest fsfreeze state +# +# Returns: GuestFsfreezeStatus (enumeration starts at 1) +# +# Since: 0.15.0 +## +{ 'enum': 'GuestFsfreezeStatus', + 'data': [ 'thawed', 'inprogress', 'frozen', 'error' ] } +{ 'command': 'guest-fsfreeze-status', + 'returns': 'GuestFsfreezeStatus' }
hmm, I thought a qapi command implementation would return an enum (ie. int), but the qapi would translate it to a string and return the string to the client. However, this returns an int (as explained above).
Did I misunderstand how the qapi handles enums then?
Quoted 26 lines
qapi-schema-guest.json new file +26
-0+ +## +# @guest-fsfreeze-freeze: +# +# Sync and freeze all non-network guest filesystems +# +# Returns: Number of file systems frozen +# If error, -1 (unknown error) or -errno +# +# 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' }
Re: [Qemu-devel] [PATCH v6 3/4] guest agent: add guest agent commands schema file
Quoted 216 lines · Luiz Capitulino
Quoted 6 lines · On Tue, 5 Jul 2011 08:21:39 -0500 Michael Roth<[email protected]>…
Signed-off-by Michael Roth<[email protected]>--- qapi-schema-guest.json | 204 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 204 insertions(+), 0 deletions(-)create mode 100644 qapi-schema-guest.json
I think this should be folded in the next patch.
More comments below.
Quoted 60 lines
qapi-schema-guest.json new file +53
-0@@ -0,0 +1,204 @@ +# *-*- 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: +# +# Initiate guest-activated shutdown. Note: this is an asynchronousqapi-schema-guest.json line 63
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+# shutdown request, with no guaruntee of successful shutdown. Errors +# will be logged to guest's syslog. +# +# @mode: "halt", "powerdown", or "reboot" +# +# Returns: Nothing on success +# +# Since: 0.15.0 +## +{ 'command': 'guest-shutdown', 'data': { 'mode': 'str' } }Shouldn't 'mode' be optional?
Quoted 8 lines
qapi-schema-guest.json new file +8
-0+ +## +# @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. +#qapi-schema-guest.json line 81
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+# @mode: #optional open mode, as per fopen(), "r" is the default. +# +# Returns: Guest file handle on success. +# If @filepath cannot be opened, OpenFileFailed +# +# Since: 0.15.0 +## +{ 'command': 'guest-file-open', + 'data': { 'filepath': 'str', '*mode': 'str' }, + 'returns': 'int' }You can use 'file-path'. Actually, I'd use just 'path'.
Quoted 11 lines
qapi-schema-guest.json new file +11
-0+ +## +# @guest-file-read: +# +# Read from an open file in the guest +# +# @filehandle: filehandle returned by guest-file-open +# +# @count: maximum number of bytes to read +# +# Returns: GuestFileRead on success.qapi-schema-guest.json line 102
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+# If @filehandle is not open, OpenFileFailed +# +# Since: 0.15.0 +## +{ 'type': 'GuestFileRead', + 'data': { 'count': 'int', 'buf': 'str', 'eof': 'bool' } } + +{ 'command': 'guest-file-read', + 'data': { 'filehandle': 'int', 'count': 'int' }, + 'returns': 'GuestFileRead' }file-handle. Also, we have to say that the returned data is base64-encoded.
Quoted 12 lines
qapi-schema-guest.json new file +12
-0+ +## +# @guest-file-write: +# +# Write to an open file in the guest +# +# @filehandle: filehandle returned by guest-file-open +# +# @data_b64: base64-encoded string representing data to be written +# +# @count: bytes to write (actual bytes, after b64-decode) +#qapi-schema-guest.json line 124
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+# Returns: GuestFileWrite on success. +# If @filehandle is not opened, OpenFileFailed +# +# Since: 0.15.0 +## +{ 'type': 'GuestFileWrite', + 'data': { 'count': 'int', 'eof': 'bool' } } +{ 'command': 'guest-file-write', + 'data': { 'filehandle': 'int', 'data_b64': 'str', 'count': 'int' }, + 'returns': 'GuestFileWrite' }data-b64
Quoted 44 lines
qapi-schema-guest.json new file +44
-0+ +## +# @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. +# +# @filehandle: 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. +# If @filehandle is not opened, OpenFileFailed +# +# Since: 0.15.0 +## +{ 'type': 'GuestFileSeek', + 'data': { 'position': 'int', 'eof': 'bool' } } + +{ 'command': 'guest-file-seek', + 'data': { 'filehandle': 'int', 'offset': 'int', 'whence': 'int' }, + 'returns': 'GuestFileSeek' } + +## +# @guest-file-close: +# +# Close an open file in the guest +# +# @filehandle: filehandle returned by guest-file-open +# +# Returns: Nothing on success. +# If @filehandle is not opened, OpenFileFailed +# +# Since: 0.15.0 +## +{ 'command': 'guest-file-close', + 'data': { 'filehandle': 'int' } } + +## +# @guest-fsfreeze-status: +#qapi-schema-guest.json line 178
Quoted 10 lines
qapi-schema-guest.json new file +10
-0+# get guest fsfreeze state +# +# Returns: GuestFsfreezeStatus (enumeration starts at 1) +# +# Since: 0.15.0 +## +{ 'enum': 'GuestFsfreezeStatus', + 'data': [ 'thawed', 'inprogress', 'frozen', 'error' ] } +{ 'command': 'guest-fsfreeze-status', + 'returns': 'GuestFsfreezeStatus' }hmm, I thought a qapi command implementation would return an enum (ie. int), but the qapi would translate it to a string and return the string to the client. However, this returns an int (as explained above).
Quoted 2 lines
Did I misunderstand how the qapi handles enums then?
No, I think you're right... the original code generation seemed to support this at least. With the switchover to visitor functions Anthony treated enum types as integers when handling input/output, but now that I look at it again there was a commented-out block that suggested a possible TODO here.
It could be done by generating a lookup table for each qapi-defined enum and then passing that to qmp_input_type_enum()/qapi_output_type_enum()
Sure would make the enum functionality more useful :) I'll see if I can work it into set2 without too much churn.
Quoted 27 lines
Quoted 26 lines
qapi-schema-guest.json new file +26
-0+ +## +# @guest-fsfreeze-freeze: +# +# Sync and freeze all non-network guest filesystems +# +# Returns: Number of file systems frozen +# If error, -1 (unknown error) or -errno +# +# 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' }
PATCH v6 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-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=qga0
... echo "{'execute':'guest-info'}" | socat stdio \
unix-connect:/tmp/qga0.sock guest:
qemu-ga -c virtio-serial -p /dev/virtio-ports/qga0 \
-p /var/run/qemu-guest-agent.pid -d--- Makefile | 15 ++- qemu-ga.c | 4 + qerror.h | 3 + qga/guest-agent-commands.c | 501 ++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 2 + 5 files changed, 523 insertions(+), 2 deletions(-) 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-qmp-marshal.o QEMULIBS=libhw32 libhw64 libuser libdis libdis-user
qemu-ga.c +4 -0
@@ -637,6 +637,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 );
@@ -645,6 +648,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.h +3 -0
@@ -184,4 +184,7 @@ QError *qobject_to_qerror(const QObject *obj);#define QERR_FEATURE_DISABLED \ "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }" +#define QERR_QGA_LOGGING_FAILED \ + "{ 'class': 'QgaLoggingFailed', 'data': {} }" +#endif /* QERROR_H */
qga/guest-agent-commands.c new file +501 -0
501 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_LIMIT 4 << 20/* 4MB block size max for chunked reads */ typedef 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 v6 4/4] guest agent: add guest agent RPCs/commands
Quoted 201 lines · On Tue, 5 Jul 2011 08:21:40 -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-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=qga0 ...echo "{'execute':'guest-info'}" | socat stdio \ unix-connect:/tmp/qga0.sockguest: qemu-ga -c virtio-serial -p /dev/virtio-ports/qga0 \ -p /var/run/qemu-guest-agent.pid -dSigned-off-by Michael Roth <[email protected]>--- Makefile | 15 ++- qemu-ga.c | 4 + qerror.h | 3 + qga/guest-agent-commands.c | 501 ++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 2 + 5 files changed, 523 insertions(+), 2 deletions(-) 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-qmp-marshal.o QEMULIBS=libhw32 libhw64 libuser libdis libdis-userqemu-ga.c +4
-0@@ -637,6 +637,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 );@@ -645,6 +648,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.h +3
-0@@ -184,4 +184,7 @@ QError *qobject_to_qerror(const QObject *obj);#define QERR_FEATURE_DISABLED \ "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }" +#define QERR_QGA_LOGGING_FAILED \ + "{ 'class': 'QgaLoggingFailed', 'data': {} }" +#endif /* QERROR_H */ qga/guest-agent-commands.c new file +84
-0@@ -0,0 +1,501 @@ +/* +* 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 (const char *mode,Error **err) +{ +int ret; +const char *shutdown_flag; + +slog ("guest-shutdown called, mode: %s" , mode); +if (strcmp (mode,"halt" ) ==0 ) { + shutdown_flag ="-H" ; + }else if (strcmp (mode,"powerdown" ) ==0 ) { + shutdown_flag ="-P" ; + }else if (strcmp (mode,"reboot" ) ==0 ) { + shutdown_flag ="-r" ; + }else { +error_set (err,QERR_INVALID_PARAMETER_VALUE ,"mode" , +"halt|powerdown|reboot" ); +return ; + }
qga/guest-agent-commands.c line 94
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ + ret =fork (); +if (ret ==0 ) { +/* child, start the shutdown */ +setsid (); +fclose (stdin); +fclose (stdout); +fclose (stderr); + +sleep (5 );
If we're required to return a response before the shutdown happens, this is a bug and I'm afraid that the right way to this is a bit complex.
Otherwise we can just leave it out.
Quoted 86 lines
qga/guest-agent-commands.c new file +86
-0+ 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 *filepath,bool has_mode,const char *mode,Error **err) +{ +FILE *fh; +int fd; +int64_t ret =-1 ; + +if (!has_mode) { + mode ="r" ; + } +slog ("guest-file-open called, filepath: %s, mode: %s" , filepath, mode); + fh =fopen (filepath, mode); +if (!fh) { +error_set (err,QERR_OPEN_FILE_FAILED , filepath); +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 , filepath); +fclose (fh); +return -1 ; + } + +guest_file_handle_add (fh); +slog ("guest-file-open, filehandle: %d" , fd); +return fd; +} + +struct GuestFileRead *qmp_guest_file_read (int64_t filehandle,int64_t count, +Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +GuestFileRead *read_data; +guchar *buf; +FILE *fh; +size_t read_count;
qga/guest-agent-commands.c line 190
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + +if (count <0 || count >QGA_READ_LIMIT ) { +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + }
Are we imposing that limit because of the malloc() call below? If that's the case I think it's wrong, because we don't know the VM (neither the guest) better than the client.
The best thing we can do here is to limit it to the file size. Additionally to this we could have a command-line option to allow the sysadmin set his/her own limit.
qga/guest-agent-commands.c line 198
Quoted 8 lines
qga/guest-agent-commands.c new file +8
-0+ + fh = gfh->fh; + read_data =qemu_mallocz (sizeof (GuestFileRead) +1 ); + buf =qemu_mallocz (count+1 ); +if (!buf) { +error_set (err,QERR_UNDEFINED_ERROR ); +return NULL ; + }
qemu_malloc() functions never fail...
qga/guest-agent-commands.c line 200
Quoted 2 lines
qga/guest-agent-commands.c new file +2
-0+ + read_count =fread (buf,1 , count, fh);
Isn't 'nmemb' and 'size' swapped?
Quoted 34 lines
qga/guest-agent-commands.c new file +34
-0+ buf[read_count] =0 ; + read_data->count = read_count; + read_data->eof =feof (fh); +if (read_count) { + read_data->buf =g_base64_encode (buf, read_count); + } +qemu_free (buf); +/* clear error and eof. error is generally due to EAGAIN from non-blocking +* mode, and no real way to differenitate from a real error since we only +* get boolean error flag from ferror() +*/ +clearerr (fh); + +return read_data; +} + +GuestFileWrite *qmp_guest_file_write (int64_t filehandle,const char *data_b64, +int64_t count,Error **err) +{ +GuestFileWrite *write_data; +guchar *data; +gsize data_len; +int write_count; +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +FILE *fh; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + + fh = gfh->fh; + data =g_base64_decode (data_b64, &data_len); +if (count > data_len) {
qga/guest-agent-commands.c line 244
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+qemu_free (data); +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + } + write_data =qemu_mallocz (sizeof (GuestFileWrite)); + write_count =fwrite (data,1 , count, fh); + write_data->count = write_count; + write_data->eof =feof (fh); +qemu_free (data); +clearerr (fh);
Shouldn't we check for errors instead of doing this?
Btw, I think it's a good idea to offer guest-file-flush() too (or do a flush() here, but that's probably bad).
Quoted 18 lines
qga/guest-agent-commands.c new file +18
-0+ +return write_data; +} + +struct GuestFileSeek *qmp_guest_file_seek (int64_t filehandle,int64_t offset, +int64_t whence,Error **err) +{ +GuestFileSeek *seek_data; +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +FILE *fh; +int ret; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + + fh = gfh->fh;
qga/guest-agent-commands.c line 272
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ seek_data =qemu_mallocz (sizeof (GuestFileRead)); + ret =fseek (fh, offset, whence); +if (ret ==-1 ) { +error_set (err,QERR_UNDEFINED_ERROR ); +qemu_free (seek_data); +return NULL ; + } + seek_data->position =ftell (fh); + seek_data->eof =feof (fh); +clearerr (fh);
Again, I don't see why we should do this.
Quoted 72 lines
qga/guest-agent-commands.c new file +72
-0+ +return seek_data; +} + +void qmp_guest_file_close (int64_t filehandle,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (filehandle); + +slog ("guest-file-close called, filehandle: %ld" , filehandle); +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return ; + } + +fclose (gfh->fh); +QTAILQ_REMOVE (&guest_file_state.filehandles, gfh, next); +qemu_free (gfh); +} + +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; + + fp =setmntent (mtab,"r" ); +if (!fp) { +g_warning ("fsfreeze: unable to read mtab" ); + goto fail; + } + +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);
qga/guest-agent-commands.c line 354
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ +return 0 ; + +fail: + 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); + }
This doesn't seem to be used.
Quoted 15 lines
qga/guest-agent-commands.c new file +15
-0+ +return -1 ; +} + +/* +* 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.
qga/guest-agent-commands.c line 379
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+*/ +int64_t qmp_guest_fsfreeze_freeze (Error **err) +{ +int ret =0 , i =0 ; +struct GuestFsfreezeMount *mount, *temp; +int fd; + +slog ("guest-fsfreeze called" ); + +if (guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_THAWED ) {
return 0;
qga/guest-agent-commands.c line 385
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+ ret =0 ; + goto out; + } + + ret =guest_fsfreeze_build_mount_list (); +if (ret <0 ) {
return ret;
Quoted 33 lines
qga/guest-agent-commands.c new file +33
-0+ goto out; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_INPROGRESS ; + +/* 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 ) { + ret = errno; + 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 reason 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 ) { +close (fd); + goto error; + } +close (fd); + + i++;
qga/guest-agent-commands.c line 428
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_FROZEN ; + ret = i; +out: +return ret; +error: +if (i >0 ) { + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_ERROR ; + }
Shouldn't you undo everything that has been done so far? Which is freeing the build list and thawing the file-systems that were frozen before the error?
Quoted 4 lines
qga/guest-agent-commands.c new file +4
-0+ goto out; +} + +/*
qga/guest-agent-commands.c line 442
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-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 ; + +if (guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_FROZEN && + guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_INPROGRESS ) {
I don't follow why we're checking against INPROGRESS here.
Quoted 5 lines
qga/guest-agent-commands.c new file +5
-0+ ret =0 ; + goto out_enable_logging; + } + + QTAILQ_FOREACH_SAFE(mount, &guest_fsfreeze_state.mount_list, next, temp) {
qga/guest-agent-commands.c line 457
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ fd =qemu_open (mount->dirname,O_RDONLY ); +if (fd ==-1 ) { + ret = -errno; + goto out; + } + ret =ioctl (fd,FITHAW ); +if (ret <0 && errno !=EOPNOTSUPP && errno !=EINVAL ) { + ret = -errno; +close (fd); + goto out;
Shouldn't you continue and try to thaw the other file-systems in the list?
Quoted 61 lines
qga/guest-agent-commands.c new file +44
-0+ } +close (fd); + +QTAILQ_REMOVE (&guest_fsfreeze_state.mount_list, mount, next); +qemu_free (mount->dirname); +qemu_free (mount->devtype); +qemu_free (mount); + i++; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_THAWED ; + ret = i; +out_enable_logging: +enable_logging (); +out: +return ret; +} + +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_LIMIT 4 << 20/* 4MB block size max for chunked reads */ typedef 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 v6 4/4] guest agent: add guest agent RPCs/commands
Quoted 218 lines · Luiz Capitulino
Quoted 201 lines · On Tue, 5 Jul 2011 08:21:40 -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-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=qga0 ...echo "{'execute':'guest-info'}" | socat stdio \ unix-connect:/tmp/qga0.sockguest: qemu-ga -c virtio-serial -p /dev/virtio-ports/qga0 \ -p /var/run/qemu-guest-agent.pid -dSigned-off-by Michael Roth<[email protected]>--- Makefile | 15 ++- qemu-ga.c | 4 + qerror.h | 3 + qga/guest-agent-commands.c | 501 ++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 2 + 5 files changed, 523 insertions(+), 2 deletions(-)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-qmp-marshal.o QEMULIBS=libhw32 libhw64 libuser libdis libdis-userqemu-ga.c +4
-0@@ -637,6 +637,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 );@@ -645,6 +648,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.h +3
-0@@ -184,4 +184,7 @@ QError *qobject_to_qerror(const QObject *obj);#define QERR_FEATURE_DISABLED \ "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }" +#define QERR_QGA_LOGGING_FAILED \ + "{ 'class': 'QgaLoggingFailed', 'data': {} }" +#endif /* QERROR_H */ qga/guest-agent-commands.c new file +84
-0@@ -0,0 +1,501 @@ +/* +* 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 (const char *mode,Error **err) +{ +int ret; +const char *shutdown_flag; + +slog ("guest-shutdown called, mode: %s" , mode); +if (strcmp (mode,"halt" ) ==0 ) { + shutdown_flag ="-H" ; + }else if (strcmp (mode,"powerdown" ) ==0 ) { + shutdown_flag ="-P" ; + }else if (strcmp (mode,"reboot" ) ==0 ) { + shutdown_flag ="-r" ; + }else { +error_set (err,QERR_INVALID_PARAMETER_VALUE ,"mode" , +"halt|powerdown|reboot" ); +return ; + }qga/guest-agent-commands.c line 94
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ + ret =fork (); +if (ret ==0 ) { +/* child, start the shutdown */ +setsid (); +fclose (stdin); +fclose (stdout); +fclose (stderr); + +sleep (5 );If we're required to return a response before the shutdown happens, this is a bug and I'm afraid that the right way to this is a bit complex.
Quoted 2 lines
Otherwise we can just leave it out.
Yah, I ran this by Anthony and Adam and just leaving it out seems to be the preferred approach, for now at least.
Quoted 101 lines
Quoted 86 lines
qga/guest-agent-commands.c new file +86
-0+ 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 *filepath,bool has_mode,const char *mode,Error **err) +{ +FILE *fh; +int fd; +int64_t ret =-1 ; + +if (!has_mode) { + mode ="r" ; + } +slog ("guest-file-open called, filepath: %s, mode: %s" , filepath, mode); + fh =fopen (filepath, mode); +if (!fh) { +error_set (err,QERR_OPEN_FILE_FAILED , filepath); +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 , filepath); +fclose (fh); +return -1 ; + } + +guest_file_handle_add (fh); +slog ("guest-file-open, filehandle: %d" , fd); +return fd; +} + +struct GuestFileRead *qmp_guest_file_read (int64_t filehandle,int64_t count, +Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +GuestFileRead *read_data; +guchar *buf; +FILE *fh; +size_t read_count;qga/guest-agent-commands.c line 190
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + +if (count<0 || count>QGA_READ_LIMIT ) { +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + }Are we imposing that limit because of the
malloc()call below? If that's the case I think it's wrong, because we don't know the VM (neither the guest) better than the client.
Quoted 4 lines
The best thing we can do here is to limit it to the file size. Additionally to this we could have a command-line option to allow the sysadmin set his/her own limit.
That's technically the better approach, but we're also bound by the maximum token size limit in the JSON parser, which is 64MB. Best we can do is set QGA_READ_LIMIT accordingly.
Quoted 9 lines
qga/guest-agent-commands.c line 198
Quoted 8 lines
qga/guest-agent-commands.c new file +8
-0+ + fh = gfh->fh; + read_data =qemu_mallocz (sizeof (GuestFileRead) +1 ); + buf =qemu_mallocz (count+1 ); +if (!buf) { +error_set (err,QERR_UNDEFINED_ERROR ); +return NULL ; + }
Quoted 7 lines
qemu_malloc()functions never fail...qga/guest-agent-commands.c line 200
Quoted 2 lines
qga/guest-agent-commands.c new file +2
-0+ + read_count =fread (buf,1 , count, fh);Isn't 'nmemb' and 'size' swapped?
I'm not sure...
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
I wrote it as $count number of 1-bytes elements. This seems logical to me, since it's a non-blocking FD which way result in a partial of some lesser number of bytes than count.
Quoted 38 lines
Quoted 38 lines
qga/guest-agent-commands.c new file +38
-0+ buf[read_count] =0 ; + read_data->count = read_count; + read_data->eof =feof (fh); +if (read_count) { + read_data->buf =g_base64_encode (buf, read_count); + } +qemu_free (buf); +/* clear error and eof. error is generally due to EAGAIN from non-blocking +* mode, and no real way to differenitate from a real error since we only +* get boolean error flag from ferror() +*/ +clearerr (fh); + +return read_data; +} + +GuestFileWrite *qmp_guest_file_write (int64_t filehandle,const char *data_b64, +int64_t count,Error **err) +{ +GuestFileWrite *write_data; +guchar *data; +gsize data_len; +int write_count; +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +FILE *fh; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + + fh = gfh->fh; + data =g_base64_decode (data_b64,&data_len); +if (count> data_len) { +qemu_free (data); +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + }
Quoted 9 lines
qga/guest-agent-commands.c line 244
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+ write_data =qemu_mallocz (sizeof (GuestFileWrite)); + write_count =fwrite (data,1 , count, fh); + write_data->count = write_count; + write_data->eof =feof (fh); +qemu_free (data); +clearerr (fh);Shouldn't we check for errors instead of doing this?
Yah...unfortunately we only get a boolean flag with ferror() so it's not all that useful, but I can add an error flag to the calls to capture it at least. clearerr() is only being used here to clear the eof flag.
Quoted 3 lines
Btw, I think it's a good idea to offer guest-file-flush() too (or do a
flush()here, but that's probably bad).
Yah, I'd been planning on adding a guest-file-flush() for a while now. I'll add that for the respin.
Quoted 107 lines
Quoted 18 lines
qga/guest-agent-commands.c new file +18
-0+ +return write_data; +} + +struct GuestFileSeek *qmp_guest_file_seek (int64_t filehandle,int64_t offset, +int64_t whence,Error **err) +{ +GuestFileSeek *seek_data; +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +FILE *fh; +int ret; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + + fh = gfh->fh;qga/guest-agent-commands.c line 272
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ seek_data =qemu_mallocz (sizeof (GuestFileRead)); + ret =fseek (fh, offset, whence); +if (ret ==-1 ) { +error_set (err,QERR_UNDEFINED_ERROR ); +qemu_free (seek_data); +return NULL ; + } + seek_data->position =ftell (fh); + seek_data->eof =feof (fh); +clearerr (fh);Again, I don't see why we should do this.
Quoted 76 lines
qga/guest-agent-commands.c new file +76
-0+ +return seek_data; +} + +void qmp_guest_file_close (int64_t filehandle,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (filehandle); + +slog ("guest-file-close called, filehandle: %ld" , filehandle); +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return ; + } + +fclose (gfh->fh); +QTAILQ_REMOVE (&guest_file_state.filehandles, gfh, next); +qemu_free (gfh); +} + +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; + + fp =setmntent (mtab,"r" ); +if (!fp) { +g_warning ("fsfreeze: unable to read mtab" ); + goto fail; + } + +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 ; + +fail:
Quoted 9 lines
qga/guest-agent-commands.c line 354
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); + }This doesn't seem to be used.
It can get used even a 2nd invocation of this function gets called that results in a goto fail. But looking again this should be done unconditionally at the start of the function, since the mount list is part of global state now.
Quoted 76 lines
Quoted 15 lines
qga/guest-agent-commands.c new file +15
-0+ +return -1 ; +} + +/* +* 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. qga/guest-agent-commands.c line 379
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+*/ +int64_t qmp_guest_fsfreeze_freeze (Error **err) +{ +int ret =0 , i =0 ; +struct GuestFsfreezeMount *mount, *temp; +int fd; + +slog ("guest-fsfreeze called" ); + +if (guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_THAWED ) {return 0;
qga/guest-agent-commands.c
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+ ret =0 ; + goto out; + } + + ret =guest_fsfreeze_build_mount_list (); +if (ret<0 ) {return ret;
Quoted 39 lines
qga/guest-agent-commands.c new file +39
-0+ goto out; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_INPROGRESS ; + +/* 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 ) { + ret = errno; + 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 reason 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 ) { +close (fd); + goto error; + } +close (fd); + + i++; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_FROZEN ; + ret = i; +out: +return ret;
Quoted 9 lines
qga/guest-agent-commands.c line 428
Quoted 4 lines
qga/guest-agent-commands.c new file +4
-0+error: +if (i>0 ) { + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_ERROR ; + }Shouldn't you undo everything that has been done so far? Which is freeing the build list and thawing the file-systems that were frozen before the error?
We can...the way it's done right now is you get a count of how many filesystems were frozen, along an error status. Depending on the error/count the user can either ignore the error, do what it is they want to do, then call thaw(), or just immediately call thaw().
So we can do an automatic thaw() on their behalf, but i figured the status was good enough.
Quoted 8 lines
Quoted 8 lines
qga/guest-agent-commands.c new file +8
-0+ goto out; +} + +/* +* Walk list of frozen file systems in the guest, and thaw them. +*/ +int64_t qmp_guest_fsfreeze_thaw (Error **err) +{
Quoted 9 lines
qga/guest-agent-commands.c line 442
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+int ret; +GuestFsfreezeMount *mount, *temp; +int fd, i =0 ; + +if (guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_FROZEN && + guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_INPROGRESS ) {I don't follow why we're checking against INPROGRESS here.
To prevent a race I believe...but we're synchronous now so that's probably no longer needed. I'll look it over and remove it if that's the case.
Quoted 16 lines
Quoted 5 lines
qga/guest-agent-commands.c new file +5
-0+ ret =0 ; + goto out_enable_logging; + } + + QTAILQ_FOREACH_SAFE(mount,&guest_fsfreeze_state.mount_list, next, temp) {qga/guest-agent-commands.c line 457
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ fd =qemu_open (mount->dirname,O_RDONLY ); +if (fd ==-1 ) { + ret = -errno; + goto out; + } + ret =ioctl (fd,FITHAW ); +if (ret<0 && errno !=EOPNOTSUPP && errno !=EINVAL ) { + ret = -errno; +close (fd); + goto out;
Quoted 2 lines
Shouldn't you continue and try to thaw the other file-systems in the list?
That's probably better
Quoted 62 lines
Quoted 61 lines
qga/guest-agent-commands.c new file +44
-0+ } +close (fd); + +QTAILQ_REMOVE (&guest_fsfreeze_state.mount_list, mount, next); +qemu_free (mount->dirname); +qemu_free (mount->devtype); +qemu_free (mount); + i++; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_THAWED ; + ret = i; +out_enable_logging: +enable_logging (); +out: +return ret; +} + +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_LIMIT 4<< 20/* 4MB block size max for chunked reads */ typedef 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 v6 4/4] guest agent: add guest agent RPCs/commands
Quoted 326 lines · On Mon, 11 Jul 2011 15:11:26 -0500 Michael Roth <[email protected]>…
Quoted 218 lines · Luiz Capitulino
Quoted 201 lines · On Tue, 5 Jul 2011 08:21:40 -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-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=qga0 ...echo "{'execute':'guest-info'}" | socat stdio \ unix-connect:/tmp/qga0.sockguest: qemu-ga -c virtio-serial -p /dev/virtio-ports/qga0 \ -p /var/run/qemu-guest-agent.pid -dSigned-off-by Michael Roth<[email protected]>--- Makefile | 15 ++- qemu-ga.c | 4 + qerror.h | 3 + qga/guest-agent-commands.c | 501 ++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 2 + 5 files changed, 523 insertions(+), 2 deletions(-)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-qmp-marshal.o QEMULIBS=libhw32 libhw64 libuser libdis libdis-userqemu-ga.c +4
-0@@ -637,6 +637,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 );@@ -645,6 +648,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.h +3
-0@@ -184,4 +184,7 @@ QError *qobject_to_qerror(const QObject *obj);#define QERR_FEATURE_DISABLED \ "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }" +#define QERR_QGA_LOGGING_FAILED \ + "{ 'class': 'QgaLoggingFailed', 'data': {} }" +#endif /* QERROR_H */ qga/guest-agent-commands.c new file +84
-0@@ -0,0 +1,501 @@ +/* +* 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 (const char *mode,Error **err) +{ +int ret; +const char *shutdown_flag; + +slog ("guest-shutdown called, mode: %s" , mode); +if (strcmp (mode,"halt" ) ==0 ) { + shutdown_flag ="-H" ; + }else if (strcmp (mode,"powerdown" ) ==0 ) { + shutdown_flag ="-P" ; + }else if (strcmp (mode,"reboot" ) ==0 ) { + shutdown_flag ="-r" ; + }else { +error_set (err,QERR_INVALID_PARAMETER_VALUE ,"mode" , +"halt|powerdown|reboot" ); +return ; + }qga/guest-agent-commands.c line 94
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ + ret =fork (); +if (ret ==0 ) { +/* child, start the shutdown */ +setsid (); +fclose (stdin); +fclose (stdout); +fclose (stderr); + +sleep (5 );If we're required to return a response before the shutdown happens, this is a bug and I'm afraid that the right way to this is a bit complex.
Quoted 2 lines
Otherwise we can just leave it out.
Yah, I ran this by Anthony and Adam and just leaving it out seems to be the preferred approach, for now at least.
Quoted 101 lines
Quoted 86 lines
qga/guest-agent-commands.c new file +86
-0+ 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 *filepath,bool has_mode,const char *mode,Error **err) +{ +FILE *fh; +int fd; +int64_t ret =-1 ; + +if (!has_mode) { + mode ="r" ; + } +slog ("guest-file-open called, filepath: %s, mode: %s" , filepath, mode); + fh =fopen (filepath, mode); +if (!fh) { +error_set (err,QERR_OPEN_FILE_FAILED , filepath); +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 , filepath); +fclose (fh); +return -1 ; + } + +guest_file_handle_add (fh); +slog ("guest-file-open, filehandle: %d" , fd); +return fd; +} + +struct GuestFileRead *qmp_guest_file_read (int64_t filehandle,int64_t count, +Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +GuestFileRead *read_data; +guchar *buf; +FILE *fh; +size_t read_count;qga/guest-agent-commands.c line 190
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + +if (count<0 || count>QGA_READ_LIMIT ) { +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + }Are we imposing that limit because of the
malloc()call below? If that's the case I think it's wrong, because we don't know the VM (neither the guest) better than the client.
Quoted 8 lines
Quoted 4 lines
The best thing we can do here is to limit it to the file size. Additionally to this we could have a command-line option to allow the sysadmin set his/her own limit.
That's technically the better approach, but we're also bound by the maximum token size limit in the JSON parser, which is 64MB. Best we can do is set
QGA_READ_LIMITaccordingly.
Good point, but I think it's ok to let the parser do this check itself, as control won't get here anyway. Maybe we should only document that the server imposes a limit on the token size.
Quoted 18 lines
Quoted 10 lines
qga/guest-agent-commands.c line 198
Quoted 9 lines
qga/guest-agent-commands.c new file +8
-0+ + fh = gfh->fh; + read_data =qemu_mallocz (sizeof (GuestFileRead) +1 ); + buf =qemu_mallocz (count+1 ); +if (!buf) { +error_set (err,QERR_UNDEFINED_ERROR ); +return NULL ; + }Quoted 7 lines
qemu_malloc()functions never fail...qga/guest-agent-commands.c line 200
Quoted 2 lines
qga/guest-agent-commands.c new file +2
-0+ + read_count =fread (buf,1 , count, fh);Isn't 'nmemb' and 'size' swapped?
Quoted 7 lines
I'm not sure...
size_tfread(void *ptr, size_t size, size_t nmemb, FILE *stream);I wrote it as $count number of 1-bytes elements. This seems logical to me, since it's a non-blocking FD which way result in a partial of some lesser number of bytes than count.
Ok. I think either way will work.
Quoted 49 lines
Quoted 39 lines
Quoted 39 lines
qga/guest-agent-commands.c new file +38
-0+ buf[read_count] =0 ; + read_data->count = read_count; + read_data->eof =feof (fh); +if (read_count) { + read_data->buf =g_base64_encode (buf, read_count); + } +qemu_free (buf); +/* clear error and eof. error is generally due to EAGAIN from non-blocking +* mode, and no real way to differenitate from a real error since we only +* get boolean error flag from ferror() +*/ +clearerr (fh); + +return read_data; +} + +GuestFileWrite *qmp_guest_file_write (int64_t filehandle,const char *data_b64, +int64_t count,Error **err) +{ +GuestFileWrite *write_data; +guchar *data; +gsize data_len; +int write_count; +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +FILE *fh; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + + fh = gfh->fh; + data =g_base64_decode (data_b64,&data_len); +if (count> data_len) { +qemu_free (data); +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + }Quoted 9 lines
qga/guest-agent-commands.c line 244
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+ write_data =qemu_mallocz (sizeof (GuestFileWrite)); + write_count =fwrite (data,1 , count, fh); + write_data->count = write_count; + write_data->eof =feof (fh); +qemu_free (data); +clearerr (fh);Shouldn't we check for errors instead of doing this?
Quoted 3 lines
Yah...unfortunately we only get a boolean flag with
ferror()so it's not all that useful, but I can add an error flag to the calls to capture it at least.clearerr()is only being used here to clear the eof flag.
I meant to check fwrite()'s return.
Quoted 38 lines
Quoted 4 lines
Btw, I think it's a good idea to offer guest-file-flush() too (or do a
flush()here, but that's probably bad).Yah, I'd been planning on adding a guest-file-flush() for a while now. I'll add that for the respin.
Quoted 30 lines
Quoted 18 lines
qga/guest-agent-commands.c new file +18
-0+ +return write_data; +} + +struct GuestFileSeek *qmp_guest_file_seek (int64_t filehandle,int64_t offset, +int64_t whence,Error **err) +{ +GuestFileSeek *seek_data; +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +FILE *fh; +int ret; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + + fh = gfh->fh;qga/guest-agent-commands.c line 272
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ seek_data =qemu_mallocz (sizeof (GuestFileRead)); + ret =fseek (fh, offset, whence); +if (ret ==-1 ) { +error_set (err,QERR_UNDEFINED_ERROR ); +qemu_free (seek_data); +return NULL ; + } + seek_data->position =ftell (fh); + seek_data->eof =feof (fh); +clearerr (fh);Again, I don't see why we should do this.
This is probably ok, as we're checking fseek() above.
Quoted 178 lines
Quoted 77 lines
Quoted 77 lines
qga/guest-agent-commands.c new file +76
-0+ +return seek_data; +} + +void qmp_guest_file_close (int64_t filehandle,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (filehandle); + +slog ("guest-file-close called, filehandle: %ld" , filehandle); +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return ; + } + +fclose (gfh->fh); +QTAILQ_REMOVE (&guest_file_state.filehandles, gfh, next); +qemu_free (gfh); +} + +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; + + fp =setmntent (mtab,"r" ); +if (!fp) { +g_warning ("fsfreeze: unable to read mtab" ); + goto fail; + } + +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 ; + +fail:Quoted 9 lines
qga/guest-agent-commands.c line 354
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); + }This doesn't seem to be used.
It can get used even a 2nd invocation of this function gets called that results in a goto fail. But looking again this should be done unconditionally at the start of the function, since the mount list is part of global state now.
Quoted 76 lines
Quoted 15 lines
qga/guest-agent-commands.c new file +15
-0+ +return -1 ; +} + +/* +* 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. qga/guest-agent-commands.c line 379
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+*/ +int64_t qmp_guest_fsfreeze_freeze (Error **err) +{ +int ret =0 , i =0 ; +struct GuestFsfreezeMount *mount, *temp; +int fd; + +slog ("guest-fsfreeze called" ); + +if (guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_THAWED ) {return 0;
qga/guest-agent-commands.c
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+ ret =0 ; + goto out; + } + + ret =guest_fsfreeze_build_mount_list (); +if (ret<0 ) {return ret;
Quoted 39 lines
qga/guest-agent-commands.c new file +39
-0+ goto out; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_INPROGRESS ; + +/* 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 ) { + ret = errno; + 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 reason 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 ) { +close (fd); + goto error; + } +close (fd); + + i++; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_FROZEN ; + ret = i; +out: +return ret;Quoted 9 lines
qga/guest-agent-commands.c line 428
Quoted 4 lines
qga/guest-agent-commands.c new file +4
-0+error: +if (i>0 ) { + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_ERROR ; + }Shouldn't you undo everything that has been done so far? Which is freeing the build list and thawing the file-systems that were frozen before the error?
Quoted 4 lines
We can...the way it's done right now is you get a count of how many filesystems were frozen, along an error status. Depending on the error/count the user can either ignore the error, do what it is they want to do, then call
thaw(), or just immediately callthaw().
But you don't get the count on error, so it's difficult (if possible) to learn how many file-systems were frozen.
Quoted 110 lines
So we can do an automatic
thaw()on their behalf, but i figured the status was good enough.Quoted 8 lines
Quoted 8 lines
qga/guest-agent-commands.c new file +8
-0+ goto out; +} + +/* +* Walk list of frozen file systems in the guest, and thaw them. +*/ +int64_t qmp_guest_fsfreeze_thaw (Error **err) +{Quoted 9 lines
qga/guest-agent-commands.c line 442
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+int ret; +GuestFsfreezeMount *mount, *temp; +int fd, i =0 ; + +if (guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_FROZEN && + guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_INPROGRESS ) {I don't follow why we're checking against INPROGRESS here.
To prevent a race I believe...but we're synchronous now so that's probably no longer needed. I'll look it over and remove it if that's the case.
Quoted 16 lines
Quoted 5 lines
qga/guest-agent-commands.c new file +5
-0+ ret =0 ; + goto out_enable_logging; + } + + QTAILQ_FOREACH_SAFE(mount,&guest_fsfreeze_state.mount_list, next, temp) {qga/guest-agent-commands.c line 457
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ fd =qemu_open (mount->dirname,O_RDONLY ); +if (fd ==-1 ) { + ret = -errno; + goto out; + } + ret =ioctl (fd,FITHAW ); +if (ret<0 && errno !=EOPNOTSUPP && errno !=EINVAL ) { + ret = -errno; +close (fd); + goto out;Quoted 2 lines
Shouldn't you continue and try to thaw the other file-systems in the list?
That's probably better
Quoted 62 lines
Quoted 61 lines
qga/guest-agent-commands.c new file +44
-0+ } +close (fd); + +QTAILQ_REMOVE (&guest_fsfreeze_state.mount_list, mount, next); +qemu_free (mount->dirname); +qemu_free (mount->devtype); +qemu_free (mount); + i++; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_THAWED ; + ret = i; +out_enable_logging: +enable_logging (); +out: +return ret; +} + +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_LIMIT 4<< 20/* 4MB block size max for chunked reads */ typedef 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 v6 4/4] guest agent: add guest agent RPCs/commands
Quoted 334 lines · Luiz Capitulino
Quoted 331 lines · On Mon, 11 Jul 2011 15:11:26 -0500 Michael Roth<[email protected]>…
Quoted 218 lines · Luiz Capitulino
Quoted 201 lines · On Tue, 5 Jul 2011 08:21:40 -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-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=qga0 ... echo "{'execute':'guest-info'}" | socat stdio \ unix-connect:/tmp/qga0.sock guest: qemu-ga -c virtio-serial -p /dev/virtio-ports/qga0 \ -p /var/run/qemu-guest-agent.pid -dSigned-off-by Michael Roth<[email protected]>--- Makefile | 15 ++- qemu-ga.c | 4 + qerror.h | 3 + qga/guest-agent-commands.c | 501 ++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 2 + 5 files changed, 523 insertions(+), 2 deletions(-)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-qmp-marshal.o QEMULIBS=libhw32 libhw64 libuser libdis libdis-userqemu-ga.c +4
-0@@ -637,6 +637,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 );@@ -645,6 +648,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.h +3
-0@@ -184,4 +184,7 @@ QError *qobject_to_qerror(const QObject *obj);#define QERR_FEATURE_DISABLED \ "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }" +#define QERR_QGA_LOGGING_FAILED \ + "{ 'class': 'QgaLoggingFailed', 'data': {} }" +#endif /* QERROR_H */ qga/guest-agent-commands.c new file +84
-0@@ -0,0 +1,501 @@ +/* +* 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 (const char *mode,Error **err) +{ +int ret; +const char *shutdown_flag; + +slog ("guest-shutdown called, mode: %s" , mode); +if (strcmp (mode,"halt" ) ==0 ) { + shutdown_flag ="-H" ; + }else if (strcmp (mode,"powerdown" ) ==0 ) { + shutdown_flag ="-P" ; + }else if (strcmp (mode,"reboot" ) ==0 ) { + shutdown_flag ="-r" ; + }else { +error_set (err,QERR_INVALID_PARAMETER_VALUE ,"mode" , +"halt|powerdown|reboot" ); +return ; + }qga/guest-agent-commands.c line 94
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ + ret =fork (); +if (ret ==0 ) { +/* child, start the shutdown */ +setsid (); +fclose (stdin); +fclose (stdout); +fclose (stderr); + +sleep (5 );If we're required to return a response before the shutdown happens, this is a bug and I'm afraid that the right way to this is a bit complex.
Quoted 2 lines
Otherwise we can just leave it out.
Yah, I ran this by Anthony and Adam and just leaving it out seems to be the preferred approach, for now at least.
Quoted 105 lines
Quoted 86 lines
qga/guest-agent-commands.c new file +86
-0+ 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 *filepath,bool has_mode,const char *mode,Error **err) +{ +FILE *fh; +int fd; +int64_t ret =-1 ; + +if (!has_mode) { + mode ="r" ; + } +slog ("guest-file-open called, filepath: %s, mode: %s" , filepath, mode); + fh =fopen (filepath, mode); +if (!fh) { +error_set (err,QERR_OPEN_FILE_FAILED , filepath); +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 , filepath); +fclose (fh); +return -1 ; + } + +guest_file_handle_add (fh); +slog ("guest-file-open, filehandle: %d" , fd); +return fd; +} + +struct GuestFileRead *qmp_guest_file_read (int64_t filehandle,int64_t count, +Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +GuestFileRead *read_data; +guchar *buf; +FILE *fh; +size_t read_count;qga/guest-agent-commands.c line 190
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + +if (count<0 || count>QGA_READ_LIMIT ) { +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + }Are we imposing that limit because of the
malloc()call below? If that's the case I think it's wrong, because we don't know the VM (neither the guest) better than the client.The best thing we can do here is to limit it to the file size. Additionally to this we could have a command-line option to allow the sysadmin set his/her own limit.
Quoted 8 lines
Quoted 3 lines
That's technically the better approach, but we're also bound by the maximum token size limit in the JSON parser, which is 64MB. Best we can do is set
QGA_READ_LIMITaccordingly.Good point, but I think it's ok to let the parser do this check itself, as control won't get here anyway. Maybe we should only document that the server imposes a limit on the token size.
From a usability perspective I think the QERR_INVALID_PARAMETER, or perhaps something more descriptive, is a little nicer. Plus, they won't have to wait for 64MB to get streamed back before they get the error :)
Quoted 77 lines
Quoted 18 lines
Quoted 10 lines
qga/guest-agent-commands.c line 198
Quoted 9 lines
qga/guest-agent-commands.c new file +8
-0+ + fh = gfh->fh; + read_data =qemu_mallocz (sizeof (GuestFileRead) +1 ); + buf =qemu_mallocz (count+1 ); +if (!buf) { +error_set (err,QERR_UNDEFINED_ERROR ); +return NULL ; + }Quoted 7 lines
qemu_malloc()functions never fail...qga/guest-agent-commands.c line 200
Quoted 2 lines
qga/guest-agent-commands.c new file +2
-0+ + read_count =fread (buf,1 , count, fh);Isn't 'nmemb' and 'size' swapped?
Quoted 7 lines
I'm not sure...
size_tfread(void *ptr, size_t size, size_t nmemb, FILE *stream);I wrote it as $count number of 1-bytes elements. This seems logical to me, since it's a non-blocking FD which way result in a partial of some lesser number of bytes than count.
Ok. I think either way will work.
Quoted 49 lines
Quoted 48 lines
Quoted 35 lines
qga/guest-agent-commands.c new file +34
-0+ buf[read_count] =0 ; + read_data->count = read_count; + read_data->eof =feof (fh); +if (read_count) { + read_data->buf =g_base64_encode (buf, read_count); + } +qemu_free (buf); +/* clear error and eof. error is generally due to EAGAIN from non-blocking +* mode, and no real way to differenitate from a real error since we only +* get boolean error flag from ferror() +*/ +clearerr (fh); + +return read_data; +} + +GuestFileWrite *qmp_guest_file_write (int64_t filehandle,const char *data_b64, +int64_t count,Error **err) +{ +GuestFileWrite *write_data; +guchar *data; +gsize data_len; +int write_count; +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +FILE *fh; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + + fh = gfh->fh; + data =g_base64_decode (data_b64,&data_len); +if (count> data_len) {qga/guest-agent-commands.c line 244
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+qemu_free (data); +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + } + write_data =qemu_mallocz (sizeof (GuestFileWrite)); + write_count =fwrite (data,1 , count, fh); + write_data->count = write_count; + write_data->eof =feof (fh); +qemu_free (data); +clearerr (fh);Shouldn't we check for errors instead of doing this?
Quoted 6 lines
Quoted 3 lines
Yah...unfortunately we only get a boolean flag with
ferror()so it's not all that useful, but I can add an error flag to the calls to capture it at least.clearerr()is only being used here to clear the eof flag.I meant to check fwrite()'s return.
Ahh, right. Definitely.
Quoted 219 lines
Quoted 38 lines
Quoted 4 lines
Btw, I think it's a good idea to offer guest-file-flush() too (or do a
flush()here, but that's probably bad).Yah, I'd been planning on adding a guest-file-flush() for a while now. I'll add that for the respin.
Quoted 30 lines
Quoted 18 lines
qga/guest-agent-commands.c new file +18
-0+ +return write_data; +} + +struct GuestFileSeek *qmp_guest_file_seek (int64_t filehandle,int64_t offset, +int64_t whence,Error **err) +{ +GuestFileSeek *seek_data; +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +FILE *fh; +int ret; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + + fh = gfh->fh;qga/guest-agent-commands.c line 272
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ seek_data =qemu_mallocz (sizeof (GuestFileRead)); + ret =fseek (fh, offset, whence); +if (ret ==-1 ) { +error_set (err,QERR_UNDEFINED_ERROR ); +qemu_free (seek_data); +return NULL ; + } + seek_data->position =ftell (fh); + seek_data->eof =feof (fh); +clearerr (fh);Again, I don't see why we should do this.
This is probably ok, as we're checking
fseek()above.Quoted 178 lines
Quoted 77 lines
Quoted 77 lines
qga/guest-agent-commands.c new file +76
-0+ +return seek_data; +} + +void qmp_guest_file_close (int64_t filehandle,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (filehandle); + +slog ("guest-file-close called, filehandle: %ld" , filehandle); +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return ; + } + +fclose (gfh->fh); +QTAILQ_REMOVE (&guest_file_state.filehandles, gfh, next); +qemu_free (gfh); +} + +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; + + fp =setmntent (mtab,"r" ); +if (!fp) { +g_warning ("fsfreeze: unable to read mtab" ); + goto fail; + } + +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 ; + +fail:Quoted 9 lines
qga/guest-agent-commands.c line 354
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); + }This doesn't seem to be used.
It can get used even a 2nd invocation of this function gets called that results in a goto fail. But looking again this should be done unconditionally at the start of the function, since the mount list is part of global state now.
Quoted 85 lines
Quoted 15 lines
qga/guest-agent-commands.c new file +15
-0+ +return -1 ; +} + +/* +* 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. qga/guest-agent-commands.c line 379
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+*/ +int64_t qmp_guest_fsfreeze_freeze (Error **err) +{ +int ret =0 , i =0 ; +struct GuestFsfreezeMount *mount, *temp; +int fd; + +slog ("guest-fsfreeze called" ); + +if (guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_THAWED ) {return 0;
qga/guest-agent-commands.c
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+ ret =0 ; + goto out; + } + + ret =guest_fsfreeze_build_mount_list (); +if (ret<0 ) {return ret;
Quoted 33 lines
qga/guest-agent-commands.c new file +33
-0+ goto out; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_INPROGRESS ; + +/* 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 ) { + ret = errno; + 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 reason 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 ) { +close (fd); + goto error; + } +close (fd); + + i++;qga/guest-agent-commands.c line 428
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_FROZEN ; + ret = i; +out: +return ret; +error: +if (i>0 ) { + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_ERROR ; + }Shouldn't you undo everything that has been done so far? Which is freeing the build list and thawing the file-systems that were frozen before the error?
Quoted 8 lines
Quoted 4 lines
We can...the way it's done right now is you get a count of how many filesystems were frozen, along an error status. Depending on the error/count the user can either ignore the error, do what it is they want to do, then call
thaw(), or just immediately callthaw().But you don't get the count on error, so it's difficult (if possible) to learn how many file-systems were frozen.
Yah, my mistake. I think the out: label was one line higher, but if we did that we lose error information. Automatically unfreezing should be okay.
Quoted 111 lines
Quoted 110 lines
So we can do an automatic
thaw()on their behalf, but i figured the status was good enough.Quoted 8 lines
Quoted 8 lines
qga/guest-agent-commands.c new file +8
-0+ goto out; +} + +/* +* Walk list of frozen file systems in the guest, and thaw them. +*/ +int64_t qmp_guest_fsfreeze_thaw (Error **err) +{Quoted 9 lines
qga/guest-agent-commands.c line 442
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+int ret; +GuestFsfreezeMount *mount, *temp; +int fd, i =0 ; + +if (guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_FROZEN && + guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_INPROGRESS ) {I don't follow why we're checking against INPROGRESS here.
To prevent a race I believe...but we're synchronous now so that's probably no longer needed. I'll look it over and remove it if that's the case.
Quoted 16 lines
Quoted 5 lines
qga/guest-agent-commands.c new file +5
-0+ ret =0 ; + goto out_enable_logging; + } + + QTAILQ_FOREACH_SAFE(mount,&guest_fsfreeze_state.mount_list, next, temp) {qga/guest-agent-commands.c line 457
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ fd =qemu_open (mount->dirname,O_RDONLY ); +if (fd ==-1 ) { + ret = -errno; + goto out; + } + ret =ioctl (fd,FITHAW ); +if (ret<0 && errno !=EOPNOTSUPP && errno !=EINVAL ) { + ret = -errno; +close (fd); + goto out;Quoted 2 lines
Shouldn't you continue and try to thaw the other file-systems in the list?
That's probably better
Quoted 62 lines
Quoted 61 lines
qga/guest-agent-commands.c new file +44
-0+ } +close (fd); + +QTAILQ_REMOVE (&guest_fsfreeze_state.mount_list, mount, next); +qemu_free (mount->dirname); +qemu_free (mount->devtype); +qemu_free (mount); + i++; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_THAWED ; + ret = i; +out_enable_logging: +enable_logging (); +out: +return ret; +} + +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_LIMIT 4<< 20/* 4MB block size max for chunked reads */ typedef 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 v6 4/4] guest agent: add guest agent RPCs/commands
Quoted 339 lines · On Mon, 11 Jul 2011 18:11:21 -0500 Michael Roth <[email protected]>…
Quoted 338 lines · Luiz Capitulino
Quoted 334 lines · On Mon, 11 Jul 2011 15:11:26 -0500 Michael Roth<[email protected]>…
Quoted 218 lines · Luiz Capitulino
Quoted 201 lines · On Tue, 5 Jul 2011 08:21:40 -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-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=qga0 ... echo "{'execute':'guest-info'}" | socat stdio \ unix-connect:/tmp/qga0.sock guest: qemu-ga -c virtio-serial -p /dev/virtio-ports/qga0 \ -p /var/run/qemu-guest-agent.pid -dSigned-off-by Michael Roth<[email protected]>--- Makefile | 15 ++- qemu-ga.c | 4 + qerror.h | 3 + qga/guest-agent-commands.c | 501 ++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 2 + 5 files changed, 523 insertions(+), 2 deletions(-)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-qmp-marshal.o QEMULIBS=libhw32 libhw64 libuser libdis libdis-userqemu-ga.c +4
-0@@ -637,6 +637,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 );@@ -645,6 +648,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.h +3
-0@@ -184,4 +184,7 @@ QError *qobject_to_qerror(const QObject *obj);#define QERR_FEATURE_DISABLED \ "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }" +#define QERR_QGA_LOGGING_FAILED \ + "{ 'class': 'QgaLoggingFailed', 'data': {} }" +#endif /* QERROR_H */ qga/guest-agent-commands.c new file +84
-0@@ -0,0 +1,501 @@ +/* +* 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 (const char *mode,Error **err) +{ +int ret; +const char *shutdown_flag; + +slog ("guest-shutdown called, mode: %s" , mode); +if (strcmp (mode,"halt" ) ==0 ) { + shutdown_flag ="-H" ; + }else if (strcmp (mode,"powerdown" ) ==0 ) { + shutdown_flag ="-P" ; + }else if (strcmp (mode,"reboot" ) ==0 ) { + shutdown_flag ="-r" ; + }else { +error_set (err,QERR_INVALID_PARAMETER_VALUE ,"mode" , +"halt|powerdown|reboot" ); +return ; + }qga/guest-agent-commands.c line 94
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ + ret =fork (); +if (ret ==0 ) { +/* child, start the shutdown */ +setsid (); +fclose (stdin); +fclose (stdout); +fclose (stderr); + +sleep (5 );If we're required to return a response before the shutdown happens, this is a bug and I'm afraid that the right way to this is a bit complex.
Quoted 2 lines
Otherwise we can just leave it out.
Yah, I ran this by Anthony and Adam and just leaving it out seems to be the preferred approach, for now at least.
Quoted 101 lines
Quoted 86 lines
qga/guest-agent-commands.c new file +86
-0+ 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 *filepath,bool has_mode,const char *mode,Error **err) +{ +FILE *fh; +int fd; +int64_t ret =-1 ; + +if (!has_mode) { + mode ="r" ; + } +slog ("guest-file-open called, filepath: %s, mode: %s" , filepath, mode); + fh =fopen (filepath, mode); +if (!fh) { +error_set (err,QERR_OPEN_FILE_FAILED , filepath); +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 , filepath); +fclose (fh); +return -1 ; + } + +guest_file_handle_add (fh); +slog ("guest-file-open, filehandle: %d" , fd); +return fd; +} + +struct GuestFileRead *qmp_guest_file_read (int64_t filehandle,int64_t count, +Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +GuestFileRead *read_data; +guchar *buf; +FILE *fh; +size_t read_count;qga/guest-agent-commands.c line 190
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + +if (count<0 || count>QGA_READ_LIMIT ) { +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + }Are we imposing that limit because of the
malloc()call below? If that's the case I think it's wrong, because we don't know the VM (neither the guest) better than the client.Quoted 4 lines
The best thing we can do here is to limit it to the file size. Additionally to this we could have a command-line option to allow the sysadmin set his/her own limit.
That's technically the better approach, but we're also bound by the maximum token size limit in the JSON parser, which is 64MB. Best we can do is set
QGA_READ_LIMITaccordingly.
Quoted 8 lines
Quoted 4 lines
Good point, but I think it's ok to let the parser do this check itself, as control won't get here anyway. Maybe we should only document that the server imposes a limit on the token size.
From a usability perspective I think the
QERR_INVALID_PARAMETER, or
perhaps something more descriptive, is a little nicer. Plus, they won't have to wait for 64MB to get streamed back before they get the error :)
That's why I suggested documenting it. Are we going to add this check to all commands that make it more likely to reach the parser's limit? (also note that theoretically all commands can do it).
Quoted 430 lines
Quoted 78 lines
Quoted 19 lines
Quoted 11 lines
qga/guest-agent-commands.c line 198
Quoted 10 lines
qga/guest-agent-commands.c new file +8
-0+ + fh = gfh->fh; + read_data =qemu_mallocz (sizeof (GuestFileRead) +1 ); + buf =qemu_mallocz (count+1 ); +if (!buf) { +error_set (err,QERR_UNDEFINED_ERROR ); +return NULL ; + }Quoted 7 lines
qemu_malloc()functions never fail...qga/guest-agent-commands.c line 200
Quoted 2 lines
qga/guest-agent-commands.c new file +2
-0+ + read_count =fread (buf,1 , count, fh);Isn't 'nmemb' and 'size' swapped?
Quoted 7 lines
I'm not sure...
size_tfread(void *ptr, size_t size, size_t nmemb, FILE *stream);I wrote it as $count number of 1-bytes elements. This seems logical to me, since it's a non-blocking FD which way result in a partial of some lesser number of bytes than count.
Ok. I think either way will work.
Quoted 49 lines
Quoted 48 lines
Quoted 35 lines
qga/guest-agent-commands.c new file +34
-0+ buf[read_count] =0 ; + read_data->count = read_count; + read_data->eof =feof (fh); +if (read_count) { + read_data->buf =g_base64_encode (buf, read_count); + } +qemu_free (buf); +/* clear error and eof. error is generally due to EAGAIN from non-blocking +* mode, and no real way to differenitate from a real error since we only +* get boolean error flag from ferror() +*/ +clearerr (fh); + +return read_data; +} + +GuestFileWrite *qmp_guest_file_write (int64_t filehandle,const char *data_b64, +int64_t count,Error **err) +{ +GuestFileWrite *write_data; +guchar *data; +gsize data_len; +int write_count; +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +FILE *fh; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + + fh = gfh->fh; + data =g_base64_decode (data_b64,&data_len); +if (count> data_len) {qga/guest-agent-commands.c line 244
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+qemu_free (data); +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + } + write_data =qemu_mallocz (sizeof (GuestFileWrite)); + write_count =fwrite (data,1 , count, fh); + write_data->count = write_count; + write_data->eof =feof (fh); +qemu_free (data); +clearerr (fh);Shouldn't we check for errors instead of doing this?
Quoted 6 lines
Quoted 3 lines
Yah...unfortunately we only get a boolean flag with
ferror()so it's not all that useful, but I can add an error flag to the calls to capture it at least.clearerr()is only being used here to clear the eof flag.I meant to check fwrite()'s return.
Ahh, right. Definitely.
Quoted 219 lines
Quoted 38 lines
Quoted 4 lines
Btw, I think it's a good idea to offer guest-file-flush() too (or do a
flush()here, but that's probably bad).Yah, I'd been planning on adding a guest-file-flush() for a while now. I'll add that for the respin.
Quoted 30 lines
Quoted 18 lines
qga/guest-agent-commands.c new file +18
-0+ +return write_data; +} + +struct GuestFileSeek *qmp_guest_file_seek (int64_t filehandle,int64_t offset, +int64_t whence,Error **err) +{ +GuestFileSeek *seek_data; +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +FILE *fh; +int ret; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + + fh = gfh->fh;qga/guest-agent-commands.c line 272
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ seek_data =qemu_mallocz (sizeof (GuestFileRead)); + ret =fseek (fh, offset, whence); +if (ret ==-1 ) { +error_set (err,QERR_UNDEFINED_ERROR ); +qemu_free (seek_data); +return NULL ; + } + seek_data->position =ftell (fh); + seek_data->eof =feof (fh); +clearerr (fh);Again, I don't see why we should do this.
This is probably ok, as we're checking
fseek()above.Quoted 178 lines
Quoted 77 lines
Quoted 77 lines
qga/guest-agent-commands.c new file +76
-0+ +return seek_data; +} + +void qmp_guest_file_close (int64_t filehandle,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (filehandle); + +slog ("guest-file-close called, filehandle: %ld" , filehandle); +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return ; + } + +fclose (gfh->fh); +QTAILQ_REMOVE (&guest_file_state.filehandles, gfh, next); +qemu_free (gfh); +} + +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; + + fp =setmntent (mtab,"r" ); +if (!fp) { +g_warning ("fsfreeze: unable to read mtab" ); + goto fail; + } + +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 ; + +fail:Quoted 9 lines
qga/guest-agent-commands.c line 354
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); + }This doesn't seem to be used.
It can get used even a 2nd invocation of this function gets called that results in a goto fail. But looking again this should be done unconditionally at the start of the function, since the mount list is part of global state now.
Quoted 85 lines
Quoted 15 lines
qga/guest-agent-commands.c new file +15
-0+ +return -1 ; +} + +/* +* 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. qga/guest-agent-commands.c line 379
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+*/ +int64_t qmp_guest_fsfreeze_freeze (Error **err) +{ +int ret =0 , i =0 ; +struct GuestFsfreezeMount *mount, *temp; +int fd; + +slog ("guest-fsfreeze called" ); + +if (guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_THAWED ) {return 0;
qga/guest-agent-commands.c
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+ ret =0 ; + goto out; + } + + ret =guest_fsfreeze_build_mount_list (); +if (ret<0 ) {return ret;
Quoted 33 lines
qga/guest-agent-commands.c new file +33
-0+ goto out; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_INPROGRESS ; + +/* 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 ) { + ret = errno; + 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 reason 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 ) { +close (fd); + goto error; + } +close (fd); + + i++;qga/guest-agent-commands.c line 428
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_FROZEN ; + ret = i; +out: +return ret; +error: +if (i>0 ) { + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_ERROR ; + }Shouldn't you undo everything that has been done so far? Which is freeing the build list and thawing the file-systems that were frozen before the error?
Quoted 8 lines
Quoted 4 lines
We can...the way it's done right now is you get a count of how many filesystems were frozen, along an error status. Depending on the error/count the user can either ignore the error, do what it is they want to do, then call
thaw(), or just immediately callthaw().But you don't get the count on error, so it's difficult (if possible) to learn how many file-systems were frozen.
Yah, my mistake. I think the out: label was one line higher, but if we did that we lose error information. Automatically unfreezing should be okay.
Quoted 111 lines
Quoted 110 lines
So we can do an automatic
thaw()on their behalf, but i figured the status was good enough.Quoted 8 lines
Quoted 8 lines
qga/guest-agent-commands.c new file +8
-0+ goto out; +} + +/* +* Walk list of frozen file systems in the guest, and thaw them. +*/ +int64_t qmp_guest_fsfreeze_thaw (Error **err) +{Quoted 9 lines
qga/guest-agent-commands.c line 442
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+int ret; +GuestFsfreezeMount *mount, *temp; +int fd, i =0 ; + +if (guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_FROZEN && + guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_INPROGRESS ) {I don't follow why we're checking against INPROGRESS here.
To prevent a race I believe...but we're synchronous now so that's probably no longer needed. I'll look it over and remove it if that's the case.
Quoted 16 lines
Quoted 5 lines
qga/guest-agent-commands.c new file +5
-0+ ret =0 ; + goto out_enable_logging; + } + + QTAILQ_FOREACH_SAFE(mount,&guest_fsfreeze_state.mount_list, next, temp) {qga/guest-agent-commands.c line 457
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ fd =qemu_open (mount->dirname,O_RDONLY ); +if (fd ==-1 ) { + ret = -errno; + goto out; + } + ret =ioctl (fd,FITHAW ); +if (ret<0 && errno !=EOPNOTSUPP && errno !=EINVAL ) { + ret = -errno; +close (fd); + goto out;Quoted 2 lines
Shouldn't you continue and try to thaw the other file-systems in the list?
That's probably better
Quoted 62 lines
Quoted 61 lines
qga/guest-agent-commands.c new file +44
-0+ } +close (fd); + +QTAILQ_REMOVE (&guest_fsfreeze_state.mount_list, mount, next); +qemu_free (mount->dirname); +qemu_free (mount->devtype); +qemu_free (mount); + i++; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_THAWED ; + ret = i; +out_enable_logging: +enable_logging (); +out: +return ret; +} + +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_LIMIT 4<< 20/* 4MB block size max for chunked reads */ typedef 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 v6 4/4] guest agent: add guest agent RPCs/commands
Quoted 347 lines · Luiz Capitulino
Quoted 344 lines · On Mon, 11 Jul 2011 18:11:21 -0500 Michael Roth<[email protected]>…
Quoted 342 lines · Luiz Capitulino
Quoted 326 lines · On Mon, 11 Jul 2011 15:11:26 -0500 Michael Roth<[email protected]>…
Quoted 218 lines · Luiz Capitulino
Quoted 201 lines · On Tue, 5 Jul 2011 08:21:40 -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-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=qga0 ... echo "{'execute':'guest-info'}" | socat stdio \ unix-connect:/tmp/qga0.sock guest: qemu-ga -c virtio-serial -p /dev/virtio-ports/qga0 \ -p /var/run/qemu-guest-agent.pid -dSigned-off-by Michael Roth<[email protected]>--- Makefile | 15 ++- qemu-ga.c | 4 + qerror.h | 3 + qga/guest-agent-commands.c | 501 ++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 2 + 5 files changed, 523 insertions(+), 2 deletions(-)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-qmp-marshal.o QEMULIBS=libhw32 libhw64 libuser libdis libdis-userqemu-ga.c +4
-0@@ -637,6 +637,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 );@@ -645,6 +648,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.h +3
-0@@ -184,4 +184,7 @@ QError *qobject_to_qerror(const QObject *obj);#define QERR_FEATURE_DISABLED \ "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }" +#define QERR_QGA_LOGGING_FAILED \ + "{ 'class': 'QgaLoggingFailed', 'data': {} }" +#endif /* QERROR_H */ qga/guest-agent-commands.c new file +84
-0@@ -0,0 +1,501 @@ +/* +* 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 (const char *mode,Error **err) +{ +int ret; +const char *shutdown_flag; + +slog ("guest-shutdown called, mode: %s" , mode); +if (strcmp (mode,"halt" ) ==0 ) { + shutdown_flag ="-H" ; + }else if (strcmp (mode,"powerdown" ) ==0 ) { + shutdown_flag ="-P" ; + }else if (strcmp (mode,"reboot" ) ==0 ) { + shutdown_flag ="-r" ; + }else { +error_set (err,QERR_INVALID_PARAMETER_VALUE ,"mode" , +"halt|powerdown|reboot" ); +return ; + }qga/guest-agent-commands.c line 94
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ + ret =fork (); +if (ret ==0 ) { +/* child, start the shutdown */ +setsid (); +fclose (stdin); +fclose (stdout); +fclose (stderr); + +sleep (5 );If we're required to return a response before the shutdown happens, this is a bug and I'm afraid that the right way to this is a bit complex.
Quoted 2 lines
Otherwise we can just leave it out.
Yah, I ran this by Anthony and Adam and just leaving it out seems to be the preferred approach, for now at least.
Quoted 101 lines
Quoted 86 lines
qga/guest-agent-commands.c new file +86
-0+ 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 *filepath,bool has_mode,const char *mode,Error **err) +{ +FILE *fh; +int fd; +int64_t ret =-1 ; + +if (!has_mode) { + mode ="r" ; + } +slog ("guest-file-open called, filepath: %s, mode: %s" , filepath, mode); + fh =fopen (filepath, mode); +if (!fh) { +error_set (err,QERR_OPEN_FILE_FAILED , filepath); +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 , filepath); +fclose (fh); +return -1 ; + } + +guest_file_handle_add (fh); +slog ("guest-file-open, filehandle: %d" , fd); +return fd; +} + +struct GuestFileRead *qmp_guest_file_read (int64_t filehandle,int64_t count, +Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +GuestFileRead *read_data; +guchar *buf; +FILE *fh; +size_t read_count;qga/guest-agent-commands.c line 190
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + +if (count<0 || count>QGA_READ_LIMIT ) { +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + }Are we imposing that limit because of the
malloc()call below? If that's the case I think it's wrong, because we don't know the VM (neither the guest) better than the client.Quoted 8 lines
Quoted 4 lines
The best thing we can do here is to limit it to the file size. Additionally to this we could have a command-line option to allow the sysadmin set his/her own limit.
That's technically the better approach, but we're also bound by the maximum token size limit in the JSON parser, which is 64MB. Best we can do is set
QGA_READ_LIMITaccordingly.Good point, but I think it's ok to let the parser do this check itself, as control won't get here anyway. Maybe we should only document that the server imposes a limit on the token size.
Quoted 8 lines
Quoted 3 lines
From a usability perspective I think the
QERR_INVALID_PARAMETER, or
perhaps something more descriptive, is a little nicer. Plus, they won't have to wait for 64MB to get streamed back before they get the error :)That's why I suggested documenting it. Are we going to add this check to all commands that make it more likely to reach the parser's limit? (also note that theoretically all commands can do it).
Good point, and I agree that it needs to be documented either way. Might not hurt to further clarify the limitations this imposes on a command like guest-file-read in the schema documentation where appropriate though.
I'm not sure about the alternative suggestion of bounding this by filesize though, since they may also be writing to the same fd via guest-file-write, and the current file size wouldn't be meaningful except after an fflush() or fclose(). So we'd be forced to fflush() in guest-file-write to implement this somewhat reliably, but I think we agree that a separate guest-file-flush would be better.
So let's just let the client blow up their guest if they're so inclined.
Quoted 431 lines
Quoted 430 lines
Quoted 78 lines
Quoted 19 lines
Quoted 11 lines
qga/guest-agent-commands.c line 198
Quoted 10 lines
qga/guest-agent-commands.c new file +8
-0+ + fh = gfh->fh; + read_data =qemu_mallocz (sizeof (GuestFileRead) +1 ); + buf =qemu_mallocz (count+1 ); +if (!buf) { +error_set (err,QERR_UNDEFINED_ERROR ); +return NULL ; + }Quoted 7 lines
qemu_malloc()functions never fail...qga/guest-agent-commands.c line 200
Quoted 2 lines
qga/guest-agent-commands.c new file +2
-0+ + read_count =fread (buf,1 , count, fh);Isn't 'nmemb' and 'size' swapped?
Quoted 7 lines
I'm not sure...
size_tfread(void *ptr, size_t size, size_t nmemb, FILE *stream);I wrote it as $count number of 1-bytes elements. This seems logical to me, since it's a non-blocking FD which way result in a partial of some lesser number of bytes than count.
Ok. I think either way will work.
Quoted 49 lines
Quoted 48 lines
Quoted 35 lines
qga/guest-agent-commands.c new file +34
-0+ buf[read_count] =0 ; + read_data->count = read_count; + read_data->eof =feof (fh); +if (read_count) { + read_data->buf =g_base64_encode (buf, read_count); + } +qemu_free (buf); +/* clear error and eof. error is generally due to EAGAIN from non-blocking +* mode, and no real way to differenitate from a real error since we only +* get boolean error flag from ferror() +*/ +clearerr (fh); + +return read_data; +} + +GuestFileWrite *qmp_guest_file_write (int64_t filehandle,const char *data_b64, +int64_t count,Error **err) +{ +GuestFileWrite *write_data; +guchar *data; +gsize data_len; +int write_count; +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +FILE *fh; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + + fh = gfh->fh; + data =g_base64_decode (data_b64,&data_len); +if (count> data_len) {qga/guest-agent-commands.c line 244
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+qemu_free (data); +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + } + write_data =qemu_mallocz (sizeof (GuestFileWrite)); + write_count =fwrite (data,1 , count, fh); + write_data->count = write_count; + write_data->eof =feof (fh); +qemu_free (data); +clearerr (fh);Shouldn't we check for errors instead of doing this?
Quoted 6 lines
Quoted 3 lines
Yah...unfortunately we only get a boolean flag with
ferror()so it's not all that useful, but I can add an error flag to the calls to capture it at least.clearerr()is only being used here to clear the eof flag.I meant to check fwrite()'s return.
Ahh, right. Definitely.
Quoted 219 lines
Quoted 38 lines
Quoted 4 lines
Btw, I think it's a good idea to offer guest-file-flush() too (or do a
flush()here, but that's probably bad).Yah, I'd been planning on adding a guest-file-flush() for a while now. I'll add that for the respin.
Quoted 30 lines
Quoted 18 lines
qga/guest-agent-commands.c new file +18
-0+ +return write_data; +} + +struct GuestFileSeek *qmp_guest_file_seek (int64_t filehandle,int64_t offset, +int64_t whence,Error **err) +{ +GuestFileSeek *seek_data; +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +FILE *fh; +int ret; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + + fh = gfh->fh;qga/guest-agent-commands.c line 272
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ seek_data =qemu_mallocz (sizeof (GuestFileRead)); + ret =fseek (fh, offset, whence); +if (ret ==-1 ) { +error_set (err,QERR_UNDEFINED_ERROR ); +qemu_free (seek_data); +return NULL ; + } + seek_data->position =ftell (fh); + seek_data->eof =feof (fh); +clearerr (fh);Again, I don't see why we should do this.
This is probably ok, as we're checking
fseek()above.Quoted 178 lines
Quoted 77 lines
Quoted 77 lines
qga/guest-agent-commands.c new file +76
-0+ +return seek_data; +} + +void qmp_guest_file_close (int64_t filehandle,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (filehandle); + +slog ("guest-file-close called, filehandle: %ld" , filehandle); +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return ; + } + +fclose (gfh->fh); +QTAILQ_REMOVE (&guest_file_state.filehandles, gfh, next); +qemu_free (gfh); +} + +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; + + fp =setmntent (mtab,"r" ); +if (!fp) { +g_warning ("fsfreeze: unable to read mtab" ); + goto fail; + } + +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 ; + +fail:Quoted 9 lines
qga/guest-agent-commands.c line 354
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); + }This doesn't seem to be used.
It can get used even a 2nd invocation of this function gets called that results in a goto fail. But looking again this should be done unconditionally at the start of the function, since the mount list is part of global state now.
Quoted 85 lines
Quoted 15 lines
qga/guest-agent-commands.c new file +15
-0+ +return -1 ; +} + +/* +* 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. qga/guest-agent-commands.c line 379
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+*/ +int64_t qmp_guest_fsfreeze_freeze (Error **err) +{ +int ret =0 , i =0 ; +struct GuestFsfreezeMount *mount, *temp; +int fd; + +slog ("guest-fsfreeze called" ); + +if (guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_THAWED ) {return 0;
qga/guest-agent-commands.c
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+ ret =0 ; + goto out; + } + + ret =guest_fsfreeze_build_mount_list (); +if (ret<0 ) {return ret;
Quoted 33 lines
qga/guest-agent-commands.c new file +33
-0+ goto out; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_INPROGRESS ; + +/* 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 ) { + ret = errno; + 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 reason 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 ) { +close (fd); + goto error; + } +close (fd); + + i++;qga/guest-agent-commands.c line 428
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_FROZEN ; + ret = i; +out: +return ret; +error: +if (i>0 ) { + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_ERROR ; + }Shouldn't you undo everything that has been done so far? Which is freeing the build list and thawing the file-systems that were frozen before the error?
Quoted 8 lines
Quoted 4 lines
We can...the way it's done right now is you get a count of how many filesystems were frozen, along an error status. Depending on the error/count the user can either ignore the error, do what it is they want to do, then call
thaw(), or just immediately callthaw().But you don't get the count on error, so it's difficult (if possible) to learn how many file-systems were frozen.
Yah, my mistake. I think the out: label was one line higher, but if we did that we lose error information. Automatically unfreezing should be okay.
Quoted 111 lines
Quoted 110 lines
So we can do an automatic
thaw()on their behalf, but i figured the status was good enough.Quoted 8 lines
Quoted 8 lines
qga/guest-agent-commands.c new file +8
-0+ goto out; +} + +/* +* Walk list of frozen file systems in the guest, and thaw them. +*/ +int64_t qmp_guest_fsfreeze_thaw (Error **err) +{Quoted 9 lines
qga/guest-agent-commands.c line 442
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+int ret; +GuestFsfreezeMount *mount, *temp; +int fd, i =0 ; + +if (guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_FROZEN && + guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_INPROGRESS ) {I don't follow why we're checking against INPROGRESS here.
To prevent a race I believe...but we're synchronous now so that's probably no longer needed. I'll look it over and remove it if that's the case.
Quoted 16 lines
Quoted 5 lines
qga/guest-agent-commands.c new file +5
-0+ ret =0 ; + goto out_enable_logging; + } + + QTAILQ_FOREACH_SAFE(mount,&guest_fsfreeze_state.mount_list, next, temp) {qga/guest-agent-commands.c line 457
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ fd =qemu_open (mount->dirname,O_RDONLY ); +if (fd ==-1 ) { + ret = -errno; + goto out; + } + ret =ioctl (fd,FITHAW ); +if (ret<0 && errno !=EOPNOTSUPP && errno !=EINVAL ) { + ret = -errno; +close (fd); + goto out;Quoted 2 lines
Shouldn't you continue and try to thaw the other file-systems in the list?
That's probably better
Quoted 62 lines
Quoted 61 lines
qga/guest-agent-commands.c new file +44
-0+ } +close (fd); + +QTAILQ_REMOVE (&guest_fsfreeze_state.mount_list, mount, next); +qemu_free (mount->dirname); +qemu_free (mount->devtype); +qemu_free (mount); + i++; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_THAWED ; + ret = i; +out_enable_logging: +enable_logging (); +out: +return ret; +} + +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_LIMIT 4<< 20/* 4MB block size max for chunked reads */ typedef 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 v6 4/4] guest agent: add guest agent RPCs/commands
Quoted 357 lines · On Tue, 12 Jul 2011 10:44:14 -0500 Michael Roth <[email protected]>…
Quoted 347 lines · Luiz Capitulino
Quoted 344 lines · On Mon, 11 Jul 2011 18:11:21 -0500 Michael Roth<[email protected]>…
Quoted 342 lines · Luiz Capitulino
Quoted 326 lines · On Mon, 11 Jul 2011 15:11:26 -0500 Michael Roth<[email protected]>…
Quoted 218 lines · Luiz Capitulino
Quoted 201 lines · On Tue, 5 Jul 2011 08:21:40 -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-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=qga0 ... echo "{'execute':'guest-info'}" | socat stdio \ unix-connect:/tmp/qga0.sock guest: qemu-ga -c virtio-serial -p /dev/virtio-ports/qga0 \ -p /var/run/qemu-guest-agent.pid -dSigned-off-by Michael Roth<[email protected]>--- Makefile | 15 ++- qemu-ga.c | 4 + qerror.h | 3 + qga/guest-agent-commands.c | 501 ++++++++++++++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 2 + 5 files changed, 523 insertions(+), 2 deletions(-)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-qmp-marshal.o QEMULIBS=libhw32 libhw64 libuser libdis libdis-userqemu-ga.c +4
-0@@ -637,6 +637,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 );@@ -645,6 +648,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.h +3
-0@@ -184,4 +184,7 @@ QError *qobject_to_qerror(const QObject *obj);#define QERR_FEATURE_DISABLED \ "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }" +#define QERR_QGA_LOGGING_FAILED \ + "{ 'class': 'QgaLoggingFailed', 'data': {} }" +#endif /* QERROR_H */ qga/guest-agent-commands.c new file +84
-0@@ -0,0 +1,501 @@ +/* +* 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 (const char *mode,Error **err) +{ +int ret; +const char *shutdown_flag; + +slog ("guest-shutdown called, mode: %s" , mode); +if (strcmp (mode,"halt" ) ==0 ) { + shutdown_flag ="-H" ; + }else if (strcmp (mode,"powerdown" ) ==0 ) { + shutdown_flag ="-P" ; + }else if (strcmp (mode,"reboot" ) ==0 ) { + shutdown_flag ="-r" ; + }else { +error_set (err,QERR_INVALID_PARAMETER_VALUE ,"mode" , +"halt|powerdown|reboot" ); +return ; + }qga/guest-agent-commands.c line 94
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ + ret =fork (); +if (ret ==0 ) { +/* child, start the shutdown */ +setsid (); +fclose (stdin); +fclose (stdout); +fclose (stderr); + +sleep (5 );If we're required to return a response before the shutdown happens, this is a bug and I'm afraid that the right way to this is a bit complex.
Quoted 2 lines
Otherwise we can just leave it out.
Yah, I ran this by Anthony and Adam and just leaving it out seems to be the preferred approach, for now at least.
Quoted 101 lines
Quoted 86 lines
qga/guest-agent-commands.c new file +86
-0+ 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 *filepath,bool has_mode,const char *mode,Error **err) +{ +FILE *fh; +int fd; +int64_t ret =-1 ; + +if (!has_mode) { + mode ="r" ; + } +slog ("guest-file-open called, filepath: %s, mode: %s" , filepath, mode); + fh =fopen (filepath, mode); +if (!fh) { +error_set (err,QERR_OPEN_FILE_FAILED , filepath); +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 , filepath); +fclose (fh); +return -1 ; + } + +guest_file_handle_add (fh); +slog ("guest-file-open, filehandle: %d" , fd); +return fd; +} + +struct GuestFileRead *qmp_guest_file_read (int64_t filehandle,int64_t count, +Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +GuestFileRead *read_data; +guchar *buf; +FILE *fh; +size_t read_count;qga/guest-agent-commands.c line 190
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + +if (count<0 || count>QGA_READ_LIMIT ) { +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + }Are we imposing that limit because of the
malloc()call below? If that's the case I think it's wrong, because we don't know the VM (neither the guest) better than the client.Quoted 8 lines
Quoted 4 lines
The best thing we can do here is to limit it to the file size. Additionally to this we could have a command-line option to allow the sysadmin set his/her own limit.
That's technically the better approach, but we're also bound by the maximum token size limit in the JSON parser, which is 64MB. Best we can do is set
QGA_READ_LIMITaccordingly.Good point, but I think it's ok to let the parser do this check itself, as control won't get here anyway. Maybe we should only document that the server imposes a limit on the token size.
Quoted 8 lines
Quoted 3 lines
From a usability perspective I think the
QERR_INVALID_PARAMETER, or
perhaps something more descriptive, is a little nicer. Plus, they won't have to wait for 64MB to get streamed back before they get the error :)That's why I suggested documenting it. Are we going to add this check to all commands that make it more likely to reach the parser's limit? (also note that theoretically all commands can do it).
Quoted 8 lines
Good point, and I agree that it needs to be documented either way. Might not hurt to further clarify the limitations this imposes on a command like guest-file-read in the schema documentation where appropriate though.
I'm not sure about the alternative suggestion of bounding this by filesize though, since they may also be writing to the same fd via guest-file-write, and the current file size wouldn't be meaningful except after an
fflush()orfclose().
This is just like the OS, the application has to what's doing.
Quoted 3 lines
So we'd be forced to
fflush()in
guest-file-write to implement this somewhat reliably, but I think we agree that a separate guest-file-flush would be better.
Yes.
Quoted 1 line
So let's just let the client blow up their guest if they're so inclined.
Exactly :) I mean, if something like this turns out to be a problem, we'd have to fix it differently IMO.
Quoted 433 lines
Quoted 432 lines
Quoted 431 lines
Quoted 79 lines
Quoted 20 lines
Quoted 12 lines
qga/guest-agent-commands.c line 198
Quoted 11 lines
qga/guest-agent-commands.c new file +8
-0+ + fh = gfh->fh; + read_data =qemu_mallocz (sizeof (GuestFileRead) +1 ); + buf =qemu_mallocz (count+1 ); +if (!buf) { +error_set (err,QERR_UNDEFINED_ERROR ); +return NULL ; + }Quoted 7 lines
qemu_malloc()functions never fail...qga/guest-agent-commands.c line 200
Quoted 2 lines
qga/guest-agent-commands.c new file +2
-0+ + read_count =fread (buf,1 , count, fh);Isn't 'nmemb' and 'size' swapped?
Quoted 7 lines
I'm not sure...
size_tfread(void *ptr, size_t size, size_t nmemb, FILE *stream);I wrote it as $count number of 1-bytes elements. This seems logical to me, since it's a non-blocking FD which way result in a partial of some lesser number of bytes than count.
Ok. I think either way will work.
Quoted 49 lines
Quoted 48 lines
Quoted 35 lines
qga/guest-agent-commands.c new file +34
-0+ buf[read_count] =0 ; + read_data->count = read_count; + read_data->eof =feof (fh); +if (read_count) { + read_data->buf =g_base64_encode (buf, read_count); + } +qemu_free (buf); +/* clear error and eof. error is generally due to EAGAIN from non-blocking +* mode, and no real way to differenitate from a real error since we only +* get boolean error flag from ferror() +*/ +clearerr (fh); + +return read_data; +} + +GuestFileWrite *qmp_guest_file_write (int64_t filehandle,const char *data_b64, +int64_t count,Error **err) +{ +GuestFileWrite *write_data; +guchar *data; +gsize data_len; +int write_count; +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +FILE *fh; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + + fh = gfh->fh; + data =g_base64_decode (data_b64,&data_len); +if (count> data_len) {qga/guest-agent-commands.c line 244
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+qemu_free (data); +error_set (err,QERR_INVALID_PARAMETER ,"count" ); +return NULL ; + } + write_data =qemu_mallocz (sizeof (GuestFileWrite)); + write_count =fwrite (data,1 , count, fh); + write_data->count = write_count; + write_data->eof =feof (fh); +qemu_free (data); +clearerr (fh);Shouldn't we check for errors instead of doing this?
Quoted 6 lines
Quoted 3 lines
Yah...unfortunately we only get a boolean flag with
ferror()so it's not all that useful, but I can add an error flag to the calls to capture it at least.clearerr()is only being used here to clear the eof flag.I meant to check fwrite()'s return.
Ahh, right. Definitely.
Quoted 219 lines
Quoted 38 lines
Quoted 4 lines
Btw, I think it's a good idea to offer guest-file-flush() too (or do a
flush()here, but that's probably bad).Yah, I'd been planning on adding a guest-file-flush() for a while now. I'll add that for the respin.
Quoted 30 lines
Quoted 18 lines
qga/guest-agent-commands.c new file +18
-0+ +return write_data; +} + +struct GuestFileSeek *qmp_guest_file_seek (int64_t filehandle,int64_t offset, +int64_t whence,Error **err) +{ +GuestFileSeek *seek_data; +GuestFileHandle *gfh =guest_file_handle_find (filehandle); +FILE *fh; +int ret; + +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return NULL ; + } + + fh = gfh->fh;qga/guest-agent-commands.c line 272
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ seek_data =qemu_mallocz (sizeof (GuestFileRead)); + ret =fseek (fh, offset, whence); +if (ret ==-1 ) { +error_set (err,QERR_UNDEFINED_ERROR ); +qemu_free (seek_data); +return NULL ; + } + seek_data->position =ftell (fh); + seek_data->eof =feof (fh); +clearerr (fh);Again, I don't see why we should do this.
This is probably ok, as we're checking
fseek()above.Quoted 178 lines
Quoted 77 lines
Quoted 77 lines
qga/guest-agent-commands.c new file +76
-0+ +return seek_data; +} + +void qmp_guest_file_close (int64_t filehandle,Error **err) +{ +GuestFileHandle *gfh =guest_file_handle_find (filehandle); + +slog ("guest-file-close called, filehandle: %ld" , filehandle); +if (!gfh) { +error_set (err,QERR_FD_NOT_FOUND ,"filehandle" ); +return ; + } + +fclose (gfh->fh); +QTAILQ_REMOVE (&guest_file_state.filehandles, gfh, next); +qemu_free (gfh); +} + +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; + + fp =setmntent (mtab,"r" ); +if (!fp) { +g_warning ("fsfreeze: unable to read mtab" ); + goto fail; + } + +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 ; + +fail:Quoted 9 lines
qga/guest-agent-commands.c line 354
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); + }This doesn't seem to be used.
It can get used even a 2nd invocation of this function gets called that results in a goto fail. But looking again this should be done unconditionally at the start of the function, since the mount list is part of global state now.
Quoted 85 lines
Quoted 15 lines
qga/guest-agent-commands.c new file +15
-0+ +return -1 ; +} + +/* +* 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. qga/guest-agent-commands.c line 379
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+*/ +int64_t qmp_guest_fsfreeze_freeze (Error **err) +{ +int ret =0 , i =0 ; +struct GuestFsfreezeMount *mount, *temp; +int fd; + +slog ("guest-fsfreeze called" ); + +if (guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_THAWED ) {return 0;
qga/guest-agent-commands.c line 385
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+ ret =0 ; + goto out; + } + + ret =guest_fsfreeze_build_mount_list (); +if (ret<0 ) {return ret;
Quoted 33 lines
qga/guest-agent-commands.c new file +33
-0+ goto out; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_INPROGRESS ; + +/* 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 ) { + ret = errno; + 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 reason 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 ) { +close (fd); + goto error; + } +close (fd); + + i++;qga/guest-agent-commands.c line 428
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_FROZEN ; + ret = i; +out: +return ret; +error: +if (i>0 ) { + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_ERROR ; + }Shouldn't you undo everything that has been done so far? Which is freeing the build list and thawing the file-systems that were frozen before the error?
Quoted 8 lines
Quoted 4 lines
We can...the way it's done right now is you get a count of how many filesystems were frozen, along an error status. Depending on the error/count the user can either ignore the error, do what it is they want to do, then call
thaw(), or just immediately callthaw().But you don't get the count on error, so it's difficult (if possible) to learn how many file-systems were frozen.
Yah, my mistake. I think the out: label was one line higher, but if we did that we lose error information. Automatically unfreezing should be okay.
Quoted 111 lines
Quoted 110 lines
So we can do an automatic
thaw()on their behalf, but i figured the status was good enough.Quoted 8 lines
Quoted 8 lines
qga/guest-agent-commands.c new file +8
-0+ goto out; +} + +/* +* Walk list of frozen file systems in the guest, and thaw them. +*/ +int64_t qmp_guest_fsfreeze_thaw (Error **err) +{Quoted 9 lines
qga/guest-agent-commands.c line 442
Quoted 6 lines
qga/guest-agent-commands.c new file +6
-0+int ret; +GuestFsfreezeMount *mount, *temp; +int fd, i =0 ; + +if (guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_FROZEN && + guest_fsfreeze_state.status !=GUEST_FSFREEZE_STATUS_INPROGRESS ) {I don't follow why we're checking against INPROGRESS here.
To prevent a race I believe...but we're synchronous now so that's probably no longer needed. I'll look it over and remove it if that's the case.
Quoted 16 lines
Quoted 5 lines
qga/guest-agent-commands.c new file +5
-0+ ret =0 ; + goto out_enable_logging; + } + + QTAILQ_FOREACH_SAFE(mount,&guest_fsfreeze_state.mount_list, next, temp) {qga/guest-agent-commands.c line 457
Quoted 10 lines
qga/guest-agent-commands.c new file +10
-0+ fd =qemu_open (mount->dirname,O_RDONLY ); +if (fd ==-1 ) { + ret = -errno; + goto out; + } + ret =ioctl (fd,FITHAW ); +if (ret<0 && errno !=EOPNOTSUPP && errno !=EINVAL ) { + ret = -errno; +close (fd); + goto out;Quoted 2 lines
Shouldn't you continue and try to thaw the other file-systems in the list?
That's probably better
Quoted 62 lines
Quoted 61 lines
qga/guest-agent-commands.c new file +44
-0+ } +close (fd); + +QTAILQ_REMOVE (&guest_fsfreeze_state.mount_list, mount, next); +qemu_free (mount->dirname); +qemu_free (mount->devtype); +qemu_free (mount); + i++; + } + + guest_fsfreeze_state.status =GUEST_FSFREEZE_STATUS_THAWED ; + ret = i; +out_enable_logging: +enable_logging (); +out: +return ret; +} + +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_LIMIT 4<< 20/* 4MB block size max for chunked reads */ typedef 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 17 lines · Michael Roth
BUILD/USAGE
build:
./configure --target-list=x86_64-softmmu make
make qemu-ga #should be built on|for target gueststart 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=qga \
-device virtio-serial \
-device virtserialport,chardev=qga,name=qga"
Quoted 3 lines
use guest agent:
./qemu-ga -h
./qemu-ga -c virtio-serial -p/dev/virtio-ports/qga
Have we documented any naming convention for virtio serial ports yet ? For both Matahari, and libguestfs we've followed the reverse domain name style naming adopted by things like DBus and AMQP, or language package namespaces. eg
org.libguestfs.channel.0
org.apache.qpid.matahari.0
The '.0' is just in case we find we need to add further channels for each agent later with different usage.
I think this would be a good general naming convention to recommend to app developers in order to avoid naming clashes, and thus think that the QEMU guest agent should use a channel name prefixed with 'org.qemu.' eg perhaps
...
-device virtserialport,chardev=qga,name=org.qemu.guestagent.0"
...
./qemu-ga -c virtio-serial -p /dev/virtio-ports/org.qemu.guestagent.0
Regards,
Daniel
Signature · 4 lines
|: http://berrange.com -o- http://www.flickr.com/photos/dberrange/ :| |: http://libvirt.org -o- http://virt-manager.org :| |: http://autobuild.org -o- http://search.cpan.org/~danberr/ :| |: http://entangle-photo.org -o- http://live.gnome.org/gtk-vnc :|
Quoted 38 lines · Daniel P. Berrange
Quoted 17 lines · Michael Roth
BUILD/USAGE
build:
./configure --target-list=x86_64-softmmu make
make qemu-ga #should be built on|for target gueststart 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=qga \ -device virtio-serial \ -device virtserialport,chardev=qga,name=qga"Quoted 3 lines
use guest agent:
./qemu-ga -h
./qemu-ga -c virtio-serial -p/dev/virtio-ports/qgaHave we documented any naming convention for virtio serial ports yet ? For both Matahari, and libguestfs we've followed the reverse domain name style naming adopted by things like DBus and AMQP, or language package namespaces. eg
org.libguestfs.channel.0
org.apache.qpid.matahari.0The '.0' is just in case we find we need to add further channels for each agent later with different usage.
I think this would be a good general naming convention to recommend to app developers in order to avoid naming clashes, and thus think that the QEMU guest agent should use a channel name prefixed with 'org.qemu.' eg perhaps
Quoted 8 lines
... -device virtserialport,chardev=qga,name=org.qemu.guestagent.0" ... ./qemu-ga -c virtio-serial -p /dev/virtio-ports/org.qemu.guestagent.0Regards,
Daniel
Hi Daniel,
If you don't specify the -p option explicitly, qemu-ga will look for "/dev/virtio-ports/org.qemu.guest_agent"
Adding ".0" would be useful though, so I'll make "/dev/virtio-ports/org.qemu.guest_agent.0" the default, and update any surrounding documentation to encourage that convention.
HI, Michael,
Quoted 91 lines · Michael Roth
This is Set 3/3 of the QAPI+QGA patchsets.
These patches apply on top of qapi-backport-set2-v5, and can also be obtained from:
git://repo.or.cz/qemu/mdroth.gitqapi-backport-set3-v6(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 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
build:
./configure --target-list=x86_64-softmmu make
make qemu-ga #should be built on|for target gueststart 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=qga \
-device virtio-serial \
-device virtserialport,chardev=qga,name=qga"
Quoted 3 lines
use guest agent:
./qemu-ga -h
./qemu-ga -c virtio-serial -p/dev/virtio-ports/qga
Is the above command "./qemu-ga" issued on guest teminal or hypervisor teminal?
Quoted 37 lines
start/use qmp:
mdroth@illuin:~$ sudo socat unix-connect:/tmp/qga.sock readline {"execute":"guest-sync", "arguments":{"id":1234}} {"return": 1234}{"execute":"guest-info"}
{"return": {}}{"execute": "guest-info"}
{"return": {"version": "1.0"}}{"execute":"guest-file-open", "arguments":{"filepath":"/tmp/testqga","mode":"w+"}}
{"return": 0}
{"execute":"guest-file-write", "arguments":{"filehandle":0,"data_b64":"aGVsbG8gd29ybGQhCg==","count":13}} // writes "hello world!\n" {"return": {"count": 13, "eof": false}}{"execute":"guest-file-open", "arguments":{"filepath":"/tmp/testqga","mode":"r"}} {"return": 1}
{"execute":"guest-file-read", "arguments":{"filehandle":1,"count":1024}} {"return": {"buf": "aGVsbG8gd29ybGQhCg==", "count": 13, "eof": true}} {"execute":"guest-file-close","arguments":{"filehandle":1}} {"return": {}}Makefile | 22 +-
configure | 1 +
qapi-schema-guest.json | 202 +++++++++++++
qemu-ga.c | 631 +++++++++++++++++++++++++++++++++++++++qerror.c| 4 +
qerror.h | 3 +qga/guest-agent-command-state.c| 73 +++++qga/guest-agent-commands.c| 522 ++++++++++++++++++++++++++++++++qga/guest-agent-core.h| 30 ++9 files changed, 1483 insertions(+), 5 deletions(-)
Signature · 3 lines
Regards, Zhi Yong Wu
Quoted 94 lines · On Thu, 14 Jul 2011 10:53:51 +0800 Zhi Yong Wu <[email protected]> wrote:
HI, Michael,
Quoted 91 lines · Michael Roth
This is Set 3/3 of the QAPI+QGA patchsets.
These patches apply on top of qapi-backport-set2-v5, and can also be obtained from:
git://repo.or.cz/qemu/mdroth.gitqapi-backport-set3-v6(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 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
build:
./configure --target-list=x86_64-softmmu make
make qemu-ga #should be built on|for target gueststart 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=qga \
-device virtio-serial \
-device virtserialport,chardev=qga,name=qga"
Quoted 4 lines
Quoted 3 lines
use guest agent:
./qemu-ga -h
./qemu-ga -c virtio-serial -p/dev/virtio-ports/qgaIs the above command "./qemu-ga" issued on guest teminal or hypervisor teminal?
In the guest.
Quoted 38 lines
Quoted 38 lines
start/use qmp:
mdroth@illuin:~$ sudo socat unix-connect:/tmp/qga.sock readline {"execute":"guest-sync", "arguments":{"id":1234}} {"return": 1234}{"execute":"guest-info"}
{"return": {}}{"execute": "guest-info"}
{"return": {"version": "1.0"}}{"execute":"guest-file-open", "arguments":{"filepath":"/tmp/testqga","mode":"w+"}}
{"return": 0}
{"execute":"guest-file-write", "arguments":{"filehandle":0,"data_b64":"aGVsbG8gd29ybGQhCg==","count":13}} // writes "hello world!\n" {"return": {"count": 13, "eof": false}}{"execute":"guest-file-open", "arguments":{"filepath":"/tmp/testqga","mode":"r"}} {"return": 1}
{"execute":"guest-file-read", "arguments":{"filehandle":1,"count":1024}} {"return": {"buf": "aGVsbG8gd29ybGQhCg==", "count": 13, "eof": true}} {"execute":"guest-file-close","arguments":{"filehandle":1}} {"return": {}}Makefile | 22 +-
configure | 1 +
qapi-schema-guest.json | 202 +++++++++++++
qemu-ga.c | 631 +++++++++++++++++++++++++++++++++++++++qerror.c| 4 +
qerror.h | 3 +qga/guest-agent-command-state.c| 73 +++++qga/guest-agent-commands.c| 522 ++++++++++++++++++++++++++++++++qga/guest-agent-core.h| 30 ++9 files changed, 1483 insertions(+), 5 deletions(-)
Quoted 97 lines · Luiz Capitulino
Quoted 94 lines · On Thu, 14 Jul 2011 10:53:51 +0800 Zhi Yong Wu <[email protected]> wrote:
HI, Michael,
Quoted 91 lines · Michael Roth
This is Set 3/3 of the QAPI+QGA patchsets.
These patches apply on top of qapi-backport-set2-v5, and can also be obtained from:
git://repo.or.cz/qemu/mdroth.gitqapi-backport-set3-v6(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 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
build:
./configure --target-list=x86_64-softmmu make
make qemu-ga #should be built on|for target gueststart 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=qga \
-device virtio-serial \
-device virtserialport,chardev=qga,name=qga"
Quoted 6 lines
Quoted 4 lines
Quoted 3 lines
use guest agent:
./qemu-ga -h
./qemu-ga -c virtio-serial -p/dev/virtio-ports/qgaIs the above command "./qemu-ga" issued on guest teminal or hypervisor teminal?
In the guest.
Can we make it work similiar as a linux service? It may is more convenient to use.
[root@f12 ~]# service qemu-ga start/stop/status/restart
[root@f12 ~]# chkconfig qemu-ga on/off
Quoted 41 lines
Quoted 39 lines
Quoted 39 lines
start/use qmp:
mdroth@illuin:~$ sudo socat unix-connect:/tmp/qga.sock readline {"execute":"guest-sync", "arguments":{"id":1234}} {"return": 1234}{"execute":"guest-info"}
{"return": {}}{"execute": "guest-info"}
{"return": {"version": "1.0"}}{"execute":"guest-file-open", "arguments":{"filepath":"/tmp/testqga","mode":"w+"}}
{"return": 0}
{"execute":"guest-file-write", "arguments":{"filehandle":0,"data_b64":"aGVsbG8gd29ybGQhCg==","count":13}} // writes "hello world!\n" {"return": {"count": 13, "eof": false}}{"execute":"guest-file-open", "arguments":{"filepath":"/tmp/testqga","mode":"r"}} {"return": 1}
{"execute":"guest-file-read", "arguments":{"filehandle":1,"count":1024}} {"return": {"buf": "aGVsbG8gd29ybGQhCg==", "count": 13, "eof": true}} {"execute":"guest-file-close","arguments":{"filehandle":1}} {"return": {}}Makefile | 22 +-
configure | 1 +
qapi-schema-guest.json | 202 +++++++++++++
qemu-ga.c | 631 +++++++++++++++++++++++++++++++++++++++qerror.c| 4 +
qerror.h | 3 +qga/guest-agent-command-state.c| 73 +++++qga/guest-agent-commands.c| 522 ++++++++++++++++++++++++++++++++qga/guest-agent-core.h| 30 ++9 files changed, 1483 insertions(+), 5 deletions(-)
Signature · 3 lines
Regards, Zhi Yong Wu
Quoted 103 lines · Zhi Yong Wu
Quoted 102 lines · Luiz Capitulino
Quoted 98 lines · On Thu, 14 Jul 2011 10:53:51 +0800 Zhi Yong Wu<[email protected]> wrote:
HI, Michael,
Quoted 91 lines · Michael Roth
This is Set 3/3 of the QAPI+QGA patchsets.
These patches apply on top of qapi-backport-set2-v5, and can also be obtained from:
git://repo.or.cz/qemu/mdroth.gitqapi-backport-set3-v6(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 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
build:
./configure --target-list=x86_64-softmmu make
make qemu-ga #should be built on|for target gueststart 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=qga \
-device virtio-serial \
-device virtserialport,chardev=qga,name=qga"Quoted 3 lines
use guest agent:
./qemu-ga -h
./qemu-ga -c virtio-serial -p/dev/virtio-ports/qgaIs the above command "./qemu-ga" issued on guest teminal or hypervisor teminal?
Quoted 9 lines
Quoted 1 line
In the guest.
Can we make it work similiar as a linux service? It may is more convenient to use.
[root@f12 ~]# service qemu-ga start/stop/status/restart
[root@f12 ~]# chkconfig qemu-ga on/off
Definitely, we need the agent to act as a service to be able to rely on it remaining after restarts and whatnot. We have some init scripts and whatnot for in-house testing/deployment, but this is somewhat distro-dependent and is more of a packaging concern than something for qemu-devel.
Although, if we do deployment via the guest tools ISO that I sent an RFC out for a while back, it may be worthwhile to cover this as part of that discussion since ideally we'd come up with something that Just Works on most distros. I hope to have a prototype of ISO generation scripts out within the next week or so.
Quoted 44 lines
Quoted 41 lines
Quoted 39 lines
Quoted 39 lines
start/use qmp:
mdroth@illuin:~$ sudo socat unix-connect:/tmp/qga.sock readline {"execute":"guest-sync", "arguments":{"id":1234}} {"return": 1234}{"execute":"guest-info"}
{"return": {}}{"execute": "guest-info"}
{"return": {"version": "1.0"}}{"execute":"guest-file-open", "arguments":{"filepath":"/tmp/testqga","mode":"w+"}}
{"return": 0}
{"execute":"guest-file-write", "arguments":{"filehandle":0,"data_b64":"aGVsbG8gd29ybGQhCg==","count":13}} // writes "hello world!\n" {"return": {"count": 13, "eof": false}}{"execute":"guest-file-open", "arguments":{"filepath":"/tmp/testqga","mode":"r"}} {"return": 1}
{"execute":"guest-file-read", "arguments":{"filehandle":1,"count":1024}} {"return": {"buf": "aGVsbG8gd29ybGQhCg==", "count": 13, "eof": true}} {"execute":"guest-file-close","arguments":{"filehandle":1}} {"return": {}}Makefile | 22 +- configure | 1 + qapi-schema-guest.json | 202 +++++++++++++ qemu-ga.c | 631 +++++++++++++++++++++++++++++++++++++++ qerror.c | 4 + qerror.h | 3 + qga/guest-agent-command-state.c | 73 +++++ qga/guest-agent-commands.c | 522 ++++++++++++++++++++++++++++++++ qga/guest-agent-core.h | 30 ++ 9 files changed, 1483 insertions(+), 5 deletions(-)