2 * Copyright (C) 2009-2011 Red Hat Inc.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 #define _BSD_SOURCE /* for mkdtemp, usleep */
34 #include <sys/select.h>
39 #include <rpc/types.h>
46 #ifdef HAVE_SYS_TYPES_H
47 #include <sys/types.h>
50 #ifdef HAVE_SYS_WAIT_H
54 #ifdef HAVE_SYS_SOCKET_H
55 #include <sys/socket.h>
62 #include <arpa/inet.h>
63 #include <netinet/in.h>
66 #include "ignore-value.h"
67 #include "glthread/lock.h"
70 #include "guestfs-internal.h"
71 #include "guestfs-internal-actions.h"
72 #include "guestfs_protocol.h"
74 static int launch_appliance (guestfs_h *g);
75 static int64_t timeval_diff (const struct timeval *x, const struct timeval *y);
76 static void print_qemu_command_line (guestfs_h *g, char **argv);
77 static int connect_unix_socket (guestfs_h *g, const char *sock);
78 static int qemu_supports (guestfs_h *g, const char *option);
81 static int qemu_supports_re (guestfs_h *g, const pcre *option_regex);
83 static void compile_regexps (void) __attribute__((constructor));
84 static void free_regexps (void) __attribute__((destructor));
87 compile_regexps (void)
92 #define COMPILE(re,pattern,options) \
94 re = pcre_compile ((pattern), (options), &err, &offset, NULL); \
96 ignore_value (write (2, err, strlen (err))); \
108 /* Add a string to the current command line. */
110 incr_cmdline_size (guestfs_h *g)
112 if (g->cmdline == NULL) {
113 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
115 g->cmdline = safe_malloc (g, sizeof (char *));
116 g->cmdline[0] = NULL;
120 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
124 add_cmdline (guestfs_h *g, const char *str)
126 if (g->state != CONFIG) {
128 _("command line cannot be altered after qemu subprocess launched"));
132 incr_cmdline_size (g);
133 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
138 guestfs___checkpoint_cmdline (guestfs_h *g)
140 return g->cmdline_size;
144 guestfs___rollback_cmdline (guestfs_h *g, size_t pos)
148 assert (g->cmdline_size >= pos);
150 for (i = pos; i < g->cmdline_size; ++i)
151 free (g->cmdline[i]);
153 g->cmdline_size = pos;
156 /* Internal command to return the command line. */
158 guestfs__debug_cmdline (guestfs_h *g)
163 if (g->cmdline == NULL) {
164 r = safe_malloc (g, sizeof (char *) * 1);
169 r = safe_malloc (g, sizeof (char *) * (g->cmdline_size + 1));
170 r[0] = safe_strdup (g, g->qemu); /* g->cmdline[0] is always NULL */
172 for (i = 1; i < g->cmdline_size; ++i)
173 r[i] = safe_strdup (g, g->cmdline[i]);
175 r[g->cmdline_size] = NULL;
177 return r; /* caller frees */
181 guestfs__config (guestfs_h *g,
182 const char *qemu_param, const char *qemu_value)
184 if (qemu_param[0] != '-') {
185 error (g, _("guestfs_config: parameter must begin with '-' character"));
189 /* A bit fascist, but the user will probably break the extra
190 * parameters that we add if they try to set any of these.
192 if (STREQ (qemu_param, "-kernel") ||
193 STREQ (qemu_param, "-initrd") ||
194 STREQ (qemu_param, "-nographic") ||
195 STREQ (qemu_param, "-serial") ||
196 STREQ (qemu_param, "-full-screen") ||
197 STREQ (qemu_param, "-std-vga") ||
198 STREQ (qemu_param, "-vnc")) {
199 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
203 if (add_cmdline (g, qemu_param) != 0) return -1;
205 if (qemu_value != NULL) {
206 if (add_cmdline (g, qemu_value) != 0) return -1;
212 /* cache=off improves reliability in the event of a host crash.
214 * However this option causes qemu to try to open the file with
215 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
216 * So we check if we can open the file with or without O_DIRECT,
217 * and use cache=off (or not) accordingly.
220 test_cache_off (guestfs_h *g, const char *filename)
222 int fd = open (filename, O_RDONLY|O_DIRECT);
228 fd = open (filename, O_RDONLY);
234 perrorf (g, "%s", filename);
238 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
240 valid_format_iface (const char *str)
242 size_t len = strlen (str);
250 if (c != '-' && c != '_' && !c_isalnum (c))
257 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
258 const struct guestfs_add_drive_opts_argv *optargs)
264 if (strchr (filename, ',') != NULL) {
265 error (g, _("filename cannot contain ',' (comma) character"));
269 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
270 ? optargs->readonly : 0;
271 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
272 ? optargs->format : NULL;
273 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
274 ? optargs->iface : DRIVE_IF;
276 if (format && !valid_format_iface (format)) {
277 error (g, _("%s parameter is empty or contains disallowed characters"),
281 if (!valid_format_iface (iface)) {
282 error (g, _("%s parameter is empty or contains disallowed characters"),
287 /* For writable files, see if we can use cache=off. This also
288 * checks for the existence of the file. For readonly we have
289 * to do the check explicitly.
291 int use_cache_off = readonly ? 0 : test_cache_off (g, filename);
292 if (use_cache_off == -1)
296 if (access (filename, F_OK) == -1) {
297 perrorf (g, "%s", filename);
302 /* Construct the final -drive parameter. */
303 size_t len = 64 + strlen (filename) + strlen (iface);
304 if (format) len += strlen (format);
307 snprintf (buf, len, "file=%s%s%s%s%s,if=%s",
309 readonly ? ",snapshot=on" : "",
310 use_cache_off ? ",cache=off" : "",
311 format ? ",format=" : "",
312 format ? format : "",
315 return guestfs__config (g, "-drive", buf);
319 guestfs__add_drive (guestfs_h *g, const char *filename)
321 struct guestfs_add_drive_opts_argv optargs = {
325 return guestfs__add_drive_opts (g, filename, &optargs);
329 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
331 struct guestfs_add_drive_opts_argv optargs = {
332 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
336 return guestfs__add_drive_opts (g, filename, &optargs);
340 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
343 struct guestfs_add_drive_opts_argv optargs = {
344 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
348 return guestfs__add_drive_opts (g, filename, &optargs);
352 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
355 struct guestfs_add_drive_opts_argv optargs = {
356 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
357 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
362 return guestfs__add_drive_opts (g, filename, &optargs);
366 guestfs__add_cdrom (guestfs_h *g, const char *filename)
368 if (strchr (filename, ',') != NULL) {
369 error (g, _("filename cannot contain ',' (comma) character"));
373 if (access (filename, F_OK) == -1) {
374 perrorf (g, "%s", filename);
378 return guestfs__config (g, "-cdrom", filename);
381 static int is_openable (guestfs_h *g, const char *path, int flags);
384 guestfs__launch (guestfs_h *g)
387 if (g->state != CONFIG) {
388 error (g, _("the libguestfs handle has already been launched"));
392 /* Make the temporary directory. */
394 TMP_TEMPLATE_ON_STACK (dir_template);
395 g->tmpdir = safe_strdup (g, dir_template);
396 if (mkdtemp (g->tmpdir) == NULL) {
397 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
402 /* Allow anyone to read the temporary directory. The socket in this
403 * directory won't be readable but anyone can see it exists if they
404 * want. (RHBZ#610880).
406 if (chmod (g->tmpdir, 0755) == -1)
407 warning (g, "chmod: %s: %m (ignored)", g->tmpdir);
409 /* Launch the appliance or attach to an existing daemon. */
410 switch (g->attach_method) {
411 case ATTACH_METHOD_APPLIANCE:
412 return launch_appliance (g);
414 case ATTACH_METHOD_UNIX:
415 return connect_unix_socket (g, g->attach_method_arg);
423 launch_appliance (guestfs_h *g)
427 char guestfsd_sock[256];
428 struct sockaddr_un addr;
430 /* At present you must add drives before starting the appliance. In
431 * future when we enable hotplugging you won't need to do this.
434 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
438 /* Start the clock ... */
439 gettimeofday (&g->launch_t, NULL);
440 guestfs___launch_send_progress (g, 0);
442 /* Locate and/or build the appliance. */
443 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
444 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
447 guestfs___launch_send_progress (g, 3);
450 guestfs___print_timestamped_message (g, "begin testing qemu features");
452 /* Get qemu help text and version. */
453 if (qemu_supports (g, NULL) == -1)
456 /* Using virtio-serial, we need to create a local Unix domain socket
457 * for qemu to connect to.
459 snprintf (guestfsd_sock, sizeof guestfsd_sock, "%s/guestfsd.sock", g->tmpdir);
460 unlink (guestfsd_sock);
462 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
464 perrorf (g, "socket");
468 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
469 perrorf (g, "fcntl");
473 addr.sun_family = AF_UNIX;
474 strncpy (addr.sun_path, guestfsd_sock, UNIX_PATH_MAX);
475 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
477 if (bind (g->sock, &addr, sizeof addr) == -1) {
482 if (listen (g->sock, 1) == -1) {
483 perrorf (g, "listen");
488 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
495 guestfs___print_timestamped_message (g, "finished testing qemu features");
509 if (r == 0) { /* Child (qemu). */
512 /* Set up the full command line. Do this in the subprocess so we
513 * don't need to worry about cleaning up.
515 g->cmdline[0] = g->qemu;
517 if (qemu_supports (g, "-nodefconfig"))
518 add_cmdline (g, "-nodefconfig");
520 /* The qemu -machine option (added 2010-12) is a bit more sane
521 * since it falls back through various different acceleration
522 * modes, so try that first (thanks Markus Armbruster).
524 if (qemu_supports (g, "-machine")) {
525 add_cmdline (g, "-machine");
526 add_cmdline (g, "accel=kvm:tcg");
528 /* qemu sometimes needs this option to enable hardware
529 * virtualization, but some versions of 'qemu-kvm' will use KVM
530 * regardless (even where this option appears in the help text).
531 * It is rumoured that there are versions of qemu where supplying
532 * this option when hardware virtualization is not available will
533 * cause qemu to fail, so we we have to check at least that
534 * /dev/kvm is openable. That's not reliable, since /dev/kvm
535 * might be openable by qemu but not by us (think: SELinux) in
536 * which case the user would not get hardware virtualization,
537 * although at least shouldn't fail. A giant clusterfuck with the
538 * qemu command line, again.
540 if (qemu_supports (g, "-enable-kvm") &&
541 is_openable (g, "/dev/kvm", O_RDWR))
542 add_cmdline (g, "-enable-kvm");
545 /* Newer versions of qemu (from around 2009/12) changed the
546 * behaviour of monitors so that an implicit '-monitor stdio' is
547 * assumed if we are in -nographic mode and there is no other
548 * -monitor option. Only a single stdio device is allowed, so
549 * this broke the '-serial stdio' option. There is a new flag
550 * called -nodefaults which gets rid of all this default crud, so
551 * let's use that to avoid this and any future surprises.
553 if (qemu_supports (g, "-nodefaults"))
554 add_cmdline (g, "-nodefaults");
556 add_cmdline (g, "-nographic");
558 snprintf (buf, sizeof buf, "%d", g->memsize);
559 add_cmdline (g, "-m");
560 add_cmdline (g, buf);
562 /* Force exit instead of reboot on panic */
563 add_cmdline (g, "-no-reboot");
565 /* These options recommended by KVM developers to improve reliability. */
566 if (qemu_supports (g, "-no-hpet"))
567 add_cmdline (g, "-no-hpet");
569 if (qemu_supports (g, "-rtc-td-hack"))
570 add_cmdline (g, "-rtc-td-hack");
572 /* Create the virtio serial bus. */
573 add_cmdline (g, "-device");
574 add_cmdline (g, "virtio-serial");
577 /* Use virtio-console (a variant form of virtio-serial) for the
578 * guest's serial console.
580 add_cmdline (g, "-chardev");
581 add_cmdline (g, "stdio,id=console");
582 add_cmdline (g, "-device");
583 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
585 /* When the above works ... until then: */
586 add_cmdline (g, "-serial");
587 add_cmdline (g, "stdio");
590 /* Set up virtio-serial for the communications channel. */
591 add_cmdline (g, "-chardev");
592 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
593 add_cmdline (g, buf);
594 add_cmdline (g, "-device");
595 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
597 /* Enable user networking. */
598 if (g->enable_network) {
599 add_cmdline (g, "-netdev");
600 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
601 add_cmdline (g, "-device");
602 add_cmdline (g, NET_IF ",netdev=usernet");
605 #define LINUX_CMDLINE \
606 "panic=1 " /* force kernel to panic if daemon exits */ \
607 "console=ttyS0 " /* serial console */ \
608 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
609 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
610 "acpi=off " /* we don't need ACPI, turn it off */ \
611 "printk.time=1 " /* display timestamp before kernel messages */ \
612 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
614 /* Linux kernel command line. */
615 snprintf (buf, sizeof buf,
617 "%s " /* (selinux) */
618 "%s " /* (verbose) */
619 "TERM=%s " /* (TERM environment variable) */
621 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
622 g->verbose ? "guestfs_verbose=1" : "",
623 getenv ("TERM") ? : "linux",
624 g->append ? g->append : "");
626 add_cmdline (g, "-kernel");
627 add_cmdline (g, kernel);
628 add_cmdline (g, "-initrd");
629 add_cmdline (g, initrd);
630 add_cmdline (g, "-append");
631 add_cmdline (g, buf);
633 /* Add the ext2 appliance drive (last of all). */
635 const char *cachemode = "";
636 if (qemu_supports (g, "cache=")) {
637 if (qemu_supports (g, "unsafe"))
638 cachemode = ",cache=unsafe";
639 else if (qemu_supports (g, "writeback"))
640 cachemode = ",cache=writeback";
643 char buf2[PATH_MAX + 64];
644 add_cmdline (g, "-drive");
645 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
646 appliance, cachemode);
647 add_cmdline (g, buf2);
650 /* Finish off the command line. */
651 incr_cmdline_size (g);
652 g->cmdline[g->cmdline_size-1] = NULL;
655 /* Set up stdin, stdout, stderr. */
662 if (dup (wfd[0]) == -1) {
664 perror ("dup failed");
665 _exit (EXIT_FAILURE);
668 if (dup (rfd[1]) == -1)
671 /* Particularly since qemu 0.15, qemu spews all sorts of debug
672 * information on stderr. It is useful to both capture this and
673 * not confuse casual users, so send stderr to the pipe as well.
676 if (dup (rfd[1]) == -1)
683 /* Dump the command line (after setting up stderr above). */
685 print_qemu_command_line (g, g->cmdline);
687 /* Put qemu in a new process group. */
691 setenv ("LC_ALL", "C", 1);
693 execv (g->qemu, g->cmdline); /* Run qemu. */
695 _exit (EXIT_FAILURE);
698 /* Parent (library). */
708 /* Fork the recovery process off which will kill qemu if the parent
709 * process fails to do so (eg. if the parent segfaults).
712 if (g->recovery_proc) {
715 pid_t qemu_pid = g->pid;
716 pid_t parent_pid = getppid ();
718 /* It would be nice to be able to put this in the same process
719 * group as qemu (ie. setpgid (0, qemu_pid)). However this is
720 * not possible because we don't have any guarantee here that
721 * the qemu process has started yet.
726 /* Writing to argv is hideously complicated and error prone. See:
727 * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
730 /* Loop around waiting for one or both of the other processes to
731 * disappear. It's fair to say this is very hairy. The PIDs that
732 * we are looking at might be reused by another process. We are
733 * effectively polling. Is the cure worse than the disease?
736 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
737 _exit (EXIT_SUCCESS);
738 if (kill (parent_pid, 0) == -1) {
739 /* Parent's gone away, qemu still around, so kill qemu. */
741 _exit (EXIT_SUCCESS);
747 /* Don't worry, if the fork failed, this will be -1. The recovery
748 * process isn't essential.
754 /* Close the other ends of the pipe. */
758 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
759 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
760 perrorf (g, "fcntl");
764 g->fd[0] = wfd[1]; /* stdin of child */
765 g->fd[1] = rfd[0]; /* stdout of child */
767 g->fd[0] = open ("/dev/null", O_RDWR);
768 if (g->fd[0] == -1) {
769 perrorf (g, "open /dev/null");
772 g->fd[1] = dup (g->fd[0]);
773 if (g->fd[1] == -1) {
780 g->state = LAUNCHING;
782 /* Wait for qemu to start and to connect back to us via
783 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
785 r = guestfs___accept_from_daemon (g);
789 close (g->sock); /* Close the listening socket. */
790 g->sock = r; /* This is the accepted data socket. */
792 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
793 perrorf (g, "fcntl");
799 r = guestfs___recv_from_daemon (g, &size, &buf);
802 if (r == -1) return -1;
804 if (size != GUESTFS_LAUNCH_FLAG) {
805 error (g, _("guestfs_launch failed, see earlier error messages"));
810 guestfs___print_timestamped_message (g, "appliance is up");
812 /* This is possible in some really strange situations, such as
813 * guestfsd starts up OK but then qemu immediately exits. Check for
814 * it because the caller is probably expecting to be able to send
815 * commands after this function returns.
817 if (g->state != READY) {
818 error (g, _("qemu launched and contacted daemon, but state != READY"));
822 guestfs___launch_send_progress (g, 12);
831 if (g->pid > 0) kill (g->pid, 9);
832 if (g->recoverypid > 0) kill (g->recoverypid, 9);
833 if (g->pid > 0) waitpid (g->pid, NULL, 0);
834 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
839 memset (&g->launch_t, 0, sizeof g->launch_t);
853 /* Alternate attach method: instead of launching the appliance,
854 * connect to an existing unix socket.
857 connect_unix_socket (guestfs_h *g, const char *sockpath)
860 struct sockaddr_un addr;
862 /* Start the clock ... */
863 gettimeofday (&g->launch_t, NULL);
865 /* Set these to nothing so we don't try to kill random processes or
866 * read from random file descriptors.
874 guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
876 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
878 perrorf (g, "socket");
882 addr.sun_family = AF_UNIX;
883 strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
884 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
886 g->state = LAUNCHING;
888 if (connect (g->sock, &addr, sizeof addr) == -1) {
893 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
894 perrorf (g, "fcntl");
900 r = guestfs___recv_from_daemon (g, &size, &buf);
903 if (r == -1) return -1;
905 if (size != GUESTFS_LAUNCH_FLAG) {
906 error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
911 guestfs___print_timestamped_message (g, "connected");
913 if (g->state != READY) {
914 error (g, _("contacted guestfsd, but state != READY"));
925 /* launch (of the ordinary appliance) generates approximate progress
926 * messages. Currently these are defined as follows:
928 * 0 / 12: launch clock starts
929 * 3 / 12: appliance created
930 * 6 / 12: detected that guest kernel started
931 * 9 / 12: detected that /init script is running
932 * 12 / 12: launch completed successfully
935 * (1) This is not a documented ABI and the behaviour may be changed
936 * or removed in future.
937 * (2) Messages are only sent if more than 5 seconds has elapsed
938 * since the launch clock started.
939 * (3) There is a gross hack in proto.c to make this work.
942 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
946 gettimeofday (&tv, NULL);
947 if (timeval_diff (&g->launch_t, &tv) >= 5000) {
948 guestfs_progress progress_message =
949 { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
951 guestfs___progress_message_callback (g, &progress_message);
955 /* Return the location of the tmpdir (eg. "/tmp") and allow users
956 * to override it at runtime using $TMPDIR.
957 * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
960 guestfs_tmpdir (void)
970 const char *t = getenv ("TMPDIR");
976 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
977 * allow users to override it at runtime using $TMPDIR.
978 * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
981 guestfs___persistent_tmpdir (void)
987 const char *t = getenv ("TMPDIR");
993 /* Compute Y - X and return the result in milliseconds.
994 * Approximately the same as this code:
995 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
998 timeval_diff (const struct timeval *x, const struct timeval *y)
1002 msec = (y->tv_sec - x->tv_sec) * 1000;
1003 msec += (y->tv_usec - x->tv_usec) / 1000;
1007 /* Note that since this calls 'debug' it should only be called
1008 * from the parent process.
1011 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1018 va_start (args, fs);
1019 err = vasprintf (&msg, fs, args);
1022 if (err < 0) return;
1024 gettimeofday (&tv, NULL);
1026 debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1031 /* This is called from the forked subprocess just before qemu runs, so
1032 * it can just print the message straight to stderr, where it will be
1033 * picked up and funnelled through the usual appliance event API.
1036 print_qemu_command_line (guestfs_h *g, char **argv)
1042 gettimeofday (&tv, NULL);
1043 fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
1046 if (argv[i][0] == '-') /* -option starts a new line */
1047 fprintf (stderr, " \\\n ");
1049 if (i > 0) fputc (' ', stderr);
1051 /* Does it need shell quoting? This only deals with simple cases. */
1052 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
1054 if (needs_quote) fputc ('\'', stderr);
1055 fprintf (stderr, "%s", argv[i]);
1056 if (needs_quote) fputc ('\'', stderr);
1061 static int test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret);
1062 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1064 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1065 * 'qemu -version' so we know what options this qemu supports and
1069 test_qemu (guestfs_h *g)
1074 free (g->qemu_help);
1075 g->qemu_help = NULL;
1076 free (g->qemu_version);
1077 g->qemu_version = NULL;
1079 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1081 /* qemu -help should always work (qemu -version OTOH wasn't
1082 * supported by qemu 0.9). If this command doesn't work then it
1083 * probably indicates that the qemu binary is missing.
1085 if (test_qemu_cmd (g, cmd, &g->qemu_help) == -1) {
1086 error (g, _("command failed: %s\n\nIf qemu is located on a non-standard path, try setting the LIBGUESTFS_QEMU\nenvironment variable. There may also be errors printed above."),
1091 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1094 /* Intentionally ignore errors from qemu -version. */
1095 ignore_value (test_qemu_cmd (g, cmd, &g->qemu_version));
1101 test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret)
1105 fp = popen (cmd, "r");
1109 if (read_all (g, fp, ret) == -1) {
1114 if (pclose (fp) != 0)
1121 read_all (guestfs_h *g, FILE *fp, char **ret)
1128 *ret = safe_realloc (g, *ret, n + 1);
1133 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1135 r = fread (p, 1, BUFSIZ, fp);
1137 perrorf (g, "read");
1144 /* Test if option is supported by qemu command line (just by grepping
1147 * The first time this is used, it has to run the external qemu
1148 * binary. If that fails, it returns -1.
1150 * To just do the first-time run of the qemu binary, call this with
1151 * option == NULL, in which case it will return -1 if there was an
1155 qemu_supports (guestfs_h *g, const char *option)
1157 if (!g->qemu_help) {
1158 if (test_qemu (g) == -1)
1165 return strstr (g->qemu_help, option) != NULL;
1169 /* As above but using a regex instead of a fixed string. */
1171 qemu_supports_re (guestfs_h *g, const pcre *option_regex)
1173 if (!g->qemu_help) {
1174 if (test_qemu (g) == -1)
1178 return match (g, g->qemu_help, option_regex);
1182 /* Check if a file can be opened. */
1184 is_openable (guestfs_h *g, const char *path, int flags)
1186 int fd = open (path, flags);
1188 debug (g, "is_openable: %s: %m", path);
1195 /* You had to call this function after launch in versions <= 1.0.70,
1196 * but it is now a no-op.
1199 guestfs__wait_ready (guestfs_h *g)
1201 if (g->state != READY) {
1202 error (g, _("qemu has not been launched yet"));
1210 guestfs__kill_subprocess (guestfs_h *g)
1212 if (g->state == CONFIG) {
1213 error (g, _("no subprocess to kill"));
1217 debug (g, "sending SIGTERM to process %d", g->pid);
1219 if (g->pid > 0) kill (g->pid, SIGTERM);
1220 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1225 /* Access current state. */
1227 guestfs__is_config (guestfs_h *g)
1229 return g->state == CONFIG;
1233 guestfs__is_launching (guestfs_h *g)
1235 return g->state == LAUNCHING;
1239 guestfs__is_ready (guestfs_h *g)
1241 return g->state == READY;
1245 guestfs__is_busy (guestfs_h *g)
1247 return g->state == BUSY;
1251 guestfs__get_state (guestfs_h *g)