[virt-who] Handle unknown libvirt events properly
by Radek Novacek
commit f529d9ffce69905353d4cc1ccda2da5941a54300
Author: Radek Novacek <rnovacek(a)redhat.com>
Date: Thu Apr 26 15:23:52 2012 +0200
Handle unknown libvirt events properly
virt.py | 29 +++++++++++++++++++----------
1 files changed, 19 insertions(+), 10 deletions(-)
---
diff --git a/virt.py b/virt.py
index b0684d6..bbedbf6 100644
--- a/virt.py
+++ b/virt.py
@@ -64,7 +64,7 @@ class Virt:
self.virt.close()
def changed(self, conn, dom, event, detail, opaque):
- print "EVENT: Domain %s(%s) %s %s" % (dom.name(), dom.ID(), eventToString(event), detailToString(event, detail))
+ self.logger.debug("EVENT: Domain %s(%s) %s %s" % (dom.name(), dom.ID(), eventToString(event), detailToString(event, detail)))
if self.changedCallback:
l = self.listDomains()
uuid = dom.UUIDString()
@@ -100,16 +100,25 @@ def eventToString(event):
"Started",
"Suspended",
"Resumed",
- "Stopped" )
- return eventStrings[event]
+ "Stopped",
+ "Shutdown"
+ )
+ try:
+ return eventStrings[event]
+ except IndexError:
+ return "Unknown (%d)" % event
def detailToString(event, detail):
eventStrings = (
- ( "Added", "Updated" ),
- ( "Removed" ),
- ( "Booted", "Migrated", "Restored", "Snapshot" ),
- ( "Paused", "Migrated", "IOError", "Watchdog" ),
- ( "Unpaused", "Migrated"),
- ( "Shutdown", "Destroyed", "Crashed", "Migrated", "Saved", "Failed", "Snapshot")
+ ( "Added", "Updated" ), # Defined
+ ( "Removed", ), # Undefined
+ ( "Booted", "Migrated", "Restored", "Snapshot", "Wakeup" ), # Started
+ ( "Paused", "Migrated", "IOError", "Watchdog", "Restored", "Snapshot" ), # Suspended
+ ( "Unpaused", "Migrated", "Snapshot" ), # Resumed
+ ( "Shutdown", "Destroyed", "Crashed", "Migrated", "Saved", "Failed", "Snapshot" ), # Stopped
+ ( "Finished", ), # Shutdown
)
- return eventStrings[event][detail]
+ try:
+ return eventStrings[event][detail]
+ except IndexError:
+ return "Unknown (%d)" % detail
12 years
[virt-who] Reenable logging to stderr in debug mode; fork earlier to avoid closing libvirt connection; make inf
by Radek Novacek
commit f081349b752bf90d570d819d2c2b95c748856633
Author: Radek Novacek <rnovacek(a)redhat.com>
Date: Thu Apr 19 15:29:39 2012 +0200
Reenable logging to stderr in debug mode; fork earlier to avoid closing libvirt connection; make info messages from some debug messages
subscriptionmanager.py | 7 ++++---
virt-who.py | 43 ++++++++++++++++++-------------------------
2 files changed, 22 insertions(+), 28 deletions(-)
---
diff --git a/subscriptionmanager.py b/subscriptionmanager.py
index 236cbd0..cd7a8c3 100644
--- a/subscriptionmanager.py
+++ b/subscriptionmanager.py
@@ -60,7 +60,8 @@ class SubscriptionManager:
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.exception("Unable to obtain status from server, UEPConnection is likely not usable:")
+ self.logger.exception(e)
+ self.logger.error("Unable to obtain status from server, UEPConnection is likely not usable:")
def sendVirtGuests(self, domains):
""" Update consumer facts with UUIDs of virtual guests. """
@@ -71,7 +72,7 @@ class SubscriptionManager:
uuids.append(domain.UUIDString())
uuids.sort()
- self.logger.debug("Sending update to updateConsumer: %s" % uuids)
+ self.logger.info("Sending list of uuids: %s" % uuids)
# Send list of guest uuids to the server
try:
@@ -82,7 +83,7 @@ class SubscriptionManager:
def hypervisorCheckIn(self, owner, env, mapping):
""" Send hosts to guests mapping to subscription manager. """
- self.logger.debug("Sending updates in hosts-to-guests mapping: %s" % mapping)
+ self.logger.info("Sending update in hosts-to-guests mapping: %s" % mapping)
# Send the mapping
try:
diff --git a/virt-who.py b/virt-who.py
index e5e083b..70efdab 100644
--- a/virt-who.py
+++ b/virt-who.py
@@ -81,7 +81,7 @@ class VirtWho(object):
self.subscriptionManager.connect()
self.tryRegisterEventCallback()
except NoOptionError, e:
- logger.error("Error in reading configuration file (/etc/rhsm/rhsm.conf): %s" % e)
+ self.logger.error("Error in reading configuration file (/etc/rhsm/rhsm.conf): %s" % e)
# Unability to parse configuration file is fatal error, so we'll quit
sys.exit(4)
except Exception, e:
@@ -129,6 +129,7 @@ class VirtWho(object):
retry - Should be True on first run, False on second.
return - True if sending is successful, False otherwise
"""
+ logger = self.logger
try:
self.checkConnections()
if self.options.virtType == "esx":
@@ -138,10 +139,10 @@ class VirtWho(object):
logger.error("Error during update list of guests: %s", str(fail))
for updated in result['updated']:
guests = [x['guestId'] for x in updated['guestIds']]
- logger.debug("Updated host: %s with guests: [%s]", updated['uuid'], ", ".join(guests))
+ logger.info("Updated host: %s with guests: [%s]", updated['uuid'], ", ".join(guests))
for created in result['created']:
guests = [x['guestId'] for x in created['guestIds']]
- logger.debug("Created host: %s with guests: [%s]", created['uuid'], ", ".join(guests))
+ logger.info("Created host: %s with guests: [%s]", created['uuid'], ", ".join(guests))
else:
self.subscriptionManager.sendVirtGuests(self.virt.listDomains())
return True
@@ -193,20 +194,8 @@ class VirtWho(object):
return False
return self.virt.ping()
-def daemonize():
- """ Perform double-fork and close stdout and stderr file descriptors """
- # Close all file descriptors (except std*)
- try:
- fds = os.listdir("/proc/self/fd")
- except:
- fds = []
- for fd in fds:
- if int(fd) > 2:
- try:
- os.close(int(fd))
- except Exception:
- # fd wasn't open, ignore
- pass
+def daemonize(debugMode):
+ """ Perform double-fork and redirect std* to /dev/null """
# First fork
try:
@@ -239,7 +228,9 @@ def daemonize():
devnull = os.open("/dev/null", os.O_RDWR)
os.dup2(devnull, 0)
os.dup2(devnull, 1)
- os.dup2(devnull, 2)
+ # Don't redirect stderr in debug mode, we need to write debugging output there
+ if not debugMode:
+ os.dup2(devnull, 2)
# Reset file creation mask
os.umask(0)
@@ -247,7 +238,7 @@ def daemonize():
os.chdir("/")
return True
-def createPidFile():
+def createPidFile(logger):
atexit.register(cleanup)
# Write pid to pidfile
@@ -303,6 +294,8 @@ if __name__ == '__main__':
# Print debugging output to stderr too
logger.addHandler(logging.StreamHandler())
+ else:
+ logger.setLevel(logging.INFO)
env = os.getenv("VIRTWHO_BACKGROUND", "0").strip().lower()
if env in ["1", "true"]:
@@ -357,6 +350,11 @@ if __name__ == '__main__':
options.interval = DefaultInterval
if options.background:
+ # Do a double-fork and other daemon initialization
+ if not daemonize(options.debug):
+ logger.error("Unable to fork, continuing in foreground")
+
+ if options.background:
if options.virtType == "libvirt":
virEventLoopPureStart()
else:
@@ -365,12 +363,7 @@ if __name__ == '__main__':
virtWho = VirtWho(logger, options)
virtWho.checkConnections()
- if options.background:
- # Do a double-fork and other daemon initialization
- if not daemonize():
- logger.error("Unable to fork, continuing in foreground")
-
- createPidFile()
+ createPidFile(logger)
logger.debug("Virt-who is running in %s mode" % options.virtType)
12 years