New API: set-smp, get-smp
[libguestfs.git] / rescue / virt-rescue.c
1 /* virt-rescue
2  * Copyright (C) 2010-2011 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 <string.h>
24 #include <inttypes.h>
25 #include <unistd.h>
26 #include <getopt.h>
27 #include <errno.h>
28 #include <locale.h>
29 #include <assert.h>
30 #include <libintl.h>
31
32 #include "ignore-value.h"
33 #include "progname.h"
34 #include "xvasprintf.h"
35
36 #include "guestfs.h"
37 #include "options.h"
38
39 /* Currently open libguestfs handle. */
40 guestfs_h *g;
41
42 int read_only = 0;
43 int live = 0;
44 int verbose = 0;
45 int keys_from_stdin = 0;
46 int echo_keys = 0;
47 const char *libvirt_uri = NULL;
48 int inspector = 0;
49
50 static inline char *
51 bad_cast (char const *s)
52 {
53   return (char *) s;
54 }
55
56 static void __attribute__((noreturn))
57 usage (int status)
58 {
59   if (status != EXIT_SUCCESS)
60     fprintf (stderr, _("Try `%s --help' for more information.\n"),
61              program_name);
62   else {
63     fprintf (stdout,
64            _("%s: Run a rescue shell on a virtual machine\n"
65              "Copyright (C) 2009-2010 Red Hat Inc.\n"
66              "Usage:\n"
67              "  %s [--options] -d domname\n"
68              "  %s [--options] -a disk.img [-a disk.img ...]\n"
69              "Options:\n"
70              "  -a|--add image       Add image\n"
71              "  --append kernelopts  Append kernel options\n"
72              "  -c|--connect uri     Specify libvirt URI for -d option\n"
73              "  -d|--domain guest    Add disks from libvirt guest\n"
74              "  --format[=raw|..]    Force disk format for -a option\n"
75              "  --help               Display brief help\n"
76              "  -m|--memsize MB      Set memory size in megabytes\n"
77              "  --network            Enable network\n"
78              "  -r|--ro              Access read-only\n"
79              "  --selinux            Enable SELinux\n"
80              "  --smp N              Enable SMP with N >= 2 virtual CPUs\n"
81              "  -v|--verbose         Verbose messages\n"
82              "  -V|--version         Display version and exit\n"
83              "  -w|--rw              Mount read-write\n"
84              "  -x                   Trace libguestfs API calls\n"
85              "For more information, see the manpage %s(1).\n"),
86              program_name, program_name, program_name,
87              program_name);
88   }
89   exit (status);
90 }
91
92 int
93 main (int argc, char *argv[])
94 {
95   /* Set global program name that is not polluted with libtool artifacts.  */
96   set_program_name (argv[0]);
97
98   setlocale (LC_ALL, "");
99   bindtextdomain (PACKAGE, LOCALEBASEDIR);
100   textdomain (PACKAGE);
101
102   parse_config ();
103
104   enum { HELP_OPTION = CHAR_MAX + 1 };
105
106   static const char *options = "a:c:d:m:rvVx";
107   static const struct option long_options[] = {
108     { "add", 1, 0, 'a' },
109     { "append", 1, 0, 0 },
110     { "connect", 1, 0, 'c' },
111     { "domain", 1, 0, 'd' },
112     { "format", 2, 0, 0 },
113     { "help", 0, 0, HELP_OPTION },
114     { "memsize", 1, 0, 'm' },
115     { "network", 0, 0, 0 },
116     { "ro", 0, 0, 'r' },
117     { "rw", 0, 0, 'w' },
118     { "selinux", 0, 0, 0 },
119     { "smp", 1, 0, 0 },
120     { "verbose", 0, 0, 'v' },
121     { "version", 0, 0, 'V' },
122     { 0, 0, 0, 0 }
123   };
124   struct drv *drvs = NULL;
125   struct drv *drv;
126   const char *format = NULL;
127   int c;
128   int option_index;
129   int network = 0;
130   const char *append = NULL;
131   char *append_full;
132   int memsize = 0;
133   int smp = 0;
134
135   g = guestfs_create ();
136   if (g == NULL) {
137     fprintf (stderr, _("guestfs_create: failed to create handle\n"));
138     exit (EXIT_FAILURE);
139   }
140
141   argv[0] = bad_cast (program_name);
142
143   for (;;) {
144     c = getopt_long (argc, argv, options, long_options, &option_index);
145     if (c == -1) break;
146
147     switch (c) {
148     case 0:                     /* options which are long only */
149       if (STREQ (long_options[option_index].name, "selinux")) {
150         guestfs_set_selinux (g, 1);
151       } else if (STREQ (long_options[option_index].name, "append")) {
152         append = optarg;
153       } else if (STREQ (long_options[option_index].name, "network")) {
154         network = 1;
155       } else if (STREQ (long_options[option_index].name, "format")) {
156         if (!optarg || STREQ (optarg, ""))
157           format = NULL;
158         else
159           format = optarg;
160       } else if (STREQ (long_options[option_index].name, "smp")) {
161         if (sscanf (optarg, "%u", &smp) != 1) {
162           fprintf (stderr, _("%s: could not parse --smp parameter '%s'\n"),
163                    program_name, optarg);
164           exit (EXIT_FAILURE);
165         }
166         if (smp < 1) {
167           fprintf (stderr, _("%s: --smp parameter '%s' should be >= 1\n"),
168                    program_name, optarg);
169           exit (EXIT_FAILURE);
170         }
171       } else {
172         fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
173                  program_name, long_options[option_index].name, option_index);
174         exit (EXIT_FAILURE);
175       }
176       break;
177
178     case 'a':
179       OPTION_a;
180       break;
181
182     case 'c':
183       OPTION_c;
184       break;
185
186     case 'd':
187       OPTION_d;
188       break;
189
190     case 'h':
191       usage (EXIT_SUCCESS);
192
193     case 'm':
194       if (sscanf (optarg, "%u", &memsize) != 1) {
195         fprintf (stderr, _("%s: could not parse memory size '%s'\n"),
196                  program_name, optarg);
197         exit (EXIT_FAILURE);
198       }
199       break;
200
201     case 'r':
202       OPTION_r;
203       break;
204
205     case 'v':
206       OPTION_v;
207       break;
208
209     case 'V':
210       OPTION_V;
211       break;
212
213     case 'w':
214       OPTION_w;
215       break;
216
217     case 'x':
218       OPTION_x;
219       break;
220
221     case HELP_OPTION:
222       usage (EXIT_SUCCESS);
223
224     default:
225       usage (EXIT_FAILURE);
226     }
227   }
228
229   /* Old-style syntax?  There were no -a or -d options in the old
230    * virt-rescue which is how we detect this.
231    */
232   if (drvs == NULL) {
233     while (optind < argc) {
234       if (strchr (argv[optind], '/') ||
235           access (argv[optind], F_OK) == 0) { /* simulate -a option */
236         drv = malloc (sizeof (struct drv));
237         if (!drv) {
238           perror ("malloc");
239           exit (EXIT_FAILURE);
240         }
241         drv->type = drv_a;
242         drv->a.filename = argv[optind];
243         drv->a.format = NULL;
244         drv->next = drvs;
245         drvs = drv;
246       } else {                  /* simulate -d option */
247         drv = malloc (sizeof (struct drv));
248         if (!drv) {
249           perror ("malloc");
250           exit (EXIT_FAILURE);
251         }
252         drv->type = drv_d;
253         drv->d.guest = argv[optind];
254         drv->next = drvs;
255         drvs = drv;
256       }
257
258       optind++;
259     }
260   }
261
262   /* These are really constants, but they have to be variables for the
263    * options parsing code.  Assert here that they have known-good
264    * values.
265    */
266   assert (inspector == 0);
267   assert (keys_from_stdin == 0);
268   assert (echo_keys == 0);
269   assert (live == 0);
270
271   /* Must be no extra arguments on the command line. */
272   if (optind != argc)
273     usage (EXIT_FAILURE);
274
275   /* User must have specified some drives. */
276   if (drvs == NULL)
277     usage (EXIT_FAILURE);
278
279   /* Setting "direct mode" is required for the rescue appliance. */
280   guestfs_set_direct (g, 1);
281
282   /* Set other features. */
283   if (memsize > 0)
284     guestfs_set_memsize (g, memsize);
285   if (network)
286     guestfs_set_network (g, 1);
287   if (smp >= 1)
288     guestfs_set_smp (g, smp);
289
290   /* Kernel command line must include guestfs_rescue=1 (see
291    * appliance/init) as well as other options.
292    */
293   append_full = xasprintf ("guestfs_rescue=1%s%s",
294                            append ? " " : "",
295                            append ? append : "");
296   guestfs_set_append (g, append_full);
297   free (append_full);
298
299   /* Add drives. */
300   add_drives (drvs, 'a');
301
302   /* Free up data structures, no longer needed after this point. */
303   free_drives (drvs);
304
305   /* Run the appliance.  This won't return until the user quits the
306    * appliance.
307    */
308   guestfs_set_error_handler (g, NULL, NULL);
309
310   /* We expect launch to fail, so ignore the return value. */
311   ignore_value (guestfs_launch (g));
312
313   guestfs_close (g);
314
315   exit (EXIT_SUCCESS);
316 }
317
318 /* The following was a nice idea, but in fact it doesn't work.  This is
319  * because qemu has some (broken) pty emulation itself.
320  */
321 #if 0
322   int fd_m, fd_s, r;
323   pid_t pid;
324   struct termios tsorig, tsnew;
325
326   /* Set up pty. */
327   fd_m = posix_openpt (O_RDWR);
328   if (fd_m == -1) {
329     perror ("posix_openpt");
330     exit (EXIT_FAILURE);
331   }
332   r = grantpt (fd_m);
333   if (r == -1) {
334     perror ("grantpt");
335     exit (EXIT_FAILURE);
336   }
337   r = unlockpt (fd_m);
338   if (r == -1) {
339     perror ("unlockpt");
340     exit (EXIT_FAILURE);
341   }
342   fd_s = open (ptsname (fd_m), O_RDWR);
343   if (fd_s == -1) {
344     perror ("open ptsname");
345     exit (EXIT_FAILURE);
346   }
347
348   pid = fork ();
349   if (pid == -1) {
350     perror ("fork");
351     exit (EXIT_FAILURE);
352   }
353   if (pid == 0) {
354     /* Child process. */
355
356 #if 1
357     /* Set raw mode. */
358     r = tcgetattr (fd_s, &tsorig);
359     tsnew = tsorig;
360     cfmakeraw (&tsnew);
361     tcsetattr (fd_s, TCSANOW, &tsnew);
362 #endif
363
364     /* Close the master side of pty and set slave side as
365      * stdin/stdout/stderr.
366      */
367     close (fd_m);
368
369     close (0);
370     close (1);
371     close (2);
372     if (dup (fd_s) == -1 || dup (fd_s) == -1 || dup (fd_s) == -1) {
373       perror ("dup");
374       exit (EXIT_FAILURE);
375     }
376     close (fd_s);
377
378 #if 1
379     if (setsid () == -1)
380       perror ("warning: failed to setsid");
381     if (ioctl (0, TIOCSCTTY, 0) == -1)
382       perror ("warning: failed to TIOCSCTTY");
383 #endif
384
385     /* Run the appliance.  This won't return until the user quits the
386      * appliance.
387      */
388     guestfs_set_error_handler (g, NULL, NULL);
389     r = guestfs_launch (g);
390
391     /* launch() expects guestfsd to start. However, virt-rescue doesn't
392      * run guestfsd, so this will always fail with ECHILD when the
393      * appliance exits unexpectedly.
394      */
395     if (errno != ECHILD) {
396       fprintf (stderr, "%s: %s\n", program_name, guestfs_last_error (g));
397       guestfs_close (g);
398       exit (EXIT_FAILURE);
399     }
400
401     guestfs_close (g);
402     _exit (EXIT_SUCCESS);
403   }
404
405   /* Parent process continues ... */
406
407   /* Close slave side of pty. */
408   close (fd_s);
409
410   /* Set raw mode. */
411   r = tcgetattr (fd_s, &tsorig);
412   tsnew = tsorig;
413   cfmakeraw (&tsnew);
414   tcsetattr (fd_s, TCSANOW, &tsnew);
415
416   /* Send input and output to master side of pty. */
417   r = multiplex (fd_m);
418   tcsetattr (fd_s, TCSANOW, &tsorig); /* Restore cooked mode. */
419   if (r == -1)
420     exit (EXIT_FAILURE);
421
422   if (waitpid (pid, &r, 0) == -1) {
423     perror ("waitpid");
424     exit (EXIT_FAILURE);
425   }
426   if (!WIFEXITED (r)) {
427     /* abnormal child exit */
428     fprintf (stderr, _("%s: unknown child exit status (%d)\n"),
429              program_name, r);
430     exit (EXIT_FAILURE);
431   }
432   else
433     exit (WEXITSTATUS (r)); /* normal exit, return child process's status */
434 }
435
436 /* Naive and simple multiplex function. */
437 static int
438 multiplex (int fd_m)
439 {
440   int r, eof_stdin = 0;
441   fd_set rfds, wfds;
442   char tobuf[BUFSIZ], frombuf[BUFSIZ]; /* to/from slave */
443   size_t tosize = 0, fromsize = 0;
444   ssize_t n;
445   size_t count;
446   long flags_0, flags_1, flags_fd_m;
447
448   flags_0 = fcntl (0, F_GETFL);
449   fcntl (0, F_SETFL, O_NONBLOCK | flags_0);
450   flags_1 = fcntl (0, F_GETFL);
451   fcntl (1, F_SETFL, O_NONBLOCK | flags_1);
452   flags_fd_m = fcntl (0, F_GETFL);
453   fcntl (fd_m, F_SETFL, O_NONBLOCK | flags_fd_m);
454
455   for (;;) {
456     FD_ZERO (&rfds);
457     FD_ZERO (&wfds);
458
459     /* Still space in to-buffer?  If so, we can read from the user. */
460     if (!eof_stdin && tosize < BUFSIZ)
461       FD_SET (0, &rfds);
462     /* Still space in from-buffer?  If so, we can read from the slave. */
463     if (fromsize < BUFSIZ)
464       FD_SET (fd_m, &rfds);
465     /* Content in to-buffer?  If so, we want to write to the slave. */
466     if (tosize > 0)
467       FD_SET (fd_m, &wfds);
468     /* Content in from-buffer?  If so, we want to write to the user. */
469     if (fromsize > 0)
470       FD_SET (1, &wfds);
471
472     r = select (fd_m+1, &rfds, &wfds, NULL, NULL);
473     if (r == -1) {
474       if (errno == EAGAIN || errno == EINTR)
475         continue;
476       perror ("select");
477       return -1;
478     }
479
480     /* Input from user: Put it in the to-buffer. */
481     if (FD_ISSET (0, &rfds)) {
482       count = BUFSIZ - tosize;
483       n = read (0, &tobuf[tosize], count);
484       if (n == -1) {
485         perror ("read");
486         return -1;
487       }
488       if (n == 0) { /* stdin was closed */
489         eof_stdin = 1;
490         /* This is what telnetd does ... */
491         tobuf[tosize] = '\004';
492         tosize += 1;
493       } else
494         tosize += n;
495     }
496
497     /* Input from slave: Put it in the from-buffer. */
498     if (FD_ISSET (fd_m, &rfds)) {
499       count = BUFSIZ - fromsize;
500       n = read (fd_m, &frombuf[fromsize], count);
501       if (n == -1) {
502         if (errno != EIO) /* EIO if slave process dies */
503           perror ("read");
504         break;
505       }
506       if (n == 0) /* slave closed the connection */
507         break;
508       fromsize += n;
509     }
510
511     /* Can write to user. */
512     if (FD_ISSET (1, &wfds)) {
513       n = write (1, frombuf, fromsize);
514       if (n == -1) {
515         perror ("write");
516         return -1;
517       }
518       memmove (frombuf, &frombuf[n], BUFSIZ - n);
519       fromsize -= n;
520     }
521
522     /* Can write to slave. */
523     if (FD_ISSET (fd_m, &wfds)) {
524       n = write (fd_m, tobuf, tosize);
525       if (n == -1) {
526         perror ("write");
527         return -1;
528       }
529       memmove (tobuf, &tobuf[n], BUFSIZ - n);
530       tosize -= n;
531     }
532   } /* for (;;) */
533
534   /* We end up here when slave has closed the connection. */
535   close (fd_m);
536
537   /* Restore blocking behaviour. */
538   fcntl (1, F_SETFL, flags_1);
539
540   /* Last chance to write out any remaining data in the buffers, but
541    * don't bother about errors.
542    */
543   ignore_value (write (1, frombuf, fromsize));
544
545   return 0;
546 }
547 #endif