class TestReadOnlyAccount(cosmicTestCase):
    def setUp(self):
        self.logger = CosmicLog(CosmicLog.LOGGER_TEST).get_logger()
        self.testClient = self.getClsTestClient()
        self.apiclient = self.testClient.getApiClient()
        self.services = self.testClient.getParsedTestDataConfig()

        # Get Zone, Domain and templates
        self.domain = get_domain(self.apiclient)
        self.zone = get_zone(self.apiclient, self.testClient.getZoneForTests())
        self.services["virtual_machine"]["zoneid"] = self.zone.id

        # Create an account with normal domain admin rights
        self.account_admin = Account.create(self.apiclient,
                                            self.services["account"],
                                            admin=True,
                                            domainid=self.domain.id)

        # Create an account with readonly domain admin rights
        self.services["account"]["accounttype"] = 4
        self.account_ro_admin = Account.create(self.apiclient,
                                               self.services["account"],
                                               admin=True,
                                               domainid=self.domain.id)

        self.user_admin = User.registerUserKeys(self.apiclient,
                                                self.account_admin.user[0].id)
        self.user_ro_admin = User.registerUserKeys(
            self.apiclient, self.account_ro_admin.user[0].id)

        self.cleanup = [self.account_admin, self.account_ro_admin]
        return

    def tearDown(self):
        cleanup_resources(self.apiclient, self.cleanup)
        return

    @attr(tags=['advanced'])
    def test_01_checkApiCallsRoAdmin(self):
        """Test which API calls are available"""
        response = None

        mgmt_details = self.testClient.getMgmtDetails()

        self.testClient.setMgmtDetails(api_key=self.user_admin.apikey,
                                       secret_key=self.user_admin.secretkey,
                                       port=8080)
        self.testClient.createTestClient()
        api_client = self.testClient.getApiClient()
        try:
            response = api_client.listApis()
        except CloudStackApiException:
            self.logger.debug("List APIs")
        except Exception as e:
            self.logger.debug("Exception %s raised listing API calls " % e)

        self.assertFalse(
            all(x['name'].startswith(("list", "login", "logout"))
                for x in response['api']),
            "Only API's calls containing list/login/logout are shown")

        self.testClient.setMgmtDetails(api_key=mgmt_details.apiKey,
                                       secret_key=mgmt_details.secretKey)
        self.testClient.createTestClient()
        return

    @attr(tags=['advanced'])
    def test_02_checkApiCallsAdmin(self):
        """Test which API RO calls are available"""
        response = None

        mgmt_details = self.testClient.getMgmtDetails()

        self.testClient.setMgmtDetails(api_key=self.user_ro_admin.apikey,
                                       secret_key=self.user_ro_admin.secretkey,
                                       port=8080)
        self.testClient.createTestClient()
        api_client = self.testClient.getApiClient()
        try:
            response = api_client.listApis()
        except CloudStackApiException:
            self.logger.debug("List APIs")
        except Exception as e:
            self.logger.debug("Exception %s raised listing API calls " % e)

        self.assertTrue(
            all(x['name'].startswith(("list", "login", "logout"))
                for x in response['api']),
            "List API's contains calls other then list/login/logout")

        self.testClient.setMgmtDetails(api_key=mgmt_details.apiKey,
                                       secret_key=mgmt_details.secretKey)
        self.testClient.createTestClient()
        return
Ejemplo n.º 2
0
class TestDeleteAccount(cosmicTestCase):
    def setUp(self):
        self.logger = CosmicLog(CosmicLog.LOGGER_TEST).get_logger()
        self.testClient = self.getClsTestClient()
        self.apiclient = self.testClient.getApiClient()
        self.services = self.testClient.getParsedTestDataConfig()

        # Get Zone, Domain and templates
        self.domain = get_domain(self.apiclient)
        self.zone = get_zone(self.apiclient, self.testClient.getZoneForTests())
        template = get_template(self.apiclient, self.zone.id)
        self.services["virtual_machine"]["zoneid"] = self.zone.id

        # Create an account, network, VM and IP addresses
        self.account = Account.create(self.apiclient,
                                      self.services["account"],
                                      admin=True,
                                      domainid=self.domain.id)

        self.vpc_offering = get_default_vpc_offering(self.apiclient)
        self.logger.debug("VPC Offering '%s' selected", self.vpc_offering.name)

        self.network_offering = get_default_network_offering(self.apiclient)
        self.logger.debug("Network Offering '%s' selected",
                          self.network_offering.name)

        self.virtual_machine_offering = get_default_virtual_machine_offering(
            self.apiclient)
        self.logger.debug("Virtual Machine Offering '%s' selected",
                          self.virtual_machine_offering.name)

        self.default_allow_acl = get_network_acl(self.apiclient,
                                                 'default_allow')
        self.logger.debug("ACL '%s' selected", self.default_allow_acl.name)

        self.template = get_template(self.apiclient, self.zone.id)
        self.logger.debug("Template '%s' selected" % self.template.name)

        self.vpc1 = VPC.create(self.apiclient,
                               self.services['vpcs']['vpc1'],
                               vpcofferingid=self.vpc_offering.id,
                               zoneid=self.zone.id,
                               domainid=self.domain.id,
                               account=self.account.name)
        self.logger.debug("VPC '%s' created, CIDR: %s", self.vpc1.name,
                          self.vpc1.cidr)

        self.network1 = Network.create(
            self.apiclient,
            self.services['networks']['network1'],
            networkofferingid=self.network_offering.id,
            aclid=self.default_allow_acl.id,
            vpcid=self.vpc1.id,
            zoneid=self.zone.id,
            domainid=self.domain.id,
            accountid=self.account.name)
        self.logger.debug("Network '%s' created, CIDR: %s, Gateway: %s",
                          self.network1.name, self.network1.cidr,
                          self.network1.gateway)

        self.vm1 = VirtualMachine.create(
            self.apiclient,
            self.services['vms']['vm1'],
            templateid=self.template.id,
            serviceofferingid=self.virtual_machine_offering.id,
            networkids=[self.network1.id],
            zoneid=self.zone.id,
            domainid=self.domain.id,
            accountid=self.account.name)
        self.logger.debug("VM '%s' created, Network: %s, IP %s", self.vm1.name,
                          self.network1.name, self.vm1.ipaddress)

        src_nat_ip_addrs = list_public_ip(self.apiclient,
                                          account=self.account.name,
                                          domainid=self.account.domainid)

        try:
            src_nat_ip_addr = src_nat_ip_addrs[0]
        except Exception as e:
            self.fail("SSH failed for VM with IP: %s %s" %
                      (src_nat_ip_addr.ipaddress, e))

        self.lb_rule = LoadBalancerRule.create(self.apiclient,
                                               self.services["lbrule"],
                                               src_nat_ip_addr.id,
                                               self.account.name,
                                               self.network1.id, self.vpc1.id)
        self.lb_rule.assign(self.apiclient, [self.vm1])

        self.nat_rule = NATRule.create(self.apiclient, self.vm1,
                                       self.services["natrule"],
                                       src_nat_ip_addr.id)
        self.cleanup = [self.account]
        return

    def tearDown(self):
        cleanup_resources(self.apiclient, self.cleanup)
        return

    @attr(tags=['advanced'])
    def test_01_getsecretkey(self):
        """Test if we can get the secretkey"""

        userkeys = None
        userinfo = None

        try:
            userkeys = User.registerUserKeys(self.apiclient,
                                             self.account.user[0].id)
        except CloudStackApiException:
            self.logger.debug("Registered user keys")
        except Exception as e:
            self.logger.debug(
                "Exception %s raised while registering user keys" % e)

        try:
            userinfo = User.list(self.apiclient, id=self.account.user[0].id)[0]
        except CloudStackApiException:
            self.logger.debug("Retrieved user")
        except Exception as e:
            self.logger.debug("Exception %s raised while retrieving user" % e)

        self.assertEqual(userkeys.apikey, userinfo.apikey,
                         "API key is different")
        self.assertNotEqual(userkeys.secretkey, userinfo.secretkey,
                            "Secret key is visible")
        return

    @attr(tags=['advanced'])
    def test_02_delete_account(self):
        """Test for delete account"""

        # Validate the Following
        # 1. after account.cleanup.interval (global setting)
        #    time all the PF/LB rules should be deleted
        # 2. verify that list(LoadBalancer/PortForwarding)Rules
        #    API does not return any rules for the account
        # 3. The domR should have been expunged for this account

        self.account.delete(self.apiclient)
        interval = list_configurations(self.apiclient,
                                       name='account.cleanup.interval')
        self.assertEqual(isinstance(interval, list), True,
                         "Check if account.cleanup.interval config present")
        # Sleep to ensure that all resources are deleted
        time.sleep(int(interval[0].value))

        # ListLoadBalancerRules should not list
        # associated rules with deleted account
        # Unable to find account testuser1 in domain 1 : Exception
        try:
            list_lb_rules(self.apiclient,
                          account=self.account.name,
                          domainid=self.account.domainid)
        except CloudStackApiException:
            self.logger.debug("Port Forwarding Rule is deleted")

        # ListPortForwardingRules should not
        # list associated rules with deleted account
        try:
            list_nat_rules(self.apiclient,
                           account=self.account.name,
                           domainid=self.account.domainid)
        except CloudStackApiException:
            self.logger.debug("NATRule is deleted")

        # Retrieve router for the user account
        try:
            routers = list_routers(self.apiclient,
                                   account=self.account.name,
                                   domainid=self.account.domainid)
            self.assertEqual(routers, None,
                             "Check routers are properly deleted.")
        except CloudStackApiException:
            self.logger.debug("Router is deleted")

        except Exception as e:
            raise Exception(
                "Encountered %s raised while fetching routers for account: %s"
                % (e, self.account.name))
        return
Ejemplo n.º 3
0
class TestReleaseIP(cosmicTestCase):
    def setUp(self):
        self.logger = CosmicLog(CosmicLog.LOGGER_TEST).get_logger()

        self.testClient = self.getClsTestClient()
        self.apiclient = self.testClient.getApiClient()
        self.services = self.testClient.getParsedTestDataConfig()
        self.vpc_offering = get_default_vpc_offering(self.apiclient)
        self.network_offering = get_default_network_offering(self.apiclient)

        # Get Zone, Domain and templates
        self.domain = get_domain(self.apiclient)
        self.zone = get_zone(self.apiclient, self.testClient.getZoneForTests())
        template = get_template(self.apiclient, self.zone.id)
        self.services["virtual_machine"]["zoneid"] = self.zone.id

        # Create an account, network, VM, Port forwarding rule, LB rules
        self.account = Account.create(self.apiclient,
                                      self.services["account"],
                                      admin=True,
                                      domainid=self.domain.id)

        self.service_offering = get_default_virtual_machine_offering(
            self.apiclient)
        self.vpc = VPC.create(self.apiclient,
                              self.services["vpc"],
                              vpcofferingid=self.vpc_offering.id,
                              zoneid=self.zone.id,
                              account=self.account.name,
                              domainid=self.account.domainid)

        ntwk = Network.create(api_client=self.apiclient,
                              services=self.services["network_1"],
                              accountid=self.account.name,
                              domainid=self.domain.id,
                              networkofferingid=self.network_offering.id,
                              zoneid=self.zone.id,
                              vpcid=self.vpc.id)

        networkids = []
        networkids.append(ntwk.id)

        self.virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            templateid=template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            networkids=networkids)

        self.ip_address = PublicIPAddress.create(self.apiclient,
                                                 self.account.name,
                                                 self.zone.id,
                                                 self.account.domainid,
                                                 vpcid=self.vpc.id)

        ip_addrs = list_public_ip(self.apiclient,
                                  account=self.account.name,
                                  domainid=self.account.domainid,
                                  issourcenat=False)

        try:
            self.ip_addr = ip_addrs[0]
        except Exception as e:
            raise Exception(
                "Failed: During acquiring source NAT for account: %s, :%s" %
                (self.account.name, e))

        self.nat_rule = NATRule.create(self.apiclient,
                                       self.virtual_machine,
                                       self.services["natrule"],
                                       self.ip_addr.id,
                                       networkid=ntwk.id)
        self.lb_rule = LoadBalancerRule.create(self.apiclient,
                                               self.services["lbrule"],
                                               self.ip_addr.id,
                                               accountid=self.account.name,
                                               networkid=ntwk.id)
        self.cleanup = [self.virtual_machine, self.account]
        return

    def tearDown(self):
        cleanup_resources(self.apiclient, self.cleanup)

    @attr(tags=['advanced'])
    def test_01_release_ip(self):
        """Test for release public IP address"""

        self.logger.debug("Deleting Public IP : %s" % self.ip_addr.id)

        self.ip_address.delete(self.apiclient)

        retriesCount = 10
        isIpAddressDisassociated = False
        while retriesCount > 0:
            listResponse = list_public_ip(self.apiclient, id=self.ip_addr.id)
            if len(listResponse) == 0:
                isIpAddressDisassociated = True
                break
            retriesCount -= 1
            time.sleep(60)
        # End while

        self.assertTrue(isIpAddressDisassociated,
                        "Failed to disassociate IP address")

        # ListPortForwardingRules should not list
        # associated rules with Public IP address
        try:
            list_nat_rule = list_nat_rules(self.apiclient, id=self.nat_rule.id)
            self.logger.debug("List NAT Rule response" + str(list_nat_rule))
        except CloudStackApiException:
            self.logger.debug("Port Forwarding Rule is deleted")

        # listLoadBalancerRules should not list
        # associated rules with Public IP address
        try:
            list_lb_rule = list_lb_rules(self.apiclient, id=self.lb_rule.id)
            self.logger.debug("List LB Rule response" + str(list_lb_rule))
        except CloudStackApiException:
            self.logger.debug("Port Forwarding Rule is deleted")

        # SSH Attempt though public IP should fail
        with self.assertRaises(Exception):
            SshClient(self.ip_addr.ipaddress,
                      self.services["natrule"]["publicport"],
                      self.virtual_machine.username,
                      self.virtual_machine.password,
                      retries=2,
                      delay=0)
        return
Ejemplo n.º 4
0
class TestSSVMs(cosmicTestCase):
    def setUp(self):
        self.logger = CosmicLog(CosmicLog.LOGGER_TEST).get_logger()
        self.testClient = super(TestSSVMs, self).getClsTestClient()
        self.apiclient = self.testClient.getApiClient()
        self.cleanup = []
        self.services = self.testClient.getParsedTestDataConfig()
        self.zone = get_zone(self.apiclient, self.testClient.getZoneForTests())

        if not getattr(self.zone, 'dns2', False):
            zone = Zone.list(self.apiclient)[0]
            zone.update(self.apiclient, dns2="1.1.1.1")

        self.services["sleep"] = 5
        self.services["timeout"] = 180

        return

    def tearDown(self):
        try:
            # Clean up, terminate the created templates
            cleanup_resources(self.apiclient, self.cleanup)

        except Exception as e:
            raise Exception("Warning: Exception during cleanup : %s" % e)
        return

    @attr(tags=['advanced'])
    def test_01_list_sec_storage_vm(self):
        self._test_list_svm_vm('secondarystoragevm')

    @attr(tags=['advanced'])
    def test_02_list_cpvm_vm(self):
        self._test_list_svm_vm('consoleproxy')

    @attr(tags=['advanced'])
    def test_03_destroy_ssvm(self):
        """Test destroy SSVM
        """

        # Validate the following
        # 1. SSVM should be completely destroyed and a new one will spin up
        # 2. listSystemVMs will show a different name for the
        #    systemVM from what it was before
        # 3. new SSVM will have a public/private and link-local-ip
        # 4. cloud process within SSVM must be up and running

        list_ssvm_response = list_ssvms(self.apiclient,
                                        systemvmtype='secondarystoragevm',
                                        state='Running',
                                        zoneid=self.zone.id)
        self.assertEqual(isinstance(list_ssvm_response, list), True,
                         "Check list response returns a valid list")
        ssvm_response = list_ssvm_response[0]

        old_name = ssvm_response.name

        self.logger.debug("Destroying SSVM: %s" % ssvm_response.id)
        cmd = {'id': ssvm_response.id, 'fetch_result': True}
        try:
            self.apiclient.destroySystemVm(**cmd)
        except CloudStackApiException as e:
            if e.error['errorcode'] != 530:
                raise e

        timeout = self.services["timeout"]
        while True:
            list_ssvm_response = list_ssvms(self.apiclient,
                                            zoneid=self.zone.id,
                                            systemvmtype='secondarystoragevm')
            if isinstance(list_ssvm_response,
                          list) and len(list_ssvm_response) > 0:
                if list_ssvm_response[0].state == 'Running':
                    break
            if timeout == 0:
                self.logger.debug(
                    "Warning: List SSVM didn't return systemvms in Running state. This is a known issue, ignoring it for now!"
                )
                return

            time.sleep(self.services["sleep"])
            timeout = timeout - 1

        ssvm_response = list_ssvm_response[0]

        # Verify Name, Public IP, Private IP and Link local IP
        # for newly created SSVM
        self.assertNotEqual(ssvm_response.name, old_name,
                            "Check SSVM new name with name of destroyed SSVM")
        self.assertEqual(hasattr(ssvm_response, 'privateip'), True,
                         "Check whether SSVM has private IP field")

        self.assertEqual(hasattr(ssvm_response, 'linklocalip'), True,
                         "Check whether SSVM has link local IP field")

        self.assertEqual(hasattr(ssvm_response, 'publicip'), True,
                         "Check whether SSVM has public IP field")

        # Wait for the agent to be up
        self.wait_for_system_vm_agent(ssvm_response.name)

        return

    @attr(tags=['advanced'])
    def test_04_destroy_cpvm(self):
        """Test destroy CPVM
        """

        # Validate the following
        # 1. CPVM should be completely destroyed and a new one will spin up
        # 2. listSystemVMs will show a different name for the systemVM from
        #    what it was before
        # 3. new CPVM will have a public/private and link-local-ip
        # 4. cloud process within CPVM must be up and running

        list_cpvm_response = list_ssvms(self.apiclient,
                                        systemvmtype='consoleproxy',
                                        zoneid=self.zone.id)
        self.assertEqual(isinstance(list_cpvm_response, list), True,
                         "Check list response returns a valid list")
        cpvm_response = list_cpvm_response[0]

        old_name = cpvm_response.name

        self.logger.debug("Destroying CPVM: %s" % cpvm_response.id)
        cmd = {'id': cpvm_response.id, 'fetch_result': True}
        try:
            self.apiclient.destroySystemVm(**cmd)
        except CloudStackApiException as e:
            if e.error['errorcode'] != 530:
                raise e

        timeout = self.services["timeout"]
        while True:
            list_cpvm_response = list_ssvms(self.apiclient,
                                            systemvmtype='consoleproxy',
                                            zoneid=self.zone.id)
            if isinstance(list_cpvm_response,
                          list) and len(list_cpvm_response) > 0:
                if list_cpvm_response[0].state == 'Running':
                    break
            if timeout == 0:
                # FIXME: This should be fixed!
                self.logger.debug(
                    "Warning: List CPVM didn't return systemvms in Running state. This is a known issue, ignoring it for now!"
                )
                return

            time.sleep(self.services["sleep"])
            timeout = timeout - 1

        cpvm_response = list_cpvm_response[0]

        # Verify Name, Public IP, Private IP and Link local IP
        # for newly created CPVM
        self.assertNotEqual(cpvm_response.name, old_name,
                            "Check SSVM new name with name of destroyed CPVM")
        self.assertEqual(hasattr(cpvm_response, 'privateip'), True,
                         "Check whether CPVM has private IP field")

        self.assertEqual(hasattr(cpvm_response, 'linklocalip'), True,
                         "Check whether CPVM has link local IP field")

        self.assertEqual(hasattr(cpvm_response, 'publicip'), True,
                         "Check whether CPVM has public IP field")

        # Wait for the agent to be up
        self.wait_for_system_vm_agent(cpvm_response.name)

        return

    def wait_for_system_vm_agent(self, vmname):
        list_host_response = []
        self.logger.debug("Waiting for system VM %s agent to be UP" % vmname)
        timeout = self.services["timeout"]
        sleep_interval = self.services["sleep"]
        while timeout > 0:
            list_host_response = list_hosts(self.apiclient, name=vmname)

            if list_host_response and list_host_response[0].state == 'Up':
                self.logger.debug("System VM %s agent is UP" % vmname)
                break

            time.sleep(sleep_interval)
            timeout = timeout - sleep_interval

        if timeout <= 0 and len(list_host_response
                                ) > 0 and list_host_response[0].state != 'Up':
            # FIXME: This should be fixed!
            self.logger.debug(
                "Warning: List CPVM didn't return systemvms in Running state. This is a known issue, ignoring it for now!"
            )
            return

    def _test_list_svm_vm(self, svm_type):
        # Validate the following:
        # 1. listSystemVM
        #    should return only ONE SVM per zone
        # 2. The returned SVM should be in Running state
        # 3. listSystemVM for should list publicip, privateip and link-localip
        # 4. The gateway programmed on the SVM by listSystemVm should be
        #    the same as the gateway returned by listVlanIpRanges
        # 5. DNS entries must match those given for the zone

        list_svm_response = list_ssvms(
            self.apiclient,
            systemvmtype=svm_type,
            state='Running',
        )
        self.assertEqual(isinstance(list_svm_response, list), True,
                         "Check list response returns a valid list")
        # Verify SSVM response
        self.assertNotEqual(len(list_svm_response), 0,
                            "Check list System VMs response")

        list_zones_response = list_zones(self.apiclient)

        self.assertEqual(isinstance(list_zones_response, list), True,
                         "Check list response returns a valid list")

        self.logger.debug("Number of zones: %s" % len(list_zones_response))
        self.logger.debug("Number of System VMs: %s" % len(list_svm_response))
        # Number of Sec storage VMs = No of Zones
        self.assertEqual(len(list_svm_response), len(list_zones_response),
                         "Check number of System VMs with number of zones")
        # For each secondary storage VM check private IP,
        # public IP, link local IP and DNS
        for svm in list_svm_response:

            self.logger.debug("SVM state: %s" % svm.state)
            self.assertEqual(svm.state, 'Running',
                             "Check whether state of System VM is running")

            self.assertEqual(hasattr(svm, 'privateip'), True,
                             "Check whether System VM has private IP field")

            self.assertEqual(
                hasattr(svm, 'linklocalip'), True,
                "Check whether System VM has link local IP field")

            self.assertEqual(hasattr(svm, 'publicip'), True,
                             "Check whether System VM has public IP field")

            # Fetch corresponding ip ranges information from listVlanIpRanges
            ipranges_response = list_vlan_ipranges(self.apiclient,
                                                   zoneid=svm.zoneid)
            self.assertEqual(isinstance(ipranges_response, list), True,
                             "Check list response returns a valid list")
            iprange = ipranges_response[0]

            # Execute the following assertion in all zones except basic Zones
            if not (self.zone.networktype.lower() == 'basic'):
                self.assertEqual(
                    svm.gateway, iprange.gateway,
                    "Check gateway with that of corresponding ip range")

            # Fetch corresponding zone information from listZones
            zone_response = list_zones(self.apiclient, id=svm.zoneid)
            self.assertEqual(isinstance(zone_response, list), True,
                             "Check list response returns a valid list")
            self.assertEqual(svm.dns1, zone_response[0].dns1,
                             "Check DNS1 with that of corresponding zone")

            self.assertEqual(svm.dns2, zone_response[0].dns2,
                             "Check DNS2 with that of corresponding zone")
        return