[virt-who] Add VDSM mode
by Radek Novacek
commit 6c76df43df047bb9eb1c01a6397d98e8bf1d7aed
Author: Radek Novacek <rnovacek(a)redhat.com>
Date: Tue Sep 13 16:14:57 2011 +0200
Add VDSM mode
vdsm.py | 112 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
virt-who.py | 28 ++++++++++++---
2 files changed, 135 insertions(+), 5 deletions(-)
---
diff --git a/vdsm.py b/vdsm.py
new file mode 100644
index 0000000..aa029c1
--- /dev/null
+++ b/vdsm.py
@@ -0,0 +1,112 @@
+"""
+Module for accessing vdsm, part of virt-who
+
+Parts of this file is based on rhn-virtualization from spacewalk
+http://git.fedorahosted.org/git/?p=spacewalk.git;a=tree;f=client/tools/rhn-virtualization
+
+Copyright (C) 2011 Radek Novacek <rnovacek(a)redhat.com>
+
+This program is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+"""
+
+import xmlrpclib
+from ConfigParser import SafeConfigParser, NoSectionError
+import subprocess
+
+class VdsmError(Exception):
+ pass
+
+class Domain:
+ """ Class for compatibility with libvirt Domain class. Only UUID supported. """
+ def __init__(self, uuid):
+ self.uuid = uuid
+
+ def UUIDString(self):
+ return self.uuid
+
+ def __str__(self):
+ return self.uuid
+
+class VDSM:
+ def __init__(self, logger):
+ self.logger = logger
+ self._readConfig("/etc/vdsm/vdsm.conf")
+ self.connect()
+
+ def _readConfig(self, configName):
+ parser = SafeConfigParser()
+ parser.read(configName)
+ try:
+ self.ssl = parser.get("vars", "ssl").lower() in ["1", "true"]
+ if self.ssl:
+ self.trust_store_path = parser.get("vars", "trust_store_path")
+ else:
+ self.trust_store_path = None
+ self.management_port = parser.get("addresses", "management_port")
+ except NoSectionError, e:
+ raise VdsmError("Error in vdsm configuration file: %s" % str(e))
+
+ def _getLocalVdsName(self, tsPath):
+ p = subprocess.Popen(['/usr/bin/openssl', 'x509', '-noout', '-subject', '-in',
+ '%s/certs/vdsmcert.pem' % tsPath], stdout=subprocess.PIPE, close_fds=True)
+ out, err = p.communicate()
+ if p.returncode != 0:
+ return '0'
+ return out.split('=')[-1].strip()
+
+ def _secureConnect(self):
+ addr = self._getLocalVdsName(self.trust_store_path)
+
+ from M2Crypto.m2xmlrpclib import SSL_Transport
+ from M2Crypto import SSL
+
+ KEYFILE = self.trust_store_path + '/keys/vdsmkey.pem'
+ CERTFILE = self.trust_store_path + '/certs/vdsmcert.pem'
+ CACERT = self.trust_store_path + '/certs/cacert.pem'
+
+ ctx = SSL.Context('sslv3')
+
+ ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 16)
+ ctx.load_verify_locations(CACERT)
+ ctx.load_cert(CERTFILE, KEYFILE)
+
+ return xmlrpclib.Server('https://%s:%s' % (addr, self.management_port), SSL_Transport(ctx))
+
+ def connect(self):
+ if self.trust_store_path:
+ try:
+ self.server = self._secureConnect()
+ return
+ except Exception, e:
+ self.logger.exception(e)
+ # Try http version if ssl is off or fails
+ self.server = xmlrpclib.Server("http://localhost:%s" % self.management_port)
+
+ def listDomains(self):
+ domains = []
+ response = self.server.list(True)
+ if response['status']['code'] != 0:
+ self.logger.error("Unable to list virtual machines: %s" % response['status']['message'])
+ else:
+ for vm in response['vmList']:
+ domains.append(Domain(vm['vmId']))
+ return domains
+
+
+if __name__ == '__main__':
+ import logging
+ logger = logging.getLogger("rhsm-app." + __name__)
+ vdsm = VDSM(logger)
+ print vdsm.listDomains()
diff --git a/virt-who.py b/virt-who.py
index ddfc090..012794b 100644
--- a/virt-who.py
+++ b/virt-who.py
@@ -23,6 +23,7 @@ import os
import time
from virt import Virt, VirtError
+from vdsm import VDSM
from event import virEventLoopPureStart
from subscriptionmanager import SubscriptionManager
@@ -43,6 +44,8 @@ if __name__ == '__main__':
parser.add_option("-d", "--debug", action="store_true", dest="debug", default=False, help="Enable debugging output")
parser.add_option("-b", "--background", action="store_true", dest="background", default=False, help="Run in the background and monitor virtual guests")
parser.add_option("-i", "--interval", type="int", dest="interval", default=0, help="Acquire and send list of virtual guest each N seconds")
+ parser.add_option("--libvirt", action="store_false", dest="useVDSM", default=False, help="Use libvirt to list virtual guests [default]")
+ parser.add_option("--vdsm", action="store_true", dest="useVDSM", default=False, help="Use vdsm to list virtual guests")
(options, args) = parser.parse_args()
@@ -69,6 +72,10 @@ if __name__ == '__main__':
except ValueError:
logger.warning("Interval is not number, ignoring")
+ env = os.getenv("VIRTWHO_VDSM", "0").strip().lower()
+ if env in ["1", "true"]:
+ options.useVDSM = True
+
if options.interval < 0:
logger.warning("Interval is not positive number, ignoring")
options.interval = 0
@@ -77,6 +84,10 @@ if __name__ == '__main__':
logger.warning("Interval and background options can't be used together, using interval only")
options.background = False
+ if options.background and options.useVDSM:
+ logger.error("Unable to start in background in VDSM mode, use interval instead")
+ sys.exit(4)
+
if options.background:
try:
pid = os.fork()
@@ -104,11 +115,18 @@ if __name__ == '__main__':
logger.error("Error in reading configuration file (/etc/rhsm/rhsm.conf): %s" % e)
sys.exit(2)
- try:
- virt = Virt(logger)
- except VirtError, e:
- print e
- sys.exit(3)
+ if options.useVDSM:
+ try:
+ virt = VDSM(logger)
+ except Exception, e:
+ logger.exception(e)
+ sys.exit(3)
+ else:
+ try:
+ virt = Virt(logger)
+ except VirtError, e:
+ logger.exception(e)
+ sys.exit(3)
subscriptionManager.connect()
if options.background:
12 years, 7 months
[virt-who] Fix printing to stderr without -d option
by Radek Novacek
commit 388b2ced129c495377b8c228ead8bd1d7b5b11ba
Author: Radek Novacek <rnovacek(a)redhat.com>
Date: Tue Sep 13 16:11:20 2011 +0200
Fix printing to stderr without -d option
virt-who.py | 5 +++--
1 files changed, 3 insertions(+), 2 deletions(-)
---
diff --git a/virt-who.py b/virt-who.py
index 5d1ba73..ddfc090 100644
--- a/virt-who.py
+++ b/virt-who.py
@@ -54,8 +54,9 @@ if __name__ == '__main__':
if options.debug:
# Enable debugging output to be writen in /var/log
logger.setLevel(logging.DEBUG)
- # Print debugging output to stderr too
- logger.addHandler(logging.StreamHandler())
+
+ # Print debugging output to stderr too
+ logger.addHandler(logging.StreamHandler())
env = os.getenv("VIRTWHO_BACKGROUND", "0").strip().lower()
if env in ["1", "true"]:
12 years, 7 months
[virt-who] Add --interval command line option
by Radek Novacek
commit e6e8b4e32a2da45ba8406bd31a0a46f441d5ca1c
Author: Radek Novacek <rnovacek(a)redhat.com>
Date: Tue Sep 13 15:24:04 2011 +0200
Add --interval command line option
virt-who.py | 32 +++++++++++++++++++++++++++-----
1 files changed, 27 insertions(+), 5 deletions(-)
---
diff --git a/virt-who.py b/virt-who.py
index 86c6ddd..5d1ba73 100644
--- a/virt-who.py
+++ b/virt-who.py
@@ -42,23 +42,40 @@ if __name__ == '__main__':
parser = OptionParser(description="Agent for reporting virtual guest IDs to subscription-manager")
parser.add_option("-d", "--debug", action="store_true", dest="debug", default=False, help="Enable debugging output")
parser.add_option("-b", "--background", action="store_true", dest="background", default=False, help="Run in the background and monitor virtual guests")
+ parser.add_option("-i", "--interval", type="int", dest="interval", default=0, help="Acquire and send list of virtual guest each N seconds")
(options, args) = parser.parse_args()
# Handle enviromental variables
- env = os.getenv("VIRTWHO_BACKGROUND", "0").strip().lower()
- if env in ["1", "true"]:
- options.background = True
+
env = os.getenv("VIRTWHO_DEBUG", "0").strip().lower()
if env in ["1", "true"]:
options.debug = True
-
if options.debug:
# Enable debugging output to be writen in /var/log
logger.setLevel(logging.DEBUG)
# Print debugging output to stderr too
logger.addHandler(logging.StreamHandler())
+ env = os.getenv("VIRTWHO_BACKGROUND", "0").strip().lower()
+ if env in ["1", "true"]:
+ options.background = True
+
+ env = os.getenv("VIRTWHO_INTERVAL", "0").strip().lower()
+ try:
+ if int(env) > 0 and options.interval == 0:
+ options.interval = int(env)
+ except ValueError:
+ logger.warning("Interval is not number, ignoring")
+
+ if options.interval < 0:
+ logger.warning("Interval is not positive number, ignoring")
+ options.interval = 0
+
+ if options.background and options.interval > 0:
+ logger.warning("Interval and background options can't be used together, using interval only")
+ options.background = False
+
if options.background:
try:
pid = os.fork()
@@ -93,7 +110,6 @@ if __name__ == '__main__':
sys.exit(3)
subscriptionManager.connect()
-
if options.background:
# Run rhsm.sendVirtGuests when something changes in libvirt
virt.domainListChangedCallback(subscriptionManager.sendVirtGuests)
@@ -105,6 +121,12 @@ if __name__ == '__main__':
logger.debug("Entering infinite loop")
while 1:
time.sleep(1)
+ elif options.interval > 0:
+ logger.debug("Starting infinite loop with %d seconds interval" % options.interval)
+ while 1:
+ # Run in infinite loop and send list of UUIDs every N seconds
+ subscriptionManager.sendVirtGuests(virt.listDomains())
+ time.sleep(options.interval)
else:
# Send list of virtual guests and exit
subscriptionManager.sendVirtGuests(virt.listDomains())
12 years, 7 months
[virt-who] Prevent failure when server not implements /status/ command
by Radek Novacek
commit b4d39cfda44f8c43cb582710a262ee850064ef98
Author: Radek Novacek <rnovacek(a)redhat.com>
Date: Wed Sep 7 09:10:22 2011 +0200
Prevent failure when server not implements /status/ command
subscriptionmanager.py | 8 ++++++--
1 files changed, 6 insertions(+), 2 deletions(-)
---
diff --git a/subscriptionmanager.py b/subscriptionmanager.py
index 1ccc3aa..34c756c 100644
--- a/subscriptionmanager.py
+++ b/subscriptionmanager.py
@@ -53,8 +53,12 @@ class SubscriptionManager:
""" Connect to the subscription-manager. """
self.connection = rhsm_connection.UEPConnection(
cert_file=self.cert_file, key_file=self.key_file)
- if not self.connection.ping()['result']:
- self.logger.error("Unable to connect to the server")
+ try:
+ if not self.connection.ping()['result']:
+ self.logger.error("Unable to obtain status from server, UEPConnection is likely not usable.")
+ except Exception, e:
+ self.logger.warn("Unable to obtain status from server, UEPConnection is likely not usable:")
+ self.logger.exception(e)
def sendVirtGuests(self, domains):
""" Update consumer facts with UUIDs of virtual guests. """
12 years, 7 months
[virt-who] Silent rpmlint warning about incoherent subsys
by Radek Novacek
commit 86c5581181863a18b2865658ffd2df5fc299e05c
Author: Radek Novacek <rnovacek(a)redhat.com>
Date: Mon Sep 5 13:37:21 2011 +0200
Silent rpmlint warning about incoherent subsys
virt-who-initscript | 2 +-
1 files changed, 1 insertions(+), 1 deletions(-)
---
diff --git a/virt-who-initscript b/virt-who-initscript
index 0efb89c..ada955d 100644
--- a/virt-who-initscript
+++ b/virt-who-initscript
@@ -30,7 +30,7 @@ pidfile="/var/run/$prog.pid"
export VIRTWHO_BACKGROUND
export VIRTWHO_DEBUG
-lockfile=/var/lock/subsys/$prog
+lockfile=/var/lock/subsys/virt-who
start() {
[ -x $exec ] || exit 5
12 years, 7 months
[virt-who] Fix permission for configuration file
by Radek Novacek
commit c0c0f77f8995769dcd9228a0971e93743b263f64
Author: Radek Novacek <rnovacek(a)redhat.com>
Date: Mon Sep 5 13:14:33 2011 +0200
Fix permission for configuration file
Makefile | 2 +-
1 files changed, 1 insertions(+), 1 deletions(-)
---
diff --git a/Makefile b/Makefile
index 46c13c3..28ac69e 100644
--- a/Makefile
+++ b/Makefile
@@ -17,7 +17,7 @@ install:
install -pm 0644 *.py $(DESTDIR)/usr/share/$(name)/
install virt-who $(DESTDIR)/usr/bin/
install virt-who-initscript $(DESTDIR)/etc/rc.d/init.d/virt-who
- install virt-who.conf $(DESTDIR)/etc/sysconfig/virt-who
+ install -pm 0644 virt-who.conf $(DESTDIR)/etc/sysconfig/virt-who
srpm: pack
rpmbuild --define "_sourcedir $(PWD)" --define "_specdir $(PWD)" --define "_srcrpmdir $(PWD)" -bs $(name).spec
12 years, 7 months
[virt-who] Add missing import sys
by Radek Novacek
commit b6959e72395fbe23c3325514eca427dbcc6349ab
Author: Radek Novacek <rnovacek(a)redhat.com>
Date: Mon Sep 5 12:29:08 2011 +0200
Add missing import sys
log.py | 1 +
1 files changed, 1 insertions(+), 0 deletions(-)
---
diff --git a/log.py b/log.py
index eb99cd5..f2fa0de 100644
--- a/log.py
+++ b/log.py
@@ -22,6 +22,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import logging
import logging.handlers
import os
+import sys
def init_logger():
logging.getLogger("rhsm-app").addHandler(_get_handler())
12 years, 7 months
[virt-who] Make initscript to use pidfile
by Radek Novacek
commit ca312378a4c7b37a8fb895aa5bb9b74ee79f7a48
Author: Radek Novacek <rnovacek(a)redhat.com>
Date: Mon Sep 5 12:28:42 2011 +0200
Make initscript to use pidfile
virt-who-initscript | 10 ++++------
1 files changed, 4 insertions(+), 6 deletions(-)
---
diff --git a/virt-who-initscript b/virt-who-initscript
index 7688eb3..0efb89c 100644
--- a/virt-who-initscript
+++ b/virt-who-initscript
@@ -23,6 +23,7 @@
exec="/usr/bin/virt-who"
prog="virt-who"
config="/etc/sysconfig/virt-who"
+pidfile="/var/run/$prog.pid"
[ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog
@@ -35,8 +36,7 @@ start() {
[ -x $exec ] || exit 5
[ -f $config ] || exit 6
echo -n $"Starting $prog: "
- # if not running, start it up here, usually something like "daemon $exec"
- daemon $exec
+ daemon --pidfile $pidfile $exec
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
@@ -45,8 +45,7 @@ start() {
stop() {
echo -n $"Stopping $prog: "
- # stop it here, often "killproc $prog"
- killproc $prog
+ killproc -p $pidfile $prog
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
@@ -67,8 +66,7 @@ force_reload() {
}
rh_status() {
- # run checks to determine if the service is running or use generic status
- status $prog
+ status -p $pidfile $prog
}
rh_status_q() {
12 years, 7 months
[virt-who] Create pidfile when starting in background mode
by Radek Novacek
commit 3a84b4206623bcbe5644c648af50bb7086bac133
Author: Radek Novacek <rnovacek(a)redhat.com>
Date: Mon Sep 5 12:27:55 2011 +0200
Create pidfile when starting in background mode
virt-who.py | 8 ++++++++
1 files changed, 8 insertions(+), 0 deletions(-)
---
diff --git a/virt-who.py b/virt-who.py
index 949fa6c..86c6ddd 100644
--- a/virt-who.py
+++ b/virt-who.py
@@ -70,6 +70,14 @@ if __name__ == '__main__':
# Parent process
sys.exit(0)
+ # Write pid to pidfile
+ try:
+ f = open("/var/run/virt-who.pid", "w")
+ f.write("%d" % os.getpid())
+ f.close()
+ except Exception, e:
+ logger.error("Unable to create pid file: %s", str(e))
+
virEventLoopPureStart()
try:
12 years, 7 months
[virt-who] Fork when running on the background
by Radek Novacek
commit b3ead0f7985d0e8ae925851fe1b75be8779f7c33
Author: Radek Novacek <rnovacek(a)redhat.com>
Date: Mon Sep 5 09:57:02 2011 +0200
Fork when running on the background
virt-who.py | 10 ++++++++++
1 files changed, 10 insertions(+), 0 deletions(-)
---
diff --git a/virt-who.py b/virt-who.py
index e10f6c0..949fa6c 100644
--- a/virt-who.py
+++ b/virt-who.py
@@ -60,6 +60,16 @@ if __name__ == '__main__':
logger.addHandler(logging.StreamHandler())
if options.background:
+ try:
+ pid = os.fork()
+ except OSError:
+ logger.error("Unable to fork, continuing in foreground")
+ pid = 0
+
+ if pid > 0:
+ # Parent process
+ sys.exit(0)
+
virEventLoopPureStart()
try:
12 years, 7 months