Convert fixed_ips to using instance_uuid.

This should be the second last blueprint finish-uuid-conversion change.

Change-Id: Idd47c5ed3c30af24d60eb23b8e3881d61b4c7976
This commit is contained in:
Michael Still
2012-07-04 14:42:08 +10:00
parent e238e07692
commit fc82c6dbbd
19 changed files with 468 additions and 147 deletions
+6 -11
View File
@@ -274,9 +274,9 @@ class FixedIpCommands(object):
sys.exit(2)
instances = db.instance_get_all(context.get_admin_context())
instances_by_id = {}
instances_by_uuid = {}
for instance in instances:
instances_by_id[instance['id']] = instance
instances_by_uuid[instance['uuid']] = instance
print "%-18s\t%-15s\t%-15s\t%s" % (_('network'),
_('IP address'),
@@ -304,8 +304,8 @@ class FixedIpCommands(object):
network = all_networks.get(fixed_ip['network_id'])
if network:
has_ip = True
if fixed_ip.get('instance_id'):
instance = instances_by_id.get(fixed_ip['instance_id'])
if fixed_ip.get('instance_uuid'):
instance = instances_by_uuid.get(fixed_ip['instance_uuid'])
if instance:
hostname = instance['hostname']
host = instance['host']
@@ -414,16 +414,11 @@ class FloatingIpCommands(object):
instance_id = None
if floating_ip['fixed_ip_id']:
fixed_ip = db.fixed_ip_get(ctxt, floating_ip['fixed_ip_id'])
try:
instance = db.instance_get(ctxt, fixed_ip['instance_id'])
instance_id = instance.get('uuid', "none")
except exception.InstanceNotFound:
msg = _('Missing instance %s')
instance_id = msg % fixed_ip['instance_id']
instance_uuid = fixed_ip['instance_uuid']
print "%s\t%s\t%s\t%s\t%s" % (floating_ip['project_id'],
floating_ip['address'],
instance_id,
instance_uuid,
floating_ip['pool'],
floating_ip['interface'])
+1 -1
View File
@@ -214,7 +214,7 @@ def get_metadata_by_address(address):
ctxt = context.get_admin_context()
fixed_ip = network.API().get_fixed_ip_by_address(ctxt, address)
instance = db.instance_get(ctxt, fixed_ip['instance_id'])
instance = db.instance_get_by_uuid(ctxt, fixed_ip['instance_uuid'])
return InstanceMetadata(instance, address)
@@ -120,13 +120,13 @@ class FloatingIPController(object):
fixed_ip_id = floating_ip['fixed_ip_id']
floating_ip['fixed_ip'] = self._get_fixed_ip(context,
fixed_ip_id)
instance_id = None
instance_uuid = None
if floating_ip['fixed_ip']:
instance_id = floating_ip['fixed_ip']['instance_id']
instance_uuid = floating_ip['fixed_ip']['instance_uuid']
if instance_id:
if instance_uuid:
floating_ip['instance'] = self._get_instance(context,
instance_id)
instance_uuid)
else:
floating_ip['instance'] = None
+9 -8
View File
@@ -418,25 +418,26 @@ def migration_get_all_unconfirmed(context, confirm_window):
####################
def fixed_ip_associate(context, address, instance_id, network_id=None,
def fixed_ip_associate(context, address, instance_uuid, network_id=None,
reserved=False):
"""Associate fixed ip to instance.
Raises if fixed ip is not available.
"""
return IMPL.fixed_ip_associate(context, address, instance_id, network_id,
return IMPL.fixed_ip_associate(context, address, instance_uuid, network_id,
reserved)
def fixed_ip_associate_pool(context, network_id, instance_id=None, host=None):
def fixed_ip_associate_pool(context, network_id, instance_uuid=None,
host=None):
"""Find free ip in network and associate it to instance or host.
Raises if one is not available.
"""
return IMPL.fixed_ip_associate_pool(context, network_id,
instance_id, host)
instance_uuid, host)
def fixed_ip_create(context, values):
@@ -474,14 +475,14 @@ def fixed_ip_get_by_address(context, address):
return IMPL.fixed_ip_get_by_address(context, address)
def fixed_ip_get_by_instance(context, instance_id):
def fixed_ip_get_by_instance(context, instance_uuid):
"""Get fixed ips by instance or raise if none exist."""
return IMPL.fixed_ip_get_by_instance(context, instance_id)
return IMPL.fixed_ip_get_by_instance(context, instance_uuid)
def fixed_ip_get_by_network_host(context, network_id, host):
def fixed_ip_get_by_network_host(context, network_uuid, host):
"""Get fixed ip for a host in a network."""
return IMPL.fixed_ip_get_by_network_host(context, network_id, host)
return IMPL.fixed_ip_get_by_network_host(context, network_uuid, host)
def fixed_ips_by_virtual_interface(context, vif_id):
+38 -22
View File
@@ -993,12 +993,15 @@ def dnsdomain_list(context):
@require_admin_context
def fixed_ip_associate(context, address, instance_id, network_id=None,
def fixed_ip_associate(context, address, instance_uuid, network_id=None,
reserved=False):
"""Keyword arguments:
reserved -- should be a boolean value(True or False), exact value will be
used to filter on the fixed ip address
"""
if not utils.is_uuid_like(instance_uuid):
raise exception.InvalidUUID(uuid=instance_uuid)
session = get_session()
with session.begin():
network_or_none = or_(models.FixedIp.network_id == network_id,
@@ -1015,18 +1018,22 @@ def fixed_ip_associate(context, address, instance_id, network_id=None,
if fixed_ip_ref is None:
raise exception.FixedIpNotFoundForNetwork(address=address,
network_id=network_id)
if fixed_ip_ref.instance_id:
if fixed_ip_ref.instance_uuid:
raise exception.FixedIpAlreadyInUse(address=address)
if not fixed_ip_ref.network_id:
fixed_ip_ref.network_id = network_id
fixed_ip_ref.instance_id = instance_id
fixed_ip_ref.instance_uuid = instance_uuid
session.add(fixed_ip_ref)
return fixed_ip_ref['address']
@require_admin_context
def fixed_ip_associate_pool(context, network_id, instance_id=None, host=None):
def fixed_ip_associate_pool(context, network_id, instance_uuid=None,
host=None):
if not utils.is_uuid_like(instance_uuid):
raise exception.InvalidUUID(uuid=instance_uuid)
session = get_session()
with session.begin():
network_or_none = or_(models.FixedIp.network_id == network_id,
@@ -1035,7 +1042,7 @@ def fixed_ip_associate_pool(context, network_id, instance_id=None, host=None):
read_deleted="no").\
filter(network_or_none).\
filter_by(reserved=False).\
filter_by(instance_id=None).\
filter_by(instance_uuid=None).\
filter_by(host=None).\
with_lockmode('update').\
first()
@@ -1047,8 +1054,8 @@ def fixed_ip_associate_pool(context, network_id, instance_id=None, host=None):
if fixed_ip_ref['network_id'] is None:
fixed_ip_ref['network'] = network_id
if instance_id:
fixed_ip_ref['instance_id'] = instance_id
if instance_uuid:
fixed_ip_ref['instance_uuid'] = instance_uuid
if host:
fixed_ip_ref['host'] = host
@@ -1081,7 +1088,7 @@ def fixed_ip_disassociate(context, address):
fixed_ip_ref = fixed_ip_get_by_address(context,
address,
session=session)
fixed_ip_ref['instance_id'] = None
fixed_ip_ref['instance_uuid'] = None
fixed_ip_ref.save(session=session)
@@ -1102,7 +1109,8 @@ def fixed_ip_disassociate_all_by_timeout(context, host, time):
join((models.Network,
models.Network.id == models.FixedIp.network_id)).\
join((models.Instance,
models.Instance.id == models.FixedIp.instance_id)).\
models.Instance.uuid == \
models.FixedIp.instance_uuid)).\
filter(host_filter).\
all()
fixed_ip_ids = [fip[0] for fip in result]
@@ -1110,7 +1118,7 @@ def fixed_ip_disassociate_all_by_timeout(context, host, time):
return 0
result = model_query(context, models.FixedIp, session=session).\
filter(models.FixedIp.id.in_(fixed_ip_ids)).\
update({'instance_id': None,
update({'instance_uuid': None,
'leased': False,
'updated_at': timeutils.utcnow()},
synchronize_session='fetch')
@@ -1127,8 +1135,9 @@ def fixed_ip_get(context, id, session=None):
# FIXME(sirp): shouldn't we just use project_only here to restrict the
# results?
if is_user_context(context) and result['instance_id'] is not None:
instance = instance_get(context, result['instance_id'], session)
if is_user_context(context) and result['instance_uuid'] is not None:
instance = instance_get_by_uuid(context, result['instance_uuid'],
session)
authorize_project_context(context, instance.project_id)
return result
@@ -1155,21 +1164,25 @@ def fixed_ip_get_by_address(context, address, session=None):
# NOTE(sirp): shouldn't we just use project_only here to restrict the
# results?
if is_user_context(context) and result['instance_id'] is not None:
instance = instance_get(context, result['instance_id'], session)
if is_user_context(context) and result['instance_uuid'] is not None:
instance = instance_get_by_uuid(context, result['instance_uuid'],
session)
authorize_project_context(context, instance.project_id)
return result
@require_context
def fixed_ip_get_by_instance(context, instance_id):
def fixed_ip_get_by_instance(context, instance_uuid):
if not utils.is_uuid_like(instance_uuid):
raise exception.InvalidUUID(uuid=instance_uuid)
result = model_query(context, models.FixedIp, read_deleted="no").\
filter_by(instance_id=instance_id).\
filter_by(instance_uuid=instance_uuid).\
all()
if not result:
raise exception.FixedIpNotFoundForInstance(instance_id=instance_id)
raise exception.FixedIpNotFoundForInstance(instance_uuid=instance_uuid)
return result
@@ -1671,9 +1684,12 @@ def instance_get_all_by_reservation(context, reservation_id):
# go away
@require_context
def instance_get_floating_address(context, instance_id):
fixed_ips = fixed_ip_get_by_instance(context, instance_id)
instance = instance_get(context, instance_id)
fixed_ips = fixed_ip_get_by_instance(context, instance['uuid'])
if not fixed_ips:
return None
# NOTE(tr3buchet): this only gets the first fixed_ip
# won't find floating ips associated with other fixed_ips
floating_ips = floating_ip_get_by_fixed_address(context,
@@ -2136,11 +2152,11 @@ def network_get_associated_fixed_ips(context, network_id, host=None):
vif_and = and_(models.VirtualInterface.id ==
models.FixedIp.virtual_interface_id,
models.VirtualInterface.deleted == False)
inst_and = and_(models.Instance.id == models.FixedIp.instance_id,
inst_and = and_(models.Instance.uuid == models.FixedIp.instance_uuid,
models.Instance.deleted == False)
session = get_session()
query = session.query(models.FixedIp.address,
models.FixedIp.instance_id,
models.FixedIp.instance_uuid,
models.FixedIp.network_id,
models.FixedIp.virtual_interface_id,
models.VirtualInterface.address,
@@ -2152,7 +2168,7 @@ def network_get_associated_fixed_ips(context, network_id, host=None):
filter(models.FixedIp.allocated == True).\
join((models.VirtualInterface, vif_and)).\
join((models.Instance, inst_and)).\
filter(models.FixedIp.instance_id != None).\
filter(models.FixedIp.instance_uuid != None).\
filter(models.FixedIp.virtual_interface_id != None)
if host:
query = query.filter(models.Instance.host == host)
@@ -2161,7 +2177,7 @@ def network_get_associated_fixed_ips(context, network_id, host=None):
for datum in result:
cleaned = {}
cleaned['address'] = datum[0]
cleaned['instance_id'] = datum[1]
cleaned['instance_uuid'] = datum[1]
cleaned['network_id'] = datum[2]
cleaned['vif_id'] = datum[3]
cleaned['vif_address'] = datum[4]
@@ -64,5 +64,5 @@ def downgrade(migrate_engine):
columns=[t.c.instance_uuid],
refcolumns=[instances.c.uuid]).drop()
except Exception:
LOG.error(_("foreign key constraint couldn't be created"))
LOG.error(_("foreign key constraint couldn't be dropped"))
raise
@@ -0,0 +1,108 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# Copyright 2012 Michael Still and Canonical Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from migrate import ForeignKeyConstraint
from sqlalchemy import MetaData, String, Table
from sqlalchemy import select, Column, ForeignKey, Integer
from nova.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
fixed_ips = Table('fixed_ips', meta, autoload=True)
instances = Table('instances', meta, autoload=True)
uuid_column = Column('instance_uuid', String(36))
uuid_column.create(fixed_ips)
try:
fixed_ips.update().values(
instance_uuid=select(
[instances.c.uuid],
instances.c.id == fixed_ips.c.instance_id)
).execute()
except Exception:
uuid_column.drop()
raise
fkeys = list(fixed_ips.c.instance_id.foreign_keys)
if fkeys:
try:
fkey_name = fkeys[0].constraint.name
ForeignKeyConstraint(
columns=[fixed_ips.c.instance_id],
refcolumns=[instances.c.id],
name=fkey_name).drop()
except Exception:
LOG.error(_("foreign key constraint couldn't be removed"))
raise
fixed_ips.c.instance_id.drop()
try:
ForeignKeyConstraint(
columns=[fixed_ips.c.instance_uuid],
refcolumns=[instances.c.uuid]).create()
except Exception:
LOG.error(_("foreign key constraint couldn't be created"))
raise
def downgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
fixed_ips = Table('fixed_ips', meta, autoload=True)
instances = Table('instances', meta, autoload=True)
id_column = Column('instance_id', Integer, ForeignKey('instances.id'))
id_column.create(fixed_ips)
fkeys = list(fixed_ips.c.instance_uuid.foreign_keys)
if fkeys:
try:
fkey_name = fkeys[0].constraint.name
ForeignKeyConstraint(
columns=[fixed_ips.c.instance_uuid],
refcolumns=[instances.c.uuid],
name=fkey_name).drop()
except Exception:
LOG.error(_("foreign key constraint couldn't be removed"))
raise
try:
fixed_ips.update().values(
instance_id=select(
[instances.c.id],
instances.c.uuid == fixed_ips.c.instance_uuid)
).execute()
except Exception:
id_column.drop()
raise
fixed_ips.c.instance_uuid.drop()
try:
ForeignKeyConstraint(
columns=[fixed_ips.c.instance_id],
refcolumns=[instances.c.id]).create()
except Exception:
LOG.error(_("foreign key constraint couldn't be created"))
raise
@@ -0,0 +1,85 @@
BEGIN TRANSACTION;
CREATE TEMPORARY TABLE fixed_ips_backup (
created_at DATETIME,
updated_at DATETIME,
deleted_at DATETIME,
deleted BOOLEAN,
id INTEGER NOT NULL,
address VARCHAR(255),
network_id INTEGER,
instance_id INTEGER NOT NULL,
instance_uuid VARCHAR(36),
allocated BOOLEAN,
leased BOOLEAN,
reserved BOOLEAN,
virtual_interface_id INTEGER,
host VARCHAR(255),
PRIMARY KEY (id)
);
INSERT INTO fixed_ips_backup
SELECT created_at,
updated_at,
deleted_at,
deleted,
id,
address,
network_id,
NULL,
instance_uuid,
allocated,
leased,
reserved,
virtual_interface_id,
host
FROM fixed_ips;
UPDATE fixed_ips_backup
SET instance_id=
(SELECT id
FROM instances
WHERE fixed_ips_backup.instance_uuid = instances.uuid
);
DROP TABLE fixed_ips;
CREATE TABLE fixed_ips (
created_at DATETIME,
updated_at DATETIME,
deleted_at DATETIME,
deleted BOOLEAN,
id INTEGER NOT NULL,
address VARCHAR(255),
network_id INTEGER,
instance_id INTEGER,
allocated BOOLEAN,
leased BOOLEAN,
reserved BOOLEAN,
virtual_interface_id INTEGER,
host VARCHAR(255),
PRIMARY KEY (id),
FOREIGN KEY(instance_id) REFERENCES instances (id)
);
CREATE INDEX fixed_ips_id ON fixed_ips(id);
CREATE INDEX address ON fixed_ips(address);
INSERT INTO fixed_ips
SELECT created_at,
updated_at,
deleted_at,
deleted,
id,
address,
network_id,
instance_id,
allocated,
leased,
reserved,
virtual_interface_id,
host
FROM fixed_ips_backup;
DROP TABLE fixed_ips_backup;
COMMIT;
@@ -0,0 +1,85 @@
BEGIN TRANSACTION;
CREATE TEMPORARY TABLE fixed_ips_backup (
created_at DATETIME,
updated_at DATETIME,
deleted_at DATETIME,
deleted BOOLEAN,
id INTEGER NOT NULL,
address VARCHAR(255),
network_id INTEGER,
instance_id INTEGER NOT NULL,
instance_uuid VARCHAR(36),
allocated BOOLEAN,
leased BOOLEAN,
reserved BOOLEAN,
virtual_interface_id INTEGER,
host VARCHAR(255),
PRIMARY KEY (id)
);
INSERT INTO fixed_ips_backup
SELECT created_at,
updated_at,
deleted_at,
deleted,
id,
address,
network_id,
instance_id,
NULL,
allocated,
leased,
reserved,
virtual_interface_id,
host
FROM fixed_ips;
UPDATE fixed_ips_backup
SET instance_uuid=
(SELECT uuid
FROM instances
WHERE fixed_ips_backup.instance_id = instances.id
);
DROP TABLE fixed_ips;
CREATE TABLE fixed_ips (
created_at DATETIME,
updated_at DATETIME,
deleted_at DATETIME,
deleted BOOLEAN,
id INTEGER NOT NULL,
address VARCHAR(255),
network_id INTEGER,
instance_uuid VARCHAR(36),
allocated BOOLEAN,
leased BOOLEAN,
reserved BOOLEAN,
virtual_interface_id INTEGER,
host VARCHAR(255),
PRIMARY KEY (id),
FOREIGN KEY(instance_uuid) REFERENCES instances (uuid)
);
CREATE INDEX fixed_ips_id ON fixed_ips(id);
CREATE INDEX address ON fixed_ips(address);
INSERT INTO fixed_ips
SELECT created_at,
updated_at,
deleted_at,
deleted,
id,
address,
network_id,
instance_uuid,
allocated,
leased,
reserved,
virtual_interface_id,
host
FROM fixed_ips_backup;
DROP TABLE fixed_ips_backup;
COMMIT;
+1 -1
View File
@@ -717,7 +717,7 @@ class FixedIp(BASE, NovaBase):
address = Column(String(255))
network_id = Column(Integer, nullable=True)
virtual_interface_id = Column(Integer, nullable=True)
instance_id = Column(Integer, nullable=True)
instance_uuid = Column(String(36), nullable=True)
# associated means that a fixed_ip has its instance_id column set
# allocated means that a fixed_ip has its virtual_interface_id column set
allocated = Column(Boolean, default=False)
+5 -4
View File
@@ -423,7 +423,7 @@ class InvalidEc2Id(Invalid):
class InvalidUUID(Invalid):
message = _("Expected a uuid but received %(uuid).")
message = _("Expected a uuid but received %(uuid)s.")
class ConstraintNotMet(NovaException):
@@ -596,7 +596,7 @@ class FixedIpNotFoundForAddress(FixedIpNotFound):
class FixedIpNotFoundForInstance(FixedIpNotFound):
message = _("Instance %(instance_id)s has zero fixed ips.")
message = _("Instance %(instance_uuid)s has zero fixed ips.")
class FixedIpNotFoundForNetworkHost(FixedIpNotFound):
@@ -605,7 +605,7 @@ class FixedIpNotFoundForNetworkHost(FixedIpNotFound):
class FixedIpNotFoundForSpecificInstance(FixedIpNotFound):
message = _("Instance %(instance_id)s doesn't have fixed ip '%(ip)s'.")
message = _("Instance %(instance_uuid)s doesn't have fixed ip '%(ip)s'.")
class FixedIpNotFoundForHost(FixedIpNotFound):
@@ -618,7 +618,8 @@ class FixedIpNotFoundForNetwork(FixedIpNotFound):
class FixedIpAlreadyInUse(NovaException):
message = _("Fixed IP address %(address)s is already in use.")
message = _("Fixed IP address %(address)s is already in use on instance "
"%(instance_uuid)s.")
class FixedIpInvalid(Invalid):
+61 -34
View File
@@ -353,12 +353,14 @@ class FloatingIP(object):
# deleted before the IPs are released, so we need to get deleted
# instances too
read_deleted_context = context.elevated(read_deleted='yes')
LOG.debug(_("floating IP deallocation for instance |%s|"), instance_id,
context=read_deleted_context)
instance = self.db.instance_get(read_deleted_context, instance_id)
LOG.debug(_("floating IP deallocation for instance |%s|"),
instance=instance, context=read_deleted_context)
try:
fixed_ips = self.db.fixed_ip_get_by_instance(read_deleted_context,
instance_id)
instance['uuid'])
except exception.FixedIpNotFoundForInstance:
fixed_ips = []
# add to kwargs so we can pass to super to save a db lookup there
@@ -503,7 +505,8 @@ class FloatingIP(object):
network = self._get_network_by_id(context.elevated(),
fixed_ip['network_id'])
if network['multi_host']:
instance = self.db.instance_get(context, fixed_ip['instance_id'])
instance = self.db.instance_get_by_uuid(context,
fixed_ip['instance_uuid'])
host = instance['host']
else:
host = network['host']
@@ -574,7 +577,8 @@ class FloatingIP(object):
# send to correct host, unless i'm the correct host
network = self._get_network_by_id(context, fixed_ip['network_id'])
if network['multi_host']:
instance = self.db.instance_get(context, fixed_ip['instance_id'])
instance = self.db.instance_get_by_uuid(context,
fixed_ip['instance_uuid'])
host = instance['host']
else:
host = network['host']
@@ -846,9 +850,15 @@ class NetworkManager(manager.SchedulerDependentManager):
# NOTE(francois.charlier): the instance may have been deleted already
# thus enabling `read_deleted`
admin_context = context.get_admin_context(read_deleted='yes')
instance_ref = self.db.instance_get(admin_context, instance_id)
group_ids = [group['id'] for group
in instance_ref['security_groups']]
if utils.is_uuid_like(instance_id):
instance_ref = self.db.instance_get_by_uuid(admin_context,
instance_id)
else:
instance_ref = self.db.instance_get(admin_context, instance_id)
groups = instance_ref['security_groups']
group_ids = [group['id'] for group in groups]
self.security_group_api.trigger_members_refresh(admin_context,
group_ids)
self.security_group_api.trigger_handler('security_group_members',
@@ -977,14 +987,16 @@ class NetworkManager(manager.SchedulerDependentManager):
read_deleted_context = context.elevated(read_deleted='yes')
instance_id = kwargs.pop('instance_id')
instance = self.db.instance_get(read_deleted_context, instance_id)
try:
fixed_ips = (kwargs.get('fixed_ips') or
self.db.fixed_ip_get_by_instance(read_deleted_context,
instance_id))
instance['uuid']))
except exception.FixedIpNotFoundForInstance:
fixed_ips = []
LOG.debug(_("network deallocation for instance |%s|"), instance_id,
context=read_deleted_context)
LOG.debug(_("network deallocation for instance"), instance=instance,
context=read_deleted_context)
# deallocate fixed ips
for fixed_ip in fixed_ips:
self.deallocate_fixed_ip(context, fixed_ip['address'], **kwargs)
@@ -1034,7 +1046,7 @@ class NetworkManager(manager.SchedulerDependentManager):
# get network dict for vif from args and build the subnets
network = networks[vif['uuid']]
subnets = self._get_subnets_from_network(context, network, vif,
instance_host)
instance_host)
# if rxtx_cap data are not set everywhere, set to none
try:
@@ -1048,9 +1060,9 @@ class NetworkManager(manager.SchedulerDependentManager):
vif['uuid'],
network['project_id'])
v6_IPs = self.ipam.get_v6_ips_by_interface(context,
network['uuid'],
vif['uuid'],
network['project_id'])
network['uuid'],
vif['uuid'],
network['project_id'])
# create model FixedIPs from these fixed_ips
network_IPs = [network_model.FixedIP(address=ip_address)
@@ -1195,11 +1207,11 @@ class NetworkManager(manager.SchedulerDependentManager):
raise exception.FixedIpNotFoundForSpecificInstance(
instance_id=instance_id, ip=address)
def _validate_instance_zone_for_dns_domain(self, context, instance_id):
instance = self.db.instance_get(context, instance_id)
def _validate_instance_zone_for_dns_domain(self, context, instance):
instance_zone = instance.get('availability_zone')
if not self.instance_dns_domain:
return True
instance_domain = self.instance_dns_domain
domainref = self.db.dnsdomain_get(context, instance_zone)
dns_zone = domainref.availability_zone
@@ -1223,16 +1235,19 @@ class NetworkManager(manager.SchedulerDependentManager):
# and use that network here with a method like
# network_get_by_compute_host
address = None
instance_ref = self.db.instance_get(context, instance_id)
if network['cidr']:
address = kwargs.get('address', None)
if address:
address = self.db.fixed_ip_associate(context,
address, instance_id,
address,
instance_ref['uuid'],
network['id'])
else:
address = self.db.fixed_ip_associate_pool(context.elevated(),
network['id'],
instance_id)
instance_ref['uuid'])
self._do_trigger_security_group_members_refresh_for_instance(
instance_id)
get_vif = self.db.virtual_interface_get_by_instance_and_network
@@ -1241,10 +1256,9 @@ class NetworkManager(manager.SchedulerDependentManager):
'virtual_interface_id': vif['id']}
self.db.fixed_ip_update(context, address, values)
instance_ref = self.db.instance_get(context, instance_id)
name = instance_ref['display_name']
if self._validate_instance_zone_for_dns_domain(context, instance_id):
if self._validate_instance_zone_for_dns_domain(context, instance_ref):
uuid = instance_ref['uuid']
self.instance_dns_manager.create_entry(name, address,
"A",
@@ -1262,11 +1276,13 @@ class NetworkManager(manager.SchedulerDependentManager):
self.db.fixed_ip_update(context, address,
{'allocated': False,
'virtual_interface_id': None})
instance_id = fixed_ip_ref['instance_id']
self._do_trigger_security_group_members_refresh_for_instance(
instance_id)
instance = self.db.instance_get_by_uuid(context,
fixed_ip_ref['instance_uuid'])
if self._validate_instance_zone_for_dns_domain(context, instance_id):
self._do_trigger_security_group_members_refresh_for_instance(
instance['uuid'])
if self._validate_instance_zone_for_dns_domain(context, instance):
for n in self.instance_dns_manager.get_entries_by_address(address,
self.instance_dns_domain):
self.instance_dns_manager.delete_entry(n,
@@ -1301,7 +1317,7 @@ class NetworkManager(manager.SchedulerDependentManager):
LOG.debug(_('Leased IP |%(address)s|'), locals(), context=context)
fixed_ip = self.db.fixed_ip_get_by_address(context, address)
if fixed_ip['instance_id'] is None:
if fixed_ip['instance_uuid'] is None:
msg = _('IP %s leased that is not associated') % address
raise exception.NovaException(msg)
now = timeutils.utcnow()
@@ -1318,7 +1334,7 @@ class NetworkManager(manager.SchedulerDependentManager):
LOG.debug(_('Released IP |%(address)s|'), locals(), context=context)
fixed_ip = self.db.fixed_ip_get_by_address(context, address)
if fixed_ip['instance_id'] is None:
if fixed_ip['instance_uuid'] is None:
msg = _('IP %s released that is not associated') % address
raise exception.NovaException(msg)
if not fixed_ip['leased']:
@@ -1596,10 +1612,12 @@ class NetworkManager(manager.SchedulerDependentManager):
network = self._get_network_by_id(context,
fixed_ip_ref['network_id'])
if network['uuid'] != network_uuid:
raise exception.FixedIpNotFoundForNetwork(address=address,
network_uuid=network_uuid)
if fixed_ip_ref['instance_id'] is not None:
raise exception.FixedIpAlreadyInUse(address=address)
raise exception.FixedIpNotFoundForNetwork(
address=address, network_uuid=network_uuid)
if fixed_ip_ref['instance_uuid'] is not None:
raise exception.FixedIpAlreadyInUse(
address=address,
instance_uuid=fixed_ip_ref['instance_uuid'])
def _get_network_by_id(self, context, network_id):
return self.db.network_get(context, network_id)
@@ -1622,7 +1640,14 @@ class NetworkManager(manager.SchedulerDependentManager):
fixed_ip = self.db.fixed_ip_get(context, floating_ip['fixed_ip_id'])
# NOTE(tr3buchet): this can be None
return fixed_ip['instance_id']
# NOTE(mikal): we need to return the instance id here because its used
# by ec2 (and possibly others)
uuid = fixed_ip['instance_uuid']
if not uuid:
return uuid
instance = self.db.instance_get_by_uuid(context, uuid)
return instance['id']
@wrap_check_policy
def get_network(self, context, network_uuid):
@@ -1852,15 +1877,17 @@ class VlanManager(RPCAllocateFixedIP, FloatingIP, NetworkManager):
network['id'],
reserved=True)
else:
instance = self.db.instance_get(context, instance_id)
address = kwargs.get('address', None)
if address:
address = self.db.fixed_ip_associate(context, address,
instance_id,
instance['uuid'],
network['id'])
else:
address = self.db.fixed_ip_associate_pool(context,
network['id'],
instance_id)
instance['uuid'])
self._do_trigger_security_group_members_refresh_for_instance(
instance_id)
vif = self.db.virtual_interface_get_by_instance_and_network(context,
+1 -1
View File
@@ -539,7 +539,7 @@ class QuantumManager(manager.FloatingIP, manager.FlatManager):
return self.db.virtual_interface_create(context, vif)
def get_instance_nw_info(self, context, instance_id, instance_uuid,
rxtx_factor, host, **kwargs):
rxtx_factor, host, **kwargs):
"""This method is used by compute to fetch all network data
that should be used when creating the VM.
+2 -1
View File
@@ -127,9 +127,10 @@ class QuantumNovaIPAMLib(object):
network = db.network_get_by_uuid(admin_context, quantum_net_id)
address = None
if network['cidr']:
instance = db.instance_get(context, vif_rec['instance_id'])
address = db.fixed_ip_associate_pool(admin_context,
network['id'],
vif_rec['instance_id'])
instance['uuid'])
values = {'allocated': True,
'virtual_interface_id': vif_rec['id']}
db.fixed_ip_update(admin_context, address, values)
@@ -36,7 +36,7 @@ FAKE_UUID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
def network_api_get_fixed_ip(self, context, id):
if id is None:
return None
return {'address': '10.0.0.1', 'id': id, 'instance_id': 1}
return {'address': '10.0.0.1', 'id': id, 'instance_uuid': 1}
def network_api_get_floating_ip(self, context, id):
@@ -214,7 +214,7 @@ class FloatingIpTest(test.TestCase):
'fixed_ip_id': 11}
def get_fixed_ip(self, context, id):
return {'address': '10.0.0.1', 'instance_id': 1}
return {'address': '10.0.0.1', 'instance_uuid': 1}
self.stubs.Set(network.api.API, "get_floating_ip", get_floating_ip)
self.stubs.Set(network.api.API, "get_fixed_ip", get_fixed_ip)
+1 -1
View File
@@ -1647,7 +1647,7 @@ class ComputeTestCase(BaseTestCase):
'power_state': power_state.PAUSED})
v_ref = db.volume_create(c, {'size': 1, 'instance_id': inst_id})
fix_addr = db.fixed_ip_create(c, {'address': '1.1.1.1',
'instance_id': inst_id})
'instance_uuid': inst_ref['uuid']})
fix_ref = db.fixed_ip_get_by_address(c, fix_addr)
db.floating_ip_create(c, {'address': flo_addr,
'fixed_ip_id': fix_ref['id']})
+42 -40
View File
@@ -38,10 +38,11 @@ LOG = logging.getLogger(__name__)
HOST = "testhost"
FAKEUUID = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
networks = [{'id': 0,
'uuid': "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
'uuid': FAKEUUID,
'label': 'test0',
'injected': False,
'multi_host': False,
@@ -84,14 +85,14 @@ networks = [{'id': 0,
fixed_ips = [{'id': 0,
'network_id': 0,
'address': '192.168.0.100',
'instance_id': 0,
'instance_uuid': 0,
'allocated': False,
'virtual_interface_id': 0,
'floating_ips': []},
{'id': 0,
'network_id': 1,
'address': '192.168.1.100',
'instance_id': 0,
'instance_uuid': 0,
'allocated': False,
'virtual_interface_id': 0,
'floating_ips': []}]
@@ -197,19 +198,19 @@ class FlatNetworkTestCase(test.TestCase):
def test_validate_networks(self):
self.mox.StubOutWithMock(db, 'network_get')
self.mox.StubOutWithMock(db, 'network_get_all_by_uuids')
self.mox.StubOutWithMock(db, "fixed_ip_get_by_address")
self.mox.StubOutWithMock(db, 'fixed_ip_get_by_address')
requested_networks = [("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
"192.168.1.100")]
requested_networks = [('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
'192.168.1.100')]
db.network_get_all_by_uuids(mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn(networks)
mox.IgnoreArg()).AndReturn(networks)
db.network_get(mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn(networks[1])
ip = fixed_ips[1].copy()
ip['instance_id'] = None
ip['instance_uuid'] = None
db.fixed_ip_get_by_address(mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn(ip)
mox.IgnoreArg()).AndReturn(ip)
self.mox.ReplayAll()
self.network.validate_networks(self.context, requested_networks)
@@ -282,14 +283,12 @@ class FlatNetworkTestCase(test.TestCase):
db.virtual_interface_get_by_instance_and_network(mox.IgnoreArg(),
mox.IgnoreArg(), mox.IgnoreArg()).AndReturn({'id': 0})
db.instance_get(mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn({'security_groups':
[{'id': 0}]})
db.instance_get(self.context,
1).AndReturn({'display_name': HOST,
'uuid': 'test-00001'})
db.instance_get(mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn({'availability_zone': ''})
mox.IgnoreArg()).AndReturn({'security_groups':
[{'id': 0}]})
db.fixed_ip_associate_pool(mox.IgnoreArg(),
mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn('192.168.0.101')
@@ -315,14 +314,12 @@ class FlatNetworkTestCase(test.TestCase):
db.virtual_interface_get_by_instance_and_network(mox.IgnoreArg(),
mox.IgnoreArg(), mox.IgnoreArg()).AndReturn({'id': 0})
db.instance_get(mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn({'security_groups':
[{'id': 0}]})
db.instance_get(self.context,
1).AndReturn({'display_name': HOST,
'uuid': 'test-00001'})
db.instance_get(mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn({'availability_zone': ''})
mox.IgnoreArg()).AndReturn({'security_groups':
[{'id': 0}]})
db.fixed_ip_associate_pool(mox.IgnoreArg(),
mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn('192.168.0.101')
@@ -372,6 +369,7 @@ class FlatNetworkTestCase(test.TestCase):
self.mox.StubOutWithMock(db, 'network_update')
self.mox.StubOutWithMock(db, 'fixed_ip_associate_pool')
self.mox.StubOutWithMock(db, 'instance_get')
self.mox.StubOutWithMock(db, 'instance_get_by_uuid')
self.mox.StubOutWithMock(db,
'virtual_interface_get_by_instance_and_network')
self.mox.StubOutWithMock(db, 'fixed_ip_update')
@@ -382,15 +380,13 @@ class FlatNetworkTestCase(test.TestCase):
db.virtual_interface_get_by_instance_and_network(mox.IgnoreArg(),
mox.IgnoreArg(), mox.IgnoreArg()).AndReturn({'id': 0})
db.instance_get(mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn({'security_groups':
[{'id': 0}]})
db.instance_get(self.context,
1).AndReturn({'display_name': HOST,
'uuid': 'test-00001'})
db.instance_get(mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn({'availability_zone': ''})
mox.IgnoreArg()).AndReturn({'security_groups':
[{'id': 0}]})
db.fixed_ip_associate_pool(mox.IgnoreArg(),
mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn(fixedip)
@@ -446,12 +442,13 @@ class VlanNetworkTestCase(test.TestCase):
network = dict(networks[0])
network['vpn_private_address'] = '192.168.0.2'
network['id'] = None
instance = db.instance_create(self.context, {})
context_admin = context.RequestContext('testuser', 'testproject',
is_admin=True)
self.assertRaises(exception.FixedIpNotFoundForNetwork,
self.network.allocate_fixed_ip,
context_admin,
0,
instance['uuid'],
network,
vpn=True)
@@ -462,6 +459,8 @@ class VlanNetworkTestCase(test.TestCase):
'virtual_interface_get_by_instance_and_network')
self.mox.StubOutWithMock(db, 'instance_get')
db.instance_get(mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn({'uuid': FAKEUUID})
db.instance_get(mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn({'security_groups':
[{'id': 0}]})
@@ -503,7 +502,7 @@ class VlanNetworkTestCase(test.TestCase):
mox.IgnoreArg()).AndReturn(networks)
fixed_ips[1]['network_id'] = networks[1]['id']
fixed_ips[1]['instance_id'] = None
fixed_ips[1]['instance_uuid'] = None
db.fixed_ip_get_by_address(mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn(fixed_ips[1])
@@ -841,6 +840,8 @@ class VlanNetworkTestCase(test.TestCase):
'virtual_interface_get_by_instance_and_network')
self.mox.StubOutWithMock(db, 'fixed_ip_update')
db.instance_get(mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn({'uuid': FAKEUUID})
db.fixed_ip_update(mox.IgnoreArg(),
mox.IgnoreArg(),
mox.IgnoreArg())
@@ -850,7 +851,8 @@ class VlanNetworkTestCase(test.TestCase):
db.instance_get(mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn({'security_groups':
[{'id': 0}],
'availability_zone': ''})
'availability_zone': '',
'uuid': FAKEUUID})
db.fixed_ip_associate_pool(mox.IgnoreArg(),
mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn('192.168.0.101')
@@ -874,14 +876,14 @@ class VlanNetworkTestCase(test.TestCase):
address = '1.2.3.4'
float_addr = db.floating_ip_create(context1.elevated(),
{'address': address,
'project_id': context1.project_id})
{'address': address,
'project_id': context1.project_id})
instance = db.instance_create(context1,
{'project_id': 'project1'})
{'project_id': 'project1'})
fix_addr = db.fixed_ip_associate_pool(context1.elevated(),
1, instance['id'])
1, instance['uuid'])
# Associate the IP with non-admin user context
self.assertRaises(exception.NotAuthorized,
@@ -932,7 +934,7 @@ class VlanNetworkTestCase(test.TestCase):
{'project_id': 'project1'})
elevated = context1.elevated()
fix_addr = db.fixed_ip_associate_pool(elevated, 1, instance['id'])
fix_addr = db.fixed_ip_associate_pool(elevated, 1, instance['uuid'])
values = {'allocated': True,
'virtual_interface_id': 3}
db.fixed_ip_update(elevated, fix_addr, values)
@@ -967,13 +969,13 @@ class VlanNetworkTestCase(test.TestCase):
{'project_id': 'project1'})
elevated = context1.elevated()
fix_addr = db.fixed_ip_associate_pool(elevated, 1, instance['id'])
fix_addr = db.fixed_ip_associate_pool(elevated, 1, instance['uuid'])
db.fixed_ip_update(elevated, fix_addr, {'deleted': 1})
elevated.read_deleted = 'yes'
delfixed = db.fixed_ip_get_by_address(elevated, fix_addr)
values = {'address': fix_addr,
'network_id': 0,
'instance_id': delfixed['instance_id']}
'instance_uuid': delfixed['instance_uuid']}
db.fixed_ip_create(elevated, values)
elevated.read_deleted = 'no'
newfixed = db.fixed_ip_get_by_address(elevated, fix_addr)
@@ -1000,10 +1002,10 @@ class VlanNetworkTestCase(test.TestCase):
context1 = context.RequestContext('user', 'project1')
instance = db.instance_create(context1,
{'project_id': 'project1'})
{'project_id': 'project1'})
elevated = context1.elevated()
fix_addr = db.fixed_ip_associate_pool(elevated, 1, instance['id'])
fix_addr = db.fixed_ip_associate_pool(elevated, 1, instance['uuid'])
values = {'allocated': True,
'virtual_interface_id': 3}
db.fixed_ip_update(elevated, fix_addr, values)
@@ -1458,12 +1460,12 @@ class AllocateTestCase(test.TestCase):
{'host': self.network.host})
project_id = self.context.project_id
nw_info = self.network.allocate_for_instance(self.context,
instance_id=inst['id'],
instance_uuid='',
host=inst['host'],
vpn=None,
rxtx_factor=3,
project_id=project_id)
instance_id=inst['id'],
instance_uuid='',
host=inst['host'],
vpn=None,
rxtx_factor=3,
project_id=project_id)
self.assertEquals(1, len(nw_info))
fixed_ip = nw_info.fixed_ips()[0]['address']
self.assertTrue(utils.is_valid_ipv4(fixed_ip))
+3 -3
View File
@@ -542,7 +542,7 @@ class QuantumNovaMACGenerationTestCase(QuantumNovaTestCase):
class QuantumNovaPortSecurityTestCase(QuantumNovaTestCase):
def test_port_securty(self):
def test_port_security(self):
self.flags(use_melange_mac_generation=True)
self.flags(quantum_use_port_security=True)
fake_mac = "ab:cd:ef:ab:cd:ef"
@@ -578,7 +578,7 @@ class QuantumNovaPortSecurityTestCase(QuantumNovaTestCase):
requested_networks=requested_networks)
self.assertEqual(nw_info[0]['address'], fake_mac)
def test_port_securty_negative(self):
def test_port_security_negative(self):
self.flags(use_melange_mac_generation=True)
self.flags(quantum_use_port_security=False)
fake_mac = "ab:cd:ef:ab:cd:ef"
@@ -593,7 +593,7 @@ class QuantumNovaPortSecurityTestCase(QuantumNovaTestCase):
requested_networks = [(n[0], None) for n in all_valid_networks]
instance_ref = db.api.instance_create(ctx,
{"project_id": project_id})
{"project_id": project_id})
oldfunc = self.net_man.q_conn.create_and_attach_port
# Make sure no pairs are passed in if port security is turned off
+13 -13
View File
@@ -334,14 +334,14 @@ class DbApiTestCase(test.TestCase):
values = {'address': 'baz',
'network_id': 1,
'allocated': True,
'instance_id': instance['id'],
'instance_uuid': instance['uuid'],
'virtual_interface_id': vif['id']}
fixed_address = db.fixed_ip_create(ctxt, values)
data = db.network_get_associated_fixed_ips(ctxt, 1)
self.assertEqual(len(data), 1)
record = data[0]
self.assertEqual(record['address'], fixed_address)
self.assertEqual(record['instance_id'], instance['id'])
self.assertEqual(record['instance_uuid'], instance['uuid'])
self.assertEqual(record['network_id'], 1)
self.assertEqual(record['instance_created'], instance['created_at'])
self.assertEqual(record['instance_updated'], instance['updated_at'])
@@ -360,25 +360,25 @@ class DbApiTestCase(test.TestCase):
new = time = timeout + datetime.timedelta(seconds=5)
# should deallocate
values = {'allocated': False,
'instance_id': instance['id'],
'instance_uuid': instance['uuid'],
'network_id': net['id'],
'updated_at': old}
db.fixed_ip_create(ctxt, values)
# still allocated
values = {'allocated': True,
'instance_id': instance['id'],
'instance_uuid': instance['uuid'],
'network_id': net['id'],
'updated_at': old}
db.fixed_ip_create(ctxt, values)
# wrong network
values = {'allocated': False,
'instance_id': instance['id'],
'instance_uuid': instance['uuid'],
'network_id': None,
'updated_at': old}
db.fixed_ip_create(ctxt, values)
# too new
values = {'allocated': False,
'instance_id': instance['id'],
'instance_uuid': instance['uuid'],
'network_id': None,
'updated_at': new}
db.fixed_ip_create(ctxt, values)
@@ -830,27 +830,27 @@ class TestIpAllocation(test.TestCase):
def test_fixed_ip_associate_fails_if_ip_not_in_network(self):
self.assertRaises(exception.FixedIpNotFoundForNetwork,
db.fixed_ip_associate,
self.ctxt, None, None)
self.ctxt, None, self.instance.uuid)
def test_fixed_ip_associate_fails_if_ip_in_use(self):
address = self.create_fixed_ip(instance_id=self.instance.id)
address = self.create_fixed_ip(instance_uuid=self.instance.uuid)
self.assertRaises(exception.FixedIpAlreadyInUse,
db.fixed_ip_associate,
self.ctxt, address, self.instance.id)
self.ctxt, address, self.instance.uuid)
def test_fixed_ip_associate_succeeds(self):
address = self.create_fixed_ip(network_id=self.network.id)
db.fixed_ip_associate(self.ctxt, address, self.instance.id,
db.fixed_ip_associate(self.ctxt, address, self.instance.uuid,
network_id=self.network.id)
fixed_ip = db.fixed_ip_get_by_address(self.ctxt, address)
self.assertEqual(fixed_ip.instance_id, self.instance.id)
self.assertEqual(fixed_ip.instance_uuid, self.instance.uuid)
def test_fixed_ip_associate_succeeds_and_sets_network(self):
address = self.create_fixed_ip()
db.fixed_ip_associate(self.ctxt, address, self.instance.id,
db.fixed_ip_associate(self.ctxt, address, self.instance.uuid,
network_id=self.network.id)
fixed_ip = db.fixed_ip_get_by_address(self.ctxt, address)
self.assertEqual(fixed_ip.instance_id, self.instance.id)
self.assertEqual(fixed_ip.instance_uuid, self.instance.uuid)
self.assertEqual(fixed_ip.network_id, self.network.id)