def setUp(self):
        self.containers_api = ContainersAPI()
        self.bridges_api = BridgesAPI()
        self.storagepool_api = StoragepoolsAPI()
        self.createdcontainer = []

        self.lg.info('Choose one random node of list of running nodes.')
        self.node_id = self.get_random_node()
        self.zeroCore_ip = [
            x['ip'] for x in self.nodes if x['id'] == self.node_id
        ]
        self.assertTrue(self.zeroCore_ip, 'No node match the random node')
        self.jwt = self.nodes_api.jwt
        self.zeroCore = Client(self.zeroCore_ip[0], password=self.jwt)
        self.root_url = "https://hub.gig.tech/gig-official-apps/ubuntu1604.flist"
        self.storage = "ardb://hub.gig.tech:16379"
        self.container_name = self.rand_str()
        self.hostname = self.rand_str()
        self.process_body = {'name': 'yes'}
        self.container_body = {
            "name": self.container_name,
            "hostname": self.hostname,
            "flist": self.root_url,
            "hostNetworking": False,
            "initProcesses": [],
            "filesystems": [],
            "ports": [],
            "storage": self.storage
        }
示例#2
0
    def setUp(self):
        super().setUp()
        self.containers_api = ContainersAPI()
        self.lg.info('Choose one random node of list of running nodes.')
        self.node_id = self.get_random_node()
        if self.node_id is None:
            self.lg.info(' No node found')
            return
        self.node = {}
        for node in self.nodes:
            if node['id'] == self.node_id:
                self.g8os_ip = node['ip']
                self.node = node
                break

        self.jwt = self.nodes_api.jwt
        self.g8core = Client(self.g8os_ip, password=self.jwt)

        self.root_url = "https://hub.gig.tech/gig-official-apps/ubuntu1604.flist"
        self.storage = "ardb://hub.gig.tech:16379"
        self.container_name = self.rand_str()
        self.hostname = self.rand_str()
        self.job_body = {'name': 'yes'}
        self.container_body = {
            "name": self.container_name,
            "hostname": self.hostname,
            "flist": self.root_url,
            "hostNetworking": False,
            "initProcesses": [],
            "filesystems": [],
            "ports": [],
            "storage": self.storage
        }
示例#3
0
    def setUp(self):
        super().setUp()
        self.vms_api = VmsAPI()
        self.storageclusters_api = Storageclusters()
        self.vdisks_apis = VDisksAPIs()
        self.lg.info('Get random nodid (N0)')
        self.nodeid = self.get_random_node()
        nodeip = [x['ip'] for x in self.nodes if x['id'] == self.nodeid][0]
        self.jwt = self.nodes_api.jwt
        self.pyclient = Client(nodeip, password=self.jwt)

        storageclusters = self.storageclusters_api.get_storageclusters()
        if storageclusters.json() == []:
            self.storagecluster = self.create_sotragecluster()['label']
        else:
            self.storagecluster = storageclusters.json()[0]

        vdisks = self.vdisks_apis.get_vdisks()
        vdisks = [
            x for x in vdisks.json()
            if (x['id'] == 'ubuntu-test-vdisk'
                and x['storageCluster'] == self.storagecluster)
        ]
        if vdisks == []:
            self.vdisk = self.create_boot_vdisk(self.storagecluster)
        else:
            self.vdisk = vdisks[0]
 def setUp(self):
     super().setUp()
     self.storagepool_api = StoragepoolsAPI()
     self.nodeid = self.get_random_node()
     self.nodeip = [x['ip'] for x in self.nodes if x['id'] == self.nodeid]
     self.jwt = self.nodes_api.jwt
     self.pyclient = Client(self.nodeip[0], password=self.jwt)
     self.CLEANUP = []
    def setUp(self):
        super().setUp()
        self.vms_api = VmsAPI()
        self.storageclusters_api = Storageclusters()
        self.vdisks_apis = VDisksAPIs()

        self.lg.info('Get random nodid (N0)')
        self.nodeid = self.get_random_node()
        pyclient_ip = [x['ip'] for x in self.nodes if x['id'] == self.nodeid]
        self.assertNotEqual(pyclient_ip, [])
        self.jwt = self.nodes_api.jwt
        self.pyclient = Client(pyclient_ip[0], password=self.jwt)

        self.lg.info('Join zerotier network (ZT0)')
        self.nwid = self.create_zerotier_network()
        self.body = {"nwid": self.nwid}
        self.zerotier_api.post_nodes_zerotiers(self.nodeid, self.body)

        for _ in range(50):
            response = self.zerotier_api.get_nodes_zerotiers_zerotierid(
                self.nodeid, self.nwid)
            if response.status_code == 200:
                if response.json()['status'] == 'OK':
                    break
                else:
                    time.sleep(3)
            else:
                self.lg.info('can\'t list node zerotier networks')
        else:
            self.lg.info('can\'t join zerotier network after 150 seconds')
    def setUp(self):
        super().setUp()
        self.bridges_api = BridgesAPI()

        self.lg.info('Get random nodid (N0)')
        self.nodeid = self.get_random_node()
        pyclient_ip = [x['ip'] for x in self.nodes
                       if x['id'] == self.nodeid][0]
        self.jwt = self.nodes_api.jwt
        self.pyclient = Client(pyclient_ip, password=self.jwt)

        self.lg.info('Create bridge (B0) on node (N0)')
        self.name = self.rand_str()
        self.hwaddr = self.randomMAC()
        self.networkMode = "none"
        self.nat = False
        self.settings = {}
        self.body = {
            "name": self.name,
            "hwaddr": self.hwaddr,
            "networkMode": self.networkMode,
            "nat": self.nat,
            "setting": self.settings
        }
        self.bridges_api.post_nodes_bridges(self.nodeid, self.body)
        time.sleep(3)
示例#7
0
 def setUp(self):
     super().setUp()
     self.nodes_api = NodesAPI()
     self.jwt = self.nodes_api.jwt
     self.lg.info('Choose one random node of list of running nodes.')
     self.node_id = self.get_random_node()
     if self.node_id is None:
         self.lg.info(' No node found')
         return
     self.node = {}
     for node in self.nodes:
         if node['id'] == self.node_id:
             self.g8os_ip = node['ip']
             self.node = node
             break
     self.python_client = Client(self.g8os_ip, password=self.jwt)
示例#8
0
    def test011_post_nodes_vms_vmid_migrate(self):
        """ GAT-077
        **Test Scenario:**

        #. Get random nodid (N0).
        #. Create virtual machine (VM0) on node (N0).
        #. Migrate virtual machine (VM0) to another node, should succeed with 204.
        #. Get virtual machine (VM0), virtual machine (VM0) status should be migrating.
        """
        if len(self.nodes) < 2:
            self.skipTest('need at least 2 nodes')

        self.lg.info('Create virtual machine (VM0) on node (N0)')
        vm = self.create_vm()

        self.lg.info(
            'Migrate virtual machine (VM0) to another node, should succeed with 204'
        )
        node_2 = self.get_random_node(except_node=self.nodeid)
        body = {"nodeid": node_2}
        response = self.vms_api.post_nodes_vms_vmid_migrate(
            self.nodeid, vm['id'], body)
        self.assertEqual(response.status_code, 204)

        time.sleep(30)

        response = self.vms_api.get_nodes_vms_vmid(node_2, vm['id'])
        self.assertEqual(response.status_code, 200)

        pyclient_ip = [x['ip'] for x in self.nodes if x['id'] == node_2]
        self.assertNotEqual(pyclient_ip, [])
        pyclient = Client(pyclient_ip)
        vms = pyclient.client.kvm.list()
        self.assertIn(vm['id'], [x['name'] for x in vms])
示例#9
0
    def setUp(self):
        super().setUp()
        self.storageclusters_api = Storageclusters()

        self.nodeid = self.get_random_node()
        pyclient_ip = [x['ip'] for x in self.nodes
                       if x['id'] == self.nodeid][0]
        self.jwt = self.nodes_api.jwt
        self.pyclient = Client(pyclient_ip, password=self.jwt)

        if self._testMethodName != 'test003_deploy_new_storagecluster':

            self.lg.info('Deploy new storage cluster (SC0)')
            free_disks = self.pyclient.getFreeDisks()
            if free_disks == []:
                self.skipTest('no free disks to create storagecluster')

            self.label = self.rand_str()
            self.servers = randint(1, len(free_disks))
            self.drivetype = 'ssd'

            self.body = {
                "label": self.label,
                "servers": self.servers,
                "driveType": self.drivetype,
                "clusterType": "storage",
                "nodes": [self.nodeid]
            }

            response = self.storageclusters_api.post_storageclusters(self.body)
            self.assertEqual(response.status_code, 201)

            for _ in range(60):
                response = self.storageclusters_api.get_storageclusters_label(
                    self.label)
                if response.status_code == 200:
                    if response.json()['status'] == 'ready':
                        break
                    else:
                        time.sleep(3)
                else:
                    time.sleep(10)
            else:
                self.lg.error(
                    'storagecluster status is not ready after 180 sec')
示例#10
0
    def setUp(self):
        super(TestBridgesAPI, self).setUp()
        self.bridges_api = BridgesAPI()
        self.containers_api = ContainersAPI()
        self.nodes_api = NodesAPI()
        self.createdbridges = []

        self.lg.info('Get random nodid (N0)')
        self.nodeid = self.get_random_node()
        zeroCore_ip = [x['ip'] for x in self.nodes
                       if x['id'] == self.nodeid][0]
        self.root_url = "https://hub.gig.tech/gig-official-apps/ubuntu1604.flist"
        self.jwt = self.nodes_api.jwt
        self.zeroCore = Client(zeroCore_ip, password=self.jwt)
        self.bridge_name = self.rand_str()
        self.nat = self.random_item([False, True])
        self.bridge_body = {
            "name": self.bridge_name,
            "networkMode": "none",
            "nat": self.nat,
            "setting": {}
        }
示例#11
0
class TestVdisks(TestcasesBase):

    def setUp(self):
        super().setUp()
        self.vdisks_apis = VDisksAPIs()
        self.storageclusters_api = Storageclusters()

        node = self.get_random_node()
        pyclient_ip = [x['ip'] for x in self.nodes if x['id'] == node][0]
        self.jwt = self.nodes_api.jwt
        self.pyclient = Client(pyclient_ip, password=self.jwt)

        free_disks = self.pyclient.getFreeDisks()
        if free_disks == []:
            self.skipTest('no free disks to create storagecluster')

        storageclusters = self.storageclusters_api.get_storageclusters()
        if storageclusters.json() == []:
            self.lg.info('Deploy new storage cluster (SC0)')
            sc_label = self.rand_str()
            sc_servers = random.randint(1, len(free_disks))
            sc_drivetype = 'ssd'
            sc_nodes = [node]
            sc_body = {"label": sc_label,
                        "servers": sc_servers,
                        "driveType": sc_drivetype,
                        "clusterType": "storage",
                        "nodes":sc_nodes}

            response = self.storageclusters_api.post_storageclusters(sc_body)
            self.assertEqual(response.status_code, 201)

            for _ in range(60):
                response = self.storageclusters_api.get_storageclusters_label(sc_label)
                if response.status_code == 200:
                    if response.json()['status'] == 'ready':
                        break
                    else:
                        time.sleep(3)
                else:
                    time.sleep(10)
            else:
                self.lg.error('storagecluster status is not ready after 180 sec')

        else:
            sc_label = storageclusters.json()[0]

        self.lg.info('Create vdisk (VD0)')
        self.vd_creation_time = time.time()
        self.vdisk_id = self.rand_str()
        self.size = random.randint(1, 50)
        self.types = ['boot','db','cache','tmp']
        self.type = random.choice(self.types)
        self.block_size = random.randint(1, self.size)*512
        self.storagecluster = sc_label
        self.readOnly = random.choice([False, True])

        self.body = {"id": self.vdisk_id,
                     "size": self.size,
                     "blocksize": self.block_size,
                     "type": self.type,
                     "storagecluster": self.storagecluster,
                     "readOnly":self.readOnly}

        response = self.vdisks_apis.post_vdisks(self.body)
        self.assertEqual(response.status_code, 201) 

    def tearDown(self):
        self.lg.info('Delete vdisk (VD0)')
        self.vdisks_apis.delete_vdisks_vdiskid(self.vdisk_id)
        super(TestVdisks, self).tearDown()

    def test001_get_vdisk_details(self):
        """ GAT-061
        *GET:/vdisks/{vdiskid}*

        **Test Scenario:**

        #. Create vdisk (VD0).
        #. Get vdisk (VD0), should succeed with 200.
        #. Get nonexisting vdisk, should fail with 404.

        """
        self.lg.info('Get vdisk (VD0), should succeed with 200')
        response = self.vdisks_apis.get_vdisks_vdiskid(self.vdisk_id)
        self.assertEqual(response.status_code, 200)
        for key in self.body.keys():
            if not self.readOnly and key == "readOnly":
                continue
            self.assertEqual(self.body[key], response.json()[key])
        self.assertEqual(response.json()['status'], 'halted')

        self.lg.info('Get nonexisting vdisk, should fail with 404')
        response = self.vdisks_apis.get_vdisks_vdiskid('fake_vdisk')
        self.assertEqual(response.status_code, 404)

    def test002_list_vdisks(self):
        """ GAT-062
        *GET:/vdisks*

        **Test Scenario:**

        #. Create vdisk (VD0).
        #. List vdisks, should succeed with 200.

        """
        self.lg.info('List vdisks, should succeed with 200')
        response = self.vdisks_apis.get_vdisks()
        self.assertEqual(response.status_code, 200)
        vd0_data = {"id": self.vdisk_id,
                    "storageCluster": self.storagecluster,
                    "type": self.type}
        self.assertIn(vd0_data, response.json())

    def test003_create_vdisk(self):
        """ GAT-063
        *POST:/vdisks*

        **Test Scenario:**

        #. Create vdisk (VD1). should succeed with 201.
        #. List vdisks, (VD1) should be listed.
        #. Delete vdisk (VD0), should succeed with 204.
        #. Create vdisk with invalid body, should fail with 400.
        """
        self.lg.info('Create vdisk (VD1). should succeed with 201')
        vdisk_id = self.rand_str()
        size = random.randint(1, 50)
        vdisk_type = random.choice(self.types)
        block_size = random.randint(1, self.size)*512
        readOnly = random.choice([False, True])

        body = {"id": vdisk_id,
                "size": size,
                "blocksize": block_size,
                "type": vdisk_type,
                "storagecluster": self.storagecluster,
                "readOnly":readOnly}

        response = self.vdisks_apis.post_vdisks(body)
        self.assertEqual(response.status_code, 201)

        self.lg.info('List vdisks, (VD1) should be listed')
        response = self.vdisks_apis.get_vdisks()
        self.assertEqual(response.status_code, 200)
        self.assertIn(vdisk_id, [x['id'] for x in response.json()])

        self.lg.info('Delete vdisk (VD0), should succeed with 204')
        response = self.vdisks_apis.delete_vdisks_vdiskid(self.vdisk_id)
        self.assertEqual(response.status_code, 204)

        self.lg.info('Create vdisk with invalid body, should fail with 400')
        body = {"id":self.rand_str()}
        response = self.vdisks_apis.post_vdisks(body)
        self.assertEqual(response.status_code, 400)


    def test004_delete_vdisk(self):
        """ GAT-064
        *Delete:/vdisks/{vdiskid}*

        **Test Scenario:**

        #. Create vdisk (VD0).
        #. Delete vdisk (VD0), should succeed with 204.
        #. List vdisks, (VD0) should be gone.
        #. Delete nonexisting vdisk, should fail with 404.
        """
        self.lg.info('Delete vdisk (VD0), should succeed with 204')
        response = self.vdisks_apis.delete_vdisks_vdiskid(self.vdisk_id)
        self.assertEqual(response.status_code, 204)

        self.lg.info('List vdisks, (VD0) should be gone')
        response = self.vdisks_apis.get_vdisks()
        self.assertEqual(response.status_code, 200)
        self.assertNotIn(self.vdisk_id, [x['id'] for x in response.json()])

        self.lg.info('Delete nonexisting vdisk, should fail with 404')
        response = self.vdisks_apis.delete_vdisks_vdiskid('fake_vdisk')
        self.assertEqual(response.status_code, 404)

    def test005_resize_vdisk(self):
        """ GAT-065
        *POST:/vdisks/{vdiskid}/resize*

        **Test Scenario:**

        #. Create vdisk (VD0).
        #. Resize vdisk (VD0), should succeed with 204.
        #. Check that size of volume changed, should succeed.
        #. Resize vdisk (VD0) with value less than the current vdisk size, should fail with 400.
        #. Check vdisk (VD0) size, shouldn't be changed.

        """
        self.lg.info('Resize vdisk (VD0), should succeed with 204')
        new_size = self.size + random.randint(1,10)
        body = {"newSize": new_size}
        response = self.vdisks_apis.post_vdisks_vdiskid_resize(self.vdisk_id, body)
        self.assertEqual(response.status_code, 204)

        self.lg.info('Check that size of volume changed, should succeed')
        response = self.vdisks_apis.get_vdisks_vdiskid(self.vdisk_id)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(new_size, response.json()['size'])
        self.size = new_size

        self.lg.info('Resize vdisk (VD0) with value less than the current vdisk size, should fail with 400')
        new_size = self.size - random.randint(1, self.size-1)
        body = {"newSize": new_size}
        response = self.vdisks_apis.post_vdisks_vdiskid_resize(self.vdisk_id, body)
        self.assertEqual(response.status_code, 400)

        self.lg.info('Check vdisk (VD0) size, shouldn\'t be changed')
        response = self.vdisks_apis.get_vdisks_vdiskid(self.vdisk_id)
        self.assertEqual(response.status_code, 200)
        self.assertNotEqual(new_size, response.json()['size'])


    @unittest.skip('Not implemented')
    def test006_Rollback_vdisk(self):
        """ GAT-066
        *POST:/vdisks/{vdiskid}/rollback*

        **Test Scenario:**

        #. Create vdisk (VD0), should succeed.
        #. Resize vdisk (VD0), should succeed.
        #. Check that size of vdisk (VD0) changed, should succeed.
        #. Rollback vdisk (VD0), should succeed.
        #. Check that vdisk (VD0) size is changed to the initial size, should succeed.
        """

        self.lg.info(' Resize  created volume.')
        new_size = self.size + random.randint(1, 10)
        body = {"newSize": new_size}
        response = self.vdisks_apis.post_volumes_volumeid_resize(self.vdisk_id, body)
        self.assertEqual(response.status_code, 204)

        self.lg.info('Check that size of volume changed, should succeed')
        response = self.vdisks_apis.get_vdisks_vdiskid(self.vdisk_id)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(new_size, response.json()['size'])

        self.lg.info('Rollback vdisk (VD0), should succeed')
        body = {"epoch": self.vd_creation_time}
        response = self.vdisks_apis.post_vdisks_vdiskid_rollback(self.vdisk_id, body)
        self.assertEqual(response.status_code, 204)

        self.lg.info('Check that vdisk (VD0) size is changed to the initial size, should succeed')
        response = self.vdisks_apis.get_vdisks_vdiskid(self.vdisk_id)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(self.size, response.json()['size'])
示例#12
0
class TestNodeidAPI(TestcasesBase):
    def setUp(self):
        super().setUp()
        self.nodes_api = NodesAPI()
        self.jwt = self.nodes_api.jwt
        self.lg.info('Choose one random node of list of running nodes.')
        self.node_id = self.get_random_node()
        if self.node_id is None:
            self.lg.info(' No node found')
            return
        self.node = {}
        for node in self.nodes:
            if node['id'] == self.node_id:
                self.g8os_ip = node['ip']
                self.node = node
                break
        self.python_client = Client(self.g8os_ip, password=self.jwt)

    def test001_list_nodes(self):
        """ GAT-001
        *GET:/node/ Expected: List of all nodes*

        **Test Scenario:**

        #. Send get nodes api request.
        #. Compare results with golden value.
        """
        self.lg.info('send get nodes api request ')
        response = self.nodes_api.get_nodes()
        self.assertEqual(response.status_code, 200)

        self.lg.info('Compare results with golden value.')
        Running_nodes = []
        Nodes_result = response.json()
        for node in Nodes_result:
            if node['status'] == 'running':
                Running_nodes.append(node)
        self.assertEqual(len(Running_nodes), len(self.nodes))
        for node in Running_nodes:
            node_info = [
                item for item in self.nodes if item["id"] == node["id"]
            ]
            self.assertEqual(len(node_info), 1)
            for key in node.keys():
                if key in node_info[0].keys():
                    self.assertEqual(node[key], node_info[0][key])

    def test002_get_nodes_details(self):
        """ GAT-002
        *GET:/nodes/{nodeid} - Expected: id, status, hostname*

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Send get nodes/{nodeid} api request.
        #. Compare results with golden value.
        """
        self.lg.info(' Send get nodes/{nodeid} api request.')
        response = self.nodes_api.get_nodes_nodeid(node_id=self.node_id)
        self.assertEqual(response.status_code, 200)

        self.lg.info('Compare results with golden value.')
        node_details = response.json()
        for key in self.node.keys():
            if key in node_details.keys():
                self.assertEqual(self.node[key], node_details[key])

    def test003_list_jobs(self):
        """ GAT-003
        *GET:/nodes/{nodeid}/jobs - Expected: job list items*

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Send get /nodes/{nodeid}/jobs api request.
        #. Compare results with golden value.
        """
        self.lg.info('Send get /nodes/{nodeid}/jobs api request.')
        response = self.nodes_api.get_nodes_nodeid_jobs(node_id=self.node_id)
        self.assertEqual(response.status_code, 200)

        self.lg.info('Compare results with golden value.')
        jobs = response.json()
        client_jobs = self.python_client.get_jobs_list()
        self.assertEqual(len(jobs), len(client_jobs))
        for job in jobs:
            for client_job in client_jobs:
                if job['id'] == client_job['id']:
                    self.assertEqual(job['startTime'], client_job['starttime'])
                    break

    def test004_kill_jobs(self):
        """ GAT-004
        *DELETE:/nodes/{nodeid}/jobs *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Send get /nodes/{nodeid}/jobs api request.
        #. Check that all jobs has been killed.
        """
        self.lg.info(' Send get /nodes/{nodeid}/jobs api request.')
        response = self.nodes_api.delete_nodes_nodeid_jobs(
            node_id=self.node_id)
        self.assertEqual(response.status_code, 204)

        self.lg.info('Check that all jobs has been killed.')
        response = self.nodes_api.get_nodes_nodeid_jobs(node_id=self.node_id)
        jobs_list = response.json()
        self.assertEqual(len(jobs_list), 6)

    def test005_get_job_details(self):
        """ GAT-005
        *GET:/nodes/{nodeid}/jobs/{jobid} *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Get list of jobs of this node .
        #. Choose one of these jobs to list its details.
        #. Send get /nodes/{nodeid}/jobs/{jobid} api request.
        #. Compare response with the golden values.
        """
        self.lg.info('Get list of jobs of this node .')
        response = self.nodes_api.get_nodes_nodeid_jobs(node_id=self.node_id)
        self.assertEqual(response.status_code, 200)

        self.lg.info('Choose one of these jobs to list its details.')
        jobs_list = response.json()
        job_id = jobs_list[random.randint(0, (len(jobs_list) - 1))]['id']

        self.lg.info('Send get /nodes/{nodeid}/jobs/{jobid} api request.')
        response = self.nodes_api.get_nodes_nodeid_jobs_jobid(
            node_id=self.node_id, job_id=job_id)
        self.assertEqual(response.status_code, 200)

        self.lg.info('Compare response with the golden values.')
        job_details = response.json()
        client_jobs = self.python_client.get_jobs_list()
        for client_job in client_jobs:
            if client_job['id'] == job_id:
                for key in job_details.keys():
                    if key in client_job.keys():
                        self.assertEqual(job_details[key], client_job[key])
                break

    def test006_kill_specific_job(self):
        """ GAT-006
        *DELETE:/nodes/{nodeid}/jobs/{jobid} *

        **Test Scenario:**

        #. Start new job .
        #. delete /nodes/{nodeid}/jobs/{jobid} api.
        #. verify this job has been killed.
        """
        self.lg.info('start new job ')
        job_id = self.python_client.start_job()
        self.assertTrue(job_id)

        self.lg.info(' delete /nodes/{nodeid}/jobs/{jobid} api.')
        response = self.nodes_api.delete_nodes_nodeid_jobs_jobid(
            node_id=self.node_id, job_id=job_id)
        self.assertEqual(response.status_code, 204)

        self.lg.info("verify this job has been killed.")
        jobs = self.python_client.get_jobs_list()
        self.assertFalse(any(job['id'] == job_id for job in jobs))

    def test007_ping_specific_node(self):
        """ GAT-007
        *POST:/nodes/{nodeid}/ping *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Post /nodes/{nodeid}/ping api.
        #. Check response status code.
        """
        self.lg.info('post /nodes/{nodeid}/ping api.')
        response = self.nodes_api.post_nodes_nodeid_ping(node_id=self.node_id)

        self.lg.info('check response status code.')
        self.assertEqual(response.status_code, 200)

    def test008_get_node_state(self):
        """ GAT-008
        *GET:/nodes/{nodeid}/state *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Get /nodes/{nodeid}/state api.
        #. Compare response data with the golden values.
        """
        self.lg.info(' get /nodes/{nodeid}/state api.')
        response = self.nodes_api.get_nodes_nodeid_state(node_id=self.node_id)
        self.assertEqual(response.status_code, 200)

        self.lg.info('Compare response data with the golden values.')
        client_state = self.python_client.get_node_state()
        node_state = response.json()
        for key in node_state.keys():
            if key in client_state.keys():
                self.assertAlmostEqual(node_state[key],
                                       client_state[key],
                                       delta=6000000,
                                       msg='different value for key%s' % key)

    @unittest.skip("https://github.com/zero-os/0-core/issues/125, wontfix")
    def test009_reboot_node(self):
        """ GAT-009
        *POST:/nodes/{nodeid}/reboot *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. post /nodes/{nodeid}/reboot api.
        #. verify that this node has been rebooted.
        #. Ping node should succeed
        """
        self.lg.info('post /nodes/{nodeid}/reboot api.')
        response = self.nodes_api.post_nodes_nodeid_reboot(
            node_id=self.node_id)
        self.assertEqual(response.status_code, 204)

        self.lg.info('verify that this node has been rebooted.')
        content = response.json()
        self.assertEqual(content, 'Machine reboot signal sent successfully')

    def test010_get_cpus_details(self):
        """ GAT-010
        *GET:/nodes/{nodeid}/cpus *

        **Test Scenario:**

        #. Choose one random node from list of running nodes.
        #. get /nodes/{nodeid}/cpus api.
        #. compare response data with the golden values.

        """
        self.lg.info('get /nodes/{nodeid}/cpus api.')
        response = self.nodes_api.get_nodes_nodeid_cpus(node_id=self.node_id)
        self.assertEqual(response.status_code, 200)

        self.lg.info('compare response data with the golden values.')
        result = self.python_client.get_nodes_cpus()
        cpus_info = response.json()
        for i, cpu_info in enumerate(cpus_info):
            for key in cpu_info.keys():
                if key in result[i].keys():
                    if key != 'cores' and key != 'mhz':
                        self.assertEqual(cpu_info[key], result[i][key],
                                         "different cpu info for key %s" % key)

    def test011_get_disks_details(self):
        """ GAT-011
        *GET:/nodes/{nodeid}/disks *

        **Test Scenario:**

        #. Choose one random node from list of running nodes.
        #. Get /nodes/{nodeid}/disks api.
        #. Compare response data with the golden values.
        """
        self.lg.info('get /nodes/{nodeid}/disks api.')
        response = self.nodes_api.get_nodes_nodeid_disks(node_id=self.node_id)
        self.assertEqual(response.status_code, 200)
        disks_info = response.json()
        self.lg.info('compare response data with the golden values.')
        result = self.python_client.get_nodes_disks()
        self.assertEqual(result, disks_info)

    def test012_get_memmory_details(self):
        """ GAT-012
        *GET:/nodes/{nodeid}/mem *

        **Test Scenario:**

        #. Choose one random node from list of running nodes.
        #. get /nodes/{nodeid}/mem api.
        #. compare response data with the golden values.
        """
        self.lg.info('get /nodes/{nodeid}/mem api.')
        response = self.nodes_api.get_nodes_nodeid_mem(node_id=self.node_id)
        self.assertEqual(response.status_code, 200)

        self.lg.info('compare response data with the golden values.')
        result = self.python_client.get_nodes_mem()
        memory_info = response.json()
        for key in memory_info.keys():
            if key in result.keys():
                self.assertAlmostEqual(memory_info[key],
                                       result[key],
                                       msg="different keys%s" % key,
                                       delta=10000000)

    def test013_get_nics_details(self):
        """ GAT-013
        *GET:/nodes/{nodeid}/nics - network interface information*

        **Test Scenario:**

        #. Choose one random node from list of running nodes.
        #. Get /nodes/{nodeid}/nics api.
        #. compare response data with the golden values.
        """
        self.lg.info('get /nodes/{nodeid}/nics api.')
        response = self.nodes_api.get_nodes_nodeid_nics(node_id=self.node_id)
        self.assertEqual(response.status_code, 200)

        self.lg.info('compare response data with the golden values.')
        golden_result = self.python_client.get_nodes_nics()
        nics_info = response.json()
        self.assertEqual(len(nics_info), len(golden_result))
        for nic_info in nics_info:
            for nic_result in golden_result:
                if nic_result['name'] == nic_info['name']:
                    for key in nic_info.keys():
                        if key in nic_result.keys():
                            self.assertEqual(
                                nic_info[key], nic_result[key],
                                'different value for key %s' % key)
                            break

    def test014_get_os_info_details(self):
        """ GAT-014
        *GET:/nodes/{nodeid}/info - os information*

        **Test Scenario:**

        #. Choose one random node from list of running nodes.
        #. Get /nodes/{nodeid}/info api.
        #. ompare response data with the golden values.
        """
        self.lg.info('Get /nodes/{nodeid}/info api.')
        response = self.nodes_api.get_nodes_nodeid_info(node_id=self.node_id)
        self.assertEqual(response.status_code, 200)

        self.lg.info('compare response data with the golden values.')
        result = self.python_client.get_nodes_info()
        node_info = response.json()
        for key in node_info.keys():
            if key in result.keys():
                self.assertEqual(node_info[key], result[key])

    def test015_list_processes(self):
        """ GAT-015
        *GET:/nodes/{nodeid}/process *

        **Test Scenario:**

        #. Choose one random node from list of running nodes.
        #. get /nodes/{nodeid}/processes api.
        #. compare response data with the golden values.
        """
        self.lg.info('Get /nodes/{nodeid}/process api.')
        response = self.nodes_api.get_nodes_nodeid_processes(
            node_id=self.node_id)
        self.assertEqual(response.status_code, 200)

        self.lg.info('compare response data with the golden values.')
        processes = {}
        client_processes = {}
        client_result = self.python_client.get_processes_list()
        for process in client_result:
            client_processes[process['pid']] = process

        for process in response.json():
            processes[process['pid']] = process
        skip_keys = ['cpu', 'vms', 'rss']
        for process_id in processes.keys():
            process_info = processes[process_id]
            for info in process_info.keys():
                if info not in skip_keys:
                    if info in client_processes[process_id].keys():
                        self.assertEqual(process_info[info],
                                         client_processes[process_id][info],
                                         "different value with key%s" % info)

    def test016_get_process_details(self):
        """ GAT-016
        *GET:/nodes/{nodeid}/processes/{processid} *

        **Test Scenario:**

        #. Choose one random node from list of running nodes.
        #. Get list of running processes
        #. choose one of them.
        #. Get /nodes/{nodeid}/processes/{processid} api.
        #. compare response data with the golden values.

        """
        self.lg.info('Get list of running processes')
        response = self.nodes_api.get_nodes_nodeid_processes(
            node_id=self.node_id)
        self.assertEqual(response.status_code, 200)
        processes_list = response.json()

        self.lg.info('Choose one of these processes to list its details.')
        process_id = processes_list[random.randint(0,
                                                   len(processes_list) -
                                                   1)]['pid']

        self.lg.info('Get /nodes/{nodeid}/process/{processid} api.')
        response = self.nodes_api.get_nodes_nodeid_processes_processid(
            node_id=self.node_id, process_id=str(process_id))
        self.assertEqual(response.status_code, 200)

        self.lg.info('Compare response data with the golden values.')
        process_info = response.json()
        client_result = self.python_client.get_processes_list()
        for process in client_result:
            if process['pid'] == process_info['pid']:
                for info in process_info.keys():
                    if info != 'cpu':
                        if info in process.keys():
                            self.assertEqual(
                                process_info[info], process[info],
                                "different value with key%s" % info)
                break

    def test017_delete_process(self):
        """ GAT-017
        *DELETE:/nodes/{nodeid}/processes/{processid} *

        **Test Scenario:**

        #. Start new process.
        #. Delete /nodes/{nodeid}/processes/{processid} api.
        #. Make sure that this process has been killed.

        """
        self.lg.info('Start new process.')
        process_id = self.python_client.start_process()
        self.assertTrue(process_id)

        self.lg.info('delete /nodes/{nodeid}/processes/{processid} api.')
        response = self.nodes_api.delete_nodes_nodeid_process_processid(
            node_id=self.node_id, process_id=str(process_id))
        self.assertEqual(response.status_code, 204)

        self.lg.info('Make sure that this process has been killed.')
        client_processes = self.python_client.get_processes_list()
        self.assertFalse(
            any(process['pid'] == process_id for process in client_processes))
示例#13
0
class TestVmsAPI(TestcasesBase):
    def setUp(self):
        super().setUp()
        self.vms_api = VmsAPI()
        self.storageclusters_api = Storageclusters()
        self.vdisks_apis = VDisksAPIs()
        self.lg.info('Get random nodid (N0)')
        self.nodeid = self.get_random_node()
        nodeip = [x['ip'] for x in self.nodes if x['id'] == self.nodeid][0]
        self.jwt = self.nodes_api.jwt
        self.pyclient = Client(nodeip, password=self.jwt)

        storageclusters = self.storageclusters_api.get_storageclusters()
        if storageclusters.json() == []:
            self.storagecluster = self.create_sotragecluster()['label']
        else:
            self.storagecluster = storageclusters.json()[0]

        vdisks = self.vdisks_apis.get_vdisks()
        vdisks = [
            x for x in vdisks.json()
            if (x['id'] == 'ubuntu-test-vdisk'
                and x['storageCluster'] == self.storagecluster)
        ]
        if vdisks == []:
            self.vdisk = self.create_boot_vdisk(self.storagecluster)
        else:
            self.vdisk = vdisks[0]

    def tearDown(self):
        self.lg.info('Delete virtual machine (VM0)')
        response = self.vms_api.get_nodes_vms(self.nodeid)
        if response.status_code == 200:
            vms = response.json()
            for vm in vms:
                self.vms_api.delete_nodes_vms_vmid(self.nodeid, vm['id'])

        super(TestVmsAPI, self).tearDown()

    def create_sotragecluster(self):
        free_disks = self.pyclient.getFreeDisks()
        if free_disks == []:
            self.skipTest('no free disks to create storagecluster')

        self.lg.info('Deploy new storage cluster (SC0)')
        label = self.rand_str()
        servers = random.randint(1, len(free_disks))
        drivetype = 'ssd'
        nodes = [self.nodeid]
        body = {
            "label": label,
            "servers": servers,
            "driveType": drivetype,
            "clusterType": "storage",
            "nodes": nodes
        }

        response = self.storageclusters_api.post_storageclusters(body)
        self.assertEqual(response.status_code, 201)

        for _ in range(60):
            response = self.storageclusters_api.get_storageclusters_label(
                label)
            if response.status_code == 200:
                if response.json()['status'] == 'ready':
                    break
                else:
                    time.sleep(3)
            else:
                time.sleep(10)
        else:
            self.lg.error('storagecluster status is not ready after 180 sec')

        return body

    def create_boot_vdisk(self, storagecluster):
        body = {
            "id": 'ubuntu-test-vdisk',
            "size": 15,
            "blocksize": 4096,
            "type": 'boot',
            "storagecluster": storagecluster,
            "templatevdisk": "ardb://hub.gig.tech:16379/template:ubuntu-1604"
        }

        response = self.vdisks_apis.post_vdisks(body)
        self.assertEqual(response.status_code, 201)
        return body

    def create_vm(self):
        self.lg.info('Create virtual machine (VM0) on node (N0)')
        vmid = self.random_string()
        mem = 1024
        cpu = 1
        nics = []
        disks = [{"vdiskid": "ubuntu-test-vdisk", "maxIOps": 2000}]
        userCloudInit = {}
        systemCloudInit = {}

        body = {
            "id": vmid,
            "memory": mem,
            "cpu": cpu,
            "nics": nics,
            "disks": disks,
            "userCloudInit": userCloudInit,
            "systemCloudInit": systemCloudInit
        }

        response = self.vms_api.post_nodes_vms(self.nodeid, body)
        self.assertEqual(response.status_code, 201)

        for _ in range(60):
            response = self.vms_api.get_nodes_vms_vmid(self.nodeid, vmid)
            if response.status_code == 200:
                if response.json()['status'] == 'running':
                    break
                else:
                    time.sleep(3)
            else:
                time.sleep(10)
        else:
            self.lg.error('vm status is not running after 180 sec')

        return body

    def test001_get_nodes_vms_vmid(self):
        """ GAT-067
        **Test Scenario:**

        #. Get random nodid (N0).
        #. Create virtual machine (VM0) on node (N0).
        #. Get virtual machine (VM0), should succeed with 200.
        #. Get nonexisting virtual machine, should fail with 404.
        """
        self.lg.info('Create virtual machine (VM0) on node (N0)')
        vm = self.create_vm()

        self.lg.info('Get virtual machine (VM0), should succeed with 200')
        response = self.vms_api.get_nodes_vms_vmid(self.nodeid, vm['id'])
        self.assertEqual(response.status_code, 200)
        keys_to_check = ['id', 'memory', 'cpu', 'nics', 'disks']
        for key in keys_to_check:
            self.assertEqual(vm[key], response.json()[key])
        self.assertEqual(response.json()['status'], 'running')

        vms_list = self.pyclient.client.kvm.list()
        self.assertIn(vm['id'], [x['name'] for x in vms_list])

        self.lg.info('Get nonexisting virtual machine, should fail with 404')
        response = self.vms_api.get_nodes_vms_vmid(self.nodeid, 'fake_vm')
        self.assertEqual(response.status_code, 404)

    def test002_get_node_vms(self):
        """ GAT-068
        **Test Scenario:**

        #. Get random nodid (N0).
        #. Create virtual machine (VM0) on node (N0).
        #. List node (N0) virtual machines, virtual machine (VM0) should be listed, should succeed with 200.
        """
        self.lg.info('Create virtual machine (VM0) on node (N0)')
        vm = self.create_vm()

        self.lg.info(
            'List node (N0) virtual machines, virtual machine (VM0) should be listed, should succeed with 200'
        )
        response = self.vms_api.get_nodes_vms(self.nodeid)
        self.assertEqual(response.status_code, 200)
        self.assertIn(vm['id'], [x['id'] for x in response.json()])

    def test003_post_node_vms(self):
        """ GAT-069
        **Test Scenario:**

        #. Get random nodid (N0).
        #. Create virtual machine (VM1) on node (N0).
        #. Get virtual machine (VM1), should succeed with 200.
        #. List kvms in python client, (VM1) should be listed.
        #. Delete virtual machine (VM1), should succeed with 204.
        #. Create virtual machine with missing parameters, should fail with 400.
        """
        self.lg.info('Create virtual machine (VM1) on node (N0)')
        vm_id = self.random_string()
        vm_mem = random.randint(1, 16) * 1024
        vm_cpu = random.randint(1, 16)
        vm_nics = []
        vm_disks = [{"vdiskid": "ubuntu-test-vdisk", "maxIOps": 2000}]
        vm_userCloudInit = {}
        vm_systemCloudInit = {}

        body = {
            "id": vm_id,
            "memory": vm_mem,
            "cpu": vm_cpu,
            "nics": vm_nics,
            "disks": vm_disks,
            "userCloudInit": vm_userCloudInit,
            "systemCloudInit": vm_systemCloudInit
        }

        response = self.vms_api.post_nodes_vms(self.nodeid, body)
        self.assertEqual(response.status_code, 201)
        time.sleep(20)

        response = self.vms_api.get_nodes_vms_vmid(self.nodeid, vm_id)
        self.assertEqual(response.status_code, 200)

        if response.json()['status'] == 'error':
            vm_id = self.rand_str()
            body['id'] = vm_id
            body['memory'] = 1024
            body['cpu'] = 1
            response = self.vms_api.post_nodes_vms(self.nodeid, body)
            self.assertEqual(response.status_code, 201)

        self.lg.info('Get virtual machine (VM1), should succeed with 200')
        response = self.vms_api.get_nodes_vms_vmid(self.nodeid, vm_id)
        self.assertEqual(response.status_code, 200)
        keys_to_check = ['id', 'memory', 'cpu', 'nics', 'disks']
        for key in keys_to_check:
            self.assertEqual(body[key], response.json()[key])
        self.assertEqual(response.json()['status'], 'deploying')

        for _ in range(60):
            response = self.vms_api.get_nodes_vms_vmid(self.nodeid, vm_id)
            if response.status_code == 200:
                if response.json()['status'] == 'running':
                    break
                else:
                    time.sleep(3)
            else:
                time.sleep(10)
        else:
            raise AssertionError('{} != {}'.format(response.json()['status'],
                                                   'running'))

        self.lg.info('List kvms in python client, (VM1) should be listed')
        vms = self.pyclient.client.kvm.list()
        self.assertIn(vm_id, [x['name'] for x in vms])

        self.lg.info('Delete virtual machine (VM1), should succeed with 204')
        response = self.vms_api.delete_nodes_vms_vmid(self.nodeid, vm_id)
        self.assertEqual(response.status_code, 204)

        self.lg.info(
            'Create virtual machine with missing parameters, should fail with 400'
        )
        body = {"id": self.random_string()}
        response = self.vms_api.post_nodes_vms(self.nodeid, body)
        self.assertEqual(response.status_code, 400)

    # @unittest.skip('https://github.com/g8os/resourcepool/issues/126')
    def test004_put_nodes_vms_vmid(self):
        """ GAT-070
        **Test Scenario:**

        #. Get random nodid (N0).
        #. Create virtual machine (VM0) on node (N0).
        #. Update virtual machine (VM1), should succeed with 201.
        #. Get virtual machine (VM1), should succeed with 200.
        #. Update virtual machine with missing parameters, should fail with 400.
        """
        self.lg.info('Create virtual machine (VM0) on node (N0)')
        vm = self.create_vm()

        self.lg.info('Create virtual machine (VM0) on node (N0)')
        vm_mem = 2 * 1024
        vm_cpu = 2
        vm_nics = []
        vm_disks = [{"vdiskid": "ubuntu-test-vdisk", "maxIOps": 2000}]
        body = {
            "memory": vm_mem,
            "cpu": vm_cpu,
            "nics": vm_nics,
            "disks": vm_disks
        }

        self.lg.info('Stop virtual machine (VM0), should succeed with 204')
        response = self.vms_api.post_nodes_vms_vmid_stop(self.nodeid, vm['id'])
        self.assertEqual(response.status_code, 204)

        self.lg.info(
            'Get virtual machine (VM0), virtual machine (VM0) status should be halting'
        )
        for _ in range(20):
            response = self.vms_api.get_nodes_vms_vmid(self.nodeid, vm['id'])
            self.assertEqual(response.status_code, 200)
            status = response.json()['status']
            if status == 'halted':
                break
            else:
                time.sleep(3)
        else:
            self.lg.error('can\'t stop vm')

        response = self.vms_api.put_nodes_vms_vmid(self.nodeid, vm['id'], body)
        self.assertEqual(response.status_code, 204)

        self.lg.info('Start virtual machine (VM0), should succeed with 204')
        response = self.vms_api.post_nodes_vms_vmid_start(
            self.nodeid, vm['id'])
        self.assertEqual(response.status_code, 204)
        for _ in range(20):
            response = self.vms_api.get_nodes_vms_vmid(self.nodeid, vm['id'])
            self.assertEqual(response.status_code, 200)
            status = response.json()['status']
            if status == 'running':
                break
            else:
                time.sleep(3)
        else:
            self.lg.error('can\'t start vm')

        self.lg.info('Get virtual machine (VM0), should succeed with 200')
        response = self.vms_api.get_nodes_vms_vmid(self.nodeid, vm['id'])
        self.assertEqual(response.status_code, 200)

        keys_to_check = ['memory', 'cpu', 'nics', 'disks']
        for key in keys_to_check:
            self.assertEqual(body[key], response.json()[key])
        self.assertEqual(response.json()['status'], 'running')

        self.lg.info(
            'Update virtual machine with missing parameters, should fail with 400'
        )
        body = {"id": self.random_string()}
        response = self.vms_api.put_nodes_vms_vmid(self.nodeid, vm['id'], body)
        self.assertEqual(response.status_code, 400)

    def test005_get_nodes_vms_vmid_info(self):
        """ GAT-071
        **Test Scenario:**

        #. Get random nodid (N0).
        #. Create virtual machine (VM0) on node (N0).
        #. Get virtual machine (VM0) info, should succeed with 200.
        #. Get nonexisting virtual machine info, should fail with 404.
        """
        self.lg.info('Create virtual machine (VM0) on node (N0)')
        vm = self.create_vm()

        self.lg.info('Get virtual machine (VM0) info, should succeed with 200')
        response = self.vms_api.get_nodes_vms_vmid_info(self.nodeid, vm['id'])
        self.assertEqual(response.status_code, 200)

        self.lg.info(
            'Get nonexisting virtual machine info, should fail with 404')
        response = self.vms_api.get_nodes_vms_vmid_info(self.nodeid, 'fake_vm')

    def test006_delete_nodes_vms_vmid(self):
        """ GAT-072
        **Test Scenario:**

        #. Get random nodid (N0).
        #. Create virtual machine (VM0) on node (N0).
        #. Delete virtual machine (VM0), should succeed with 204.
        #. List kvms in python client, (VM0) should be gone.
        #. Delete nonexisting virtual machine, should fail with 404.
        """
        self.lg.info('Create virtual machine (VM0) on node (N0)')
        vm = self.create_vm()

        self.lg.info('Delete virtual machine (VM0), should succeed with 204')
        response = self.vms_api.delete_nodes_vms_vmid(self.nodeid, vm['id'])
        self.assertEqual(response.status_code, 204)

        self.lg.info('List kvms in python client, (VM0) should be gone')
        vms = self.pyclient.client.kvm.list()
        self.assertNotIn(vm['id'], [x['name'] for x in vms])

        self.lg.info(
            'Delete nonexisting virtual machine, should fail with 404')
        response = self.vms_api.delete_nodes_vms_vmid(self.nodeid,
                                                      'fake_vm_id')
        self.assertEqual(response.status_code, 404)

    def test007_post_nodes_vms_vmid_start(self):
        """ GAT-073
        **Test Scenario:**

        #. Get random nodid (N0).
        #. Create virtual machine (VM0) on node (N0).
        #. Stop virtual machine (VM0), should succeed with 204.
        #. Start virtual machine (VM0), should succeed with 204.
        #. Get virtual machine (VM0), virtual machine (VM0) status should be running.
        """
        self.lg.info('Create virtual machine (VM0) on node (N0)')
        vm = self.create_vm()

        self.lg.info('Stop virtual machine (VM0), should succeed with 204')
        response = self.vms_api.post_nodes_vms_vmid_stop(self.nodeid, vm['id'])
        self.assertEqual(response.status_code, 204)
        for _ in range(20):
            response = self.vms_api.get_nodes_vms_vmid(self.nodeid, vm['id'])
            self.assertEqual(response.status_code, 200)
            status = response.json()['status']
            if status == 'halted':
                break
            else:
                time.sleep(3)
        else:
            raise AssertionError('{} is not {}'.format(status, 'halted'))

        vms = self.pyclient.client.kvm.list()
        vm0 = [x for x in vms if x['name'] == vm['id']]
        self.assertEqual(vm0, [])

        self.lg.info('Start virtual machine (VM0), should succeed with 204')
        response = self.vms_api.post_nodes_vms_vmid_start(
            self.nodeid, vm['id'])
        self.assertEqual(response.status_code, 204)
        for _ in range(20):
            response = self.vms_api.get_nodes_vms_vmid(self.nodeid, vm['id'])
            self.assertEqual(response.status_code, 200)
            status = response.json()['status']
            if status == 'running':
                break
            else:
                time.sleep(3)
        else:
            raise AssertionError('{} is not {}'.format(status, 'running'))

        vms = self.pyclient.client.kvm.list()
        vm0 = [x for x in vms if x['name'] == vm['id']]
        self.assertNotEqual(vm0, [])
        self.assertEquals(vm0[0]['state'], 'running')

    def test008_post_nodes_vms_vmid_stop(self):
        """ GAT-074
        **Test Scenario:**

        #. Get random nodid (N0).
        #. Create virtual machine (VM0) on node (N0).
        #. Stop virtual machine (VM0), should succeed with 204.
        #. Get virtual machine (VM0), virtual machine (VM0) status should be halting.
        """
        self.lg.info('Create virtual machine (VM0) on node (N0)')
        vm = self.create_vm()

        self.lg.info('Stop virtual machine (VM0), should succeed with 204')
        response = self.vms_api.post_nodes_vms_vmid_stop(self.nodeid, vm['id'])
        self.assertEqual(response.status_code, 204)

        self.lg.info(
            'Get virtual machine (VM0), virtual machine (VM0) status should be halting'
        )
        for _ in range(20):
            response = self.vms_api.get_nodes_vms_vmid(self.nodeid, vm['id'])
            self.assertEqual(response.status_code, 200)
            status = response.json()['status']
            if status == 'halted':
                break
            else:
                time.sleep(3)
        else:
            raise AssertionError('{} != {}'.format(status, 'halted'))

        vms = self.pyclient.client.kvm.list()
        vm0 = [x for x in vms if x['name'] == vm['id']]
        self.assertEqual(vm0, [])

    def test009_post_nodes_vms_vmid_pause_resume(self):
        """ GAT-075
        **Test Scenario:**

        #. Get random nodid (N0).
        #. Create virtual machine (VM0) on node (N0).
        #. Pause virtual machine (VM0), should succeed with 204.
        #. Get virtual machine (VM0), virtual machine (VM0) status should be paused.
        #. Resume virtual machine (VM0), should succeed with 204.
        #. Get virtual machine (VM0), virtual machine (VM0) status should be running
        """
        self.lg.info('Create virtual machine (VM0) on node (N0)')
        vm = self.create_vm()

        self.lg.info('Pause virtual machine (VM0), should succeed with 204')
        response = self.vms_api.post_nodes_vms_vmid_pause(
            self.nodeid, vm['id'])
        self.assertEqual(response.status_code, 204)

        self.lg.info(
            'Get virtual machine (VM0), virtual machine (VM0) status should be halting'
        )
        for _ in range(15):
            response = self.vms_api.get_nodes_vms_vmid(self.nodeid, vm['id'])
            self.assertEqual(response.status_code, 200)
            status = response.json()['status']
            if status == 'paused':
                break
            else:
                time.sleep(1)
        else:
            raise AssertionError('{} != {}'.format(status, 'paused'))

        vms = self.pyclient.client.kvm.list()
        vm0 = [x for x in vms if x['name'] == vm['id']]
        self.assertNotEqual(vm0, [])
        self.assertEquals(vm0[0]['state'], 'paused')

        self.lg.info('Resume virtual machine (VM0), should succeed with 204')
        response = self.vms_api.post_nodes_vms_vmid_resume(
            self.nodeid, vm['id'])
        self.assertEqual(response.status_code, 204)

        self.lg.info(
            'Get virtual machine (VM0), virtual machine (VM0) status should be running'
        )
        for _ in range(15):
            response = self.vms_api.get_nodes_vms_vmid(self.nodeid, vm['id'])
            self.assertEqual(response.status_code, 200)
            status = response.json()['status']
            if status == 'running':
                break
            else:
                time.sleep(1)
        else:
            raise AssertionError('{} != {}'.format(status, 'paused'))

        vms = self.pyclient.client.kvm.list()
        vm0 = [x for x in vms if x['name'] == vm['id']]
        self.assertNotEqual(vm0, [])
        self.assertEquals(vm0[0]['state'], 'running')

    @unittest.skip('https://github.com/g8os/resourcepool/issues/128')
    def test010_post_nodes_vms_vmid_shutdown(self):
        """ GAT-076
        **Test Scenario:**

        #. Get random nodid (N0).
        #. Create virtual machine (VM0) on node (N0).
        #. Shutdown virtual machine (VM0), should succeed with 204.
        #. Get virtual machine (VM0), virtual machine (VM0) status should be halted.
        """
        self.lg.info('Create virtual machine (VM0) on node (N0)')
        vm = self.create_vm()

        self.lg.info('Shutdown virtual machine (VM0), should succeed with 204')
        response = self.vms_api.post_nodes_vms_vmid_shutdown(
            self.nodeid, vm['id'])
        self.assertEqual(response.status_code, 204)
        for _ in range(15):
            response = self.vms_api.get_nodes_vms_vmid(self.nodeid, vm['id'])
            self.assertEqual(response.status_code, 200)
            status = response.json()['status']
            if status in ['halting', 'halted']:
                break
            else:
                time.sleep(1)
        else:
            raise AssertionError('{} not {}'.format(status,
                                                    'halting or halted'))

        vms = self.pyclient.client.kvm.list()
        vm0 = [x for x in vms if x['name'] == vm['id']]
        self.assertEqual(vm0, [])

    @unittest.skip('https://github.com/g8os/resourcepool/issues/215')
    def test011_post_nodes_vms_vmid_migrate(self):
        """ GAT-077
        **Test Scenario:**

        #. Get random nodid (N0).
        #. Create virtual machine (VM0) on node (N0).
        #. Migrate virtual machine (VM0) to another node, should succeed with 204.
        #. Get virtual machine (VM0), virtual machine (VM0) status should be migrating.
        """
        if len(self.nodes) < 2:
            self.skipTest('need at least 2 nodes')

        self.lg.info('Create virtual machine (VM0) on node (N0)')
        vm = self.create_vm()

        self.lg.info(
            'Migrate virtual machine (VM0) to another node, should succeed with 204'
        )
        node_2 = self.get_random_node(except_node=self.nodeid)
        body = {"nodeid": node_2}
        response = self.vms_api.post_nodes_vms_vmid_migrate(
            self.nodeid, vm['id'], body)
        self.assertEqual(response.status_code, 204)

        time.sleep(30)

        response = self.vms_api.get_nodes_vms_vmid(node_2, vm['id'])
        self.assertEqual(response.status_code, 200)

        pyclient_ip = [x['ip'] for x in self.nodes if x['id'] == node_2]
        self.assertNotEqual(pyclient_ip, [])
        pyclient = Client(pyclient_ip)
        vms = pyclient.client.kvm.list()
        self.assertIn(vm['id'], [x['name'] for x in vms])
示例#14
0
class TestcontaineridAPI(TestcasesBase):
    def setUp(self):
        super().setUp()
        self.containers_api = ContainersAPI()
        self.lg.info('Choose one random node of list of running nodes.')
        self.node_id = self.get_random_node()
        if self.node_id is None:
            self.lg.info(' No node found')
            return
        self.node = {}
        for node in self.nodes:
            if node['id'] == self.node_id:
                self.g8os_ip = node['ip']
                self.node = node
                break

        self.jwt = self.nodes_api.jwt
        self.g8core = Client(self.g8os_ip, password=self.jwt)

        self.root_url = "https://hub.gig.tech/gig-official-apps/ubuntu1604.flist"
        self.storage = "ardb://hub.gig.tech:16379"
        self.container_name = self.rand_str()
        self.hostname = self.rand_str()
        self.job_body = {'name': 'yes'}
        self.container_body = {
            "name": self.container_name,
            "hostname": self.hostname,
            "flist": self.root_url,
            "hostNetworking": False,
            "initProcesses": [],
            "filesystems": [],
            "ports": [],
            "storage": self.storage
        }

    def tearDown(self):
        self.lg.info('TearDown:delete all created container ')
        for container in self.createdcontainer:
            self.containers_api.delete_containers_containerid(
                container['node'], container['container'])

    def test001_list_containers(self):
        """ GAT-022
        *GET:/node/{nodeid}/containers Expected: List of all running containers *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Send get nodes/{nodeid}/containers api request.
        #. Compare results with golden value.
        """
        containers_id = []
        Running_containers_list = []
        self.lg.info('Send get nodes/{nodeid}/containers api request.')
        response = self.containers_api.get_containers(self.node_id)
        self.assertEqual(response.status_code, 200)
        self.lg.info('Compare results with golden value.')
        containers_list = response.json()
        for container in containers_list:
            if container['status'] == "running":
                Running_containers_list.append(container)
        golden_value_list = self.g8core.client.container.list()
        self.assertEqual(len(Running_containers_list), len(golden_value_list))
        for container in Running_containers_list:
            if container['name']:
                self.assertTrue(
                    self.g8core.client.container.find(container['name']),
                    'container %s not in golden value ' % container['name'])

    def test002_create_containers(self):
        """ GAT-023
        *post:/node/{nodeid}/containers Expected: create container then delete it *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Send post nodes/{nodeid}/containers api request.
        #. Make sure it created with required values, should succeed.
        #. Delete ctreated container,should succeed
        #. make sure that it deleted .
        """

        self.lg.info('Send post nodes/{nodeid}/containers api request.')
        response = self.containers_api.post_containers(
            nodeid=self.node_id, data=self.container_body)
        self.assertEqual(response.status_code, 201)

        self.lg.info(
            'Make sure it created with required values, should succeed.')
        self.assertEqual(
            response.headers['Location'],
            "/nodes/%s/containers/%s" % (self.node_id, self.container_name))
        response = self.containers_api.get_containers_containerid(
            self.node_id, self.container_name)
        self.assertEqual(response.status_code, 200)
        response_data = response.json()
        for key in response_data.keys():
            if key == 'initprocesses':
                self.assertEqual(response_data[key],
                                 self.container_body['initProcesses'])
                continue
            if key in self.container_body.keys():
                self.assertEqual(response_data[key], self.container_body[key])

        self.lg.info('delete created container')
        response = self.containers_api.delete_containers_containerid(
            self.node_id, self.container_name)
        self.assertEqual(response.status_code, 204)

        self.lg.info('Make sure that it deleted ')
        response = self.containers_api.get_containers(self.node_id)
        containers_list = response.json()
        self.assertFalse(
            any(container['name'] == self.container_name
                for container in containers_list))
        self.assertFalse(
            self.g8core.client.container.find(self.container_name),
            'container %s still exist in g8os ' % self.container_name)

    def test003_get_container_details(self):
        """ GAT-024
        *get:/node/{nodeid}/containers/containerid Expected: get container details *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Choose one random conatainer of list of running containers.
        #. Get:/node/{nodeid}/containers/containerid
        #. Compare results with golden value.

        """
        self.lg.info('Choose random container of list of running nodes')
        container_name = self.create_contaienr(self.node_id)
        self.assertTrue(container_name)

        self.lg.info(
            'Send get nodes/{nodeid}/containers/containerid api request.')
        response = self.containers_api.get_containers_containerid(
            self.node_id, container_name)
        self.assertEqual(response.status_code, 200)
        data = response.json()

        self.lg.info(' Compare results with golden value.')
        golden_value = self.g8core.get_container_info(container_name)
        self.assertTrue(golden_value)
        for key in data.keys():
            if key in golden_value.keys():
                self.assertEqual(data[key], golden_value[key])

    def test004_stop_and_start_container(self):
        """ GAT-025
        *post:/node/{nodeid}/containers/containerid/start Expected: get container details *

        **Test Scenario:**

        #. Create container.
        #. post:/node/{nodeid}/containers/containerid/stop.
        #. Check that container stpoed .
        #. Post:/node/{nodeid}/containers/containerid/start.
        #. Check that container running .

        """
        self.lg.info('Create container ')
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": self.container_name
        })

        self.lg.info('post:/node/{nodeid}/containers/containerid/stop.')
        response = self.containers_api.post_containers_containerid_stop(
            self.node_id, self.container_name)
        self.assertEqual(response.status_code, 204)

        self.lg.info('Check that container stoped.')
        self.assertTrue(
            self.g8core.wait_on_container_update(self.container_name, 60,
                                                 True))

        self.lg.info('post:/node/{nodeid}/containers/containerid/start.')
        response = self.containers_api.post_containers_containerid_start(
            self.node_id, self.container_name)
        self.assertEqual(response.status_code, 201)

        self.lg.info('Check that container running.')
        self.assertTrue(
            self.g8core.wait_on_container_update(self.container_name, 60,
                                                 False))

    def test005_get_running_jobs(self):
        """ GAT-026
        *get:/node/{nodeid}/containers/containerid/jobs Expected: get container details *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Choose one random conatainer of list of running containers.
        #. Get:/node/{nodeid}/containers/containerid/jobs
        #. Compare results with golden value.

        """
        self.lg.info('Choose random container of list of running nodes')
        container_name = self.create_contaienr(self.node_id)
        self.assertTrue(container_name)

        self.lg.info(
            'Send get nodes/{nodeid}/containers/containerid/jobs api request.')
        response = self.containers_api.get_containers_containerid_jobs(
            self.node_id, container_name)
        self.assertEqual(response.status_code, 200)

        self.lg.info('Compare results with golden value.')
        running_jobs_list = response.json()
        golden_values = self.g8core.get_container_job_list(container_name)

        api_jobs = set([(job['id'], job['startTime'])
                        for job in running_jobs_list])
        self.assertEqual(len(golden_values.difference(api_jobs)), 1)

    def test006_post_new_job_in_container(self):
        """ GAT-027
        *post:/node/{nodeid}/containers/containerid/jobs *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Choose one random conatainer of list of running containers.
        #. Send post nodes/{nodeid}/containers/containerid/jobs request.
        #. Check that you can get created job.

        """
        job_name = self.job_body['name']
        self.lg.info('Choose one random container of list of running nodes')
        container_name = self.create_contaienr(self.node_id)
        self.assertTrue(container_name)

        self.lg.info(
            'Send post  nodes/{nodeid}/containers/containerid/jobs api request.'
        )
        response = self.containers_api.post_containers_containerid_jobs(
            self.node_id, container_name, self.job_body)
        self.assertEqual(response.status_code, 202)
        job_id = response.headers['Location'].split('/')[6]
        self.assertTrue(
            self.g8core.wait_on_container_job_update(container_name, job_id,
                                                     100, False))

        self.lg.info('Check that you can get created job.')
        time.sleep(7)
        response = self.containers_api.get_containers_containerid_jobs_jobid(
            self.node_id, container_name, job_id)
        self.assertEqual(response.status_code, 200)

    def test007_kill_all_running_jobs(self):
        """ GAT-028
        *get:/node/{nodeid}/containers/containerid/jobs Expected: get container details*

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Choose one random conatainer of list of running containers.
        #. delete :/node/{nodeid}/containers/containerid/jobs.
        #. Check that all jobs in this container killed.
        #. Compare results with golden value.

        """
        self.lg.info('Choose random container of list of running nodes')
        container_name = self.create_contaienr(self.node_id)
        self.assertTrue(container_name)

        self.lg.info('Spawn multiple jobs.')
        for i in range(0, 3):
            response = self.containers_api.post_containers_containerid_jobs(
                self.node_id, container_name, self.job_body)
            self.assertEqual(response.status_code, 202)
            job_id = response.headers['Location'].split('/')[6]
            self.assertTrue(
                self.g8core.wait_on_container_job_update(
                    container_name, job_id, 15, False))

        self.lg.info(
            'Send delete nodes/{nodeid}/containers/containerid/jobs api request.'
        )
        response = self.containers_api.delete_containers_containerid_jobs(
            self.node_id, container_name)
        self.assertEqual(response.status_code, 204)
        time.sleep(5)

        self.lg.info('Check that all jobs in this container killed ')
        response = self.containers_api.get_containers_containerid_jobs(
            self.node_id, container_name)
        self.assertEqual(response.status_code, 200)
        jobs_list = response.json()
        self.assertEqual(len(jobs_list), 1)
        self.assertEqual(
            len(self.g8core.get_container_job_list(container_name)), 1)

        self.lg.info('Compare results with golden value.')

    def test008_get_job_in_container_details(self):
        """ GAT-029
        *get:/node/{nodeid}/containers/containerid/jobs/jobid Expected: get container details *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Choose one random conatainer of list of running containers.
        #. Choose one random job of list of running jobs in  container.
        #. Send get nodes/{nodeid}/containers/containerid/jobs/jobid api request
        #. Compare results with golden value.

        """
        self.lg.info('Choose one random container of list of running nodes')
        container_name = self.create_contaienr(self.node_id)
        self.assertTrue(container_name)

        self.lg.info(' spawn job in container ')
        response = self.containers_api.post_containers_containerid_jobs(
            self.node_id, container_name, self.job_body)
        self.assertEqual(response.status_code, 202)
        job_id = response.headers['Location'].split('/')[6]
        self.assertTrue(
            self.g8core.wait_on_container_job_update(container_name, job_id,
                                                     100, False))

        self.lg.info(
            'Send get nodes/{nodeid}/containers/containerid/jobs/jobid api request.'
        )
        response = self.containers_api.get_containers_containerid_jobs_jobid(
            self.node_id, container_name, job_id)
        self.assertEqual(response.status_code, 200)
        job_details = response.json()

        self.lg.info('Compare results with golden value.')
        container_id = int(
            list(self.g8core.client.container.find(container_name).keys())[0])
        container = self.g8core.client.container.client(container_id)
        golden_value = container.job.list(job_id)[0]
        self.assertEqual(golden_value['cmd']['command'], job_details['name'])
        self.assertEqual(golden_value['cmd']['id'], job_details['id'])
        self.assertEqual(golden_value['starttime'], job_details['startTime'])

        response = self.containers_api.delete_containers_containerid_jobs_jobid(
            self.node_id, container_name, job_id)
        self.assertEqual(response.status_code, 204)
        self.assertTrue(
            self.g8core.wait_on_container_job_update(container_name, job_id,
                                                     100, True))

    def test009_post_signal_job_in_container_details(self):
        """ GAT-030
        *get:/node/{nodeid}/containers/containerid/jobs/jobid Expected: get container details *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Choose one random conatainer of list of running containers.
        #. Choose one random job of list of running jobs in  container.
        #. Send post nodes/{nodeid}/containers/containerid/jobs/jobid api request, should succeed

        """
        signal = random.randint(1, 30)
        body = {'signal': signal}
        self.lg.info('Choose one random container of list of running nodes')
        container_name = self.create_contaienr(self.node_id)
        self.assertTrue(container_name)

        self.lg.info(' spawn job in container ')
        response = self.containers_api.post_containers_containerid_jobs(
            self.node_id, container_name, self.job_body)
        self.assertEqual(response.status_code, 202)
        job_id = response.headers['Location'].split('/')[6]

        self.lg.info(
            'Send post  nodes/{nodeid}/containers/containerid/jobs/jobid api request.'
        )
        response = self.containers_api.post_containers_containerid_jobs_jobid(
            self.node_id, container_name, job_id, body)
        self.assertEqual(response.status_code, 204)

    def test010_kill_specific_job(self):
        """ GAT-031
        *get:/node/{nodeid}/containers/containerid/jobs/jobid Expected: get container details *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Choose one random conatainer of list of running containers.
        #. Choose one random job of list of running jobs in  container.
        #. Send delete nodes/{nodeid}/containers/containerid/jobs/jobid api request, should succeed
        #. Check that job delted from running jobs list.
        #. Check that job delted from client list.
        """
        self.lg.info('Choose one random container of list of running nodes')
        container_name = self.create_contaienr(self.node_id)
        self.assertTrue(container_name)

        self.lg.info(' spawn job in container ')
        response = self.containers_api.post_containers_containerid_jobs(
            self.node_id, container_name, self.job_body)
        self.assertEqual(response.status_code, 202)
        job_id = response.headers['Location'].split('/')[6]
        self.assertTrue(
            self.g8core.wait_on_container_job_update(container_name, job_id,
                                                     60, False))

        self.lg.info(
            'Send delete  nodes/{nodeid}/containers/containerid/jobs/jobid api request.'
        )
        response = self.containers_api.delete_containers_containerid_jobs_jobid(
            self.node_id, container_name, job_id)
        self.assertEqual(response.status_code, 204)

        self.lg.info('Check that job delted from running jobs list.')
        response = self.containers_api.get_containers_containerid_jobs(
            self.node_id, container_name)
        self.assertEqual(response.status_code, 200)
        running_jobs_list = response.json()
        for job in running_jobs_list:
            self.assertNotEqual(job['id'], job_id)

        self.lg.info('Check that job delted from client list.')
        self.assertTrue(
            self.g8core.wait_on_container_job_update(container_name, job_id,
                                                     60, True))

    def test011_post_ping_to_container(self):
        """ GAT-032
        *get:/node/{nodeid}/containers/containerid/ping *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Choose one random conatainer of list of running containers.
        #. Send post nodes/{nodeid}/containers/containerid/post request.

        """
        self.lg.info('Choose one random container of list of running nodes')
        container_name = self.create_contaienr(self.node_id)
        self.assertTrue(container_name)

        self.lg.info(
            'Send post  nodes/{nodeid}/containers/containerid/ping api request.'
        )
        response = self.containers_api.post_containers_containerid_ping(
            self.node_id, container_name)
        self.assertEqual(response.status_code, 200)

    def test012_get_state_of_container(self):
        """ GAT-033
        *get:/node/{nodeid}/containers/containerid/state *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Choose one random conatainer of list of running containers.
        #. Send get nodes/{nodeid}/containers/containerid/state request.
        #. Compare results with golden value.

        """
        self.lg.info('Choose one random container of list of running nodes')
        container_name = self.create_contaienr(self.node_id)
        self.assertTrue(container_name)

        self.lg.info(
            'Send GET  nodes/{nodeid}/containers/containerid/state api request.'
        )
        response = self.containers_api.get_containers_containerid_state(
            self.node_id, container_name)
        self.assertEqual(response.status_code, 200)

        self.lg.info(' Compare results with golden value.')
        container_state = response.json()
        container_id = int(
            list(self.g8core.client.container.find(container_name).keys())[0])
        golden_value = self.g8core.client.container.list()[str(container_id)]
        self.assertEqual(golden_value['swap'], container_state['swap'])

    def test013_get_info_of_container_os(self):
        """ GAT-034
        *get:/node/{nodeid}/containers/containerid/info *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Choose one random conatainer of list of running containers.
        #. Send get nodes/{nodeid}/containers/containerid/info request.
        #. Compare results with golden value.

        """
        self.lg.info('Choose one random container of list of running nodes')
        container_name = self.create_contaienr(self.node_id)
        self.assertTrue(container_name)

        self.lg.info(
            'Send post  nodes/{nodeid}/containers/containerid/state api request.'
        )
        response = self.containers_api.get_containers_containerid_info(
            self.node_id, container_name)
        self.assertEqual(response.status_code, 200)

        self.lg.info(' Compare results with golden value.')
        container_info = response.json()
        container_id = int(
            list(self.g8core.client.container.find(container_name).keys())[0])
        container = self.g8core.client.container.client(container_id)
        golden_value = container.info.os()
        self.assertAlmostEqual(golden_value.pop('uptime'),
                               container_info.pop('uptime'),
                               delta=50)
        for key in container_info:
            if key not in golden_value:
                self.assertEqual(golden_value[key], container_info[key])

    def test014_get_running_processes_in_container(self):
        """ GAT-035
        *get:/node/{nodeid}/containers/containerid/processes *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Choose one random conatainer of list of running containers.
        #. Send get nodes/{nodeid}/containers/containerid/processes request.
        #. Compare results with golden value.

        """
        self.lg.info('Choose one random container of list of running nodes')
        container_name = self.create_contaienr(self.node_id)
        self.assertTrue(container_name)

        self.lg.info(
            'Send post  nodes/{nodeid}/containers/containerid/state api request.'
        )
        response = self.containers_api.get_containers_containerid_processes(
            self.node_id, container_name)
        self.assertEqual(response.status_code, 200)
        processes = response.json()
        container_id = int(
            list(self.g8core.client.container.find(container_name).keys())[0])
        container = self.g8core.client.container.client(container_id)
        golden_values = container.process.list()

        self.lg.info(' Compare results with golden value.')
        processes.sort(key=lambda d: d['pid'])
        golden_values.sort(key=lambda d: d['pid'])
        for i, p in enumerate(processes):
            self.assertEqual(p['cmdline'], golden_values[i]['cmdline'])
            self.assertEqual(p['pid'], golden_values[i]['pid'])
            self.assertEqual(p['swap'], golden_values[i]['swap'])

    def test015_get_process_details_in_container(self):
        """ GAT-036
        *post:/node/{nodeid}/containers/containerid/processes/processid *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Choose one random conatainer of list of running containers.
        #. Choose one random process of list of process.
        #. Send get nodes/{nodeid}/containers/containerid/processes/processid request.
        #. Compare results with golden value.

        """
        self.lg.info('Choose one random container of list of running nodes')
        container_name = self.create_contaienr(self.node_id)
        self.assertTrue(container_name)

        self.lg.info('Choose one random process of list of process.')
        response = self.containers_api.post_containers_containerid_jobs(
            self.node_id, container_name, self.job_body)
        self.assertEqual(response.status_code, 202)
        job_id = response.headers['Location'].split('/')[6]
        self.assertTrue(
            self.g8core.wait_on_container_job_update(container_name, job_id,
                                                     100, False))

        response = self.containers_api.get_containers_containerid_processes(
            self.node_id, container_name)
        self.assertEqual(response.status_code, 200)
        processes_list = response.json()
        process_id = None
        while not process_id or process_id == 1:
            random_number = random.randint(0, len(processes_list) - 1)
            process_id = processes_list[random_number]['pid']

        self.lg.info(
            'Send get  nodes/{nodeid}/containers/containerid/processes/processid api request.'
        )
        response = self.containers_api.get_containers_containerid_processes_processid(
            self.node_id, container_name, str(process_id))
        self.assertEqual(response.status_code, 200)
        process = response.json()
        container_id = int(
            list(self.g8core.client.container.find(container_name).keys())[0])
        container = self.g8core.client.container.client(container_id)
        golden_value = container.process.list(process_id)[0]

        self.lg.info(' Compare results with golden value.')
        skip_keys = ['cpu', 'vms', 'rss']
        for key in process:
            if key in skip_keys:
                continue
            if key in golden_value.keys():
                self.assertEqual(golden_value[key], process[key])

    def test016_delete_process_in_container(self):
        """ GAT-037
        *post:/node/{nodeid}/containers/containerid/processes/processid *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Choose one random conatainer of list of running containers.
        #. Choose one random process of list of process.
        #. Send delete nodes/{nodeid}/containers/containerid/processes/processid request.
        #. Check that created process deleted from process list.
        #. Compare results with golden value.

        """
        self.lg.info('Choose one random container of list of running nodes')
        container_name = self.create_contaienr(self.node_id)
        self.assertTrue(container_name)

        self.lg.info('Choose one random process of list of processes')
        response = self.containers_api.post_containers_containerid_jobs(
            self.node_id, container_name, self.job_body)

        self.assertEqual(response.status_code, 202)
        job_id = response.headers['Location'].split('/')[6]
        self.assertTrue(
            self.g8core.wait_on_container_job_update(container_name, job_id,
                                                     100, False))
        response = self.containers_api.get_containers_containerid_processes(
            self.node_id, container_name)
        self.assertEqual(response.status_code, 200)
        processes_list = response.json()
        process_id = None
        while not process_id or process_id == 1:
            random_number = random.randint(0, len(processes_list) - 1)
            process_id = processes_list[random_number]['pid']

        self.lg.info(
            'Send delete  nodes/{nodeid}/containers/containerid/processes/processid api request.'
        )
        response = self.containers_api.delete_containers_containerid_processes_processid(
            self.node_id, container_name, str(process_id))
        self.assertEqual(response.status_code, 204)

        self.lg.info('Check that deletd process deleted from process list.')
        response = self.containers_api.get_containers_containerid_processes(
            self.node_id, container_name)
        self.assertEqual(response.status_code, 200)
        processes_list = response.json()
        for process in processes_list:
            self.assertNotEqual(process['pid'], process_id)

        self.lg.info(' Compare results with golden value.')
        container = self.g8core.client.container.find(container_name)
        self.assertTrue(container)
        container_id = int(list(container.keys())[0])
        container = self.g8core.client.container.client(container_id)
        golden_value = container.process.list()
        for process in golden_value:
            self.assertNotEqual(process['pid'], process_id)

    def test017_post_signal_to_process_in_container(self):
        """ GAT-038
        *get:/node/{nodeid}/containers/containerid/processes/processid Expected: get container details *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Choose one random conatainer of list of running containers.
        #. Choose one random process of list of running processes in  container.
        #. Send post nodes/{nodeid}/containers/containerid/processes/process  api request, should succeed

        """
        signal = random.randint(1, 30)
        body = {'signal': signal}
        self.lg.info('Choose one random container of list of running nodes')
        container_name = self.create_contaienr(self.node_id)
        self.assertTrue(container_name)
        response = self.containers_api.post_containers_containerid_jobs(
            self.node_id, container_name, self.job_body)

        self.assertEqual(response.status_code, 202)
        job_id = response.headers['Location'].split('/')[6]
        self.assertTrue(
            self.g8core.wait_on_container_job_update(container_name, job_id,
                                                     100, False))

        self.lg.info('Choose one random process of list of processes')
        response = self.containers_api.get_containers_containerid_processes(
            self.node_id, container_name)
        self.assertEqual(response.status_code, 200)
        processes_list = response.json()
        process_id = None
        while not process_id or process_id == 1:
            random_number = random.randint(0, len(processes_list) - 1)
            process_id = processes_list[random_number]['pid']

        self.lg.info(
            'Send post  nodes/{nodeid}/containers/containerid/processes/processid api request.'
        )
        response = self.containers_api.post_containers_containerid_processes_processid(
            self.node_id, container_name, str(process_id), body)
        self.assertEqual(response.status_code, 204)

    def test018_upload_file_to_container(self):
        """ GAT-039
        *post:/node/{nodeid}/containers/containerid/filesystem  *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Create new container .
        #. post /node/{nodeid}/containers/containerid/filesystem api request should succeed.
        #. Check that file exist in container .
        #. Delete  file from g8os node.
        #. Delete  file from container.
        #. Check that file doesn\'t exist in container.

        """
        self.lg.info('create container ')
        response = self.containers_api.post_containers(
            nodeid=self.node_id, data=self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": self.container_name
        })

        self.lg.info('create file in g8os node ')
        file_name = self.rand_str()
        self.g8core.client.bash('touch %s.text' % file_name)
        body = {"file": '/%s.text' % file_name}
        params = {"path": "/%s.text" % file_name}
        response = self.containers_api.post_containers_containerid_filesystem(
            nodeid=self.node_id,
            containername=self.container_name,
            data=body,
            params=params)
        self.assertEqual(response.status_code, 204)

        self.lg.info('Check that file exist in container ')
        container = self.g8core.client.container.find(self.container_name)
        self.assertTrue(container)
        container_id = int(list(container.keys())[0])
        container = self.g8core.client.container.client(container_id)
        output = container.bash('ls | grep %s.text' % file_name).get().state
        self.assertEqual(output, "SUCCESS")

        self.lg.info('delete  file from g8os node ')
        self.g8core.client.bash('rm %s.text' % file_name)

        self.lg.info('delete  file from container ')
        body = {"path": "/%s.text" % file_name}
        response = self.containers_api.delete_containers_containerid_filesystem(
            nodeid=self.node_id, containername=self.container_name, data=body)
        self.assertEqual(response.status_code, 204)

        self.lg.info('Check that file doesn\'t exist in container ')
        container = self.g8core.client.container.find(self.container_name)
        self.assertTrue(container)
        container_id = int(list(container.keys())[0])
        container = self.g8core.client.container.client(container_id)
        output = container.bash('ls | grep %s.text' % file_name).get().state
        self.assertNotEqual(output, "SUCCESS")

    def test019_download_file_from_container(self):
        """ GAT-040
        *get:/node/{nodeid}/containers/containerid/filesystem  *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Create new container .
        #.  Make new file in container .
        #. Get /node/{nodeid}/containers/containerid/filesystem api request should succeed.
        #. Check that file downloaded
        #. Delete  file from container,

        """
        file_name = self.rand_str()
        self.lg.info('create container ')
        response = self.containers_api.post_containers(
            nodeid=self.node_id, data=self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": self.container_name
        })

        self.lg.info('create new file in container ')
        container = self.g8core.client.container.find(self.container_name)
        self.assertTrue(container)
        container_id = int(list(container.keys())[0])
        container = self.g8core.client.container.client(container_id)
        output = container.bash('echo "test" >%s.text' % file_name).get().state
        self.assertEqual(output, "SUCCESS")

        self.lg.info('Get created file from container ')
        params = {"path": "/%s.text" % file_name}
        response = self.containers_api.get_containers_containerid_filesystem(
            nodeid=self.node_id,
            containername=self.container_name,
            params=params)
        self.assertTrue(response.status_code, 201)

        self.lg.info('Check that file downloaded')
        self.assertTrue(response.text, "test")

        self.lg.info('delete  file from container ')
        output = container.bash('rm %s.text' % file_name).get().state
        self.assertEqual(output, "SUCCESS")
示例#15
0
class TestBridgesAPI(TestcasesBase):
    def setUp(self):
        super(TestBridgesAPI, self).setUp()
        self.bridges_api = BridgesAPI()
        self.containers_api = ContainersAPI()
        self.nodes_api = NodesAPI()
        self.createdbridges = []

        self.lg.info('Get random nodid (N0)')
        self.nodeid = self.get_random_node()
        zeroCore_ip = [x['ip'] for x in self.nodes
                       if x['id'] == self.nodeid][0]
        self.root_url = "https://hub.gig.tech/gig-official-apps/ubuntu1604.flist"
        self.jwt = self.nodes_api.jwt
        self.zeroCore = Client(zeroCore_ip, password=self.jwt)
        self.bridge_name = self.rand_str()
        self.nat = self.random_item([False, True])
        self.bridge_body = {
            "name": self.bridge_name,
            "networkMode": "none",
            "nat": self.nat,
            "setting": {}
        }

    def tearDown(self):
        self.lg.info('TearDown:delete all created bridges ')
        for bridge in self.createdbridges:
            self.bridges_api.delete_nodes_bridges_bridgeid(
                bridge['node'], bridge['name'])

    def test001_create_bridges_with_same_name(self):
        """ GAT-101
        *Create two bridges with same name *

        **Test Scenario:**

        #. Create bridge (B1) , should succeed .
        #. Check that created bridge exist in bridges list.
        #. Create bridge (B2) with same name for (B1),should fail.
        #. Delete bridge (B1), should succeed.

        """
        self.lg.info('Create bridge (B1) , should succeed .')
        response = self.bridges_api.post_nodes_bridges(self.nodeid,
                                                       self.bridge_body)
        self.assertEqual(response.status_code, 201, response.content)
        time.sleep(3)

        self.lg.info("Check that created bridge exist in bridges list.")
        response = self.bridges_api.get_nodes_bridges(self.nodeid)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(
            [x for x in response.json() if x["name"] == self.bridge_name])

        self.lg.info('Create bridge (B2) with same name for (B1),should fail.')
        response = self.bridges_api.post_nodes_bridges(self.nodeid,
                                                       self.bridge_body)
        self.assertEqual(response.status_code, 409, response.content)
        time.sleep(3)

        self.lg.info('Delete bridge (B1), should succeed..')
        response = self.bridges_api.delete_nodes_bridges_bridgeid(
            self.nodeid, self.bridge_name)
        self.assertEqual(response.status_code, 204, response.content)

    def test002_create_bridge_with_nat(self):
        """ GAT-102
        *Create bridge with nat options *

        **Test Scenario:**

        #. Create bridge (B0) with false in nat option,should succeed.
        #. Create container (C0) with (B0) bridge,should succeed.
        #. Check that C0 can connect to internet ,should fail.
        #. Create bridge (B1) with true in nat option , should succed.
        #. Create container(C1) with (B1) bridge ,should succeed.
        #. Check that (C1) can connect to internet ,should succeed.

        """
        nat_options = [False, True]
        for i, nat in enumerate(nat_options):
            B_name = self.rand_str()
            cidr = "217.102.2.1"
            B_body = {
                "name": B_name,
                "hwaddr": self.randomMAC(),
                "networkMode": "dnsmasq",
                "nat": nat,
                "setting": {
                    "cidr": "%s/24" % cidr,
                    "start": "217.102.2.2",
                    "end": "217.102.2.3"
                }
            }

            self.lg.info(
                'Create bridge (B{0}) with dnsmasq and {1} in nat option,should succeed.'
                .format(i, nat))
            response = self.bridges_api.post_nodes_bridges(self.nodeid, B_body)
            self.assertEqual(response.status_code, 201, response.content)
            time.sleep(3)

            self.lg.info(
                'Create (C{0}) with (B{0}) bridge,should succeed.'.format(i))
            C_nics = [{
                "type": "bridge",
                "id": B_name,
                "config": {
                    "dhcp": True
                },
                "status": "up"
            }]
            C_name = self.rand_str()
            C_body = {
                "name": C_name,
                "hostname": self.rand_str(),
                "flist": self.root_url,
                "hostNetworking": False,
                "nics": C_nics
            }
            response = self.containers_api.post_containers(self.nodeid, C_body)
            self.assertEqual(response.status_code, 201)
            C_client = self.zeroCore.get_container_client(C_name)
            time.sleep(4)
            if not nat:
                self.lg.info(
                    'Check that C{} can connect to internet ,should fail.'.
                    format(i))
                response = C_client.bash("ping -c1 8.8.8.8").get()
                self.assertEqual(response.state, "ERROR", response.stdout)
            else:

                self.lg.info(
                    'Check that C{} can connect to internet ,should succeed.'.
                    format(i))
                response = C_client.bash("ping -c1 8.8.8.8").get()
                self.assertEqual(response.state, "SUCCESS", response.stdout)

            self.lg.info(
                'Delete created bridge (B{0}) and container (c{0}), should succeed'
                .format(i))
            response = self.bridges_api.delete_nodes_bridges_bridgeid(
                self.nodeid, B_name)
            self.assertEqual(response.status_code, 204)
            response = self.containers_api.delete_containers_containerid(
                self.nodeid, C_name)
            self.assertTrue(response.status_code, 204)

    def test003_create_bridge_with_hwaddr(self):
        """ GAT-103
        *Create bridge with hardware address *

        **Test Scenario:**

        #. Create bridge (B0) with specefic hardware address,should succeed.
        #. Check that bridge created with this hardware address, should succeed.
        #. Create bridge (B1) with wrong hardware address, should fail.

        """
        hardwareaddr = self.randomMAC()
        self.bridge_body["hwaddr"] = hardwareaddr
        self.lg.info(
            "Create bridge (B0) with specefic hardware address,should succeed."
        )
        response = self.bridges_api.post_nodes_bridges(self.nodeid,
                                                       self.bridge_body)
        self.assertEqual(response.status_code, 201, response.content)
        time.sleep(3)
        self.createdbridges.append({
            "node": self.nodeid,
            "name": self.bridge_name
        })

        self.lg.info(
            " Check that bridge(B0) created with this hardware address, should succeed."
        )
        response = self.nodes_api.get_nodes_nodeid_nics(self.nodeid)
        self.assertEqual(response.status_code, 200)
        nic = [x for x in response.json() if x["name"] == self.bridge_name][0]
        self.assertEqual(nic["hardwareaddr"], hardwareaddr)

        self.lg.info(
            "Create bridge (B1) with wrong hardware address, should fail.")
        hardwareaddr = self.rand_str()
        B1_name = self.rand_str()
        self.bridge_body["hwaddr"] = hardwareaddr
        self.bridge_body["name"] = B1_name
        response = self.bridges_api.post_nodes_bridges(self.nodeid,
                                                       self.bridge_body)
        self.createdbridges.append({
            "node": self.nodeid,
            "name": self.bridge_name
        })
        self.assertEqual(response.status_code, 400, response.content)

    def test004_create_bridge_with_static_networkMode(self):
        """ GAT-104
        *Create bridge with static network mode *

        **Test Scenario:**

        #. Create bridge (B0), should succeed.
        #. Check that (B0)bridge took given cidr address, should succeed.

        """
        cidr_address = "130.111.3.1/8"
        self.bridge_body["networkMode"] = "static"
        self.bridge_body["setting"] = {"cidr": cidr_address}

        self.lg.info(" Create bridge (B0), should succeed.")
        response = self.bridges_api.post_nodes_bridges(self.nodeid,
                                                       self.bridge_body)
        self.assertEqual(response.status_code, 201, response.content)
        time.sleep(3)
        self.createdbridges.append({
            "node": self.nodeid,
            "name": self.bridge_name
        })

        self.lg.info(
            "Check that (B0)bridge took given cidr address, should succeed.")
        response = self.nodes_api.get_nodes_nodeid_nics(self.nodeid)
        self.assertEqual(response.status_code, 200)
        nic = [x for x in response.json() if x["name"] == self.bridge_name][0]
        self.assertIn(cidr_address, nic["addrs"])

    def test005_create_bridges_with_static_networkMode_and_same_cidr(self):
        """ GAT-105
        *Create two bridges with static network mode and same cidr address *

        **Test Scenario:**

        #. Create bridge (B0), should succeed.
        #. Check that created bridge exist in bridges list.
        #. Create bridge(B1)with same cidr as (B0),should fail.

        """

        cidr_address = "130.111.3.1/8"
        self.bridge_body["networkMode"] = "static"
        self.bridge_body["setting"] = {"cidr": cidr_address}

        self.lg.info(" Create bridge (B0), should succeed.")
        response = self.bridges_api.post_nodes_bridges(self.nodeid,
                                                       self.bridge_body)
        self.assertEqual(response.status_code, 201, response.content)
        time.sleep(3)
        self.createdbridges.append({
            "node": self.nodeid,
            "name": self.bridge_name
        })

        self.lg.info("Check that created bridge exist in bridges list.")
        response = self.bridges_api.get_nodes_bridges(self.nodeid)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(
            [x for x in response.json() if x["name"] == self.bridge_name])

        self.lg.info("Create bridge(B1)with same cidr as (B0),should fail.")
        B1_name = self.rand_str()
        self.bridge_body["name"] = B1_name
        response = self.bridges_api.post_nodes_bridges(self.nodeid,
                                                       self.bridge_body)
        self.createdbridges.append({"node": self.nodeid, "name": B1_name})
        self.assertEqual(response.status_code, 409, response.content)

    def test006_create_bridge_with_invalid_cidr_in_static_networkMode(self):
        """ GAT-106
        *Create bridge with static network mode and invalid cidr address  *

        **Test Scenario:**

        #. Create bridge (B) with invalid cidr address, should fail.

        """

        self.lg.info(
            " Create bridge (B) with invalid cidr address, should fail..")
        B_name = self.rand_str()
        cidr_address = "260.120.3.1/8"
        self.bridge_body["name"] = B_name
        self.bridge_body["networkMode"] = "static"
        self.bridge_body["setting"] = {"cidr": cidr_address}
        response = self.bridges_api.post_nodes_bridges(self.nodeid,
                                                       self.bridge_body)
        self.createdbridges.append({"node": self.nodeid, "name": B_name})
        self.assertEqual(response.status_code, 400, response.content)

    def test007_create_bridge_with_empty_setting_in_static_networkMode(self):
        """ GAT-107
        *Create bridge with static network mode and invalid empty cidr address. *

        **Test Scenario:**

        #. Create bridge (B) with static network mode and empty cidr value,should fail.

        """

        self.lg.info(
            " Create bridge (B) with static network mode and empty cidr value,should fail."
        )
        B_name = self.rand_str()
        self.bridge_body["name"] = B_name
        self.bridge_body["networkMode"] = "static"
        self.bridge_body["setting"] = {}
        response = self.bridges_api.post_nodes_bridges(self.nodeid,
                                                       self.bridge_body)
        self.createdbridges.append({"node": self.nodeid, "name": B_name})
        self.assertEqual(response.status_code, 400, response.content)

    def test008_create_bridge_with_dnsmasq_networkMode(self):
        """ GAT-108
        *Create bridge with dnsmasq network mode *

        **Test Scenario:**

        #. Create bridge (B) with dnsmasq network mode, should succeed.
        #. Check that (B)bridge took given cidr address, should succeed.

        """

        cidr_address = "205.102.2.1/8"
        start = "205.102.3.2"
        end = "205.102.3.3"
        self.bridge_body["networkMode"] = "dnsmasq"
        self.bridge_body["setting"] = {
            "cidr": cidr_address,
            "start": start,
            "end": end
        }

        self.lg.info(
            " Create bridge (B) with dnsmasq network mode,cidr value and start and end range in settings, should succeed."
        )
        response = self.bridges_api.post_nodes_bridges(self.nodeid,
                                                       self.bridge_body)
        self.assertEqual(response.status_code, 201, response.content)
        time.sleep(3)
        self.createdbridges.append({
            "node": self.nodeid,
            "name": self.bridge_name
        })

        self.lg.info(
            "Check that (B) bridge took given cidr address, should succeed.")
        response = self.nodes_api.get_nodes_nodeid_nics(self.nodeid)
        self.assertEqual(response.status_code, 200)
        nic = [x for x in response.json() if x["name"] == self.bridge_name][0]
        self.assertIn(cidr_address, nic["addrs"])

    def test009_create_bridges_with_dnsmasq_networkMode_and_opverlapping_cidrs(
            self):
        """ GAT-109
        *Create bridges with dnsmasq network mode and overlapping cidrs. *

        **Test Scenario:**

        #. Create bridge (B0) with dnsmasq network mode, should succeed.
        #. Check that created bridge exist in bridges list.
        #. Create bridge (B1) overlapping with (B0) cidr address,shoud fail.

        """

        cidr_address = "205.102.2.1/8"
        start = "205.102.3.2"
        end = "205.102.3.3"
        self.bridge_body["networkMode"] = "dnsmasq"
        self.bridge_body["setting"] = {
            "cidr": cidr_address,
            "start": start,
            "end": end
        }

        self.lg.info(
            " Create bridge (B0) with dnsmasq network mode,cidr value and start and end range in settings, should succeed."
        )
        response = self.bridges_api.post_nodes_bridges(self.nodeid,
                                                       self.bridge_body)
        self.assertEqual(response.status_code, 201, response.content)
        time.sleep(3)
        self.createdbridges.append({
            "node": self.nodeid,
            "name": self.bridge_name
        })

        self.lg.info("Check that created bridge exist in bridges list.")
        response = self.bridges_api.get_nodes_bridges(self.nodeid)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(
            [x for x in response.json() if x["name"] == self.bridge_name])

        self.lg.info(
            " Create bridge (B1) overlapping with (B0) address,shoud fail.")
        B1_name = self.rand_str()
        cidr_address = "205.103.2.1/8"
        start = "205.103.3.2"
        end = "205.103.3.2"
        self.bridge_body["name"] = B1_name
        self.bridge_body["networkMode"] = "dnsmasq"
        self.bridge_body["setting"] = {
            "cidr": cidr_address,
            "start": start,
            "end": end
        }
        response = self.bridges_api.post_nodes_bridges(self.nodeid,
                                                       self.bridge_body)
        self.createdbridges.append({"node": self.nodeid, "name": B1_name})
        self.assertEqual(response.status_code, 409, response.content)

    def test010_create_bridge_with_out_of_range_address_in_dnsmasq(self):
        """ GAT-110
        *Create bridge with dnsmasq network mode and out of range start and end values *

        **Test Scenario:**

        #. Create bridge(B) with out of range start and end values, shoud fail.

        """

        self.lg.info(
            "Create bridge(B) with out of range start and end values, shoud fail."
        )
        B_name = self.rand_str()
        cidr_address = "192.22.2.1/24"
        start = "192.22.3.1"
        end = "192.22.3.2"
        self.bridge_body["networkMode"] = "dnsmasq"
        self.bridge_body["setting"] = {
            "cidr": cidr_address,
            "start": start,
            "end": end
        }
        self.bridge_body["name"] = B_name
        response = self.bridges_api.post_nodes_bridges(self.nodeid,
                                                       self.bridge_body)
        self.createdbridges.append({"node": self.nodeid, "name": B_name})
        self.assertEqual(response.status_code, 400, response.content)

    def test011_create_bridge_with_invalid_settings_in_dnsmasq(self):
        """ GAT-111
        *Create bridge with dnsmasq network mode and invalid settings. *

        **Test Scenario:**

        #.Create bridge (B0) with dnsmasq network mode and empty setting value,should fail.
        #.Create bridge (B1) with dnsmasq network and empty start and end values, should fail.

        """
        self.lg.info(
            " Create bridge (B0) with dnsmasq network mode and empty setting value,should fail."
        )
        B0_name = self.rand_str()
        self.bridge_body["name"] = B0_name
        self.bridge_body["networkMode"] = "dnsmasq"
        self.bridge_body["setting"] = {}
        response = self.bridges_api.post_nodes_bridges(self.nodeid,
                                                       self.bridge_body)
        self.createdbridges.append({"node": self.nodeid, "name": B0_name})
        self.assertEqual(response.status_code, 400, response.content)

        self.lg.info(
            " Create bridge (B1) with dnsmasq network and empty start and end values, should fail."
        )
        B1_name = self.rand_str()
        cidr_address = "192.22.3.5/24"
        self.bridge_body["name"] = B1_name
        self.bridge_body["networkMode"] = "dnsmasq"
        self.bridge_body["setting"] = {"cidr": cidr_address}
        response = self.bridges_api.post_nodes_bridges(self.nodeid,
                                                       self.bridge_body)
        self.createdbridges.append({"node": self.nodeid, "name": B1_name})
        self.assertEqual(response.status_code, 400, response.content)
class TestcontaineridAPI(TestcasesBase):
    def setUp(self):
        self.containers_api = ContainersAPI()
        self.bridges_api = BridgesAPI()
        self.storagepool_api = StoragepoolsAPI()
        self.createdcontainer = []

        self.lg.info('Choose one random node of list of running nodes.')
        self.node_id = self.get_random_node()
        self.zeroCore_ip = [
            x['ip'] for x in self.nodes if x['id'] == self.node_id
        ]
        self.assertTrue(self.zeroCore_ip, 'No node match the random node')
        self.jwt = self.nodes_api.jwt
        self.zeroCore = Client(self.zeroCore_ip[0], password=self.jwt)
        self.root_url = "https://hub.gig.tech/gig-official-apps/ubuntu1604.flist"
        self.storage = "ardb://hub.gig.tech:16379"
        self.container_name = self.rand_str()
        self.hostname = self.rand_str()
        self.process_body = {'name': 'yes'}
        self.container_body = {
            "name": self.container_name,
            "hostname": self.hostname,
            "flist": self.root_url,
            "hostNetworking": False,
            "initProcesses": [],
            "filesystems": [],
            "ports": [],
            "storage": self.storage
        }

    def tearDown(self):
        self.lg.info('TearDown:delete all created container ')
        for container in self.createdcontainer:
            self.containers_api.delete_containers_containerid(
                container['node'], container['container'])

    def test001_check_coonection_with_False_hostNetworking(self):
        """ GAT-082
        *Check container internet connection with false hostNetworking options *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Create container with false hostNetworking.
        #. Try to connect to internet from created container ,Should fail.

        """
        self.lg.info('Send post nodes/{nodeid}/containers api request.')
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": self.container_name
        })

        self.lg.info(
            "Try to connect to internet from created container , Should fail.")
        container = self.zeroCore.get_container_client(self.container_name)
        self.assertTrue(container)
        response = container.bash('ping -c 5 google.com').get()
        self.assertEqual(response.state, 'ERROR')

    def test002_check_coonection_with_True_hostNetworking(self):
        """ GAT-083
        *Check container internet connection with true hostNetworking options *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Create container with True hostNetworking.
        #. Try to connect to internet from created container ,Should succeed.

        """
        self.container_body['hostNetworking'] = True

        self.lg.info('Send post nodes/{nodeid}/containers api request.')
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": self.container_name
        })

        self.lg.info(
            "Try to connect to internet from created container ,Should succeed."
        )
        container = self.zeroCore.get_container_client(self.container_name)
        self.assertTrue(container)
        response = container.bash('ping -c 5 google.com').get()
        self.assertEqual(response.state, 'SUCCESS')
        self.assertNotIn("unreachable", response.stdout)

    def test003_create_container_with_init_process(self):
        """ GAT-084
        *Check that container created with init process *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Create container with initProcess.
        #. Check that container created with init process.

        """
        self.container_body[
            'flist'] = "https://hub.gig.tech/dina_magdy/initprocess.flist"
        ## flist which have script which print environment varaibles and print stdin
        Environmentvaraible = "MYVAR=%s" % self.rand_str()
        stdin = self.rand_str()
        self.container_body['initProcesses'] = [{
            "name":
            "sh",
            "pwd":
            "/",
            "args": ["sbin/process_init"],
            "environment": [Environmentvaraible],
            "stdin":
            stdin
        }]
        self.lg.info('Send post nodes/{nodeid}/containers api request.')
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": self.container_name
        })

        self.lg.info("Check that container created with init process.")
        container = self.zeroCore.get_container_client(self.container_name)
        response = container.bash("ls |grep  out.text").get()
        self.assertEqual(response.state, "SUCCESS")
        response = container.bash("cat out.text | grep %s" % stdin).get()
        self.assertEqual(response.state, "SUCCESS",
                         "init processes didn't get stdin correctly")
        response = container.bash("cat out.text | grep %s" %
                                  Environmentvaraible).get()
        self.assertEqual(response.state, "SUCCESS",
                         "init processes didn't get Env varaible  correctly")

    def test004_create_containers_with_different_flists(self):
        """ GAT-085
        *create contaner with different flists *

        **Test Scenario:**

        #. Choose one random node of list of running nodes.
        #. Choose one random flist .
        #. Create container with this flist, Should succeed.
        #. Make sure it created with required values, should succeed.
        #. Make sure that created container is running,should succeed.
        #. Check that container created on node, should succeed
        """
        flistslist = [
            "ovs.flist", "ubuntu1604.flist", "grid-api-flistbuild.flist",
            "cloud-init-server-master.flist"
        ]

        flist = random.choice(flistslist)
        self.container_body[
            'flist'] = "https://hub.gig.tech/gig-official-apps/%s" % flist
        self.lg.info('Send post nodes/{nodeid}/containers api request.')
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": self.container_name
        })

        response = self.containers_api.get_containers_containerid(
            self.node_id, self.container_name)
        self.assertEqual(response.status_code, 200)
        response_data = response.json()
        for key in response_data.keys():
            if key == 'initprocesses':
                self.assertEqual(response_data[key],
                                 self.container_body['initProcesses'])
            if key in self.container_body.keys():
                self.assertEqual(response_data[key], self.container_body[key])

        self.lg.info("check that container created on node, should succeed")
        self.assertTrue(
            self.zeroCore.client.container.find(self.container_name))

    @unittest.skip("https://github.com/g8os/core0/issues/228")
    def test005_Check_container_access_to_host_dev(self):
        """ GAT-086
        *Make sure that container doesn't have access to host dev files *

        **Test Scenario:**

        #. Create container, Should succeed.
        #. Make sure that created container is running,should succeed.
        #. Check that container doesn't has access to host dev files .

        """

        self.lg.info('Send post nodes/{nodeid}/containers api request.')
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": self.container_name
        })

        self.lg.info(
            "Check that container doesn't has access to host dev files .")
        container = self.zeroCore.get_container_client(self.container_name)
        response = container.bash("ls -alh").get().stdout
        for line in response.splitlines():
            if "dev" in line:
                self.assertNotIn('w', line)

    def test006_create_container_with_bridge(self):
        """ GAT-087
        *Test case for create containers with same bridge and make sure they can connect to each other *

        **Test Scenario:**

        #. Create bridge with dnsmasq network , should succeed.
        #. Create 2 containers C1, C2 with created bridge, should succeed.
        #. Check if each container (C1), (C2) got an ip address, should succeed.
        #. Check if first container (c1) can ping second container (c2), should succeed.
        #. Check if second container (c2) can ping first container (c1), should succeed.
        #. Check that two containers get ip and they are in bridge range, should succeed.
        #. Delete created bridge .

        """

        self.lg.info('Create bridge with dnsmasq network, should succeed')
        bridge_name = self.rand_str()
        hwaddr = self.randomMAC()
        ip_range = ["201.100.2.2", "201.100.2.3"]
        body = {
            "name": bridge_name,
            "hwaddr": hwaddr,
            "networkMode": "dnsmasq",
            "nat": False,
            "setting": {
                "cidr": "201.100.2.1/24",
                "start": ip_range[0],
                "end": ip_range[1]
            }
        }

        response = self.bridges_api.post_nodes_bridges(self.node_id, body)
        self.assertEqual(response.status_code, 201, response.content)
        time.sleep(3)

        self.lg.info(
            'Create 2 containers C1, C2 with created bridge, should succeed.')
        nics = [{
            "type": "bridge",
            "id": bridge_name,
            "config": {
                "dhcp": True
            },
            "status": "up"
        }]
        self.container_body["nics"] = nics
        C1_name = self.rand_str()
        C2_name = self.rand_str()

        self.container_body["name"] = C1_name
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C1_name
        })

        self.container_body["name"] = C2_name
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C2_name
        })

        self.lg.info("Get two containers client C1_client and C2_client .")
        C1_client = self.zeroCore.get_container_client(C1_name)
        C2_client = self.zeroCore.get_container_client(C2_name)

        self.lg.info(
            "Check that two containers get ip and they are in bridge range, should succeed "
        )
        C1_br_ip = self.zeroCore.get_container_bridge_ip(C1_client, ip_range)
        C2_br_ip = self.zeroCore.get_container_bridge_ip(C2_client, ip_range)
        self.assertNotEqual(C2_br_ip, C1_br_ip)

        self.lg.info(
            "Check if first container (c1) can ping second container (c2), should succeed."
        )
        response = C1_client.bash('ping -c 10 %s' % C2_br_ip).get()
        self.assertEqual(response.state, 'SUCCESS')

        self.lg.info(
            "Check if second container (c2) can ping first container (c1), should succeed."
        )
        response = C2_client.bash('ping -c 10 %s' % C1_br_ip).get()
        self.assertEqual(response.state, 'SUCCESS')

        self.lg.info("Create C3 without bridge ")
        C3_name = self.rand_str()
        nics = []
        self.container_body["name"] = C3_name
        self.container_body["nics"] = nics

        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C3_name
        })
        C3_client = self.zeroCore.get_container_client(C3_name)

        self.lg.info(
            "Check if third container (c3) can ping first container (c1), should fail."
        )
        response = C3_client.bash('ping -c 10 %s' % C1_br_ip).get()
        self.assertEqual(response.state, 'ERROR')

        self.lg.info("Delete created bridge ")
        self.bridges_api.delete_nodes_bridges_bridgeid(self.node_id,
                                                       bridge_name)

    def test007_create_containers_with_diff_bridges(self):
        """ GAT-088
        *Test case for create containers with different bridges and make sure they can't connect to  each other through bridge ip *

        **Test Scenario:**

        #. Create 2 bridges (B1),(B2) with dnsmasq network , should succeed.
        #. Create container(C1) with (B1), should succeed.
        #. Create container(C2) with (B2), should succeed.
        #. Check if each container (C1), (C2) got an ip address, should succeed.
        #. Check if first container (c1) can ping second container (c2), should fail .
        #. Check if second container (c2) can ping first container (c1), should fail.
        #. Delete created bridges .

        """

        self.lg.info(
            'Create bridged (B1),(B2) with dnsmasq network, should succeed')
        B1_name = self.rand_str()
        B2_name = self.rand_str()
        hwaddr1 = self.randomMAC()
        hwaddr2 = self.randomMAC()
        cidr1 = "198.101.5.1"
        cidr2 = "201.100.2.1"
        ip_range1 = ["198.101.5.2", "198.101.5.3"]
        ip_range2 = ["201.100.2.2", "201.100.2.3"]

        body1 = {
            "name": B1_name,
            "hwaddr": hwaddr1,
            "networkMode": "dnsmasq",
            "nat": False,
            "setting": {
                "cidr": "%s/24" % cidr1,
                "start": ip_range1[0],
                "end": ip_range1[1]
            }
        }

        body2 = {
            "name": B2_name,
            "hwaddr": hwaddr2,
            "networkMode": "dnsmasq",
            "nat": False,
            "setting": {
                "cidr": "%s/24" % cidr2,
                "start": ip_range2[0],
                "end": ip_range2[1]
            }
        }

        response = self.bridges_api.post_nodes_bridges(self.node_id, body1)
        self.assertEqual(response.status_code, 201, response.content)
        time.sleep(3)

        response = self.bridges_api.post_nodes_bridges(self.node_id, body2)
        self.assertEqual(response.status_code, 201, response.content)
        time.sleep(3)

        self.lg.info('Create container(C1) with (B1), should succeed.')
        nics1 = [{
            "type": "bridge",
            "id": B1_name,
            "config": {
                "dhcp": True
            },
            "status": "up"
        }]
        self.container_body["nics"] = nics1
        C1_name = self.rand_str()
        self.container_body["name"] = C1_name
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C1_name
        })

        self.lg.info('Create container(C2) with (B2), should succeed.')
        nics2 = [{
            "type": "bridge",
            "id": B2_name,
            "config": {
                "dhcp": True
            },
            "status": "up"
        }]
        self.container_body["nics"] = nics2
        C2_name = self.rand_str()
        self.container_body["name"] = C2_name

        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C2_name
        })

        self.lg.info("Get two containers client C1_client and C2_client .")
        C1_client = self.zeroCore.get_container_client(C1_name)
        C2_client = self.zeroCore.get_container_client(C2_name)

        self.lg.info(
            "Check that two containers get ip and they are in bridge range, should succeed "
        )
        C1_br_ip = self.zeroCore.get_container_bridge_ip(C1_client, ip_range1)
        C2_br_ip = self.zeroCore.get_container_bridge_ip(C2_client, ip_range2)

        self.lg.info(
            "Check if first container (c1) can ping second container (c2), should fail."
        )
        response = C1_client.bash('ping -w 5 %s' % C2_br_ip).get()
        self.assertEqual(response.state, 'ERROR')

        self.lg.info(
            "Check if second container (c2) can ping first container (c1), should fail."
        )
        response = C2_client.bash('ping -w 5 %s' % C1_br_ip).get()
        self.assertEqual(response.state, 'ERROR')

        self.lg.info("Delete created bridge ")
        self.bridges_api.delete_nodes_bridges_bridgeid(self.node_id, B2_name)
        self.bridges_api.delete_nodes_bridges_bridgeid(self.node_id, B1_name)

    def test008_Create_container_with_zerotier_network(self):
        """ GAT-089
        *Test case for create containers with same zerotier network *

        **Test Scenario:**
        #. Create Zerotier network using zerotier api ,should succeed.
        #. Create two containers C1,C2 with same zertoier networkId, should succeed.
        #. Check that two containers get zerotier ip, should succeed.
        #. Make sure that two containers can connect to each other, should succeed.

        """

        Z_Id = self.create_zerotier_network()

        self.lg.info(
            'Create 2 containers C1, C2 with same zerotier network Id , should succeed'
        )
        nic = [{'type': 'default'}, {'type': 'zerotier', 'id': Z_Id}]
        self.container_body["nics"] = nic
        C1_name = self.rand_str()
        C2_name = self.rand_str()

        self.container_body["name"] = C1_name
        response = self.containers_api.post_containers(
            nodeid=self.node_id, data=self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C1_name
        })

        self.container_body["name"] = C2_name
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C2_name
        })

        self.lg.info("Get two containers client C1_client and C2_client .")
        C1_client = self.zeroCore.get_container_client(C1_name)
        C2_client = self.zeroCore.get_container_client(C2_name)

        self.lg.info(
            "Check that two containers get zerotier ip, should succeed ")
        time.sleep(5)
        C1_Zt_ip = self.zeroCore.get_client_zt_ip(C1_client)
        self.assertTrue(C1_Zt_ip)
        C2_Zt_ip = self.zeroCore.get_client_zt_ip(C2_client)
        self.assertTrue(C2_Zt_ip)

        self.lg.info(
            "first container C1 ping second container C2 ,should succeed")
        response = C1_client.bash('ping -c 5 %s' % C2_Zt_ip).get()
        self.assertEqual(response.state, "SUCCESS")

        self.lg.info(
            "second container C2 ping first container C1 ,should succeed")
        response = C2_client.bash('ping -c 5 %s' % C1_Zt_ip).get()
        self.assertEqual(response.state, "SUCCESS")

        self.lg.info("Create C3 without zerotier ")
        C3_name = self.rand_str()
        nics = []
        self.container_body["name"] = C3_name
        self.container_body["nics"] = nics

        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C3_name
        })
        C3_client = self.zeroCore.get_container_client(C3_name)

        self.lg.info(
            "Check if third container (c3) can ping first container (c1), should fail."
        )
        response = C3_client.bash('ping -c 10 %s' % C1_Zt_ip).get()
        self.assertEqual(response.state, 'ERROR')

        self.lg.info("Delete zerotier network ")
        self.delete_zerotier_network(Z_Id)

    def test009_create_containers_with_vlan_network(self):
        """ GAT-090

        *Test case for test creation of containers with vlan network*

        **Test Scenario:**

        #. Create ovs container .
        #. Create two containers with same vlan tag, should succeed.
        #. Check that two containers get correct vlan ip, should succeed.
        #. First container C1 ping second container C2 ,should succeed.
        #. Second container C2 ping first container C1 ,should succeed.
        #. Create C3 with different vlan tag , should succeed.
        #. Check if third container (c3) can ping first container (c1), should fail.

        """
        self.lg.info("create ovs container")
        self.zeroCore.create_ovs_container()

        self.lg.info("create two container with same vlan tag,should succeed")
        vlan1_id, vlan2_id = random.sample(range(1, 4096), 2)
        C1_ip = "201.100.2.1"
        C2_ip = "201.100.2.2"

        C1_name = self.rand_str()
        nic = [{
            'type': 'default'
        }, {
            'type': 'vlan',
            'id': "%s" % vlan1_id,
            'config': {
                'cidr': '%s/24' % C1_ip
            }
        }]
        self.container_body["nics"] = nic
        self.container_body["name"] = C1_name
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C1_name
        })

        C2_name = self.rand_str()
        self.container_body["name"] = C2_name
        nic = [{
            'type': 'default'
        }, {
            'type': 'vlan',
            'id': "%s" % vlan1_id,
            'config': {
                'cidr': '%s/24' % C2_ip
            }
        }]
        self.container_body["nics"] = nic
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C2_name
        })

        self.lg.info("Get two containers client C1_client and C2_client.")
        C1_client = self.zeroCore.get_container_client(C1_name)
        C2_client = self.zeroCore.get_container_client(C2_name)

        self.lg.info(
            "Check that two containers get correct vlan ip, should succeed ")
        self.assertTrue(
            self.zeroCore.check_container_vlan_vxlan_ip(C1_client, C1_ip))
        self.assertTrue(
            self.zeroCore.check_container_vlan_vxlan_ip(C2_client, C2_ip))

        self.lg.info(
            "first container C1 ping second container C2 ,should succeed")
        response = C1_client.bash('ping -w 2 %s' % C2_ip).get()
        self.assertEqual(response.state, "SUCCESS")

        self.lg.info(
            "second container C2 ping first container C1 ,should succeed")
        response = C2_client.bash('ping -w 2 %s' % C1_ip).get()
        self.assertEqual(response.state, "SUCCESS")

        self.lg.info("Create C3 with different vlan tag ")
        C3_ip = "201.100.2.3"
        C3_name = self.rand_str()
        nic = [{
            'type': 'default'
        }, {
            'type': 'vlan',
            'id': "%s" % vlan2_id,
            'config': {
                'cidr': '%s/24' % C3_ip
            }
        }]
        self.container_body["nics"] = nic
        self.container_body["name"] = C3_name
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C3_name
        })
        C3_client = self.zeroCore.get_container_client(C3_name)
        self.assertTrue(C3_client)
        self.assertTrue(
            self.zeroCore.check_container_vlan_vxlan_ip(C3_client, C3_ip))

        self.lg.info(
            "Check if third container (c3) can ping first container (c1), should fail."
        )
        response = C3_client.bash('ping -w 2 %s' % C1_ip).get()
        self.assertEqual(response.state, 'ERROR')

    def test010_create_containers_with_vxlan_network(self):
        """ GAT-091

        *Test case for test creation of containers with vxlan network*

        **Test Scenario:**

        #. Create ovs container .
        #. Create two containers with same vxlan tag, should succeed.
        #. Check that two containers get correct vxlan ip, should succeed.
        #. First container C1 ping second container C2 ,should succeed.
        #. Second container C2 ping first container C1 ,should succeed.
        #. Create third container c3 with different vxlan Id,should succeed
        #. Check if third container (c3) can ping first container (c1), should fail.
        """
        self.lg.info("create ovs container")
        self.zeroCore.create_ovs_container()

        self.lg.info("create two container with same vxlan id,should succeed")

        vxlan1_id, vxlan2_id = random.sample(range(4096, 8000), 2)
        C1_ip = "201.100.3.1"
        C2_ip = "201.100.3.2"

        C1_name = self.rand_str()
        nic = [{
            'type': 'default'
        }, {
            'type': 'vxlan',
            'id': "%s" % vxlan1_id,
            'config': {
                'cidr': '%s/24' % C1_ip
            }
        }]
        self.container_body["nics"] = nic
        self.container_body["name"] = C1_name
        response = self.containers_api.post_containers(
            nodeid=self.node_id, data=self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C1_name
        })
        C2_name = self.rand_str()
        self.container_body["name"] = C2_name
        nic = [{
            'type': 'default'
        }, {
            'type': 'vxlan',
            'id': "%s" % vxlan1_id,
            'config': {
                'cidr': '%s/24' % C2_ip
            }
        }]
        self.container_body["nics"] = nic
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C2_name
        })

        self.lg.info("Get two containers client C1_client and C2_client.")
        C1_client = self.zeroCore.get_container_client(C1_name)
        C2_client = self.zeroCore.get_container_client(C2_name)

        self.lg.info(
            "Check that two containers get correct vxlan ip, should succeed ")
        self.assertTrue(
            self.zeroCore.check_container_vlan_vxlan_ip(C1_client, C1_ip))
        self.assertTrue(
            self.zeroCore.check_container_vlan_vxlan_ip(C2_client, C2_ip))

        self.lg.info(
            "first container C1 ping second container C2 ,should succeed")
        response = C1_client.bash('ping -w 5 %s' % C2_ip).get()
        self.assertEqual(response.state, "SUCCESS")

        self.lg.info(
            "second container C2 ping first container C1 ,should succeed")
        response = C2_client.bash('ping -w 5 %s' % C1_ip).get()
        self.assertEqual(response.state, "SUCCESS")

        self.lg.info(
            "Create third container c3 with different vxlan Id,should succeed")
        C3_ip = "201.100.3.3"
        C3_name = self.rand_str()
        nic = [{
            'type': 'default'
        }, {
            'type': 'vxlan',
            'id': "%s" % vxlan2_id,
            'config': {
                'cidr': '%s/24' % C3_ip
            }
        }]
        self.container_body["nics"] = nic
        self.container_body["name"] = C3_name
        response = self.containers_api.post_containers(
            nodeid=self.node_id, data=self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C3_name
        })
        C3_client = self.zeroCore.get_container_client(C3_name)
        self.assertTrue(C3_client)
        self.assertTrue(
            self.zeroCore.check_container_vlan_vxlan_ip(C3_client, C3_ip))

        self.lg.info(
            "Check if third container (c3) can ping (c1) and (c2), should fail."
        )
        response = C3_client.bash('ping -w 5 %s' % C1_ip).get()
        self.assertEqual(response.state, 'ERROR')
        response = C3_client.bash('ping -w 5 %s' % C2_ip).get()
        self.assertEqual(response.state, 'ERROR')

    def test011_create_containers_with_gateway_network_in_config(self):
        """ GAT-092

        *Test case for test creation of containers with gateway in configeration  *

        **Test Scenario:**

        #. Create bridge (B0) with nat true and  with static network mode .
        #. Create container (C1) with (B0) without gateway.
        #. Create container (C2) with (B0) with gateway same ip of bridge.
        #. Check that (C1) can connect to internet, should fail.
        #. Check that (C2) can connect to internt, should succeed.

        """
        self.lg.info("create ovs container")
        self.zeroCore.create_ovs_container()

        self.lg.info(
            'Create bridge with static network and nat true , should succeed')
        bridge_name = self.rand_str()
        hwaddr = self.randomMAC()
        bridge_cidr = "192.122.2.5"
        body = {
            "name": bridge_name,
            "hwaddr": hwaddr,
            "networkMode": "static",
            "nat": True,
            "setting": {
                "cidr": "%s/24" % bridge_cidr
            }
        }
        response = self.bridges_api.post_nodes_bridges(self.node_id, body)
        self.assertEqual(response.status_code, 201, response.content)
        time.sleep(3)

        self.lg.info("Create container (C1) with (B0) without gateway.")
        nics = [{
            "type": "bridge",
            "id": bridge_name,
            "config": {
                "cidr": "190.122.2.4/24"
            },
            "status": "up"
        }]
        self.container_body["nics"] = nics
        C1_name = self.rand_str()
        self.container_body["name"] = C1_name
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C1_name
        })

        self.lg.info(
            "Create container (C2) with (B0) with gateway same ip of bridge.")
        nics = [{
            "type": "bridge",
            "id": bridge_name,
            "config": {
                "cidr": "192.122.2.3/24",
                "gateway": bridge_cidr
            },
            "status": "up"
        }]
        C2_name = self.rand_str()
        self.container_body["nics"] = nics
        self.container_body["name"] = C2_name
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C2_name
        })

        C1_client = self.zeroCore.get_container_client(C1_name)
        C2_client = self.zeroCore.get_container_client(C2_name)

        self.lg.info("Check that C1 can connect to internet, should fail.")
        response = C1_client.bash("ping -w 5  8.8.8.8").get()
        self.assertEqual(response.state, "ERROR", response.stdout)

        self.lg.info("Check that C2 can connect to internet, should fail.")
        response = C2_client.bash("ping -w 5 8.8.8.8").get()
        self.assertEqual(response.state, "SUCCESS", response.stdout)

        self.lg.info("Delete created bridge ")
        self.bridges_api.delete_nodes_bridges_bridgeid(self.node_id,
                                                       bridge_name)

    def test012_create_container_with_dns_in_config(self):
        """ GAT-093

        *Test case for test creation of containers with different network and with dns *

        **Test Scenario:**

        #. Create container (C1) with type default in nic with dns.
        #. Check if values of dns in /etc/resolve.conf ,should fail .
        #. Create container (c2) with vlan and with dns .
        #. Check if values of dns in /etc/resolve.conf ,should succeed .

        """

        self.lg.info("create ovs container")
        self.zeroCore.create_ovs_container()

        self.lg.info(
            "create container (C1) with type default in nic with dns , should succeed"
        )

        C1_name = self.rand_str()
        dns = '8.8.4.4'
        cidr = "192.125.2.1"
        nic = [{
            'type': 'default',
            "config": {
                "cidr": "%s/8" % cidr,
                "dns": ["%s" % dns]
            }
        }]
        self.container_body["nics"] = nic
        self.container_body["name"] = C1_name
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C1_name
        })

        self.lg.info(
            "Check if values of dns in /etc/resolve.conf ,should fail")
        C1_client = self.zeroCore.get_container_client(C1_name)
        response = C1_client.bash('cat /etc/resolv.conf | grep %s' % dns).get()
        self.assertEqual(response.state, "ERROR")

        self.lg.info(
            " Create container (c2) with vlan and with dns, should succeed")
        C_ip = "201.100.2.0"
        vlan_Id = random.randint(1, 4096)
        C2_name = self.rand_str()
        self.container_body["name"] = C2_name
        nic = [{
            'type': 'default'
        }, {
            'type': 'vlan',
            'id': "%s" % vlan_Id,
            'config': {
                'cidr': '%s/24' % C_ip,
                'dns': ['%s' % dns]
            }
        }]
        self.container_body["nics"] = nic
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C2_name
        })

        self.lg.info(
            "Check if values of dns in /etc/resolve.conf ,should succeed. ")
        C2_client = self.zeroCore.get_container_client(C2_name)
        response = C2_client.bash('cat /etc/resolv.conf | grep %s' % dns).get()
        self.assertEqual(response.state, "SUCCESS")
        response = C2_client.bash('ping -c 2 %s' % dns).get()
        self.assertEqual(response.state, "SUCCESS")

    def test013_create_container_with_filesystem(self):
        """ GAT-094

        *Test case for test creation of containers with filesystem. *

        **Test Scenario:**

        #. Create file system in fsucash storage pool.
        #. Create container with created file system,should succeed .
        #. Check that file exist in /fs/storagepool_name/filesystem_name ,should succeed .
        """

        self.lg.info("Create file system in fsucash storage pool")
        name = self.random_string()

        quota = random.randint(1, 100)
        body = {"name": name, "quota": quota}
        storagepool_name = "%s_fscache" % self.node_id
        response = self.storagepool_api.post_storagepools_storagepoolname_filesystems(
            self.node_id, storagepool_name, body)
        self.assertEqual(response.status_code, 201)
        time.sleep(5)

        self.lg.info(
            "Create container with created file system,should succeed.")
        self.container_body["filesystems"].append("%s:%s" %
                                                  (storagepool_name, name))
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": self.container_name
        })

        self.lg.info(
            "Check that file exist in /fs/storagepool_name/filesystem_name ,should succeed"
        )
        C_client = self.zeroCore.get_container_client(self.container_name)
        response = C_client.filesystem.list('/fs/%s' % storagepool_name)
        self.assertEqual(response[0]['name'], name)

    def test014_Writing_in_containers_files(self):
        """ GAT-095

        *Test case for test writing in containner files *

        **Test Scenario:**

        #. Create two conainer  container C1,C2 ,should succeed.
        #. Create file in C1,should succeed.
        #. Check that created file doesn't exicst in C2.

        """
        self.lg.info("Create two conainer  container C1,C2 ,should succeed.")
        C1_name = self.rand_str()
        C2_name = self.rand_str()
        self.container_body["name"] = C1_name
        response = self.containers_api.post_containers(
            nodeid=self.node_id, data=self.container_body)
        self.assertTrue(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C1_name
        })

        C2_name = self.rand_str()
        self.container_body["name"] = C2_name
        response = self.containers_api.post_containers(
            nodeid=self.node_id, data=self.container_body)
        self.assertTrue(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C2_name
        })
        C1_client = self.zeroCore.get_container_client(C1_name)
        C2_client = self.zeroCore.get_container_client(C2_name)

        self.lg.info("Create file in C1,should succeed.")
        file_name = self.rand_str()
        response = C1_client.bash("touch %s" % file_name).get()
        self.assertEqual(response.state, 'SUCCESS')

        self.lg.info("Check that created file doesn't exicst in C2.")

        response = C1_client.bash("ls | grep %s" % file_name).get()
        self.assertEqual(response.state, 'SUCCESS')

        response = C2_client.bash("ls | grep %s" % file_name).get()
        self.assertEqual(response.state, 'ERROR')

    def test015_create_containers_with_open_ports(self):
        """ GAT-096

        *Test case for test create containers with open ports*

        **Test Scenario:**

        #. Create container C1 with open port .
        #. Open server in container port ,should succeed.
        #. Check that portforward work,should succeed
        """

        file_name = self.rand_str()
        hostport = "6060"
        containerport = "60"
        ports = "%s:%s" % (hostport, containerport)
        nics = [{"type": "default"}]
        self.container_body["nics"] = nics
        self.container_body["ports"].append(ports)

        self.lg.info("Create container C1 with open port")
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertTrue(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": self.container_name
        })
        C1_client = self.zeroCore.get_container_client(self.container_name)
        self.zeroCore.timeout = 300
        time.sleep(2)
        self.lg.info("Open server in container port ,should succeed")
        response = C1_client.bash("apt-get -y install python ").get()
        self.assertEqual(response.state, "SUCCESS")
        response = C1_client.bash(
            "mkdir {0} && cd {0}&& echo 'test'>{0}.text ".format(
                file_name)).get()
        self.assertEqual(response.state, "SUCCESS")
        C1_client.bash("cd %s &&  nohup python -m SimpleHTTPServer %s & " %
                       (file_name, containerport))

        self.lg.info("Check that portforward work,should succeed")
        response = C1_client.bash("netstat -nlapt | grep %s" %
                                  containerport).get()
        self.assertEqual(response.state, 'SUCCESS')
        url = ' http://{0}:{1}/{2}.text'.format(self.zeroCore_ip, hostport,
                                                file_name)
        response = urlopen(url)
        html = response.read()
        self.assertIn("test", html.decode('utf-8'))

    @unittest.skip("https://github.com/g8os/resourcepool/issues/297")
    def test016_post_new_job_to_container_with_specs(self):
        """ GAT-097

        *Test case for test create containers with open ports*

        **Test Scenario:**

        #. Create containers C1 , should succeed
        #. post job with to container with all specs ,should succeed.
        #. check that job created successfully with it's specs.

        """
        self.lg.info("Create container C1, should succeed.")
        self.container_body[
            'flist'] = "https://hub.gig.tech/dina_magdy/initprocess.flist"
        ## flist which have script which print environment varaibles and print stdin
        Environmentvaraible = "MYVAR=%s" % self.rand_str()
        stdin = self.rand_str()
        job_body = {
            'name': 'sh',
            'pwd': '/',
            'args': ["sbin/process_init"],
            "environment": [Environmentvaraible],
            "stdin": stdin
        }

        response = self.containers_api.post_containers(
            nodeid=self.node_id, data=self.container_body)
        self.assertTrue(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": self.container_name
        })
        C1_client = self.zeroCore.get_container_client(self.container_name)

        self.lg.info(
            'Send post  nodes/{nodeid}/containers/containerid/jobs api request.'
        )
        response = self.containers_api.post_containers_containerid_jobs(
            self.node_id, self.container_name, job_body)
        self.assertEqual(response.status_code, 202)
        job_id = response.headers['Location'].split('/')[6]
        self.assertTrue(
            self.zeroCore.wait_on_container_job_update(self.container_name,
                                                       job_id, 15, False))

        self.lg.info("check that job created successfully with it's specs.")
        response = C1_client.bash("ls |grep  out.text").get()
        self.assertEqual(response.state, "SUCCESS")
        response = C1_client.bash("cat out.text | grep %s" % stdin).get()
        self.assertEqual(response.state, "SUCCESS",
                         "job didn't get stdin correctly")
        response = C1_client.bash("cat out.text | grep %s" %
                                  Environmentvaraible).get()
        self.assertEqual(response.state, "SUCCESS",
                         "job didn't get Env varaible  correctly")

    def test017_Create_containers_with_common_vlan(self):
        """ GAT-098

        *Test case for test creation of containers with cmmon vlan  network*

        **Test Scenario:**

        #. Create ovs container .
        #. Create C1 which is binding to vlan1 and vlan2.
        #. Create C2 which is binding to vlan1.
        #. Create C3 which is binding to vlan2.
        #. Check that containers get correct vlan ip, should succeed
        #. Check that C1 can ping C2 and C3 ,should succeed.
        #. Check that C2 can ping C1 and can't ping C3, should succeed.
        #. Check that C3 can ping C1 and can't ping C2,should succeed.

        """
        self.lg.info("create ovs container")
        self.zeroCore.create_ovs_container()
        vlan1_id, vlan2_id = random.sample(range(1, 4096), 2)
        C1_ip_vlan1 = "201.100.2.1"
        C1_ip_vlan2 = "201.100.3.1"
        C2_ip = "201.100.2.2"
        C3_ip = "201.100.3.2"

        self.lg.info("Create C1 which is binding to vlan1 and vlan2.")
        C1_name = self.rand_str()
        nic = [{
            'type': 'vlan',
            'id': vlan1_id,
            'config': {
                'cidr': '%s/24' % C1_ip_vlan1
            }
        }, {
            'type': 'vlan',
            'id': vlan2_id,
            'config': {
                'cidr': '%s/24' % C1_ip_vlan2
            }
        }]
        self.container_body["nics"] = nic
        self.container_body["name"] = C1_name
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C1_name
        })

        self.lg.info("Create C2 which is binding to vlan1.")
        C2_name = self.rand_str()
        nic = [{
            'type': 'vlan',
            'id': vlan1_id,
            'config': {
                'cidr': '%s/24' % C2_ip
            }
        }]
        self.container_body["nics"] = nic
        self.container_body["name"] = C2_name
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C2_name
        })

        self.lg.info("Create C3 which is binding to vlan2.")
        C3_name = self.rand_str()
        nic = [{
            'type': 'vlan',
            'id': vlan2_id,
            'config': {
                'cidr': '%s/24' % C3_ip
            }
        }]
        self.container_body["nics"] = nic
        self.container_body["name"] = C3_name
        response = self.containers_api.post_containers(self.node_id,
                                                       self.container_body)
        self.assertEqual(response.status_code, 201)
        self.createdcontainer.append({
            "node": self.node_id,
            "container": C3_name
        })

        self.lg.info(
            "Get three containers client C1_client ,C2_client ansd C3_client.")
        C1_client = self.zeroCore.get_container_client(C1_name)
        C2_client = self.zeroCore.get_container_client(C2_name)
        C3_client = self.zeroCore.get_container_client(C3_name)

        self.lg.info(
            "Check that containers get correct vlan ip, should succeed ")
        self.assertTrue(
            self.zeroCore.check_container_vlan_vxlan_ip(
                C1_client, C1_ip_vlan1))
        self.assertTrue(
            self.zeroCore.check_container_vlan_vxlan_ip(
                C1_client, C1_ip_vlan2))
        self.assertTrue(
            self.zeroCore.check_container_vlan_vxlan_ip(C2_client, C2_ip))
        self.assertTrue(
            self.zeroCore.check_container_vlan_vxlan_ip(C3_client, C3_ip))

        self.lg.info("Check that C1 can ping C2 and C3 ,should succeed.")
        response = C1_client.bash('ping -w 5 %s' % C2_ip).get()
        self.assertEqual(response.state, "SUCCESS")
        response = C1_client.bash('ping -w 5 %s' % C3_ip).get()
        self.assertEqual(response.state, "SUCCESS")

        self.lg.info(
            "Check that C2 can ping C1 and can't ping C3, should succeed.")
        response = C2_client.bash('ping -w 5 %s' % C1_ip_vlan1).get()
        self.assertEqual(response.state, "SUCCESS")

        response = C2_client.bash('ping -w 5 %s' % C3_ip).get()
        self.assertEqual(response.state, "ERROR")

        self.lg.info(
            "Check that C3 can ping C1 and can't ping C2, should succeed.")
        response = C3_client.bash('ping -w 5 %s' % C1_ip_vlan2).get()
        self.assertEqual(response.state, "SUCCESS")

        response = C3_client.bash('ping -w 5 %s' % C2_ip).get()
        self.assertEqual(response.state, "ERROR")
class TestStoragepoolsAPI(TestcasesBase):
    def setUp(self):
        super().setUp()
        self.storagepool_api = StoragepoolsAPI()
        self.nodeid = self.get_random_node()
        self.nodeip = [x['ip'] for x in self.nodes if x['id'] == self.nodeid]
        self.jwt = self.nodes_api.jwt
        self.pyclient = Client(self.nodeip[0], password=self.jwt)
        self.CLEANUP = []

    def tearDown(self):
        for storagepool in self.CLEANUP:
            self.storagepool_api.delete_storagepools_storagepoolname(self.nodeid, storagepool)
        super(TestStoragepoolsAPI, self).tearDown()

    def create_storagepool(self):
        freeDisks = self.pyclient.getFreeDisks()
        if freeDisks == []:
            self.skipTest('no free disks on node {}'.format(self.nodeid))

        self.lg.info('Create storagepool (SP0) on node (N0)')
        name = self.random_string()
        metadata = 'single'
        data = 'single'
        device = random.choice(freeDisks)
        body = {"name":name,
                "metadataProfile":metadata,
                "dataProfile":data,
                "devices":[device]}

        response = self.storagepool_api.post_storagepools(self.nodeid, body)
        self.assertEqual(response.status_code, 201)

        for _ in range(60):
            freeDisks = self.pyclient.getFreeDisks()
            if device not in freeDisks:
                self.CLEANUP.append(name)
                break
            else:
                time.sleep(3)
        else:
            self.lg.error('storagepool {} doesn\'t mount device {}'.format(name, device))
            
        return body

    def delete_storage_pool(self, storagepool):
        response = self.storagepool_api.delete_storagepools_storagepoolname(self.nodeid, storagepool)
        if response.status_code == 204:
            try:
                self.CLEANUP.remove(storagepool)
            except:
                pass
        
    def create_filesystem(self, storagepool):
        self.lg.info('Create filesystem (FS0) on storagepool {}'.format(storagepool))
        name = self.random_string()
        quota = random.randint(0, 10)
        body = {"name":name, "quota":quota}
        response = self.storagepool_api.post_storagepools_storagepoolname_filesystems(self.nodeid, storagepool, body)
        self.assertEqual(response.status_code, 201)
        for _ in range(60):
            try:
                data = self.pyclient.client.btrfs.subvol_list('/mnt/storagepools/{}'.format(storagepool))
                filesystems = [x for x in data if 'filesystems' in x['Path']]
                filesystems = [x['Path'][x['Path'].rfind('/')+1:] for x in filesystems]
                if name in filesystems:
                    break
                else:
                    time.sleep(3)
            except:
                pass
        else:
            self.lg.error('filesystem {} is not created {}'.format(name))
        return body
        
    def create_snapshot(self, storagepool, filesystem):
        self.lg.info('Create snapshot (SS0) of filesystem {}'.format(filesystem))
        name = self.rand_str()
        body = {"name":name}
        self.storagepool_api.post_filesystems_snapshots(self.nodeid, storagepool, filesystem, body)

        for _ in range(60):
            try:
                data = self.pyclient.client.btrfs.subvol_list('/mnt/storagepools/{}'.format(storagepool))
                snapshots = [x for x in data if 'snapshots/{}'.format(filesystem) in x['Path']]
                snapshots = [x['Path'][x['Path'].rfind('/')+1:] for x in snapshots]
                if name in snapshots:
                    break
                else:
                    time.sleep(3)
            except:
                pass
        else:
            self.lg.error('snapshot {} is not created {}'.format(name))

        return body
    

    def test001_get_storagepool(self):
        """ GAT-045
        **Test Scenario:**

        #. Create storagepool (SP0) on node (N0), should succeed.
        #. Get storagepool (SP0), should succeed with 200.
        #. Get storagepool (SP0) using python client, should be listed
        #. Get nonexisting storagepool, should fail with 404.
        """
        self.lg.info('Create storagepool (SP0) on node (N0), should succeed')
        storagepool = self.create_storagepool()
        
        self.lg.info('Get storagepool (SP0), should succeed with 200')
        response = self.storagepool_api.get_storagepools_storagepoolname(self.nodeid, storagepool['name'])
        self.assertEqual(response.status_code, 200)
        for key in storagepool.keys():
            if key == 'devices':
                continue
            self.assertEqual(response.json()[key], storagepool[key])

        self.lg.info('Get storagepool (SP0) using python client, should be listed')
        storagepools = self.pyclient.client.btrfs.list()
        storagepool_sp0 = [x for x in storagepools if x['label'] == 'sp_{}'.format(storagepool['name'])]
        self.assertNotEqual(storagepool_sp0, [])
        for device in storagepool['devices']: 
            self.assertIn(device, [x['path'][:-1] for x in storagepool_sp0[0]['devices']])

        self.lg.info('Get nonexisting storagepool, should fail with 404')
        response = self.storagepool_api.get_storagepools_storagepoolname(self.nodeid, 'fake_storagepool')
        self.assertEqual(response.status_code, 404)


    def test002_list_storagepool(self):
        """ GAT-046
        **Test Scenario:**

        #. Create Storagepool (SP0) on node (N0).
        #. list node (N0) storagepools, storagepool (SP0) should be listed.
        """
        self.lg.info('Create storagepool (SP0) on node (N0), should succeed')
        storagepool = self.create_storagepool()

        self.lg.info('list node (N0) storagepools, storagepool (SP0) should be listed')
        response = self.storagepool_api.get_storagepools(self.nodeid)
        self.assertEqual(response.status_code, 200)
        self.assertIn(storagepool['name'], [x['name'] for x in response.json()])

    def test003_post_storagepool(self):
        """ GAT-047
        **Test Scenario:**

        #. Get random nodid (N0).
        #. Create storagepool (SP0) on node (N0).
        #. Get storagepool (SP0), should succeed with 200.
        #. Get storagepool (SP1) using python client, should be listed
        #. Delete Storagepool (SP0), should succeed with 204.
        #. Create invalid storagepool (missing required params), should fail with 400.
        """

        self.lg.info('Create Storagepool (SP1), should succeed with 201')
        name = self.random_string()
        free_devices = self.pyclient.getFreeDisks()

        levels = ['raid0', 'raid1', 'raid5', 'raid6', 'raid10', 'dup', 'single']

        if free_devices == []:
            self.skipTest('no free disks on node {}'.format(self.nodeid))

        if len(free_devices) < 6:
            metadata = 'single'
            data = 'single'
            devices = [random.choice(free_devices)]
        else:
            metadata = self.random_item(levels)
            data = self.random_item(levels)
            devices = free_devices[:4]

        body = {"name":name,
                "metadataProfile":metadata,
                "dataProfile":data,
                "devices":devices}

        response = self.storagepool_api.post_storagepools(self.nodeid, body)
        self.assertEqual(response.status_code, 201)
        time.sleep(30)

        self.lg.info('Get Storagepool (SP1), should succeed with 200')
        response = self.storagepool_api.get_storagepools_storagepoolname(self.nodeid, name)
        self.assertEqual(response.status_code, 200)
        for key in body.keys():
            if key == 'devices':
                continue
            self.assertEqual(response.json()[key], body[key])

        time.sleep(20)
        self.lg.info('Get storagepool (SP0) using python client, should be listed')
        storagepools = self.pyclient.client.btrfs.list()
        storagepool_sp1 = [x for x in storagepools if x['label'] == 'sp_{}'.format(name)]
        self.assertNotEqual(storagepool_sp1, [])
        
        for device in devices:
            self.assertIn(device, [x['path'][:-1] for x in storagepool_sp1[0]['devices']])

        self.lg.info('Delete Storagepool (SP0), should succeed with 204')
        response = self.storagepool_api.delete_storagepools_storagepoolname(self.nodeid, name)
        self.assertEqual(response.status_code, 204)

        self.lg.info('Create invalid storagepool, should fail with 400')
        body = {"name":name, "metadataProfile":metadata}
        response = self.storagepool_api.post_storagepools(self.nodeid, body)
        self.assertEqual(response.status_code, 400)

    def test004_delete_storagepool(self):
        """ GAT-048
        **Test Scenario:**

        #. Create Storagepool (SP0) on node (N0).
        #. Delete Storagepool (SP0), should succeed with 204.
        #. list node (N0) storagepools, storagepool (SP0) should be gone.
        #. Delete nonexisting storagepool, should fail with 404.
        """

        self.lg.info('Create storagepool (SP0) on node (N0), should succeed')
        storagepool = self.create_storagepool()

        self.lg.info('Delete storagepool (SP0), should succeed with 204')
        response = self.storagepool_api.delete_storagepools_storagepoolname(self.nodeid, storagepool['name'])
        self.assertEqual(response.status_code, 204)
        self.CLEANUP.remove(storagepool['name'])

        self.lg.info('list node (N0) storagepools, storagepool (SP0) should be gone')
        response = self.storagepool_api.get_storagepools(self.nodeid)
        self.assertEqual(response.status_code, 200)
        self.assertNotIn(storagepool['name'], [x['name'] for x in response.json()])

        self.lg.info('Delete nonexisting storagepool, should fail with 404')
        response = self.storagepool_api.delete_storagepools_storagepoolname(self.nodeid, 'fake_storagepool')
        self.assertEqual(response.status_code, 404)

    # @unittest.skip('https://github.com/zero-os/0-orchestrator/issues/209')
    def test005_get_storagepool_device(self):
        """ GAT-049
        **Test Scenario:**

        #. Create storagepool (SP0) with device (DV0) on node (N0).
        #. Get device (DV0), should succeed with 200.
        #. Get nonexisting device, should fail with 404.
        """
        self.lg.info('Create storagepool (SP0) on node (N0), should succeed')
        storagepool = self.create_storagepool()
        time.sleep(15)

        self.lg.info('Get device (DV0), should succeed with 200')
        response = self.storagepool_api.get_storagepools_storagepoolname_devices(self.nodeid, storagepool['name'])
        self.assertEqual(response.status_code, 200)
        self.assertNotEqual(response.json(), [])
        device_uuid = response.json()[0]['uuid']

        response = self.storagepool_api.get_storagepools_storagepoolname_devices_deviceid(self.nodeid, storagepool['name'], device_uuid)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json()['deviceName'][:-1], storagepool['devices'][0])
        self.assertEqual(response.json()['uuid'], device_uuid)
        self.assertEqual(response.json()['status'], 'healthy')

        self.lg.info('Get nonexisting device, should fail with 404')
        response = self.storagepool_api.get_storagepools_storagepoolname_devices_deviceid(self.nodeid, storagepool['name'], 'fake_device')
        self.assertEqual(response.status_code, 404)

    def test006_list_storagepool_devices(self):
        """ GAT-050
        **Test Scenario:**

        #. Create storagepool (SP0) with device (DV0) on node (N0).
        #. list storagepool (SP0) devices, should succeed with 200.
        """
        self.lg.info('Create storagepool (SP0) on node (N0), should succeed')
        storagepool = self.create_storagepool()

        self.lg.info('list storagepool (SP0) devices, should succeed with 200')
        response = self.storagepool_api.get_storagepools_storagepoolname_devices(self.nodeid, storagepool['name'])
        self.assertEqual(response.status_code, 200)
        self.assertNotEqual(response.json(), [])
        self.assertEqual(len(response.json()), len(storagepool['devices']))
        self.assertEqual(response.json()[0]['status'], 'healthy')

    def test007_post_storagepool_device(self):
        """ GAT-051
        **Test Scenario:**

        #. Get random nodid (N0).
        #. Create storagepool (SP0) with device (DV0) on node (N0).
        #. Create device (DV1) on storagepool (SP0), should succeed with 201.
        #. list storagepool (SP0) devices, device (DV1) should be listed.
        #. Create device with invalid body, should fail with 400.
        """
        self.lg.info('Create storagepool (SP0) on node (N0), should succeed')
        storagepool = self.create_storagepool()

        self.lg.info('Create device (DV1) on storagepool (SP0), should succeed with 201')
        free_devices = self.pyclient.getFreeDisks()
        if free_devices == []:
            self.skipTest('no free disks on node {}'.format(self.nodeid))

        device = random.choice(free_devices)
        body = [device]
        response = self.storagepool_api.post_storagepools_storagepoolname_devices(self.nodeid, storagepool['name'], body)
        self.assertEqual(response.status_code, 201)
        
        for _ in range(30):
            free_devices = self.pyclient.getFreeDisks()
            if device not in free_devices:
                break
            else:
                time.sleep(1)
            
        self.lg.info('list storagepool (SP0) devices, should succeed with 200')
        response = self.storagepool_api.get_storagepools_storagepoolname_devices(self.nodeid, storagepool['name'])
        self.assertEqual(response.status_code, 200)
        self.assertIn(device, [x['deviceName'][:-1] for x in response.json()])

        #issue https://github.com/zero-os/0-orchestrator/issues/398
        # self.lg.info('Create device with invalid body, should fail with 400')
        # body = ""
        # response = self.storagepool_api.post_storagepools_storagepoolname_devices(self.nodeid, storagepool['name'], body)
        # self.assertEqual(response.status_code, 400)
    
    # @unittest.skip('https://github.com/zero-os/0-orchestrator/issues/209')
    def test008_delete_storagepool_device(self):
        """ GAT-052
        **Test Scenario:**

        #. Create storagepool (SP0) with device (DV0) on node (N1), should succeed with 201.
        #. Delete device (DV0), should succeed with 204.
        #. list storagepool (SP0) devices, device (DV0) should be gone.
        #. Delete nonexisting device, should fail with 404.
        """
        self.lg.info('Create storagepool (SP0) on node (N0), should succeed')
        storagepool = self.create_storagepool()

        self.lg.info('Create device (DV1) on storagepool (SP0), should succeed with 201')
        free_devices = self.pyclient.getFreeDisks()
        if free_devices == []:
            self.skipTest('no free disks on node {}'.format(self.nodeid))

        device = random.choice(free_devices)
        body = [device]
        response = self.storagepool_api.post_storagepools_storagepoolname_devices(self.nodeid, storagepool['name'], body)
        self.assertEqual(response.status_code, 201)
        
        for _ in range(30):
            free_devices = self.pyclient.getFreeDisks()
            if device not in free_devices:
                break
            else:
                time.sleep(1)

        self.lg.info('list storagepool (SP0) devices, device (DV0) should be gone')
        response = self.storagepool_api.get_storagepools_storagepoolname_devices(self.nodeid, storagepool['name'])
        self.assertEqual(response.status_code, 200)
        deviceuuid = [x['uuid'] for x in response.json() if x['deviceName'][:-1] == device]
        self.assertNotEqual(deviceuuid, [], 'device was not added to storagepool')

        self.lg.info('Delete device (DV1), should succeed with 204')
        response = self.storagepool_api.delete_storagepools_storagepoolname_devices_deviceid(self.nodeid, storagepool['name'], deviceuuid[0])
        self.assertEqual(response.status_code, 204)

        for _ in range(30):
            free_devices = self.pyclient.getFreeDisks()
            if device in free_devices:
                break
            else:
                time.sleep(1)

        self.lg.info('list storagepool (SP0) devices, device (DV0) should be gone')
        response = self.storagepool_api.get_storagepools_storagepoolname_devices(self.nodeid, storagepool['name'])
        self.assertEqual(response.status_code, 200)
        self.assertNotIn(device, [x['deviceName'][:-1] for x in response.json()])

        self.lg.info('Delete nonexisting device, should fail with 404')
        response = self.storagepool_api.delete_storagepools_storagepoolname_devices_deviceid(self.nodeid, storagepool['name'], 'fake_device')
        self.assertEqual(response.status_code, 404)

    def test009_get_storagepool_filessystem(self):
        """ GAT-053
        **Test Scenario:**

        #. Create storagepool (SP0) on node (N0), should succeed.
        #. Create filesystem (FS0) on storagepool (SP0).
        #. Get filesystem (FS0), should succeed with 200.
        #. Get nonexisting filesystem, should fail with 404.
        """
        self.lg.info('Create storagepool (SP0) on node (N0), should succeed')
        storagepool = self.create_storagepool()

        self.lg.info('Create filesystem (FS0) on storagepool (SP0)')
        filesystem = self.create_filesystem(storagepool['name'])

        self.lg.info('Get filesystem (FS0), should succeed with 200')
        response = self.storagepool_api.get_storagepools_storagepoolname_filesystems_filesystemname(self.nodeid, storagepool['name'], filesystem['name'])
        self.assertEqual(response.status_code, 200)
        for key in filesystem.keys():
            self.assertEqual(response.json()[key], filesystem[key])

        self.lg.info('Get nonexisting filesystem, should fail with 404')
        response = self.storagepool_api.get_storagepools_storagepoolname_filesystems_filesystemname(self.nodeid, storagepool['name'], 'fake_filesystem')
        self.assertEqual(response.status_code, 404)

    def test010_list_storagepool_filesystems(self):
        """ GAT-054
        **Test Scenario:**

        #. Create Storagepool (SP0) on node (N0).
        #. Create filesystem (FS0) on storagepool (SP0).
        #. list storagepools (SP0) filesystems, filesystem (FS0) should be listed.
        """
        self.lg.info('Create storagepool (SP0) on node (N0), should succeed')
        storagepool = self.create_storagepool()

        self.lg.info('Create filesystem (FS0) on storagepool (SP0)')
        filesystem = self.create_filesystem(storagepool['name'])

        self.lg.info('list storagepools (SP0) filesystems, filesystem (FS0) should be listed')
        response = self.storagepool_api.get_storagepools_storagepoolname_filesystems(self.nodeid, storagepool['name'])
        self.assertEqual(response.status_code, 200)
        self.assertIn(filesystem['name'], response.json())

    def test011_post_storagepool_filesystem(self):
        """ GAT-055
        **Test Scenario:**

        #. Get random nodid (N0).
        #. Create storagepool (SP0) on node (N0).
        #. Create filesystem (FS1) on storagepool (SP0), should succeed with 201.
        #. Get filesystem (FS1), should succeed with 200.
        #. Delete filesystem (FS1), should succeed with 204.
        #. Create invalid filesystem (missing required params), should fail with 400.
        """
        self.lg.info('Create storagepool (SP0) on node (N0), should succeed')
        storagepool = self.create_storagepool()
        
        self.lg.info('Create filesystem (FS1) on storagepool (SP0), should succeed with 201')
        name = self.random_string()
        quota = random.randint(0, 10)
        body = {"name":name, "quota":quota}
        response = self.storagepool_api.post_storagepools_storagepoolname_filesystems(self.nodeid, storagepool['name'], body)
        self.assertEqual(response.status_code, 201)
        time.sleep(5)

        self.lg.info('Get filesystem (FS1), should succeed with 200')
        response = self.storagepool_api.get_storagepools_storagepoolname_filesystems_filesystemname(self.nodeid, storagepool['name'], name)
        self.assertEqual(response.status_code, 200)
        for key in body.keys():
            self.assertEqual(response.json()[key], body[key])

        self.lg.info('Delete filesystem (FS1), should succeed with 204')
        response = self.storagepool_api.delete_storagepools_storagepoolname_filesystems_filesystemname(self.nodeid, storagepool['name'], name)
        self.assertEqual(response.status_code, 204)

        self.lg.info('Create filesystem with invalid body, should fail with 400')
        body = {self.random_string() : self.random_string()}
        response = self.storagepool_api.post_storagepools_storagepoolname_filesystems(self.nodeid, storagepool['name'], body)
        self.assertEqual(response.status_code, 400)

    def test012_delete_storagepool_filesystem(self):
        """ GAT-056
        **Test Scenario:**

        #. Create Storagepool (SP0) on node (N0).
        #. Create filesystem (FS0) on storagepool (SP0).
        #. Delete filesystem (FS0), should succeed with 204.
        #. list storagepool (SP0) filesystems, filesystem (FS0) should be gone.
        #. Delete nonexisting filesystems, should fail with 404.
        """
        self.lg.info('Create storagepool (SP0) on node (N0), should succeed')
        storagepool = self.create_storagepool()

        self.lg.info('Create filesystem (FS0) on storagepool (SP0)')
        filesystem = self.create_filesystem(storagepool['name'])

        self.lg.info('Delete filesystem (FS0), should succeed with 204')
        response = self.storagepool_api.delete_storagepools_storagepoolname_filesystems_filesystemname(self.nodeid, storagepool['name'], filesystem['name'])
        self.assertEqual(response.status_code, 204)

        self.lg.info('list storagepool (SP0) filesystems, filesystem (FS0) should be gone')
        response = self.storagepool_api.get_storagepools_storagepoolname_filesystems(self.nodeid, storagepool['name'])
        self.assertEqual(response.status_code, 200)
        self.assertNotIn(filesystem['name'], response.json())

        self.lg.info('Delete nonexisting filesystems, should fail with 404')
        response = self.storagepool_api.delete_storagepools_storagepoolname_filesystems_filesystemname(self.nodeid, storagepool['name'], 'fake_filesystem')
        self.assertEqual(response.status_code, 404)

    # @unittest.skip('https://github.com/zero-os/0-orchestrator/issues/687')
    def test013_get_storagepool_filessystem_snapshot(self):
        """ GAT-057
        **Test Scenario:**

        #. Create storagepool (SP0) on node (N0), should succeed.
        #. Create filesystem (FS0) on storagepool (SP0).
        #. Create snapshot (SS0) on filesystem (FS0).
        #. Get snapshot (SS0), should succeed with 200.
        #. Get nonexisting snapshot, should fail with 404.
        """
        self.lg.info('Create storagepool (SP0) on node (N0), should succeed')
        storagepool = self.create_storagepool()

        self.lg.info('Create filesystem (FS0) on storagepool (SP0)')
        filesystem = self.create_filesystem(storagepool['name'])

        self.lg.info('Create snapshot (SS0) on filesystem (FS0)')
        snapshot = self.create_snapshot(storagepool['name'], filesystem['name'])


        self.lg.info('Get snapshot (SS0), should succeed with 200')
        response = self.storagepool_api.get_filesystem_snapshots_snapshotname(self.nodeid, storagepool['name'],
                                                                                           filesystem['name'],
                                                                                           snapshot['name'])
        self.assertEqual(response.status_code, 200)
        for key in snapshot.keys():
            self.assertEqual(response.json()[key], snapshot[key])

        self.lg.info('Get nonexisting snapshot, should fail with 404')
        response = self.storagepool_api.get_filesystem_snapshots_snapshotname(self.nodeid, storagepool['name'],
                                                                                           filesystem['name'],
                                                                                           'fake_snapshot')
        self.assertEqual(response.status_code, 404)

    # @unittest.skip('https://github.com/zero-os/0-orchestrator/issues/687')
    def test014_list_storagepool_filesystems_snapshots(self):
        """ GAT-058
        **Test Scenario:**

        #. Create storagepool (SP0) on node (N0), should succeed.
        #. Create filesystem (FS0) on storagepool (SP0).
        #. Create snapshot (SS0) on filesystem (FS0).
        #. list snapshots of filesystems (FS0), snapshot (SS0) should be listed.
        """
        self.lg.info('Create storagepool (SP0) on node (N0), should succeed')
        storagepool = self.create_storagepool()

        self.lg.info('Create filesystem (FS0) on storagepool (SP0)')
        filesystem = self.create_filesystem(storagepool['name'])

        self.lg.info('Create snapshot (SS0) on filesystem (FS0)')
        snapshot = self.create_snapshot(storagepool['name'], filesystem['name'])
        
        self.lg.info('list snapshots of filesystems (FS0), snapshot (SS0) should be listed')
        response = self.storagepool_api.get_filesystem_snapshots(self.nodeid, storagepool['name'], filesystem['name'])
        self.assertEqual(response.status_code, 200)
        self.assertIn(snapshot['name'], response.json())

    # @unittest.skip('https://github.com/zero-os/0-orchestrator/issues/687')
    def test015_post_storagepool_filesystem_snapshot(self):
        """ GAT-059
        **Test Scenario:**

        #. Create storagepool (SP0) on node (N0), should succeed.
        #. Create filesystem (FS0) on storagepool (SP0).
        #. Create snapshot (SS1) on filesystem (FS0).
        #. Get snapshot (SS1), should succeed with 200.
        #. Delete snapshot (SS1), should succeed with 204.
        #. Create snapshot with missing required params, should fail with 400.
        """
        self.lg.info('Create storagepool (SP0) on node (N0), should succeed')
        storagepool = self.create_storagepool()

        self.lg.info('Create filesystem (FS0) on storagepool (SP0)')
        filesystem = self.create_filesystem(storagepool['name'])

        self.lg.info('Create snapshot (SS1) on filesystem (FS0)')
        name = self.random_string()
        body = {"name":name}
        response = self.storagepool_api.post_filesystems_snapshots(self.nodeid, storagepool['name'], filesystem['name'], body)
        self.assertEqual(response.status_code, 201)

        self.lg.info(' Get snapshot (SS1), should succeed with 200')
        response = self.storagepool_api.get_filesystem_snapshots_snapshotname(self.nodeid, storagepool['name'],
                                                                                           filesystem['name'],
                                                                                           name)
        self.assertEqual(response.status_code, 200)
        for key in body.keys():
            self.assertEqual(response.json()[key], body[key])

        self.lg.info('Delete snapshot (SS1), should succeed with 204')
        response = self.storagepool_api.delete_filesystem_snapshots_snapshotname(self.nodeid, storagepool['name'],
                                                                                              filesystem['name'],
                                                                                              name)
        self.assertEqual(response.status_code, 204)

        self.lg.info('Create snapshot with missing required params, should fail with 400')
        body = {}
        response = self.storagepool_api.post_filesystems_snapshots(self.nodeid, storagepool['name'], filesystem['name'], body)
        self.assertEqual(response.status_code, 400)

    # @unittest.skip('https://github.com/zero-os/0-orchestrator/issues/687')
    def test016_delete_storagepool_filesystem_snapshot(self):
        """ GAT-060
        **Test Scenario:**

        #. Get random nodid (N0), should succeed.
        #. Create storagepool (SP0) on node (N0), should succeed.
        #. Create filesystem (FS0) on storagepool (SP0).
        #. Create snapshot (SS0) on filesystem (FS0).
        #. Delete  snapshot (SS0), should succeed with 204.
        #. list filesystem (FS0) snapshots, snapshot (SS0) should be gone.
        #. Delete nonexisting snapshot, should fail with 404.
        """

        self.lg.info('Create storagepool (SP0) on node (N0), should succeed')
        storagepool = self.create_storagepool()

        self.lg.info('Create filesystem (FS0) on storagepool (SP0)')
        filesystem = self.create_filesystem(storagepool['name'])

        self.lg.info('Create snapshot (SS0) on filesystem (FS0)')
        snapshot = self.create_snapshot(storagepool['name'], filesystem['name'])

        self.lg.info('Delete  snapshot (SS0), should succeed with 204')
        response = self.storagepool_api.delete_filesystem_snapshots_snapshotname(self.nodeid, storagepool['name'],
                                                                                              filesystem['name'],
                                                                                              snapshot['name'])
        self.assertEqual(response.status_code, 204)

        self.lg.info('list filesystem (FS0) snapshots, snapshot (SS0) should be gone')
        response = self.storagepool_api.get_filesystem_snapshots(self.nodeid, storagepool['name'], filesystem['name'])
        self.assertEqual(response.status_code, 200)
        self.assertNotIn(snapshot['name'], response.json())

        self.lg.info('Delete nonexisting snapshot, should fail with 404')
        response = self.storagepool_api.delete_filesystem_snapshots_snapshotname(self.nodeid, storagepool['name'], filesystem['name'], 'fake_filesystem')
        self.assertEqual(response.status_code, 404)
示例#18
0
    def setUp(self):
        super().setUp()
        self.vdisks_apis = VDisksAPIs()
        self.storageclusters_api = Storageclusters()

        node = self.get_random_node()
        pyclient_ip = [x['ip'] for x in self.nodes if x['id'] == node][0]
        self.jwt = self.nodes_api.jwt
        self.pyclient = Client(pyclient_ip, password=self.jwt)

        free_disks = self.pyclient.getFreeDisks()
        if free_disks == []:
            self.skipTest('no free disks to create storagecluster')

        storageclusters = self.storageclusters_api.get_storageclusters()
        if storageclusters.json() == []:
            self.lg.info('Deploy new storage cluster (SC0)')
            sc_label = self.rand_str()
            sc_servers = random.randint(1, len(free_disks))
            sc_drivetype = 'ssd'
            sc_nodes = [node]
            sc_body = {"label": sc_label,
                        "servers": sc_servers,
                        "driveType": sc_drivetype,
                        "clusterType": "storage",
                        "nodes":sc_nodes}

            response = self.storageclusters_api.post_storageclusters(sc_body)
            self.assertEqual(response.status_code, 201)

            for _ in range(60):
                response = self.storageclusters_api.get_storageclusters_label(sc_label)
                if response.status_code == 200:
                    if response.json()['status'] == 'ready':
                        break
                    else:
                        time.sleep(3)
                else:
                    time.sleep(10)
            else:
                self.lg.error('storagecluster status is not ready after 180 sec')

        else:
            sc_label = storageclusters.json()[0]

        self.lg.info('Create vdisk (VD0)')
        self.vd_creation_time = time.time()
        self.vdisk_id = self.rand_str()
        self.size = random.randint(1, 50)
        self.types = ['boot','db','cache','tmp']
        self.type = random.choice(self.types)
        self.block_size = random.randint(1, self.size)*512
        self.storagecluster = sc_label
        self.readOnly = random.choice([False, True])

        self.body = {"id": self.vdisk_id,
                     "size": self.size,
                     "blocksize": self.block_size,
                     "type": self.type,
                     "storagecluster": self.storagecluster,
                     "readOnly":self.readOnly}

        response = self.vdisks_apis.post_vdisks(self.body)
        self.assertEqual(response.status_code, 201) 
示例#19
0
class TestStorageclustersAPI(TestcasesBase):
    def setUp(self):
        super().setUp()
        self.storageclusters_api = Storageclusters()

        self.nodeid = self.get_random_node()
        pyclient_ip = [x['ip'] for x in self.nodes
                       if x['id'] == self.nodeid][0]
        self.jwt = self.nodes_api.jwt
        self.pyclient = Client(pyclient_ip, password=self.jwt)

        if self._testMethodName != 'test003_deploy_new_storagecluster':

            self.lg.info('Deploy new storage cluster (SC0)')
            free_disks = self.pyclient.getFreeDisks()
            if free_disks == []:
                self.skipTest('no free disks to create storagecluster')

            self.label = self.rand_str()
            self.servers = randint(1, len(free_disks))
            self.drivetype = 'ssd'

            self.body = {
                "label": self.label,
                "servers": self.servers,
                "driveType": self.drivetype,
                "clusterType": "storage",
                "nodes": [self.nodeid]
            }

            response = self.storageclusters_api.post_storageclusters(self.body)
            self.assertEqual(response.status_code, 201)

            for _ in range(60):
                response = self.storageclusters_api.get_storageclusters_label(
                    self.label)
                if response.status_code == 200:
                    if response.json()['status'] == 'ready':
                        break
                    else:
                        time.sleep(3)
                else:
                    time.sleep(10)
            else:
                self.lg.error(
                    'storagecluster status is not ready after 180 sec')

    def tearDown(self):
        self.lg.info('Kill storage cluster (SC0)')
        if self._testMethodName != 'test003_deploy_new_storagecluster':
            self.storageclusters_api.delete_storageclusters_label(self.label)
        super(TestStorageclustersAPI, self).tearDown()

    def test001_get_storageclusters_label(self):
        """ GAT-041
        **Test Scenario:**
        #. Deploy new storage cluster (SC0)
        #. Get storage cluster (SC0), should succeed with 200
        #. Get nonexisting storage cluster (SC0), should fail with 404
        """
        self.lg.info('Get storage cluster (SC0), should succeed with 200')
        response = self.storageclusters_api.get_storageclusters_label(
            self.label)
        self.assertEqual(response.status_code, 200)
        for key in ['label', 'driveType', 'nodes']:
            self.assertEqual(response.json()[key], self.body[key])
        self.assertNotEqual(response.json()['status'], 'error')

        self.lg.info(
            'Get nonexisting storage cluster (SC0), should fail with 404')
        response = self.storageclusters_api.get_storageclusters_label(
            'fake_label')
        self.assertEqual(response.status_code, 404)

    def test002_list_storageclusters(self):
        """ GAT-042
        **Test Scenario:**
        #. Deploy new storage cluster (SC0)
        #. List storage clusters, should succeed with 200
        """
        self.lg.info('Get storage cluster (SC0), should succeed with 200')
        response = self.storageclusters_api.get_storageclusters()
        self.assertEqual(response.status_code, 200)
        self.assertIn(self.label, response.json())

    def test003_deploy_new_storagecluster(self):
        """ GAT-043
        **Test Scenario:**
        #. Deploy new storage cluster (SC1), should succeed with 201
        #. List storage clusters, (SC1) should be listed
        #. Kill storage cluster (SC0), should succeed with 204
        """
        self.lg.info(
            'Deploy new storage cluster (SC1), should succeed with 201')

        free_disks = self.pyclient.getFreeDisks()
        if free_disks == []:
            self.skipTest('no free disks to create storagecluster')

        label = self.rand_str()
        servers = randint(1, len(free_disks))
        drivetype = 'ssd'
        body = {
            "label": label,
            "servers": servers,
            "driveType": drivetype,
            "clusterType": "storage",
            "nodes": [self.nodeid]
        }

        response = self.storageclusters_api.post_storageclusters(body)
        self.assertEqual(response.status_code, 201)

        for _ in range(60):
            response = self.storageclusters_api.get_storageclusters_label(
                label)
            if response.status_code == 200:
                if response.json()['status'] == 'ready':
                    break
                else:
                    time.sleep(3)
            else:
                time.sleep(10)
        else:
            self.lg.error('storagecluster status is not ready after 180 sec')

        self.lg.info('List storage clusters, (SC1) should be listed')
        response = self.storageclusters_api.get_storageclusters()
        self.assertEqual(response.status_code, 200)
        self.assertIn(label, response.json())

        self.lg.info('Kill storage cluster (SC1), should succeed with 204')
        response = self.storageclusters_api.delete_storageclusters_label(label)
        self.assertEqual(response.status_code, 204)

    def test004_kill_storagecluster_label(self):
        """ GAT-044
        **Test Scenario:**
        #. #. Deploy new storage cluster (SC0)
        #. Kill storage cluster (SC0), should succeed with 204
        #. List storage clusters, (SC0) should be gone
        #. Kill nonexisting storage cluster, should fail with 404
        """
        self.lg.info('Kill storage cluster (SC0), should succeed with 204')
        response = self.storageclusters_api.delete_storageclusters_label(
            self.label)
        self.assertEqual(response.status_code, 204)

        self.lg.info('List storage clusters, (SC0) should be gone')
        response = self.storageclusters_api.get_storageclusters()
        self.assertEqual(response.status_code, 200)
        self.assertNotIn(self.label, response.json())

        self.lg.info('Kill nonexisting storage cluster, should fail with 404')
        response = self.storageclusters_api.delete_storageclusters_label(
            'fake_label')
        self.assertEqual(response.status_code, 404)