Allow $TMPDIR to override most temporary directory uses.
[libguestfs.git] / test-tool / test-tool.c
1 /* libguestfs-test-tool
2  * Copyright (C) 2009 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program 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
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 #include <config.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <stdint.h>
24 #include <inttypes.h>
25 #include <string.h>
26 #include <fcntl.h>
27 #include <unistd.h>
28 #include <getopt.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/wait.h>
32 #include <locale.h>
33 #include <limits.h>
34
35 #include <guestfs.h>
36
37 #ifdef HAVE_GETTEXT
38 #include "gettext.h"
39 #define _(str) dgettext(PACKAGE, (str))
40 #define N_(str) dgettext(PACKAGE, (str))
41 #else
42 #define _(str) str
43 #define N_(str) str
44 #endif
45
46 #if !ENABLE_NLS
47 #undef textdomain
48 #define textdomain(Domainname) /* empty */
49 #undef bindtextdomain
50 #define bindtextdomain(Domainname, Dirname) /* empty */
51 #endif
52
53 #define STREQ(a,b) (strcmp((a),(b)) == 0)
54 #define STRCASEEQ(a,b) (strcasecmp((a),(b)) == 0)
55 #define STRNEQ(a,b) (strcmp((a),(b)) != 0)
56 #define STRCASENEQ(a,b) (strcasecmp((a),(b)) != 0)
57 #define STREQLEN(a,b,n) (strncmp((a),(b),(n)) == 0)
58 #define STRCASEEQLEN(a,b,n) (strncasecmp((a),(b),(n)) == 0)
59 #define STRNEQLEN(a,b,n) (strncmp((a),(b),(n)) != 0)
60 #define STRCASENEQLEN(a,b,n) (strncasecmp((a),(b),(n)) != 0)
61 #define STRPREFIX(a,b) (strncmp((a),(b),strlen((b))) == 0)
62
63 #ifndef P_tmpdir
64 #define P_tmpdir "/tmp"
65 #endif
66
67 #define DEFAULT_TIMEOUT 120
68
69 static const char *helper = DEFAULT_HELPER;
70 static int timeout = DEFAULT_TIMEOUT;
71 static char tmpf[] = P_tmpdir "/libguestfs-test-tool-sda-XXXXXX";
72 static char isof[] = P_tmpdir "/libguestfs-test-tool-iso-XXXXXX";
73 static guestfs_h *g;
74
75 static void preruncheck (void);
76 static void make_files (void);
77 static void set_qemu (const char *path, int use_wrapper);
78
79 static void
80 usage (void)
81 {
82   printf (_("libguestfs-test-tool: interactive test tool\n"
83             "Copyright (C) 2009 Red Hat Inc.\n"
84             "Usage:\n"
85             "  libguestfs-test-tool [--options]\n"
86             "Options:\n"
87             "  --help         Display usage\n"
88             "  --helper libguestfs-test-tool-helper\n"
89             "                 Helper program (default: %s)\n"
90             "  --qemudir dir  Specify QEMU source directory\n"
91             "  --qemu qemu    Specify QEMU binary\n"
92             "  --timeout n\n"
93             "  -t n           Set launch timeout (default: %d seconds)\n"
94             ),
95           DEFAULT_HELPER, DEFAULT_TIMEOUT);
96 }
97
98 int
99 main (int argc, char *argv[])
100 {
101   setlocale (LC_ALL, "");
102   bindtextdomain (PACKAGE, LOCALEBASEDIR);
103   textdomain (PACKAGE);
104
105   static const char *options = "t:?";
106   static const struct option long_options[] = {
107     { "help", 0, 0, '?' },
108     { "helper", 1, 0, 0 },
109     { "qemu", 1, 0, 0 },
110     { "qemudir", 1, 0, 0 },
111     { "timeout", 1, 0, 't' },
112     { 0, 0, 0, 0 }
113   };
114   int c;
115   int option_index;
116   extern char **environ;
117   int i;
118   struct guestfs_version *vers;
119   char *sfdisk_lines[] = { ",", NULL };
120   char *str;
121   /* XXX This is wrong if the user renames the helper. */
122   char *helper_args[] = { "/iso/libguestfs-test-tool-helper", NULL };
123
124   for (;;) {
125     c = getopt_long (argc, argv, options, long_options, &option_index);
126     if (c == -1) break;
127
128     switch (c) {
129     case 0:                     /* options which are long only */
130       if (STREQ (long_options[option_index].name, "helper"))
131         helper = optarg;
132       else if (STREQ (long_options[option_index].name, "qemu"))
133         set_qemu (optarg, 0);
134       else if (STREQ (long_options[option_index].name, "qemudir"))
135         set_qemu (optarg, 1);
136       else {
137         fprintf (stderr,
138                  _("libguestfs-test-tool: unknown long option: %s (%d)\n"),
139                  long_options[option_index].name, option_index);
140         exit (EXIT_FAILURE);
141       }
142       break;
143
144     case 't':
145       if (sscanf (optarg, "%d", &timeout) != 1 || timeout < 0) {
146         fprintf (stderr,
147                  _("libguestfs-test-tool: invalid timeout: %s\n"),
148                  optarg);
149         exit (EXIT_FAILURE);
150       }
151       break;
152
153     case '?':
154       usage ();
155       exit (EXIT_SUCCESS);
156
157     default:
158       fprintf (stderr,
159                _("libguestfs-test-tool: unexpected command line option 0x%x\n"),
160                c);
161       exit (EXIT_FAILURE);
162     }
163   }
164
165   preruncheck ();
166   make_files ();
167
168   printf ("===== Test starts here =====\n");
169
170   /* Must set LIBGUESTFS_DEBUG=1 */
171   setenv ("LIBGUESTFS_DEBUG", "1", 1);
172
173   /* Print out any environment variables which may relate to this test. */
174   for (i = 0; environ[i] != NULL; ++i)
175     if (STREQLEN (environ[i], "LIBGUESTFS_", 11))
176       printf ("%s\n", environ[i]);
177
178   /* Create the handle and configure it. */
179   g = guestfs_create ();
180   if (g == NULL) {
181     fprintf (stderr,
182              _("libguestfs-test-tool: failed to create libguestfs handle\n"));
183     exit (EXIT_FAILURE);
184   }
185   if (guestfs_add_drive (g, tmpf) == -1) {
186     fprintf (stderr,
187              _("libguestfs-test-tool: failed to add drive '%s'\n"),
188              tmpf);
189     exit (EXIT_FAILURE);
190   }
191   if (guestfs_add_drive (g, isof) == -1) {
192     fprintf (stderr,
193              _("libguestfs-test-tool: failed to add drive '%s'\n"),
194              isof);
195     exit (EXIT_FAILURE);
196   }
197
198   /* Print any version info etc. */
199   vers = guestfs_version (g);
200   if (vers == NULL) {
201     fprintf (stderr, _("libguestfs-test-tool: guestfs_version failed\n"));
202     exit (EXIT_FAILURE);
203   }
204   printf ("library version: %"PRIi64".%"PRIi64".%"PRIi64"%s\n",
205           vers->major, vers->minor, vers->release, vers->extra);
206   guestfs_free_version (vers);
207
208   printf ("guestfs_get_append: %s\n", guestfs_get_append (g) ? : "(null)");
209   printf ("guestfs_get_autosync: %d\n", guestfs_get_autosync (g));
210   printf ("guestfs_get_memsize: %d\n", guestfs_get_memsize (g));
211   printf ("guestfs_get_path: %s\n", guestfs_get_path (g));
212   printf ("guestfs_get_qemu: %s\n", guestfs_get_qemu (g));
213   printf ("guestfs_get_verbose: %d\n", guestfs_get_verbose (g));
214
215   /* Launch the guest handle. */
216   printf ("Launching appliance, timeout set to %d seconds.\n", timeout);
217   fflush (stdout);
218
219   alarm (timeout);
220
221   if (guestfs_launch (g) == -1) {
222     fprintf (stderr,
223              _("libguestfs-test-tool: failed to launch appliance\n"));
224     exit (EXIT_FAILURE);
225   }
226
227   alarm (0);
228
229   printf ("Guest launched OK.\n");
230   fflush (stdout);
231
232   /* Create the filesystem and mount everything. */
233   if (guestfs_sfdiskM (g, "/dev/sda", sfdisk_lines) == -1) {
234     fprintf (stderr,
235              _("libguestfs-test-tool: failed to run sfdisk\n"));
236     exit (EXIT_FAILURE);
237   }
238
239   if (guestfs_mkfs (g, "ext2", "/dev/sda1") == -1) {
240     fprintf (stderr,
241              _("libguestfs-test-tool: failed to mkfs.ext2\n"));
242     exit (EXIT_FAILURE);
243   }
244
245   if (guestfs_mount_options (g, "", "/dev/sda1", "/") == -1) {
246     fprintf (stderr,
247              _("libguestfs-test-tool: failed to mount /dev/sda1 on /\n"));
248     exit (EXIT_FAILURE);
249   }
250
251   if (guestfs_mkdir (g, "/iso") == -1) {
252     fprintf (stderr,
253              _("libguestfs-test-tool: failed to mkdir /iso\n"));
254     exit (EXIT_FAILURE);
255   }
256
257   if (guestfs_mount (g, "/dev/sdb", "/iso") == -1) {
258     fprintf (stderr,
259              _("libguestfs-test-tool: failed to mount /dev/sdb on /iso\n"));
260     exit (EXIT_FAILURE);
261   }
262
263   /* Let's now run some simple tests using the helper program. */
264   str = guestfs_command (g, helper_args);
265   if (str == NULL) {
266     fprintf (stderr,
267              _("libguestfs-test-tool: could not run helper program, or helper failed\n"));
268     exit (EXIT_FAILURE);
269   }
270   free (str);
271
272   printf ("===== TEST FINISHED OK =====\n");
273   exit (EXIT_SUCCESS);
274 }
275
276 static char qemuwrapper[] = P_tmpdir "/libguestfs-test-tool-wrapper-XXXXXX";
277
278 static void
279 cleanup_wrapper (void)
280 {
281   unlink (qemuwrapper);
282 }
283
284 /* Handle the --qemu and --qemudir parameters.  use_wrapper is true
285  * in the --qemudir (source directory) case, where we have to create
286  * a wrapper shell script.
287  */
288 static void
289 set_qemu (const char *path, int use_wrapper)
290 {
291   char buffer[PATH_MAX];
292   struct stat statbuf;
293   int fd;
294   FILE *fp;
295
296   if (getenv ("LIBGUESTFS_QEMU")) {
297     fprintf (stderr,
298     _("LIBGUESTFS_QEMU environment variable is already set, so\n"
299       "--qemu/--qemudir options cannot be used.\n"));
300     exit (EXIT_FAILURE);
301   }
302
303   if (!use_wrapper) {
304     if (access (path, X_OK) == -1) {
305       fprintf (stderr,
306                _("Binary '%s' does not exist or is not executable\n"),
307                path);
308       exit (EXIT_FAILURE);
309     }
310
311     setenv ("LIBGUESTFS_QEMU", path, 1);
312     return;
313   }
314
315   /* This should be a source directory, so check it. */
316   snprintf (buffer, sizeof buffer, "%s/pc-bios", path);
317   if (stat (buffer, &statbuf) == -1 ||
318       !S_ISDIR (statbuf.st_mode)) {
319     fprintf (stderr,
320              _("%s: does not look like a qemu source directory\n"),
321              path);
322     exit (EXIT_FAILURE);
323   }
324
325   /* Make a wrapper script. */
326   fd = mkstemp (qemuwrapper);
327   if (fd == -1) {
328     perror (qemuwrapper);
329     exit (EXIT_FAILURE);
330   }
331
332   fchmod (fd, 0700);
333
334   fp = fdopen (fd, "w");
335   fprintf (fp,
336            "#!/bin/sh -\n"
337            "qemudir='%s'\n"
338            "\"$qemudir\"/",
339            path);
340
341   /* Select the right qemu binary for the wrapper script. */
342 #ifdef __i386__
343   fprintf (fp, "i386-softmmu/qemu");
344 #else
345   fprintf (fp, host_cpu "-softmmu/qemu-system-" host_cpu);
346 #endif
347
348   fprintf (fp, " -L \"$qemudir\"/pc-bios \"$@\"\n");
349
350   fclose (fp);
351
352   setenv ("LIBGUESTFS_QEMU", qemuwrapper, 1);
353   atexit (cleanup_wrapper);
354 }
355
356 /* After getting the command line args, but before running
357  * anything, we check everything is in place to do the tests.
358  */
359 static void
360 preruncheck (void)
361 {
362   int r;
363   FILE *fp;
364   char cmd[256];
365   char buffer[1024];
366
367   if (access (helper, R_OK) == -1) {
368     fprintf (stderr,
369     _("Test tool helper program 'libguestfs-test-tool-helper' is not\n"
370       "available.  Expected to find it in '%s'\n"
371       "\n"
372       "Use the --helper option to specify the location of this program.\n"),
373              helper);
374     exit (EXIT_FAILURE);
375   }
376
377   snprintf (cmd, sizeof cmd, "file '%s'", helper);
378   fp = popen (cmd, "r");
379   if (fp == NULL) {
380     perror (cmd);
381     exit (EXIT_FAILURE);
382   }
383   r = fread (buffer, 1, sizeof buffer - 1, fp);
384   if (r == 0) {
385     fprintf (stderr, _("command failed: %s"), cmd);
386     exit (EXIT_FAILURE);
387   }
388   pclose (fp);
389   buffer[r] = '\0';
390
391   if (strstr (buffer, "statically linked") == NULL) {
392     fprintf (stderr,
393     _("Test tool helper program %s\n"
394       "is not statically linked.  This is a build error when this test tool\n"
395       "was built.\n"),
396              helper);
397     exit (EXIT_FAILURE);
398   }
399 }
400
401 static void
402 cleanup_tmpfiles (void)
403 {
404   unlink (tmpf);
405   unlink (isof);
406 }
407
408 static void
409 make_files (void)
410 {
411   int fd, r;
412   char cmd[256];
413
414   /* Make the ISO which will contain the helper program. */
415   fd = mkstemp (isof);
416   if (fd == -1) {
417     perror (isof);
418     exit (EXIT_FAILURE);
419   }
420   close (fd);
421
422   snprintf (cmd, sizeof cmd, "mkisofs -quiet -rJT -o '%s' '%s'",
423             isof, helper);
424   r = system (cmd);
425   if (r == -1 || WEXITSTATUS(r) != 0) {
426     fprintf (stderr,
427              _("mkisofs command failed: %s\n"), cmd);
428     exit (EXIT_FAILURE);
429   }
430
431   /* Allocate the sparse file for /dev/sda. */
432   fd = mkstemp (tmpf);
433   if (fd == -1) {
434     perror (tmpf);
435     unlink (isof);
436     exit (EXIT_FAILURE);
437   }
438
439   if (lseek (fd, 100 * 1024 * 1024 - 1, SEEK_SET) == -1) {
440     perror ("lseek");
441     close (fd);
442     unlink (tmpf);
443     unlink (isof);
444     exit (EXIT_FAILURE);
445   }
446
447   if (write (fd, "\0", 1) == -1) {
448     perror ("write");
449     close (fd);
450     unlink (tmpf);
451     unlink (isof);
452     exit (EXIT_FAILURE);
453   }
454
455   close (fd);
456
457   atexit (cleanup_tmpfiles);    /* Removes tmpf and isof. */
458 }