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)
295 if (strchr (filename, ',') != NULL) {
296 error (g, _("filename cannot contain ',' (comma) character"));
300 readonly = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK
301 ? optargs->readonly : 0;
302 format = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK
303 ? safe_strdup (g, optargs->format) : NULL;
304 iface = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
305 ? safe_strdup (g, optargs->iface) : safe_strdup (g, DRIVE_IF);
306 name = optargs->bitmask & GUESTFS_ADD_DRIVE_OPTS_NAME_BITMASK
307 ? safe_strdup (g, optargs->name) : NULL;
309 if (format && !valid_format_iface (format)) {
310 error (g, _("%s parameter is empty or contains disallowed characters"),
317 if (!valid_format_iface (iface)) {
318 error (g, _("%s parameter is empty or contains disallowed characters"),
326 /* For writable files, see if we can use cache=off. This also
327 * checks for the existence of the file. For readonly we have
328 * to do the check explicitly.
330 use_cache_off = readonly ? 0 : test_cache_off (g, filename);
331 if (use_cache_off == -1) {
339 if (access (filename, F_OK) == -1) {
340 perrorf (g, "%s", filename);
348 struct drive **i = &(g->drives);
349 while (*i != NULL) i = &((*i)->next);
351 *i = safe_malloc (g, sizeof (struct drive));
353 (*i)->path = safe_strdup (g, filename);
354 (*i)->readonly = readonly;
355 (*i)->format = format;
358 (*i)->use_cache_off = use_cache_off;
364 guestfs__add_drive (guestfs_h *g, const char *filename)
366 struct guestfs_add_drive_opts_argv optargs = {
370 return guestfs__add_drive_opts (g, filename, &optargs);
374 guestfs__add_drive_ro (guestfs_h *g, const char *filename)
376 struct guestfs_add_drive_opts_argv optargs = {
377 .bitmask = GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
381 return guestfs__add_drive_opts (g, filename, &optargs);
385 guestfs__add_drive_with_if (guestfs_h *g, const char *filename,
388 struct guestfs_add_drive_opts_argv optargs = {
389 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK,
393 return guestfs__add_drive_opts (g, filename, &optargs);
397 guestfs__add_drive_ro_with_if (guestfs_h *g, const char *filename,
400 struct guestfs_add_drive_opts_argv optargs = {
401 .bitmask = GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK
402 | GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK,
407 return guestfs__add_drive_opts (g, filename, &optargs);
411 guestfs__add_cdrom (guestfs_h *g, const char *filename)
413 if (strchr (filename, ',') != NULL) {
414 error (g, _("filename cannot contain ',' (comma) character"));
418 if (access (filename, F_OK) == -1) {
419 perrorf (g, "%s", filename);
423 return guestfs__config (g, "-cdrom", filename);
426 static int is_openable (guestfs_h *g, const char *path, int flags);
429 guestfs__launch (guestfs_h *g)
432 if (g->state != CONFIG) {
433 error (g, _("the libguestfs handle has already been launched"));
437 TRACE0 (launch_start);
439 /* Make the temporary directory. */
441 TMP_TEMPLATE_ON_STACK (dir_template);
442 g->tmpdir = safe_strdup (g, dir_template);
443 if (mkdtemp (g->tmpdir) == NULL) {
444 perrorf (g, _("%s: cannot create temporary directory"), dir_template);
449 /* Allow anyone to read the temporary directory. The socket in this
450 * directory won't be readable but anyone can see it exists if they
451 * want. (RHBZ#610880).
453 if (chmod (g->tmpdir, 0755) == -1)
454 warning (g, "chmod: %s: %m (ignored)", g->tmpdir);
456 /* Launch the appliance or attach to an existing daemon. */
457 switch (g->attach_method) {
458 case ATTACH_METHOD_APPLIANCE:
459 return launch_appliance (g);
461 case ATTACH_METHOD_UNIX:
462 return connect_unix_socket (g, g->attach_method_arg);
470 launch_appliance (guestfs_h *g)
474 char guestfsd_sock[256];
475 struct sockaddr_un addr;
477 /* At present you must add drives before starting the appliance. In
478 * future when we enable hotplugging you won't need to do this.
481 error (g, _("you must call guestfs_add_drive before guestfs_launch"));
485 /* Start the clock ... */
486 gettimeofday (&g->launch_t, NULL);
487 guestfs___launch_send_progress (g, 0);
489 TRACE0 (launch_build_appliance_start);
491 /* Locate and/or build the appliance. */
492 char *kernel = NULL, *initrd = NULL, *appliance = NULL;
493 if (guestfs___build_appliance (g, &kernel, &initrd, &appliance) == -1)
496 TRACE0 (launch_build_appliance_end);
498 guestfs___launch_send_progress (g, 3);
501 guestfs___print_timestamped_message (g, "begin testing qemu features");
503 /* Get qemu help text and version. */
504 if (qemu_supports (g, NULL) == -1)
507 /* Using virtio-serial, we need to create a local Unix domain socket
508 * for qemu to connect to.
510 snprintf (guestfsd_sock, sizeof guestfsd_sock, "%s/guestfsd.sock", g->tmpdir);
511 unlink (guestfsd_sock);
513 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
515 perrorf (g, "socket");
519 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
520 perrorf (g, "fcntl");
524 addr.sun_family = AF_UNIX;
525 strncpy (addr.sun_path, guestfsd_sock, UNIX_PATH_MAX);
526 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
528 if (bind (g->sock, &addr, sizeof addr) == -1) {
533 if (listen (g->sock, 1) == -1) {
534 perrorf (g, "listen");
539 if (pipe (wfd) == -1 || pipe (rfd) == -1) {
546 guestfs___print_timestamped_message (g, "finished testing qemu features");
560 if (r == 0) { /* Child (qemu). */
563 /* Set up the full command line. Do this in the subprocess so we
564 * don't need to worry about cleaning up.
567 /* Set g->cmdline[0] to the name of the qemu process. However
568 * it is possible that no g->cmdline has been allocated yet so
569 * we must do that first.
572 g->cmdline[0] = g->qemu;
575 struct drive *i = g->drives;
577 /* Construct the final -drive parameter. */
578 size_t len = 64 + strlen (i->path) + strlen (i->iface);
579 if (i->format) len += strlen (i->format);
582 snprintf (buf, len, "file=%s%s%s%s%s,if=%s",
584 i->readonly ? ",snapshot=on" : "",
585 i->use_cache_off ? ",cache=off" : "",
586 i->format ? ",format=" : "",
587 i->format ? i->format : "",
590 add_cmdline (g, "-drive");
591 add_cmdline (g, buf);
596 if (qemu_supports (g, "-nodefconfig"))
597 add_cmdline (g, "-nodefconfig");
599 /* The qemu -machine option (added 2010-12) is a bit more sane
600 * since it falls back through various different acceleration
601 * modes, so try that first (thanks Markus Armbruster).
603 if (qemu_supports (g, "-machine")) {
604 add_cmdline (g, "-machine");
605 add_cmdline (g, "accel=kvm:tcg");
607 /* qemu sometimes needs this option to enable hardware
608 * virtualization, but some versions of 'qemu-kvm' will use KVM
609 * regardless (even where this option appears in the help text).
610 * It is rumoured that there are versions of qemu where supplying
611 * this option when hardware virtualization is not available will
612 * cause qemu to fail, so we we have to check at least that
613 * /dev/kvm is openable. That's not reliable, since /dev/kvm
614 * might be openable by qemu but not by us (think: SELinux) in
615 * which case the user would not get hardware virtualization,
616 * although at least shouldn't fail. A giant clusterfuck with the
617 * qemu command line, again.
619 if (qemu_supports (g, "-enable-kvm") &&
620 is_openable (g, "/dev/kvm", O_RDWR))
621 add_cmdline (g, "-enable-kvm");
624 /* Newer versions of qemu (from around 2009/12) changed the
625 * behaviour of monitors so that an implicit '-monitor stdio' is
626 * assumed if we are in -nographic mode and there is no other
627 * -monitor option. Only a single stdio device is allowed, so
628 * this broke the '-serial stdio' option. There is a new flag
629 * called -nodefaults which gets rid of all this default crud, so
630 * let's use that to avoid this and any future surprises.
632 if (qemu_supports (g, "-nodefaults"))
633 add_cmdline (g, "-nodefaults");
635 add_cmdline (g, "-nographic");
638 snprintf (buf, sizeof buf, "%d", g->smp);
639 add_cmdline (g, "-smp");
640 add_cmdline (g, buf);
643 snprintf (buf, sizeof buf, "%d", g->memsize);
644 add_cmdline (g, "-m");
645 add_cmdline (g, buf);
647 /* Force exit instead of reboot on panic */
648 add_cmdline (g, "-no-reboot");
650 /* These options recommended by KVM developers to improve reliability. */
651 if (qemu_supports (g, "-no-hpet"))
652 add_cmdline (g, "-no-hpet");
654 if (qemu_supports (g, "-rtc-td-hack"))
655 add_cmdline (g, "-rtc-td-hack");
657 /* Create the virtio serial bus. */
658 add_cmdline (g, "-device");
659 add_cmdline (g, "virtio-serial");
662 /* Use virtio-console (a variant form of virtio-serial) for the
663 * guest's serial console.
665 add_cmdline (g, "-chardev");
666 add_cmdline (g, "stdio,id=console");
667 add_cmdline (g, "-device");
668 add_cmdline (g, "virtconsole,chardev=console,name=org.libguestfs.console.0");
670 /* When the above works ... until then: */
671 add_cmdline (g, "-serial");
672 add_cmdline (g, "stdio");
675 /* Set up virtio-serial for the communications channel. */
676 add_cmdline (g, "-chardev");
677 snprintf (buf, sizeof buf, "socket,path=%s,id=channel0", guestfsd_sock);
678 add_cmdline (g, buf);
679 add_cmdline (g, "-device");
680 add_cmdline (g, "virtserialport,chardev=channel0,name=org.libguestfs.channel.0");
682 /* Enable user networking. */
683 if (g->enable_network) {
684 add_cmdline (g, "-netdev");
685 add_cmdline (g, "user,id=usernet,net=169.254.0.0/16");
686 add_cmdline (g, "-device");
687 add_cmdline (g, NET_IF ",netdev=usernet");
690 #define LINUX_CMDLINE \
691 "panic=1 " /* force kernel to panic if daemon exits */ \
692 "console=ttyS0 " /* serial console */ \
693 "udevtimeout=300 " /* good for very slow systems (RHBZ#480319) */ \
694 "no_timer_check " /* fix for RHBZ#502058 */ \
695 "acpi=off " /* we don't need ACPI, turn it off */ \
696 "printk.time=1 " /* display timestamp before kernel messages */ \
697 "cgroup_disable=memory " /* saves us about 5 MB of RAM */
699 /* Linux kernel command line. */
700 snprintf (buf, sizeof buf,
702 "%s " /* (selinux) */
703 "%s " /* (verbose) */
704 "TERM=%s " /* (TERM environment variable) */
706 g->selinux ? "selinux=1 enforcing=0" : "selinux=0",
707 g->verbose ? "guestfs_verbose=1" : "",
708 getenv ("TERM") ? : "linux",
709 g->append ? g->append : "");
711 add_cmdline (g, "-kernel");
712 add_cmdline (g, kernel);
713 add_cmdline (g, "-initrd");
714 add_cmdline (g, initrd);
715 add_cmdline (g, "-append");
716 add_cmdline (g, buf);
718 /* Add the ext2 appliance drive (last of all). */
720 const char *cachemode = "";
721 if (qemu_supports (g, "cache=")) {
722 if (qemu_supports (g, "unsafe"))
723 cachemode = ",cache=unsafe";
724 else if (qemu_supports (g, "writeback"))
725 cachemode = ",cache=writeback";
728 char buf2[PATH_MAX + 64];
729 add_cmdline (g, "-drive");
730 snprintf (buf2, sizeof buf2, "file=%s,snapshot=on,if=" DRIVE_IF "%s",
731 appliance, cachemode);
732 add_cmdline (g, buf2);
735 /* Finish off the command line. */
736 incr_cmdline_size (g);
737 g->cmdline[g->cmdline_size-1] = NULL;
740 /* Set up stdin, stdout, stderr. */
747 if (dup (wfd[0]) == -1) {
749 perror ("dup failed");
750 _exit (EXIT_FAILURE);
753 if (dup (rfd[1]) == -1)
756 /* Particularly since qemu 0.15, qemu spews all sorts of debug
757 * information on stderr. It is useful to both capture this and
758 * not confuse casual users, so send stderr to the pipe as well.
761 if (dup (rfd[1]) == -1)
768 /* Dump the command line (after setting up stderr above). */
770 print_qemu_command_line (g, g->cmdline);
772 /* Put qemu in a new process group. */
776 setenv ("LC_ALL", "C", 1);
778 TRACE0 (launch_run_qemu);
780 execv (g->qemu, g->cmdline); /* Run qemu. */
782 _exit (EXIT_FAILURE);
785 /* Parent (library). */
795 /* Fork the recovery process off which will kill qemu if the parent
796 * process fails to do so (eg. if the parent segfaults).
799 if (g->recovery_proc) {
802 pid_t qemu_pid = g->pid;
803 pid_t parent_pid = getppid ();
805 /* It would be nice to be able to put this in the same process
806 * group as qemu (ie. setpgid (0, qemu_pid)). However this is
807 * not possible because we don't have any guarantee here that
808 * the qemu process has started yet.
813 /* Writing to argv is hideously complicated and error prone. See:
814 * http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/misc/ps_status.c;hb=HEAD
817 /* Loop around waiting for one or both of the other processes to
818 * disappear. It's fair to say this is very hairy. The PIDs that
819 * we are looking at might be reused by another process. We are
820 * effectively polling. Is the cure worse than the disease?
823 if (kill (qemu_pid, 0) == -1) /* qemu's gone away, we aren't needed */
824 _exit (EXIT_SUCCESS);
825 if (kill (parent_pid, 0) == -1) {
826 /* Parent's gone away, qemu still around, so kill qemu. */
828 _exit (EXIT_SUCCESS);
834 /* Don't worry, if the fork failed, this will be -1. The recovery
835 * process isn't essential.
841 /* Close the other ends of the pipe. */
845 if (fcntl (wfd[1], F_SETFL, O_NONBLOCK) == -1 ||
846 fcntl (rfd[0], F_SETFL, O_NONBLOCK) == -1) {
847 perrorf (g, "fcntl");
851 g->fd[0] = wfd[1]; /* stdin of child */
852 g->fd[1] = rfd[0]; /* stdout of child */
854 g->fd[0] = open ("/dev/null", O_RDWR);
855 if (g->fd[0] == -1) {
856 perrorf (g, "open /dev/null");
859 g->fd[1] = dup (g->fd[0]);
860 if (g->fd[1] == -1) {
867 g->state = LAUNCHING;
869 /* Wait for qemu to start and to connect back to us via
870 * virtio-serial and send the GUESTFS_LAUNCH_FLAG message.
872 r = guestfs___accept_from_daemon (g);
876 close (g->sock); /* Close the listening socket. */
877 g->sock = r; /* This is the accepted data socket. */
879 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
880 perrorf (g, "fcntl");
886 r = guestfs___recv_from_daemon (g, &size, &buf);
889 if (r == -1) return -1;
891 if (size != GUESTFS_LAUNCH_FLAG) {
892 error (g, _("guestfs_launch failed, see earlier error messages"));
897 guestfs___print_timestamped_message (g, "appliance is up");
899 /* This is possible in some really strange situations, such as
900 * guestfsd starts up OK but then qemu immediately exits. Check for
901 * it because the caller is probably expecting to be able to send
902 * commands after this function returns.
904 if (g->state != READY) {
905 error (g, _("qemu launched and contacted daemon, but state != READY"));
911 guestfs___launch_send_progress (g, 12);
920 if (g->pid > 0) kill (g->pid, 9);
921 if (g->recoverypid > 0) kill (g->recoverypid, 9);
922 if (g->pid > 0) waitpid (g->pid, NULL, 0);
923 if (g->recoverypid > 0) waitpid (g->recoverypid, NULL, 0);
928 memset (&g->launch_t, 0, sizeof g->launch_t);
942 /* Alternate attach method: instead of launching the appliance,
943 * connect to an existing unix socket.
946 connect_unix_socket (guestfs_h *g, const char *sockpath)
949 struct sockaddr_un addr;
951 /* Start the clock ... */
952 gettimeofday (&g->launch_t, NULL);
954 /* Set these to nothing so we don't try to kill random processes or
955 * read from random file descriptors.
963 guestfs___print_timestamped_message (g, "connecting to %s", sockpath);
965 g->sock = socket (AF_UNIX, SOCK_STREAM, 0);
967 perrorf (g, "socket");
971 addr.sun_family = AF_UNIX;
972 strncpy (addr.sun_path, sockpath, UNIX_PATH_MAX);
973 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
975 g->state = LAUNCHING;
977 if (connect (g->sock, &addr, sizeof addr) == -1) {
982 if (fcntl (g->sock, F_SETFL, O_NONBLOCK) == -1) {
983 perrorf (g, "fcntl");
989 r = guestfs___recv_from_daemon (g, &size, &buf);
992 if (r == -1) return -1;
994 if (size != GUESTFS_LAUNCH_FLAG) {
995 error (g, _("guestfs_launch failed, unexpected initial message from guestfsd"));
1000 guestfs___print_timestamped_message (g, "connected");
1002 if (g->state != READY) {
1003 error (g, _("contacted guestfsd, but state != READY"));
1014 /* launch (of the ordinary appliance) generates approximate progress
1015 * messages. Currently these are defined as follows:
1017 * 0 / 12: launch clock starts
1018 * 3 / 12: appliance created
1019 * 6 / 12: detected that guest kernel started
1020 * 9 / 12: detected that /init script is running
1021 * 12 / 12: launch completed successfully
1024 * (1) This is not a documented ABI and the behaviour may be changed
1025 * or removed in future.
1026 * (2) Messages are only sent if more than 5 seconds has elapsed
1027 * since the launch clock started.
1028 * (3) There is a gross hack in proto.c to make this work.
1031 guestfs___launch_send_progress (guestfs_h *g, int perdozen)
1035 gettimeofday (&tv, NULL);
1036 if (timeval_diff (&g->launch_t, &tv) >= 5000) {
1037 guestfs_progress progress_message =
1038 { .proc = 0, .serial = 0, .position = perdozen, .total = 12 };
1040 guestfs___progress_message_callback (g, &progress_message);
1044 /* Return the location of the tmpdir (eg. "/tmp") and allow users
1045 * to override it at runtime using $TMPDIR.
1046 * http://www.pathname.com/fhs/pub/fhs-2.3.html#TMPTEMPORARYFILES
1049 guestfs_tmpdir (void)
1059 const char *t = getenv ("TMPDIR");
1065 /* Return the location of the persistent tmpdir (eg. "/var/tmp") and
1066 * allow users to override it at runtime using $TMPDIR.
1067 * http://www.pathname.com/fhs/pub/fhs-2.3.html#VARTMPTEMPORARYFILESPRESERVEDBETWEE
1070 guestfs___persistent_tmpdir (void)
1074 tmpdir = "/var/tmp";
1076 const char *t = getenv ("TMPDIR");
1082 /* Compute Y - X and return the result in milliseconds.
1083 * Approximately the same as this code:
1084 * http://www.mpp.mpg.de/~huber/util/timevaldiff.c
1087 timeval_diff (const struct timeval *x, const struct timeval *y)
1091 msec = (y->tv_sec - x->tv_sec) * 1000;
1092 msec += (y->tv_usec - x->tv_usec) / 1000;
1096 /* Note that since this calls 'debug' it should only be called
1097 * from the parent process.
1100 guestfs___print_timestamped_message (guestfs_h *g, const char *fs, ...)
1107 va_start (args, fs);
1108 err = vasprintf (&msg, fs, args);
1111 if (err < 0) return;
1113 gettimeofday (&tv, NULL);
1115 debug (g, "[%05" PRIi64 "ms] %s", timeval_diff (&g->launch_t, &tv), msg);
1120 /* This is called from the forked subprocess just before qemu runs, so
1121 * it can just print the message straight to stderr, where it will be
1122 * picked up and funnelled through the usual appliance event API.
1125 print_qemu_command_line (guestfs_h *g, char **argv)
1131 gettimeofday (&tv, NULL);
1132 fprintf (stderr, "[%05" PRIi64 "ms] ", timeval_diff (&g->launch_t, &tv));
1135 if (argv[i][0] == '-') /* -option starts a new line */
1136 fprintf (stderr, " \\\n ");
1138 if (i > 0) fputc (' ', stderr);
1140 /* Does it need shell quoting? This only deals with simple cases. */
1141 needs_quote = strcspn (argv[i], " ") != strlen (argv[i]);
1143 if (needs_quote) fputc ('\'', stderr);
1144 fprintf (stderr, "%s", argv[i]);
1145 if (needs_quote) fputc ('\'', stderr);
1150 static int test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret);
1151 static int read_all (guestfs_h *g, FILE *fp, char **ret);
1153 /* Test qemu binary (or wrapper) runs, and do 'qemu -help' and
1154 * 'qemu -version' so we know what options this qemu supports and
1158 test_qemu (guestfs_h *g)
1163 free (g->qemu_help);
1164 g->qemu_help = NULL;
1165 free (g->qemu_version);
1166 g->qemu_version = NULL;
1168 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -help", g->qemu);
1170 /* qemu -help should always work (qemu -version OTOH wasn't
1171 * supported by qemu 0.9). If this command doesn't work then it
1172 * probably indicates that the qemu binary is missing.
1174 if (test_qemu_cmd (g, cmd, &g->qemu_help) == -1) {
1175 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."),
1180 snprintf (cmd, sizeof cmd, "LC_ALL=C '%s' -nographic -version 2>/dev/null",
1183 /* Intentionally ignore errors from qemu -version. */
1184 ignore_value (test_qemu_cmd (g, cmd, &g->qemu_version));
1190 test_qemu_cmd (guestfs_h *g, const char *cmd, char **ret)
1194 fp = popen (cmd, "r");
1198 if (read_all (g, fp, ret) == -1) {
1203 if (pclose (fp) != 0)
1210 read_all (guestfs_h *g, FILE *fp, char **ret)
1217 *ret = safe_realloc (g, *ret, n + 1);
1222 *ret = safe_realloc (g, *ret, n + BUFSIZ);
1224 r = fread (p, 1, BUFSIZ, fp);
1226 perrorf (g, "read");
1233 /* Test if option is supported by qemu command line (just by grepping
1236 * The first time this is used, it has to run the external qemu
1237 * binary. If that fails, it returns -1.
1239 * To just do the first-time run of the qemu binary, call this with
1240 * option == NULL, in which case it will return -1 if there was an
1244 qemu_supports (guestfs_h *g, const char *option)
1246 if (!g->qemu_help) {
1247 if (test_qemu (g) == -1)
1254 return strstr (g->qemu_help, option) != NULL;
1258 /* As above but using a regex instead of a fixed string. */
1260 qemu_supports_re (guestfs_h *g, const pcre *option_regex)
1262 if (!g->qemu_help) {
1263 if (test_qemu (g) == -1)
1267 return match (g, g->qemu_help, option_regex);
1271 /* Check if a file can be opened. */
1273 is_openable (guestfs_h *g, const char *path, int flags)
1275 int fd = open (path, flags);
1277 debug (g, "is_openable: %s: %m", path);
1284 /* You had to call this function after launch in versions <= 1.0.70,
1285 * but it is now a no-op.
1288 guestfs__wait_ready (guestfs_h *g)
1290 if (g->state != READY) {
1291 error (g, _("qemu has not been launched yet"));
1299 guestfs__kill_subprocess (guestfs_h *g)
1301 if (g->state == CONFIG) {
1302 error (g, _("no subprocess to kill"));
1306 debug (g, "sending SIGTERM to process %d", g->pid);
1308 if (g->pid > 0) kill (g->pid, SIGTERM);
1309 if (g->recoverypid > 0) kill (g->recoverypid, 9);
1314 /* Access current state. */
1316 guestfs__is_config (guestfs_h *g)
1318 return g->state == CONFIG;
1322 guestfs__is_launching (guestfs_h *g)
1324 return g->state == LAUNCHING;
1328 guestfs__is_ready (guestfs_h *g)
1330 return g->state == READY;
1334 guestfs__is_busy (guestfs_h *g)
1336 return g->state == BUSY;
1340 guestfs__get_state (guestfs_h *g)