e494a839e13fc68fd212acfa9fe77fb1208186f7
[collectd.git] / src / virt.c
1 /**
2  * collectd - src/virt.c
3  * Copyright (C) 2006-2008  Red Hat Inc.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the license is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Richard W.M. Jones <rjones@redhat.com>
20  **/
21
22 #include "collectd.h"
23
24 #include "common.h"
25 #include "plugin.h"
26 #include "utils_ignorelist.h"
27 #include "utils_complain.h"
28
29 #include <libvirt/libvirt.h>
30 #include <libvirt/virterror.h>
31 #include <libxml/parser.h>
32 #include <libxml/tree.h>
33 #include <libxml/xpath.h>
34 #include <libgen.h> /* for basename(3) */
35
36 /* Plugin name */
37 #define PLUGIN_NAME "virt"
38
39 static const char *config_keys[] = {
40     "Connection",
41
42     "RefreshInterval",
43
44     "Domain",
45     "BlockDevice",
46     "BlockDeviceFormat",
47     "BlockDeviceFormatBasename",
48     "InterfaceDevice",
49     "IgnoreSelected",
50
51     "HostnameFormat",
52     "InterfaceFormat",
53
54     "PluginInstanceFormat",
55
56     NULL
57 };
58 #define NR_CONFIG_KEYS ((sizeof config_keys / sizeof config_keys[0]) - 1)
59
60 /* Connection. */
61 static virConnectPtr conn = 0;
62 static char *conn_string = NULL;
63 static c_complain_t conn_complain = C_COMPLAIN_INIT_STATIC;
64
65 /* Seconds between list refreshes, 0 disables completely. */
66 static int interval = 60;
67
68 /* List of domains, if specified. */
69 static ignorelist_t *il_domains = NULL;
70 /* List of block devices, if specified. */
71 static ignorelist_t *il_block_devices = NULL;
72 /* List of network interface devices, if specified. */
73 static ignorelist_t *il_interface_devices = NULL;
74
75 static int ignore_device_match (ignorelist_t *,
76                                 const char *domname, const char *devpath);
77
78 /* Actual list of domains found on last refresh. */
79 static virDomainPtr *domains = NULL;
80 static int nr_domains = 0;
81
82 static void free_domains (void);
83 static int add_domain (virDomainPtr dom);
84
85 /* Actual list of block devices found on last refresh. */
86 struct block_device {
87     virDomainPtr dom;           /* domain */
88     char *path;                 /* name of block device */
89 };
90
91 static struct block_device *block_devices = NULL;
92 static int nr_block_devices = 0;
93
94 static void free_block_devices (void);
95 static int add_block_device (virDomainPtr dom, const char *path);
96
97 /* Actual list of network interfaces found on last refresh. */
98 struct interface_device {
99     virDomainPtr dom;           /* domain */
100     char *path;                 /* name of interface device */
101     char *address;              /* mac address of interface device */
102     char *number;               /* interface device number */
103 };
104
105 static struct interface_device *interface_devices = NULL;
106 static int nr_interface_devices = 0;
107
108 static void free_interface_devices (void);
109 static int add_interface_device (virDomainPtr dom, const char *path, const char *address, unsigned int number);
110
111 /* HostnameFormat. */
112 #define HF_MAX_FIELDS 3
113
114 enum hf_field {
115     hf_none = 0,
116     hf_hostname,
117     hf_name,
118     hf_uuid
119 };
120
121 static enum hf_field hostname_format[HF_MAX_FIELDS] =
122     { hf_name };
123
124 /* PluginInstanceFormat */
125 #define PLGINST_MAX_FIELDS 2
126
127 enum plginst_field {
128     plginst_none = 0,
129     plginst_name,
130     plginst_uuid
131 };
132
133 static enum plginst_field plugin_instance_format[PLGINST_MAX_FIELDS] =
134     { plginst_none };
135
136 /* BlockDeviceFormat */
137 enum bd_field {
138         target,
139         source
140 };
141
142 /* InterfaceFormat. */
143 enum if_field {
144     if_address,
145     if_name,
146     if_number
147 };
148
149 /* BlockDeviceFormatBasename */
150 _Bool blockdevice_format_basename = 0;
151 static enum bd_field blockdevice_format = target;
152 static enum if_field interface_format = if_name;
153
154 /* Time that we last refreshed. */
155 static time_t last_refresh = (time_t) 0;
156
157 static int refresh_lists (void);
158
159 /* ERROR(...) macro for virterrors. */
160 #define VIRT_ERROR(conn,s) do {                 \
161         virErrorPtr err;                        \
162         err = (conn) ? virConnGetLastError ((conn)) : virGetLastError (); \
163         if (err) ERROR ("%s: %s", (s), err->message);                   \
164     } while(0)
165
166 static void
167 init_value_list (value_list_t *vl, virDomainPtr dom)
168 {
169     int n;
170     const char *name;
171     char uuid[VIR_UUID_STRING_BUFLEN];
172
173     sstrncpy (vl->plugin, PLUGIN_NAME, sizeof (vl->plugin));
174
175     vl->host[0] = '\0';
176
177     /* Construct the hostname field according to HostnameFormat. */
178     for (int i = 0; i < HF_MAX_FIELDS; ++i) {
179         if (hostname_format[i] == hf_none)
180             continue;
181
182         n = DATA_MAX_NAME_LEN - strlen (vl->host) - 2;
183
184         if (i > 0 && n >= 1) {
185             strncat (vl->host, ":", 1);
186             n--;
187         }
188
189         switch (hostname_format[i]) {
190         case hf_none: break;
191         case hf_hostname:
192             strncat (vl->host, hostname_g, n);
193             break;
194         case hf_name:
195             name = virDomainGetName (dom);
196             if (name)
197                 strncat (vl->host, name, n);
198             break;
199         case hf_uuid:
200             if (virDomainGetUUIDString (dom, uuid) == 0)
201                 strncat (vl->host, uuid, n);
202             break;
203         }
204     }
205
206     vl->host[sizeof (vl->host) - 1] = '\0';
207
208     /* Construct the plugin instance field according to PluginInstanceFormat. */
209     for (int i = 0; i < PLGINST_MAX_FIELDS; ++i) {
210         if (plugin_instance_format[i] == plginst_none)
211             continue;
212
213         n = sizeof(vl->plugin_instance) - strlen (vl->plugin_instance) - 2;
214
215         if (i > 0 && n >= 1) {
216             strncat (vl->plugin_instance, ":", 1);
217             n--;
218         }
219
220         switch (plugin_instance_format[i]) {
221         case plginst_none: break;
222         case plginst_name:
223             name = virDomainGetName (dom);
224             if (name)
225                 strncat (vl->plugin_instance, name, n);
226             break;
227         case plginst_uuid:
228             if (virDomainGetUUIDString (dom, uuid) == 0)
229                 strncat (vl->plugin_instance, uuid, n);
230             break;
231         }
232     }
233
234     vl->plugin_instance[sizeof (vl->plugin_instance) - 1] = '\0';
235
236 } /* void init_value_list */
237
238 static void submit (virDomainPtr dom,
239                     char const *type, char const *type_instance,
240                     value_t *values, size_t values_len)
241 {
242     value_list_t vl = VALUE_LIST_INIT;
243     init_value_list (&vl, dom);
244
245     vl.values = values;
246     vl.values_len = values_len;
247
248     sstrncpy (vl.type, type, sizeof (vl.type));
249     if (type_instance != NULL)
250         sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
251
252     plugin_dispatch_values (&vl);
253 }
254
255 static void
256 memory_submit (gauge_t value, virDomainPtr dom)
257 {
258     submit (dom, "memory", "total", &(value_t) { .gauge = value }, 1);
259 }
260
261 static void
262 memory_stats_submit (gauge_t value, virDomainPtr dom, int tag_index)
263 {
264     static const char *tags[] = { "swap_in", "swap_out", "major_fault", "minor_fault",
265                                     "unused", "available", "actual_balloon", "rss"};
266
267     if ((tag_index < 0) || (tag_index >= STATIC_ARRAY_SIZE (tags))) {
268         ERROR ("virt plugin: Array index out of bounds: tag_index = %d", tag_index);
269         return;
270     }
271
272     submit (dom, "memory", tags[tag_index], &(value_t) { .gauge = value }, 1);
273 }
274
275 static void
276 cpu_submit (unsigned long long value,
277             virDomainPtr dom, const char *type)
278 {
279     submit (dom, type, NULL, &(value_t) { .derive = (derive_t) value }, 1);
280 }
281
282 static void
283 vcpu_submit (derive_t value,
284              virDomainPtr dom, int vcpu_nr, const char *type)
285 {
286     char type_instance[DATA_MAX_NAME_LEN];
287
288     ssnprintf (type_instance, sizeof (type_instance), "%d", vcpu_nr);
289
290     submit (dom, type, type_instance, &(value_t) { .derive = value }, 1);
291 }
292
293 static void
294 submit_derive2 (const char *type, derive_t v0, derive_t v1,
295              virDomainPtr dom, const char *devname)
296 {
297     value_t values[] = {
298         { .derive = v0 },
299         { .derive = v1 },
300     };
301
302     submit (dom, type, devname, values, STATIC_ARRAY_SIZE (values));
303 } /* void submit_derive2 */
304
305 static int
306 lv_init (void)
307 {
308     if (virInitialize () != 0)
309         return -1;
310     else
311         return 0;
312 }
313
314 static int
315 lv_config (const char *key, const char *value)
316 {
317     if (virInitialize () != 0)
318         return 1;
319
320     if (il_domains == NULL)
321         il_domains = ignorelist_create (1);
322     if (il_block_devices == NULL)
323         il_block_devices = ignorelist_create (1);
324     if (il_interface_devices == NULL)
325         il_interface_devices = ignorelist_create (1);
326
327     if (strcasecmp (key, "Connection") == 0) {
328         char *tmp = strdup (value);
329         if (tmp == NULL) {
330             ERROR (PLUGIN_NAME " plugin: Connection strdup failed.");
331             return 1;
332         }
333         sfree (conn_string);
334         conn_string = tmp;
335         return 0;
336     }
337
338     if (strcasecmp (key, "RefreshInterval") == 0) {
339         char *eptr = NULL;
340         interval = strtol (value, &eptr, 10);
341         if (eptr == NULL || *eptr != '\0') return 1;
342         return 0;
343     }
344
345     if (strcasecmp (key, "Domain") == 0) {
346         if (ignorelist_add (il_domains, value)) return 1;
347         return 0;
348     }
349     if (strcasecmp (key, "BlockDevice") == 0) {
350         if (ignorelist_add (il_block_devices, value)) return 1;
351         return 0;
352     }
353
354     if (strcasecmp (key, "BlockDeviceFormat") == 0) {
355         if (strcasecmp (value, "target") == 0)
356             blockdevice_format = target;
357         else if (strcasecmp (value, "source") == 0)
358             blockdevice_format = source;
359         else {
360             ERROR (PLUGIN_NAME " plugin: unknown BlockDeviceFormat: %s", value);
361             return -1;
362         }
363         return 0;
364     }
365     if (strcasecmp (key, "BlockDeviceFormatBasename") == 0) {
366         blockdevice_format_basename = IS_TRUE (value);
367         return 0;
368     }
369     if (strcasecmp (key, "InterfaceDevice") == 0) {
370         if (ignorelist_add (il_interface_devices, value)) return 1;
371         return 0;
372     }
373
374     if (strcasecmp (key, "IgnoreSelected") == 0) {
375         if (IS_TRUE (value))
376         {
377             ignorelist_set_invert (il_domains, 0);
378             ignorelist_set_invert (il_block_devices, 0);
379             ignorelist_set_invert (il_interface_devices, 0);
380         }
381         else
382         {
383             ignorelist_set_invert (il_domains, 1);
384             ignorelist_set_invert (il_block_devices, 1);
385             ignorelist_set_invert (il_interface_devices, 1);
386         }
387         return 0;
388     }
389
390     if (strcasecmp (key, "HostnameFormat") == 0) {
391         char *value_copy;
392         char *fields[HF_MAX_FIELDS];
393         int n;
394
395         value_copy = strdup (value);
396         if (value_copy == NULL) {
397             ERROR (PLUGIN_NAME " plugin: strdup failed.");
398             return -1;
399         }
400
401         n = strsplit (value_copy, fields, HF_MAX_FIELDS);
402         if (n < 1) {
403             sfree (value_copy);
404             ERROR (PLUGIN_NAME " plugin: HostnameFormat: no fields");
405             return -1;
406         }
407
408         for (int i = 0; i < n; ++i) {
409             if (strcasecmp (fields[i], "hostname") == 0)
410                 hostname_format[i] = hf_hostname;
411             else if (strcasecmp (fields[i], "name") == 0)
412                 hostname_format[i] = hf_name;
413             else if (strcasecmp (fields[i], "uuid") == 0)
414                 hostname_format[i] = hf_uuid;
415             else {
416                 ERROR (PLUGIN_NAME " plugin: unknown HostnameFormat field: %s", fields[i]);
417                 sfree (value_copy);
418                 return -1;
419             }
420         }
421         sfree (value_copy);
422
423         for (int i = n; i < HF_MAX_FIELDS; ++i)
424             hostname_format[i] = hf_none;
425
426         return 0;
427     }
428
429     if (strcasecmp (key, "PluginInstanceFormat") == 0) {
430         char *value_copy;
431         char *fields[PLGINST_MAX_FIELDS];
432         int n;
433
434         value_copy = strdup (value);
435         if (value_copy == NULL) {
436             ERROR (PLUGIN_NAME " plugin: strdup failed.");
437             return -1;
438         }
439
440         n = strsplit (value_copy, fields, PLGINST_MAX_FIELDS);
441         if (n < 1) {
442             sfree (value_copy);
443             ERROR (PLUGIN_NAME " plugin: PluginInstanceFormat: no fields");
444             return -1;
445         }
446
447         for (int i = 0; i < n; ++i) {
448             if (strcasecmp (fields[i], "none") == 0) {
449                 plugin_instance_format[i] = plginst_none;
450                 break;
451             } else if (strcasecmp (fields[i], "name") == 0)
452                 plugin_instance_format[i] = plginst_name;
453             else if (strcasecmp (fields[i], "uuid") == 0)
454                 plugin_instance_format[i] = plginst_uuid;
455             else {
456                 ERROR (PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s", fields[i]);
457                 sfree (value_copy);
458                 return -1;
459             }
460         }
461         sfree (value_copy);
462
463         for (int i = n; i < PLGINST_MAX_FIELDS; ++i)
464             plugin_instance_format[i] = plginst_none;
465
466         return 0;
467     }
468
469     if (strcasecmp (key, "InterfaceFormat") == 0) {
470         if (strcasecmp (value, "name") == 0)
471             interface_format = if_name;
472         else if (strcasecmp (value, "address") == 0)
473             interface_format = if_address;
474         else if (strcasecmp (value, "number") == 0)
475             interface_format = if_number;
476         else {
477             ERROR (PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", value);
478             return -1;
479         }
480         return 0;
481     }
482
483     /* Unrecognised option. */
484     return -1;
485 }
486
487 static int
488 lv_read (void)
489 {
490     time_t t;
491
492     if (conn == NULL) {
493         /* `conn_string == NULL' is acceptable. */
494         conn = virConnectOpenReadOnly (conn_string);
495         if (conn == NULL) {
496             c_complain (LOG_ERR, &conn_complain,
497                     PLUGIN_NAME " plugin: Unable to connect: "
498                     "virConnectOpenReadOnly failed.");
499             return -1;
500         }
501     }
502     c_release (LOG_NOTICE, &conn_complain,
503             PLUGIN_NAME " plugin: Connection established.");
504
505     time (&t);
506
507     /* Need to refresh domain or device lists? */
508     if ((last_refresh == (time_t) 0) ||
509             ((interval > 0) && ((last_refresh + interval) <= t))) {
510         if (refresh_lists () != 0) {
511             if (conn != NULL)
512                 virConnectClose (conn);
513             conn = NULL;
514             return -1;
515         }
516         last_refresh = t;
517     }
518
519 #if 0
520     for (int i = 0; i < nr_domains; ++i)
521         fprintf (stderr, "domain %s\n", virDomainGetName (domains[i]));
522     for (int i = 0; i < nr_block_devices; ++i)
523         fprintf  (stderr, "block device %d %s:%s\n",
524                   i, virDomainGetName (block_devices[i].dom),
525                   block_devices[i].path);
526     for (int i = 0; i < nr_interface_devices; ++i)
527         fprintf (stderr, "interface device %d %s:%s\n",
528                  i, virDomainGetName (interface_devices[i].dom),
529                  interface_devices[i].path);
530 #endif
531
532     /* Get CPU usage, memory, VCPU usage for each domain. */
533     for (int i = 0; i < nr_domains; ++i) {
534         virDomainInfo info;
535         virVcpuInfoPtr vinfo = NULL;
536         virDomainMemoryStatPtr minfo = NULL;
537         int status;
538
539         status = virDomainGetInfo (domains[i], &info);
540         if (status != 0)
541         {
542             ERROR (PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
543                     status);
544             continue;
545         }
546
547         if (info.state != VIR_DOMAIN_RUNNING)
548         {
549             /* only gather stats for running domains */
550             continue;
551         }
552
553         cpu_submit (info.cpuTime, domains[i], "virt_cpu_total");
554         memory_submit ((gauge_t) info.memory * 1024, domains[i]);
555
556         vinfo = malloc (info.nrVirtCpu * sizeof (vinfo[0]));
557         if (vinfo == NULL) {
558             ERROR (PLUGIN_NAME " plugin: malloc failed.");
559             continue;
560         }
561
562         status = virDomainGetVcpus (domains[i], vinfo, info.nrVirtCpu,
563                 /* cpu map = */ NULL, /* cpu map length = */ 0);
564         if (status < 0)
565         {
566             ERROR (PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
567                     status);
568             sfree (vinfo);
569             continue;
570         }
571
572         for (int j = 0; j < info.nrVirtCpu; ++j)
573             vcpu_submit (vinfo[j].cpuTime,
574                     domains[i], vinfo[j].number, "virt_vcpu");
575
576         sfree (vinfo);
577
578         minfo = malloc (VIR_DOMAIN_MEMORY_STAT_NR * sizeof (virDomainMemoryStatStruct));
579         if (minfo == NULL) {
580             ERROR ("virt plugin: malloc failed.");
581             continue;
582         }
583
584         status = virDomainMemoryStats (domains[i], minfo, VIR_DOMAIN_MEMORY_STAT_NR, 0);
585
586         if (status < 0) {
587             ERROR ("virt plugin: virDomainMemoryStats failed with status %i.",
588                     status);
589             sfree (minfo);
590             continue;
591         }
592
593         for (int j = 0; j < status; j++) {
594             memory_stats_submit ((gauge_t) minfo[j].val * 1024, domains[i], minfo[j].tag);
595         }
596
597         sfree (minfo);
598     }
599
600
601     /* Get block device stats for each domain. */
602     for (int i = 0; i < nr_block_devices; ++i) {
603         struct _virDomainBlockStats stats;
604
605         if (virDomainBlockStats (block_devices[i].dom, block_devices[i].path,
606                     &stats, sizeof stats) != 0)
607             continue;
608
609         char *type_instance = NULL;
610         if (blockdevice_format_basename && blockdevice_format == source)
611             type_instance = strdup(basename(block_devices[i].path));
612         else
613             type_instance = strdup(block_devices[i].path);
614
615         if ((stats.rd_req != -1) && (stats.wr_req != -1))
616             submit_derive2 ("disk_ops",
617                     (derive_t) stats.rd_req, (derive_t) stats.wr_req,
618                     block_devices[i].dom, type_instance);
619
620         if ((stats.rd_bytes != -1) && (stats.wr_bytes != -1))
621             submit_derive2 ("disk_octets",
622                     (derive_t) stats.rd_bytes, (derive_t) stats.wr_bytes,
623                     block_devices[i].dom, type_instance);
624
625         sfree (type_instance);
626     } /* for (nr_block_devices) */
627
628     /* Get interface stats for each domain. */
629     for (int i = 0; i < nr_interface_devices; ++i) {
630         struct _virDomainInterfaceStats stats;
631         char *display_name = NULL;
632
633         switch (interface_format) {
634             case if_address:
635                 display_name = interface_devices[i].address;
636                 break;
637             case if_number:
638                 display_name = interface_devices[i].number;
639                 break;
640             case if_name:
641             default:
642                 display_name = interface_devices[i].path;
643         }
644
645         if (virDomainInterfaceStats (interface_devices[i].dom,
646                     interface_devices[i].path,
647                     &stats, sizeof stats) != 0)
648             continue;
649
650         if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
651             submit_derive2 ("if_octets",
652                     (derive_t) stats.rx_bytes, (derive_t) stats.tx_bytes,
653                     interface_devices[i].dom, display_name);
654
655         if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
656             submit_derive2 ("if_packets",
657                     (derive_t) stats.rx_packets, (derive_t) stats.tx_packets,
658                     interface_devices[i].dom, display_name);
659
660         if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
661             submit_derive2 ("if_errors",
662                     (derive_t) stats.rx_errs, (derive_t) stats.tx_errs,
663                     interface_devices[i].dom, display_name);
664
665         if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
666             submit_derive2 ("if_dropped",
667                     (derive_t) stats.rx_drop, (derive_t) stats.tx_drop,
668                     interface_devices[i].dom, display_name);
669     } /* for (nr_interface_devices) */
670
671     return 0;
672 }
673
674 /*
675   virConnectListAllDomains() appeared in 0.10.2
676   Note that LIBVIR_CHECK_VERSION appeared a year later, so
677   in some systems which actually have virConnectListAllDomains()
678   we can't detect this.
679  */
680 #ifdef LIBVIR_CHECK_VERSION
681 # if LIBVIR_CHECK_VERSION(0,10,2)
682 #  define HAVE_LIST_ALL_DOMAINS 1
683 # endif
684 #endif
685
686 static int
687 refresh_lists (void)
688 {
689     int n;
690
691     n = virConnectNumOfDomains (conn);
692     if (n < 0) {
693         VIRT_ERROR (conn, "reading number of domains");
694         return -1;
695     }
696
697     if (n > 0) {
698 #ifdef HAVE_LIST_ALL_DOMAINS
699         virDomainPtr *domains;
700         n = virConnectListAllDomains (conn, &domains, VIR_CONNECT_LIST_DOMAINS_ACTIVE);
701 #else
702         int *domids;
703
704         /* Get list of domains. */
705         domids = malloc (sizeof (*domids) * n);
706         if (domids == NULL) {
707             ERROR (PLUGIN_NAME " plugin: malloc failed.");
708             return -1;
709         }
710
711         n = virConnectListDomains (conn, domids, n);
712 #endif
713
714         if (n < 0) {
715             VIRT_ERROR (conn, "reading list of domains");
716 #ifndef HAVE_LIST_ALL_DOMAINS
717             sfree (domids);
718 #endif
719             return -1;
720         }
721
722         free_block_devices ();
723         free_interface_devices ();
724         free_domains ();
725
726         /* Fetch each domain and add it to the list, unless ignore. */
727         for (int i = 0; i < n; ++i) {
728             const char *name;
729             char *xml = NULL;
730             xmlDocPtr xml_doc = NULL;
731             xmlXPathContextPtr xpath_ctx = NULL;
732             xmlXPathObjectPtr xpath_obj = NULL;
733
734 #ifdef HAVE_LIST_ALL_DOMAINS
735             virDomainPtr dom = domains[i];
736 #else
737             virDomainPtr dom = NULL;
738
739             dom = virDomainLookupByID (conn, domids[i]);
740             if (dom == NULL) {
741                 VIRT_ERROR (conn, "virDomainLookupByID");
742                 /* Could be that the domain went away -- ignore it anyway. */
743                 continue;
744             }
745 #endif
746
747             name = virDomainGetName (dom);
748             if (name == NULL) {
749                 VIRT_ERROR (conn, "virDomainGetName");
750                 goto cont;
751             }
752
753             if (il_domains && ignorelist_match (il_domains, name) != 0)
754                 goto cont;
755
756             if (add_domain (dom) < 0) {
757                 ERROR (PLUGIN_NAME " plugin: malloc failed.");
758                 goto cont;
759             }
760
761             /* Get a list of devices for this domain. */
762             xml = virDomainGetXMLDesc (dom, 0);
763             if (!xml) {
764                 VIRT_ERROR (conn, "virDomainGetXMLDesc");
765                 goto cont;
766             }
767
768             /* Yuck, XML.  Parse out the devices. */
769             xml_doc = xmlReadDoc ((xmlChar *) xml, NULL, NULL, XML_PARSE_NONET);
770             if (xml_doc == NULL) {
771                 VIRT_ERROR (conn, "xmlReadDoc");
772                 goto cont;
773             }
774
775             xpath_ctx = xmlXPathNewContext (xml_doc);
776
777             /* Block devices. */
778             char *bd_xmlpath = "/domain/devices/disk/target[@dev]";
779             if (blockdevice_format == source)
780                 bd_xmlpath = "/domain/devices/disk/source[@dev]";
781             xpath_obj = xmlXPathEval ((xmlChar *) bd_xmlpath, xpath_ctx);
782
783             if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
784                 xpath_obj->nodesetval == NULL)
785                 goto cont;
786
787             for (int j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
788                 xmlNodePtr node;
789                 char *path = NULL;
790
791                 node = xpath_obj->nodesetval->nodeTab[j];
792                 if (!node) continue;
793                 path = (char *) xmlGetProp (node, (xmlChar *) "dev");
794                 if (!path) continue;
795
796                 if (il_block_devices &&
797                     ignore_device_match (il_block_devices, name, path) != 0)
798                     goto cont2;
799
800                 add_block_device (dom, path);
801             cont2:
802                 if (path) xmlFree (path);
803             }
804             xmlXPathFreeObject (xpath_obj);
805
806             /* Network interfaces. */
807             xpath_obj = xmlXPathEval
808                 ((xmlChar *) "/domain/devices/interface[target[@dev]]",
809                  xpath_ctx);
810             if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
811                 xpath_obj->nodesetval == NULL)
812                 goto cont;
813
814             xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
815
816             for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
817                 char *path = NULL;
818                 char *address = NULL;
819                 xmlNodePtr xml_interface;
820
821                 xml_interface = xml_interfaces->nodeTab[j];
822                 if (!xml_interface) continue;
823
824                 for (xmlNodePtr child = xml_interface->children; child; child = child->next) {
825                     if (child->type != XML_ELEMENT_NODE) continue;
826
827                     if (xmlStrEqual(child->name, (const xmlChar *) "target")) {
828                         path = (char *) xmlGetProp (child, (const xmlChar *) "dev");
829                         if (!path) continue;
830                     } else if (xmlStrEqual(child->name, (const xmlChar *) "mac")) {
831                         address = (char *) xmlGetProp (child, (const xmlChar *) "address");
832                         if (!address) continue;
833                     }
834                 }
835
836                 if (il_interface_devices &&
837                     (ignore_device_match (il_interface_devices, name, path) != 0 ||
838                      ignore_device_match (il_interface_devices, name, address) != 0))
839                     goto cont3;
840
841                 add_interface_device (dom, path, address, j+1);
842                 cont3:
843                     if (path) xmlFree (path);
844                     if (address) xmlFree (address);
845             }
846
847         cont:
848             if (xpath_obj) xmlXPathFreeObject (xpath_obj);
849             if (xpath_ctx) xmlXPathFreeContext (xpath_ctx);
850             if (xml_doc) xmlFreeDoc (xml_doc);
851             sfree (xml);
852         }
853
854 #ifdef HAVE_LIST_ALL_DOMAINS
855         sfree (domains);
856 #else
857         sfree (domids);
858 #endif
859     }
860
861     return 0;
862 }
863
864 static void
865 free_domains (void)
866 {
867     if (domains) {
868         for (int i = 0; i < nr_domains; ++i)
869             virDomainFree (domains[i]);
870         sfree (domains);
871     }
872     domains = NULL;
873     nr_domains = 0;
874 }
875
876 static int
877 add_domain (virDomainPtr dom)
878 {
879     virDomainPtr *new_ptr;
880     int new_size = sizeof (domains[0]) * (nr_domains+1);
881
882     if (domains)
883         new_ptr = realloc (domains, new_size);
884     else
885         new_ptr = malloc (new_size);
886
887     if (new_ptr == NULL)
888         return -1;
889
890     domains = new_ptr;
891     domains[nr_domains] = dom;
892     return nr_domains++;
893 }
894
895 static void
896 free_block_devices (void)
897 {
898     if (block_devices) {
899         for (int i = 0; i < nr_block_devices; ++i)
900             sfree (block_devices[i].path);
901         sfree (block_devices);
902     }
903     block_devices = NULL;
904     nr_block_devices = 0;
905 }
906
907 static int
908 add_block_device (virDomainPtr dom, const char *path)
909 {
910     struct block_device *new_ptr;
911     int new_size = sizeof (block_devices[0]) * (nr_block_devices+1);
912     char *path_copy;
913
914     path_copy = strdup (path);
915     if (!path_copy)
916         return -1;
917
918     if (block_devices)
919         new_ptr = realloc (block_devices, new_size);
920     else
921         new_ptr = malloc (new_size);
922
923     if (new_ptr == NULL) {
924         sfree (path_copy);
925         return -1;
926     }
927     block_devices = new_ptr;
928     block_devices[nr_block_devices].dom = dom;
929     block_devices[nr_block_devices].path = path_copy;
930     return nr_block_devices++;
931 }
932
933 static void
934 free_interface_devices (void)
935 {
936     if (interface_devices) {
937         for (int i = 0; i < nr_interface_devices; ++i) {
938             sfree (interface_devices[i].path);
939             sfree (interface_devices[i].address);
940             sfree (interface_devices[i].number);
941         }
942         sfree (interface_devices);
943     }
944     interface_devices = NULL;
945     nr_interface_devices = 0;
946 }
947
948 static int
949 add_interface_device (virDomainPtr dom, const char *path, const char *address, unsigned int number)
950 {
951     struct interface_device *new_ptr;
952     int new_size = sizeof (interface_devices[0]) * (nr_interface_devices+1);
953     char *path_copy, *address_copy, number_string[15];
954
955     if ((path == NULL) || (address == NULL))
956         return EINVAL;
957
958     path_copy = strdup (path);
959     if (!path_copy) return -1;
960
961     address_copy = strdup (address);
962     if (!address_copy) {
963         sfree(path_copy);
964         return -1;
965     }
966
967     snprintf(number_string, sizeof (number_string), "interface-%u", number);
968
969     if (interface_devices)
970         new_ptr = realloc (interface_devices, new_size);
971     else
972         new_ptr = malloc (new_size);
973
974     if (new_ptr == NULL) {
975         sfree (path_copy);
976         sfree (address_copy);
977         return -1;
978     }
979     interface_devices = new_ptr;
980     interface_devices[nr_interface_devices].dom = dom;
981     interface_devices[nr_interface_devices].path = path_copy;
982     interface_devices[nr_interface_devices].address = address_copy;
983     interface_devices[nr_interface_devices].number = strdup(number_string);
984     return nr_interface_devices++;
985 }
986
987 static int
988 ignore_device_match (ignorelist_t *il, const char *domname, const char *devpath)
989 {
990     char *name;
991     int n, r;
992
993     if ((domname == NULL) || (devpath == NULL))
994         return 0;
995
996     n = sizeof (char) * (strlen (domname) + strlen (devpath) + 2);
997     name = malloc (n);
998     if (name == NULL) {
999         ERROR (PLUGIN_NAME " plugin: malloc failed.");
1000         return 0;
1001     }
1002     ssnprintf (name, n, "%s:%s", domname, devpath);
1003     r = ignorelist_match (il, name);
1004     sfree (name);
1005     return r;
1006 }
1007
1008 static int
1009 lv_shutdown (void)
1010 {
1011     free_block_devices ();
1012     free_interface_devices ();
1013     free_domains ();
1014
1015     if (conn != NULL)
1016         virConnectClose (conn);
1017     conn = NULL;
1018
1019     ignorelist_free (il_domains);
1020     il_domains = NULL;
1021     ignorelist_free (il_block_devices);
1022     il_block_devices = NULL;
1023     ignorelist_free (il_interface_devices);
1024     il_interface_devices = NULL;
1025
1026     return 0;
1027 }
1028
1029 void
1030 module_register (void)
1031 {
1032     plugin_register_config (PLUGIN_NAME,
1033     lv_config,
1034     config_keys, NR_CONFIG_KEYS);
1035     plugin_register_init (PLUGIN_NAME, lv_init);
1036     plugin_register_read (PLUGIN_NAME, lv_read);
1037     plugin_register_shutdown (PLUGIN_NAME, lv_shutdown);
1038 }
1039
1040 /*
1041  * vim: shiftwidth=4 tabstop=8 softtabstop=4 expandtab fdm=marker
1042  */