commit 2ab883cee8b0187f6c12145f6f28a112e1b903e8
Author: Radek Novacek <rnovacek(a)redhat.com>
Date: Mon Jul 16 15:59:37 2012 +0200
Simplify exceptions
Since virt-who can reload configuration now, most of the errors are not
fatal. Therefore exception can be simplified.
subscriptionmanager.py | 28 ++-------------
virt-who.py | 89 ++++++++++++++++++++++++++---------------------
virt.py | 5 ++-
3 files changed, 57 insertions(+), 65 deletions(-)
---
diff --git a/subscriptionmanager.py b/subscriptionmanager.py
index 4050655..2ffd8ce 100644
--- a/subscriptionmanager.py
+++ b/subscriptionmanager.py
@@ -26,17 +26,6 @@ import rhsm.certificate as rhsm_certificate
import rhsm.config as rhsm_config
class SubscriptionManagerError(Exception):
- def __init__(self):
- pass
-
-class SubscriptionManagerCertError(SubscriptionManagerError):
- def __init__(self, message):
- self.message = message
-
- def __str__(self):
- return self.message
-
-class SubscriptionManagerConnectionError(SubscriptionManagerError):
def __init__(self, message):
self.message = message
@@ -64,7 +53,7 @@ class SubscriptionManager:
self.cert_file = os.path.join(consumerCertDir, cert)
self.key_file = os.path.join(consumerCertDir, key)
if not os.access(self.cert_file, os.R_OK):
- raise SubscriptionManagerCertError("Unable to read certificate, system
is not registered or you are not root")
+ raise SubscriptionManagerError("Unable to read certificate, system is
not registered or you are not root")
def connect(self, Connection=rhsm_connection.UEPConnection):
""" Connect to the subscription-manager. """
@@ -92,11 +81,7 @@ class SubscriptionManager:
self.logger.debug("Sending list of uuids: %s" % uuids)
# Send list of guest uuids to the server
- try:
- self.connection.updateConsumer(self.uuid(), guest_uuids=uuids)
- except Exception, e:
- self.logger.exception("Updating consumer failed:")
- raise SubscriptionManagerError()
+ self.connection.updateConsumer(self.uuid(), guest_uuids=uuids)
def hypervisorCheckIn(self, owner, env, mapping):
""" Send hosts to guests mapping to subscription manager.
"""
@@ -104,11 +89,7 @@ class SubscriptionManager:
self.logger.debug("Sending update in hosts-to-guests mapping: %s" %
mapping)
# Send the mapping
- try:
- return self.connection.hypervisorCheckIn(owner, env, mapping)
- except Exception, e:
- self.logger.exception("Hypervisor check-in failed:")
- raise SubscriptionManagerError()
+ return self.connection.hypervisorCheckIn(owner, env, mapping)
def uuid(self):
""" Read consumer certificate and get consumer UUID from it.
"""
@@ -116,8 +97,7 @@ class SubscriptionManager:
try:
f = open(self.cert_file, "r")
except Exception, e:
- self.logger.exception("Unable to open certificate (%s):" %
self.cert_file)
- raise SubscriptionManagerError()
+ raise SubscriptionManagerError("Unable to open certificate %s
(%s):" % self.cert_file, str(e))
certificate = rhsm_certificate.Certificate(f.read())
f.close()
self.cert_uuid = certificate.subject().get('CN')
diff --git a/virt-who.py b/virt-who.py
index 3ae6e37..b1f7908 100644
--- a/virt-who.py
+++ b/virt-who.py
@@ -28,7 +28,7 @@ from virt import Virt, VirtError
from vdsm import VDSM
from vsphere import VSphere
from event import virEventLoopPureStart
-from subscriptionmanager import SubscriptionManager, SubscriptionManagerError,
SubscriptionManagerCertError
+from subscriptionmanager import SubscriptionManager, SubscriptionManagerError
import logging
import log
@@ -107,13 +107,11 @@ class VirtWho(object):
self.subscriptionManager = SubscriptionManager(self.logger)
self.subscriptionManager.connect()
except NoOptionError, e:
- self.logger.error("Error in reading configuration file
(/etc/rhsm/rhsm.conf)")
- # Unability to parse configuration file is fatal error, so we'll quit
- sys.exit(4)
- except SubscriptionManagerCertError, e:
- self.logger.error(e.message)
- # virt-who can't work properly without certificate, exitting
- sys.exit(5)
+ self.logger.exception("Error in reading configuration file
(/etc/rhsm/rhsm.conf):")
+ return
+ except SubscriptionManagerError, e:
+ self.logger.exception("Unable to obtain status from server,
UEPConnection is likely not usable:")
+ return
if self.options.virtType == "libvirt":
self.tryRegisterEventCallback()
@@ -161,57 +159,58 @@ class VirtWho(object):
logger = self.logger
try:
self.checkConnections()
- if self.options.virtType == "esx":
- result =
self.subscriptionManager.hypervisorCheckIn(self.options.esx_owner, self.options.esx_env,
self.virt.getHostGuestMapping())
- # Show the result of hypervisorCheckIn
- for fail in result['failedUpdate']:
- 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.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.info("Created host: %s with guests: [%s]",
created['uuid'], ", ".join(guests))
- else:
- self.subscriptionManager.sendVirtGuests(self.virt.listDomains())
- return True
- except SystemExit,e:
- # In python2.4 SystemExit is inherited from Exception, so must be catched
extra
- raise e
- except VirtError, e:
- # Communication with virtualization supervisor failed
- logger.exception(e)
- self.virt = None
- # Retry once
+ except Exception,e:
if retry:
- logger.error("Error in communication with virt backend, trying to
recover")
+ logger.exception("Unable to create connection:")
return self._send(False)
else:
logger.error(self.unableToRecoverStr)
return False
- except SubscriptionManagerError, e:
- # Communication with subscription manager failed
- self.subscriptionManager = None
+
+ try:
+ if self.options.virtType != "esx":
+ virtualGuests = self.virt.listDomains()
+ else:
+ virtualGuests = self.virt.getHostGuestMapping()
+ except Exception, e:
+ # Communication with virtualization supervisor failed
+ self.virt = None
# Retry once
if retry:
- logger.error("Error in communication with candlepin, trying to
recover")
+ logger.exception("Error in communication with virt backend, trying
to recover:")
return self._send(False)
else:
logger.error(self.unableToRecoverStr)
return False
+
+ try:
+ if self.options.virtType != "esx":
+ self.subscriptionManager.sendVirtGuests(virtualGuests)
+ else:
+ result =
self.subscriptionManager.hypervisorCheckIn(self.options.esx_owner, self.options.esx_env,
virtualGuests)
+
+ # Show the result of hypervisorCheckIn
+ for fail in result['failedUpdate']:
+ 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.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.info("Created host: %s with guests: [%s]",
created['uuid'], ", ".join(guests))
except Exception, e:
- # Some other error happens
- logger.exception(e)
- self.virt = None
+ # Communication with subscription manager failed
self.subscriptionManager = None
# Retry once
if retry:
- logger.error("Unexcepted error occurs, trying to recover")
+ logger.exception("Error in communication with subscription manager,
trying to recover:")
return self._send(False)
else:
logger.error(self.unableToRecoverStr)
return False
+ return True
+
def ping(self):
"""
Test if connection to virtualization manager is alive.
@@ -304,7 +303,7 @@ def cleanup(sig=None, stack=None):
if sig is not None and sig in [signal.SIGINT, signal.SIGTERM, signal.SIGKILL]:
sys.exit(0)
-if __name__ == '__main__':
+def main():
if os.access(PIDFILE, os.F_OK):
print >>sys.stderr, "virt-who seems to be already running. If not,
remove %s" % PIDFILE
sys.exit(1)
@@ -459,3 +458,13 @@ if __name__ == '__main__':
else:
# If last send fails, new try will be sooner
time.sleep(RetryInterval)
+
+if __name__ == '__main__':
+ try:
+ main()
+ except SystemExit:
+ raise
+ except Exception, e:
+ logger = log.getLogger(False, False)
+ logger.exception("Fatal error:")
+ sys.exit(1)
diff --git a/virt.py b/virt.py
index 75d8019..4cb4b5e 100644
--- a/virt.py
+++ b/virt.py
@@ -86,7 +86,10 @@ class Virt:
break
if not hasDomain:
l.append(dom)
- self.changedCallback(l)
+ try:
+ self.changedCallback(l)
+ except Exception, e:
+ self.logger.exception("Updating consumer failed:")
def domainEventRegisterCallback(self, callback):
self.changedCallback = callback