Exemple #1
0
 def test_resources_from_request_spec_having_requested_resources(self):
     flavor = objects.Flavor(vcpus=1,
                             memory_mb=1024,
                             root_gb=10,
                             ephemeral_gb=5,
                             swap=0)
     rg1 = objects.RequestGroup()
     rg2 = objects.RequestGroup()
     reqspec = objects.RequestSpec(flavor=flavor,
                                   requested_resources=[rg1, rg2])
     req = utils.resources_from_request_spec(self.context, reqspec,
                                             self.mock_host_manager)
     self.assertEqual({
         'MEMORY_MB': 1024,
         'DISK_GB': 15,
         'VCPU': 1
     },
                      req.get_request_group(None).resources)
     self.assertIs(rg1, req.get_request_group(1))
     self.assertIs(rg2, req.get_request_group(2))
Exemple #2
0
 def test_resources_from_request_spec_flavor_forbidden_trait(self):
     flavor = objects.Flavor(
         vcpus=1,
         memory_mb=1024,
         root_gb=10,
         ephemeral_gb=5,
         swap=0,
         extra_specs={'trait:CUSTOM_FLAVOR_TRAIT': 'forbidden'})
     expected_resources = utils.ResourceRequest()
     expected_resources._rg_by_id[None] = objects.RequestGroup(
         use_same_provider=False,
         resources={
             'VCPU': 1,
             'MEMORY_MB': 1024,
             'DISK_GB': 15,
         },
         forbidden_traits={
             'CUSTOM_FLAVOR_TRAIT',
         })
     self._test_resources_from_request_spec(expected_resources, flavor)
Exemple #3
0
 def test_isolate_agg_trait_on_flv_img_destination_not_set(self,
                                                           mock_getnotmd):
     mock_getnotmd.return_value = []
     flavor_traits = set(['HW_GPU_API_DXVA'])
     image_traits = set(['HW_NIC_DCB_ETS'])
     fake_flavor = objects.Flavor(
         vcpus=1, memory_mb=1024, root_gb=10, ephemeral_gb=5, swap=0,
         extra_specs={
             'trait:' + trait: 'required' for trait in flavor_traits})
     fake_image = objects.ImageMeta(
         properties=objects.ImageMetaProps(
             traits_required=[trait for trait in image_traits]))
     reqspec = objects.RequestSpec(flavor=fake_flavor, image=fake_image)
     result = request_filter.isolate_aggregates(self.context, reqspec)
     self.assertTrue(result)
     self.assertNotIn('requested_destination', reqspec)
     keys = ['trait:%s' % trait for trait in flavor_traits.union(
         image_traits)]
     mock_getnotmd.assert_called_once_with(
         self.context, utils.ItemsMatcher(keys), 'trait:', value='required')
    def test_to_legacy_instance(self):
        spec = objects.RequestSpec()
        spec.flavor = objects.Flavor(root_gb=10,
                                     ephemeral_gb=0,
                                     memory_mb=10,
                                     vcpus=1)
        spec.numa_topology = None
        spec.pci_requests = None
        spec.project_id = fakes.FAKE_PROJECT_ID
        spec.availability_zone = 'nova'

        instance = spec._to_legacy_instance()
        self.assertEqual({'root_gb': 10,
                          'ephemeral_gb': 0,
                          'memory_mb': 10,
                          'vcpus': 1,
                          'numa_topology': None,
                          'pci_requests': None,
                          'project_id': fakes.FAKE_PROJECT_ID,
                          'availability_zone': 'nova'}, instance)
Exemple #5
0
    def _removeTenantAccess(self, req, id, body):
        context = req.environ['nova.context']
        authorize(context, action="removeTenantAccess")

        self._check_body(body)

        vals = body['removeTenantAccess']
        tenant = vals.get('tenant')
        if not tenant:
            msg = _("Missing tenant parameter")
            raise webob.exc.HTTPBadRequest(explanation=msg)

        flavor = objects.Flavor(context=context, flavorid=id)
        try:
            flavor.remove_access(tenant)
        except (exception.FlavorNotFound,
                exception.FlavorAccessNotFound) as err:
            raise webob.exc.HTTPNotFound(explanation=err.format_message())

        return _marshall_flavor_access(flavor)
Exemple #6
0
 def setUp(self):
     super(InstanceTypeExtraSpecsTestCase, self).setUp()
     self.context = context.get_admin_context()
     flavor = objects.Flavor(context=self.context,
                             name="cg1.4xlarge",
                             memory_mb=22000,
                             vcpus=8,
                             root_gb=1690,
                             ephemeral_gb=2000,
                             flavorid=105)
     self.specs = dict(cpu_arch=arch.X86_64,
                       cpu_model="Nehalem",
                       xpu_arch="fermi",
                       xpus="2",
                       xpu_model="Tesla 2050")
     flavor.extra_specs = self.specs
     flavor.create()
     self.flavor = flavor
     self.instance_type_id = flavor.id
     self.flavorid = flavor.flavorid
 def setUp(self):
     super(FlavorsSampleJsonTest2_61, self).setUp()
     # Get the existing flavors created by DefaultFlavorsFixture.
     ctxt = nova_context.get_admin_context()
     flavors = objects.FlavorList.get_all(ctxt)
     # Flavors are sorted by flavorid in ascending order by default, so
     # get the last flavor in the list and create a new flavor with an
     # incremental flavorid so we have a predictable sort order for the
     # sample response.
     new_flavor_id = int(flavors[-1].flavorid) + 1
     new_flavor = objects.Flavor(
         ctxt, memory_mb=2048, vcpus=1, root_gb=20, flavorid=new_flavor_id,
         name='m1.small.description', description='test description',
         extra_specs={
             'hw:numa_nodes': '1',
             'hw:cpu_policy': 'shared',
         })
     new_flavor.create()
     self.flavor_show_id = new_flavor_id
     self.subs = {'flavorid': new_flavor_id}
Exemple #8
0
    def test_resources_from_request_spec_requested_resources_unfilled(self):
        flavor = objects.Flavor(
                vcpus=1,
                memory_mb=1024,
                root_gb=10,
                ephemeral_gb=5,
                swap=0)
        reqspec = objects.RequestSpec(flavor=flavor)
        req = utils.resources_from_request_spec(
                self.context, reqspec, self.mock_host_manager)
        self.assertEqual({'MEMORY_MB': 1024, 'DISK_GB': 15, 'VCPU': 1},
                         req.get_request_group(None).resources)
        self.assertEqual(1, len(list(req.resource_groups())))

        reqspec = objects.RequestSpec(flavor=flavor, requested_resources=[])
        req = utils.resources_from_request_spec(
                self.context, reqspec, self.mock_host_manager)
        self.assertEqual({'MEMORY_MB': 1024, 'DISK_GB': 15, 'VCPU': 1},
                         req.get_request_group(None).resources)
        self.assertEqual(1, len(list(req.resource_groups())))
Exemple #9
0
 def test_get_resources_from_request_spec_override_flavor_amounts(self):
     flavor = objects.Flavor(vcpus=1,
                             memory_mb=1024,
                             root_gb=10,
                             ephemeral_gb=5,
                             swap=0,
                             extra_specs={
                                 "resources:VCPU": 99,
                                 "resources:MEMORY_MB": 99,
                                 "resources:DISK_GB": 99
                             })
     expected_resources = utils.ResourceRequest()
     expected_resources._rg_by_id[None] = plib.RequestGroup(
         use_same_provider=False,
         resources={
             "VCPU": 99,
             "MEMORY_MB": 99,
             "DISK_GB": 99,
         })
     self._test_resources_from_request_spec(flavor, expected_resources)
Exemple #10
0
    def test_get_arq_uuids_for_instance(self, mock_cyborg_get):
        # Happy path, without only_resolved=True
        _, bound_arqs = self._get_bound_arqs()
        instance_uuid = bound_arqs[0]['instance_uuid']
        flavor = objects.Flavor(extra_specs={'accel:device_profile': 'dp1'})
        instance = objects.Instance(flavor=flavor,
                                    uuid=instance_uuid)
        query = {"instance": instance_uuid}
        content = jsonutils.dumps({'arqs': bound_arqs})
        resp = fake_requests.FakeResponse(200, content)
        mock_cyborg_get.return_value = resp

        ret_arqs = self.client.get_arq_uuids_for_instance(instance)

        mock_cyborg_get.assert_called_once_with(
            self.client.ARQ_URL, params=query)
        bound_arqs = [bound_arq['uuid'] for bound_arq in bound_arqs]
        bound_arqs.sort()
        ret_arqs.sort()
        self.assertEqual(bound_arqs, ret_arqs)
Exemple #11
0
    def test_resources_from_request_spec_no_aggregates(self):
        flavor = objects.Flavor(vcpus=1, memory_mb=1024,
                                root_gb=1, ephemeral_gb=0,
                                swap=0)
        reqspec = objects.RequestSpec(flavor=flavor)

        req = utils.resources_from_request_spec(reqspec)
        self.assertEqual([], req.get_request_group(None).aggregates)

        reqspec.requested_destination = None
        req = utils.resources_from_request_spec(reqspec)
        self.assertEqual([], req.get_request_group(None).aggregates)

        reqspec.requested_destination = objects.Destination()
        req = utils.resources_from_request_spec(reqspec)
        self.assertEqual([], req.get_request_group(None).aggregates)

        reqspec.requested_destination.aggregates = None
        req = utils.resources_from_request_spec(reqspec)
        self.assertEqual([], req.get_request_group(None).aggregates)
Exemple #12
0
 def test_process_no_force_hosts_or_force_nodes(self):
     flavor = objects.Flavor(vcpus=1,
                             memory_mb=1024,
                             root_gb=15,
                             ephemeral_gb=0,
                             swap=0)
     expected = utils.ResourceRequest()
     expected._rg_by_id[None] = objects.RequestGroup(
         use_same_provider=False,
         resources={
             'VCPU': 1,
             'MEMORY_MB': 1024,
             'DISK_GB': 15,
         },
     )
     rr = self._test_resources_from_request_spec(expected, flavor)
     expected_querystring = (
         'limit=1000&'
         'resources=DISK_GB%3A15%2CMEMORY_MB%3A1024%2CVCPU%3A1')
     self.assertEqual(expected_querystring, rr.to_querystring())
Exemple #13
0
def _fake_instance(start, end, instance_id, tenant_id,
                   vm_state=vm_states.ACTIVE):
    flavor = objects.Flavor(**FAKE_INST_TYPE)
    return objects.Instance(
        deleted=False,
        id=instance_id,
        uuid=getattr(uuids, 'instance_%d' % instance_id),
        image_ref='1',
        project_id=tenant_id,
        user_id='fakeuser',
        display_name='name',
        instance_type_id=FAKE_INST_TYPE['id'],
        launched_at=start,
        terminated_at=end,
        vm_state=vm_state,
        memory_mb=MEMORY_MB,
        vcpus=VCPUS,
        root_gb=ROOT_GB,
        ephemeral_gb=EPHEMERAL_GB,
        flavor=flavor)
Exemple #14
0
    def setUp(self):
        super(ComputeValidateDeviceTestCase, self).setUp()
        self.context = context.RequestContext('fake', 'fake')
        # check if test name includes "xen"
        if 'xen' in self.id():
            self.flags(compute_driver='xenapi.XenAPIDriver')
            self.instance = objects.Instance(uuid=uuid.uuid4().hex,
                root_device_name=None,
                default_ephemeral_device=None)
        else:
            self.instance = objects.Instance(uuid=uuid.uuid4().hex,
                root_device_name='/dev/vda',
                default_ephemeral_device='/dev/vdb')

        flavor = objects.Flavor(**test_flavor.fake_flavor)
        self.instance.system_metadata = {}
        self.instance.flavor = flavor
        self.instance.default_swap_device = None

        self.data = []
Exemple #15
0
    def test_select_destinations(self, mock_get_extra, mock_get_all,
                                 mock_by_host, mock_get_by_binary):
        """select_destinations is basically a wrapper around _schedule().

        Similar to the _schedule tests, this just does a happy path test to
        ensure there is nothing glaringly wrong.
        """

        self.next_weight = 1.0

        selected_hosts = []
        selected_nodes = []

        def _fake_weigh_objects(_self, functions, hosts, options):
            self.next_weight += 2.0
            host_state = hosts[0]
            selected_hosts.append(host_state.host)
            selected_nodes.append(host_state.nodename)
            return [weights.WeighedHost(host_state, self.next_weight)]

        self.stubs.Set(self.driver.host_manager, 'get_filtered_hosts',
                       fake_get_filtered_hosts)
        self.stubs.Set(weights.HostWeightHandler, 'get_weighed_objects',
                       _fake_weigh_objects)

        spec_obj = objects.RequestSpec(flavor=objects.Flavor(memory_mb=512,
                                                             root_gb=512,
                                                             ephemeral_gb=0,
                                                             vcpus=1),
                                       project_id=1,
                                       os_type='Linux',
                                       instance_uuid='fake-uuid',
                                       num_instances=1,
                                       pci_requests=None,
                                       numa_topology=None,
                                       instance_group=None)
        self.mox.ReplayAll()
        dests = self.driver.select_destinations(self.context, spec_obj)
        (host, node) = (dests[0]['host'], dests[0]['nodename'])
        self.assertEqual(host, selected_hosts[0])
        self.assertEqual(node, selected_nodes[0])
    def test_schedule_successful_claim(self, mock_get_hosts,
                                       mock_get_all_states, mock_claim):
        spec_obj = objects.RequestSpec(num_instances=1,
                                       flavor=objects.Flavor(memory_mb=512,
                                                             root_gb=512,
                                                             ephemeral_gb=0,
                                                             swap=0,
                                                             vcpus=1),
                                       project_id=uuids.project_id,
                                       instance_group=None)

        host_state = mock.Mock(spec=host_manager.HostState,
                               host=mock.sentinel.host,
                               uuid=uuids.cn1)
        all_host_states = [host_state]
        mock_get_all_states.return_value = all_host_states
        mock_get_hosts.return_value = all_host_states
        mock_claim.return_value = True

        instance_uuids = [uuids.instance]
        alloc_reqs_by_rp_uuid = {
            uuids.cn1: [mock.sentinel.alloc_req],
        }
        ctx = mock.Mock()
        selected_hosts = self.driver._schedule(
            ctx, spec_obj, instance_uuids, alloc_reqs_by_rp_uuid,
            mock.sentinel.provider_summaries)

        mock_get_all_states.assert_called_once_with(
            ctx.elevated.return_value, spec_obj,
            mock.sentinel.provider_summaries)
        mock_get_hosts.assert_called_once_with(spec_obj, all_host_states, 0)
        mock_claim.assert_called_once_with(ctx.elevated.return_value, spec_obj,
                                           uuids.instance,
                                           [mock.sentinel.alloc_req])

        self.assertEqual(len(selected_hosts), 1)
        self.assertEqual([host_state], selected_hosts)

        # Ensure that we have consumed the resources on the chosen host states
        host_state.consume_from_request.assert_called_once_with(spec_obj)
    def test_schedule_chooses_best_host(self, mock_get_extra, mock_cn_get_all,
                                        mock_get_by_binary,
                                        mock_add_inst_info):
        """If scheduler_host_subset_size is 1, the largest host with greatest
        weight should be returned.
        """

        self.flags(scheduler_host_subset_size=1)
        self.stubs.Set(self.driver.host_manager, 'get_filtered_hosts',
                       fake_get_filtered_hosts)

        self.next_weight = 50

        def _fake_weigh_objects(_self, functions, hosts, options):
            this_weight = self.next_weight
            self.next_weight = 0
            host_state = hosts[0]
            return [weights.WeighedHost(host_state, this_weight)]

        spec_obj = objects.RequestSpec(num_instances=1,
                                       project_id=1,
                                       os_type='Linux',
                                       uuid='fake-uuid',
                                       flavor=objects.Flavor(root_gb=512,
                                                             memory_mb=512,
                                                             ephemeral_gb=0,
                                                             vcpus=1),
                                       pci_requests=None,
                                       numa_topology=None,
                                       instance_group=None)

        self.stubs.Set(weights.HostWeightHandler, 'get_weighed_objects',
                       _fake_weigh_objects)

        self.mox.ReplayAll()
        hosts = self.driver._schedule(self.context, spec_obj)

        # one host should be chosen
        self.assertEqual(1, len(hosts))

        self.assertEqual(50, hosts[0].weight)
Exemple #18
0
    def test_find_destination_works_with_no_request_spec(self):
        task = live_migrate.LiveMigrationTask(
            self.context,
            self.instance,
            self.destination,
            self.block_migration,
            self.disk_over_commit,
            self.migration,
            compute_rpcapi.ComputeAPI(),
            servicegroup.API(),
            scheduler_client.SchedulerClient(),
            request_spec=None)
        another_spec = objects.RequestSpec()
        self.instance.flavor = objects.Flavor()
        self.instance.numa_topology = None
        self.instance.pci_requests = None

        @mock.patch.object(task, '_call_livem_checks_on_host')
        @mock.patch.object(task, '_check_compatible_with_source_hypervisor')
        @mock.patch.object(task.scheduler_client, 'select_destinations')
        @mock.patch.object(objects.RequestSpec, 'from_components')
        @mock.patch.object(scheduler_utils, 'setup_instance_group')
        @mock.patch.object(utils, 'get_image_from_system_metadata')
        def do_test(get_image, setup_ig, from_components, select_dest,
                    check_compat, call_livem_checks):
            get_image.return_value = "image"
            from_components.return_value = another_spec
            select_dest.return_value = [{'host': 'host1'}]

            self.assertEqual("host1", task._find_destination())

            get_image.assert_called_once_with(self.instance.system_metadata)
            fake_props = {'instance_properties': {'uuid': self.instance_uuid}}
            setup_ig.assert_called_once_with(
                self.context, fake_props,
                {'ignore_hosts': [self.instance_host]})
            select_dest.assert_called_once_with(self.context, another_spec)
            check_compat.assert_called_once_with("host1")
            call_livem_checks.assert_called_once_with("host1")

        do_test()
Exemple #19
0
    def test_schedule_placement_bad_comms(self, mock_get_hosts,
                                          mock_get_all_states, mock_claim):
        """If there was a problem communicating with the Placement service,
        alloc_reqs_by_rp_uuid will be None and we need to avoid trying to claim
        in the Placement API.
        """
        spec_obj = objects.RequestSpec(num_instances=1,
                                       flavor=objects.Flavor(memory_mb=512,
                                                             root_gb=512,
                                                             ephemeral_gb=0,
                                                             swap=0,
                                                             vcpus=1),
                                       project_id=uuids.project_id,
                                       instance_group=None)

        host_state = mock.Mock(spec=host_manager.HostState,
                               host=mock.sentinel.host,
                               uuid=uuids.cn1)
        all_host_states = [host_state]
        mock_get_all_states.return_value = all_host_states
        mock_get_hosts.return_value = all_host_states

        instance_uuids = None
        ctx = mock.Mock()
        selected_hosts = self.driver._schedule(
            ctx, spec_obj, instance_uuids, None,
            mock.sentinel.provider_summaries)

        mock_get_all_states.assert_called_once_with(
            ctx.elevated.return_value, spec_obj,
            mock.sentinel.provider_summaries)
        mock_get_hosts.assert_called_once_with(spec_obj, all_host_states, 0)

        self.assertEqual(len(selected_hosts), 1)
        self.assertEqual([host_state], selected_hosts)

        # Ensure that we have consumed the resources on the chosen host states
        host_state.consume_from_request.assert_called_once_with(spec_obj)

        # And ensure we never called _claim_resources()
        self.assertFalse(mock_claim.called)
Exemple #20
0
    def test_resources_from_request_spec_aggregates(self):
        destination = objects.Destination()
        flavor = objects.Flavor(vcpus=1,
                                memory_mb=1024,
                                root_gb=1,
                                ephemeral_gb=0,
                                swap=0)
        reqspec = objects.RequestSpec(flavor=flavor,
                                      requested_destination=destination)

        destination.require_aggregates(['foo', 'bar'])
        req = utils.resources_from_request_spec(self.context, reqspec,
                                                self.mock_host_manager)
        self.assertEqual([['foo', 'bar']],
                         req.get_request_group(None).aggregates)

        destination.require_aggregates(['baz'])
        req = utils.resources_from_request_spec(self.context, reqspec,
                                                self.mock_host_manager)
        self.assertEqual([['foo', 'bar'], ['baz']],
                         req.get_request_group(None).aggregates)
Exemple #21
0
def get_test_flavor(context=None, options=None):
    options = options or {}
    if not context:
        context = get_test_admin_context()

    test_flavor = {'name': 'kinda.big',
                   'flavorid': 'someid',
                   'memory_mb': 2048,
                   'vcpus': 4,
                   'root_gb': 40,
                   'ephemeral_gb': 80,
                   'swap': 1024}

    test_flavor.update(options)
    flavor_ref = objects.Flavor(context, **test_flavor)
    try:
        flavor_ref.create()
    except (exception.FlavorExists, exception.FlavorIdExists):
        flavor_ref = objects.Flavor.get_by_flavor_id(
            context, test_flavor['flavorid'])
    return flavor_ref
 def test_update_with_invalid_description(self, mock_flavor_save, mock_get):
     # First create a flavor.
     flavor = self._create_flavor_success_case(self.request_body)['flavor']
     self.assertEqual('test description', flavor['description'])
     mock_get.return_value = objects.Flavor(
         flavorid=flavor['id'], name=flavor['name'],
         memory_mb=flavor['ram'], vcpus=flavor['vcpus'],
         root_gb=flavor['disk'], swap=flavor['swap'],
         ephemeral_gb=flavor['OS-FLV-EXT-DATA:ephemeral'],
         disabled=flavor['OS-FLV-DISABLED:disabled'],
         is_public=flavor['os-flavor-access:is_public'],
         description=flavor['description'])
     # NOTE(mriedem): Intentionally not using ddt for this since ddt will
     # create a test name that has 65536 'a's in the name which blows up
     # the console output.
     for description in ('bad !@#!$%\x00 description',   # printable chars
                         'a' * 65536):                   # maxLength
         self.request_body['flavor']['description'] = description
         self.assertRaises(self.validation_error, self.controller._update,
                           self._get_http_request(), flavor['id'],
                           body={'flavor': {'description': description}})
Exemple #23
0
 def setUp(self):
     super().setUp()
     self.context = nova_context.get_admin_context()
     flavor = objects.Flavor(context=self.context,
                             name="cg1.4xlarge",
                             memory_mb=22000,
                             vcpus=8,
                             root_gb=1690,
                             ephemeral_gb=2000,
                             flavorid=105)
     self.specs = {
         'cpu_arch': fields.Architecture.X86_64,
         'cpu_model': 'Nehalem',
         'xpu_arch': 'fermi',
         'xpus': '2',
         'xpu_model': 'Tesla 2050',
     }
     flavor.extra_specs = self.specs
     flavor.create()
     self.flavor = flavor
     self.flavorid = flavor.flavorid
Exemple #24
0
 def test_type_filter(self):
     self.filt_cls = type_filter.TypeAffinityFilter()
     host = fakes.FakeHostState('fake_host', 'fake_node', {})
     host.instances = {}
     target_id = 1
     spec_obj = objects.RequestSpec(
         context=mock.MagicMock(),
         flavor=objects.Flavor(id=target_id))
     # True since no instances on host
     self.assertTrue(self.filt_cls.host_passes(host, spec_obj))
     # Add an instance with the same instance_type_id
     inst1 = objects.Instance(uuid='aa', instance_type_id=target_id)
     host.instances = {inst1.uuid: inst1}
     # True since only same instance_type_id on host
     self.assertTrue(self.filt_cls.host_passes(host, spec_obj))
     # Add an instance with a different instance_type_id
     diff_type = target_id + 1
     inst2 = objects.Instance(uuid='bb', instance_type_id=diff_type)
     host.instances.update({inst2.uuid: inst2})
     # False since host now has an instance of a different type
     self.assertFalse(self.filt_cls.host_passes(host, spec_obj))
Exemple #25
0
 def test_get_resources_from_request_spec_vgpu(self):
     flavor = objects.Flavor(vcpus=1,
                             memory_mb=1024,
                             root_gb=10,
                             ephemeral_gb=0,
                             swap=0,
                             extra_specs={
                                 "resources:VGPU": 1,
                                 "resources:VGPU_DISPLAY_HEAD": 1
                             })
     expected_resources = utils.ResourceRequest()
     expected_resources._rg_by_id[None] = plib.RequestGroup(
         use_same_provider=False,
         resources={
             "VCPU": 1,
             "MEMORY_MB": 1024,
             "DISK_GB": 10,
             "VGPU": 1,
             "VGPU_DISPLAY_HEAD": 1,
         })
     self._test_resources_from_request_spec(flavor, expected_resources)
Exemple #26
0
    def test_compat_legacy_props(self, to_props, to_spec):
        fake_flavor = objects.Flavor()
        fake_context = mock.Mock()
        fake_spec = objects.RequestSpec(context=fake_context,
                                        flavor=fake_flavor)
        fake_spec.config_options = None
        to_props.return_value = {'prop1': 'val1'}
        to_spec.return_value = {'spec1': 'val2'}

        @filters.compat_legacy_props
        def fake_host_passes(self, host_state, filter_properties):
            # NOTE(sbauza): Convenient way to verify the passed properties
            return filter_properties

        expected = {'prop1': 'val1',
                    'request_spec': {'spec1': 'val2'},
                    'instance_type': fake_flavor,
                    'context': fake_context,
                    'config_options': None}
        self.assertEqual(expected,
                         fake_host_passes('self', 'host_state', fake_spec))
Exemple #27
0
 def test_get_flags_by_flavor_specs(self):
     flavor = objects.Flavor(
         id=1,
         flavorid='fakeid-1',
         name='fake1.small',
         memory_mb=128,
         vcpus=1,
         root_gb=1,
         ephemeral_gb=0,
         swap=0,
         rxtx_factor=0,
         deleted=False,
         extra_specs={
             'trait:%s' % os_traits.HW_CPU_X86_3DNOW: 'required',
             'trait:%s' % os_traits.HW_CPU_X86_SSE2: 'required',
             'trait:%s' % os_traits.HW_CPU_HYPERTHREADING: 'required',
         })
     traits = libvirt_utils.get_flags_by_flavor_specs(flavor)
     # we shouldn't see the hyperthreading trait since that's a valid trait
     # but not a CPU flag
     self.assertEqual(set(['3dnow', 'sse2']), traits)
Exemple #28
0
    def test_instance_fault_message_no_traceback_with_retry(self):
        """This test simulates a spawn failure on the last retry attempt.

        If driver spawn raises an exception on the last retry attempt, the
        instance fault message should not contain a traceback for the
        last exception. The fault message field is limited in size and a long
        message with a traceback displaces the original error message.
        """
        self.flags(max_attempts=3, group='scheduler')
        flavor = objects.Flavor(
                id=1, name='flavor1', memory_mb=256, vcpus=1, root_gb=1,
                ephemeral_gb=1, flavorid='1', swap=0, rxtx_factor=1.0,
                vcpu_weight=1, disabled=False, is_public=True, extra_specs={},
                projects=[])
        instance = objects.Instance(self.context, flavor=flavor, vcpus=1,
                                    memory_mb=256, root_gb=0, ephemeral_gb=0,
                                    project_id='fake')
        instance.create()

        # Amongst others, mock the resource tracker, otherwise it will
        # not have been sufficiently initialized and will raise a KeyError
        # on the self.compute_nodes dict after the TestingException.
        @mock.patch.object(self.conductor.manager.compute_task_mgr,
                           '_cleanup_allocated_networks')
        @mock.patch.object(self.compute.manager.network_api,
                           'cleanup_instance_network_on_host')
        @mock.patch('nova.compute.utils.notify_about_instance_usage')
        @mock.patch.object(self.compute.manager, '_get_resource_tracker')
        @mock.patch.object(self.compute.manager.driver, 'spawn')
        def _test(mock_spawn, mock_grt, mock_notify, mock_cinoh, mock_can):
            mock_spawn.side_effect = test.TestingException('Preserve this')
            # Simulate that we're on the last retry attempt
            filter_properties = {'retry': {'num_attempts': 3}}
            request_spec = objects.RequestSpec.from_primitives(
                self.context, {}, filter_properties)
            self.compute.manager.build_and_run_instance(
                    self.context, instance, {}, request_spec,
                    filter_properties, block_device_mapping=[])
        _test()
        self.assertIn('Preserve this', instance.fault.message)
 def _create_instance(self,
                      node=None,
                      set_image_ref=True,
                      uuid=None,
                      instance_type='m1.large',
                      ephemeral=None,
                      instance_type_updates=None):
     if not node:
         node = self.node_name
     if not uuid:
         uuid = uuidutils.generate_uuid()
     self.type_data = self._get_instance_type_by_name(instance_type)
     if instance_type_updates:
         self.type_data.update(instance_type_updates)
     if ephemeral is not None:
         self.type_data['ephemeral_gb'] = ephemeral
     values = {
         'name': 'fake_name',
         'id': 1,
         'uuid': uuid,
         'project_id': self.project_id,
         'user_id': self.user_id,
         'kernel_id': "fake_kernel_uuid",
         'ramdisk_id': "fake_ramdisk_uuid",
         'mac_address': "de:ad:be:ef:be:ef",
         'Flavor': instance_type,
         'node': node,
         'memory_mb': self.type_data['memory_mb'],
         'root_gb': self.type_data['root_gb'],
         'ephemeral_gb': self.type_data['ephemeral_gb'],
         'vcpus': self.type_data['vcpus'],
         'swap': self.type_data['swap'],
         'expected_attrs': ['system_metadata'],
     }
     if set_image_ref:
         values['image_ref'] = self.fake_image_uuid
     self.instance_node = node
     self.uuid = uuid
     self.instance = fake_instance.fake_instance_obj(self.context, **values)
     self.instance.flavor = objects.Flavor(**self.type_data)
    def test_schedule_happy_day(self, mock_get_extra, mock_get_mv,
                                mock_get_rps, mock_get_all,
                                mock_by_host, mock_get_by_binary):
        """Make sure there's nothing glaringly wrong with _schedule()
        by doing a happy day pass through.
        """

        self.next_weight = 1.0

        def _fake_weigh_objects(_self, functions, hosts, options):
            self.next_weight += 2.0
            host_state = hosts[0]
            return [weights.WeighedHost(host_state, self.next_weight)]

        self.stub_out('nova.scheduler.weights.HostWeightHandler.'
                'get_weighed_objects', _fake_weigh_objects)

        spec_obj = objects.RequestSpec(
            num_instances=10,
            flavor=objects.Flavor(memory_mb=512,
                                  root_gb=512,
                                  ephemeral_gb=0,
                                  swap=0,
                                  vcpus=1),
            project_id=1,
            os_type='Linux',
            uuid=uuids.instance,
            pci_requests=None,
            numa_topology=None,
            instance_group=None)

        with mock.patch.object(self.driver.host_manager,
                               'get_filtered_hosts') as mock_get_hosts:
            mock_get_hosts.side_effect = fake_get_filtered_hosts
            weighed_hosts = self.driver._schedule(self.context, spec_obj,
                    [uuids.instance])

        self.assertEqual(len(weighed_hosts), 10)
        for weighed_host in weighed_hosts:
            self.assertIsNotNone(weighed_host.obj)