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_drives (guestfs_h *g)
145 struct drive **i = &g->drives;
146 while (*i != NULL) i = &((*i)->next);
151 guestfs___rollback_drives (guestfs_h *g, struct drive **i)
153 guestfs___free_drives(i);
156 /* Internal command to return the command line. */
158 guestfs__debug_cmdline (guestfs_h *g)
165 r = safe_malloc (g, sizeof (char *) * (g->cmdline_size + 1));
166 r[0] = safe_strdup (g, g->qemu); /* g->cmdline[0] is always NULL */
168 for (i = 1; i < g->cmdline_size; ++i)
169 r[i] = safe_strdup (g, g->cmdline[i]);
171 r[g->cmdline_size] = NULL;
173 return r; /* caller frees */
176 /* Internal command to return the list of drives. */
178 guestfs__debug_drives (guestfs_h *g)
184 for (count = 0, drv = g->drives; drv; count++, drv = drv->next)
187 ret = safe_malloc (g, sizeof (char *) * (count + 1));
189 for (i = 0, drv = g->drives; drv; i++, drv = drv->next) {
190 size_t len = 64 + strlen (drv->path) + strlen (drv->iface);
191 if (drv->format) len += strlen (drv->format);
193 ret[i] = safe_malloc (g, len);
195 snprintf (ret[i], len, "file=%s%s%s%s%s,if=%s",
197 drv->readonly ? ",snapshot=on" : "",
198 drv->use_cache_off ? ",cache=off" : "",
199 drv->format ? ",format=" : "",
200 drv->format ? drv->format : "",
206 return ret; /* caller frees */
210 guestfs__config (guestfs_h *g,
211 const char *qemu_param, const char *qemu_value)
213 if (qemu_param[0] != '-') {
214 error (g, _("guestfs_config: parameter must begin with '-' character"));
218 /* A bit fascist, but the user will probably break the extra
219 * parameters that we add if they try to set any of these.
221 if (STREQ (qemu_param, "-kernel") ||
222 STREQ (qemu_param, "-initrd") ||
223 STREQ (qemu_param, "-nographic") ||
224 STREQ (qemu_param, "-serial") ||
225 STREQ (qemu_param, "-full-screen") ||
226 STREQ (qemu_param, "-std-vga") ||
227 STREQ (qemu_param, "-vnc")) {
228 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
232 if (add_cmdline (g, qemu_param) != 0) return -1;
234 if (qemu_value != NULL) {
235 if (add_cmdline (g, qemu_value) != 0) return -1;
241 /* cache=off improves reliability in the event of a host crash.
243 * However this option causes qemu to try to open the file with
244 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
245 * So we check if we can open the file with or without O_DIRECT,
246 * and use cache=off (or not) accordingly.
249 test_cache_off (guestfs_h *g, const char *filename)
251 int fd = open (filename, O_RDONLY|O_DIRECT);
257 fd = open (filename, O_RDONLY);
263 perrorf (g, "%s", filename);
267 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
269 valid_format_iface (const char *str)
271 size_t len = strlen (str);
279 if (c != '-' && c != '_' && !c_isalnum (c))
286 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
287 const struct guestfs_add_drive_opts_argv *optargs)
294 if (strchr (filename, ',') != NULL) {
295 error (g, _("filename cannot contain ',' (comma) character"));
299 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
300 ? optargs->readonly : 0;
301 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
302 ? safe_strdup (g, optargs->format) : NULL;
303 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
304 ? safe_strdup (g, optargs->iface) : safe_strdup (g, DRIVE_IF);
306 if (format && !valid_format_iface (format)) {
307 error (g, _("%s parameter is empty or contains disallowed characters"),
313 if (!valid_format_iface (iface)) {
314 error (g, _("%s parameter is empty or contains disallowed characters"),
321 /* For writable files, see if we can use cache=off. This also
322 * checks for the existence of the file. For readonly we have
323 * to do the check explicitly.
325 use_cache_off = readonly ? 0 : test_cache_off (g, filename);
326 if (use_cache_off == -1) {
333 if (access (filename, F_OK) == -1) {
334 perrorf (g, "%s", filename);
341 struct drive **i = &(g->drives);
342 while (*i != NULL) i = &((*i)->next);
344 *i = safe_malloc (g, sizeof (struct drive));
346 (*i)->path = safe_strdup (g, filename);
347 (*i)->readonly = readonly;
348 (*i)->format = format;
350 (*i)->use_cache_off = use_cache_off;
356 guestfs__add_drive (guestfs_h *g, const char *filename)
358 struct guestfs_add_drive_opts_argv optargs = {
362 return guestfs__add_drive_opts (g, filename, &optargs);
366 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
368 struct guestfs_add_drive_opts_argv optargs = {
369 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
373 return guestfs__add_drive_opts (g, filename, &optargs);
377 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
380 struct guestfs_add_drive_opts_argv optargs = {
381 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
385 return guestfs__add_drive_opts (g, filename, &optargs);
389 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
392 struct guestfs_add_drive_opts_argv optargs = {
393 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
394 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
399 return guestfs__add_drive_opts (g, filename, &optargs);
403 guestfs__add_cdrom (guestfs_h *g, const char *filename)
405 if (strchr (filename, ',') != NULL) {
406 error (g, _("filename cannot contain ',' (comma) character"));
410 if (access (filename, F_OK) == -1) {
411 perrorf (g, "%s", filename);
415 return guestfs__config (g, "-cdrom", filename);
418 static int is_openable (guestfs_h *g, const char *path, int flags);
421 guestfs__launch (guestfs_h *g)
424 if (g->state != CONFIG) {
425 error (g, _("the libguestfs handle has already been launched"));
429 TRACE0 (launch_start);
431 /* Make the temporary directory. */
433 TMP_TEMPLATE_ON_STACK (dir_template);
434 g->tmpdir = safe_strdup (g, dir_template);
435 if (mkdtemp (g->tmpdir) == NULL) {
436 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
441 /* Allow anyone to read the temporary directory. The socket in this
442 * directory won't be readable but anyone can see it exists if they
443 * want. (RHBZ#610880).
445 if (chmod (g->tmpdir, 0755) == -1)
446 warning (g, "chmod: %s: %m (ignored)", g->tmpdir);
448 /* Launch the appliance or attach to an existing daemon. */
449 switch (g->attach_method) {
450 case ATTACH_METHOD_APPLIANCE:
451 return launch_appliance (g);
453 case ATTACH_METHOD_UNIX:
454 return connect_unix_socket (g, g->attach_method_arg);
462 launch_appliance (guestfs_h *g)
466 char guestfsd_sock[256];
467 struct sockaddr_un addr;
469 /* At present you must add drives before starting the appliance. In
470 * future when we enable hotplugging you won't need to do this.
473 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
477 /* Start the clock ... */
478 gettimeofday (&g->launch_t, NULL);
479 guestfs___launch_send_progress (g, 0);
481 TRACE0 (launch_build_appliance_start);
483 /* Locate and/or build the appliance. */
484 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
485 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
488 TRACE0 (launch_build_appliance_end);
490 guestfs___launch_send_progress (g, 3);
493 guestfs___print_timestamped_message (g, "begin testing qemu features");
495 /* Get qemu help text and version. */
496 if (qemu_supports (g, NULL) == -1)
499 /* Using virtio-serial, we need to create a local Unix domain socket
500 * for qemu to connect to.
502 snprintf (guestfsd_sock, sizeof guestfsd_sock, "%s/guestfsd.sock", g->tmpdir);
503 unlink (guestfsd_sock);
505 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
507 perrorf (g, "socket");
511 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
512 perrorf (g, "fcntl");
516 addr.sun_family = AF_UNIX;
517 strncpy (addr.sun_path, guestfsd_sock, UNIX_PATH_MAX);
518 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
520 if (bind (g->sock, &addr, sizeof addr) == -1) {
525 if (listen (g->sock, 1) == -1) {
526 perrorf (g, "listen");
531 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
538 guestfs___print_timestamped_message (g, "finished testing qemu features");
552 if (r == 0) { /* Child (qemu). */
555 /* Set up the full command line. Do this in the subprocess so we
556 * don't need to worry about cleaning up.
559 /* Set g->cmdline[0] to the name of the qemu process. However
560 * it is possible that no g->cmdline has been allocated yet so
561 * we must do that first.
564 g->cmdline[0] = g->qemu;
567 struct drive *i = g->drives;
569 /* Construct the final -drive parameter. */
570 size_t len = 64 + strlen (i->path) + strlen (i->iface);
571 if (i->format) len += strlen (i->format);
574 snprintf (buf, len, "file=%s%s%s%s%s,if=%s",
576 i->readonly ? ",snapshot=on" : "",
577 i->use_cache_off ? ",cache=off" : "",
578 i->format ? ",format=" : "",
579 i->format ? i->format : "",
582 add_cmdline (g, "-drive");
583 add_cmdline (g, buf);
588 if (qemu_supports (g, "-nodefconfig"))
589 add_cmdline (g, "-nodefconfig");
591 /* The qemu -machine option (added 2010-12) is a bit more sane
592 * since it falls back through various different acceleration
593 * modes, so try that first (thanks Markus Armbruster).
595 if (qemu_supports (g, "-machine")) {
596 add_cmdline (g, "-machine");
597 add_cmdline (g, "accel=kvm:tcg");
599 /* qemu sometimes needs this option to enable hardware
600 * virtualization, but some versions of 'qemu-kvm' will use KVM
601 * regardless (even where this option appears in the help text).
602 * It is rumoured that there are versions of qemu where supplying
603 * this option when hardware virtualization is not available will
604 * cause qemu to fail, so we we have to check at least that
605 * /dev/kvm is openable. That's not reliable, since /dev/kvm
606 * might be openable by qemu but not by us (think: SELinux) in
607 * which case the user would not get hardware virtualization,
608 * although at least shouldn't fail. A giant clusterfuck with the
609 * qemu command line, again.
611 if (qemu_supports (g, "-enable-kvm") &&
612 is_openable (g, "/dev/kvm", O_RDWR))
613 add_cmdline (g, "-enable-kvm");
616 /* Newer versions of qemu (from around 2009/12) changed the
617 * behaviour of monitors so that an implicit '-monitor stdio' is
618 * assumed if we are in -nographic mode and there is no other
619 * -monitor option. Only a single stdio device is allowed, so
620 * this broke the '-serial stdio' option. There is a new flag
621 * called -nodefaults which gets rid of all this default crud, so
622 * let's use that to avoid this and any future surprises.
624 if (qemu_supports (g, "-nodefaults"))
625 add_cmdline (g, "-nodefaults");
627 add_cmdline (g, "-nographic");
630 snprintf (buf, sizeof buf, "%d", g->smp);
631 add_cmdline (g, "-smp");
632 add_cmdline (g, buf);
635 snprintf (buf, sizeof buf, "%d", g->memsize);
636 add_cmdline (g, "-m");
637 add_cmdline (g, buf);
639 /* Force exit instead of reboot on panic */
640 add_cmdline (g, "-no-reboot");
642 /* These options recommended by KVM developers to improve reliability. */
643 if (qemu_supports (g, "-no-hpet"))
644 add_cmdline (g, "-no-hpet");
646 if (qemu_supports (g, "-rtc-td-hack"))
647 add_cmdline (g, "-rtc-td-hack");
649 /* Create the virtio serial bus. */
650 add_cmdline (g, "-device");
651 add_cmdline (g, "virtio-serial");
654 /* Use virtio-console (a variant form of virtio-serial) for the
655 * guest's serial console.
657 add_cmdline (g, "-chardev");
658 add_cmdline (g, "stdio,id=console");
659 add_cmdline (g, "-device");
660 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
662 /* When the above works ... until then: */
663 add_cmdline (g, "-serial");
664 add_cmdline (g, "stdio");
667 /* Set up virtio-serial for the communications channel. */
668 add_cmdline (g, "-chardev");
669 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
670 add_cmdline (g, buf);
671 add_cmdline (g, "-device");
672 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
674 /* Enable user networking. */
675 if (g->enable_network) {
676 add_cmdline (g, "-netdev");
677 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
678 add_cmdline (g, "-device");
679 add_cmdline (g, NET_IF ",netdev=usernet");
682 #define LINUX_CMDLINE \
683 "panic=1 " /* force kernel to panic if daemon exits */ \
684 "console=ttyS0 " /* serial console */ \
685 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
686 "no_timer_check " /* fix for RHBZ#502058 */ \
687 "acpi=off " /* we don't need ACPI, turn it off */ \
688 "printk.time=1 " /* display timestamp before kernel messages */ \
689 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
691 /* Linux kernel command line. */
692 snprintf (buf, sizeof buf,
694 "%s " /* (selinux) */
695 "%s " /* (verbose) */
696 "TERM=%s " /* (TERM environment variable) */
698 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
699 g->verbose ? "guestfs_verbose=1" : "",
700 getenv ("TERM") ? : "linux",
701 g->append ? g->append : "");
703 add_cmdline (g, "-kernel");
704 add_cmdline (g, kernel);
705 add_cmdline (g, "-initrd");
706 add_cmdline (g, initrd);
707 add_cmdline (g, "-append");
708 add_cmdline (g, buf);
710 /* Add the ext2 appliance drive (last of all). */
712 const char *cachemode = "";
713 if (qemu_supports (g, "cache=")) {
714 if (qemu_supports (g, "unsafe"))
715 cachemode = ",cache=unsafe";
716 else if (qemu_supports (g, "writeback"))
717 cachemode = ",cache=writeback";
720 char buf2[PATH_MAX + 64];
721 add_cmdline (g, "-drive");
722 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
723 appliance, cachemode);
724 add_cmdline (g, buf2);
727 /* Finish off the command line. */
728 incr_cmdline_size (g);
729 g->cmdline[g->cmdline_size-1] = NULL;
732 /* Set up stdin, stdout, stderr. */
739 if (dup (wfd[0]) == -1) {
741 perror ("dup failed");
742 _exit (EXIT_FAILURE);
745 if (dup (rfd[1]) == -1)
748 /* Particularly since qemu 0.15, qemu spews all sorts of debug
749 * information on stderr. It is useful to both capture this and
750 * not confuse casual users, so send stderr to the pipe as well.
753 if (dup (rfd[1]) == -1)
760 /* Dump the command line (after setting up stderr above). */
762 print_qemu_command_line (g, g->cmdline);
764 /* Put qemu in a new process group. */
768 setenv ("LC_ALL", "C", 1);
770 TRACE0 (launch_run_qemu);
772 execv (g->qemu, g->cmdline); /* Run qemu. */
774 _exit (EXIT_FAILURE);
777 /* Parent (library). */
787 /* Fork the recovery process off which will kill qemu if the parent
788 * process fails to do so (eg. if the parent segfaults).
791 if (g->recovery_proc) {
794 pid_t qemu_pid = g->pid;
795 pid_t parent_pid = getppid ();
797 /* It would be nice to be able to put this in the same process
798 * group as qemu (ie. setpgid (0, qemu_pid)). However this is
799 * not possible because we don't have any guarantee here that
800 * the qemu process has started yet.
805 /* Writing to argv is hideously complicated and error prone. See:
806 * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
809 /* Loop around waiting for one or both of the other processes to
810 * disappear. It's fair to say this is very hairy. The PIDs that
811 * we are looking at might be reused by another process. We are
812 * effectively polling. Is the cure worse than the disease?
815 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
816 _exit (EXIT_SUCCESS);
817 if (kill (parent_pid, 0) == -1) {
818 /* Parent's gone away, qemu still around, so kill qemu. */
820 _exit (EXIT_SUCCESS);
826 /* Don't worry, if the fork failed, this will be -1. The recovery
827 * process isn't essential.
833 /* Close the other ends of the pipe. */
837 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
838 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
839 perrorf (g, "fcntl");
843 g->fd[0] = wfd[1]; /* stdin of child */
844 g->fd[1] = rfd[0]; /* stdout of child */
846 g->fd[0] = open ("/dev/null", O_RDWR);
847 if (g->fd[0] == -1) {
848 perrorf (g, "open /dev/null");
851 g->fd[1] = dup (g->fd[0]);
852 if (g->fd[1] == -1) {
859 g->state = LAUNCHING;
861 /* Wait for qemu to start and to connect back to us via
862 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
864 r = guestfs___accept_from_daemon (g);
868 close (g->sock); /* Close the listening socket. */
869 g->sock = r; /* This is the accepted data socket. */
871 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
872 perrorf (g, "fcntl");
878 r = guestfs___recv_from_daemon (g, &size, &buf);
881 if (r == -1) return -1;
883 if (size != GUESTFS_LAUNCH_FLAG) {
884 error (g, _("guestfs_launch failed, see earlier error messages"));
889 guestfs___print_timestamped_message (g, "appliance is up");
891 /* This is possible in some really strange situations, such as
892 * guestfsd starts up OK but then qemu immediately exits. Check for
893 * it because the caller is probably expecting to be able to send
894 * commands after this function returns.
896 if (g->state != READY) {
897 error (g, _("qemu launched and contacted daemon, but state != READY"));
903 guestfs___launch_send_progress (g, 12);
912 if (g->pid > 0) kill (g->pid, 9);
913 if (g->recoverypid > 0) kill (g->recoverypid, 9);
914 if (g->pid > 0) waitpid (g->pid, NULL, 0);
915 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
920 memset (&g->launch_t, 0, sizeof g->launch_t);
934 /* Alternate attach method: instead of launching the appliance,
935 * connect to an existing unix socket.
938 connect_unix_socket (guestfs_h *g, const char *sockpath)
941 struct sockaddr_un addr;
943 /* Start the clock ... */
944 gettimeofday (&g->launch_t, NULL);
946 /* Set these to nothing so we don't try to kill random processes or
947 * read from random file descriptors.
955 guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
957 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
959 perrorf (g, "socket");
963 addr.sun_family = AF_UNIX;
964 strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
965 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
967 g->state = LAUNCHING;
969 if (connect (g->sock, &addr, sizeof addr) == -1) {
974 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
975 perrorf (g, "fcntl");
981 r = guestfs___recv_from_daemon (g, &size, &buf);
984 if (r == -1) return -1;
986 if (size != GUESTFS_LAUNCH_FLAG) {
987 error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
992 guestfs___print_timestamped_message (g, "connected");
994 if (g->state != READY) {
995 error (g, _("contacted guestfsd, but state != READY"));
1006 /* launch (of the ordinary appliance) generates approximate progress
1007 * messages. Currently these are defined as follows:
1009 * 0 / 12: launch clock starts
1010 * 3 / 12: appliance created
1011 * 6 / 12: detected that guest kernel started
1012 * 9 / 12: detected that /init script is running
1013 * 12 / 12: launch completed successfully
1016 * (1) This is not a documented ABI and the behaviour may be changed
1017 * or removed in future.
1018 * (2) Messages are only sent if more than 5 seconds has elapsed
1019 * since the launch clock started.
1020 * (3) There is a gross hack in proto.c to make this work.
1023 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
1027 gettimeofday (&tv, NULL);
1028 if (timeval_diff (&g->launch_t, &tv) >= 5000) {
1029 guestfs_progress progress_message =
1030 { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
1032 guestfs___progress_message_callback (g, &progress_message);
1036 /* Return the location of the tmpdir (eg. "/tmp") and allow users
1037 * to override it at runtime using $TMPDIR.
1038 * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
1041 guestfs_tmpdir (void)
1051 const char *t = getenv ("TMPDIR");
1057 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
1058 * allow users to override it at runtime using $TMPDIR.
1059 * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
1062 guestfs___persistent_tmpdir (void)
1066 tmpdir = "/var/tmp";
1068 const char *t = getenv ("TMPDIR");
1074 /* Compute Y - X and return the result in milliseconds.
1075 * Approximately the same as this code:
1076 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1079 timeval_diff (const struct timeval *x, const struct timeval *y)
1083 msec = (y->tv_sec - x->tv_sec) * 1000;
1084 msec += (y->tv_usec - x->tv_usec) / 1000;
1088 /* Note that since this calls 'debug' it should only be called
1089 * from the parent process.
1092 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1099 va_start (args, fs);
1100 err = vasprintf (&msg, fs, args);
1103 if (err < 0) return;
1105 gettimeofday (&tv, NULL);
1107 debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1112 /* This is called from the forked subprocess just before qemu runs, so
1113 * it can just print the message straight to stderr, where it will be
1114 * picked up and funnelled through the usual appliance event API.
1117 print_qemu_command_line (guestfs_h *g, char **argv)
1123 gettimeofday (&tv, NULL);
1124 fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
1127 if (argv[i][0] == '-') /* -option starts a new line */
1128 fprintf (stderr, " \\\n ");
1130 if (i > 0) fputc (' ', stderr);
1132 /* Does it need shell quoting? This only deals with simple cases. */
1133 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
1135 if (needs_quote) fputc ('\'', stderr);
1136 fprintf (stderr, "%s", argv[i]);
1137 if (needs_quote) fputc ('\'', stderr);
1142 static int test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret);
1143 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1145 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1146 * 'qemu -version' so we know what options this qemu supports and
1150 test_qemu (guestfs_h *g)
1155 free (g->qemu_help);
1156 g->qemu_help = NULL;
1157 free (g->qemu_version);
1158 g->qemu_version = NULL;
1160 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1162 /* qemu -help should always work (qemu -version OTOH wasn't
1163 * supported by qemu 0.9). If this command doesn't work then it
1164 * probably indicates that the qemu binary is missing.
1166 if (test_qemu_cmd (g, cmd, &g->qemu_help) == -1) {
1167 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."),
1172 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1175 /* Intentionally ignore errors from qemu -version. */
1176 ignore_value (test_qemu_cmd (g, cmd, &g->qemu_version));
1182 test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret)
1186 fp = popen (cmd, "r");
1190 if (read_all (g, fp, ret) == -1) {
1195 if (pclose (fp) != 0)
1202 read_all (guestfs_h *g, FILE *fp, char **ret)
1209 *ret = safe_realloc (g, *ret, n + 1);
1214 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1216 r = fread (p, 1, BUFSIZ, fp);
1218 perrorf (g, "read");
1225 /* Test if option is supported by qemu command line (just by grepping
1228 * The first time this is used, it has to run the external qemu
1229 * binary. If that fails, it returns -1.
1231 * To just do the first-time run of the qemu binary, call this with
1232 * option == NULL, in which case it will return -1 if there was an
1236 qemu_supports (guestfs_h *g, const char *option)
1238 if (!g->qemu_help) {
1239 if (test_qemu (g) == -1)
1246 return strstr (g->qemu_help, option) != NULL;
1250 /* As above but using a regex instead of a fixed string. */
1252 qemu_supports_re (guestfs_h *g, const pcre *option_regex)
1254 if (!g->qemu_help) {
1255 if (test_qemu (g) == -1)
1259 return match (g, g->qemu_help, option_regex);
1263 /* Check if a file can be opened. */
1265 is_openable (guestfs_h *g, const char *path, int flags)
1267 int fd = open (path, flags);
1269 debug (g, "is_openable: %s: %m", path);
1276 /* You had to call this function after launch in versions <= 1.0.70,
1277 * but it is now a no-op.
1280 guestfs__wait_ready (guestfs_h *g)
1282 if (g->state != READY) {
1283 error (g, _("qemu has not been launched yet"));
1291 guestfs__kill_subprocess (guestfs_h *g)
1293 if (g->state == CONFIG) {
1294 error (g, _("no subprocess to kill"));
1298 debug (g, "sending SIGTERM to process %d", g->pid);
1300 if (g->pid > 0) kill (g->pid, SIGTERM);
1301 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1306 /* Access current state. */
1308 guestfs__is_config (guestfs_h *g)
1310 return g->state == CONFIG;
1314 guestfs__is_launching (guestfs_h *g)
1316 return g->state == LAUNCHING;
1320 guestfs__is_ready (guestfs_h *g)
1322 return g->state == READY;
1326 guestfs__is_busy (guestfs_h *g)
1328 return g->state == BUSY;
1332 guestfs__get_state (guestfs_h *g)