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