Example #1
0
    def is_service_instance_valid(cls):
        """
		Check if the current service instance bound to the static class is valid
		"""
        try:
            logger.debug(
                "[Connection] Checking for current time on the service instance."
            )
            cls.svcInstance.currentTime()
            logger.debug("[Connection] Time returned properly.")
            return True
        except Exception as e:
            logger.error(
                "[Connection] I can't check the time for domain %s.  Exception below.  Returning False on valid session. Killing all the rebel scum!"
                % (cls.domain))
            logger.exception(e)
            logger.info("[Connection] Destroying bad session for domain %s" %
                        (cls.domain))
            cls._destroy_vim_service()
            return False
Example #2
0
def CreateHierarchyCollector(managedObjectReference=None, targetConfigObject=None, updateType="update", version=None, oneTime=False, addlTargetConfig=None):
	''' Primary method to create collecting inventory.  managedObjectReference is to reference a propertyCollector
	that has already been created.  You can pass the MOR value to this method, and it will create a reference
	to that existing property collector.  You do not need to specify targetEntityType when using a MOR reference.
	For all new property collectors (like the first run), you should use targetEntityType.  This will reference
	the entity out of the targetConfig class for what properties to collect.  updateType is to be used in
	conjunction with an existing MOR, "update" will allow the user to submit a version for checking differences,
	while "recycle" will destroy the property collector and then create a new property collector.
	"addlTargetConfig" will include any additional properties that need to be collected, as specified in the conf file.
	It also create filterspec and filter as well before return property collector object
	
	Returns: version, property collector object, targetConfigObject (the returned configuration target for chaining to a formatter), mor (The returned MOR to
	the created / updated property collector, version
	'''
	try:
		logger.debug("[Inventory] CollectInventory called with these options: managedObjectReference:{0}, targetConfigObject:{1}, updateType:{2}, version:{3}, oneTime:{4}, addlTargetConfig: {5}".format(managedObjectReference, targetConfigObject, updateType, version, oneTime, addlTargetConfig))

		configObject = getattr(targetConfig, targetConfigObject)
		if  addlTargetConfig:
			configObject['HostSystem'].extend(addlTargetConfig)
			logger.debug("[Inventory] CollectInventory: Addl properties added for 'HostSystem', configObject now contains:"+str(configObject))
                                            
		if managedObjectReference:
			logger.debug("[Inventory] Received an MOR.  Rebuilding old collector.")
			hierarchyCollector = PropCollector(mor=managedObjectReference)
			if updateType=="recycle":
				try:
					logger.debug("[Inventory] Old collector being recycled")
					hierarchyCollector.targetCollector.destroyPropertyCollector()
				except Exception as wf:
					if "Server raised fault:" in str(wf) and "has already been deleted or has not been completely created" in str(wf):
						logger.debug("[Inventory] Destroy Collector called with a non-existing collector, assuming deleted and creating new.")
					else:
						raise wf
				mor=None
				version=None
				hierarchyCollector = PropCollector()
				mor = str(hierarchyCollector.targetCollector.getMOR().value)
				logger.debug("[Inventory] Recycled collector MOR:{0}".format(mor))
				hierarchyCollector.buildFilterSpecList(configObject)
				hierarchyCollector.buildFilter(hierarchyCollector.fSpecList, partUpdates=True)
			if oneTime == True:
				logger.debug("[Inventory] OneTime collection is set to true with existing MOR.")
				hierarchyCollector.buildFilterSpecList(configObject)
			mor = str(hierarchyCollector.targetCollector.getMOR().value)
			return version, hierarchyCollector, targetConfigObject, mor
		else:
			logger.debug("[Inventory] Creating new collector.")
			hierarchyCollector = PropCollector()
			mor = str(hierarchyCollector.targetCollector.getMOR().value)
			logger.debug("[Inventory] New collector MOR:{0}".format(mor))
			hierarchyCollector.buildFilterSpecList(configObject)
			hierarchyCollector.buildFilter(hierarchyCollector.fSpecList, partUpdates=True)
			return version, hierarchyCollector, targetConfigObject, mor
	except Exception as e:
		logger.error("error in creating hierarchy collector")
		logger.exception(e)
		raise e
Example #3
0
    def update_connection(cls,
                          url,
                          username=None,
                          password=None,
                          session_key=None,
                          cookie=None,
                          raise_exceptions=False):
        """
		Create/update the static class Connection with the provided credentials and url.
		
		RETURNS True if successful, False if not
		"""
        if (username is None or password is None) and cookie is None:
            raise Exception(
                "Must provide either a username-password and/or a cookie for domain : %s"
                % url)
        if url.startswith("https://") or url.startswith("http://"):
            domain = url.lstrip("htps:").lstrip("/")
        else:
            domain = url

        logger.debug(
            "[Connection] Update called with url=%s username=%s password=[REDACTED] session_key=%s cookie=%s",
            url, username, session_key, cookie)

        #Create a cookie, mainly so I don't have to change unit tests
        if cookie is None and session_key is not None:
            logger.warning(
                "[Connection] null cookie passed into update connection, creating an artificial cookie based on session_key, this will break for short named urls"
            )
            cookie = cls.create_session_cookie(domain, session_key)

        #First check if there even is a service instance
        if cls.svcInstance is None:
            logger.debug(
                "[Connection] Update called with no active svcInstance, building new service instance for domain=%s",
                domain)
            return cls._create_vim_service(domain, username, password, cookie,
                                           raise_exceptions)
        else:
            logger.info("[Connection] Connection has a vimservice, testing it")
            try:
                #Check if URL has changed from the currently loaded wsdl, if so reload it
                if Connection.svcInstance.serverConnection.getUrl() != domain:
                    logger.info(
                        "[Connection] swapping connection from old_domain=%s to new_domain=%s",
                        Connection.svcInstance.serverConnection.getUrl(),
                        domain)
                    return cls._create_vim_service(
                        domain=domain,
                        username=username,
                        password=password,
                        cookie=cookie,
                        use_cache=True,
                        raise_exceptions=raise_exceptions)
                elif Connection.svcInstance.serverConnection.getUrl(
                ) == domain:
                    logger.info(
                        "[Connection] Update was called with a connection that is already in place with the same url. Validating that the current session is still valid"
                    )
                    old_session_key = cls.session_key
                    session_valid = cls.is_service_instance_valid()
                    if session_valid and cookie is None and password is None:
                        logger.info(
                            "[Connection] current_session_key=%s was valid and happy happy happy",
                            cls.session_key)
                        return True
                    elif password is not None:
                        logger.info(
                            "[Connection] Connection update called with password on an already created object. Updating with password."
                        )
                        cls._destroy_vim_service()
                        return cls._create_vim_service(
                            domain=domain,
                            username=username,
                            password=password,
                            raise_exceptions=raise_exceptions)
                    elif cookie is not None:
                        logger.info(
                            "[Connection] was passed a session key/cookie, checking if it's what I'm already using"
                        )
                        if cookie.value != old_session_key:
                            #Got a new session key, remake the connection:
                            logger.info(
                                "[Connection] was passed a different session key, making a new connection with session_key=%s",
                                cookie.value)
                            cls._destroy_vim_service()
                            return cls._create_vim_service(
                                domain=domain,
                                cookie=cookie,
                                raise_exceptions=raise_exceptions)
                        else:
                            logger.info(
                                "[Connection] urls are the same, and the session key is the same. returning current session status=%s",
                                session_valid)
                            return session_valid
            except Exception as e:
                logger.exception(
                    "[Connection] Could not update connection for domain: %s %s",
                    url, e)
                if raise_exceptions:
                    raise e
                return False