1 /**
2 * collectd - src/libvirt.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 **/
22 #include "collectd.h"
23 #include "common.h"
24 #include "plugin.h"
25 #include "configfile.h"
26 #include "utils_ignorelist.h"
27 #include "utils_complain.h"
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>
35 static const char *config_keys[] = {
36 "Connection",
38 "RefreshInterval",
40 "Domain",
41 "BlockDevice",
42 "InterfaceDevice",
43 "IgnoreSelected",
45 "HostnameFormat",
47 NULL
48 };
49 #define NR_CONFIG_KEYS ((sizeof config_keys / sizeof config_keys[0]) - 1)
51 /* Connection. */
52 static virConnectPtr conn = 0;
53 static char *conn_string = NULL;
54 static c_complain_t conn_complain = C_COMPLAIN_INIT_STATIC;
56 /* Seconds between list refreshes, 0 disables completely. */
57 static int interval = 60;
59 /* List of domains, if specified. */
60 static ignorelist_t *il_domains = NULL;
61 /* List of block devices, if specified. */
62 static ignorelist_t *il_block_devices = NULL;
63 /* List of network interface devices, if specified. */
64 static ignorelist_t *il_interface_devices = NULL;
66 static int ignore_device_match (ignorelist_t *,
67 const char *domname, const char *devpath);
69 /* Actual list of domains found on last refresh. */
70 static virDomainPtr *domains = NULL;
71 static int nr_domains = 0;
73 static void free_domains (void);
74 static int add_domain (virDomainPtr dom);
76 /* Actual list of block devices found on last refresh. */
77 struct block_device {
78 virDomainPtr dom; /* domain */
79 char *path; /* name of block device */
80 };
82 static struct block_device *block_devices = NULL;
83 static int nr_block_devices = 0;
85 static void free_block_devices (void);
86 static int add_block_device (virDomainPtr dom, const char *path);
88 /* Actual list of network interfaces found on last refresh. */
89 struct interface_device {
90 virDomainPtr dom; /* domain */
91 char *path; /* name of interface device */
92 };
94 static struct interface_device *interface_devices = NULL;
95 static int nr_interface_devices = 0;
97 static void free_interface_devices (void);
98 static int add_interface_device (virDomainPtr dom, const char *path);
100 /* HostnameFormat. */
101 #define HF_MAX_FIELDS 3
103 enum hf_field {
104 hf_none = 0,
105 hf_hostname,
106 hf_name,
107 hf_uuid
108 };
110 static enum hf_field hostname_format[HF_MAX_FIELDS] =
111 { hf_name };
113 /* Time that we last refreshed. */
114 static time_t last_refresh = (time_t) 0;
116 static int refresh_lists (void);
118 /* Submit functions. */
119 static void cpu_submit (unsigned long long cpu_time,
120 time_t t,
121 virDomainPtr dom, const char *type);
122 static void vcpu_submit (unsigned long long cpu_time,
123 time_t t,
124 virDomainPtr dom, int vcpu_nr, const char *type);
125 static void submit_counter2 (const char *type, counter_t v0, counter_t v1,
126 time_t t,
127 virDomainPtr dom, const char *devname);
129 /* ERROR(...) macro for virterrors. */
130 #define VIRT_ERROR(conn,s) do { \
131 virErrorPtr err; \
132 err = (conn) ? virConnGetLastError ((conn)) : virGetLastError (); \
133 if (err) ERROR ("%s: %s", (s), err->message); \
134 } while(0)
136 static int
137 lv_init (void)
138 {
139 if (virInitialize () != 0)
140 return -1;
142 return 0;
143 }
145 static int
146 lv_config (const char *key, const char *value)
147 {
148 if (virInitialize () != 0)
149 return 1;
151 if (il_domains == NULL)
152 il_domains = ignorelist_create (1);
153 if (il_block_devices == NULL)
154 il_block_devices = ignorelist_create (1);
155 if (il_interface_devices == NULL)
156 il_interface_devices = ignorelist_create (1);
158 if (strcasecmp (key, "Connection") == 0) {
159 char *tmp = strdup (value);
160 if (tmp == NULL) {
161 ERROR ("libvirt plugin: Connection strdup failed.");
162 return 1;
163 }
164 sfree (conn_string);
165 conn_string = tmp;
166 return 0;
167 }
169 if (strcasecmp (key, "RefreshInterval") == 0) {
170 char *eptr = NULL;
171 interval = strtol (value, &eptr, 10);
172 if (eptr == NULL || *eptr != '\0') return 1;
173 return 0;
174 }
176 if (strcasecmp (key, "Domain") == 0) {
177 if (ignorelist_add (il_domains, value)) return 1;
178 return 0;
179 }
180 if (strcasecmp (key, "BlockDevice") == 0) {
181 if (ignorelist_add (il_block_devices, value)) return 1;
182 return 0;
183 }
184 if (strcasecmp (key, "InterfaceDevice") == 0) {
185 if (ignorelist_add (il_interface_devices, value)) return 1;
186 return 0;
187 }
189 if (strcasecmp (key, "IgnoreSelected") == 0) {
190 if (IS_TRUE (value))
191 {
192 ignorelist_set_invert (il_domains, 0);
193 ignorelist_set_invert (il_block_devices, 0);
194 ignorelist_set_invert (il_interface_devices, 0);
195 }
196 else
197 {
198 ignorelist_set_invert (il_domains, 1);
199 ignorelist_set_invert (il_block_devices, 1);
200 ignorelist_set_invert (il_interface_devices, 1);
201 }
202 return 0;
203 }
205 if (strcasecmp (key, "HostnameFormat") == 0) {
206 char *value_copy;
207 char *fields[HF_MAX_FIELDS];
208 int i, n;
210 value_copy = strdup (value);
211 if (value_copy == NULL) {
212 ERROR ("libvirt plugin: strdup failed.");
213 return -1;
214 }
216 n = strsplit (value_copy, fields, HF_MAX_FIELDS);
217 if (n < 1) {
218 free (value_copy);
219 ERROR ("HostnameFormat: no fields");
220 return -1;
221 }
223 for (i = 0; i < n; ++i) {
224 if (strcasecmp (fields[i], "hostname") == 0)
225 hostname_format[i] = hf_hostname;
226 else if (strcasecmp (fields[i], "name") == 0)
227 hostname_format[i] = hf_name;
228 else if (strcasecmp (fields[i], "uuid") == 0)
229 hostname_format[i] = hf_uuid;
230 else {
231 free (value_copy);
232 ERROR ("unknown HostnameFormat field: %s", fields[i]);
233 return -1;
234 }
235 }
236 free (value_copy);
238 for (i = n; i < HF_MAX_FIELDS; ++i)
239 hostname_format[i] = hf_none;
241 return 0;
242 }
244 /* Unrecognised option. */
245 return -1;
246 }
248 static int
249 lv_read (void)
250 {
251 time_t t;
252 int i;
254 if (conn == NULL) {
255 /* `conn_string == NULL' is acceptable. */
256 conn = virConnectOpenReadOnly (conn_string);
257 if (conn == NULL) {
258 c_complain (LOG_ERR, &conn_complain,
259 "libvirt plugin: Unable to connect: "
260 "virConnectOpenReadOnly failed.");
261 return -1;
262 }
263 }
264 c_release (LOG_NOTICE, &conn_complain,
265 "libvirt plugin: Connection established.");
267 time (&t);
269 /* Need to refresh domain or device lists? */
270 if ((last_refresh == (time_t) 0) ||
271 ((interval > 0) && ((last_refresh + interval) <= t))) {
272 if (refresh_lists () != 0) {
273 if (conn != NULL)
274 virConnectClose (conn);
275 conn = NULL;
276 return -1;
277 }
278 last_refresh = t;
279 }
281 #if 0
282 for (i = 0; i < nr_domains; ++i)
283 fprintf (stderr, "domain %s\n", virDomainGetName (domains[i]));
284 for (i = 0; i < nr_block_devices; ++i)
285 fprintf (stderr, "block device %d %s:%s\n",
286 i, virDomainGetName (block_devices[i].dom),
287 block_devices[i].path);
288 for (i = 0; i < nr_interface_devices; ++i)
289 fprintf (stderr, "interface device %d %s:%s\n",
290 i, virDomainGetName (interface_devices[i].dom),
291 interface_devices[i].path);
292 #endif
294 /* Get CPU usage, VCPU usage for each domain. */
295 for (i = 0; i < nr_domains; ++i) {
296 virDomainInfo info;
297 virVcpuInfoPtr vinfo = NULL;
298 int status;
299 int j;
301 status = virDomainGetInfo (domains[i], &info);
302 if (status != 0)
303 {
304 ERROR ("libvirt plugin: virDomainGetInfo failed with status %i.",
305 status);
306 continue;
307 }
309 if (info.state != VIR_DOMAIN_RUNNING)
310 {
311 /* only gather stats for running domains */
312 continue;
313 }
315 cpu_submit (info.cpuTime, t, domains[i], "virt_cpu_total");
317 vinfo = malloc (info.nrVirtCpu * sizeof (vinfo[0]));
318 if (vinfo == NULL) {
319 ERROR ("libvirt plugin: malloc failed.");
320 continue;
321 }
323 status = virDomainGetVcpus (domains[i], vinfo, info.nrVirtCpu,
324 /* cpu map = */ NULL, /* cpu map length = */ 0);
325 if (status < 0)
326 {
327 ERROR ("libvirt plugin: virDomainGetVcpus failed with status %i.",
328 status);
329 free (vinfo);
330 continue;
331 }
333 for (j = 0; j < info.nrVirtCpu; ++j)
334 vcpu_submit (vinfo[j].cpuTime,
335 t, domains[i], vinfo[j].number, "virt_vcpu");
337 free (vinfo);
338 }
340 /* Get block device stats for each domain. */
341 for (i = 0; i < nr_block_devices; ++i) {
342 struct _virDomainBlockStats stats;
344 if (virDomainBlockStats (block_devices[i].dom, block_devices[i].path,
345 &stats, sizeof stats) != 0)
346 continue;
348 if ((stats.rd_req != -1) && (stats.wr_req != -1))
349 submit_counter2 ("disk_ops",
350 (counter_t) stats.rd_req, (counter_t) stats.wr_req,
351 t, block_devices[i].dom, block_devices[i].path);
353 if ((stats.rd_bytes != -1) && (stats.wr_bytes != -1))
354 submit_counter2 ("disk_octets",
355 (counter_t) stats.rd_bytes, (counter_t) stats.wr_bytes,
356 t, block_devices[i].dom, block_devices[i].path);
357 } /* for (nr_block_devices) */
359 /* Get interface stats for each domain. */
360 for (i = 0; i < nr_interface_devices; ++i) {
361 struct _virDomainInterfaceStats stats;
363 if (virDomainInterfaceStats (interface_devices[i].dom,
364 interface_devices[i].path,
365 &stats, sizeof stats) != 0)
366 continue;
368 if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
369 submit_counter2 ("if_octets",
370 (counter_t) stats.rx_bytes, (counter_t) stats.tx_bytes,
371 t, interface_devices[i].dom, interface_devices[i].path);
373 if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
374 submit_counter2 ("if_packets",
375 (counter_t) stats.rx_packets, (counter_t) stats.tx_packets,
376 t, interface_devices[i].dom, interface_devices[i].path);
378 if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
379 submit_counter2 ("if_errors",
380 (counter_t) stats.rx_errs, (counter_t) stats.tx_errs,
381 t, interface_devices[i].dom, interface_devices[i].path);
383 if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
384 submit_counter2 ("if_dropped",
385 (counter_t) stats.rx_drop, (counter_t) stats.tx_drop,
386 t, interface_devices[i].dom, interface_devices[i].path);
387 } /* for (nr_interface_devices) */
389 return 0;
390 }
392 static int
393 refresh_lists (void)
394 {
395 int n;
397 n = virConnectNumOfDomains (conn);
398 if (n < 0) {
399 VIRT_ERROR (conn, "reading number of domains");
400 return -1;
401 }
403 if (n > 0) {
404 int i;
405 int *domids;
407 /* Get list of domains. */
408 domids = malloc (sizeof (int) * n);
409 if (domids == 0) {
410 ERROR ("libvirt plugin: malloc failed.");
411 return -1;
412 }
414 n = virConnectListDomains (conn, domids, n);
415 if (n < 0) {
416 VIRT_ERROR (conn, "reading list of domains");
417 free (domids);
418 return -1;
419 }
421 free_block_devices ();
422 free_interface_devices ();
423 free_domains ();
425 /* Fetch each domain and add it to the list, unless ignore. */
426 for (i = 0; i < n; ++i) {
427 virDomainPtr dom = NULL;
428 const char *name;
429 char *xml = NULL;
430 xmlDocPtr xml_doc = NULL;
431 xmlXPathContextPtr xpath_ctx = NULL;
432 xmlXPathObjectPtr xpath_obj = NULL;
433 int j;
435 dom = virDomainLookupByID (conn, domids[i]);
436 if (dom == NULL) {
437 VIRT_ERROR (conn, "virDomainLookupByID");
438 /* Could be that the domain went away -- ignore it anyway. */
439 continue;
440 }
442 name = virDomainGetName (dom);
443 if (name == NULL) {
444 VIRT_ERROR (conn, "virDomainGetName");
445 goto cont;
446 }
448 if (il_domains && ignorelist_match (il_domains, name) != 0)
449 goto cont;
451 if (add_domain (dom) < 0) {
452 ERROR ("libvirt plugin: malloc failed.");
453 goto cont;
454 }
456 /* Get a list of devices for this domain. */
457 xml = virDomainGetXMLDesc (dom, 0);
458 if (!xml) {
459 VIRT_ERROR (conn, "virDomainGetXMLDesc");
460 goto cont;
461 }
463 /* Yuck, XML. Parse out the devices. */
464 xml_doc = xmlReadDoc ((xmlChar *) xml, NULL, NULL, XML_PARSE_NONET);
465 if (xml_doc == NULL) {
466 VIRT_ERROR (conn, "xmlReadDoc");
467 goto cont;
468 }
470 xpath_ctx = xmlXPathNewContext (xml_doc);
472 /* Block devices. */
473 xpath_obj = xmlXPathEval
474 ((xmlChar *) "/domain/devices/disk/target[@dev]",
475 xpath_ctx);
476 if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
477 xpath_obj->nodesetval == NULL)
478 goto cont;
480 for (j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
481 xmlNodePtr node;
482 char *path = NULL;
484 node = xpath_obj->nodesetval->nodeTab[j];
485 if (!node) continue;
486 path = (char *) xmlGetProp (node, (xmlChar *) "dev");
487 if (!path) continue;
489 if (il_block_devices &&
490 ignore_device_match (il_block_devices, name, path) != 0)
491 goto cont2;
493 add_block_device (dom, path);
494 cont2:
495 if (path) xmlFree (path);
496 }
497 xmlXPathFreeObject (xpath_obj);
499 /* Network interfaces. */
500 xpath_obj = xmlXPathEval
501 ((xmlChar *) "/domain/devices/interface/target[@dev]",
502 xpath_ctx);
503 if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
504 xpath_obj->nodesetval == NULL)
505 goto cont;
507 for (j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
508 xmlNodePtr node;
509 char *path = NULL;
511 node = xpath_obj->nodesetval->nodeTab[j];
512 if (!node) continue;
513 path = (char *) xmlGetProp (node, (xmlChar *) "dev");
514 if (!path) continue;
516 if (il_interface_devices &&
517 ignore_device_match (il_interface_devices, name, path) != 0)
518 goto cont3;
520 add_interface_device (dom, path);
521 cont3:
522 if (path) xmlFree (path);
523 }
525 cont:
526 if (xpath_obj) xmlXPathFreeObject (xpath_obj);
527 if (xpath_ctx) xmlXPathFreeContext (xpath_ctx);
528 if (xml_doc) xmlFreeDoc (xml_doc);
529 if (xml) free (xml);
530 }
532 free (domids);
533 }
535 return 0;
536 }
538 static void
539 free_domains ()
540 {
541 int i;
543 if (domains) {
544 for (i = 0; i < nr_domains; ++i)
545 virDomainFree (domains[i]);
546 free (domains);
547 }
548 domains = NULL;
549 nr_domains = 0;
550 }
552 static int
553 add_domain (virDomainPtr dom)
554 {
555 virDomainPtr *new_ptr;
556 int new_size = sizeof (domains[0]) * (nr_domains+1);
558 if (domains)
559 new_ptr = realloc (domains, new_size);
560 else
561 new_ptr = malloc (new_size);
563 if (new_ptr == NULL)
564 return -1;
566 domains = new_ptr;
567 domains[nr_domains] = dom;
568 return nr_domains++;
569 }
571 static void
572 free_block_devices ()
573 {
574 int i;
576 if (block_devices) {
577 for (i = 0; i < nr_block_devices; ++i)
578 free (block_devices[i].path);
579 free (block_devices);
580 }
581 block_devices = NULL;
582 nr_block_devices = 0;
583 }
585 static int
586 add_block_device (virDomainPtr dom, const char *path)
587 {
588 struct block_device *new_ptr;
589 int new_size = sizeof (block_devices[0]) * (nr_block_devices+1);
590 char *path_copy;
592 path_copy = strdup (path);
593 if (!path_copy)
594 return -1;
596 if (block_devices)
597 new_ptr = realloc (block_devices, new_size);
598 else
599 new_ptr = malloc (new_size);
601 if (new_ptr == NULL) {
602 free (path_copy);
603 return -1;
604 }
605 block_devices = new_ptr;
606 block_devices[nr_block_devices].dom = dom;
607 block_devices[nr_block_devices].path = path_copy;
608 return nr_block_devices++;
609 }
611 static void
612 free_interface_devices ()
613 {
614 int i;
616 if (interface_devices) {
617 for (i = 0; i < nr_interface_devices; ++i)
618 free (interface_devices[i].path);
619 free (interface_devices);
620 }
621 interface_devices = NULL;
622 nr_interface_devices = 0;
623 }
625 static int
626 add_interface_device (virDomainPtr dom, const char *path)
627 {
628 struct interface_device *new_ptr;
629 int new_size = sizeof (interface_devices[0]) * (nr_interface_devices+1);
630 char *path_copy;
632 path_copy = strdup (path);
633 if (!path_copy) return -1;
635 if (interface_devices)
636 new_ptr = realloc (interface_devices, new_size);
637 else
638 new_ptr = malloc (new_size);
640 if (new_ptr == NULL) {
641 free (path_copy);
642 return -1;
643 }
644 interface_devices = new_ptr;
645 interface_devices[nr_interface_devices].dom = dom;
646 interface_devices[nr_interface_devices].path = path_copy;
647 return nr_interface_devices++;
648 }
650 static int
651 ignore_device_match (ignorelist_t *il, const char *domname, const char *devpath)
652 {
653 char *name;
654 int n, r;
656 n = sizeof (char) * (strlen (domname) + strlen (devpath) + 2);
657 name = malloc (n);
658 if (name == NULL) {
659 ERROR ("libvirt plugin: malloc failed.");
660 return 0;
661 }
662 ssnprintf (name, n, "%s:%s", domname, devpath);
663 r = ignorelist_match (il, name);
664 free (name);
665 return r;
666 }
668 static void
669 init_value_list (value_list_t *vl, time_t t, virDomainPtr dom)
670 {
671 int i, n;
672 const char *name;
673 char uuid[VIR_UUID_STRING_BUFLEN];
675 vl->time = t;
676 vl->interval = interval_g;
678 sstrncpy (vl->plugin, "libvirt", sizeof (vl->plugin));
680 vl->host[0] = '\0';
682 /* Construct the hostname field according to HostnameFormat. */
683 for (i = 0; i < HF_MAX_FIELDS; ++i) {
684 if (hostname_format[i] == hf_none)
685 continue;
687 n = DATA_MAX_NAME_LEN - strlen (vl->host) - 2;
689 if (i > 0 && n >= 1) {
690 strncat (vl->host, ":", 1);
691 n--;
692 }
694 switch (hostname_format[i]) {
695 case hf_none: break;
696 case hf_hostname:
697 strncat (vl->host, hostname_g, n);
698 break;
699 case hf_name:
700 name = virDomainGetName (dom);
701 if (name)
702 strncat (vl->host, name, n);
703 break;
704 case hf_uuid:
705 if (virDomainGetUUIDString (dom, uuid) == 0)
706 strncat (vl->host, uuid, n);
707 break;
708 }
709 }
711 vl->host[sizeof (vl->host) - 1] = '\0';
712 } /* void init_value_list */
714 static void
715 cpu_submit (unsigned long long cpu_time,
716 time_t t,
717 virDomainPtr dom, const char *type)
718 {
719 value_t values[1];
720 value_list_t vl = VALUE_LIST_INIT;
722 init_value_list (&vl, t, dom);
724 values[0].counter = cpu_time;
726 vl.values = values;
727 vl.values_len = 1;
729 sstrncpy (vl.type, type, sizeof (vl.type));
731 plugin_dispatch_values (&vl);
732 }
734 static void
735 vcpu_submit (counter_t cpu_time,
736 time_t t,
737 virDomainPtr dom, int vcpu_nr, const char *type)
738 {
739 value_t values[1];
740 value_list_t vl = VALUE_LIST_INIT;
742 init_value_list (&vl, t, dom);
744 values[0].counter = cpu_time;
745 vl.values = values;
746 vl.values_len = 1;
748 sstrncpy (vl.type, type, sizeof (vl.type));
749 ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%d", vcpu_nr);
751 plugin_dispatch_values (&vl);
752 }
754 static void
755 submit_counter2 (const char *type, counter_t v0, counter_t v1,
756 time_t t,
757 virDomainPtr dom, const char *devname)
758 {
759 value_t values[2];
760 value_list_t vl = VALUE_LIST_INIT;
762 init_value_list (&vl, t, dom);
764 values[0].counter = v0;
765 values[1].counter = v1;
766 vl.values = values;
767 vl.values_len = 2;
769 sstrncpy (vl.type, type, sizeof (vl.type));
770 sstrncpy (vl.type_instance, devname, sizeof (vl.type_instance));
772 plugin_dispatch_values (&vl);
773 } /* void submit_counter2 */
775 static int
776 lv_shutdown (void)
777 {
778 free_block_devices ();
779 free_interface_devices ();
780 free_domains ();
782 if (conn != NULL)
783 virConnectClose (conn);
784 conn = NULL;
786 ignorelist_free (il_domains);
787 il_domains = NULL;
788 ignorelist_free (il_block_devices);
789 il_block_devices = NULL;
790 ignorelist_free (il_interface_devices);
791 il_interface_devices = NULL;
793 return 0;
794 }
796 void
797 module_register (void)
798 {
799 plugin_register_config ("libvirt",
800 lv_config,
801 config_keys, NR_CONFIG_KEYS);
802 plugin_register_init ("libvirt", lv_init);
803 plugin_register_read ("libvirt", lv_read);
804 plugin_register_shutdown ("libvirt", lv_shutdown);
805 }
807 /*
808 * vim: shiftwidth=4 tabstop=8 softtabstop=4 expandtab fdm=marker
809 */