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);
79 static char *qemu_drive_param (guestfs_h *g, const struct drive *drv);
82 static int qemu_supports_re (guestfs_h *g, const pcre *option_regex);
84 static void compile_regexps (void) __attribute__((constructor));
85 static void free_regexps (void) __attribute__((destructor));
88 compile_regexps (void)
93 #define COMPILE(re,pattern,options) \
95 re = pcre_compile ((pattern), (options), &err, &offset, NULL); \
97 ignore_value (write (2, err, strlen (err))); \
109 /* Functions to add a string to the current command line. */
111 alloc_cmdline (guestfs_h *g)
113 if (g->cmdline == NULL) {
114 /* g->cmdline[0] is reserved for argv[0], set in guestfs_launch. */
116 g->cmdline = safe_malloc (g, sizeof (char *));
117 g->cmdline[0] = NULL;
122 incr_cmdline_size (guestfs_h *g)
126 g->cmdline = safe_realloc (g, g->cmdline, sizeof (char *) * g->cmdline_size);
130 add_cmdline (guestfs_h *g, const char *str)
132 if (g->state != CONFIG) {
134 _("command line cannot be altered after qemu subprocess launched"));
138 incr_cmdline_size (g);
139 g->cmdline[g->cmdline_size-1] = safe_strdup (g, str);
144 guestfs___checkpoint_drives (guestfs_h *g)
146 struct drive **i = &g->drives;
147 while (*i != NULL) i = &((*i)->next);
152 guestfs___rollback_drives (guestfs_h *g, struct drive **i)
154 guestfs___free_drives(i);
157 /* Internal command to return the command line. */
159 guestfs__debug_cmdline (guestfs_h *g)
166 r = safe_malloc (g, sizeof (char *) * (g->cmdline_size + 1));
167 r[0] = safe_strdup (g, g->qemu); /* g->cmdline[0] is always NULL */
169 for (i = 1; i < g->cmdline_size; ++i)
170 r[i] = safe_strdup (g, g->cmdline[i]);
172 r[g->cmdline_size] = NULL;
174 return r; /* caller frees */
177 /* Internal command to return the list of drives. */
179 guestfs__debug_drives (guestfs_h *g)
185 for (count = 0, drv = g->drives; drv; count++, drv = drv->next)
188 ret = safe_malloc (g, sizeof (char *) * (count + 1));
190 for (i = 0, drv = g->drives; drv; i++, drv = drv->next)
191 ret[i] = qemu_drive_param (g, drv);
195 return ret; /* caller frees */
199 guestfs__config (guestfs_h *g,
200 const char *qemu_param, const char *qemu_value)
202 if (qemu_param[0] != '-') {
203 error (g, _("guestfs_config: parameter must begin with '-' character"));
207 /* A bit fascist, but the user will probably break the extra
208 * parameters that we add if they try to set any of these.
210 if (STREQ (qemu_param, "-kernel") ||
211 STREQ (qemu_param, "-initrd") ||
212 STREQ (qemu_param, "-nographic") ||
213 STREQ (qemu_param, "-serial") ||
214 STREQ (qemu_param, "-full-screen") ||
215 STREQ (qemu_param, "-std-vga") ||
216 STREQ (qemu_param, "-vnc")) {
217 error (g, _("guestfs_config: parameter '%s' isn't allowed"), qemu_param);
221 if (add_cmdline (g, qemu_param) != 0) return -1;
223 if (qemu_value != NULL) {
224 if (add_cmdline (g, qemu_value) != 0) return -1;
230 /* cache=off improves reliability in the event of a host crash.
232 * However this option causes qemu to try to open the file with
233 * O_DIRECT. This fails on some filesystem types (notably tmpfs).
234 * So we check if we can open the file with or without O_DIRECT,
235 * and use cache=off (or not) accordingly.
237 * NB: This function is only called on the !readonly path. We must
238 * try to open with O_RDWR to test that the file is readable and
242 test_cache_off (guestfs_h *g, const char *filename)
244 int fd = open (filename, O_RDWR|O_DIRECT);
250 fd = open (filename, O_RDWR);
256 perrorf (g, "%s", filename);
260 /* Check string parameter matches ^[-_[:alnum:]]+$ (in C locale). */
262 valid_format_iface (const char *str)
264 size_t len = strlen (str);
272 if (c != '-' && c != '_' && !c_isalnum (c))
279 guestfs__add_drive_opts (guestfs_h *g, const char *filename,
280 const struct guestfs_add_drive_opts_argv *optargs)
288 if (strchr (filename, ',') != NULL) {
289 error (g, _("filename cannot contain ',' (comma) character"));
293 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
294 ? optargs->readonly : 0;
295 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
296 ? safe_strdup (g, optargs->format) : NULL;
297 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
298 ? safe_strdup (g, optargs->iface) : safe_strdup (g, DRIVE_IF);
299 name = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_NAME_BITMASK
300 ? safe_strdup (g, optargs->name) : NULL;
302 if (format && !valid_format_iface (format)) {
303 error (g, _("%s parameter is empty or contains disallowed characters"),
310 if (!valid_format_iface (iface)) {
311 error (g, _("%s parameter is empty or contains disallowed characters"),
319 /* For writable files, see if we can use cache=off. This also
320 * checks for the existence of the file. For readonly we have
321 * to do the check explicitly.
323 use_cache_off = readonly ? 0 : test_cache_off (g, filename);
324 if (use_cache_off == -1) {
332 if (access (filename, R_OK) == -1) {
333 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;
351 (*i)->use_cache_off = use_cache_off;
357 guestfs__add_drive (guestfs_h *g, const char *filename)
359 struct guestfs_add_drive_opts_argv optargs = {
363 return guestfs__add_drive_opts (g, filename, &optargs);
367 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
369 struct guestfs_add_drive_opts_argv optargs = {
370 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
374 return guestfs__add_drive_opts (g, filename, &optargs);
378 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
381 struct guestfs_add_drive_opts_argv optargs = {
382 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
386 return guestfs__add_drive_opts (g, filename, &optargs);
390 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
393 struct guestfs_add_drive_opts_argv optargs = {
394 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
395 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
400 return guestfs__add_drive_opts (g, filename, &optargs);
404 guestfs__add_cdrom (guestfs_h *g, const char *filename)
406 if (strchr (filename, ',') != NULL) {
407 error (g, _("filename cannot contain ',' (comma) character"));
411 if (access (filename, F_OK) == -1) {
412 perrorf (g, "%s", filename);
416 return guestfs__config (g, "-cdrom", filename);
419 static int is_openable (guestfs_h *g, const char *path, int flags);
422 guestfs__launch (guestfs_h *g)
425 if (g->state != CONFIG) {
426 error (g, _("the libguestfs handle has already been launched"));
430 TRACE0 (launch_start);
432 /* Make the temporary directory. */
434 TMP_TEMPLATE_ON_STACK (dir_template);
435 g->tmpdir = safe_strdup (g, dir_template);
436 if (mkdtemp (g->tmpdir) == NULL) {
437 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
442 /* Allow anyone to read the temporary directory. The socket in this
443 * directory won't be readable but anyone can see it exists if they
444 * want. (RHBZ#610880).
446 if (chmod (g->tmpdir, 0755) == -1)
447 warning (g, "chmod: %s: %m (ignored)", g->tmpdir);
449 /* Launch the appliance or attach to an existing daemon. */
450 switch (g->attach_method) {
451 case ATTACH_METHOD_APPLIANCE:
452 return launch_appliance (g);
454 case ATTACH_METHOD_UNIX:
455 return connect_unix_socket (g, g->attach_method_arg);
463 launch_appliance (guestfs_h *g)
467 char guestfsd_sock[256];
468 struct sockaddr_un addr;
470 /* At present you must add drives before starting the appliance. In
471 * future when we enable hotplugging you won't need to do this.
474 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
478 /* Start the clock ... */
479 gettimeofday (&g->launch_t, NULL);
480 guestfs___launch_send_progress (g, 0);
482 TRACE0 (launch_build_appliance_start);
484 /* Locate and/or build the appliance. */
485 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
486 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
489 TRACE0 (launch_build_appliance_end);
491 guestfs___launch_send_progress (g, 3);
494 guestfs___print_timestamped_message (g, "begin testing qemu features");
496 /* Get qemu help text and version. */
497 if (qemu_supports (g, NULL) == -1)
500 /* Using virtio-serial, we need to create a local Unix domain socket
501 * for qemu to connect to.
503 snprintf (guestfsd_sock, sizeof guestfsd_sock, "%s/guestfsd.sock", g->tmpdir);
504 unlink (guestfsd_sock);
506 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
508 perrorf (g, "socket");
512 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
513 perrorf (g, "fcntl");
517 addr.sun_family = AF_UNIX;
518 strncpy (addr.sun_path, guestfsd_sock, UNIX_PATH_MAX);
519 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
521 if (bind (g->sock, &addr, sizeof addr) == -1) {
526 if (listen (g->sock, 1) == -1) {
527 perrorf (g, "listen");
532 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
539 guestfs___print_timestamped_message (g, "finished testing qemu features");
553 if (r == 0) { /* Child (qemu). */
556 /* Set up the full command line. Do this in the subprocess so we
557 * don't need to worry about cleaning up.
560 /* Set g->cmdline[0] to the name of the qemu process. However
561 * it is possible that no g->cmdline has been allocated yet so
562 * we must do that first.
565 g->cmdline[0] = g->qemu;
568 struct drive *drv = g->drives;
569 while (drv != NULL) {
570 /* Construct the final -drive parameter. */
571 char *buf = qemu_drive_param (g, drv);
573 add_cmdline (g, "-drive");
574 add_cmdline (g, buf);
580 if (qemu_supports (g, "-nodefconfig"))
581 add_cmdline (g, "-nodefconfig");
583 /* The qemu -machine option (added 2010-12) is a bit more sane
584 * since it falls back through various different acceleration
585 * modes, so try that first (thanks Markus Armbruster).
587 if (qemu_supports (g, "-machine")) {
588 add_cmdline (g, "-machine");
589 #if QEMU_MACHINE_TYPE_IS_BROKEN
590 /* Workaround for qemu 0.15: We have to add the '[type=]pc'
591 * since there is no default. This is not a permanent solution
592 * because this only works on PC-like hardware. Other platforms
593 * like ppc would need a different machine type.
595 * This bug is fixed in qemu commit 2645c6dcaf6ea2a51a, and was
596 * not a problem in qemu < 0.15.
598 add_cmdline (g, "pc,accel=kvm:tcg");
600 add_cmdline (g, "accel=kvm:tcg");
603 /* qemu sometimes needs this option to enable hardware
604 * virtualization, but some versions of 'qemu-kvm' will use KVM
605 * regardless (even where this option appears in the help text).
606 * It is rumoured that there are versions of qemu where supplying
607 * this option when hardware virtualization is not available will
608 * cause qemu to fail, so we we have to check at least that
609 * /dev/kvm is openable. That's not reliable, since /dev/kvm
610 * might be openable by qemu but not by us (think: SELinux) in
611 * which case the user would not get hardware virtualization,
612 * although at least shouldn't fail. A giant clusterfuck with the
613 * qemu command line, again.
615 if (qemu_supports (g, "-enable-kvm") &&
616 is_openable (g, "/dev/kvm", O_RDWR))
617 add_cmdline (g, "-enable-kvm");
620 /* Newer versions of qemu (from around 2009/12) changed the
621 * behaviour of monitors so that an implicit '-monitor stdio' is
622 * assumed if we are in -nographic mode and there is no other
623 * -monitor option. Only a single stdio device is allowed, so
624 * this broke the '-serial stdio' option. There is a new flag
625 * called -nodefaults which gets rid of all this default crud, so
626 * let's use that to avoid this and any future surprises.
628 if (qemu_supports (g, "-nodefaults"))
629 add_cmdline (g, "-nodefaults");
631 add_cmdline (g, "-nographic");
634 snprintf (buf, sizeof buf, "%d", g->smp);
635 add_cmdline (g, "-smp");
636 add_cmdline (g, buf);
639 snprintf (buf, sizeof buf, "%d", g->memsize);
640 add_cmdline (g, "-m");
641 add_cmdline (g, buf);
643 /* Force exit instead of reboot on panic */
644 add_cmdline (g, "-no-reboot");
646 /* These options recommended by KVM developers to improve reliability. */
647 if (qemu_supports (g, "-no-hpet"))
648 add_cmdline (g, "-no-hpet");
650 if (qemu_supports (g, "-rtc-td-hack"))
651 add_cmdline (g, "-rtc-td-hack");
653 /* Create the virtio serial bus. */
654 add_cmdline (g, "-device");
655 add_cmdline (g, "virtio-serial");
658 /* Use virtio-console (a variant form of virtio-serial) for the
659 * guest's serial console.
661 add_cmdline (g, "-chardev");
662 add_cmdline (g, "stdio,id=console");
663 add_cmdline (g, "-device");
664 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
666 /* When the above works ... until then: */
667 add_cmdline (g, "-serial");
668 add_cmdline (g, "stdio");
671 /* Set up virtio-serial for the communications channel. */
672 add_cmdline (g, "-chardev");
673 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
674 add_cmdline (g, buf);
675 add_cmdline (g, "-device");
676 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
678 /* Enable user networking. */
679 if (g->enable_network) {
680 add_cmdline (g, "-netdev");
681 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
682 add_cmdline (g, "-device");
683 add_cmdline (g, NET_IF ",netdev=usernet");
686 #define LINUX_CMDLINE \
687 "panic=1 " /* force kernel to panic if daemon exits */ \
688 "console=ttyS0 " /* serial console */ \
689 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
690 "no_timer_check " /* fix for RHBZ#502058 */ \
691 "acpi=off " /* we don't need ACPI, turn it off */ \
692 "printk.time=1 " /* display timestamp before kernel messages */ \
693 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
695 /* Linux kernel command line. */
696 snprintf (buf, sizeof buf,
698 "%s " /* (selinux) */
699 "%s " /* (verbose) */
700 "TERM=%s " /* (TERM environment variable) */
702 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
703 g->verbose ? "guestfs_verbose=1" : "",
704 getenv ("TERM") ? : "linux",
705 g->append ? g->append : "");
707 add_cmdline (g, "-kernel");
708 add_cmdline (g, kernel);
709 add_cmdline (g, "-initrd");
710 add_cmdline (g, initrd);
711 add_cmdline (g, "-append");
712 add_cmdline (g, buf);
714 /* Add the ext2 appliance drive (last of all). */
716 const char *cachemode = "";
717 if (qemu_supports (g, "cache=")) {
718 if (qemu_supports (g, "unsafe"))
719 cachemode = ",cache=unsafe";
720 else if (qemu_supports (g, "writeback"))
721 cachemode = ",cache=writeback";
724 char buf2[PATH_MAX + 64];
725 add_cmdline (g, "-drive");
726 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
727 appliance, cachemode);
728 add_cmdline (g, buf2);
731 /* Finish off the command line. */
732 incr_cmdline_size (g);
733 g->cmdline[g->cmdline_size-1] = NULL;
736 /* Set up stdin, stdout, stderr. */
743 if (dup (wfd[0]) == -1) {
745 perror ("dup failed");
746 _exit (EXIT_FAILURE);
749 if (dup (rfd[1]) == -1)
752 /* Particularly since qemu 0.15, qemu spews all sorts of debug
753 * information on stderr. It is useful to both capture this and
754 * not confuse casual users, so send stderr to the pipe as well.
757 if (dup (rfd[1]) == -1)
764 /* Dump the command line (after setting up stderr above). */
766 print_qemu_command_line (g, g->cmdline);
768 /* Put qemu in a new process group. */
772 setenv ("LC_ALL", "C", 1);
774 TRACE0 (launch_run_qemu);
776 execv (g->qemu, g->cmdline); /* Run qemu. */
778 _exit (EXIT_FAILURE);
781 /* Parent (library). */
791 /* Fork the recovery process off which will kill qemu if the parent
792 * process fails to do so (eg. if the parent segfaults).
795 if (g->recovery_proc) {
798 pid_t qemu_pid = g->pid;
799 pid_t parent_pid = getppid ();
801 /* It would be nice to be able to put this in the same process
802 * group as qemu (ie. setpgid (0, qemu_pid)). However this is
803 * not possible because we don't have any guarantee here that
804 * the qemu process has started yet.
809 /* Writing to argv is hideously complicated and error prone. See:
810 * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
813 /* Loop around waiting for one or both of the other processes to
814 * disappear. It's fair to say this is very hairy. The PIDs that
815 * we are looking at might be reused by another process. We are
816 * effectively polling. Is the cure worse than the disease?
819 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
820 _exit (EXIT_SUCCESS);
821 if (kill (parent_pid, 0) == -1) {
822 /* Parent's gone away, qemu still around, so kill qemu. */
824 _exit (EXIT_SUCCESS);
830 /* Don't worry, if the fork failed, this will be -1. The recovery
831 * process isn't essential.
837 /* Close the other ends of the pipe. */
841 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
842 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
843 perrorf (g, "fcntl");
847 g->fd[0] = wfd[1]; /* stdin of child */
848 g->fd[1] = rfd[0]; /* stdout of child */
850 g->fd[0] = open ("/dev/null", O_RDWR);
851 if (g->fd[0] == -1) {
852 perrorf (g, "open /dev/null");
855 g->fd[1] = dup (g->fd[0]);
856 if (g->fd[1] == -1) {
863 g->state = LAUNCHING;
865 /* Wait for qemu to start and to connect back to us via
866 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
868 r = guestfs___accept_from_daemon (g);
872 /* NB: We reach here just because qemu has opened the socket. It
873 * does not mean the daemon is up until we read the
874 * GUESTFS_LAUNCH_FLAG below. Failures in qemu startup can still
875 * happen even if we reach here, even early failures like not being
876 * able to open a drive.
879 close (g->sock); /* Close the listening socket. */
880 g->sock = r; /* This is the accepted data socket. */
882 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
883 perrorf (g, "fcntl");
889 r = guestfs___recv_from_daemon (g, &size, &buf);
892 if (r == -1) return -1;
894 if (size != GUESTFS_LAUNCH_FLAG) {
895 error (g, _("guestfs_launch failed, see earlier error messages"));
900 guestfs___print_timestamped_message (g, "appliance is up");
902 /* This is possible in some really strange situations, such as
903 * guestfsd starts up OK but then qemu immediately exits. Check for
904 * it because the caller is probably expecting to be able to send
905 * commands after this function returns.
907 if (g->state != READY) {
908 error (g, _("qemu launched and contacted daemon, but state != READY"));
914 guestfs___launch_send_progress (g, 12);
923 if (g->pid > 0) kill (g->pid, 9);
924 if (g->recoverypid > 0) kill (g->recoverypid, 9);
925 if (g->pid > 0) waitpid (g->pid, NULL, 0);
926 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
931 memset (&g->launch_t, 0, sizeof g->launch_t);
945 /* Alternate attach method: instead of launching the appliance,
946 * connect to an existing unix socket.
949 connect_unix_socket (guestfs_h *g, const char *sockpath)
952 struct sockaddr_un addr;
954 /* Start the clock ... */
955 gettimeofday (&g->launch_t, NULL);
957 /* Set these to nothing so we don't try to kill random processes or
958 * read from random file descriptors.
966 guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
968 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
970 perrorf (g, "socket");
974 addr.sun_family = AF_UNIX;
975 strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
976 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
978 g->state = LAUNCHING;
980 if (connect (g->sock, &addr, sizeof addr) == -1) {
985 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
986 perrorf (g, "fcntl");
992 r = guestfs___recv_from_daemon (g, &size, &buf);
995 if (r == -1) return -1;
997 if (size != GUESTFS_LAUNCH_FLAG) {
998 error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
1003 guestfs___print_timestamped_message (g, "connected");
1005 if (g->state != READY) {
1006 error (g, _("contacted guestfsd, but state != READY"));
1017 /* launch (of the ordinary appliance) generates approximate progress
1018 * messages. Currently these are defined as follows:
1020 * 0 / 12: launch clock starts
1021 * 3 / 12: appliance created
1022 * 6 / 12: detected that guest kernel started
1023 * 9 / 12: detected that /init script is running
1024 * 12 / 12: launch completed successfully
1027 * (1) This is not a documented ABI and the behaviour may be changed
1028 * or removed in future.
1029 * (2) Messages are only sent if more than 5 seconds has elapsed
1030 * since the launch clock started.
1031 * (3) There is a gross hack in proto.c to make this work.
1034 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
1038 gettimeofday (&tv, NULL);
1039 if (timeval_diff (&g->launch_t, &tv) >= 5000) {
1040 guestfs_progress progress_message =
1041 { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
1043 guestfs___progress_message_callback (g, &progress_message);
1047 /* Return the location of the tmpdir (eg. "/tmp") and allow users
1048 * to override it at runtime using $TMPDIR.
1049 * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
1052 guestfs_tmpdir (void)
1062 const char *t = getenv ("TMPDIR");
1068 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
1069 * allow users to override it at runtime using $TMPDIR.
1070 * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
1073 guestfs___persistent_tmpdir (void)
1077 tmpdir = "/var/tmp";
1079 const char *t = getenv ("TMPDIR");
1085 /* Compute Y - X and return the result in milliseconds.
1086 * Approximately the same as this code:
1087 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1090 timeval_diff (const struct timeval *x, const struct timeval *y)
1094 msec = (y->tv_sec - x->tv_sec) * 1000;
1095 msec += (y->tv_usec - x->tv_usec) / 1000;
1099 /* Note that since this calls 'debug' it should only be called
1100 * from the parent process.
1103 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1110 va_start (args, fs);
1111 err = vasprintf (&msg, fs, args);
1114 if (err < 0) return;
1116 gettimeofday (&tv, NULL);
1118 debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1123 /* This is called from the forked subprocess just before qemu runs, so
1124 * it can just print the message straight to stderr, where it will be
1125 * picked up and funnelled through the usual appliance event API.
1128 print_qemu_command_line (guestfs_h *g, char **argv)
1134 gettimeofday (&tv, NULL);
1135 fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
1138 if (argv[i][0] == '-') /* -option starts a new line */
1139 fprintf (stderr, " \\\n ");
1141 if (i > 0) fputc (' ', stderr);
1143 /* Does it need shell quoting? This only deals with simple cases. */
1144 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
1146 if (needs_quote) fputc ('\'', stderr);
1147 fprintf (stderr, "%s", argv[i]);
1148 if (needs_quote) fputc ('\'', stderr);
1153 static int test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret);
1154 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1156 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1157 * 'qemu -version' so we know what options this qemu supports and
1161 test_qemu (guestfs_h *g)
1166 free (g->qemu_help);
1167 g->qemu_help = NULL;
1168 free (g->qemu_version);
1169 g->qemu_version = NULL;
1171 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1173 /* qemu -help should always work (qemu -version OTOH wasn't
1174 * supported by qemu 0.9). If this command doesn't work then it
1175 * probably indicates that the qemu binary is missing.
1177 if (test_qemu_cmd (g, cmd, &g->qemu_help) == -1) {
1178 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."),
1183 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1186 /* Intentionally ignore errors from qemu -version. */
1187 ignore_value (test_qemu_cmd (g, cmd, &g->qemu_version));
1193 test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret)
1197 fp = popen (cmd, "r");
1201 if (read_all (g, fp, ret) == -1) {
1206 if (pclose (fp) != 0)
1213 read_all (guestfs_h *g, FILE *fp, char **ret)
1220 *ret = safe_realloc (g, *ret, n + 1);
1225 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1227 r = fread (p, 1, BUFSIZ, fp);
1229 perrorf (g, "read");
1236 /* Test if option is supported by qemu command line (just by grepping
1239 * The first time this is used, it has to run the external qemu
1240 * binary. If that fails, it returns -1.
1242 * To just do the first-time run of the qemu binary, call this with
1243 * option == NULL, in which case it will return -1 if there was an
1247 qemu_supports (guestfs_h *g, const char *option)
1249 if (!g->qemu_help) {
1250 if (test_qemu (g) == -1)
1257 return strstr (g->qemu_help, option) != NULL;
1261 /* As above but using a regex instead of a fixed string. */
1263 qemu_supports_re (guestfs_h *g, const pcre *option_regex)
1265 if (!g->qemu_help) {
1266 if (test_qemu (g) == -1)
1270 return match (g, g->qemu_help, option_regex);
1274 /* Check if a file can be opened. */
1276 is_openable (guestfs_h *g, const char *path, int flags)
1278 int fd = open (path, flags);
1280 debug (g, "is_openable: %s: %m", path);
1288 qemu_drive_param (guestfs_h *g, const struct drive *drv)
1293 len += strlen (drv->path);
1294 len += strlen (drv->iface);
1296 len += strlen (drv->format);
1298 r = safe_malloc (g, len);
1300 snprintf (r, len, "file=%s%s%s%s%s,if=%s",
1302 drv->readonly ? ",snapshot=on" : "",
1303 drv->use_cache_off ? ",cache=off" : "",
1304 drv->format ? ",format=" : "",
1305 drv->format ? drv->format : "",
1308 return r; /* caller frees */
1311 /* You had to call this function after launch in versions <= 1.0.70,
1312 * but it is now a no-op.
1315 guestfs__wait_ready (guestfs_h *g)
1317 if (g->state != READY) {
1318 error (g, _("qemu has not been launched yet"));
1326 guestfs__kill_subprocess (guestfs_h *g)
1328 if (g->state == CONFIG) {
1329 error (g, _("no subprocess to kill"));
1333 debug (g, "sending SIGTERM to process %d", g->pid);
1335 if (g->pid > 0) kill (g->pid, SIGTERM);
1336 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1341 /* Access current state. */
1343 guestfs__is_config (guestfs_h *g)
1345 return g->state == CONFIG;
1349 guestfs__is_launching (guestfs_h *g)
1351 return g->state == LAUNCHING;
1355 guestfs__is_ready (guestfs_h *g)
1357 return g->state == READY;
1361 guestfs__is_busy (guestfs_h *g)
1363 return g->state == BUSY;
1367 guestfs__get_state (guestfs_h *g)