Exemplo n.º 1
0
def create_ctx_from_trust(trust_id):
    """Return context built from given trust."""
    ctx = context.current()

    ctx = context.BlazarContext(user_name=CONF.os_admin_username,
                                project_name=CONF.os_admin_project_name,
                                request_id=ctx.request_id,
                                global_request_id=ctx.global_request_id)
    auth_url = "%s://%s:%s" % (CONF.os_auth_protocol,
                               base.get_os_auth_host(CONF), CONF.os_auth_port)
    if CONF.os_auth_prefix:
        auth_url += "/%s" % CONF.os_auth_prefix
    client = keystone.BlazarKeystoneClient(
        password=CONF.os_admin_password,
        trust_id=trust_id,
        auth_url=auth_url,
        ctx=ctx,
    )

    # use 'with ctx' statement in the place you need context from trust
    return context.BlazarContext(
        user_name=ctx.user_name,
        project_name=ctx.project_name,
        auth_token=client.auth_token,
        service_catalog=client.service_catalog.catalog['catalog'],
        project_id=client.tenant_id,
        request_id=ctx.request_id,
        global_request_id=ctx.global_request_id)
Exemplo n.º 2
0
    def test_service_catalog_default(self):
        ctxt = context.BlazarContext(user_id=uuidsentinel.user_id,
                                     project_id=uuidsentinel.project_id)
        self.assertEqual([], ctxt.service_catalog)

        ctxt = context.BlazarContext(user_id=uuidsentinel.user_id,
                                     project_id=uuidsentinel.project_id,
                                     service_catalog=[])
        self.assertEqual([], ctxt.service_catalog)

        ctxt = context.BlazarContext(user_id=uuidsentinel.user_id,
                                     project_id=uuidsentinel.project_id,
                                     service_catalog=None)
        self.assertEqual([], ctxt.service_catalog)
Exemplo n.º 3
0
 def fake_ctx_from_headers(headers):
     if not headers:
         return context.BlazarContext(user_id='fake',
                                      project_id='fake',
                                      roles=['member'])
     roles = headers.get('X-Roles', six.text_type('member')).split(',')
     return context.BlazarContext(
         user_id=headers.get('X-User-Id', 'fake'),
         project_id=headers.get('X-Project-Id', 'fake'),
         auth_token=headers.get('X-Auth-Token', None),
         service_catalog=None,
         user_name=headers.get('X-User-Name', 'fake'),
         project_name=headers.get('X-Project-Name', 'fake'),
         roles=roles,
     )
Exemplo n.º 4
0
 def test_to_dict(self):
     ctx = context.BlazarContext(
         user_id=111,
         project_id=222,
         request_id='req-679033b7-1755-4929-bf85-eb3bfaef7e0b')
     expected = {
         'auth_token': None,
         'domain': None,
         'global_request_id': None,
         'is_admin': False,
         'is_admin_project': True,
         'project': 222,
         'project_domain': None,
         'project_id': 222,
         'project_name': None,
         'read_only': False,
         'request_id': 'req-679033b7-1755-4929-bf85-eb3bfaef7e0b',
         'resource_uuid': None,
         'roles': [],
         'service_catalog': [],
         'show_deleted': False,
         'system_scope': None,
         'tenant': 222,
         'user': 111,
         'user_domain': None,
         'user_id': 111,
         'user_identity': '111 222 - - -',
         'user_name': None
     }
     self.assertEqual(expected, ctx.to_dict())
    def test_on_end(self):
        fip_reservation_get = self.patch(self.db_api, 'fip_reservation_get')
        fip_reservation_get.return_value = {
            'reservation_id': 'reservation-id1',
            'network_id': 'network-id1'
        }
        fip_allocation_get_all_by_values = self.patch(
            self.db_api, 'fip_allocation_get_all_by_values')
        fip_allocation_get_all_by_values.return_value = [{
            'floatingip_id':
            'fip-id',
        }]
        fip_get = self.patch(self.db_api, 'floatingip_get')
        fip_get.return_value = {
            'network_id': 'net-id',
            'subnet_id': 'subnet-id',
            'floating_ip_address': '172.2.24.100'
        }
        self.set_context(context.BlazarContext(project_id='fake-project-id'))
        m = mock.MagicMock()
        self.fip_pool.return_value = m

        fip_plugin = floatingip_plugin.FloatingIpPlugin()
        fip_plugin.on_end('resource-id1')

        self.fip_pool.assert_called_once_with('network-id1')
        m.delete_reserved_floatingip.assert_called_once_with('172.2.24.100')
Exemplo n.º 6
0
    def setUp(self):
        super(ReservationPoolTestCase, self).setUp()
        self.pool_name = 'pool-name-xxx'
        self.project_id = 'project-uuid'
        self.fake_aggregate = AggregateFake(i=123,
                                            name='fooname',
                                            hosts=['host1', 'host2'])
        physical_host_conf = cfg.CONF[host_plugin.RESOURCE_TYPE]
        nova_conf = cfg.CONF.nova
        self.freepool_name = nova_conf.aggregate_freepool_name
        self.project_id_key = nova_conf.project_id_key
        self.blazar_owner = nova_conf.blazar_owner
        self.blazar_az_prefix = physical_host_conf.blazar_az_prefix

        self.fake_freepool = AggregateFake(i=456,
                                           name=self.freepool_name,
                                           hosts=['host3'])

        self.set_context(context.BlazarContext(project_id=self.project_id))

        self.nova_client = nova_client
        self.nova = self.patch(self.nova_client, 'Client').return_value

        self.patch(self.nova.aggregates, 'set_metadata')
        self.patch(self.nova.aggregates, 'remove_host')

        self.patch(base, 'url_for').return_value = 'http://foo.bar'
        self.pool = nova.ReservationPool()

        self.p_name = self.patch(self.pool, '_generate_aggregate_name')
        self.p_name.return_value = self.pool_name
    def setUp(self):
        super(MaxLeaseDurationTestCase, self).setUp()

        self.cfg = cfg
        self.region = 'RegionOne'
        filters.all_filters = ['MaxLeaseDurationFilter']

        self.enforcement = enforcement.UsageEnforcement()

        cfg.CONF.set_override('enabled_filters',
                              filters.all_filters,
                              group='enforcement')
        cfg.CONF.set_override('os_region_name', self.region)

        self.enforcement.load_filters()
        cfg.CONF.set_override('max_lease_duration', 3600, group='enforcement')
        self.fake_service_catalog = [
            dict(type='identity',
                 endpoints=[
                     dict(interface='public',
                          region=self.region,
                          url='https://fakeauth.com')
                 ])
        ]

        self.ctx = context.BlazarContext(
            user_id='111',
            project_id='222',
            service_catalog=self.fake_service_catalog)
        self.set_context(self.ctx)

        self.fake_host_id = '1'
        self.fake_host = {
            'id': self.fake_host_id,
            'hypervisor_hostname': 'hypvsr1',
            'service_name': 'compute1',
            'vcpus': 4,
            'cpu_info': 'foo',
            'hypervisor_type': 'xen',
            'hypervisor_version': 1,
            'memory_mb': 8192,
            'local_gb': 10,
        }

        self.addCleanup(self.cfg.CONF.clear_override,
                        'enabled_filters',
                        group='enforcement')
        self.addCleanup(self.cfg.CONF.clear_override,
                        'max_lease_duration',
                        group='enforcement')
        self.addCleanup(self.cfg.CONF.clear_override,
                        'max_lease_duration_exempt_project_ids',
                        group='enforcement')
        self.addCleanup(self.cfg.CONF.clear_override, 'os_region_name')
Exemplo n.º 8
0
    def test_blazar_context_elevated(self):
        user_context = context.BlazarContext(
            user_id=uuidsentinel.user_id,
            project_id=uuidsentinel.project_id,
            is_admin=False)
        self.assertFalse(user_context.is_admin)

        admin_context = user_context.elevated()
        self.assertFalse(user_context.is_admin)
        self.assertTrue(admin_context.is_admin)
        self.assertNotIn('admin', user_context.roles)
        self.assertIn('admin', admin_context.roles)
Exemplo n.º 9
0
def create_ctx_from_trust(trust_id):
    """Return context built from given trust."""
    ctx = context.BlazarContext(
        user_name=CONF.os_admin_username,
        project_name=CONF.os_admin_project_name,
    )
    auth_url = "%s://%s:%s/%s" % (CONF.os_auth_protocol,
                                  CONF.os_auth_host,
                                  CONF.os_auth_port,
                                  CONF.os_auth_prefix)
    client = keystone.BlazarKeystoneClient(
        password=CONF.os_admin_password,
        trust_id=trust_id,
        auth_url=auth_url,
        ctx=ctx,
    )

    # use 'with ctx' statement in the place you need context from trust
    return context.BlazarContext(
        ctx,
        auth_token=client.auth_token,
        service_catalog=client.service_catalog.catalog['catalog'],
        project_id=client.tenant_id,
    )
Exemplo n.º 10
0
 def setUp(self):
     super(LeaseAPITestCase, self).setUp()
     self.app = make_app()
     self.headers = {
         'Accept': 'application/json',
         'OpenStack-API-Version': 'reservation 1.0'
     }
     self.lease_uuid = six.text_type(uuidutils.generate_uuid())
     self.mock_ctx = self.patch(api_context, 'ctx_from_headers')
     self.mock_ctx.return_value = context.BlazarContext(user_id='fake',
                                                        project_id='fake',
                                                        roles=['member'])
     self.create_lease = self.patch(service_api.API, 'create_lease')
     self.get_leases = self.patch(service_api.API, 'get_leases')
     self.get_lease = self.patch(service_api.API, 'get_lease')
     self.update_lease = self.patch(service_api.API, 'update_lease')
     self.delete_lease = self.patch(service_api.API, 'delete_lease')
Exemplo n.º 11
0
def ctx_from_headers(headers):
    try:
        service_catalog = jsonutils.loads(headers['X-Service-Catalog'])
    except KeyError:
        raise exceptions.ServiceCatalogNotFound()
    except TypeError:
        raise exceptions.WrongFormat()

    return context.BlazarContext(
        user_id=headers['X-User-Id'],
        project_id=headers['X-Project-Id'],
        auth_token=headers['X-Auth-Token'],
        service_catalog=service_catalog,
        user_name=headers['X-User-Name'],
        project_name=headers['X-Project-Name'],
        roles=list(map(six.text_type.strip, headers['X-Roles'].split(','))),
    )
Exemplo n.º 12
0
    def test_update_resources_in_active(self):
        def fake_host_get(host_id):
            return {'service_name': 'host' + host_id[-1]}

        reservation = {
            'id': 'reservation-id1',
            'status': 'active',
            'vcpus': 2,
            'memory_mb': 1024,
            'disk_gb': 10,
            'aggregate_id': 'aggregate-1'
        }

        mock_reservation_get = self.patch(db_api, 'reservation_get')
        mock_reservation_get.return_value = reservation
        self.set_context(context.BlazarContext(project_id='fake-project'))
        plugin = instance_plugin.VirtualInstancePlugin()

        fake_pool = mock.MagicMock()
        mock_pool = self.patch(nova, 'ReservationPool')
        mock_pool.return_value = fake_pool

        mock_alloc_get = self.patch(db_api,
                                    'host_allocation_get_all_by_values')
        mock_alloc_get.return_value = [{
            'compute_host_id': 'host-id1'
        }, {
            'compute_host_id': 'host-id2'
        }, {
            'compute_host_id': 'host-id3'
        }]

        mock_host_get = self.patch(db_api, 'host_get')
        mock_host_get.side_effect = fake_host_get

        plugin.update_resources('reservation-id1')

        mock_reservation_get.assert_called_once_with('reservation-id1')
        for i in range(3):
            fake_pool.add_computehost.assert_any_call('aggregate-1',
                                                      'host' + str(i + 1),
                                                      stay_in=True)
Exemplo n.º 13
0
    def test_update_resources(self):
        reservation = {
            'id': 'reservation-id1',
            'status': 'pending',
            'vcpus': 2,
            'memory_mb': 1024,
            'disk_gb': 10,
            'server_group_id': 'group-1'
        }
        mock_reservation_get = self.patch(db_api, 'reservation_get')
        mock_reservation_get.return_value = reservation
        fake_client = mock.MagicMock()
        mock_nova_client = self.patch(nova, 'NovaClientWrapper')
        mock_nova_client.return_value = fake_client
        self.set_context(
            context.BlazarContext(project_id='fake-project',
                                  auth_token='fake-token'))
        plugin = instance_plugin.VirtualInstancePlugin()
        fake_flavor = mock.MagicMock(method='set_keys',
                                     flavorid='reservation-id1')
        mock_nova = mock.MagicMock()
        type(plugin).nova = mock_nova
        mock_nova.nova.flavors.create.return_value = fake_flavor

        plugin.update_resources('reservation-id1')

        mock_reservation_get.assert_called_once_with('reservation-id1')
        mock_nova.nova.flavors.delete.assert_called_once_with(
            'reservation-id1')
        mock_nova.nova.flavors.create.assert_called_once_with(
            flavorid='reservation-id1',
            name='reservation:reservation-id1',
            vcpus=2,
            ram=1024,
            disk=10,
            is_public=False)
        fake_flavor.set_keys.assert_called_once_with({
            'aggregate_instance_extra_specs:reservation':
            'reservation-id1',
            'affinity_id':
            'group-1'
        })
Exemplo n.º 14
0
    def test_on_start(self):
        def fake_host_get(host_id):
            return {'service_name': 'host' + host_id[-1]}

        self.set_context(context.BlazarContext(project_id='fake-project'))
        plugin = instance_plugin.VirtualInstancePlugin()

        mock_inst_get = self.patch(db_api, 'instance_reservation_get')
        mock_inst_get.return_value = {
            'reservation_id': 'reservation-id1',
            'aggregate_id': 'aggregate-id1'
        }

        mock_nova = mock.MagicMock()
        type(plugin).nova = mock_nova

        fake_pool = mock.MagicMock()
        mock_pool = self.patch(nova, 'ReservationPool')
        mock_pool.return_value = fake_pool

        mock_alloc_get = self.patch(db_api,
                                    'host_allocation_get_all_by_values')
        mock_alloc_get.return_value = [{
            'compute_host_id': 'host-id1'
        }, {
            'compute_host_id': 'host-id2'
        }, {
            'compute_host_id': 'host-id3'
        }]

        mock_host_get = self.patch(db_api, 'host_get')
        mock_host_get.side_effect = fake_host_get

        plugin.on_start('resource-id1')

        mock_nova.flavor_access.add_tenant_access.assert_called_once_with(
            'reservation-id1', 'fake-project')
        for i in range(3):
            fake_pool.add_computehost.assert_any_call('aggregate-id1',
                                                      'host' + str(i + 1),
                                                      stay_in=True)
Exemplo n.º 15
0
    def test_on_end(self):
        self.set_context(context.BlazarContext(project_id='fake-project-id'))

        plugin = instance_plugin.VirtualInstancePlugin()

        fake_instance_reservation = {'reservation_id': 'reservation-id1'}
        mock_inst_get = self.patch(db_api, 'instance_reservation_get')
        mock_inst_get.return_value = fake_instance_reservation

        mock_alloc_get = self.patch(db_api,
                                    'host_allocation_get_all_by_values')
        mock_alloc_get.return_value = [{
            'id': 'host-alloc-id1'
        }, {
            'id': 'host-alloc-id2'
        }]

        self.patch(db_api, 'host_allocation_destroy')

        fake_servers = [mock.MagicMock(method='delete') for i in range(5)]
        mock_nova = mock.MagicMock()
        type(plugin).nova = mock_nova
        mock_nova.servers.list.return_value = fake_servers

        mock_cleanup_resources = self.patch(plugin, 'cleanup_resources')

        plugin.on_end('resource-id1')

        mock_nova.flavor_access.remove_tenant_access.assert_called_once_with(
            'reservation-id1', 'fake-project-id')

        mock_nova.servers.list.assert_called_once_with(search_opts={
            'flavor': 'reservation-id1',
            'all_tenants': 1
        },
                                                       detailed=False)
        for fake in fake_servers:
            fake.delete.assert_called_once()
        mock_cleanup_resources.assert_called_once_with(
            fake_instance_reservation)
Exemplo n.º 16
0
 def setUp(self):
     super(OsHostAPITestCase, self).setUp()
     self.app = make_app()
     self.headers = {
         'Accept': 'application/json',
         'OpenStack-API-Version': 'reservation 1.0'
     }
     self.host_id = str('1')
     self.mock_ctx = self.patch(api_context, 'ctx_from_headers')
     self.mock_ctx.return_value = context.BlazarContext(user_id='fake',
                                                        project_id='fake',
                                                        roles=['member'])
     self.get_computehosts = self.patch(service_api.API, 'get_computehosts')
     self.create_computehost = self.patch(service_api.API,
                                          'create_computehost')
     self.get_computehost = self.patch(service_api.API, 'get_computehost')
     self.update_computehost = self.patch(service_api.API,
                                          'update_computehost')
     self.delete_computehost = self.patch(service_api.API,
                                          'delete_computehost')
     self.list_allocations = self.patch(service_api.API, 'list_allocations')
     self.get_allocations = self.patch(service_api.API, 'get_allocations')
Exemplo n.º 17
0
def ctx_from_headers(headers):
    try:
        service_catalog = jsonutils.loads(headers['X-Service-Catalog'])
    except KeyError:
        raise exceptions.ServiceCatalogNotFound()
    except TypeError:
        raise exceptions.WrongFormat()

    kwargs = {"user_id": headers['X-User-Id'],
              "project_id": headers['X-Project-Id'],
              "auth_token": headers['X-Auth-Token'],
              "service_catalog": service_catalog,
              "user_name": headers['X-User-Name'],
              "project_name": headers['X-Project-Name'],
              "roles": list(
                  map(str.strip, headers['X-Roles'].split(',')))}

    # For v1 only, request_id and global_request_id will be available.
    if headers.environ['PATH_INFO'].startswith('/v1'):
        kwargs['request_id'] = headers.environ['openstack.request_id']
        kwargs['global_request_id'] = headers.environ.get(
            'openstack.global_request_id')
    return context.BlazarContext(**kwargs)
Exemplo n.º 18
0
    def setUp(self):
        super(BlazarPolicyTestCase, self).setUp()

        self.context = context.BlazarContext(user_id='fake',
                                             project_id='fake',
                                             roles=['member'])
Exemplo n.º 19
0
 def decorator(*args, **kwargs):
     with context.BlazarContext():
         return func(*args, **kwargs)
Exemplo n.º 20
0
 def run_method(__ctx, **kwargs):
     with context.BlazarContext(**__ctx):
         return method(**kwargs)
Exemplo n.º 21
0
    def test_create_resources(self):
        instance_reservation = {
            'reservation_id': 'reservation-id1',
            'vcpus': 2,
            'memory_mb': 1024,
            'disk_gb': 20,
            'affinity': False
        }

        plugin = instance_plugin.VirtualInstancePlugin()

        fake_client = mock.MagicMock()
        mock_nova_client = self.patch(nova, 'NovaClientWrapper')
        mock_nova_client.return_value = fake_client
        fake_server_group = mock.MagicMock(id='server_group_id1')
        fake_client.nova.server_groups.create.return_value = \
            fake_server_group

        self.set_context(
            context.BlazarContext(project_id='fake-project',
                                  auth_token='fake-token'))
        fake_flavor = mock.MagicMock(method='set_keys',
                                     flavorid='reservation-id1')
        mock_nova = mock.MagicMock()
        type(plugin).nova = mock_nova
        mock_nova.nova.flavors.create.return_value = fake_flavor

        fake_pool = mock.MagicMock(id='pool-id1')
        fake_agg = mock.MagicMock()
        fake_pool.create.return_value = fake_agg
        mock_pool = self.patch(nova, 'ReservationPool')
        mock_pool.return_value = fake_pool

        expected = (fake_flavor, fake_server_group, fake_agg)

        ret = plugin._create_resources(instance_reservation)

        self.assertEqual(expected, ret)

        fake_client.nova.server_groups.create.assert_called_once_with(
            'reservation:reservation-id1', 'anti-affinity')
        mock_nova.nova.flavors.create.assert_called_once_with(
            flavorid='reservation-id1',
            name='reservation:reservation-id1',
            vcpus=2,
            ram=1024,
            disk=20,
            is_public=False)
        fake_flavor.set_keys.assert_called_once_with({
            'aggregate_instance_extra_specs:reservation':
            'reservation-id1',
            'affinity_id':
            'server_group_id1'
        })
        fake_pool.create.assert_called_once_with(name='reservation-id1',
                                                 metadata={
                                                     'reservation':
                                                     'reservation-id1',
                                                     'filter_tenant_id':
                                                     'fake-project',
                                                     'affinity_id':
                                                     'server_group_id1'
                                                 })
Exemplo n.º 22
0
 def test_elevated(self):
     with context.BlazarContext(user_id="user", project_id="project"):
         ctx = context.BlazarContext.elevated()
         self.assertEqual(ctx.user_id, "user")
         self.assertEqual(ctx.project_id, "project")
         self.assertEqual(ctx.is_admin, True)
Exemplo n.º 23
0
 def test_update_active_reservation_fip_creation_failure(self):
     fip_plugin = floatingip_plugin.FloatingIpPlugin()
     values = {
         'start_date': datetime.datetime(2013, 12, 19, 20, 0),
         'end_date': datetime.datetime(2013, 12, 19, 21, 0),
         'resource_type': plugin.RESOURCE_TYPE,
         'amount': 3,
     }
     lease_get = self.patch(self.db_api, 'lease_get')
     lease_get.return_value = {
         'id': '018c1b43-e69e-4aef-a543-09681539cf4c',
         'start_date': datetime.datetime(2013, 12, 19, 20, 0),
         'end_date': datetime.datetime(2013, 12, 19, 21, 0),
     }
     reservation_get = self.patch(self.db_api, 'reservation_get')
     reservation_get.return_value = {
         'id': '441c1476-9f8f-4700-9f30-cd9b6fef3509',
         'lease_id': '018c1b43-e69e-4aef-a543-09681539cf4c',
         'resource_id': 'fip-reservation-id-1',
         'resource_type': 'virtual:floatingip',
         'status': 'active',
     }
     fip_allocation_get_all_by_values = self.patch(
         self.db_api, 'fip_allocation_get_all_by_values')
     fip_allocation_get_all_by_values.return_value = [{
         'floatingip_id':
         'fip1'
     }]
     fip_reservation_get = self.patch(self.db_api, 'fip_reservation_get')
     fip_reservation_get.return_value = {
         'id': 'fip_resv_id1',
         'amount': 1,
         'reservation_id': '441c1476-9f8f-4700-9f30-cd9b6fef3509',
         'network_id': 'f548089e-fb3e-4013-a043-c5ed809c7a67',
         'required_floatingips': [],
     }
     matching_fips = self.patch(fip_plugin, '_matching_fips')
     matching_fips.return_value = ['fip2', 'fip3']
     fip_get = self.patch(self.db_api, 'floatingip_get')
     fip_get.side_effect = ({
         'network_id': 'f548089e-fb3e-4013-a043-c5ed809c7a67',
         'subnet_id': 'subnet-id',
         'floating_ip_address': '172.2.24.100'
     }, {
         'network_id': 'f548089e-fb3e-4013-a043-c5ed809c7a67',
         'subnet_id': 'subnet-id',
         'floating_ip_address': '172.2.24.101'
     })
     self.set_context(context.BlazarContext(project_id='fake-project-id'))
     m = mock.MagicMock()
     m.create_reserved_floatingip.side_effect = (None, Exception())
     self.fip_pool.return_value = m
     fip_allocation_create = self.patch(self.db_api,
                                        'fip_allocation_create')
     fip_allocation_destroy = self.patch(self.db_api,
                                         'fip_allocation_destroy')
     self.assertRaises(mgr_exceptions.NeutronClientError,
                       fip_plugin.update_reservation,
                       '441c1476-9f8f-4700-9f30-cd9b6fef3509', values)
     self.fip_pool.assert_called_once_with(
         'f548089e-fb3e-4013-a043-c5ed809c7a67')
     calls = [
         mock.call('subnet-id', '172.2.24.100', 'fake-project-id',
                   '441c1476-9f8f-4700-9f30-cd9b6fef3509'),
         mock.call('subnet-id', '172.2.24.101', 'fake-project-id',
                   '441c1476-9f8f-4700-9f30-cd9b6fef3509'),
     ]
     m.create_reserved_floatingip.assert_has_calls(calls)
     self.assertFalse(fip_allocation_create.called)
     self.assertFalse(fip_allocation_destroy.called)