Esempio n. 1
0
 def addVmWareDataCenter(self, vmwareDc):
     try:
         vdc = addVmwareDc.addVmwareDcCmd()
         vdc.zoneid = vmwareDc.zoneid
         vdc.name = vmwareDc.name
         vdc.vcenter = vmwareDc.vcenter
         vdc.username = vmwareDc.username
         vdc.password = vmwareDc.password
         ret = self.__apiClient.addVmwareDc(vdc)
         if ret.id:
             self.__tcRunLogger.debug("=== Adding VmWare DC Successful===")
             self.__addToCleanUp("VmwareDc", ret.id)
     except Exception as e:
         print "Exception Occurred: %s" % GetDetailExceptionInfo(e)
         self.__tcRunLogger.exception("=== Adding VmWare DC Failed===")
         self.__cleanAndExit()
Esempio n. 2
0
 def __setTestDataPath(self):
     '''
     @Name : __setTestDataPath
     @Desc : Sets the TestData Path for tests to run
     @Output:Returns SUCCESS or FAILED
     '''
     try:
         if ((self.__parsedConfig.TestData is not None)
                 and (self.__parsedConfig.TestData.Path is not None)):
             self.__testDataFilePath = self.__parsedConfig.TestData.Path
         print("\n=== Marvin Setting TestData Successful===")
         return SUCCESS
     except Exception as e:
         print("\nException Occurred Under __setTestDataPath : %s" % \
               GetDetailExceptionInfo(e))
         return FAILED
Esempio n. 3
0
 def updateConfiguration(self, globalCfg):
     try:
         if globalCfg is None or self.__apiClient is None:
             return None
         for config in globalCfg:
             updateCfg = updateConfiguration.updateConfigurationCmd()
             updateCfg.name = config.name
             updateCfg.value = config.value
             ret = self.__apiClient.updateConfiguration(updateCfg)
             if ret.id:
                 self.__tcRunLogger.debug(
                     "==UpdateConfiguration Successfull===")
     except Exception as e:
         print "Exception Occurred %s" % GetDetailExceptionInfo(e)
         self.__tcRunLogger.\
             exception("===UpdateConfiguration Failed===")
         self.__cleanAndExit()
Esempio n. 4
0
 def __parseConfig(self):
     '''
     @Name: __parseConfig
     @Desc : Parses the configuration file passed and assigns
     the parsed configuration
     @Output : SUCCESS or FAILED
     '''
     try:
         if not os.path.isfile(self.__configFile):
             print "\n=== Marvin Parse Config Init Failed ==="
             return FAILED
         self.__parsedConfig = getSetupConfig(self.__configFile)
         print "\n=== Marvin Parse Config Successful ==="
         return SUCCESS
     except Exception as e:
         print "\nException Occurred Under __parseConfig : " \
               "%s" % GetDetailExceptionInfo(e)
         return FAILED
Esempio n. 5
0
 def __persistDcConfig(self):
     try:
         if self.__logFolderPath:
             dc_file_path = self.__logFolderPath + "/dc_entries.obj"
         else:
             ts = strftime("%b_%d_%Y_%H_%M_%S", localtime())
             dc_file_path = "dc_entries_" + str(ts) + ".obj"
         file_to_write = open(dc_file_path, 'w')
         if file_to_write:
             pickle.dump(self.__cleanUp, file_to_write)
             print "\n=== Data Center Settings are dumped to %s===" % \
                   dc_file_path
             self.__tcRunLogger.debug(
                 "\n=== Data Center Settings are dumped to %s===" %
                 dc_file_path)
     except Exception as e:
         print "Exception Occurred  while persisting DC Settings: %s" % \
               GetDetailExceptionInfo(e)
 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
         return (register_user_res.apikey, register_user_res.secretkey)
     except Exception as e:
         self.__logger.exception("Exception Occurred Under __geKeys : "
                                 "%s" % GetDetailExceptionInfo(e))
         return FAILED
Esempio n. 7
0
 def __setHypervisorAndZoneInfo(self):
     '''
     @Name : __setHypervisorAndZoneInfo
     @Desc:  Set the HyperVisor and Zone details;
             default to XenServer
     '''
     try:
         if not self.__hypervisorType:
             self.__hypervisorType = XEN_SERVER
         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
         return SUCCESS
     except Exception as e:
         print "\n Exception Occurred Under init " \
               "%s" % GetDetailExceptionInfo(e)
         return FAILED
Esempio n. 8
0
 def createPhysicalNetwork(self, net, zoneid):
     try:
         phynet = createPhysicalNetwork.createPhysicalNetworkCmd()
         phynet.zoneid = zoneid
         phynet.name = net.name
         phynet.isolationmethods = net.isolationmethods
         phynetwrk = self.__apiClient.createPhysicalNetwork(phynet)
         if phynetwrk.id:
             self.__tcRunLogger.\
                 debug("Creating Physical Network Name : "
                       "%s Id : %s Successful" % (str(phynet.name),
                                                  str(phynetwrk.id)))
             self.__addToCleanUp("PhysicalNetwork", phynetwrk.id)
         self.addTrafficTypes(phynetwrk.id, net.traffictypes)
         return phynetwrk
     except Exception as e:
         print "Exception Occurred: %s" % GetDetailExceptionInfo(e)
         self.__tcRunLogger.exception("====Physical Network "
                                      "Creation Failed=====")
         self.__cleanAndExit()
Esempio n. 9
0
 def finalize(self, result):
     try:
         if not self.__userLogPath:
             src = self.__logFolderPath
             log_cfg = self.__parsedConfig.logger
             tmp = log_cfg.__dict__.get('LogFolderPath') + "/MarvinLogs"
             dst = tmp + "//" + random_gen()
             mod_name = "test_suite"
             if self.__testModName:
                 mod_name = self.__testModName.split(".")
                 if len(mod_name) > 2:
                     mod_name = mod_name[-2]
             if mod_name:
                 dst = tmp + "/" + mod_name + "_" + random_gen()
             cmd = "mv " + src + " " + dst
             os.system(cmd)
             print "===final results are now copied to: %s===" % str(dst)
     except Exception as e:
         print "=== Exception occurred under finalize :%s ===" % \
               str(GetDetailExceptionInfo(e))
Esempio n. 10
0
 def __deployDC(self):
     '''
     @Name : __deployDC
     @Desc : Deploy the DataCenter and returns accordingly.
     @Output: SUCCESS or FAILED
     '''
     try:
         ret = SUCCESS
         if self.__deployFlag:
             deploy_obj = DeployDataCenters(self.__testClient,
                                            self.__parsedConfig,
                                            self.__tcRunLogger)
             ret = deploy_obj.deploy()
             if ret != SUCCESS:
                 print "==== Deploy DC Failed ===="
         return ret
     except Exception as e:
         print "\n Exception Occurred Under __deployDC : %s" % \
               GetDetailExceptionInfo(e)
         return FAILED
Esempio n. 11
0
 def waitForHost(self, zoneId, clusterId):
     """
     Wait for the hosts in the zoneid, clusterid to be up
     2 retries with 30s delay
     """
     try:
         retry, timeout = 2, 30
         cmd = listHosts.listHostsCmd()
         cmd.clusterid, cmd.zoneid = clusterId, zoneId
         hosts = self.__apiClient.listHosts(cmd)
         while retry != 0:
             for host in hosts:
                 if host.state != 'Up':
                     break
             sleep(timeout)
             retry = retry - 1
     except Exception as e:
         print "\nException Occurred:%s" %\
               GetDetailExceptionInfo(e)
         self.__tcRunLogger.exception("=== List Hosts Failed===")
         self.__cleanAndExit()
Esempio n. 12
0
 def __checkImport(self, filename):
     '''
     @Name : __checkImport
     @Desc : Verifies to run the available test module for any Import
             Errors before running and check
             whether if it is importable.
             This will check for test modules which has some issues to be
             getting imported.
             Returns False or True based upon the result.
     '''
     try:
         if os.path.isfile(filename):
             ret = os.path.splitext(filename)
             if ret[1] == ".py":
                 os.system("python " + filename)
                 return True
         return False
     except ImportError as e:
         print "FileName :%s : Error : %s" % \
               (filename, GetDetailExceptionInfo(e))
         return False
Esempio n. 13
0
    def __sendCmdToCS(self, command, auth=True, payload={}, method='GET'):
        """
        @Name : __sendCmdToCS
        @Desc : Makes requests to CS using the Inputs provided
        @Input: command: cloudstack API command name
                    eg: deployVirtualMachineCommand
                auth: Authentication (apikey,secretKey) => True
                     else False for integration.api.port
                payload: request data composed as a dictionary
                method: GET/POST via HTTP
        @output: FAILED or else response from CS
        """
        try:
            payload["command"] = command
            payload["response"] = "json"

            if auth:
                payload["apiKey"] = self.apiKey
                payload["signature"] = self.__sign(payload)

            # Verify whether protocol is "http" or "https", then send the
            # request
            if self.protocol in ["http", "https"]:
                self.logger.debug("Payload: %s" % str(payload))
                if method == 'POST':
                    self.logger.debug("=======Sending POST Cmd : %s======="
                                      % str(command))
                    return self.__sendPostReqToCS(self.baseUrl, payload)
                if method == "GET":
                    self.logger.debug("========Sending GET Cmd : %s======="
                                      % str(command))
                    return self.__sendGetReqToCS(self.baseUrl, payload)
            else:
                self.logger.exception("__sendCmdToCS: Invalid Protocol")
                return FAILED
        except Exception as e:
            self.__lastError = e
            self.logger.exception("__sendCmdToCS: Exception:%s" %
                                  GetDetailExceptionInfo(e))
            return FAILED
Esempio n. 14
0
 def createVlanIpRanges(self,
                        mode,
                        ipranges,
                        zoneId,
                        podId=None,
                        networkId=None,
                        forvirtualnetwork=None):
     try:
         if ipranges is None:
             return
         for iprange in ipranges:
             vlanipcmd = createVlanIpRange.createVlanIpRangeCmd()
             vlanipcmd.account = iprange.account
             vlanipcmd.domainid = iprange.domainid
             vlanipcmd.endip = iprange.endip
             vlanipcmd.gateway = iprange.gateway
             vlanipcmd.netmask = iprange.netmask
             vlanipcmd.networkid = networkId
             vlanipcmd.podid = podId
             vlanipcmd.startip = iprange.startip
             vlanipcmd.zoneid = zoneId
             vlanipcmd.vlan = iprange.vlan
             if mode == "Basic":
                 if forvirtualnetwork:
                     vlanipcmd.forvirtualnetwork = "true"
                 else:
                     vlanipcmd.forvirtualnetwork = "false"
             else:
                 vlanipcmd.forvirtualnetwork = "true"
             ret = self.__apiClient.createVlanIpRange(vlanipcmd)
             if ret.id:
                 self.__tcRunLogger.debug(
                     "=== Creating Vlan Ip Range Successful===")
                 self.__addToCleanUp("VlanIpRange", ret.id)
     except Exception as e:
         print "Exception Occurred: %s" % GetDetailExceptionInfo(e)
         self.__tcRunLogger.\
             exception("=== Create Vlan Ip Range Failed===")
         self.__cleanAndExit()
Esempio n. 15
0
 def start_marvin(self):
     '''
     Initialize the Marvin
     '''
     try:
         obj_marvininit = MarvinInit(config_file=self.__configFile,
                                     deploy_dc_flag=self.__deployFlag,
                                     zone=self.__zone,
                                     hypervisor_type=self.__hypervisorType,
                                     user_logfolder_path=None)
         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()
             return SUCCESS
         return FAILED
     except Exception as e:
         print "====Exception Occurred under start_marvin: %s ====" % \
               GetDetailExceptionInfo(e)
         return FAILED
Esempio n. 16
0
 def createPrimaryStorages(self, primaryStorages, zoneId, podId, clusterId):
     try:
         if primaryStorages is None:
             return
         for primary in primaryStorages:
             primarycmd = createStoragePool.createStoragePoolCmd()
             primarycmd.details = primary.details
             primarycmd.name = primary.name
             primarycmd.podid = podId
             primarycmd.tags = primary.tags
             primarycmd.url = primary.url
             primarycmd.zoneid = zoneId
             primarycmd.clusterid = clusterId
             ret = self.__apiClient.createStoragePool(primarycmd)
             if ret.id:
                 self.__tcRunLogger.debug(
                     "=== Creating Storage Pool Successful===")
                 self.__addToCleanUp("StoragePool", ret.id)
     except Exception as e:
         print "Exception Occurred: %s" % GetDetailExceptionInfo(e)
         self.__tcRunLogger.\
             exception("=== Create Storage Pool Failed===")
         self.__cleanAndExit()
Esempio n. 17
0
 def __createTestClient(self):
     '''
     @Name : __createTestClient
     @Desc : Creates the TestClient during init
             based upon the parameters provided
     @Output: Returns SUCCESS or FAILED
     '''
     try:
         mgt_details = self.__parsedConfig.mgtSvr[0]
         dbsvr_details = self.__parsedConfig.dbSvr
         self.__testClient = CSTestClient(
             mgt_details, dbsvr_details,
             logger=self.__tcRunLogger,
             test_data_filepath=self.__testDataFilePath,
             zone=self.__zoneForTests,
             hypervisor_type=self.__hypervisorType)
         if self.__testClient:
             return self.__testClient.createTestClient()
         return FAILED
     except Exception as e:
         print "\n Exception Occurred Under __createTestClient : %s" % \
               GetDetailExceptionInfo(e)
         return FAILED
Esempio n. 18
0
 def addTrafficType(self, physical_network_id, traffictype):
     try:
         traffic_type = addTrafficType.addTrafficTypeCmd()
         traffic_type.physicalnetworkid = physical_network_id
         traffic_type.traffictype = traffictype.typ
         traffic_type.kvmnetworklabel = traffictype.kvm\
             if traffictype.kvm is not None else None
         traffic_type.xennetworklabel = traffictype.xen\
             if traffictype.xen is not None else None
         traffic_type.vmwarenetworklabel = traffictype.vmware\
             if traffictype.vmware is not None else None
         traffic_type.simulatorlabel = traffictype.simulator\
             if traffictype.simulator is not None else None
         ret = self.__apiClient.addTrafficType(traffic_type)
         if ret.id:
             self.__tcRunLogger.debug("===Add TrafficType Successful====")
             self.__addToCleanUp("TrafficType", ret.id)
             return ret
     except Exception as e:
         print "Exception Occurred: %s" % GetDetailExceptionInfo(e)
         self.__tcRunLogger.\
             exception("==== Add TrafficType Failed=====")
         self.__cleanAndExit()
Esempio n. 19
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:
         if ((self.__parseConfig() != FAILED)
                 and (self.__setHypervisorAndZoneInfo())
                 and (self.__setTestDataPath() != FAILED)
                 and (self.__initLogging() != FAILED)
                 and (self.__createTestClient() != FAILED)
                 and (self.__deployDC() != FAILED)):
             return SUCCESS
         return FAILED
     except Exception as e:
         print "\n Exception Occurred Under init " \
               "%s" % GetDetailExceptionInfo(e)
         return FAILED
Esempio n. 20
0
    def createClusters(self, clusters, zoneId, podId, vmwareDc=None):
        try:
            if clusters is None:
                return
            if vmwareDc is not None:
                vmwareDc.zoneid = zoneId
                self.addVmWareDataCenter(vmwareDc)

            for cluster in clusters:
                clustercmd = addCluster.addClusterCmd()
                clustercmd.clustername = cluster.clustername
                clustercmd.clustertype = cluster.clustertype
                clustercmd.hypervisor = cluster.hypervisor
                clustercmd.password = cluster.password
                clustercmd.podid = podId
                clustercmd.url = cluster.url
                clustercmd.username = cluster.username
                clustercmd.zoneid = zoneId
                clusterresponse = self.__apiClient.addCluster(clustercmd)
                if clusterresponse[0].id:
                    clusterId = clusterresponse[0].id
                    self.__tcRunLogger.\
                        debug("Cluster Name : %s Id : %s Created Successfully"
                              % (str(cluster.clustername), str(clusterId)))
                    self.__addToCleanUp("Cluster", clusterId)
                if cluster.hypervisor.lower() != "vmware":
                    self.addHosts(cluster.hosts, zoneId, podId, clusterId,
                                  cluster.hypervisor)
                self.waitForHost(zoneId, clusterId)
                self.createPrimaryStorages(cluster.primaryStorages, zoneId,
                                           podId, clusterId)
        except Exception as e:
            print "Exception Occurred %s" % GetDetailExceptionInfo(e)
            self.__tcRunLogger.exception("====Cluster %s Creation Failed"
                                         "=====" % str(cluster.clustername))
            self.__cleanAndExit()
Esempio n. 21
0
 def __cleanAndExit(self):
     try:
         print "\n===deploy dc failed, so cleaning the created entries==="
         if not test_data.get("deleteDC", None):
             print "\n=== Deploy DC Clean Up flag not set. So, exiting ==="
             exit(1)
         self.__tcRunLogger.debug(
             "===Deploy DC Failed, So Cleaning to Exit===")
         remove_dc_obj = DeleteDataCenters(self.__testClient,
                                           dc_cfg=self.__cleanUp,
                                           tc_run_logger=self.__tcRunLogger)
         if remove_dc_obj:
             if remove_dc_obj.removeDataCenter() == FAILED:
                 print "\n===Removing DataCenter Failed==="
                 self.__tcRunLogger.debug(
                     "===Removing DataCenter Failed===")
             else:
                 print "\n===Removing DataCenter Successful==="
                 self.__tcRunLogger.debug(
                     "===Removing DataCenter Successful===")
         exit(1)
     except Exception as e:
         print "Exception Occurred during DC CleanUp: %s" % \
               GetDetailExceptionInfo(e)
Esempio n. 22
0
 def handleFailure(self, test, err):
     '''
     Adds Failing test cases and information to log.
     '''
     self.printMsg(FAILED, self.__testName, GetDetailExceptionInfo(err))
     self.__testResult = FAILED
Esempio n. 23
0
 def handleError(self, test, err):
     '''
     Adds Exception throwing test cases and information to log.
     '''
     self.printMsg(EXCEPTION, self.__testName, GetDetailExceptionInfo(err))
     self.__testResult = EXCEPTION
Esempio n. 24
0
    def __createUserApiClient(self, UserName, DomainName, acctType=0):
        '''
        @Name : ___createUserApiClient
        @Desc : Creates a User API Client with given
                UserName\DomainName Parameters
        @Input: UserName: Username to be created in cloudstack
                DomainName: Domain under which the above account be created
                accType: Type of Account EX: Root,Non Root etc
        @Output: Return the API client for the user
        '''
        try:
            if not self.isAdminContext():
                return self.__apiClient
            mgmt_details = self.__mgmtDetails
            listDomain = listDomains.listDomainsCmd()
            listDomain.listall = True
            listDomain.name = DomainName
            try:
                domains = self.__apiClient.listDomains(listDomain)
                domId = domains[0].id
            except:
                cdomain = createDomain.createDomainCmd()
                cdomain.name = DomainName
                domain = self.__apiClient.createDomain(cdomain)
                domId = domain.id

            cmd = listAccounts.listAccountsCmd()
            cmd.name = UserName
            cmd.domainid = domId
            cmd.listall = True
            try:
                accounts = self.__apiClient.listAccounts(cmd)
                acctId = accounts[0].id
            except:
                createAcctCmd = createAccount.createAccountCmd()
                createAcctCmd.accounttype = acctType
                createAcctCmd.domainid = domId
                createAcctCmd.email = "test-" + random_gen()\
                    + "@cloudstack.org"
                createAcctCmd.firstname = UserName
                createAcctCmd.lastname = UserName
                createAcctCmd.password = '******'
                createAcctCmd.username = UserName
                acct = self.__apiClient.createAccount(createAcctCmd)
                acctId = acct.id

            listuser = listUsers.listUsersCmd()
            listuser.username = UserName
            listuser.domainid = domId
            listuser.listall = True

            listuserRes = self.__apiClient.listUsers(listuser)
            userId = listuserRes[0].id

            getuser_keys = getUserKeys.getUserKeysCmd()
            getuser_keys.id = listuserRes[0].id
            getuser_keys_res = self.__apiClient.getUserKeys(getuser_keys)
            if getuser_keys_res is None or\
                (validateList(getuser_keys_res) != PASS):
                self.__logger.error("__createApiClient: API "
                                "Client Creation Failed")

            apiKey = getuser_keys_res.apikey
            securityKey = getuser_keys_res.secretkey

            if apiKey is None:
                ret = self.__getKeys(userId)
                if ret != FAILED:
                    mgmt_details.apiKey = ret[0]
                    mgmt_details.securityKey = ret[1]
                else:
                    self.__logger.error("__createUserApiClient: "
                                        "User API Client Creation."
                                        " While Registering User Failed")
                    return FAILED
            else:
                mgmt_details.port = 8080
                mgmt_details.apiKey = apiKey
                mgmt_details.securityKey = securityKey

            newUserConnection =\
                CSConnection(mgmt_details,
                             self.__csConnection.asyncTimeout,
                             self.__csConnection.logger)
            self.__userApiClient = CloudStackAPIClient(newUserConnection)
            self.__userApiClient.connection = newUserConnection
            self.__userApiClient.hypervisor = self.__hypervisor
            return self.__userApiClient
        except Exception as e:
            self.__logger.exception("Exception Occurred "
                                    "Under getUserApiClient : %s" %
                                    GetDetailExceptionInfo(e))
            return FAILED
Esempio n. 25
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

                getuser_keys = getUserKeys.getUserKeysCmd()
                getuser_keys.id = list_user_res[0].id
                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

                user_id = list_user_res[0].id
                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
Esempio n. 26
0
 def configureProviders(self, phynetwrk, providers):
     """
     We will enable the virtualrouter elements for all zones. Other
     providers like NetScalers, SRX, etc are explicitly added/configured
     """
     try:
         for provider in providers:
             pnetprov = listNetworkServiceProviders.\
                 listNetworkServiceProvidersCmd()
             pnetprov.physicalnetworkid = phynetwrk.id
             pnetprov.state = "Disabled"
             pnetprov.name = provider.name
             pnetprovres = self.__apiClient.listNetworkServiceProviders(
                 pnetprov)
             if pnetprovres and len(pnetprovres) > 0:
                 if provider.name == 'VirtualRouter'\
                    or provider.name == 'VpcVirtualRouter':
                     vrprov = listVirtualRouterElements.\
                         listVirtualRouterElementsCmd()
                     vrprov.nspid = pnetprovres[0].id
                     vrprovresponse = self.__apiClient.\
                         listVirtualRouterElements(vrprov)
                     vrprovid = vrprovresponse[0].id
                     vrconfig = \
                         configureVirtualRouterElement.\
                         configureVirtualRouterElementCmd()
                     vrconfig.enabled = "true"
                     vrconfig.id = vrprovid
                     self.__apiClient.\
                         configureVirtualRouterElement(vrconfig)
                     self.enableProvider(pnetprovres[0].id)
                 elif provider.name == 'InternalLbVm':
                     internallbprov = listInternalLoadBalancerElements.\
                         listInternalLoadBalancerElementsCmd()
                     internallbprov.nspid = pnetprovres[0].id
                     internallbresponse = self.__apiClient.\
                         listInternalLoadBalancerElements(internallbprov)
                     internallbid = internallbresponse[0].id
                     internallbconfig = \
                         configureInternalLoadBalancerElement.\
                         configureInternalLoadBalancerElementCmd()
                     internallbconfig.enabled = "true"
                     internallbconfig.id = internallbid
                     self.__apiClient.\
                         configureInternalLoadBalancerElement(
                             internallbconfig)
                     self.enableProvider(pnetprovres[0].id)
                 elif provider.name == 'SecurityGroupProvider':
                     self.enableProvider(pnetprovres[0].id)
             elif provider.name in ['Netscaler', 'JuniperSRX', 'F5BigIp']:
                 netprov = addNetworkServiceProvider.\
                     addNetworkServiceProviderCmd()
                 netprov.name = provider.name
                 netprov.physicalnetworkid = phynetwrk.id
                 result = self.__apiClient.addNetworkServiceProvider(
                     netprov)
                 if result.id:
                     self.__tcRunLogger.\
                         debug("==== AddNetworkServiceProvider "
                               "Successful=====")
                     self.__addToCleanUp("NetworkServiceProvider",
                                         result.id)
                 for device in provider.devices:
                     if provider.name == 'Netscaler':
                         dev = addNetscalerLoadBalancer.\
                             addNetscalerLoadBalancerCmd()
                         dev.username = device.username
                         dev.password = device.password
                         dev.networkdevicetype = device.networkdevicetype
                         dev.url = configGenerator.getDeviceUrl(device)
                         dev.physicalnetworkid = phynetwrk.id
                         ret = self.__apiClient.addNetscalerLoadBalancer(
                             dev)
                         if ret.id:
                             self.__tcRunLogger.\
                                 debug("==== AddNetScalerLB "
                                       "Successful=====")
                             self.__addToCleanUp("NetscalerLoadBalancer",
                                                 ret.id)
                     elif provider.name == 'JuniperSRX':
                         dev = addSrxFirewall.addSrxFirewallCmd()
                         dev.username = device.username
                         dev.password = device.password
                         dev.networkdevicetype = device.networkdevicetype
                         dev.url = configGenerator.getDeviceUrl(device)
                         dev.physicalnetworkid = phynetwrk.id
                         ret = self.__apiClient.addSrxFirewall(dev)
                         if ret.id:
                             self.__tcRunLogger.\
                                 debug("==== AddSrx "
                                       "Successful=====")
                             self.__addToCleanUp("SrxFirewall", ret.id)
                     elif provider.name == 'F5BigIp':
                         dev = addF5LoadBalancer.addF5LoadBalancerCmd()
                         dev.username = device.username
                         dev.password = device.password
                         dev.networkdevicetype = device.networkdevicetype
                         dev.url = configGenerator.getDeviceUrl(device)
                         dev.physicalnetworkid = phynetwrk.id
                         ret = self.__apiClient.addF5LoadBalancer(dev)
                         if ret.id:
                             self.__tcRunLogger.\
                                 debug("==== AddF5 "
                                       "Successful=====")
                             self.__addToCleanUp("F5LoadBalancer", ret.id)
                     else:
                         raise InvalidParameterException(
                             "Device %s doesn't match "
                             "any know provider "
                             "type" % device)
                 self.enableProvider(result.id)
     except Exception as e:
         print "Exception Occurred: %s" % GetDetailExceptionInfo(e)
         self.__tcRunLogger.\
             exception("====List Network "
                       "Service Providers Failed=====")
         self.__cleanAndExit()
Esempio n. 27
0
    def createLogs(self,
                   test_module_name=None,
                   log_cfg=None,
                   user_provided_logpath=None,
                   use_temp_path=True):
        '''
        @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.
                 use_temp_path: Boolean value which specifies either logs will
                                       be prepended by random path or not.
        @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 = os.path.join(user_provided_logpath, "MarvinLogs")
            elif ((log_cfg is not None)
                  and ('LogFolderPath' in list(log_cfg.__dict__.keys()))
                  and (log_cfg.__dict__.get('LogFolderPath') is not None)):
                temp_dir = os.path.join(log_cfg.__dict__.get('LogFolderPath'),
                                        "MarvinLogs")

            if use_temp_path == True:
                self.__logFolderDir = os.path.join(temp_dir, temp_path)
            else:
                if test_module_name == None:
                    self.__logFolderDir = temp_dir
                else:
                    self.__logFolderDir = os.path.join(temp_dir,
                                                       str(test_module_name))

            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 = os.path.join(
                self.__logFolderDir, "failed_plus_exceptions.txt")
            tc_run_log = os.path.join(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
Esempio n. 28
0
 def createZones(self, zones):
     try:
         for zone in zones:
             zonecmd = createZone.createZoneCmd()
             zonecmd.dns1 = zone.dns1
             zonecmd.dns2 = zone.dns2
             zonecmd.internaldns1 = zone.internaldns1
             zonecmd.internaldns2 = zone.internaldns2
             zonecmd.name = zone.name
             zonecmd.securitygroupenabled = zone.securitygroupenabled
             zonecmd.localstorageenabled = zone.localstorageenabled
             zonecmd.networktype = zone.networktype
             if zone.securitygroupenabled != "true":
                 zonecmd.guestcidraddress = zone.guestcidraddress
             zoneId = self.createZone(zonecmd)
             if zoneId == FAILED:
                 self.__tcRunLogger.\
                     exception(
                         "====Zone: %s Creation Failed. So Exiting=====" %
                         str(zone.name))
                 self.__cleanAndExit()
             for pnet in zone.physical_networks:
                 phynetwrk = self.createPhysicalNetwork(pnet, zoneId)
                 self.configureProviders(phynetwrk, pnet.providers)
                 self.updatePhysicalNetwork(phynetwrk.id,
                                            "Enabled",
                                            vlan=pnet.vlan)
             if zone.networktype == "Basic":
                 listnetworkoffering =\
                     listNetworkOfferings.listNetworkOfferingsCmd()
                 listnetworkoffering.name =\
                     "DefaultSharedNetscalerEIPandELBNetworkOffering" \
                     if len(filter(lambda x:
                                   x.typ == 'Public',
                                   zone.physical_networks[0].
                                   traffictypes)) > 0 \
                     else "DefaultSharedNetworkOfferingWithSGService"
                 if zone.networkofferingname is not None:
                     listnetworkoffering.name = zone.networkofferingname
                 listnetworkofferingresponse = \
                     self.__apiClient.listNetworkOfferings(
                         listnetworkoffering)
                 guestntwrk = configGenerator.network()
                 guestntwrk.displaytext = "guestNetworkForBasicZone"
                 guestntwrk.name = "guestNetworkForBasicZone"
                 guestntwrk.zoneid = zoneId
                 guestntwrk.networkofferingid = \
                     listnetworkofferingresponse[0].id
                 networkid = self.createNetworks([guestntwrk], zoneId)
                 self.createPods(zone.pods, zoneId, networkid)
                 if self.isEipElbZone(zone):
                     self.createVlanIpRanges(zone.networktype,
                                             zone.ipranges,
                                             zoneId,
                                             forvirtualnetwork=True)
             isPureAdvancedZone = (zone.networktype == "Advanced"
                                   and zone.securitygroupenabled != "true")
             if isPureAdvancedZone:
                 self.createPods(zone.pods, zoneId)
                 self.createVlanIpRanges(zone.networktype, zone.ipranges,
                                         zoneId)
             elif (zone.networktype == "Advanced"
                   and zone.securitygroupenabled == "true"):
                 listnetworkoffering =\
                     listNetworkOfferings.listNetworkOfferingsCmd()
                 listnetworkoffering.name =\
                     "DefaultSharedNetworkOfferingWithSGService"
                 if zone.networkofferingname is not None:
                     listnetworkoffering.name = zone.networkofferingname
                 listnetworkofferingresponse = \
                     self.__apiClient.listNetworkOfferings(
                         listnetworkoffering)
                 networkcmd = createNetwork.createNetworkCmd()
                 networkcmd.displaytext = "Shared SG enabled network"
                 networkcmd.name = "Shared SG enabled network"
                 networkcmd.networkofferingid =\
                     listnetworkofferingresponse[0].id
                 networkcmd.zoneid = zoneId
                 ipranges = zone.ipranges
                 if ipranges:
                     iprange = ipranges.pop()
                     networkcmd.startip = iprange.startip
                     networkcmd.endip = iprange.endip
                     networkcmd.gateway = iprange.gateway
                     networkcmd.netmask = iprange.netmask
                     networkcmd.vlan = iprange.vlan
                 networkcmdresponse = self.__apiClient.createNetwork(
                     networkcmd)
                 if networkcmdresponse.id:
                     self.__addToCleanUp("Network", networkcmdresponse.id)
                     self.__tcRunLogger.\
                         debug("create Network Successful. NetworkId : %s "
                               % str(networkcmdresponse.id))
                 self.createPods(zone.pods, zoneId, networkcmdresponse.id)
             '''Note: Swift needs cache storage first'''
             self.createCacheStorages(zone.cacheStorages, zoneId)
             self.createSecondaryStorages(zone.secondaryStorages, zoneId)
             enabled = getattr(zone, 'enabled', 'True')
             if enabled == 'True' or enabled is None:
                 self.enableZone(zoneId, "Enabled")
             details = getattr(zone, 'details')
             if details is not None:
                 det = [d.__dict__ for d in details]
                 self.updateZoneDetails(zoneId, det)
         return
     except Exception as e:
         print "\nException Occurred %s" % GetDetailExceptionInfo(e)
         self.__tcRunLogger.exception("==== Create Zones Failed ===")