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 /* Functions to add a string to the current command line. */
110 alloc_cmdline (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;
121 incr_cmdline_size (guestfs_h *g)
125 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
129 add_cmdline (guestfs_h *g, const char *str)
131 if (g->state != CONFIG) {
133 _("command line cannot be altered after qemu subprocess launched"));
137 incr_cmdline_size (g);
138 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
143 guestfs___checkpoint_cmdline (guestfs_h *g)
145 return g->cmdline_size;
149 guestfs___rollback_cmdline (guestfs_h *g, size_t pos)
153 assert (g->cmdline_size >= pos);
155 for (i = pos; i < g->cmdline_size; ++i)
156 free (g->cmdline[i]);
158 g->cmdline_size = pos;
161 /* Internal command to return the command line. */
163 guestfs__debug_cmdline (guestfs_h *g)
170 r = safe_malloc (g, sizeof (char *) * (g->cmdline_size + 1));
171 r[0] = safe_strdup (g, g->qemu); /* g->cmdline[0] is always NULL */
173 for (i = 1; i < g->cmdline_size; ++i)
174 r[i] = safe_strdup (g, g->cmdline[i]);
176 r[g->cmdline_size] = NULL;
178 return r; /* caller frees */
182 guestfs__config (guestfs_h *g,
183 const char *qemu_param, const char *qemu_value)
185 if (qemu_param[0] != '-') {
186 error (g, _("guestfs_config: parameter must begin with '-' character"));
190 /* A bit fascist, but the user will probably break the extra
191 * parameters that we add if they try to set any of these.
193 if (STREQ (qemu_param, "-kernel") ||
194 STREQ (qemu_param, "-initrd") ||
195 STREQ (qemu_param, "-nographic") ||
196 STREQ (qemu_param, "-serial") ||
197 STREQ (qemu_param, "-full-screen") ||
198 STREQ (qemu_param, "-std-vga") ||
199 STREQ (qemu_param, "-vnc")) {
200 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
204 if (add_cmdline (g, qemu_param) != 0) return -1;
206 if (qemu_value != NULL) {
207 if (add_cmdline (g, qemu_value) != 0) return -1;
213 /* cache=off improves reliability in the event of a host crash.
215 * However this option causes qemu to try to open the file with
216 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
217 * So we check if we can open the file with or without O_DIRECT,
218 * and use cache=off (or not) accordingly.
221 test_cache_off (guestfs_h *g, const char *filename)
223 int fd = open (filename, O_RDONLY|O_DIRECT);
229 fd = open (filename, O_RDONLY);
235 perrorf (g, "%s", filename);
239 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
241 valid_format_iface (const char *str)
243 size_t len = strlen (str);
251 if (c != '-' && c != '_' && !c_isalnum (c))
258 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
259 const struct guestfs_add_drive_opts_argv *optargs)
265 if (strchr (filename, ',') != NULL) {
266 error (g, _("filename cannot contain ',' (comma) character"));
270 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
271 ? optargs->readonly : 0;
272 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
273 ? optargs->format : NULL;
274 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
275 ? optargs->iface : DRIVE_IF;
277 if (format && !valid_format_iface (format)) {
278 error (g, _("%s parameter is empty or contains disallowed characters"),
282 if (!valid_format_iface (iface)) {
283 error (g, _("%s parameter is empty or contains disallowed characters"),
288 /* For writable files, see if we can use cache=off. This also
289 * checks for the existence of the file. For readonly we have
290 * to do the check explicitly.
292 int use_cache_off = readonly ? 0 : test_cache_off (g, filename);
293 if (use_cache_off == -1)
297 if (access (filename, F_OK) == -1) {
298 perrorf (g, "%s", filename);
303 /* Construct the final -drive parameter. */
304 size_t len = 64 + strlen (filename) + strlen (iface);
305 if (format) len += strlen (format);
308 snprintf (buf, len, "file=%s%s%s%s%s,if=%s",
310 readonly ? ",snapshot=on" : "",
311 use_cache_off ? ",cache=off" : "",
312 format ? ",format=" : "",
313 format ? format : "",
316 return guestfs__config (g, "-drive", buf);
320 guestfs__add_drive (guestfs_h *g, const char *filename)
322 struct guestfs_add_drive_opts_argv optargs = {
326 return guestfs__add_drive_opts (g, filename, &optargs);
330 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
332 struct guestfs_add_drive_opts_argv optargs = {
333 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
337 return guestfs__add_drive_opts (g, filename, &optargs);
341 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
344 struct guestfs_add_drive_opts_argv optargs = {
345 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
349 return guestfs__add_drive_opts (g, filename, &optargs);
353 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
356 struct guestfs_add_drive_opts_argv optargs = {
357 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
358 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
363 return guestfs__add_drive_opts (g, filename, &optargs);
367 guestfs__add_cdrom (guestfs_h *g, const char *filename)
369 if (strchr (filename, ',') != NULL) {
370 error (g, _("filename cannot contain ',' (comma) character"));
374 if (access (filename, F_OK) == -1) {
375 perrorf (g, "%s", filename);
379 return guestfs__config (g, "-cdrom", filename);
382 static int is_openable (guestfs_h *g, const char *path, int flags);
385 guestfs__launch (guestfs_h *g)
388 if (g->state != CONFIG) {
389 error (g, _("the libguestfs handle has already been launched"));
393 /* Make the temporary directory. */
395 TMP_TEMPLATE_ON_STACK (dir_template);
396 g->tmpdir = safe_strdup (g, dir_template);
397 if (mkdtemp (g->tmpdir) == NULL) {
398 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
403 /* Allow anyone to read the temporary directory. The socket in this
404 * directory won't be readable but anyone can see it exists if they
405 * want. (RHBZ#610880).
407 if (chmod (g->tmpdir, 0755) == -1)
408 warning (g, "chmod: %s: %m (ignored)", g->tmpdir);
410 /* Launch the appliance or attach to an existing daemon. */
411 switch (g->attach_method) {
412 case ATTACH_METHOD_APPLIANCE:
413 return launch_appliance (g);
415 case ATTACH_METHOD_UNIX:
416 return connect_unix_socket (g, g->attach_method_arg);
424 launch_appliance (guestfs_h *g)
428 char guestfsd_sock[256];
429 struct sockaddr_un addr;
431 /* At present you must add drives before starting the appliance. In
432 * future when we enable hotplugging you won't need to do this.
435 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
439 /* Start the clock ... */
440 gettimeofday (&g->launch_t, NULL);
441 guestfs___launch_send_progress (g, 0);
443 /* Locate and/or build the appliance. */
444 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
445 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
448 guestfs___launch_send_progress (g, 3);
451 guestfs___print_timestamped_message (g, "begin testing qemu features");
453 /* Get qemu help text and version. */
454 if (qemu_supports (g, NULL) == -1)
457 /* Using virtio-serial, we need to create a local Unix domain socket
458 * for qemu to connect to.
460 snprintf (guestfsd_sock, sizeof guestfsd_sock, "%s/guestfsd.sock", g->tmpdir);
461 unlink (guestfsd_sock);
463 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
465 perrorf (g, "socket");
469 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
470 perrorf (g, "fcntl");
474 addr.sun_family = AF_UNIX;
475 strncpy (addr.sun_path, guestfsd_sock, UNIX_PATH_MAX);
476 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
478 if (bind (g->sock, &addr, sizeof addr) == -1) {
483 if (listen (g->sock, 1) == -1) {
484 perrorf (g, "listen");
489 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
496 guestfs___print_timestamped_message (g, "finished testing qemu features");
510 if (r == 0) { /* Child (qemu). */
513 /* Set up the full command line. Do this in the subprocess so we
514 * don't need to worry about cleaning up.
517 /* Set g->cmdline[0] to the name of the qemu process. However
518 * it is possible that no g->cmdline has been allocated yet so
519 * we must do that first.
522 g->cmdline[0] = g->qemu;
524 if (qemu_supports (g, "-nodefconfig"))
525 add_cmdline (g, "-nodefconfig");
527 /* The qemu -machine option (added 2010-12) is a bit more sane
528 * since it falls back through various different acceleration
529 * modes, so try that first (thanks Markus Armbruster).
531 if (qemu_supports (g, "-machine")) {
532 add_cmdline (g, "-machine");
533 add_cmdline (g, "accel=kvm:tcg");
535 /* qemu sometimes needs this option to enable hardware
536 * virtualization, but some versions of 'qemu-kvm' will use KVM
537 * regardless (even where this option appears in the help text).
538 * It is rumoured that there are versions of qemu where supplying
539 * this option when hardware virtualization is not available will
540 * cause qemu to fail, so we we have to check at least that
541 * /dev/kvm is openable. That's not reliable, since /dev/kvm
542 * might be openable by qemu but not by us (think: SELinux) in
543 * which case the user would not get hardware virtualization,
544 * although at least shouldn't fail. A giant clusterfuck with the
545 * qemu command line, again.
547 if (qemu_supports (g, "-enable-kvm") &&
548 is_openable (g, "/dev/kvm", O_RDWR))
549 add_cmdline (g, "-enable-kvm");
552 /* Newer versions of qemu (from around 2009/12) changed the
553 * behaviour of monitors so that an implicit '-monitor stdio' is
554 * assumed if we are in -nographic mode and there is no other
555 * -monitor option. Only a single stdio device is allowed, so
556 * this broke the '-serial stdio' option. There is a new flag
557 * called -nodefaults which gets rid of all this default crud, so
558 * let's use that to avoid this and any future surprises.
560 if (qemu_supports (g, "-nodefaults"))
561 add_cmdline (g, "-nodefaults");
563 add_cmdline (g, "-nographic");
565 snprintf (buf, sizeof buf, "%d", g->memsize);
566 add_cmdline (g, "-m");
567 add_cmdline (g, buf);
569 /* Force exit instead of reboot on panic */
570 add_cmdline (g, "-no-reboot");
572 /* These options recommended by KVM developers to improve reliability. */
573 if (qemu_supports (g, "-no-hpet"))
574 add_cmdline (g, "-no-hpet");
576 if (qemu_supports (g, "-rtc-td-hack"))
577 add_cmdline (g, "-rtc-td-hack");
579 /* Create the virtio serial bus. */
580 add_cmdline (g, "-device");
581 add_cmdline (g, "virtio-serial");
584 /* Use virtio-console (a variant form of virtio-serial) for the
585 * guest's serial console.
587 add_cmdline (g, "-chardev");
588 add_cmdline (g, "stdio,id=console");
589 add_cmdline (g, "-device");
590 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
592 /* When the above works ... until then: */
593 add_cmdline (g, "-serial");
594 add_cmdline (g, "stdio");
597 /* Set up virtio-serial for the communications channel. */
598 add_cmdline (g, "-chardev");
599 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
600 add_cmdline (g, buf);
601 add_cmdline (g, "-device");
602 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
604 /* Enable user networking. */
605 if (g->enable_network) {
606 add_cmdline (g, "-netdev");
607 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
608 add_cmdline (g, "-device");
609 add_cmdline (g, NET_IF ",netdev=usernet");
612 #define LINUX_CMDLINE \
613 "panic=1 " /* force kernel to panic if daemon exits */ \
614 "console=ttyS0 " /* serial console */ \
615 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
616 "noapic " /* workaround for RHBZ#502058 - ok if not SMP */ \
617 "no_timer_check " /* fix for RHBZ#502058 */ \
618 "acpi=off " /* we don't need ACPI, turn it off */ \
619 "printk.time=1 " /* display timestamp before kernel messages */ \
620 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
622 /* Linux kernel command line. */
623 snprintf (buf, sizeof buf,
625 "%s " /* (selinux) */
626 "%s " /* (verbose) */
627 "TERM=%s " /* (TERM environment variable) */
629 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
630 g->verbose ? "guestfs_verbose=1" : "",
631 getenv ("TERM") ? : "linux",
632 g->append ? g->append : "");
634 add_cmdline (g, "-kernel");
635 add_cmdline (g, kernel);
636 add_cmdline (g, "-initrd");
637 add_cmdline (g, initrd);
638 add_cmdline (g, "-append");
639 add_cmdline (g, buf);
641 /* Add the ext2 appliance drive (last of all). */
643 const char *cachemode = "";
644 if (qemu_supports (g, "cache=")) {
645 if (qemu_supports (g, "unsafe"))
646 cachemode = ",cache=unsafe";
647 else if (qemu_supports (g, "writeback"))
648 cachemode = ",cache=writeback";
651 char buf2[PATH_MAX + 64];
652 add_cmdline (g, "-drive");
653 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
654 appliance, cachemode);
655 add_cmdline (g, buf2);
658 /* Finish off the command line. */
659 incr_cmdline_size (g);
660 g->cmdline[g->cmdline_size-1] = NULL;
663 /* Set up stdin, stdout, stderr. */
670 if (dup (wfd[0]) == -1) {
672 perror ("dup failed");
673 _exit (EXIT_FAILURE);
676 if (dup (rfd[1]) == -1)
679 /* Particularly since qemu 0.15, qemu spews all sorts of debug
680 * information on stderr. It is useful to both capture this and
681 * not confuse casual users, so send stderr to the pipe as well.
684 if (dup (rfd[1]) == -1)
691 /* Dump the command line (after setting up stderr above). */
693 print_qemu_command_line (g, g->cmdline);
695 /* Put qemu in a new process group. */
699 setenv ("LC_ALL", "C", 1);
701 execv (g->qemu, g->cmdline); /* Run qemu. */
703 _exit (EXIT_FAILURE);
706 /* Parent (library). */
716 /* Fork the recovery process off which will kill qemu if the parent
717 * process fails to do so (eg. if the parent segfaults).
720 if (g->recovery_proc) {
723 pid_t qemu_pid = g->pid;
724 pid_t parent_pid = getppid ();
726 /* It would be nice to be able to put this in the same process
727 * group as qemu (ie. setpgid (0, qemu_pid)). However this is
728 * not possible because we don't have any guarantee here that
729 * the qemu process has started yet.
734 /* Writing to argv is hideously complicated and error prone. See:
735 * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
738 /* Loop around waiting for one or both of the other processes to
739 * disappear. It's fair to say this is very hairy. The PIDs that
740 * we are looking at might be reused by another process. We are
741 * effectively polling. Is the cure worse than the disease?
744 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
745 _exit (EXIT_SUCCESS);
746 if (kill (parent_pid, 0) == -1) {
747 /* Parent's gone away, qemu still around, so kill qemu. */
749 _exit (EXIT_SUCCESS);
755 /* Don't worry, if the fork failed, this will be -1. The recovery
756 * process isn't essential.
762 /* Close the other ends of the pipe. */
766 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
767 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
768 perrorf (g, "fcntl");
772 g->fd[0] = wfd[1]; /* stdin of child */
773 g->fd[1] = rfd[0]; /* stdout of child */
775 g->fd[0] = open ("/dev/null", O_RDWR);
776 if (g->fd[0] == -1) {
777 perrorf (g, "open /dev/null");
780 g->fd[1] = dup (g->fd[0]);
781 if (g->fd[1] == -1) {
788 g->state = LAUNCHING;
790 /* Wait for qemu to start and to connect back to us via
791 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
793 r = guestfs___accept_from_daemon (g);
797 close (g->sock); /* Close the listening socket. */
798 g->sock = r; /* This is the accepted data socket. */
800 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
801 perrorf (g, "fcntl");
807 r = guestfs___recv_from_daemon (g, &size, &buf);
810 if (r == -1) return -1;
812 if (size != GUESTFS_LAUNCH_FLAG) {
813 error (g, _("guestfs_launch failed, see earlier error messages"));
818 guestfs___print_timestamped_message (g, "appliance is up");
820 /* This is possible in some really strange situations, such as
821 * guestfsd starts up OK but then qemu immediately exits. Check for
822 * it because the caller is probably expecting to be able to send
823 * commands after this function returns.
825 if (g->state != READY) {
826 error (g, _("qemu launched and contacted daemon, but state != READY"));
830 guestfs___launch_send_progress (g, 12);
839 if (g->pid > 0) kill (g->pid, 9);
840 if (g->recoverypid > 0) kill (g->recoverypid, 9);
841 if (g->pid > 0) waitpid (g->pid, NULL, 0);
842 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
847 memset (&g->launch_t, 0, sizeof g->launch_t);
861 /* Alternate attach method: instead of launching the appliance,
862 * connect to an existing unix socket.
865 connect_unix_socket (guestfs_h *g, const char *sockpath)
868 struct sockaddr_un addr;
870 /* Start the clock ... */
871 gettimeofday (&g->launch_t, NULL);
873 /* Set these to nothing so we don't try to kill random processes or
874 * read from random file descriptors.
882 guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
884 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
886 perrorf (g, "socket");
890 addr.sun_family = AF_UNIX;
891 strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
892 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
894 g->state = LAUNCHING;
896 if (connect (g->sock, &addr, sizeof addr) == -1) {
901 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
902 perrorf (g, "fcntl");
908 r = guestfs___recv_from_daemon (g, &size, &buf);
911 if (r == -1) return -1;
913 if (size != GUESTFS_LAUNCH_FLAG) {
914 error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
919 guestfs___print_timestamped_message (g, "connected");
921 if (g->state != READY) {
922 error (g, _("contacted guestfsd, but state != READY"));
933 /* launch (of the ordinary appliance) generates approximate progress
934 * messages. Currently these are defined as follows:
936 * 0 / 12: launch clock starts
937 * 3 / 12: appliance created
938 * 6 / 12: detected that guest kernel started
939 * 9 / 12: detected that /init script is running
940 * 12 / 12: launch completed successfully
943 * (1) This is not a documented ABI and the behaviour may be changed
944 * or removed in future.
945 * (2) Messages are only sent if more than 5 seconds has elapsed
946 * since the launch clock started.
947 * (3) There is a gross hack in proto.c to make this work.
950 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
954 gettimeofday (&tv, NULL);
955 if (timeval_diff (&g->launch_t, &tv) >= 5000) {
956 guestfs_progress progress_message =
957 { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
959 guestfs___progress_message_callback (g, &progress_message);
963 /* Return the location of the tmpdir (eg. "/tmp") and allow users
964 * to override it at runtime using $TMPDIR.
965 * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
968 guestfs_tmpdir (void)
978 const char *t = getenv ("TMPDIR");
984 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
985 * allow users to override it at runtime using $TMPDIR.
986 * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
989 guestfs___persistent_tmpdir (void)
995 const char *t = getenv ("TMPDIR");
1001 /* Compute Y - X and return the result in milliseconds.
1002 * Approximately the same as this code:
1003 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1006 timeval_diff (const struct timeval *x, const struct timeval *y)
1010 msec = (y->tv_sec - x->tv_sec) * 1000;
1011 msec += (y->tv_usec - x->tv_usec) / 1000;
1015 /* Note that since this calls 'debug' it should only be called
1016 * from the parent process.
1019 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1026 va_start (args, fs);
1027 err = vasprintf (&msg, fs, args);
1030 if (err < 0) return;
1032 gettimeofday (&tv, NULL);
1034 debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1039 /* This is called from the forked subprocess just before qemu runs, so
1040 * it can just print the message straight to stderr, where it will be
1041 * picked up and funnelled through the usual appliance event API.
1044 print_qemu_command_line (guestfs_h *g, char **argv)
1050 gettimeofday (&tv, NULL);
1051 fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
1054 if (argv[i][0] == '-') /* -option starts a new line */
1055 fprintf (stderr, " \\\n ");
1057 if (i > 0) fputc (' ', stderr);
1059 /* Does it need shell quoting? This only deals with simple cases. */
1060 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
1062 if (needs_quote) fputc ('\'', stderr);
1063 fprintf (stderr, "%s", argv[i]);
1064 if (needs_quote) fputc ('\'', stderr);
1069 static int test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret);
1070 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1072 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1073 * 'qemu -version' so we know what options this qemu supports and
1077 test_qemu (guestfs_h *g)
1082 free (g->qemu_help);
1083 g->qemu_help = NULL;
1084 free (g->qemu_version);
1085 g->qemu_version = NULL;
1087 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1089 /* qemu -help should always work (qemu -version OTOH wasn't
1090 * supported by qemu 0.9). If this command doesn't work then it
1091 * probably indicates that the qemu binary is missing.
1093 if (test_qemu_cmd (g, cmd, &g->qemu_help) == -1) {
1094 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."),
1099 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1102 /* Intentionally ignore errors from qemu -version. */
1103 ignore_value (test_qemu_cmd (g, cmd, &g->qemu_version));
1109 test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret)
1113 fp = popen (cmd, "r");
1117 if (read_all (g, fp, ret) == -1) {
1122 if (pclose (fp) != 0)
1129 read_all (guestfs_h *g, FILE *fp, char **ret)
1136 *ret = safe_realloc (g, *ret, n + 1);
1141 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1143 r = fread (p, 1, BUFSIZ, fp);
1145 perrorf (g, "read");
1152 /* Test if option is supported by qemu command line (just by grepping
1155 * The first time this is used, it has to run the external qemu
1156 * binary. If that fails, it returns -1.
1158 * To just do the first-time run of the qemu binary, call this with
1159 * option == NULL, in which case it will return -1 if there was an
1163 qemu_supports (guestfs_h *g, const char *option)
1165 if (!g->qemu_help) {
1166 if (test_qemu (g) == -1)
1173 return strstr (g->qemu_help, option) != NULL;
1177 /* As above but using a regex instead of a fixed string. */
1179 qemu_supports_re (guestfs_h *g, const pcre *option_regex)
1181 if (!g->qemu_help) {
1182 if (test_qemu (g) == -1)
1186 return match (g, g->qemu_help, option_regex);
1190 /* Check if a file can be opened. */
1192 is_openable (guestfs_h *g, const char *path, int flags)
1194 int fd = open (path, flags);
1196 debug (g, "is_openable: %s: %m", path);
1203 /* You had to call this function after launch in versions <= 1.0.70,
1204 * but it is now a no-op.
1207 guestfs__wait_ready (guestfs_h *g)
1209 if (g->state != READY) {
1210 error (g, _("qemu has not been launched yet"));
1218 guestfs__kill_subprocess (guestfs_h *g)
1220 if (g->state == CONFIG) {
1221 error (g, _("no subprocess to kill"));
1225 debug (g, "sending SIGTERM to process %d", g->pid);
1227 if (g->pid > 0) kill (g->pid, SIGTERM);
1228 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1233 /* Access current state. */
1235 guestfs__is_config (guestfs_h *g)
1237 return g->state == CONFIG;
1241 guestfs__is_launching (guestfs_h *g)
1243 return g->state == LAUNCHING;
1247 guestfs__is_ready (guestfs_h *g)
1249 return g->state == READY;
1253 guestfs__is_busy (guestfs_h *g)
1255 return g->state == BUSY;
1259 guestfs__get_state (guestfs_h *g)