df: Rewrite virt-df in C.
[libguestfs.git] / df / domains.c
1 /* virt-df
2  * Copyright (C) 2010 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 <assert.h>
25
26 #ifdef HAVE_LIBVIRT
27 #include <libvirt/libvirt.h>
28 #include <libvirt/virterror.h>
29 #endif
30
31 #include "progname.h"
32
33 #define GUESTFS_PRIVATE_FOR_EACH_DISK 1
34
35 #include "guestfs.h"
36 #include "options.h"
37 #include "virt-df.h"
38
39 #ifdef HAVE_LIBVIRT
40
41 /* Limit the number of devices we will ever add to the appliance.  The
42  * overall limit in current libguestfs is 25: 26 = number of letters
43  * in the English alphabet since we are only confident that
44  * /dev/sd[a-z] will work because of various limits, minus 1 because
45  * that may be used by the ext2 initial filesystem.  (RHBZ#635373).
46  */
47 #define MAX_DISKS 25
48
49 /* The list of domains and disks that we build up in
50  * get_domains_from_libvirt.
51  */
52 struct disk {
53   struct disk *next;
54   char *filename;
55   char *format; /* could be NULL */
56 };
57
58 struct domain {
59   char *name;
60   char *uuid;
61   struct disk *disks;
62   size_t nr_disks;
63 };
64
65 struct domain *domains = NULL;
66 size_t nr_domains;
67
68 static int
69 compare_domain_names (const void *p1, const void *p2)
70 {
71   const struct domain *d1 = p1;
72   const struct domain *d2 = p2;
73
74   return strcmp (d1->name, d2->name);
75 }
76
77 static void
78 free_domain (struct domain *domain)
79 {
80   struct disk *disk, *next;
81
82   for (disk = domain->disks; disk; disk = next) {
83     next = disk->next;
84     free (disk->filename);
85     free (disk->format);
86     free (disk);
87   }
88
89   free (domain->name);
90   free (domain->uuid);
91 }
92
93 static void add_domains_by_id (virConnectPtr conn, int *ids, size_t n);
94 static void add_domains_by_name (virConnectPtr conn, char **names, size_t n);
95 static void add_domain (virDomainPtr dom);
96 static int add_disk (guestfs_h *g, const char *filename, const char *format, void *domain_vp);
97 static void multi_df (struct domain *, size_t n);
98
99 void
100 get_domains_from_libvirt (void)
101 {
102   virErrorPtr err;
103   virConnectPtr conn;
104   int n;
105   size_t i, j, nr_disks_added;
106
107   nr_domains = 0;
108   domains = NULL;
109
110   /* Get the list of all domains. */
111   conn = virConnectOpenReadOnly (libvirt_uri);
112   if (!conn) {
113     err = virGetLastError ();
114     fprintf (stderr,
115              _("%s: could not connect to libvirt (code %d, domain %d): %s"),
116              program_name, err->code, err->domain, err->message);
117     exit (EXIT_FAILURE);
118   }
119
120   n = virConnectNumOfDomains (conn);
121   if (n == -1) {
122     err = virGetLastError ();
123     fprintf (stderr,
124              _("%s: could not get number of running domains (code %d, domain %d): %s"),
125              program_name, err->code, err->domain, err->message);
126     exit (EXIT_FAILURE);
127   }
128
129   int ids[n];
130   n = virConnectListDomains (conn, ids, n);
131   if (n == -1) {
132     err = virGetLastError ();
133     fprintf (stderr,
134              _("%s: could not list running domains (code %d, domain %d): %s"),
135              program_name, err->code, err->domain, err->message);
136     exit (EXIT_FAILURE);
137   }
138
139   add_domains_by_id (conn, ids, n);
140
141   n = virConnectNumOfDefinedDomains (conn);
142   if (n == -1) {
143     err = virGetLastError ();
144     fprintf (stderr,
145              _("%s: could not get number of inactive domains (code %d, domain %d): %s"),
146              program_name, err->code, err->domain, err->message);
147     exit (EXIT_FAILURE);
148   }
149
150   char *names[n];
151   n = virConnectListDefinedDomains (conn, names, n);
152   if (n == -1) {
153     err = virGetLastError ();
154     fprintf (stderr,
155              _("%s: could not list inactive domains (code %d, domain %d): %s"),
156              program_name, err->code, err->domain, err->message);
157     exit (EXIT_FAILURE);
158   }
159
160   add_domains_by_name (conn, names, n);
161
162   /* You must free these even though the libvirt documentation doesn't
163    * mention it.
164    */
165   for (i = 0; i < (size_t) n; ++i)
166     free (names[i]);
167
168   virConnectClose (conn);
169
170   /* No domains? */
171   if (nr_domains == 0)
172     return;
173
174   /* Sort the domains alphabetically by name for display. */
175   qsort (domains, nr_domains, sizeof (struct domain), compare_domain_names);
176
177   print_title ();
178
179   /* To minimize the number of times we have to launch the appliance,
180    * shuffle as many domains together as we can, but not exceeding
181    * MAX_DISKS per request.  If --one-per-guest was requested then only
182    * request disks from a single guest each time.
183    * Interesting application for NP-complete knapsack problem here.
184    */
185   if (one_per_guest) {
186     for (i = 0; i < nr_domains; ++i)
187       multi_df (&domains[i], 1);
188   } else {
189     for (i = 0; i < nr_domains; /**/) {
190       nr_disks_added = 0;
191
192       /* Make a request with domains [i..j-1]. */
193       for (j = i; j < nr_domains; ++j) {
194         if (nr_disks_added + domains[j].nr_disks > MAX_DISKS)
195           break;
196         nr_disks_added += domains[j].nr_disks;
197       }
198       multi_df (&domains[i], j-i);
199
200       i = j;
201     }
202   }
203
204   /* Free up domains structure. */
205   for (i = 0; i < nr_domains; ++i)
206     free_domain (&domains[i]);
207   free (domains);
208 }
209
210 static void
211 add_domains_by_id (virConnectPtr conn, int *ids, size_t n)
212 {
213   size_t i;
214   virDomainPtr dom;
215
216   for (i = 0; i < n; ++i) {
217     if (ids[i] != 0) {          /* RHBZ#538041 */
218       dom = virDomainLookupByID (conn, ids[i]);
219       if (dom) { /* transient errors are possible here, ignore them */
220         add_domain (dom);
221         virDomainFree (dom);
222       }
223     }
224   }
225 }
226
227 static void
228 add_domains_by_name (virConnectPtr conn, char **names, size_t n)
229 {
230   size_t i;
231   virDomainPtr dom;
232
233   for (i = 0; i < n; ++i) {
234     dom = virDomainLookupByName (conn, names[i]);
235     if (dom) { /* transient errors are possible here, ignore them */
236       add_domain (dom);
237       virDomainFree (dom);
238     }
239   }
240 }
241
242 static void
243 add_domain (virDomainPtr dom)
244 {
245   struct domain *domain;
246
247   domains = realloc (domains, (nr_domains + 1) * sizeof (struct domain));
248   if (domains == NULL) {
249     perror ("realloc");
250     exit (EXIT_FAILURE);
251   }
252
253   domain = &domains[nr_domains];
254   nr_domains++;
255
256   domain->name = strdup (virDomainGetName (dom));
257   if (domain->name == NULL) {
258     perror ("strdup");
259     exit (EXIT_FAILURE);
260   }
261
262   char uuid[VIR_UUID_STRING_BUFLEN];
263   if (virDomainGetUUIDString (dom, uuid) == 0) {
264     domain->uuid = strdup (uuid);
265     if (domain->uuid == NULL) {
266       perror ("strdup");
267       exit (EXIT_FAILURE);
268     }
269   }
270   else
271     domain->uuid = NULL;
272
273   domain->disks = NULL;
274   int n = guestfs___for_each_disk (g, dom, add_disk, domain);
275   if (n == -1)
276     exit (EXIT_FAILURE);
277   domain->nr_disks = n;
278
279   if (domain->nr_disks > MAX_DISKS) {
280     fprintf (stderr,
281              _("%s: ignoring %s, it has too many disks (%zu > %d)"),
282              program_name, domain->name, domain->nr_disks, MAX_DISKS);
283     free_domain (domain);
284     nr_domains--;
285     return;
286   }
287 }
288
289 static int
290 add_disk (guestfs_h *g, const char *filename, const char *format,
291           void *domain_vp)
292 {
293   struct domain *domain = domain_vp;
294   struct disk *disk;
295
296   disk = malloc (sizeof *disk);
297   if (disk == NULL) {
298     perror ("malloc");
299     return -1;
300   }
301
302   disk->next = domain->disks;
303   domain->disks = disk;
304
305   disk->filename = strdup (filename);
306   if (disk->filename == NULL) {
307     perror ("malloc");
308     return -1;
309   }
310   if (format) {
311     disk->format = strdup (format);
312     if (disk->format == NULL) {
313       perror ("malloc");
314       return -1;
315     }
316   }
317   else
318     disk->format = NULL;
319
320   return 0;
321 }
322
323 static size_t
324 count_strings (char **argv)
325 {
326   size_t i;
327
328   for (i = 0; argv[i] != NULL; ++i)
329     ;
330   return i;
331 }
332
333 static void reset_guestfs_handle (void);
334 static void add_disks_to_handle_reverse (struct disk *disk);
335
336 /* Perform 'df' operation on the domain(s) given in the list. */
337 static void
338 multi_df (struct domain *domains, size_t n)
339 {
340   size_t i;
341   size_t nd;
342   int r;
343   char **devices;
344
345   /* Add all the disks to the handle (since they were added in reverse
346    * order, we must add them here in reverse too).
347    */
348   for (i = 0; i < n; ++i)
349     add_disks_to_handle_reverse (domains[i].disks);
350
351   /* Launch the handle. */
352   if (guestfs_launch (g) == -1)
353     exit (EXIT_FAILURE);
354
355   devices = guestfs_list_devices (g);
356   if (devices == NULL)
357     exit (EXIT_FAILURE);
358
359   /* Check the number of disks we think we added is the same as the
360    * number of devices returned by libguestfs.
361    */
362   nd = 0;
363   for (i = 0; i < n; ++i)
364     nd += domains[i].nr_disks;
365   assert (nd == count_strings (devices));
366
367   nd = 0;
368   for (i = 0; i < n; ++i) {
369     /* So that &devices[nd] is a NULL-terminated list of strings. */
370     char *p = devices[nd + domains[i].nr_disks];
371     devices[nd + domains[i].nr_disks] = NULL;
372
373     r = df_on_handle (domains[i].name, domains[i].uuid, &devices[nd], nd);
374
375     /* Restore devices to original. */
376     devices[nd + domains[i].nr_disks] = p;
377     nd += domains[i].nr_disks;
378
379     /* Something broke in df_on_handle.  Give up on the remaining
380      * devices for this handle, but keep going on the next handle.
381      */
382     if (r == -1)
383       break;
384   }
385
386   for (i = 0; devices[i] != NULL; ++i)
387     free (devices[i]);
388   free (devices);
389
390   /* Reset the handle. */
391   reset_guestfs_handle ();
392 }
393
394 static void
395 add_disks_to_handle_reverse (struct disk *disk)
396 {
397   if (disk == NULL)
398     return;
399
400   add_disks_to_handle_reverse (disk->next);
401
402   struct guestfs_add_drive_opts_argv optargs = { .bitmask = 0 };
403
404   optargs.bitmask |= GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK;
405   optargs.readonly = 1;
406
407   if (disk->format) {
408     optargs.bitmask |= GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK;
409     optargs.format = disk->format;
410   }
411
412   if (guestfs_add_drive_opts_argv (g, disk->filename, &optargs) == -1)
413     exit (EXIT_FAILURE);
414 }
415
416 /* Close and reopen the libguestfs handle. */
417 static void
418 reset_guestfs_handle (void)
419 {
420   /* Copy the settings from the old handle. */
421   int verbose = guestfs_get_verbose (g);
422   int trace = guestfs_get_trace (g);
423
424   guestfs_close (g);
425
426   g = guestfs_create ();
427   if (g == NULL) {
428     fprintf (stderr, _("guestfs_create: failed to create handle\n"));
429     exit (EXIT_FAILURE);
430   }
431
432   guestfs_set_verbose (g, verbose);
433   guestfs_set_trace (g, trace);
434 }
435
436 #endif