def init_db(self): """ Initializes the vConnector Database backend """ logging.info('Initializing vConnector database at %s', self.db) self.cursor = self.conn.cursor() sql = """ CREATE TABLE hosts ( host TEXT UNIQUE, user TEXT, pwd TEXT, enabled INTEGER ) """ try: self.cursor.execute(sql) except sqlite3.OperationalError as e: raise VConnectorException('Cannot initialize database: {}'.format( e.message)) self.conn.commit() self.cursor.close()
def get_object_by_property(self, property_name, property_value, obj_type): """ Find a Managed Object by a propery If cache is enabled then we search for the managed object from the cache first and if present we return the object from cache. Args: property_name (str): Name of the property to look for property_value (str): Value of the property to match obj_type (pyVmomi.vim.*): Type of the Managed Object Returns: The first matching object """ if not issubclass(obj_type, pyVmomi.vim.ManagedEntity): raise VConnectorException('Type should be a subclass of vim.ManagedEntity') if self.cache_enabled: cached_obj_name = '{}:{}'.format(obj_type.__name__, property_value) if cached_obj_name in self.cache: logging.debug('Using cached object %s', cached_obj_name) return self.cache.get(cached_obj_name) view_ref = self.get_container_view(obj_type=[obj_type]) props = self.collect_properties( view_ref=view_ref, obj_type=obj_type, path_set=[property_name], include_mors=True ) view_ref.DestroyView() obj = None for each_obj in props: if each_obj[property_name] == property_value: obj = each_obj['obj'] break if self.cache_enabled: cached_obj = CachedObject( name=cached_obj_name, obj=obj, ttl=self.cache_ttl ) self.cache.add(obj=cached_obj) return obj