add-domain: Add allowuuid flag to allow UUIDs to be used for names.
[libguestfs.git] / src / virt.c
1 /* libguestfs
2  * Copyright (C) 2010 Red Hat Inc.
3  *
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.
8  *
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.
13  *
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
17  */
18
19 #include <config.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <assert.h>
24
25 #ifdef HAVE_LIBVIRT
26 #include <libvirt/libvirt.h>
27 #include <libvirt/virterror.h>
28 #endif
29
30 #ifdef HAVE_LIBXML2
31 #include <libxml/xpath.h>
32 #include <libxml/parser.h>
33 #include <libxml/tree.h>
34 #endif
35
36 #define GUESTFS_PRIVATE_FOR_EACH_DISK 1
37
38 #include "guestfs.h"
39 #include "guestfs-internal.h"
40 #include "guestfs-internal-actions.h"
41 #include "guestfs_protocol.h"
42
43 #if defined(HAVE_LIBVIRT) && defined(HAVE_LIBXML2)
44
45 static void init_libxml2 (void) __attribute__((constructor));
46
47 static void
48 init_libxml2 (void)
49 {
50   /* I am told that you don't really need to call virInitialize ... */
51
52   xmlInitParser ();
53   LIBXML_TEST_VERSION;
54 }
55
56 static void
57 ignore_errors (void *ignore, virErrorPtr ignore2)
58 {
59   /* empty */
60 }
61
62 struct guestfs___add_libvirt_dom_argv {
63   uint64_t bitmask;
64 #define GUESTFS___ADD_LIBVIRT_DOM_READONLY_BITMASK (UINT64_C(1)<<0)
65   int readonly;
66 #define GUESTFS___ADD_LIBVIRT_DOM_IFACE_BITMASK (UINT64_C(1)<<1)
67   const char *iface;
68 #define GUESTFS___ADD_LIBVIRT_DOM_LIVE_BITMASK (UINT64_C(1)<<2)
69   int live;
70 };
71
72 static int guestfs___add_libvirt_dom (guestfs_h *g, virDomainPtr dom, const struct guestfs___add_libvirt_dom_argv *optargs);
73
74 int
75 guestfs__add_domain (guestfs_h *g, const char *domain_name,
76                      const struct guestfs_add_domain_argv *optargs)
77 {
78   virErrorPtr err;
79   virConnectPtr conn = NULL;
80   virDomainPtr dom = NULL;
81   int r = -1;
82   const char *libvirturi;
83   int readonly;
84   int live;
85   int allowuuid;
86   const char *iface;
87   struct guestfs___add_libvirt_dom_argv optargs2 = { .bitmask = 0 };
88
89   libvirturi = optargs->bitmask & GUESTFS_ADD_DOMAIN_LIBVIRTURI_BITMASK
90                ? optargs->libvirturi : NULL;
91   readonly = optargs->bitmask & GUESTFS_ADD_DOMAIN_READONLY_BITMASK
92              ? optargs->readonly : 0;
93   iface = optargs->bitmask & GUESTFS_ADD_DOMAIN_IFACE_BITMASK
94           ? optargs->iface : NULL;
95   live = optargs->bitmask & GUESTFS_ADD_DOMAIN_LIVE_BITMASK
96          ? optargs->live : 0;
97   allowuuid = optargs->bitmask & GUESTFS_ADD_DOMAIN_ALLOWUUID_BITMASK
98             ? optargs->allowuuid : 0;
99
100   if (live && readonly) {
101     error (g, _("you cannot set both live and readonly flags"));
102     return -1;
103   }
104
105   /* Connect to libvirt, find the domain. */
106   conn = virConnectOpenReadOnly (libvirturi);
107   if (!conn) {
108     err = virGetLastError ();
109     error (g, _("could not connect to libvirt (code %d, domain %d): %s"),
110            err->code, err->domain, err->message);
111     goto cleanup;
112   }
113
114   /* Suppress default behaviour of printing errors to stderr.  Note
115    * you can't set this to NULL to ignore errors; setting it to NULL
116    * restores the default error handler ...
117    */
118   virConnSetErrorFunc (conn, NULL, ignore_errors);
119
120   /* Try UUID first. */
121   if (allowuuid)
122     dom = virDomainLookupByUUIDString (conn, domain_name);
123
124   /* Try ordinary domain name. */
125   if (!dom)
126     dom = virDomainLookupByName (conn, domain_name);
127
128   if (!dom) {
129     err = virGetLastError ();
130     error (g, _("no libvirt domain called '%s': %s"),
131            domain_name, err->message);
132     goto cleanup;
133   }
134
135   if (readonly) {
136     optargs2.bitmask |= GUESTFS___ADD_LIBVIRT_DOM_READONLY_BITMASK;
137     optargs2.readonly = readonly;
138   }
139   if (iface) {
140     optargs2.bitmask |= GUESTFS___ADD_LIBVIRT_DOM_IFACE_BITMASK;
141     optargs2.iface = iface;
142   }
143   if (live) {
144     optargs2.bitmask |= GUESTFS___ADD_LIBVIRT_DOM_LIVE_BITMASK;
145     optargs2.live = live;
146   }
147
148   r = guestfs___add_libvirt_dom (g, dom, &optargs2);
149
150  cleanup:
151   if (dom) virDomainFree (dom);
152   if (conn) virConnectClose (conn);
153
154   return r;
155 }
156
157 /* This function is also used in virt-df to avoid having all that
158  * stupid XPath code repeated.  This is something that libvirt should
159  * really provide.
160  *
161  * The callback function 'f' is called once for each disk.
162  *
163  * Returns number of disks, or -1 if there was an error.
164  */
165 int
166 guestfs___for_each_disk (guestfs_h *g,
167                          virDomainPtr dom,
168                          int (*f) (guestfs_h *g,
169                                    const char *filename, const char *format,
170                                    void *data),
171                          void *data)
172 {
173   int i, nr_added = 0, r = -1;
174   virErrorPtr err;
175   xmlDocPtr doc = NULL;
176   xmlXPathContextPtr xpathCtx = NULL;
177   xmlXPathObjectPtr xpathObj = NULL;
178   char *xml = NULL;
179
180   /* Domain XML. */
181   xml = virDomainGetXMLDesc (dom, 0);
182
183   if (!xml) {
184     err = virGetLastError ();
185     error (g, _("error reading libvirt XML information: %s"),
186            err->message);
187     goto cleanup;
188   }
189
190   /* Now the horrible task of parsing out the fields we need from the XML.
191    * http://www.xmlsoft.org/examples/xpath1.c
192    */
193   doc = xmlParseMemory (xml, strlen (xml));
194   if (doc == NULL) {
195     error (g, _("unable to parse XML information returned by libvirt"));
196     goto cleanup;
197   }
198
199   xpathCtx = xmlXPathNewContext (doc);
200   if (xpathCtx == NULL) {
201     error (g, _("unable to create new XPath context"));
202     goto cleanup;
203   }
204
205   /* This gives us a set of all the <disk> nodes. */
206   xpathObj = xmlXPathEvalExpression (BAD_CAST "//devices/disk", xpathCtx);
207   if (xpathObj == NULL) {
208     error (g, _("unable to evaluate XPath expression"));
209     goto cleanup;
210   }
211
212   xmlNodeSetPtr nodes = xpathObj->nodesetval;
213   for (i = 0; i < nodes->nodeNr; ++i) {
214     xmlXPathObjectPtr xptype;
215
216     /* Change the context to the current <disk> node.
217      * DV advises to reset this before each search since older versions of
218      * libxml2 might overwrite it.
219      */
220     xpathCtx->node = nodes->nodeTab[i];
221
222     /* Filename can be in <source dev=..> or <source file=..> attribute.
223      * Check the <disk type=..> attribute first to find out which one.
224      */
225     xptype = xmlXPathEvalExpression (BAD_CAST "./@type", xpathCtx);
226     if (xptype == NULL ||
227         xptype->nodesetval == NULL ||
228         xptype->nodesetval->nodeNr == 0) {
229       xmlXPathFreeObject (xptype);
230       continue;                 /* no type attribute, skip it */
231     }
232     assert (xptype->nodesetval->nodeTab[0]);
233     assert (xptype->nodesetval->nodeTab[0]->type == XML_ATTRIBUTE_NODE);
234     xmlAttrPtr attr = (xmlAttrPtr) xptype->nodesetval->nodeTab[0];
235     char *type = (char *) xmlNodeListGetString (doc, attr->children, 1);
236     xmlXPathFreeObject (xptype);
237
238     xmlXPathObjectPtr xpfilename;
239
240     if (STREQ (type, "file")) { /* type = "file" so look at source/@file */
241       free (type);
242
243       xpathCtx->node = nodes->nodeTab[i];
244       xpfilename = xmlXPathEvalExpression (BAD_CAST "./source/@file", xpathCtx);
245       if (xpfilename == NULL ||
246           xpfilename->nodesetval == NULL ||
247           xpfilename->nodesetval->nodeNr == 0) {
248         xmlXPathFreeObject (xpfilename);
249         continue;             /* disk filename not found, skip this */
250       }
251     } else if (STREQ (type, "block")) { /* type = "block", use source/@dev */
252       free (type);
253
254       xpathCtx->node = nodes->nodeTab[i];
255       xpfilename = xmlXPathEvalExpression (BAD_CAST "./source/@dev", xpathCtx);
256       if (xpfilename == NULL ||
257           xpfilename->nodesetval == NULL ||
258           xpfilename->nodesetval->nodeNr == 0) {
259         xmlXPathFreeObject (xpfilename);
260         continue;             /* disk filename not found, skip this */
261       }
262     } else {
263       free (type);
264       continue;               /* type <> "file" or "block", skip it */
265     }
266
267     assert (xpfilename->nodesetval->nodeTab[0]);
268     assert (xpfilename->nodesetval->nodeTab[0]->type == XML_ATTRIBUTE_NODE);
269     attr = (xmlAttrPtr) xpfilename->nodesetval->nodeTab[0];
270     char *filename = (char *) xmlNodeListGetString (doc, attr->children, 1);
271
272     /* Get the disk format (may not be set). */
273     xmlXPathObjectPtr xpformat;
274
275     xpathCtx->node = nodes->nodeTab[i];
276     xpformat = xmlXPathEvalExpression (BAD_CAST "./driver/@type", xpathCtx);
277     char *format = NULL;
278     if (xpformat != NULL &&
279         xpformat->nodesetval &&
280         xpformat->nodesetval->nodeNr > 0) {
281       assert (xpformat->nodesetval->nodeTab[0]);
282       assert (xpformat->nodesetval->nodeTab[0]->type == XML_ATTRIBUTE_NODE);
283       attr = (xmlAttrPtr) xpformat->nodesetval->nodeTab[0];
284       format = (char *) xmlNodeListGetString (doc, attr->children, 1);
285     }
286
287     int t;
288     if (f)
289       t = f (g, filename, format, data);
290     else
291       t = 0;
292
293     xmlFree (filename);
294     xmlFree (format);
295     xmlXPathFreeObject (xpfilename);
296     xmlXPathFreeObject (xpformat);
297
298     if (t == -1)
299       goto cleanup;
300
301     nr_added++;
302   }
303
304   if (nr_added == 0) {
305     error (g, _("libvirt domain has no disks"));
306     goto cleanup;
307   }
308
309   /* Successful. */
310   r = nr_added;
311
312  cleanup:
313   free (xml);
314   if (xpathObj) xmlXPathFreeObject (xpathObj);
315   if (xpathCtx) xmlXPathFreeContext (xpathCtx);
316   if (doc) xmlFreeDoc (doc);
317
318   return r;
319 }
320
321 /* This was proposed as an external API, but it's not quite baked yet. */
322
323 static int add_disk (guestfs_h *g, const char *filename, const char *format, void *optargs_vp);
324 static int connect_live (guestfs_h *g, virDomainPtr dom);
325
326 static int
327 guestfs___add_libvirt_dom (guestfs_h *g, virDomainPtr dom,
328                            const struct guestfs___add_libvirt_dom_argv *optargs)
329 {
330   size_t cmdline_pos;
331   int r;
332   int readonly;
333   const char *iface;
334   int live;
335
336   readonly =
337     optargs->bitmask & GUESTFS___ADD_LIBVIRT_DOM_READONLY_BITMASK
338     ? optargs->readonly : 0;
339   iface =
340     optargs->bitmask & GUESTFS___ADD_LIBVIRT_DOM_IFACE_BITMASK
341     ? optargs->iface : NULL;
342   live =
343     optargs->bitmask & GUESTFS___ADD_LIBVIRT_DOM_LIVE_BITMASK
344     ? optargs->live : 0;
345
346   if (live && readonly) {
347     error (g, _("you cannot set both live and readonly flags"));
348     return -1;
349   }
350
351   if (!readonly) {
352     virDomainInfo info;
353     virErrorPtr err;
354     int vm_running;
355
356     if (virDomainGetInfo (dom, &info) == -1) {
357       err = virGetLastError ();
358       error (g, _("error getting domain info: %s"), err->message);
359       return -1;
360     }
361     vm_running = info.state != VIR_DOMAIN_SHUTOFF;
362
363     if (vm_running) {
364       /* If the caller specified the 'live' flag, then they want us to
365        * try to connect to guestfsd if the domain is running.  Note
366        * that live readonly connections are not possible.
367        */
368       if (live)
369         return connect_live (g, dom);
370
371       /* Dangerous to modify the disks of a running VM. */
372       error (g, _("error: domain is a live virtual machine.\n"
373                   "Writing to the disks of a running virtual machine can cause disk corruption.\n"
374                   "Either use read-only access, or if the guest is running the guestfsd daemon\n"
375                   "specify live access.  In most libguestfs tools these options are --ro or\n"
376                   "--live respectively.  Consult the documentation for further information."));
377       return -1;
378     }
379   }
380
381   /* Add the disks. */
382   struct guestfs_add_drive_opts_argv optargs2 = { .bitmask = 0 };
383   if (readonly) {
384     optargs2.bitmask |= GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK;
385     optargs2.readonly = readonly;
386   }
387   if (iface) {
388     optargs2.bitmask |= GUESTFS_ADD_DRIVE_OPTS_IFACE_BITMASK;
389     optargs2.iface = iface;
390   }
391
392   /* Checkpoint the command line around the operation so that either
393    * all disks are added or none are added.
394    */
395   cmdline_pos = guestfs___checkpoint_cmdline (g);
396   r = guestfs___for_each_disk (g, dom, add_disk, &optargs2);
397   if (r == -1)
398     guestfs___rollback_cmdline (g, cmdline_pos);
399
400   return r;
401 }
402
403 static int
404 add_disk (guestfs_h *g, const char *filename, const char *format,
405           void *optargs_vp)
406 {
407   struct guestfs_add_drive_opts_argv *optargs = optargs_vp;
408
409   if (format) {
410     optargs->bitmask |= GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK;
411     optargs->format = format;
412   } else
413     optargs->bitmask &= ~GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK;
414
415   return guestfs__add_drive_opts (g, filename, optargs);
416 }
417
418 static int
419 connect_live (guestfs_h *g, virDomainPtr dom)
420 {
421   int i, r = -1;
422   virErrorPtr err;
423   xmlDocPtr doc = NULL;
424   xmlXPathContextPtr xpathCtx = NULL;
425   xmlXPathObjectPtr xpathObj = NULL;
426   char *xml = NULL;
427   char *path = NULL;
428   char *attach_method = NULL;
429
430   /* Domain XML. */
431   xml = virDomainGetXMLDesc (dom, 0);
432
433   if (!xml) {
434     err = virGetLastError ();
435     error (g, _("error reading libvirt XML information: %s"),
436            err->message);
437     goto cleanup;
438   }
439
440   /* Parse XML to document. */
441   doc = xmlParseMemory (xml, strlen (xml));
442   if (doc == NULL) {
443     error (g, _("unable to parse XML information returned by libvirt"));
444     goto cleanup;
445   }
446
447   xpathCtx = xmlXPathNewContext (doc);
448   if (xpathCtx == NULL) {
449     error (g, _("unable to create new XPath context"));
450     goto cleanup;
451   }
452
453   /* This gives us a set of all the <channel> nodes related to the
454    * guestfsd virtio-serial channel.
455    */
456   xpathObj = xmlXPathEvalExpression (BAD_CAST
457       "//devices/channel[@type=\"unix\" and "
458                         "./source/@mode=\"bind\" and "
459                         "./source/@path and "
460                         "./target/@type=\"virtio\" and "
461                         "./target/@name=\"org.libguestfs.channel.0\"]",
462                                      xpathCtx);
463   if (xpathObj == NULL) {
464     error (g, _("unable to evaluate XPath expression"));
465     goto cleanup;
466   }
467
468   xmlNodeSetPtr nodes = xpathObj->nodesetval;
469   for (i = 0; i < nodes->nodeNr; ++i) {
470     xmlXPathObjectPtr xppath;
471
472     /* See note in function above. */
473     xpathCtx->node = nodes->nodeTab[i];
474
475     /* The path is in <source path=..> attribute. */
476     xppath = xmlXPathEvalExpression (BAD_CAST "./source/@path", xpathCtx);
477     if (xppath == NULL ||
478         xppath->nodesetval == NULL ||
479         xppath->nodesetval->nodeNr == 0) {
480       xmlXPathFreeObject (xppath);
481       continue;                 /* no type attribute, skip it */
482     }
483     assert (xppath->nodesetval->nodeTab[0]);
484     assert (xppath->nodesetval->nodeTab[0]->type == XML_ATTRIBUTE_NODE);
485     xmlAttrPtr attr = (xmlAttrPtr) xppath->nodesetval->nodeTab[0];
486     path = (char *) xmlNodeListGetString (doc, attr->children, 1);
487     xmlXPathFreeObject (xppath);
488     break;
489   }
490
491   if (path == NULL) {
492     error (g, _("this guest has no libvirt <channel> definition for guestfsd\n"
493                 "See ATTACHING TO RUNNING DAEMONS in guestfs(3) for further information."));
494     goto cleanup;
495   }
496
497   /* Got a path. */
498   attach_method = safe_malloc (g, strlen (path) + 5 + 1);
499   strcpy (attach_method, "unix:");
500   strcat (attach_method, path);
501   r = guestfs_set_attach_method (g, attach_method);
502
503  cleanup:
504   free (path);
505   free (attach_method);
506   free (xml);
507   if (xpathObj) xmlXPathFreeObject (xpathObj);
508   if (xpathCtx) xmlXPathFreeContext (xpathCtx);
509   if (doc) xmlFreeDoc (doc);
510
511   return r;
512 }
513
514 #else /* no libvirt or libxml2 at compile time */
515
516 #define NOT_IMPL(r)                                                     \
517   error (g, _("add-domain API not available since this version of libguestfs was compiled without libvirt or libxml2")); \
518   return r
519
520 int
521 guestfs__add_domain (guestfs_h *g, const char *dom,
522                      const struct guestfs_add_domain_argv *optargs)
523 {
524   NOT_IMPL(-1);
525 }
526
527 #endif /* no libvirt or libxml2 at compile time */