def __init__(self, hv_uri, vm_name): '''Get some basic config and connect to hypervisor''' SpokeVMPower.__init__(self, vm_name) self.hv_uri = hv_uri self.vm_name = common.validate_hostname(vm_name) self.conn = None try: self.conn = libvirt.open(self.hv_uri) msg = "Successfully connected to: " + self.hv_uri self.log.debug(msg) except libvirt.libvirtError: trace = traceback.format_exc() msg = 'Libvirt connection to URI %s failed' % self.hv_uri raise error.LibvirtError(msg, trace) except Exception: trace = traceback.format_exc() msg = 'Unknown error' raise error.SpokeError(msg, trace) finally: if self.conn == None: msg = 'Libvirt connection to URI %s failed' % self.hv_uri raise error.LibvirtError(msg) try: self.dom = self.conn.lookupByName(self.vm_name) except libvirt.libvirtError: msg = "VM %s not found." % self.vm_name raise error.NotFound(msg)
def __init__(self): """Bind to LDAP directory, return an ldap object.""" self.config = config.setup() self.log = logger.setup(__name__) self.search_scope = ldap.SCOPE_SUBTREE #(2) self.server = self.config.get('LDAP', 'server') self.port = self.config.get('LDAP', 'port', '389') self.bind_dn = self.config.get('LDAP', 'binddn') self.start_tls = self.config.get('LDAP', 'start_tls', False) self.bind_password = self.config.get('LDAP', 'bindpw') try: self.LDAP = ldap.initialize('ldap://%s:%s' % (self.server, self.port)) self.LDAP.protocol_version = 3 #ldap.VERSION3 if self.start_tls: self.LDAP.start_tls_s() self.LDAP.simple_bind_s(self.bind_dn, self.bind_password) self.log.debug('Bound to LDAP server %s:%s as %s' % (self.server, self.port, self.bind_dn)) except ldap.LDAPError: trace = traceback.format_exc() msg = 'Failed to bind to LDAP server %s:%s as %s' % \ (self.server,self.port, self.bind_dn) raise error.SpokeLDAPError(msg, trace) except Exception: trace = traceback.format_exc() msg = 'Unknown error' raise error.SpokeError(msg, trace)
def create(self, lv_name, lv_size): """Create logical volume; return True""" lv_size = str(lv_size) + self.lv_units lv_name = common.validate_hostname( lv_name) # LV names are always hostnames lv_size = common.validate_storage_format(lv_size) args = ['lvcreate', '-n', lv_name, '-L', lv_size, self.vg_name] str_args = " ".join(args) msg = "Running " + str_args self.log.debug(msg) try: result = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) except Exception: msg = 'Running command %s failed' % str_args # trace = traceback.format_exec() raise error.SpokeError(msg) data = result.communicate() stdout = data[0] stderr = data[1] msg = "Command stdout was: %s, stderr was: %s" % (stdout, stderr) self.log.debug(msg) # Errors we know about if "Volume group \"%s\" not found" % self.vg_name in stderr: msg = "volume group '%s' was not found." % self.vg_name raise error.NotFound(msg) elif "Insufficient free extents" in stderr: msg = "Not enough free space to create LV" raise error.InsufficientResource(msg) elif "Logical volume \"%s\" already exists in volume group \"%s\"" % ( lv_name, self.vg_name) in stderr: msg = "Logical volume '%s' already exists in volume group '%s'" % ( lv_name, self.vg_name) raise error.AlreadyExists(msg) # Catch unexpected errors if result.returncode != 0: msg = "Create command returned non-zero: %s stdout was: %s, stderr was: %s" % \ (result.returncode, stdout, stderr) raise error.LVMError(msg) result = self.get(lv_name) if result['exit_code'] == 0 and result['count'] == 1: result['msg'] = "Created %s:" % result['type'] return result else: msg = 'Create operation returned OK, but unable to find object' raise error.NotFound(msg) self.log.debug('Result: %s' % result) return result
def delete(self, lv_name): """Delete logical volume; return True.""" lv_name = common.validate_hostname( lv_name) # LV names are always hostnames args = ['lvremove', '-f', '%s/%s' % (self.vg_name, lv_name)] str_args = " ".join(args) msg = "Running " + str_args self.log.debug(msg) try: result = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) except Exception: msg = 'Running command %s failed' % str_args #trace = traceback.format_exec() raise error.SpokeError(msg) data = result.communicate() stdout = data[0] stderr = data[1] msg = "Command stdout was: %s, stderr was: %s" % (stdout, stderr) self.log.debug(msg) if "Volume group \"%s\" not found" % self.vg_name in stderr: msg = "volume group '%s' was not found." % self.vg_name raise error.NotFound(msg) elif "logical volume(s) not found" in stderr: msg = "logical volume '%s' not found." % lv_name raise error.NotFound(msg) # Catch non-specific errors if result.returncode != 0: msg = "Delete command returned non-zero: %s stdout was: %s, stderr was: %s" % \ (result.returncode, stdout, stderr) raise error.LVMError(msg) result = self.get(lv_name) if result['exit_code'] == 3 and result['count'] == 0: result['msg'] = "Deleted %s:" % result['type'] self.log.debug('Result: %s' % result) return result else: msg = 'Delete operation returned OK, but object still there?' raise error.SearchError(msg)
class SpokeLDAP: """Extend ldap class with convenience methods.""" def __init__(self): """Bind to LDAP directory; return an LDAP connection object.""" self.config = config.setup() self.log = logger.setup(__name__) self.LDAP = setup().LDAP def _create_object(self, dn, dn_info): """Create a new LDAP object (e.g. a dn or attribute).""" # Allowed LDAP operations operation = {'add':self.LDAP.add_s, 'mod':self.LDAP.modify_s} try: int(dn_info[0][0]) #attribute mod opertations begin with an integer. type = 'mod' attrlist = [] # Collect a list of attributes to return for item in dn_info: attrlist.append(item[1]) except: type = 'add' #if it's not a modification, it's an add operation. attrlist = None try: operation[type](dn, dn_info) except ldap.ALREADY_EXISTS: msg = 'Entry %s already exists.' % dn raise error.AlreadyExists(msg) except ldap.TYPE_OR_VALUE_EXISTS: msg = 'Attempt to add attribute to %s which already exists.' % dn raise error.AlreadyExists(msg) except ldap.CONSTRAINT_VIOLATION: msg = 'Attribute already exists and does not support multiples' raise error.AlreadyExists(msg) except ldap.NO_SUCH_OBJECT: msg = "Part of %s missing, can't create." % dn raise error.NotFound(msg) except ldap.LDAPError, e: trace = traceback.format_exc() raise error.SpokeLDAPError(e, trace) except Exception, e: trace = traceback.format_exc() msg = 'Unknown error' raise error.SpokeError(msg, trace)
if filter is None: filter = '(objectClass=*)' #if attr is not None: # attr = self.retrieve_attr try: result = self.LDAP.search_s(dn, scope, filter, attr) except ldap.NO_SUCH_OBJECT, e: self.log.debug('Get failed; part of dn %s does not exist' % dn) result = [] # treat missing branch elements as missing leaf except ldap.LDAPError, e: trace = traceback.format_exc() raise error.SpokeLDAPError(e, trace) except Exception, e: trace = traceback.format_exc() msg = 'Unknown error' raise error.SpokeError(msg, trace) if unique != False and len(result) > 1: msg = 'Multiple results found yet uniqueness requested' raise error.SearchUniqueError(msg) result = self._process_results(result, self.__module__) return result def _modify_attributes(self, dn, new_attrs, old_attrs=None): """Modify an LDAP object (e.g. a dn or attribute).""" ignore_old = 0 if old_attrs==None: old_object = self._get_object(dn, ldap.SCOPE_BASE, '(objectClass=*)', unique=True) if old_object['data'] == []: msg = '%s does not exist, cannot modify' % dn
Exceptions: SpokeError - raised when action fails for unknown reason. """ # core modules from xml.dom.minidom import Document import StringIO # own modules import spoke.lib.error as error try: import xml.etree.ElementTree as ET # needs python =>2.5 except: msg = 'Failed to import xml.etree.ElementTree, is your python => 2.5?' raise error.SpokeError(msg) def createDoc(doc_name): doc_name = Document() return doc_name def createElement(doc_name, element, attribute=None): element = doc_name.createElement(element) if (attribute is not None): for key in attribute: value = attribute[key] element.setAttribute(key, value) doc_name.appendChild(element) return element