示例#1
0
class NovaClientPluginFetchServerTests(NovaClientPluginTestCase):

    server = mock.Mock()
    # set explicitly as id and name has internal meaning in mock.Mock
    server.id = '1234'
    server.name = 'test_fetch_server'
    msg = ("ClientException: The server has either erred or is "
           "incapable of performing the requested operation.")
    scenarios = [
        ('successful_refresh', dict(value=server, e_raise=False)),
        ('overlimit_error',
         dict(value=nova_exceptions.OverLimit(413, "limit reached"),
              e_raise=False)),
        ('500_error',
         dict(value=nova_exceptions.ClientException(500, msg), e_raise=False)),
        ('503_error',
         dict(value=nova_exceptions.ClientException(503, msg), e_raise=False)),
        ('unhandled_exception',
         dict(value=nova_exceptions.ClientException(501, msg), e_raise=True)),
    ]

    def test_fetch_server(self):
        self.nova_client.servers.get.side_effect = [self.value]
        if self.e_raise:
            self.assertRaises(nova_exceptions.ClientException,
                              self.nova_plugin.fetch_server, self.server.id)
        elif isinstance(self.value, mock.Mock):
            self.assertEqual(self.value,
                             self.nova_plugin.fetch_server(self.server.id))
        else:
            self.assertIsNone(self.nova_plugin.fetch_server(self.server.id))

        self.nova_client.servers.get.assert_called_once_with(self.server.id)
示例#2
0
class NovaClientPluginRefreshServerTests(NovaClientPluginTestCase):
    msg = ("ClientException: The server has either erred or is "
           "incapable of performing the requested operation.")

    scenarios = [
        ('successful_refresh', dict(value=None, e_raise=False)),
        ('overlimit_error',
         dict(value=nova_exceptions.OverLimit(413, "limit reached"),
              e_raise=False)),
        ('500_error',
         dict(value=nova_exceptions.ClientException(500, msg), e_raise=False)),
        ('503_error',
         dict(value=nova_exceptions.ClientException(503, msg), e_raise=False)),
        ('unhandled_exception',
         dict(value=nova_exceptions.ClientException(501, msg), e_raise=True)),
    ]

    def test_refresh(self):
        server = mock.MagicMock()
        server.get.side_effect = [self.value]
        if self.e_raise:
            self.assertRaises(nova_exceptions.ClientException,
                              self.nova_plugin.refresh_server, server)
        else:
            self.assertIsNone(self.nova_plugin.refresh_server(server))
        server.get.assert_called_once_with()
示例#3
0
 def test_import_key_pair_invalid(self):
     self.nova.keypairs.create.side_effect = (nova_exception.OverLimit(413))
     self.assert_execution_error(
         'ResourceLimitExceeded', 'ImportKeyPair', {
             'KeyName': fakes.NAME_KEY_PAIR,
             'PublicKeyMaterial': base64.b64encode(
                 fakes.PUBLIC_KEY_KEY_PAIR)
         })
示例#4
0
 def test_create_key_pair_invalid(self):
     self.nova.keypairs.create.side_effect = (nova_exception.Conflict(409))
     self.assert_execution_error('InvalidKeyPair.Duplicate',
                                 'CreateKeyPair',
                                 {'KeyName': fakes.NAME_KEY_PAIR})
     self.assert_execution_error('ValidationError', 'CreateKeyPair',
                                 {'KeyName': 'k' * 256})
     self.nova.keypairs.create.side_effect = (nova_exception.OverLimit(413))
     self.assert_execution_error('ResourceLimitExceeded', 'CreateKeyPair',
                                 {'KeyName': fakes.NAME_KEY_PAIR})
示例#5
0
 def test_create_security_group_over_quota(self):
     security_group.security_group_engine = (
         security_group.SecurityGroupEngineNeutron())
     self.nova.security_groups.create.side_effect = (
         nova_exception.OverLimit(413))
     self.assert_execution_error(
         'ResourceLimitExceeded', 'CreateSecurityGroup', {
             'VpcId': fakes.ID_EC2_VPC_1,
             'GroupName': 'groupname',
             'GroupDescription': 'Group description'
         })
     self.nova.security_groups.create.assert_called_once_with(
         'groupname', 'Group description')
示例#6
0
    def create_vm(self,
                  name,
                  image,
                  flavor,
                  nics=None,
                  security_groups=None,
                  scheduler_hints=None,
                  **kwargs):
        """Mock'd version of novaclient...create_vm().

        Create a Nova VM.

        :param body: Dictionary with vm information.
        :return: An updated copy of the 'body' that was passed in, with other
                 information populated.
        """
        if len(self._vm_list) >= self._vm_limit:
            raise nova_exc.OverLimit(413)
        try:
            flavor_id = flavor.id
        except AttributeError:
            flavor_id = flavor

        try:
            image_id = image.id
        except AttributeError:
            image_id = image

        if flavor_id not in self._flavor_list:
            raise nova_exc.BadRequest(400)

        if image_id not in self._image_list:
            raise nova_exc.BadRequest(400)

        port_list = list()
        if nics is not None:
            neutron_client = client.neutron_client()
            for nic in nics:
                if 'net-id' in nic:
                    network_list = neutron_client.list_networks(
                        id=nic['net-id'])
                    if (not network_list or 'networks' not in network_list
                            or len(network_list['networks']) == 0):
                        raise nova_exc.BadRequest(400)

                    else:
                        body_value = {
                            "port": {
                                "admin_state_up": True,
                                "name": "test port",
                                "network_id": nic['net-id'],
                            }
                        }
                        port_info = neutron_client.create_port(body=body_value)
                        port_id = port_info['port']['id']
                        port_list.append(
                            InterfaceDetails(net_id=nic['net-id'],
                                             port_id=port_id))
                if 'port-id' in nic:
                    port_list.append(InterfaceDetails(port_id=nic['port-id']))

        if security_groups is not None:
            missing = set(security_groups) - set(self._security_group_list)
            if missing:
                raise nova_exc.BadRequest(400)

        newVm = VmDetails(vm_id=uuid.uuid4(),
                          name=name,
                          flavor=flavor,
                          image=image,
                          port_list=port_list,
                          status='BUILDING')

        if scheduler_hints is not None:
            try:
                group_id = scheduler_hints['group']
            except AttributeError:
                group_id = scheduler_hints

            if group_id not in self._vm_group_list:
                raise nova_exc.BadRequest(400)

            newVm.host_id = str(uuid.uuid4())

        self._vm_list[str(newVm.id)] = newVm

        return newVm
示例#7
0
    def launch_instances(self,
                         name,
                         image,
                         flavor,
                         meta=None,
                         files=None,
                         reservation_id=None,
                         min_count=None,
                         max_count=None,
                         security_groups=None,
                         userdata=None,
                         key_name=None,
                         availability_zone=None,
                         block_device_mapping=None,
                         nics=None,
                         scheduler_hints=None,
                         config_drive=None,
                         **kwargs):
        ''' Launch a cluster'''

        # TODO: theme handling?

        # name is used to provide extra information to this function via the
        # openstack launch api
        extras = name.split("-")

        headnode_size = extras[0]
        headnode_image = "-".join(extras[1:6])

        # check the quotas

        quotas = self._cloud.list_quotas()
        instances = self._cloud.list_instances()
        flavor_dict = {f["id"]: f for f in self._cloud.list_sizes()}

        # in flavors it's "vcpus" in quotas it's "cores"
        quotas["vcpus"] = quotas["cores"]

        get_old_total = lambda attr: sum(
            [flavor_dict[i["flavor"]["id"]].get(attr, 1) for i in instances])

        get_new_total = lambda attr: (min_count * flavor_dict[flavor].get(
            attr, 1) + flavor_dict[headnode_size].get(attr, 1))

        for stat in ["vcpus", "ram", "instances"]:
            if get_old_total(stat) + get_new_total(stat) > quotas[stat]:
                raise nova_exceptions.OverLimit(413, message="Quota exceeded")

        constructor = nc.TORQUECluster

        cluster = constructor(self._cloud.client,
                              min_count,
                              self._cloud.client.images.get(headnode_image),
                              self._cloud.client.images.get(image),
                              node_flavor=flavor,
                              headnode_flavor=int(headnode_size),
                              os_key_name=key_name)

        # There is an issue with using novaclient as the same user from
        # multiple processes because of locks that it creates. This used
        # multiprocessing.Process before but caused a problem on the pdc
        # production server. Using threading.Thread caused the issue to go
        # away. My theory was that the GIL prevent the deadlock from happening
        # Could still be an issue.

        launch_proc = Thread(target=cluster.launch)

        launch_proc.start()

        return {"server": {}}
示例#8
0
 def test_overlimit_error(self):
     server = mock.Mock()
     server.get.side_effect = nova_exceptions.OverLimit(
         413, "limit reached")
     self.assertIsNone(self.nova_plugin.refresh_server(server))