pmdalibvirt: initial version of a PMDA for libvirt-based metrics
[pcp.git] / src / pmdas / libvirt / connect.py
blob56f5818a7cf597aea19c65d839acf26e1d64654e
1 #!/usr/bin/env python
3 # Copyright (C) 2016 Marko Myllynen <myllynen@redhat.com>
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
16 try:
17 import ConfigParser
18 except ImportError:
19 import configparser as ConfigParser
21 import os
22 import pwd
23 import sys
24 import libvirt
26 from pcp.pmapi import pmContext as PCP
28 conffile = PCP.pmGetConfig('PCP_PMDAS_DIR')
29 conffile += '/libvirt/libvirt.conf'
31 user = 'root'
32 uri = 'qemu:///system'
34 config = ConfigParser.SafeConfigParser()
35 config.read(conffile)
36 if config.has_section('pmda'):
37 for opt in config.options('pmda'):
38 if opt == 'user':
39 user = config.get('pmda', opt)
40 elif opt == 'uri':
41 uri = config.get('pmda', opt)
42 else:
43 sys.stderr.write("Invalid directive '%s' in %s.\n" % (opt, conffile))
44 sys.exit(1)
46 if len(sys.argv) > 1 and (sys.argv[1] == '-c' or sys.argv[1] == '--config'):
47 sys.stdout.write("user=%s\nuri=%s\n" % (user, uri))
48 sys.exit(0)
50 try:
51 uid = pwd.getpwnam(user).pw_uid
52 os.setuid(uid)
53 except:
54 sys.stderr.write("Failed to switch as user %s, try sudo perhaps?\n" % user)
55 sys.exit(1)
57 try:
58 conn = libvirt.openReadOnly(uri)
59 doms = conn.listAllDomains(libvirt.VIR_CONNECT_LIST_DOMAINS_ACTIVE)
60 except:
61 sys.stdout.write("Connection as %s to %s failed!\n" % (user, uri))
62 sys.exit(1)
64 sys.stdout.write("Connection as %s to %s ok.\n" % (user, uri))