Exemplo n.º 1
0
    def test_instance_fault_get_by_instance(self):
        """ ensure we can retrieve an instance fault by  instance UUID """
        ctxt = context.get_admin_context()

        # Create faults
        uuid = str(utils.gen_uuid())
        fault_values = {
            'message': 'message',
            'details': 'detail',
            'instance_uuid': uuid,
            'code': 404,
        }
        db.instance_fault_create(ctxt, fault_values)

        uuid2 = str(utils.gen_uuid())
        fault_values = {
            'message': 'message',
            'details': 'detail',
            'instance_uuid': uuid2,
            'code': 500,
        }
        db.instance_fault_create(ctxt, fault_values)

        # Retrieve the fault to ensure it was successfully added
        instance_fault = db.instance_fault_get_by_instance(ctxt, uuid2)
        self.assertEqual(500, instance_fault['code'])
Exemplo n.º 2
0
def fake_instance_get(context, instance_id):
        return {
        "id": 1,
        "uuid": utils.gen_uuid(),
        "name": 'fake',
        "user_id": 'fakeuser',
        "project_id": '123'}
Exemplo n.º 3
0
    def test_multi_choice_server(self):
        uuid = str(utils.gen_uuid())
        req = webob.Request.blank('/servers/' + uuid)
        req.accept = "application/json"
        res = req.get_response(fakes.wsgi_app())
        self.assertEqual(res.status_int, 300)
        self.assertEqual(res.content_type, "application/json")

        expected = {
        "choices": [
            {
                "id": "v1.1",
                "status": "CURRENT",
                "links": [
                    {
                        "href": "http://localhost/v1.1/servers/" + uuid,
                        "rel": "self",
                    },
                ],
                "media-types": [
                    {
                        "base": "application/xml",
                        "type": "application/vnd.openstack.compute+xml"
                                ";version=1.1"
                    },
                    {
                        "base": "application/json",
                        "type": "application/vnd.openstack.compute+json"
                                ";version=1.1"
                    },
                ],
            },
        ], }

        self.assertDictMatch(expected, json.loads(res.body))
Exemplo n.º 4
0
 def setUp(self):
     super(AdminActionsTest, self).setUp()
     self.stubs.Set(compute.API, "get", fake_compute_api_get)
     self.UUID = utils.gen_uuid()
     for _method in self._methods:
         self.stubs.Set(compute.API, _method, fake_compute_api)
     self.stubs.Set(scheduler_rpcapi.SchedulerAPI, "live_migration", fake_scheduler_api_live_migration)
Exemplo n.º 5
0
    def get_vnc_console(self, context, console_type, instance):
        """Return connection information for a vnc console."""
        context = context.elevated()
        LOG.debug(_("Getting vnc console"), instance=instance)
        token = str(utils.gen_uuid())

        if console_type == 'ajaxterm':
            access_url = '%s?token=%s' % (FLAGS.ajaxterm_base_url, token)
            connect_info = self.driver.get_web_console(instance)
            connect_info['token'] = token
            connect_info['access_url'] = access_url
            return connect_info
        elif console_type == 'novnc':
            # For essex, novncproxy_base_url must include the full path
            # including the html file (like http://myhost/vnc_auto.html)
            access_url = '%s?token=%s' % (FLAGS.novncproxy_base_url, token)
        elif console_type == 'xvpvnc':
            access_url = '%s?token=%s' % (FLAGS.xvpvncproxy_base_url, token)
        else:
            raise exception.ConsoleTypeInvalid(console_type=console_type)

        # Retrieve connect info from driver, and then decorate with our
        # access info token
        connect_info = self.driver.get_vnc_console(instance)
        connect_info['token'] = token
        connect_info['access_url'] = access_url

        return connect_info
Exemplo n.º 6
0
    def setUp(self):
        super(CreateBackupTests, self).setUp()

        self.stubs.Set(compute_api.API, 'get', fake_compute_api_get)
        self.backup_stubs = fakes.stub_out_compute_api_backup(self.stubs)
        self.app = compute.APIRouter(init_only=('servers',))
        self.uuid = utils.gen_uuid()
Exemplo n.º 7
0
    def test_instance_fault_get_by_instance_first_fault(self):
        """Instance_fault_get_by_instance should return the latest fault """
        ctxt = context.get_admin_context()

        # Create faults
        uuid = str(utils.gen_uuid())
        fault_values = {
            'message': 'message',
            'details': 'detail',
            'instance_uuid': uuid,
            'code': 404,
        }
        db.instance_fault_create(ctxt, fault_values)

        fault_values = {
            'message': 'message',
            'details': 'detail',
            'instance_uuid': uuid,
            'code': 500,
        }
        db.instance_fault_create(ctxt, fault_values)

        # Retrieve the fault to ensure it was successfully added
        instance_fault = db.instance_fault_get_by_instance(ctxt, uuid)
        self.assertEqual(500, instance_fault['code'])
Exemplo n.º 8
0
    def setUp(self):
        super(CreateBackupTests, self).setUp()

        self.stubs.Set(compute.API, "get", fake_compute_api_get)
        self.backup_stubs = fakes.stub_out_compute_api_backup(self.stubs)
        self.app = compute_api.APIRouter()
        self.uuid = utils.gen_uuid()
Exemplo n.º 9
0
    def fake_instance_create(context, values):
        """Stubs out the db.instance_create method."""

        type_data = INSTANCE_TYPES[values['instance_type']]

        base_options = {
            'name': values['name'],
            'id': values['id'],
            'uuid': utils.gen_uuid(),
            'reservation_id': utils.generate_uid('r'),
            'image_ref': values['image_ref'],
            'kernel_id': values['kernel_id'],
            'ramdisk_id': values['ramdisk_id'],
            'vm_state': vm_states.BUILDING,
            'task_state': task_states.SCHEDULING,
            'user_id': values['user_id'],
            'project_id': values['project_id'],
            'launch_time': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
            'instance_type': values['instance_type'],
            'memory_mb': type_data['memory_mb'],
            'vcpus': type_data['vcpus'],
            'mac_addresses': [{'address': values['mac_address']}],
            'local_gb': type_data['local_gb'],
            }
        return FakeModel(base_options)
Exemplo n.º 10
0
    def test_instance_get_all_by_filters_paginate(self):
        self.flags(sql_connection="notdb://")
        test1 = self.create_instances_with_args(display_name='test1')
        test2 = self.create_instances_with_args(display_name='test2')
        test3 = self.create_instances_with_args(display_name='test3')

        result = db.instance_get_all_by_filters(self.context,
                                                {'display_name': '%test%'},
                                                marker=None)
        self.assertEqual(3, len(result))
        result = db.instance_get_all_by_filters(self.context,
                                                {'display_name': '%test%'},
                                                sort_dir="asc",
                                                marker=test1['uuid'])
        self.assertEqual(2, len(result))
        result = db.instance_get_all_by_filters(self.context,
                                                {'display_name': '%test%'},
                                                sort_dir="asc",
                                                marker=test2['uuid'])
        self.assertEqual(1, len(result))
        result = db.instance_get_all_by_filters(self.context,
                                                {'display_name': '%test%'},
                                                sort_dir="asc",
                                                marker=test3['uuid'])
        self.assertEqual(0, len(result))

        self.assertRaises(exception.MarkerNotFound,
                          db.instance_get_all_by_filters,
                          self.context, {'display_name': '%test%'},
                          marker=str(utils.gen_uuid()))
Exemplo n.º 11
0
 def setUp(self):
     super(AdminActionsTest, self).setUp()
     self.stubs.Set(compute.API, 'get', fake_compute_api_get)
     self.UUID = utils.gen_uuid()
     self.flags(allow_admin_api=True)
     for _method in self._methods:
         self.stubs.Set(compute.API, _method, fake_compute_api)
Exemplo n.º 12
0
 def __init__(self, size, name, description, id, snapshot, volume_type, metadata, availability_zone):
     snapshot_id = None
     if snapshot is not None:
         snapshot_id = snapshot["id"]
     if id is None:
         id = str(utils.gen_uuid())
     self.vol = {
         "created_at": timeutils.utcnow(),
         "deleted_at": None,
         "updated_at": timeutils.utcnow(),
         "uuid": "WTF",
         "deleted": False,
         "id": id,
         "user_id": self.user_uuid,
         "project_id": "fake-project-id",
         "snapshot_id": snapshot_id,
         "host": None,
         "size": size,
         "availability_zone": availability_zone,
         "instance_uuid": None,
         "mountpoint": None,
         "attach_time": timeutils.utcnow(),
         "status": "available",
         "attach_status": "detached",
         "scheduled_at": None,
         "launched_at": None,
         "terminated_at": None,
         "display_name": name,
         "display_description": description,
         "provider_location": "fake-location",
         "provider_auth": "fake-auth",
         "volume_type_id": 99,
     }
Exemplo n.º 13
0
    def create_network(self, tenant_id, network_name, **kwargs):

        uuid = str(utils.gen_uuid())
        self.nets[uuid] = {'net-name': network_name,
                           'tenant-id': tenant_id,
                           'ports': {}}
        return uuid
Exemplo n.º 14
0
 def create_network(self, body=None, tenant=None):
     """Creates a new network"""
     nets = self._get_tenant_nets(tenant)
     uuid = str(utils.gen_uuid())
     name = body["network"]["name"]
     nets[uuid] = {"ports": {}, "name": name}
     return {"network": {"id": uuid}}
Exemplo n.º 15
0
    def __init__(self, user_id, project_id, is_admin=None, read_deleted="no",
                 roles=None, remote_address=None, timestamp=None,
                 request_id=None, auth_token=None, strategy='noauth',
                 overwrite=True):
        """
        :param read_deleted: 'no' indicates deleted records are hidden, 'yes'
            indicates deleted records are visible, 'only' indicates that
            *only* deleted records are visible.

        :param overwrite: Set to False to ensure that the greenthread local
            copy of the index is not overwritten.
        """
        self.user_id = user_id
        self.project_id = project_id
        self.roles = roles or []
        self.is_admin = is_admin
        if self.is_admin is None:
            self.is_admin = 'admin' in [x.lower() for x in self.roles]
        elif self.is_admin and 'admin' not in self.roles:
            self.roles.append('admin')
        self.read_deleted = read_deleted
        self.remote_address = remote_address
        if not timestamp:
            timestamp = utils.utcnow()
        if isinstance(timestamp, basestring):
            timestamp = utils.parse_strtime(timestamp)
        self.timestamp = timestamp
        if not request_id:
            request_id = 'req-' + str(utils.gen_uuid())
        self.request_id = request_id
        self.auth_token = auth_token
        self.strategy = strategy
        if overwrite or not hasattr(local.store, 'context'):
            local.store.context = self
Exemplo n.º 16
0
    def create_and_attach_port(self, tenant_id, net_id, interface_id):
        if not self.network_exists(tenant_id, net_id):
            raise Exception(_("network %(net_id)s does not exist for tenant %(tenant_id)" % locals()))

        self._confirm_not_attached(interface_id)
        uuid = str(utils.gen_uuid())
        self.nets[net_id]["ports"][uuid] = {"port-state": "ACTIVE", "attachment-id": interface_id}
Exemplo n.º 17
0
 def create_port(self, network, body=None, tenant=None):
     """Creates a new port on a given network"""
     nets = self._get_tenant_nets(tenant)
     self._verify_net(network, nets)
     uuid = str(utils.gen_uuid())
     nets[network]['ports'][uuid] = {'attachment': None,
                                     'state': body['port']['state']}
     return {"port": {"id": uuid}}
Exemplo n.º 18
0
    def test_reboot_not_found(self):
        self.stubs.Set(nova.db, 'instance_get_by_uuid',
                       return_server_by_uuid_not_found)

        body = dict(reboot=dict(type="HARD"))
        req = fakes.HTTPRequest.blank(self.url)
        self.assertRaises(webob.exc.HTTPNotFound, self.controller.action,
                          req, str(utils.gen_uuid()), body)
Exemplo n.º 19
0
def create(name, memory, vcpus, root_gb, ephemeral_gb=None, flavorid=None,
           swap=None, rxtx_factor=None, is_public=True):
    """Creates instance types."""

    if flavorid is None:
        flavorid = utils.gen_uuid()
    if swap is None:
        swap = 0
    if rxtx_factor is None:
        rxtx_factor = 1
    if ephemeral_gb is None:
        ephemeral_gb = 0

    kwargs = {
        'memory_mb': memory,
        'vcpus': vcpus,
        'root_gb': root_gb,
        'ephemeral_gb': ephemeral_gb,
        'swap': swap,
        'rxtx_factor': rxtx_factor,
    }

    # ensure name does not contain any special characters
    invalid_name = INVALID_NAME_REGEX.search(name)
    if invalid_name:
        msg = _("names can only contain [a-zA-Z0-9_.- ]")
        raise exception.InvalidInput(reason=msg)

    # ensure some attributes are integers and greater than or equal to 0
    for option in kwargs:
        try:
            kwargs[option] = int(kwargs[option])
            assert kwargs[option] >= 0
        except (ValueError, AssertionError):
            msg = _("create arguments must be positive integers")
            raise exception.InvalidInput(reason=msg)

    # some value are required to be nonzero, not just positive
    for option in ['memory_mb', 'vcpus']:
        try:
            assert kwargs[option] > 0
        except AssertionError:
            msg = _("create arguments must be positive integers")
            raise exception.InvalidInput(reason=msg)

    kwargs['name'] = name
    # NOTE(vish): Internally, flavorid is stored as a string but it comes
    #             in through json as an integer, so we convert it here.
    kwargs['flavorid'] = unicode(flavorid)

    # ensure is_public attribute is boolean
    kwargs['is_public'] = utils.bool_from_str(is_public)

    try:
        return db.instance_type_create(context.get_admin_context(), kwargs)
    except exception.DBError, e:
        LOG.exception(_('DB error: %s') % e)
        raise exception.InstanceTypeCreateFailed()
Exemplo n.º 20
0
Arquivo: auth.py Projeto: xww/nova-old
    def __call__(self, req):
        user_id = req.headers.get('X_USER')
        user_id = req.headers.get('X_USER_ID', user_id)
        if user_id is None:
            LOG.debug("Neither X_USER_ID nor X_USER found in request")
            return webob.exc.HTTPUnauthorized()

        roles = self._get_roles(req)

        if 'X_TENANT_ID' in req.headers:
            # This is the new header since Keystone went to ID/Name
            project_id = req.headers['X_TENANT_ID']
        else:
            # This is for legacy compatibility
            project_id = req.headers['X_TENANT']
        project_name = req.headers.get('X_TENANT_NAME')
        user_name = req.headers.get('X_USER_NAME')

        # Get the auth token
        auth_token = req.headers.get('X_AUTH_TOKEN',
                                     req.headers.get('X_STORAGE_TOKEN'))

        # Build a context, including the auth_token...
        remote_address = req.remote_addr
        if FLAGS.use_forwarded_for:
            remote_address = req.headers.get('X-Forwarded-For', remote_address)

        service_catalog = None
        if req.headers.get('X_SERVICE_CATALOG') is not None:
            try:
                catalog_header = req.headers.get('X_SERVICE_CATALOG')
                service_catalog = jsonutils.loads(catalog_header)
            except ValueError:
                raise webob.exc.HTTPInternalServerError(
                          _('Invalid service catalog json.'))

        # NOTE(hzyangtk): add two parameters unified_log_id and unified_log_seq
        #                 for unified log module
        unified_log_id = req.headers.get('X-UNIFIED-LOG-ID',
                                         str(utils.gen_uuid()))
        unified_log_seq = '0'
        if req.headers.get('X-UNIFIED-LOG-SEQ'):
            unified_log_seq = req.headers.get('X-UNIFIED-LOG-SEQ') + '.0'

        ctx = context.RequestContext(user_id,
                                     project_id,
                                     user_name=user_name,
                                     project_name=project_name,
                                     roles=roles,
                                     auth_token=auth_token,
                                     remote_address=remote_address,
                                     service_catalog=service_catalog,
                                     unified_log_id=unified_log_id,
                                     unified_log_seq=unified_log_seq)

        req.environ['nova.context'] = ctx
        return self.application
def upgrade(migrate_engine):
    meta.bind = migrate_engine
    virtual_interfaces.create_column(uuid_column)

    rows = migrate_engine.execute(virtual_interfaces.select())
    for row in rows:
        vif_uuid = str(utils.gen_uuid())
        migrate_engine.execute(virtual_interfaces.update()\
                .where(virtual_interfaces.c.id == row[0])\
                .values(uuid=vif_uuid))
def upgrade(migrate_engine):
    meta.bind = migrate_engine
    networks.create_column(uuid_column)

    rows = migrate_engine.execute(networks.select())
    for row in rows:
        networks_uuid = str(utils.gen_uuid())
        migrate_engine.execute(networks.update()\
                .where(networks.c.id == row[0])\
                .values(uuid=networks_uuid))
Exemplo n.º 23
0
    def setUp(self):
        super(CreateBackupTests, self).setUp()

        self.stubs.Set(compute.API, 'get', fake_compute_api_get)
        self.backup_stubs = fakes.stub_out_compute_api_backup(self.stubs)

        self.flags(allow_admin_api=True)
        self.app = compute_api.APIRouter()

        self.uuid = utils.gen_uuid()
Exemplo n.º 24
0
 def _add_server(self, id=None, uuid=None):
     if id is None:
         id = self.max_id + 1
     if uuid is None:
         uuid = str(utils.gen_uuid())
     instance = stub_instance(id, uuid=uuid)
     self.instances_by_id[id] = instance
     self.ids_by_uuid[uuid] = id
     if id > self.max_id:
         self.max_id = id
Exemplo n.º 25
0
    def setUp(self):
        super(CreateBackupTests, self).setUp()

        self.stubs.Set(compute.API, 'get', fake_compute_api_get)
        self.backup_stubs = fakes.stub_out_compute_api_backup(self.stubs)

        router = compute_api.APIRouter()
        ext_middleware = extensions.ExtensionMiddleware(router)
        self.app = wsgi.LazySerializationMiddleware(ext_middleware)

        self.uuid = utils.gen_uuid()
Exemplo n.º 26
0
Arquivo: manager.py Projeto: bgh/nova
    def _add_virtual_interface(self, context, instance_id, network_id):
        vif = {"instance_id": instance_id, "network_id": network_id, "uuid": str(utils.gen_uuid())}

        # TODO(Vek): Ideally, we would have a VirtualInterface class
        #            that would take care of delegating to whoever it
        #            needs to get information from.  We'll look at
        #            this after Trey's refactorings...
        m_ipam = melange_ipam_lib.get_ipam_lib(self)
        vif["address"] = m_ipam.create_vif(vif["uuid"], vif["instance_id"], context.project_id)

        return self.db.virtual_interface_create(context, vif)
Exemplo n.º 27
0
 def setUp(self):
     super(ConsolesControllerTest, self).setUp()
     self.flags(verbose=True)
     self.instance_db = FakeInstanceDB()
     self.stubs.Set(db, 'instance_get',
                    self.instance_db.return_server_by_id)
     self.stubs.Set(db, 'instance_get_by_uuid',
                    self.instance_db.return_server_by_uuid)
     self.uuid = str(utils.gen_uuid())
     self.url = '/v2/fake/servers/%s/consoles' % self.uuid
     self.controller = consoles.Controller()
Exemplo n.º 28
0
Arquivo: fake.py Projeto: rohit-k/nova
    def create(self, context, metadata, data=None):
        """Store the image data and return the new image id.

        :raises: Duplicate if the image already exist.

        """
        image_id = str(metadata.get('id', utils.gen_uuid()))
        metadata['id'] = image_id
        if image_id in self.images:
            raise exception.Duplicate()
        self.images[image_id] = copy.deepcopy(metadata)
        return self.images[image_id]
Exemplo n.º 29
0
    def test_instance_fault_create(self):
        """Ensure we can create an instance fault"""
        ctxt = context.get_admin_context()
        uuid = str(utils.gen_uuid())

        # Create a fault
        fault_values = {"message": "message", "details": "detail", "instance_uuid": uuid, "code": 404}
        db.instance_fault_create(ctxt, fault_values)

        # Retrieve the fault to ensure it was successfully added
        faults = db.instance_fault_get_by_instance_uuids(ctxt, [uuid])
        self.assertEqual(404, faults[uuid][0]["code"])
Exemplo n.º 30
0
def get_fake_instance_data(name, project_id, user_id):
    return {'name': name,
              'id': 1,
              'uuid': utils.gen_uuid(),
              'project_id': project_id,
              'user_id': user_id,
              'image_ref': "1",
              'kernel_id': "1",
              'ramdisk_id': "1",
              'mac_address': "de:ad:be:ef:be:ef",
              'instance_type': 'm1.tiny',
              }
Exemplo n.º 31
0
 def test_gen_valid_uuid(self):
     self.assertUUIDLike(str(utils.gen_uuid()), True)
Exemplo n.º 32
0
    def setUp(self):
        super(TestQuantumv2, self).setUp()
        self.mox.StubOutWithMock(quantumv2, 'get_client')
        self.moxed_client = self.mox.CreateMock(client.Client)
        quantumv2.get_client(mox.IgnoreArg()).MultipleTimes().AndReturn(
            self.moxed_client)
        self.context = context.RequestContext('userid', 'my_tenantid')
        setattr(self.context, 'auth_token', 'bff4a5a6b9eb4ea2a6efec6eefb77936')
        self.instance = {
            'project_id': '9d049e4b60b64716978ab415e6fbd5c0',
            'uuid': str(utils.gen_uuid()),
            'display_name': 'test_instance',
            'security_groups': []
        }
        self.nets1 = [{
            'id': 'my_netid1',
            'name': 'my_netname1',
            'tenant_id': 'my_tenantid'
        }]
        self.nets2 = []
        self.nets2.append(self.nets1[0])
        self.nets2.append({
            'id': 'my_netid2',
            'name': 'my_netname2',
            'tenant_id': 'my_tenantid'
        })
        self.nets3 = self.nets2 + [{
            'id': 'my_netid3',
            'name': 'my_netname3',
            'tenant_id': 'my_tenantid'
        }]
        self.nets4 = [{
            'id': 'his_netid4',
            'name': 'his_netname4',
            'tenant_id': 'his_tenantid'
        }]

        self.nets = [self.nets1, self.nets2, self.nets3, self.nets4]

        self.port_address = '10.0.1.2'
        self.port_data1 = [{
            'network_id':
            'my_netid1',
            'device_id':
            'device_id1',
            'device_owner':
            'compute:nova',
            'id':
            'my_portid1',
            'fixed_ips': [{
                'ip_address': self.port_address,
                'subnet_id': 'my_subid1'
            }],
            'mac_address':
            'my_mac1',
        }]
        self.dhcp_port_data1 = [{
            'fixed_ips': [{
                'ip_address': '10.0.1.9',
                'subnet_id': 'my_subid1'
            }]
        }]
        self.port_data2 = []
        self.port_data2.append(self.port_data1[0])
        self.port_data2.append({
            'network_id':
            'my_netid2',
            'device_id':
            'device_id2',
            'device_owner':
            'compute:nova',
            'id':
            'my_portid2',
            'fixed_ips': [{
                'ip_address': '10.0.2.2',
                'subnet_id': 'my_subid2'
            }],
            'mac_address':
            'my_mac2',
        })
        self.port_data3 = [{
            'network_id': 'my_netid1',
            'device_id': 'device_id3',
            'device_owner': 'compute:nova',
            'id': 'my_portid3',
            'fixed_ips': [],  # no fixed ip
            'mac_address': 'my_mac3',
        }]
        self.subnet_data1 = [{
            'id': 'my_subid1',
            'cidr': '10.0.1.0/24',
            'network_id': 'my_netid1',
            'gateway_ip': '10.0.1.1',
            'dns_nameservers': ['8.8.1.1', '8.8.1.2']
        }]
        self.subnet_data2 = []
        self.subnet_data2.append({
            'id': 'my_subid2',
            'cidr': '10.0.2.0/24',
            'network_id': 'my_netid2',
            'gateway_ip': '10.0.2.1',
            'dns_nameservers': ['8.8.2.1', '8.8.2.2']
        })

        self.fip_pool = {
            'id': '4fdbfd74-eaf8-4884-90d9-00bd6f10c2d3',
            'name': 'ext_net',
            'router:external': True,
            'tenant_id': 'admin_tenantid'
        }
        self.fip_pool_nova = {
            'id': '435e20c3-d9f1-4f1b-bee5-4611a1dd07db',
            'name': 'nova',
            'router:external': True,
            'tenant_id': 'admin_tenantid'
        }
        self.fip_unassociated = {
            'tenant_id': 'my_tenantid',
            'id': 'fip_id1',
            'floating_ip_address': '172.24.4.227',
            'floating_network_id': self.fip_pool['id'],
            'port_id': None,
            'fixed_ip_address': None,
            'router_id': None
        }
        fixed_ip_address = self.port_data2[1]['fixed_ips'][0]['ip_address']
        self.fip_associated = {
            'tenant_id': 'my_tenantid',
            'id': 'fip_id2',
            'floating_ip_address': '172.24.4.228',
            'floating_network_id': self.fip_pool['id'],
            'port_id': self.port_data2[1]['id'],
            'fixed_ip_address': fixed_ip_address,
            'router_id': 'router_id1'
        }
Exemplo n.º 33
0
def create(name,
           memory,
           vcpus,
           root_gb,
           ephemeral_gb,
           flavorid=None,
           swap=None,
           rxtx_factor=None,
           is_public=True):
    """Creates instance types."""

    if flavorid is None:
        flavorid = utils.gen_uuid()
    if swap is None:
        swap = 0
    if rxtx_factor is None:
        rxtx_factor = 1

    kwargs = {
        'memory_mb': memory,
        'vcpus': vcpus,
        'root_gb': root_gb,
        'ephemeral_gb': ephemeral_gb,
        'swap': swap,
        'rxtx_factor': rxtx_factor,
    }

    # ensure name does not contain any special characters
    invalid_name = INVALID_NAME_REGEX.search(name)
    if invalid_name:
        msg = _("names can only contain [a-zA-Z0-9_.- ]")
        raise exception.InvalidInput(reason=msg)

    # ensure some attributes are integers and greater than or equal to 0
    for option in kwargs:
        try:
            kwargs[option] = int(kwargs[option])
            assert kwargs[option] >= 0
        except (ValueError, AssertionError):
            msg = _("create arguments must be positive integers")
            raise exception.InvalidInput(reason=msg)

    # some value are required to be nonzero, not just positive
    for option in ['memory_mb', 'vcpus']:
        try:
            assert kwargs[option] > 0
        except AssertionError:
            msg = _("create arguments must be positive integers")
            raise exception.InvalidInput(reason=msg)

    kwargs['name'] = name
    # NOTE(vish): Internally, flavorid is stored as a string but it comes
    #             in through json as an integer, so we convert it here.
    kwargs['flavorid'] = unicode(flavorid)

    # ensure is_public attribute is boolean
    kwargs['is_public'] = utils.bool_from_str(is_public)

    try:
        return db.instance_type_create(context.get_admin_context(), kwargs)
    except exception.DBError, e:
        LOG.exception(_('DB error: %s') % e)
        raise exception.InstanceTypeCreateFailed()
Exemplo n.º 34
0
    def setUp(self):
        super(TestQuantumv2, self).setUp()
        self.mox.StubOutWithMock(quantumv2, 'get_client')
        self.moxed_client = self.mox.CreateMock(client.Client)
        quantumv2.get_client(mox.IgnoreArg()).MultipleTimes().AndReturn(
            self.moxed_client)
        self.context = context.RequestContext('userid', 'my_tenantid')
        setattr(self.context, 'auth_token', 'bff4a5a6b9eb4ea2a6efec6eefb77936')
        self.instance = {
            'project_id': '9d049e4b60b64716978ab415e6fbd5c0',
            'uuid': str(utils.gen_uuid()),
            'display_name': 'test_instance'
        }
        self.nets1 = [{
            'id': 'my_netid1',
            'name': 'my_netname1',
            'tenant_id': 'my_tenantid'
        }]
        self.nets2 = []
        self.nets2.append(self.nets1[0])
        self.nets2.append({
            'id': 'my_netid2',
            'name': 'my_netname2',
            'tenant_id': 'my_tenantid'
        })

        self.port_data1 = [{
            'network_id':
            'my_netid1',
            'device_id':
            'device_id1',
            'id':
            'my_portid1',
            'fixed_ips': [{
                'ip_address': '10.0.1.2',
                'subnet_id': 'my_subid1'
            }],
            'mac_address':
            'my_mac1',
        }]
        self.port_data2 = []
        self.port_data2.append(self.port_data1[0])
        self.port_data2.append({
            'network_id':
            'my_netid2',
            'device_id':
            'device_id2',
            'id':
            'my_portid2',
            'fixed_ips': [{
                'ip_address': '10.0.2.2',
                'subnet_id': 'my_subid2'
            }],
            'mac_address':
            'my_mac2',
        })
        self.subnet_data1 = [{
            'cidr': '10.0.1.0/24',
            'gateway_ip': '10.0.1.1',
            'dns_nameservers': ['8.8.1.1', '8.8.1.2']
        }]
        self.subnet_data2 = []
        self.subnet_data2.append({
            'cidr': '10.0.2.0/24',
            'gateway_ip': '10.0.2.1',
            'dns_nameservers': ['8.8.2.1', '8.8.2.2']
        })
Exemplo n.º 35
0
def upgrade(migrate_engine):
    """Build mapping tables for our volume uuid migration.

    These mapping tables serve two purposes:
    1. Provide a method for downgrade after UUID conversion
    2. Provide a uuid to associate with existing volumes and snapshots
       when we do the actual datatype migration from int to uuid

    """
    meta = MetaData()
    meta.bind = migrate_engine

    volume_id_mappings = Table(
        'volume_id_mappings', meta,
        Column('created_at', DateTime(timezone=False)),
        Column('updated_at', DateTime(timezone=False)),
        Column('deleted_at', DateTime(timezone=False)),
        Column('deleted', Boolean(create_constraint=True, name=None)),
        Column('id',
               Integer(),
               primary_key=True,
               nullable=False,
               autoincrement=True), Column('uuid', String(36), nullable=False))
    try:
        volume_id_mappings.create()
    except Exception:
        LOG.exception("Exception while creating table 'volume_id_mappings'")
        meta.drop_all(tables=[volume_id_mappings])
        raise

    snapshot_id_mappings = Table(
        'snapshot_id_mappings', meta,
        Column('created_at', DateTime(timezone=False)),
        Column('updated_at', DateTime(timezone=False)),
        Column('deleted_at', DateTime(timezone=False)),
        Column('deleted', Boolean(create_constraint=True, name=None)),
        Column('id',
               Integer(),
               primary_key=True,
               nullable=False,
               autoincrement=True), Column('uuid', String(36), nullable=False))
    try:
        snapshot_id_mappings.create()
    except Exception:
        LOG.exception("Exception while creating table 'snapshot_id_mappings'")
        meta.drop_all(tables=[snapshot_id_mappings])
        raise

    if migrate_engine.name == "mysql":
        migrate_engine.execute("ALTER TABLE volume_id_mappings Engine=InnoDB")
        migrate_engine.execute("ALTER TABLE snapshot_id_mappings "\
                "Engine=InnoDB")

    volumes = Table('volumes', meta, autoload=True)
    snapshots = Table('snapshots', meta, autoload=True)
    volume_id_mappings = Table('volume_id_mappings', meta, autoload=True)
    snapshot_id_mappings = Table('snapshot_id_mappings', meta, autoload=True)

    volume_list = list(volumes.select().execute())
    for v in volume_list:
        old_id = v['id']
        new_id = utils.gen_uuid()
        row = volume_id_mappings.insert()
        row.execute({'id': old_id, 'uuid': str(new_id)})

    snapshot_list = list(snapshots.select().execute())
    for s in snapshot_list:
        old_id = s['id']
        new_id = utils.gen_uuid()
        row = snapshot_id_mappings.insert()
        row.execute({'id': old_id, 'uuid': str(new_id)})
Exemplo n.º 36
0
 def get_invalid_image(self):
     return str(utils.gen_uuid())
Exemplo n.º 37
0
def generate_request_id():
    return 'req-' + str(utils.gen_uuid())
Exemplo n.º 38
0
 def instance_get_id_to_uuid_mapping(self, context, ids):
     # NOTE(jkoelker): This is just here until we can rely on UUIDs
     mapping = {}
     for id in ids:
         mapping[id] = str(utils.gen_uuid())
     return mapping
Exemplo n.º 39
0
def get_fake_uuid(token=0):
    if not token in FAKE_UUIDS:
        FAKE_UUIDS[token] = str(utils.gen_uuid())
    return FAKE_UUIDS[token]
Exemplo n.º 40
0
 def setUp(self):
     super(AdminActionsTest, self).setUp()
     self.stubs.Set(compute.API, 'get', fake_compute_api_get)
     self.UUID = utils.gen_uuid()
     for _method in self._methods:
         self.stubs.Set(compute.API, _method, fake_compute_api)