コード例 #1
0
ファイル: sshClient.py プロジェクト: slavkap/cloudstack
 def runCommand(self, command):
     '''
     @Name: runCommand
     @Desc: Runs a command over ssh and
            returns the result along with status code
     @Input: command to execute
     @Output: 1: status of command executed.
              SUCCESS : If command execution is successful
              FAILED    : If command execution has failed
              2: stdin,stdout,stderr values of command output
     '''
     ret = {"status": FAILED, "stdin": None, "stdout": None,
            "stderr": INVALID_INPUT}
     if command is None or command == '':
         return ret
     try:
         status_check = 1
         stdin, stdout, stderr = self.ssh.\
             exec_command(command, timeout=self.timeout)
         if stdout is not None:
             status_check = stdout.channel.recv_exit_status()
             if status_check == 0:
                 ret["status"] = SUCCESS
             ret["stdout"] = stdout.readlines()
             if stderr is not None:
                 ret["stderr"] = stderr.readlines()
     except Exception as e:
         ret["stderr"] = GetDetailExceptionInfo(e)
         self.logger.exception("SshClient: Exception under runCommand :%s" %
                               GetDetailExceptionInfo(e))
     finally:
         self.logger.debug(" Host: %s Cmd: %s Output:%s" %
                           (self.host, command, str(ret)))
         return ret
コード例 #2
0
 def removeDataCenter(self):
     '''
     @Name : removeDataCenter
     @Desc : Removes the Data Center provided by Configuration
             If Input dc file configuration is None, uses the cfg provided
             else uses the dc file to get the configuration
     '''
     try:
         self.__setClient()
         self.__tcRunLogger.debug("====DeployDC: CleanUp Started====")
         print "\n====DeployDC: CleanUp Started===="
         ret = FAILED
         if self.__dcCfgFile:
             file_to_read = open(self.__dcCfgFile, 'r')
             if file_to_read:
                 self.__dcCfg = pickle.load(file_to_read)
         if self.__dcCfg:
             ret = self.__cleanEntries()
     except Exception as e:
         print "\n==== Exception Under removeDataCenter: %s ====" % \
               GetDetailExceptionInfo(e)
         self.__tcRunLogger.exception(
             "===DeployDC CleanUp FAILED: %s ====" %
             GetDetailExceptionInfo(e))
     finally:
         return ret
コード例 #3
0
ファイル: utils.py プロジェクト: woduxi/cloudstack
def checkVolumeSize(ssh_handle=None,
                    volume_name="/dev/sda",
                    cmd_inp="/sbin/fdisk -l | grep Disk",
                    size_to_verify=0):
    '''
    @Name : getDiskUsage
    @Desc : provides facility to verify the volume size against the size to verify
    @Input: 1. ssh_handle : machine against which to execute the disk size cmd
            2. volume_name : The name of the volume against which to verify the size
            3. cmd_inp : Input command used to veify the size
            4. size_to_verify: size against which to compare.
    @Output: Returns FAILED in case of an issue, else SUCCESS
    '''
    try:
        if ssh_handle is None or cmd_inp is None or volume_name is None:
            return INVALID_INPUT

        cmd = cmd_inp
        '''
        Retrieve the cmd output
        '''
        if system().lower() != "windows":
            fdisk_output = ssh_handle.runCommand(cmd_inp)
            if fdisk_output["status"] != SUCCESS:
                return FAILED
            for line in fdisk_output["stdout"]:
                if volume_name in line:
                    parts = line.strip().split()
                    if str(parts[-2]) == str(size_to_verify):
                        return [SUCCESS,str(parts[-2])]
            return [FAILED,"Volume Not Found"]
    except Exception, e:
        print "\n Exception Occurred under getDiskUsage: " \
              "%s" %GetDetailExceptionInfo(e)
        return [FAILED,GetDetailExceptionInfo(e)]
コード例 #4
0
ファイル: sshClient.py プロジェクト: slavkap/cloudstack
 def createConnection(self):
     '''
     @Name: createConnection
     @Desc: Creates an ssh connection for
            retries mentioned,along with sleep mentioned
     @Output: SUCCESS on successful connection
              FAILED If connection through ssh failed
     '''
     ret = FAILED
     except_msg = ''
     while self.retryCnt >= 0:
         try:
             self.logger.debug("====Trying SSH Connection: Host:%s User:%s\
                                Port:%s RetryCnt:%s===" %
                               (self.host, self.user, str(self.port),
                                str(self.retryCnt)))
             if self.keyPairFiles is None:
                 self.ssh.connect(hostname=self.host,
                                  port=self.port,
                                  username=self.user,
                                  password=self.passwd,
                                  timeout=self.timeout,
                                  allow_agent=False)
             else:
                 self.ssh.connect(hostname=self.host,
                                  port=self.port,
                                  username=self.user,
                                  password=self.passwd,
                                  key_filename=self.keyPairFiles,
                                  timeout=self.timeout,
                                  look_for_keys=False
                                  )
             self.logger.debug("===SSH to Host %s port : %s SUCCESSFUL==="
                               % (str(self.host), str(self.port)))
             ret = SUCCESS
             break
         except BadHostKeyException as e:
             except_msg = GetDetailExceptionInfo(e)
         except AuthenticationException as e:
             except_msg = GetDetailExceptionInfo(e)
         except SSHException as e:
             except_msg = GetDetailExceptionInfo(e)
         except socket.error as e:
             except_msg = GetDetailExceptionInfo(e)
         except Exception as e:
             except_msg = GetDetailExceptionInfo(e)
         finally:
             if self.retryCnt == 0 or ret == SUCCESS:
                 break
             if except_msg != '':
                 self.logger.\
                     exception("SshClient: Exception under "
                               "createConnection: %s" % except_msg)
             self.retryCnt -= 1
             time.sleep(self.delay)
     return ret
コード例 #5
0
 def __setHypervisorAndZoneInfo(self):
     '''
     @Name : __setHypervisorAndZoneInfo
     @Desc:  Set the HyperVisor and Zone details;
             default to XenServer
     '''
     try:
         if not self.__hypervisorType:
             if self.__parsedConfig and self.__parsedConfig.zones is not None:
                 for zone in self.__parsedConfig.zones:
                     for pod in zone.pods:
                         if pod is not None:
                             for cluster in pod.clusters:
                                 if cluster is not None and cluster.hypervisor is not None:
                                     self.__hypervisorType = cluster.hypervisor
                                     break
         if not self.__zoneForTests:
             if self.__parsedConfig and self.__parsedConfig.zones is not None:
                 for zone in self.__parsedConfig.zones:
                     self.__zoneForTests = zone.name
                     break
         if not self.__hypervisorType:
             self.__hypervisorType = XEN_SERVER
         return SUCCESS
     except Exception as e:
         print "\n Exception Occurred Under init " \
               "%s" % GetDetailExceptionInfo(e)
         return FAILED
コード例 #6
0
 def init(self):
     '''
     @Name : init
     @Desc :Initializes the marvin by
            1. Parsing the configuration and creating a parsed config
               structure
            2. Creates a timestamped log folder and provides all logs
               to be dumped there
            3. Creates the DataCenter based upon configuration provided
     @Output : SUCCESS or FAILED
     '''
     try:
         print "\n==== Marvin Init Started ===="
         if ((self.__parseConfig() != FAILED)
                 and (self.__setHypervisorAndZoneInfo())
                 and (self.__setTestDataPath() != FAILED)
                 and (self.__initLogging() != FAILED)
                 and (self.__createTestClient() != FAILED)
                 and (self.__deployDC() != FAILED)):
             print "\n==== Marvin Init Successful ===="
             return SUCCESS
         print "\n==== Marvin Init Failed ===="
         return FAILED
     except Exception as e:
         print "\n Exception Occurred Under init " \
               "%s" % GetDetailExceptionInfo(e)
         return FAILED
コード例 #7
0
    def __parseAndGetResponse(self, cmd_response, response_cls, is_async):
        '''
        @Name : __parseAndGetResponse
        @Desc : Verifies the  Response(from CS) and returns an
                appropriate json parsed Response
        @Input: cmd_response: Command Response from cs
                response_cls : Mapping class for this Response
                is_async: Whether the cmd is async or not.
        @Output:Response output from CS
        '''
        try:
            try:
                ret = jsonHelper.getResultObj(
                    cmd_response.json(),
                    response_cls)
            except TypeError:
                ret = jsonHelper.getResultObj(cmd_response.json, response_cls)

            '''
            If the response is asynchronous, poll and return response
            else return response as it is
            '''
            if is_async == "false":
                self.logger.debug("Response : %s" % str(ret))
                return ret
            else:
                response = self.__poll(ret.jobid, response_cls)
                self.logger.debug("Response : %s" % str(response))
                return response.jobresult if response != FAILED else FAILED
        except Exception as e:
            self.__lastError = e
            self.logger.\
                exception("Exception:%s" % GetDetailExceptionInfo(e))
            return FAILED
コード例 #8
0
 def __initLogging(self):
     '''
     @Name : __initLogging
     @Desc : 1. Initializes the logging for marvin and so provides
                 various log features for automation run.
                 2. Initializes all logs to be available under
                 given Folder Path,where all test run logs
                 are available for a given run.
                 3. All logging like exception log,results, run info etc
                  for a given test run are available under a given
                  timestamped folder
     @Output : SUCCESS or FAILED
     '''
     try:
         log_obj = MarvinLog("CSLog")
         if log_obj:
             ret = log_obj.\
                 createLogs(self.__testModName,
                            self.__parsedConfig.logger,
                            self.__userLogFolderPath)
             if ret != FAILED:
                 self.__logFolderPath = log_obj.getLogFolderPath()
                 self.__tcRunLogger = log_obj.getLogger()
                 print "\n=== Marvin Init Logging Successful==="
                 return SUCCESS
         return FAILED
     except Exception as e:
         print "\n Exception Occurred Under __initLogging " \
               ":%s" % GetDetailExceptionInfo(e)
         return FAILED
コード例 #9
0
 def createZone(self, zone, rec=0):
     try:
         zoneresponse = self.__apiClient.createZone(zone)
         if zoneresponse.id:
             self.__addToCleanUp("Zone", zoneresponse.id)
             self.__tcRunLogger.\
                 debug("Zone Name : %s Id : %s Created Successfully" %
                       (str(zone.name), str(zoneresponse.id)))
             return zoneresponse.id
         else:
             self.__tcRunLogger.\
                 exception("====Zone : %s Creation Failed=====" %
                           str(zone.name))
             print "\n====Zone : %s Creation Failed=====" % str(zone.name)
             if not rec:
                 zone.name = zone.name + "_" + random_gen()
                 self.__tcRunLogger.\
                     debug("====Recreating Zone With New Name : "
                           "%s" % zone.name)
                 print "\n====Recreating Zone With New Name ====", \
                     str(zone.name)
                 return self.createZone(zone, 1)
     except Exception as e:
         print "\nException Occurred under createZone : %s" % \
               GetDetailExceptionInfo(e)
         self.__tcRunLogger.exception("====Create Zone Failed ===")
         return FAILED
コード例 #10
0
    def __setLogHandler(self,
                        log_file_path,
                        log_format=None,
                        log_level=logging.DEBUG):
        '''
        @Name : __setLogHandler
        @Desc: Adds the given Log handler to the current logger
        @Input: log_file_path: Log File Path as where to store the logs
               log_format : Format of log messages to be dumped
               log_level : Determines the level of logging for this logger
        @Output: SUCCESS if no issues else FAILED
        '''
        try:
            if log_file_path is not None:
                stream = logging.FileHandler(log_file_path)
            else:
                stream = logging.StreamHandler(stream=sys.stdout)

            if log_format is not None:
                stream.setFormatter(log_format)
            else:
                stream.setFormatter(self.__class__.logFormat)
            stream.setLevel(log_level)
            self.__logger.addHandler(stream)
            return SUCCESS
        except Exception as e:
            print("\nException Occurred Under " \
                  "__setLogHandler %s" % GetDetailExceptionInfo(e))
            return FAILED
コード例 #11
0
    def createNetworks(self, networks, zoneId):
        try:
            if networks is None:
                return
            for network in networks:
                networkcmd = createNetwork.createNetworkCmd()
                networkcmd.displaytext = network.displaytext
                networkcmd.name = network.name
                networkcmd.networkofferingid = network.networkofferingid
                networkcmd.zoneid = zoneId

                ipranges = network.ipranges
                if ipranges:
                    iprange = ipranges.pop()
                    networkcmd.startip = iprange.startip
                    networkcmd.endip = iprange.endip
                    networkcmd.gateway = iprange.gateway
                    networkcmd.netmask = iprange.netmask
                networkcmdresponse = self.__apiClient.createNetwork(networkcmd)
                if networkcmdresponse.id:
                    networkId = networkcmdresponse.id
                    self.__tcRunLogger.\
                        debug("Creating Network Name : %s Id : %s Successful"
                              % (str(network.name), str(networkId)))
                    self.__addToCleanUp("Network", networkId)
                    return networkId
        except Exception as e:
            print "Exception Occurred %s" % GetDetailExceptionInfo(e)
            self.__tcRunLogger.\
                exception("====Network : %s "
                          "Creation Failed=====" % str(network.name))
            self.__cleanAndExit()
コード例 #12
0
    def createCacheStorages(self, cacheStorages, zoneId):
        try:
            if cacheStorages is None:
                return
            for cache in cacheStorages:
                cachecmd = createSecondaryStagingStore.\
                    createSecondaryStagingStoreCmd()
                cachecmd.url = cache.url
                cachecmd.provider = cache.provider
                cachecmd.zoneid = zoneId
                cachecmd.details = []

                if cache.details:
                    for key, value in vars(cache.details).iteritems():
                        cachecmd.details.append({'key': key, 'value': value})
                ret = self.__apiClient.createSecondaryStagingStore(cachecmd)
                if ret.id:
                    self.__tcRunLogger.debug(
                        "===Creating Secondary StagingStore Successful===")
                    self.__addToCleanUp("SecondaryStagingStore", ret.id)
        except Exception as e:
            print "Exception Occurred: %s" % GetDetailExceptionInfo(e)
            self.__tcRunLogger.\
                exception("=== Creating "
                          "SecondaryStagingStorage Failed===")
            self.__cleanAndExit()
コード例 #13
0
    def createSecondaryStorages(self, secondaryStorages, zoneId):
        try:
            if secondaryStorages is None:
                return
            for secondary in secondaryStorages:
                secondarycmd = addImageStore.addImageStoreCmd()
                secondarycmd.url = secondary.url
                secondarycmd.provider = secondary.provider
                secondarycmd.details = []

                if secondarycmd.provider == 'S3' \
                        or secondarycmd.provider == "Swift":
                    for key, value in vars(secondary.details).iteritems():
                        secondarycmd.details.append({
                            'key': key,
                            'value': value
                        })
                if secondarycmd.provider == "NFS":
                    secondarycmd.zoneid = zoneId
                ret = self.__apiClient.addImageStore(secondarycmd)
                if ret.id:
                    self.__tcRunLogger.debug(
                        "===Add Image Store Successful===")
                    self.__addToCleanUp("ImageStore", ret.id)
        except Exception as e:
            print "Exception Occurred: %s" % GetDetailExceptionInfo(e)
            self.__tcRunLogger.\
                exception("=== Add Image Store Failed===")
            self.__cleanAndExit()
コード例 #14
0
 def createPods(self, pods, zoneId, networkId=None):
     try:
         if pods is None:
             return
         for pod in pods:
             createpod = createPod.createPodCmd()
             createpod.name = pod.name
             createpod.gateway = pod.gateway
             createpod.netmask = pod.netmask
             createpod.startip = pod.startip
             createpod.endip = pod.endip
             createpod.zoneid = zoneId
             createpodResponse = self.__apiClient.createPod(createpod)
             if createpodResponse.id:
                 podId = createpodResponse.id
                 self.__tcRunLogger.debug("Pod Name : %s Id : %s "
                                          "Created Successfully" %
                                          (str(pod.name), str(podId)))
                 self.__addToCleanUp("Pod", podId)
             if pod.guestIpRanges is not None and networkId is not None:
                 self.createVlanIpRanges("Basic", pod.guestIpRanges, zoneId,
                                         podId, networkId)
             self.createClusters(pod.clusters,
                                 zoneId,
                                 podId,
                                 vmwareDc=pod.vmwaredc)
     except Exception as e:
         print "Exception Occurred: %s" % GetDetailExceptionInfo(e)
         self.__tcRunLogger.\
             exception("====Pod: %s Creation "
                       "Failed=====" % str(pod.name))
         self.__cleanAndExit()
コード例 #15
0
 def addHosts(self, hosts, zoneId, podId, clusterId, hypervisor):
     try:
         if hosts is None:
             return
         for host in hosts:
             hostcmd = addHost.addHostCmd()
             hostcmd.clusterid = clusterId
             hostcmd.cpunumber = host.cpunumer
             hostcmd.cpuspeed = host.cpuspeed
             hostcmd.hostmac = host.hostmac
             hostcmd.hosttags = host.hosttags
             hostcmd.hypervisor = host.hypervisor
             hostcmd.memory = host.memory
             hostcmd.password = host.password
             hostcmd.podid = podId
             hostcmd.url = host.url
             hostcmd.username = host.username
             hostcmd.zoneid = zoneId
             hostcmd.hypervisor = hypervisor
             ret = self.__apiClient.addHost(hostcmd)
             if ret:
                 self.__tcRunLogger.debug("=== Add Host Successful ===")
                 self.__addToCleanUp("Host", ret[0].id)
     except Exception as e:
         print "Exception Occurred %s" % GetDetailExceptionInfo(e)
         self.__tcRunLogger.exception("=== Adding Host Failed ===")
         self.__cleanAndExit()
コード例 #16
0
 def __parseConfig(self):
     '''
     @Name : __parseConfig
     @Description: Parses the Input configuration Json file
               and returns a dictionary from the file.
     @Input      : NA
     @Output     : Returns the parsed dictionary from json file
                   Returns None for invalid input or if parsing failed
     '''
     config_dict = None
     try:
         if self.__filePath.endswith(".py"):
             config_dict = test_data
         else:
             configLines = []
             with open(file, 'r') as fp:
                 for line in fp:
                     ws = line.strip()
                     if not ws.startswith("#"):
                         configLines.append(ws)
             config = json.loads("\n".join(configLines))
             config_dict = config
     except Exception as e:
         # Will replace with log once we have logging done
         print "\n Exception occurred under ConfigManager:__parseConfig" \
               " :%s", GetDetailExceptionInfo(e)
     finally:
         return config_dict
コード例 #17
0
    def __getKeys(self, userid):
        '''
        @Name : ___getKeys
        @Desc : Retrieves the API and Secret Key for the provided Userid
        @Input: userid: Userid to register
        @Output: FAILED or tuple with apikey and secretkey
        '''
        try:
            register_user = registerUserKeys.registerUserKeysCmd()
            register_user.id = userid
            register_user_res = \
                self.__apiClient.registerUserKeys(register_user)
            if not register_user_res:
                return FAILED

            getuser_keys = getUserKeys.getUserKeysCmd()
            getuser_keys.id = userid
            getuser_keys_res = self.__apiClient.getUserKeys(getuser_keys)
            if getuser_keys_res is None :
                self.__logger.error("__createApiClient: API "
                                "Client Creation Failed")
                return FAILED

            api_key = getuser_keys_res.apikey
            security_key = getuser_keys_res.secretkey
            return (api_key, security_key)
        except Exception as e:
            self.__logger.exception("Exception Occurred Under __geKeys : "
                                    "%s" % GetDetailExceptionInfo(e))
            return FAILED
コード例 #18
0
 def deploy(self):
     try:
         print "\n==== Deploy DC Started ===="
         self.__tcRunLogger.debug("\n==== Deploy DC Started ====")
         '''
         Step1 : Set the Client
         '''
         self.setClient()
         '''
         Step2: Update the Configuration
         '''
         self.updateConfiguration(self.__config.globalConfig)
         '''
         Step3 :Deploy the Zone
         '''
         self.createZones(self.__config.zones)
         self.configureS3(self.__config.s3)
         '''
         Persist the Configuration to an external file post DC creation
         '''
         self.__persistDcConfig()
         print "\n====Deploy DC Successful====="
         self.__tcRunLogger.debug("\n====Deploy DC Successful====")
         return SUCCESS
     except Exception as e:
         print "\nException Occurred Under deploy :%s" % \
               GetDetailExceptionInfo(e)
         self.__tcRunLogger.debug("\n====Deploy DC Failed====")
         print "\n====Deploy DC Failed===="
         self.__cleanAndExit()
         return FAILED
コード例 #19
0
ファイル: marvinPlugin.py プロジェクト: terod/cloudstack
 def startMarvin(self):
     '''
     @Name : startMarvin
     @Desc : Initializes the Marvin
             creates the test Client
             creates the runlogger for logging
             Parses the config and creates a parsedconfig
             Creates a debugstream for tc debug log
     '''
     try:
         obj_marvininit = MarvinInit(self.__configFile, self.__deployDcFlag,
                                     None, self.__zoneForTests,
                                     self.__hypervisorType,
                                     self.__userLogPath)
         if obj_marvininit and obj_marvininit.init() == SUCCESS:
             self.__testClient = obj_marvininit.getTestClient()
             self.__tcRunLogger = obj_marvininit.getLogger()
             self.__parsedConfig = obj_marvininit.getParsedConfig()
             self.__resultStream = obj_marvininit.getResultFile()
             self.__logFolderPath = obj_marvininit.getLogFolderPath()
             self.__testRunner = nose.core.\
                 TextTestRunner(stream=self.__resultStream,
                                descriptions=True,
                                verbosity=2,
                                config=self.conf)
             return SUCCESS
         return FAILED
     except Exception as e:
         print "Exception Occurred under startMarvin: %s" % \
               GetDetailExceptionInfo(e)
         return FAILED
コード例 #20
0
    def __createApiClient(self):
        try:
            '''
            Step1 : Create a CS Connection Object
            '''
            mgmt_details = self.__mgmtDetails
            self.__csConnection = CSConnection(mgmt_details,
                                               self.__asyncTimeOut,
                                               self.__logger)

            '''
            Step2 : Create API Client with earlier created connection object
            '''
            self.__apiClient = CloudStackAPIClient(self.__csConnection)

            '''
            Step3:  If API Key is not provided as part of Management Details,
                    then verify and register
            '''
            if mgmt_details.apiKey is None:
                list_user = listUsers.listUsersCmd()
                list_user.account = "admin"
                list_user_res = self.__apiClient.listUsers(list_user)
                if list_user_res is None or\
                        (validateList(list_user_res)[0] != PASS):
                    self.__logger.error("__createApiClient: API "
                                        "Client Creation Failed")
                    return FAILED
                user_id = list_user_res[0].id
                api_key = list_user_res[0].apikey
                security_key = list_user_res[0].secretkey
                if api_key is None:
                    ret = self.__getKeys(user_id)
                    if ret != FAILED:
                        mgmt_details.apiKey = ret[0]
                        mgmt_details.securityKey = ret[1]
                    else:
                        self.__logger.error("__createApiClient: API Client "
                                            "Creation Failed while "
                                            "Registering User")
                        return FAILED
                else:
                    mgmt_details.port = 8080
                    mgmt_details.apiKey = api_key
                    mgmt_details.securityKey = security_key
                '''
                Now Create the Connection objects and Api Client using
                new details
                '''
                self.__csConnection = CSConnection(mgmt_details,
                                                   self.__asyncTimeOut,
                                                   self.__logger)
                self.__apiClient = CloudStackAPIClient(self.__csConnection)
            return SUCCESS
        except Exception as e:
            self.__logger.exception(" Exception Occurred Under "
                                    "__createApiClient: %s" %
                                    GetDetailExceptionInfo(e))
            return FAILED
コード例 #21
0
    def createTestClient(self):
        '''
        @Name : createTestClient
        @Desc : Creates the Test Client.
                The test Client is used by test suites
                Here we create ParsedTestData Config.
                Creates a DB Connection.
                Creates an API Client
        @Output : FAILED In case of an issue\Failure
                  SUCCESS in case of Success of this function
        '''
        try:
            '''
            1. Create Config Object
               Provides the Configuration Object to test suites through
               getConfigParser. The purpose of this config object is to
               parse the default config and provide dictionary of the
               config so users can use that configuration.
               Users can later call getConfig on this object and it will
               return the default parsed config dictionary from default
               configuration file. They can overwrite it with
               providing their own configuration file as well.
            '''
            '''
            1. Check Config,Zone,Hypervisor Information
            '''
            self.__configObj = ConfigManager(self.__testDataFilePath)

            if not self.__configObj or not self.__hypervisor:
                self.__logger.error("createTestClient : "
                                    "Either Hypervisor is None or "
                                    "Not able to create "
                                    "ConfigManager Object")
                return FAILED

            self.__parsedTestDataConfig = self.__configObj.getConfig()
            self.__logger.debug("Parsing Test data successful")

            '''
            2. Create DB Connection
            '''
            self.__createDbConnection()
            '''
            3. Creates API Client
            '''
            ret = self.__createApiClient()
            if ret == FAILED:
                self.__logger.\
                    error("==== Test Client Creation Failed ====")
            else:
                self.__logger.\
                    debug("==== Test Client Creation Successful ====")
            return ret
        except Exception as e:
            self.__logger.exception("Exception Occurred "
                                    "Under createTestClient "
                                    ": %s" % GetDetailExceptionInfo(e))
            return FAILED
コード例 #22
0
ファイル: marvinLog.py プロジェクト: chiradeep/cloudstack-1
    def createLogs(self,
                   test_module_name=None,
                   log_cfg=None,
                   user_provided_logpath=None):
        '''
        @Name : createLogs
        @Desc : Gets the Logger with file paths initialized and created
        @Inputs :test_module_name: Test Module Name to use for logs while
                 creating log folder path
                 log_cfg: Log Configuration provided inside of
                 Configuration
                 user_provided_logpath:LogPath provided by user
                                       If user provided log path
                                       is available, then one in cfg
                                       will  not be picked up.
        @Output : SUCCESS\FAILED
        '''
        try:
            temp_ts = time.strftime("%b_%d_%Y_%H_%M_%S", time.localtime())
            if test_module_name is None:
                temp_path = temp_ts + "_" + random_gen()
            else:
                temp_path = str(test_module_name) + \
                    "__" + str(temp_ts) + "_" + random_gen()

            if user_provided_logpath:
                temp_dir = user_provided_logpath
            elif ((log_cfg is not None)
                  and ('LogFolderPath' in log_cfg.__dict__.keys())
                  and (log_cfg.__dict__.get('LogFolderPath') is not None)):
                temp_dir = \
                    log_cfg.__dict__.get('LogFolderPath') + "/MarvinLogs"

            self.__logFolderDir = temp_dir + "//" + temp_path
            print "\n==== Log Folder Path: %s. " \
                  "All logs will be available here ====" \
                  % str(self.__logFolderDir)
            os.makedirs(self.__logFolderDir)
            '''
            Log File Paths
            1. FailedExceptionLog
            2. RunLog contains the complete Run Information for Test Run
            3. ResultFile contains the TC result information for Test Run
            '''
            tc_failed_exception_log = \
                self.__logFolderDir + "/failed_plus_exceptions.txt"
            tc_run_log = self.__logFolderDir + "/runinfo.txt"
            if self.__setLogHandler(tc_run_log,
                                    log_level=logging.DEBUG) != FAILED:
                self.__setLogHandler(tc_failed_exception_log,
                                     log_level=logging.FATAL)
                return SUCCESS
            return FAILED
        except Exception as e:
            print "\n Exception Occurred Under createLogs :%s" % \
                  GetDetailExceptionInfo(e)
            return FAILED
コード例 #23
0
ファイル: marvinPlugin.py プロジェクト: terod/cloudstack
 def printMsg(self, status, tname, err):
     if status in [FAILED, EXCEPTION] and self.__tcRunLogger:
         self.__tcRunLogger.\
             fatal("%s: %s: %s" % (status,
                                   tname,
                                   GetDetailExceptionInfo(err)))
     write_str = "=== TestName: %s | Status : %s ===\n" % (tname, status)
     self.__resultStream.write(write_str)
     print write_str
コード例 #24
0
 def __cleanEntries(self):
     '''
     @Name : __cleanAndEntries
     @Description: Cleans up the created DC in order of creation
     '''
     try:
         ret = FAILED
         if "order" in self.__dcCfg.keys() and len(self.__dcCfg["order"]):
             self.__dcCfg["order"].reverse()
         print "\n====Clean Up Entries===", self.__dcCfg
         for type in self.__dcCfg["order"]:
             self.__tcRunLogger.debug(
                 "====CleanUp Started For Type: %s====" % type)
             if type:
                 temp_ids = self.__dcCfg[type]
                 ids = [items for items in temp_ids if items]
                 for id in ids:
                     del_mod = "delete" + type
                     del_cmd = getattr(globals()[del_mod], del_mod + "Cmd")
                     del_cmd_obj = del_cmd()
                     del_cmd_resp = getattr(globals()[del_mod],
                                            del_mod + "Response")
                     del_cmd_obj.id = id
                     del_cmd_obj = self.__deleteCmds(
                         del_mod + "Cmd", del_cmd_obj)
                     del_func = getattr(self.__apiClient, del_mod)
                     del_cmd_resp = del_func(del_cmd_obj)
                     if del_cmd_resp:
                         self.__tcRunLogger.debug(
                             "====%s CleanUp Failed. ID: %s ===" %
                             (type, id))
                     else:
                         self.__tcRunLogger.debug(
                             "====%s CleanUp Successful. ID : %s===" %
                             (type, id))
         ret = SUCCESS
     except Exception as e:
         print "\n==== Exception Under __cleanEntries: %s ==== % " \
               % GetDetailExceptionInfo(e)
         self.__tcRunLogger.exception(
             "\n==== Exception Under __cleanEntries: %s ==== % " %
             GetDetailExceptionInfo(e))
     finally:
         return ret
コード例 #25
0
 def __sanitizeCmd(self, cmd):
     """
     @Name : __sanitizeCmd
     @Desc : Removes None values, Validates all required params are present
     @Input: cmd: Cmd object eg: createPhysicalNetwork
     @Output: Returns command name, asynchronous or not,request payload
              FAILED for failed cases
     """
     try:
         cmd_name = ''
         payload = {}
         required = []
         isAsync = "false"
         for attribute in dir(cmd):
             if not attribute.startswith('__'):
                 if attribute == "isAsync":
                     isAsync = getattr(cmd, attribute)
                 elif attribute == "required":
                     required = getattr(cmd, attribute)
                 else:
                     payload[attribute] = getattr(cmd, attribute)
         cmd_name = cmd.__class__.__name__.replace("Cmd", "")
         for required_param in required:
             if payload[required_param] is None:
                 self.logger.debug(
                     "CmdName: %s Parameter : %s is Required" %
                     (cmd_name, required_param))
                 self.__lastError = InvalidParameterException(
                     "Invalid Parameters")
                 return FAILED
         for param, value in payload.items():
             if value is None:
                 payload.pop(param)
             elif param == 'typeInfo':
                 payload.pop(param)
             elif isinstance(value, list):
                 if len(value) == 0:
                     payload.pop(param)
                 else:
                     if not isinstance(value[0], dict):
                         payload[param] = ",".join(value)
                     else:
                         payload.pop(param)
                         i = 0
                         for val in value:
                             for k, v in val.iteritems():
                                 payload["%s[%d].%s" % (param, i, k)] = v
                             i += 1
         return cmd_name.strip(), isAsync, payload
     except Exception as e:
         self.__lastError = e
         self.logger.\
             exception("__sanitizeCmd: CmdName : "
                       "%s : Exception:%s" % (cmd_name,
                                              GetDetailExceptionInfo(e)))
         return FAILED
コード例 #26
0
    def marvinRequest(self, cmd, response_type=None, method='GET', data=''):
        """
        @Name : marvinRequest
        @Desc: Handles Marvin Requests
        @Input  cmd: marvin's command from cloudstackAPI
                response_type: response type of the command in cmd
                method: HTTP GET/POST, defaults to GET
        @Output: Response received from CS
                 Exception in case of Error\Exception
        """
        try:
            '''
            1. Verify the Inputs Provided
            '''
            if (cmd is None or cmd == '')or \
                    (response_type is None or response_type == ''):
                self.logger.exception("marvinRequest : Invalid Command Input")
                raise InvalidParameterException("Invalid Parameter")

            '''
            2. Sanitize the Command
            '''
            sanitize_cmd_out = self.__sanitizeCmd(cmd)

            if sanitize_cmd_out == FAILED:
                raise self.__lastError

            cmd_name, is_async, payload = sanitize_cmd_out
            '''
            3. Send Command to CS
            '''
            cmd_response = self.__sendCmdToCS(cmd_name,
                                              self.auth,
                                              payload=payload,
                                              method=method)
            if cmd_response == FAILED:
                raise self.__lastError

            '''
            4. Check if the Command Response received above is valid or Not.
               If not return Invalid Response
            '''
            ret = self.__parseAndGetResponse(cmd_response,
                                             response_type,
                                             is_async)
            if ret == FAILED:
                raise self.__lastError
            return ret
        except Exception as e:
            self.logger.exception("marvinRequest : CmdName: %s Exception: %s" %
                                  (str(cmd), GetDetailExceptionInfo(e)))
            raise e
コード例 #27
0
 def enableZone(self, zoneid, allocation_state="Enabled"):
     try:
         zoneCmd = updateZone.updateZoneCmd()
         zoneCmd.id = zoneid
         zoneCmd.allocationstate = allocation_state
         ret = self.__apiClient.updateZone(zoneCmd)
         if ret.id:
             self.__tcRunLogger.debug("==== Enable Zone SuccessFul=====")
             return ret
     except Exception as e:
         print "Exception Occurred: %s" % GetDetailExceptionInfo(e)
         self.__tcRunLogger.exception("==== Enable Zone Failed=====")
         self.__cleanAndExit()
コード例 #28
0
 def updateZoneDetails(self, zoneid, details):
     try:
         zoneCmd = updateZone.updateZoneCmd()
         zoneCmd.id = zoneid
         zoneCmd.details = details
         ret = self.__apiClient.updateZone(zoneCmd)
         if ret.id:
             self.__tcRunLogger.debug("=== Update Zone SuccessFul===")
             return ret
     except Exception as e:
         print "Exception Occurred: %s" % GetDetailExceptionInfo(e)
         self.__tcRunLogger.exception("==== Update Zone  Failed=====")
         self.__cleanAndExit()
コード例 #29
0
ファイル: test_iso.py プロジェクト: slavkap/cloudstack
    def test_03_1_create_iso_with_checksum_md5_negative(self):
        self.iso.checksum = "{md5}" + "someInvalidValue"
        iso = self.registerIso(self.iso)

        try:
            self.download(self.apiclient, iso.id)
        except Exception as e:
            print("Negative Test Passed - Exception Occurred Under iso download " \
                  "%s" % GetDetailExceptionInfo(e))
        else:
            self.fail(
                "Negative Test Failed - Exception DID NOT Occurred Under iso download "
            )
コード例 #30
0
 def __setHypervisorInfo(self):
     '''
     @Name : __setHypervisorInfo
     @Desc:  Set the HyperVisor details;
             default to XenServer
     '''
     try:
         if not self.__hypervisor:
             self.__hypervisor = XEN_SERVER
         return SUCCESS
     except Exception as e:
         print("\n Exception Occurred Under __setHypervisorInfo " \
               "%s" % GetDetailExceptionInfo(e))
         return FAILED