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