virt plugin: Add comment for <libgen.h> include.
[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         if (strcasecmp (value, "true") == 0)
367             blockdevice_format_basename = 1;
368         else if (strcasecmp (value, "false") == 0)
369             blockdevice_format_basename = 0;
370         else {
371             ERROR (PLUGIN_NAME " plugin: unknown BlockDeviceFormatBasename: %s", value);
372             return -1;
373         }
374         return 0;
375     }
376     if (strcasecmp (key, "InterfaceDevice") == 0) {
377         if (ignorelist_add (il_interface_devices, value)) return 1;
378         return 0;
379     }
380
381     if (strcasecmp (key, "IgnoreSelected") == 0) {
382         if (IS_TRUE (value))
383         {
384             ignorelist_set_invert (il_domains, 0);
385             ignorelist_set_invert (il_block_devices, 0);
386             ignorelist_set_invert (il_interface_devices, 0);
387         }
388         else
389         {
390             ignorelist_set_invert (il_domains, 1);
391             ignorelist_set_invert (il_block_devices, 1);
392             ignorelist_set_invert (il_interface_devices, 1);
393         }
394         return 0;
395     }
396
397     if (strcasecmp (key, "HostnameFormat") == 0) {
398         char *value_copy;
399         char *fields[HF_MAX_FIELDS];
400         int n;
401
402         value_copy = strdup (value);
403         if (value_copy == NULL) {
404             ERROR (PLUGIN_NAME " plugin: strdup failed.");
405             return -1;
406         }
407
408         n = strsplit (value_copy, fields, HF_MAX_FIELDS);
409         if (n < 1) {
410             sfree (value_copy);
411             ERROR (PLUGIN_NAME " plugin: HostnameFormat: no fields");
412             return -1;
413         }
414
415         for (int i = 0; i < n; ++i) {
416             if (strcasecmp (fields[i], "hostname") == 0)
417                 hostname_format[i] = hf_hostname;
418             else if (strcasecmp (fields[i], "name") == 0)
419                 hostname_format[i] = hf_name;
420             else if (strcasecmp (fields[i], "uuid") == 0)
421                 hostname_format[i] = hf_uuid;
422             else {
423                 ERROR (PLUGIN_NAME " plugin: unknown HostnameFormat field: %s", fields[i]);
424                 sfree (value_copy);
425                 return -1;
426             }
427         }
428         sfree (value_copy);
429
430         for (int i = n; i < HF_MAX_FIELDS; ++i)
431             hostname_format[i] = hf_none;
432
433         return 0;
434     }
435
436     if (strcasecmp (key, "PluginInstanceFormat") == 0) {
437         char *value_copy;
438         char *fields[PLGINST_MAX_FIELDS];
439         int n;
440
441         value_copy = strdup (value);
442         if (value_copy == NULL) {
443             ERROR (PLUGIN_NAME " plugin: strdup failed.");
444             return -1;
445         }
446
447         n = strsplit (value_copy, fields, PLGINST_MAX_FIELDS);
448         if (n < 1) {
449             sfree (value_copy);
450             ERROR (PLUGIN_NAME " plugin: PluginInstanceFormat: no fields");
451             return -1;
452         }
453
454         for (int i = 0; i < n; ++i) {
455             if (strcasecmp (fields[i], "none") == 0) {
456                 plugin_instance_format[i] = plginst_none;
457                 break;
458             } else if (strcasecmp (fields[i], "name") == 0)
459                 plugin_instance_format[i] = plginst_name;
460             else if (strcasecmp (fields[i], "uuid") == 0)
461                 plugin_instance_format[i] = plginst_uuid;
462             else {
463                 ERROR (PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s", fields[i]);
464                 sfree (value_copy);
465                 return -1;
466             }
467         }
468         sfree (value_copy);
469
470         for (int i = n; i < PLGINST_MAX_FIELDS; ++i)
471             plugin_instance_format[i] = plginst_none;
472
473         return 0;
474     }
475
476     if (strcasecmp (key, "InterfaceFormat") == 0) {
477         if (strcasecmp (value, "name") == 0)
478             interface_format = if_name;
479         else if (strcasecmp (value, "address") == 0)
480             interface_format = if_address;
481         else if (strcasecmp (value, "number") == 0)
482             interface_format = if_number;
483         else {
484             ERROR (PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", value);
485             return -1;
486         }
487         return 0;
488     }
489
490     /* Unrecognised option. */
491     return -1;
492 }
493
494 static int
495 lv_read (void)
496 {
497     time_t t;
498
499     if (conn == NULL) {
500         /* `conn_string == NULL' is acceptable. */
501         conn = virConnectOpenReadOnly (conn_string);
502         if (conn == NULL) {
503             c_complain (LOG_ERR, &conn_complain,
504                     PLUGIN_NAME " plugin: Unable to connect: "
505                     "virConnectOpenReadOnly failed.");
506             return -1;
507         }
508     }
509     c_release (LOG_NOTICE, &conn_complain,
510             PLUGIN_NAME " plugin: Connection established.");
511
512     time (&t);
513
514     /* Need to refresh domain or device lists? */
515     if ((last_refresh == (time_t) 0) ||
516             ((interval > 0) && ((last_refresh + interval) <= t))) {
517         if (refresh_lists () != 0) {
518             if (conn != NULL)
519                 virConnectClose (conn);
520             conn = NULL;
521             return -1;
522         }
523         last_refresh = t;
524     }
525
526 #if 0
527     for (int i = 0; i < nr_domains; ++i)
528         fprintf (stderr, "domain %s\n", virDomainGetName (domains[i]));
529     for (int i = 0; i < nr_block_devices; ++i)
530         fprintf  (stderr, "block device %d %s:%s\n",
531                   i, virDomainGetName (block_devices[i].dom),
532                   block_devices[i].path);
533     for (int i = 0; i < nr_interface_devices; ++i)
534         fprintf (stderr, "interface device %d %s:%s\n",
535                  i, virDomainGetName (interface_devices[i].dom),
536                  interface_devices[i].path);
537 #endif
538
539     /* Get CPU usage, memory, VCPU usage for each domain. */
540     for (int i = 0; i < nr_domains; ++i) {
541         virDomainInfo info;
542         virVcpuInfoPtr vinfo = NULL;
543         virDomainMemoryStatPtr minfo = NULL;
544         int status;
545
546         status = virDomainGetInfo (domains[i], &info);
547         if (status != 0)
548         {
549             ERROR (PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
550                     status);
551             continue;
552         }
553
554         if (info.state != VIR_DOMAIN_RUNNING)
555         {
556             /* only gather stats for running domains */
557             continue;
558         }
559
560         cpu_submit (info.cpuTime, domains[i], "virt_cpu_total");
561         memory_submit ((gauge_t) info.memory * 1024, domains[i]);
562
563         vinfo = malloc (info.nrVirtCpu * sizeof (vinfo[0]));
564         if (vinfo == NULL) {
565             ERROR (PLUGIN_NAME " plugin: malloc failed.");
566             continue;
567         }
568
569         status = virDomainGetVcpus (domains[i], vinfo, info.nrVirtCpu,
570                 /* cpu map = */ NULL, /* cpu map length = */ 0);
571         if (status < 0)
572         {
573             ERROR (PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
574                     status);
575             sfree (vinfo);
576             continue;
577         }
578
579         for (int j = 0; j < info.nrVirtCpu; ++j)
580             vcpu_submit (vinfo[j].cpuTime,
581                     domains[i], vinfo[j].number, "virt_vcpu");
582
583         sfree (vinfo);
584
585         minfo = malloc (VIR_DOMAIN_MEMORY_STAT_NR * sizeof (virDomainMemoryStatStruct));
586         if (minfo == NULL) {
587             ERROR ("virt plugin: malloc failed.");
588             continue;
589         }
590
591         status = virDomainMemoryStats (domains[i], minfo, VIR_DOMAIN_MEMORY_STAT_NR, 0);
592
593         if (status < 0) {
594             ERROR ("virt plugin: virDomainMemoryStats failed with status %i.",
595                     status);
596             sfree (minfo);
597             continue;
598         }
599
600         for (int j = 0; j < status; j++) {
601             memory_stats_submit ((gauge_t) minfo[j].val * 1024, domains[i], minfo[j].tag);
602         }
603
604         sfree (minfo);
605     }
606
607
608     /* Get block device stats for each domain. */
609     for (int i = 0; i < nr_block_devices; ++i) {
610         struct _virDomainBlockStats stats;
611
612         if (virDomainBlockStats (block_devices[i].dom, block_devices[i].path,
613                     &stats, sizeof stats) != 0)
614             continue;
615
616         char *type_instance = NULL;
617         if (blockdevice_format_basename && blockdevice_format == source)
618                 type_instance = strdup(basename(block_devices[i].path));
619         else
620                 type_instance = strdup(block_devices[i].path);
621         if ((stats.rd_req != -1) && (stats.wr_req != -1))
622             submit_derive2 ("disk_ops",
623                     (derive_t) stats.rd_req, (derive_t) stats.wr_req,
624                     block_devices[i].dom, type_instance);
625
626         if ((stats.rd_bytes != -1) && (stats.wr_bytes != -1))
627             submit_derive2 ("disk_octets",
628                     (derive_t) stats.rd_bytes, (derive_t) stats.wr_bytes,
629                     block_devices[i].dom, type_instance);
630         
631         sfree(type_instance);
632     } /* for (nr_block_devices) */
633
634     /* Get interface stats for each domain. */
635     for (int i = 0; i < nr_interface_devices; ++i) {
636         struct _virDomainInterfaceStats stats;
637         char *display_name = NULL;
638
639
640         switch (interface_format) {
641             case if_address:
642                 display_name = interface_devices[i].address;
643                 break;
644             case if_number:
645                 display_name = interface_devices[i].number;
646                 break;
647             case if_name:
648             default:
649                 display_name = interface_devices[i].path;
650         }
651
652         if (virDomainInterfaceStats (interface_devices[i].dom,
653                     interface_devices[i].path,
654                     &stats, sizeof stats) != 0)
655             continue;
656
657         if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
658             submit_derive2 ("if_octets",
659                     (derive_t) stats.rx_bytes, (derive_t) stats.tx_bytes,
660                     interface_devices[i].dom, display_name);
661
662         if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
663             submit_derive2 ("if_packets",
664                     (derive_t) stats.rx_packets, (derive_t) stats.tx_packets,
665                     interface_devices[i].dom, display_name);
666
667         if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
668             submit_derive2 ("if_errors",
669                     (derive_t) stats.rx_errs, (derive_t) stats.tx_errs,
670                     interface_devices[i].dom, display_name);
671
672         if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
673             submit_derive2 ("if_dropped",
674                     (derive_t) stats.rx_drop, (derive_t) stats.tx_drop,
675                     interface_devices[i].dom, display_name);
676     } /* for (nr_interface_devices) */
677
678     return 0;
679 }
680
681 static int
682 refresh_lists (void)
683 {
684     int n;
685
686     n = virConnectNumOfDomains (conn);
687     if (n < 0) {
688         VIRT_ERROR (conn, "reading number of domains");
689         return -1;
690     }
691
692     if (n > 0) {
693         int *domids;
694
695         /* Get list of domains. */
696         domids = malloc (sizeof (*domids) * n);
697         if (domids == NULL) {
698             ERROR (PLUGIN_NAME " plugin: malloc failed.");
699             return -1;
700         }
701
702         n = virConnectListDomains (conn, domids, n);
703         if (n < 0) {
704             VIRT_ERROR (conn, "reading list of domains");
705             sfree (domids);
706             return -1;
707         }
708
709         free_block_devices ();
710         free_interface_devices ();
711         free_domains ();
712
713         /* Fetch each domain and add it to the list, unless ignore. */
714         for (int i = 0; i < n; ++i) {
715             virDomainPtr dom = NULL;
716             const char *name;
717             char *xml = NULL;
718             xmlDocPtr xml_doc = NULL;
719             xmlXPathContextPtr xpath_ctx = NULL;
720             xmlXPathObjectPtr xpath_obj = NULL;
721
722             dom = virDomainLookupByID (conn, domids[i]);
723             if (dom == NULL) {
724                 VIRT_ERROR (conn, "virDomainLookupByID");
725                 /* Could be that the domain went away -- ignore it anyway. */
726                 continue;
727             }
728
729             name = virDomainGetName (dom);
730             if (name == NULL) {
731                 VIRT_ERROR (conn, "virDomainGetName");
732                 goto cont;
733             }
734
735             if (il_domains && ignorelist_match (il_domains, name) != 0)
736                 goto cont;
737
738             if (add_domain (dom) < 0) {
739                 ERROR (PLUGIN_NAME " plugin: malloc failed.");
740                 goto cont;
741             }
742
743             /* Get a list of devices for this domain. */
744             xml = virDomainGetXMLDesc (dom, 0);
745             if (!xml) {
746                 VIRT_ERROR (conn, "virDomainGetXMLDesc");
747                 goto cont;
748             }
749
750             /* Yuck, XML.  Parse out the devices. */
751             xml_doc = xmlReadDoc ((xmlChar *) xml, NULL, NULL, XML_PARSE_NONET);
752             if (xml_doc == NULL) {
753                 VIRT_ERROR (conn, "xmlReadDoc");
754                 goto cont;
755             }
756
757             xpath_ctx = xmlXPathNewContext (xml_doc);
758
759             /* Block devices. */
760             char *bd_xmlpath = "/domain/devices/disk/target[@dev]";
761             if (blockdevice_format == source)
762                 bd_xmlpath = "/domain/devices/disk/source[@dev]";
763             xpath_obj = xmlXPathEval ((xmlChar *) bd_xmlpath, xpath_ctx);
764
765             if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
766                 xpath_obj->nodesetval == NULL)
767                 goto cont;
768
769             for (int j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
770                 xmlNodePtr node;
771                 char *path = NULL;
772
773                 node = xpath_obj->nodesetval->nodeTab[j];
774                 if (!node) continue;
775                 path = (char *) xmlGetProp (node, (xmlChar *) "dev");
776                 if (!path) continue;
777
778                 if (il_block_devices &&
779                     ignore_device_match (il_block_devices, name, path) != 0)
780                     goto cont2;
781
782                 add_block_device (dom, path);
783             cont2:
784                 if (path) xmlFree (path);
785             }
786             xmlXPathFreeObject (xpath_obj);
787
788             /* Network interfaces. */
789             xpath_obj = xmlXPathEval
790                 ((xmlChar *) "/domain/devices/interface[target[@dev]]",
791                  xpath_ctx);
792             if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
793                 xpath_obj->nodesetval == NULL)
794                 goto cont;
795
796             xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
797
798             for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
799                 char *path = NULL;
800                 char *address = NULL;
801                 xmlNodePtr xml_interface;
802
803                 xml_interface = xml_interfaces->nodeTab[j];
804                 if (!xml_interface) continue;
805
806                 for (xmlNodePtr child = xml_interface->children; child; child = child->next) {
807                     if (child->type != XML_ELEMENT_NODE) continue;
808
809                     if (xmlStrEqual(child->name, (const xmlChar *) "target")) {
810                         path = (char *) xmlGetProp (child, (const xmlChar *) "dev");
811                         if (!path) continue;
812                     } else if (xmlStrEqual(child->name, (const xmlChar *) "mac")) {
813                         address = (char *) xmlGetProp (child, (const xmlChar *) "address");
814                         if (!address) continue;
815                     }
816                 }
817
818                 if (il_interface_devices &&
819                     (ignore_device_match (il_interface_devices, name, path) != 0 ||
820                      ignore_device_match (il_interface_devices, name, address) != 0))
821                     goto cont3;
822
823                 add_interface_device (dom, path, address, j+1);
824                 cont3:
825                     if (path) xmlFree (path);
826                     if (address) xmlFree (address);
827             }
828
829         cont:
830             if (xpath_obj) xmlXPathFreeObject (xpath_obj);
831             if (xpath_ctx) xmlXPathFreeContext (xpath_ctx);
832             if (xml_doc) xmlFreeDoc (xml_doc);
833             sfree (xml);
834         }
835
836         sfree (domids);
837     }
838
839     return 0;
840 }
841
842 static void
843 free_domains (void)
844 {
845     if (domains) {
846         for (int i = 0; i < nr_domains; ++i)
847             virDomainFree (domains[i]);
848         sfree (domains);
849     }
850     domains = NULL;
851     nr_domains = 0;
852 }
853
854 static int
855 add_domain (virDomainPtr dom)
856 {
857     virDomainPtr *new_ptr;
858     int new_size = sizeof (domains[0]) * (nr_domains+1);
859
860     if (domains)
861         new_ptr = realloc (domains, new_size);
862     else
863         new_ptr = malloc (new_size);
864
865     if (new_ptr == NULL)
866         return -1;
867
868     domains = new_ptr;
869     domains[nr_domains] = dom;
870     return nr_domains++;
871 }
872
873 static void
874 free_block_devices (void)
875 {
876     if (block_devices) {
877         for (int i = 0; i < nr_block_devices; ++i)
878             sfree (block_devices[i].path);
879         sfree (block_devices);
880     }
881     block_devices = NULL;
882     nr_block_devices = 0;
883 }
884
885 static int
886 add_block_device (virDomainPtr dom, const char *path)
887 {
888     struct block_device *new_ptr;
889     int new_size = sizeof (block_devices[0]) * (nr_block_devices+1);
890     char *path_copy;
891
892     path_copy = strdup (path);
893     if (!path_copy)
894         return -1;
895
896     if (block_devices)
897         new_ptr = realloc (block_devices, new_size);
898     else
899         new_ptr = malloc (new_size);
900
901     if (new_ptr == NULL) {
902         sfree (path_copy);
903         return -1;
904     }
905     block_devices = new_ptr;
906     block_devices[nr_block_devices].dom = dom;
907     block_devices[nr_block_devices].path = path_copy;
908     return nr_block_devices++;
909 }
910
911 static void
912 free_interface_devices (void)
913 {
914     if (interface_devices) {
915         for (int i = 0; i < nr_interface_devices; ++i) {
916             sfree (interface_devices[i].path);
917             sfree (interface_devices[i].address);
918             sfree (interface_devices[i].number);
919         }
920         sfree (interface_devices);
921     }
922     interface_devices = NULL;
923     nr_interface_devices = 0;
924 }
925
926 static int
927 add_interface_device (virDomainPtr dom, const char *path, const char *address, unsigned int number)
928 {
929     struct interface_device *new_ptr;
930     int new_size = sizeof (interface_devices[0]) * (nr_interface_devices+1);
931     char *path_copy, *address_copy, number_string[15];
932
933     if ((path == NULL) || (address == NULL))
934         return EINVAL;
935
936     path_copy = strdup (path);
937     if (!path_copy) return -1;
938
939     address_copy = strdup (address);
940     if (!address_copy) {
941         sfree(path_copy);
942         return -1;
943     }
944
945     snprintf(number_string, sizeof (number_string), "interface-%u", number);
946
947     if (interface_devices)
948         new_ptr = realloc (interface_devices, new_size);
949     else
950         new_ptr = malloc (new_size);
951
952     if (new_ptr == NULL) {
953         sfree (path_copy);
954         sfree (address_copy);
955         return -1;
956     }
957     interface_devices = new_ptr;
958     interface_devices[nr_interface_devices].dom = dom;
959     interface_devices[nr_interface_devices].path = path_copy;
960     interface_devices[nr_interface_devices].address = address_copy;
961     interface_devices[nr_interface_devices].number = strdup(number_string);
962     return nr_interface_devices++;
963 }
964
965 static int
966 ignore_device_match (ignorelist_t *il, const char *domname, const char *devpath)
967 {
968     char *name;
969     int n, r;
970
971     if ((domname == NULL) || (devpath == NULL))
972         return 0;
973
974     n = sizeof (char) * (strlen (domname) + strlen (devpath) + 2);
975     name = malloc (n);
976     if (name == NULL) {
977         ERROR (PLUGIN_NAME " plugin: malloc failed.");
978         return 0;
979     }
980     ssnprintf (name, n, "%s:%s", domname, devpath);
981     r = ignorelist_match (il, name);
982     sfree (name);
983     return r;
984 }
985
986 static int
987 lv_shutdown (void)
988 {
989     free_block_devices ();
990     free_interface_devices ();
991     free_domains ();
992
993     if (conn != NULL)
994         virConnectClose (conn);
995     conn = NULL;
996
997     ignorelist_free (il_domains);
998     il_domains = NULL;
999     ignorelist_free (il_block_devices);
1000     il_block_devices = NULL;
1001     ignorelist_free (il_interface_devices);
1002     il_interface_devices = NULL;
1003
1004     return 0;
1005 }
1006
1007 void
1008 module_register (void)
1009 {
1010     plugin_register_config (PLUGIN_NAME,
1011     lv_config,
1012     config_keys, NR_CONFIG_KEYS);
1013     plugin_register_init (PLUGIN_NAME, lv_init);
1014     plugin_register_read (PLUGIN_NAME, lv_read);
1015     plugin_register_shutdown (PLUGIN_NAME, lv_shutdown);
1016 }
1017
1018 /*
1019  * vim: shiftwidth=4 tabstop=8 softtabstop=4 expandtab fdm=marker
1020  */