Browse Source

Merge remote-tracking branch 'origin/master' into merge-branch

Change-Id: I7bd5d0568e773365eaab1ebd99dcd7186da22dae
changes/51/197751/1
Kyle Mestery 7 years ago
parent
commit
d7e60d59a3
  1. 4
      doc/source/devref/callbacks.rst
  2. 27
      doc/source/devref/linuxbridge_agent.rst
  3. 2
      doc/source/policies/thirdparty-ci.rst
  4. 4
      etc/dhcp_agent.ini
  5. 4
      etc/l3_agent.ini
  6. 4
      etc/metadata_agent.ini
  7. 0
      etc/neutron/plugins/ml2/linuxbridge_agent.ini
  8. 3
      etc/neutron/plugins/ml2/openvswitch_agent.ini
  9. 3
      etc/neutron/plugins/vmware/nsx.ini
  10. 2
      neutron/agent/common/config.py
  11. 5
      neutron/agent/dhcp/agent.py
  12. 4
      neutron/agent/dhcp_agent.py
  13. 7
      neutron/agent/l3/agent.py
  14. 11
      neutron/agent/l3/dvr_local_router.py
  15. 4
      neutron/agent/l3_agent.py
  16. 45
      neutron/agent/linux/dhcp.py
  17. 27
      neutron/agent/linux/ip_lib.py
  18. 2
      neutron/agent/linux/polling.py
  19. 3
      neutron/agent/metadata/agent.py
  20. 6
      neutron/agent/rpc.py
  21. 2
      neutron/cmd/eventlet/plugins/ovs_neutron_agent.py
  22. 3
      neutron/cmd/sanity/checks.py
  23. 9
      neutron/cmd/sanity_check.py
  24. 2
      neutron/common/rpc.py
  25. 42
      neutron/common/test_lib.py
  26. 26
      neutron/db/agents_db.py
  27. 2
      neutron/db/agentschedulers_db.py
  28. 21
      neutron/db/api.py
  29. 11
      neutron/db/db_base_plugin_common.py
  30. 39
      neutron/db/db_base_plugin_v2.py
  31. 118
      neutron/db/ipam_backend_mixin.py
  32. 3
      neutron/db/migration/migrate_to_ml2.py
  33. 5
      neutron/db/migration/models/head.py
  34. 3
      neutron/hacking/checks.py
  35. 55
      neutron/ipam/__init__.py
  36. 36
      neutron/ipam/utils.py
  37. 5
      neutron/manager.py
  38. 151
      neutron/openstack/common/eventlet_backdoor.py
  39. 147
      neutron/openstack/common/loopingcall.py
  40. 232
      neutron/openstack/common/periodic_task.py
  41. 507
      neutron/openstack/common/service.py
  42. 105
      neutron/openstack/common/systemd.py
  43. 150
      neutron/openstack/common/threadgroup.py
  44. 2
      neutron/plugins/hyperv/agent/l2_agent.py
  45. 2
      neutron/plugins/ibm/agent/sdnve_neutron_agent.py
  46. 2
      neutron/plugins/ml2/drivers/cisco/apic/apic_sync.py
  47. 6
      neutron/plugins/ml2/drivers/cisco/apic/apic_topology.py
  48. 2
      neutron/plugins/ml2/drivers/freescale/README.fslsdn
  49. 0
      neutron/plugins/ml2/drivers/l2pop/rpc_manager/__init__.py
  50. 0
      neutron/plugins/ml2/drivers/l2pop/rpc_manager/l2population_rpc.py
  51. 0
      neutron/plugins/ml2/drivers/linuxbridge/__init__.py
  52. 0
      neutron/plugins/ml2/drivers/linuxbridge/agent/README
  53. 0
      neutron/plugins/ml2/drivers/linuxbridge/agent/__init__.py
  54. 0
      neutron/plugins/ml2/drivers/linuxbridge/agent/common/__init__.py
  55. 0
      neutron/plugins/ml2/drivers/linuxbridge/agent/common/config.py
  56. 0
      neutron/plugins/ml2/drivers/linuxbridge/agent/common/constants.py
  57. 0
      neutron/plugins/ml2/drivers/linuxbridge/agent/l2network_models_v2.py
  58. 14
      neutron/plugins/ml2/drivers/linuxbridge/agent/linuxbridge_neutron_agent.py
  59. 0
      neutron/plugins/ml2/drivers/linuxbridge/mech_driver/__init__.py
  60. 0
      neutron/plugins/ml2/drivers/linuxbridge/mech_driver/mech_linuxbridge.py
  61. 0
      neutron/plugins/ml2/drivers/mech_sriov/agent/__init__.py
  62. 0
      neutron/plugins/ml2/drivers/mech_sriov/agent/common/__init__.py
  63. 0
      neutron/plugins/ml2/drivers/mech_sriov/agent/common/config.py
  64. 0
      neutron/plugins/ml2/drivers/mech_sriov/agent/common/exceptions.py
  65. 5
      neutron/plugins/ml2/drivers/mech_sriov/agent/eswitch_manager.py
  66. 3
      neutron/plugins/ml2/drivers/mech_sriov/agent/pci_lib.py
  67. 9
      neutron/plugins/ml2/drivers/mech_sriov/agent/sriov_nic_agent.py
  68. 0
      neutron/plugins/ml2/drivers/mech_sriov/mech_driver/__init__.py
  69. 0
      neutron/plugins/ml2/drivers/mech_sriov/mech_driver/exceptions.py
  70. 3
      neutron/plugins/ml2/drivers/mech_sriov/mech_driver/mech_driver.py
  71. 0
      neutron/plugins/ml2/drivers/openvswitch/__init__.py
  72. 0
      neutron/plugins/ml2/drivers/openvswitch/agent/README
  73. 0
      neutron/plugins/ml2/drivers/openvswitch/agent/__init__.py
  74. 0
      neutron/plugins/ml2/drivers/openvswitch/agent/common/__init__.py
  75. 3
      neutron/plugins/ml2/drivers/openvswitch/agent/common/config.py
  76. 0
      neutron/plugins/ml2/drivers/openvswitch/agent/common/constants.py
  77. 6
      neutron/plugins/ml2/drivers/openvswitch/agent/main.py
  78. 0
      neutron/plugins/ml2/drivers/openvswitch/agent/openflow/__init__.py
  79. 0
      neutron/plugins/ml2/drivers/openvswitch/agent/openflow/ovs_ofctl/__init__.py
  80. 0
      neutron/plugins/ml2/drivers/openvswitch/agent/openflow/ovs_ofctl/br_dvr_process.py
  81. 5
      neutron/plugins/ml2/drivers/openvswitch/agent/openflow/ovs_ofctl/br_int.py
  82. 8
      neutron/plugins/ml2/drivers/openvswitch/agent/openflow/ovs_ofctl/br_phys.py
  83. 9
      neutron/plugins/ml2/drivers/openvswitch/agent/openflow/ovs_ofctl/br_tun.py
  84. 11
      neutron/plugins/ml2/drivers/openvswitch/agent/openflow/ovs_ofctl/main.py
  85. 0
      neutron/plugins/ml2/drivers/openvswitch/agent/openflow/ovs_ofctl/ofswitch.py
  86. 3
      neutron/plugins/ml2/drivers/openvswitch/agent/openflow/ovs_ofctl/ovs_bridge.py
  87. 2
      neutron/plugins/ml2/drivers/openvswitch/agent/ovs_dvr_neutron_agent.py
  88. 0
      neutron/plugins/ml2/drivers/openvswitch/agent/ovs_models_v2.py
  89. 22
      neutron/plugins/ml2/drivers/openvswitch/agent/ovs_neutron_agent.py
  90. 0
      neutron/plugins/ml2/drivers/openvswitch/agent/xenapi/README
  91. 0
      neutron/plugins/ml2/drivers/openvswitch/agent/xenapi/contrib/build-rpm.sh
  92. 0
      neutron/plugins/ml2/drivers/openvswitch/agent/xenapi/contrib/rpmbuild/SPECS/openstack-quantum-xen-plugins.spec
  93. 0
      neutron/plugins/ml2/drivers/openvswitch/agent/xenapi/etc/xapi.d/plugins/netwrap
  94. 0
      neutron/plugins/ml2/drivers/openvswitch/mech_driver/__init__.py
  95. 0
      neutron/plugins/ml2/drivers/openvswitch/mech_driver/mech_openvswitch.py
  96. 4
      neutron/plugins/ml2/plugin.py
  97. 9
      neutron/service.py
  98. 8
      neutron/services/metering/agents/metering_agent.py
  99. 2
      neutron/tests/api/test_allowed_address_pair.py
  100. 34
      neutron/tests/base.py

4
doc/source/devref/callbacks.rst

@ -69,7 +69,7 @@ do whatever they are supposed to do. In a callback-less world this would work li
C->my_random_very_difficult_to_remember_method_about_router_created()
If B and/or C change, things become sour. In a callback-based world, things become a lot
more uniform and straightward:
more uniform and straightforward:
::
@ -319,7 +319,7 @@ Is the registry thread-safe?
Short answer is no: it is not safe to make mutations while callbacks are being called (more
details as to why can be found `here <https://hg.python.org/releasing/2.7.9/file/753a8f457ddc/Objects/dictobject.c#l937>`_).
A mutation could happen if a 'subscribe'/'unsuscribe' operation interleaves with the execution
A mutation could happen if a 'subscribe'/'unsubscribe' operation interleaves with the execution
of the notify loop. Albeit there is a possibility that things may end up in a bad state, the
registry works correctly under the assumption that subscriptions happen at the very beginning
of the life of the process and that the unsubscriptions (if any) take place at the very end.

27
doc/source/devref/linuxbridge_agent.rst

@ -1,2 +1,27 @@
===============================
L2 Networking with Linux Bridge
-------------------------------
===============================
This Agent uses the `Linux Bridge
<http://www.linuxfoundation.org/collaborate/workgroups/networking/bridge>`_ to
provide L2 connectivity for VM instances running on the compute node to the
public network. A graphical illustration of the deployment can be found in
`OpenStack Admin Guide Linux Bridge
<http://docs.openstack.org/admin-guide-cloud/content/under_the_hood_linuxbridge.html>`_
In most common deployments, there is a compute and a network node. On both the
compute and the network node, the Linux Bridge Agent will manage virtual
switches, connectivity among them, and interaction via virtual ports with other
network components such as namespaces and underlying interfaces. Additionally,
on the compute node, the Linux Bridge Agent will manage security groups.
Three use cases and their packet flow are documented as follows:
1. `Legacy implementation with Linux Bridge
<http://docs.openstack.org/networking-guide/deploy_scenario1b.html>`_
2. `High Availability using L3HA with Linux Bridge
<http://docs.openstack.org/networking-guide/deploy_scenario3b.html>`_
3. `Provider networks with Linux Bridge
<http://docs.openstack.org/networking-guide/deploy_scenario4b.html>`_

2
doc/source/policies/thirdparty-ci.rst

@ -18,7 +18,7 @@ changes to the infrastructure documentation using this url[2] (and please
review the patches) and check this doc on a regular basis for updates.
[1] http://ci.openstack.org/third_party.html
[2] https://review.openstack.org/#/q/status:open+project:openstack-infra/config+branch:master+topic:third-party,n,z
[2] https://review.openstack.org/#/q/status:open+project:openstack-infra/system-config+branch:master+topic:third-party,n,z
What Changes to Run Against
---------------------------

4
etc/dhcp_agent.ini

@ -90,3 +90,7 @@
# Timeout for ovs-vsctl commands.
# If the timeout expires, ovs commands will fail with ALARMCLOCK error.
# ovs_vsctl_timeout = 10
[AGENT]
# Log agent heartbeats from this DHCP agent
# log_agent_heartbeats = False

4
etc/l3_agent.ini

@ -122,3 +122,7 @@
# The advertisement interval in seconds
# ha_vrrp_advert_int = 2
[AGENT]
# Log agent heartbeats from this L3 agent
# log_agent_heartbeats = False

4
etc/metadata_agent.ini

@ -66,3 +66,7 @@ admin_password = %SERVICE_PASSWORD%
# Otherwise default_ttl specifies time in seconds a cache entry is valid for.
# No cache is used in case no value is passed.
# cache_url = memory://?default_ttl=5
[AGENT]
# Log agent heartbeats from this Metadata agent
# log_agent_heartbeats = False

0
etc/neutron/plugins/linuxbridge/linuxbridge_conf.ini → etc/neutron/plugins/ml2/linuxbridge_agent.ini

3
etc/neutron/plugins/openvswitch/ovs_neutron_plugin.ini → etc/neutron/plugins/ml2/openvswitch_agent.ini

@ -58,6 +58,9 @@
# of_interface = ovs-ofctl
[agent]
# Log agent heartbeats from this OVS agent
# log_agent_heartbeats = False
# Agent's polling interval in seconds
# polling_interval = 2

3
etc/neutron/plugins/vmware/nsx.ini

@ -156,6 +156,9 @@
# lock management.
# locking_coordinator_url =
# (Optional) DHCP lease time
# dhcp_lease_time = 86400
[nsx]
# Maximum number of ports for each bridged logical switch
# The recommended value for this parameter varies with NSX version

2
neutron/agent/common/config.py

@ -44,6 +44,8 @@ AGENT_STATE_OPTS = [
help=_('Seconds between nodes reporting state to server; '
'should be less than agent_down_time, best if it '
'is half or less than agent_down_time.')),
cfg.BoolOpt('log_agent_heartbeats', default=False,
help=_('Log agent heartbeats')),
]
INTERFACE_DRIVER_OPTS = [

5
neutron/agent/dhcp/agent.py

@ -21,6 +21,7 @@ import eventlet
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging
from oslo_service import loopingcall
from oslo_utils import importutils
from neutron.agent.linux import dhcp
@ -36,7 +37,6 @@ from neutron.common import utils
from neutron import context
from neutron.i18n import _LE, _LI, _LW
from neutron import manager
from neutron.openstack.common import loopingcall
LOG = logging.getLogger(__name__)
@ -548,7 +548,8 @@ class DhcpAgentWithStateReport(DhcpAgent):
'configurations': {
'dhcp_driver': cfg.CONF.dhcp_driver,
'use_namespaces': cfg.CONF.use_namespaces,
'dhcp_lease_duration': cfg.CONF.dhcp_lease_duration},
'dhcp_lease_duration': cfg.CONF.dhcp_lease_duration,
'log_agent_heartbeats': cfg.CONF.AGENT.log_agent_heartbeats},
'start_flag': True,
'agent_type': constants.AGENT_TYPE_DHCP}
report_interval = cfg.CONF.AGENT.report_interval

4
neutron/agent/dhcp_agent.py

@ -17,6 +17,7 @@
import sys
from oslo_config import cfg
from oslo_service import service
from neutron.agent.common import config
from neutron.agent.dhcp import config as dhcp_config
@ -24,7 +25,6 @@ from neutron.agent.linux import interface
from neutron.agent.metadata import config as metadata_config
from neutron.common import config as common_config
from neutron.common import topics
from neutron.openstack.common import service
from neutron import service as neutron_service
@ -49,4 +49,4 @@ def main():
topic=topics.DHCP_AGENT,
report_interval=cfg.CONF.AGENT.report_interval,
manager='neutron.agent.dhcp.agent.DhcpAgentWithStateReport')
service.launch(server).wait()
service.launch(cfg.CONF, server).wait()

7
neutron/agent/l3/agent.py

@ -18,6 +18,8 @@ import netaddr
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging
from oslo_service import loopingcall
from oslo_service import periodic_task
from oslo_utils import excutils
from oslo_utils import importutils
from oslo_utils import timeutils
@ -47,8 +49,6 @@ from neutron.common import topics
from neutron import context as n_context
from neutron.i18n import _LE, _LI, _LW
from neutron import manager
from neutron.openstack.common import loopingcall
from neutron.openstack.common import periodic_task
try:
from neutron_fwaas.services.firewall.agents.l3reference \
@ -595,7 +595,8 @@ class L3NATAgentWithStateReport(L3NATAgent):
'external_network_bridge': self.conf.external_network_bridge,
'gateway_external_network_id':
self.conf.gateway_external_network_id,
'interface_driver': self.conf.interface_driver},
'interface_driver': self.conf.interface_driver,
'log_agent_heartbeats': self.conf.AGENT.log_agent_heartbeats},
'start_flag': True,
'agent_type': l3_constants.AGENT_TYPE_L3}
report_interval = self.conf.AGENT.report_interval

11
neutron/agent/l3/dvr_local_router.py

@ -417,6 +417,17 @@ class DvrLocalRouter(router.RouterInfo):
is_first = False
if floating_ips:
is_first = self.fip_ns.subscribe(self.router_id)
if is_first and not fip_agent_port:
LOG.debug("No FloatingIP agent gateway port possibly due to "
"late binding of the private port to the host, "
"requesting agent gateway port for 'network-id' :"
"%s", ex_gw_port['network_id'])
fip_agent_port = self.agent.plugin_rpc.get_agent_gateway_port(
self.agent.context, ex_gw_port['network_id'])
if not fip_agent_port:
LOG.error(_LE("No FloatingIP agent gateway port "
"returned from server for 'network-id': "
"%s"), ex_gw_port['network_id'])
if is_first and fip_agent_port:
if 'subnets' not in fip_agent_port:
LOG.error(_LE('Missing subnet/agent_gateway_port'))

4
neutron/agent/l3_agent.py

@ -17,6 +17,7 @@
import sys
from oslo_config import cfg
from oslo_service import service
from neutron.agent.common import config
from neutron.agent.l3 import config as l3_config
@ -26,7 +27,6 @@ from neutron.agent.linux import interface
from neutron.agent.metadata import config as metadata_config
from neutron.common import config as common_config
from neutron.common import topics
from neutron.openstack.common import service
from neutron import service as neutron_service
@ -51,4 +51,4 @@ def main(manager='neutron.agent.l3.agent.L3NATAgentWithStateReport'):
topic=topics.L3_AGENT,
report_interval=cfg.CONF.AGENT.report_interval,
manager=manager)
service.launch(server).wait()
service.launch(cfg.CONF, server).wait()

45
neutron/agent/linux/dhcp.py

@ -434,6 +434,44 @@ class Dnsmasq(DhcpLocalProcess):
LOG.debug('Reloading allocations for network: %s', self.network.id)
self.device_manager.update(self.network, self.interface_name)
def _sort_fixed_ips_for_dnsmasq(self, fixed_ips, v6_nets):
"""Sort fixed_ips so that stateless IPv6 subnets appear first.
For example, If a port with v6 extra_dhcp_opts is on a network with
IPv4 and IPv6 stateless subnets. Then dhcp host file will have
below 2 entries for same MAC,
fa:16:3e:8f:9d:65,30.0.0.5,set:aabc7d33-4874-429e-9637-436e4232d2cd
(entry for IPv4 dhcp)
fa:16:3e:8f:9d:65,set:aabc7d33-4874-429e-9637-436e4232d2cd
(entry for stateless IPv6 for v6 options)
dnsmasq internal details for processing host file entries
1) dnsmaq reads the host file from EOF.
2) So it first picks up stateless IPv6 entry,
fa:16:3e:8f:9d:65,set:aabc7d33-4874-429e-9637-436e4232d2cd
3) But dnsmasq doesn't have sufficient checks to skip this entry and
pick next entry, to process dhcp IPv4 request.
4) So dnsmaq uses this this entry to process dhcp IPv4 request.
5) As there is no ip in this entry, dnsmaq logs "no address available"
and fails to send DHCPOFFER message.
As we rely on internal details of dnsmasq to understand and fix the
issue, Ihar sent a mail to dnsmasq-discuss mailing list
http://lists.thekelleys.org.uk/pipermail/dnsmasq-discuss/2015q2/
009650.html
So If we reverse the order of writing entries in host file,
so that entry for stateless IPv6 comes first,
then dnsmasq can correctly fetch the IPv4 address.
"""
return sorted(
fixed_ips,
key=lambda fip: ((fip.subnet_id in v6_nets) and (
v6_nets[fip.subnet_id].ipv6_address_mode == (
constants.DHCPV6_STATELESS))),
reverse=True)
def _iter_hosts(self):
"""Iterate over hosts.
@ -449,8 +487,11 @@ class Dnsmasq(DhcpLocalProcess):
"""
v6_nets = dict((subnet.id, subnet) for subnet in
self.network.subnets if subnet.ip_version == 6)
for port in self.network.ports:
for alloc in port.fixed_ips:
fixed_ips = self._sort_fixed_ips_for_dnsmasq(port.fixed_ips,
v6_nets)
for alloc in fixed_ips:
# Note(scollins) Only create entries that are
# associated with the subnet being managed by this
# dhcp agent
@ -911,7 +952,7 @@ class DeviceManager(object):
device = ip_lib.IPDevice(device_name, namespace=network.namespace)
gateway = device.route.get_gateway()
if gateway:
gateway = gateway['gateway']
gateway = gateway.get('gateway')
for subnet in network.subnets:
skip_subnet = (

27
neutron/agent/linux/ip_lib.py

@ -19,6 +19,7 @@ import os
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import excutils
import re
from neutron.agent.common import utils
from neutron.common import exceptions
@ -36,6 +37,8 @@ OPTS = [
LOOPBACK_DEVNAME = 'lo'
SYS_NET_PATH = '/sys/class/net'
DEFAULT_GW_PATTERN = re.compile(r"via (\S+)")
METRIC_PATTERN = re.compile(r"metric (\S+)")
class AddressNotReady(exceptions.NeutronException):
@ -531,12 +534,13 @@ class IpRouteCommand(IpDeviceCommandBase):
route_list_lines if
x.strip().startswith('default')), None)
if default_route_line:
gateway_index = 2
parts = default_route_line.split()
retval = dict(gateway=parts[gateway_index])
if 'metric' in parts:
metric_index = parts.index('metric') + 1
retval.update(metric=int(parts[metric_index]))
retval = dict()
gateway = DEFAULT_GW_PATTERN.search(default_route_line)
if gateway:
retval.update(gateway=gateway.group(1))
metric = METRIC_PATTERN.search(default_route_line)
if metric:
retval.update(metric=int(metric.group(1)))
return retval
@ -630,6 +634,17 @@ class IpNeighCommand(IpDeviceCommandBase):
('show',
'dev', self.name))
def flush(self, ip_version, ip_address):
"""Flush neighbour entries
Given address entry is removed from neighbour cache (ARP or NDP). To
flush all entries pass string 'all' as an address.
:param ip_version: Either 4 or 6 for IPv4 or IPv6 respectively
:param ip_address: The prefix selecting the neighbours to flush
"""
self._as_root([ip_version], ('flush', 'to', ip_address))
class IpNetnsCommand(IpCommandBase):
COMMAND = 'netns'

2
neutron/agent/linux/polling.py

@ -18,7 +18,7 @@ import eventlet
from neutron.agent.common import base_polling
from neutron.agent.linux import ovsdb_monitor
from neutron.plugins.openvswitch.common import constants
from neutron.plugins.ml2.drivers.openvswitch.agent.common import constants
@contextlib.contextmanager

3
neutron/agent/metadata/agent.py

@ -20,6 +20,7 @@ from neutronclient.v2_0 import client
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging
from oslo_service import loopingcall
import six
import six.moves.urllib.parse as urlparse
import webob
@ -34,7 +35,6 @@ from neutron.common import utils
from neutron import context
from neutron.i18n import _LE, _LW
from neutron.openstack.common.cache import cache
from neutron.openstack.common import loopingcall
LOG = logging.getLogger(__name__)
@ -289,6 +289,7 @@ class UnixDomainMetadataProxy(object):
'metadata_proxy_socket': cfg.CONF.metadata_proxy_socket,
'nova_metadata_ip': cfg.CONF.nova_metadata_ip,
'nova_metadata_port': cfg.CONF.nova_metadata_port,
'log_agent_heartbeats': cfg.CONF.AGENT.log_agent_heartbeats,
},
'start_flag': True,
'agent_type': n_const.AGENT_TYPE_METADATA}

6
neutron/agent/rpc.py

@ -18,6 +18,7 @@ import itertools
from oslo_log import log as logging
import oslo_messaging
from oslo_utils import timeutils
from oslo_utils import uuidutils
from neutron.common import constants
from neutron.common import rpc as n_rpc
@ -72,6 +73,11 @@ class PluginReportStateAPI(object):
def report_state(self, context, agent_state, use_call=False):
cctxt = self.client.prepare()
# add unique identifier to a report
# that can be logged on server side.
# This create visible correspondence between events on
# the agent and on the server
agent_state['uuid'] = uuidutils.generate_uuid()
kwargs = {
'agent_state': {'agent_state': agent_state},
'time': timeutils.strtime(),

2
neutron/cmd/eventlet/plugins/ovs_neutron_agent.py

@ -13,7 +13,7 @@
# License for the specific language governing permissions and limitations
# under the License.
import neutron.plugins.openvswitch.agent.main as agent_main
import neutron.plugins.ml2.drivers.openvswitch.agent.main as agent_main
def main():

3
neutron/cmd/sanity/checks.py

@ -27,7 +27,8 @@ from neutron.agent.linux import utils as agent_utils
from neutron.common import utils
from neutron.i18n import _LE
from neutron.plugins.common import constants as const
from neutron.plugins.openvswitch.common import constants as ovs_const
from neutron.plugins.ml2.drivers.openvswitch.agent.common \
import constants as ovs_const
LOG = logging.getLogger(__name__)

9
neutron/cmd/sanity_check.py

@ -25,9 +25,12 @@ from neutron.i18n import _LE, _LW
LOG = logging.getLogger(__name__)
cfg.CONF.import_group('AGENT', 'neutron.plugins.openvswitch.common.config')
cfg.CONF.import_group('OVS', 'neutron.plugins.openvswitch.common.config')
cfg.CONF.import_group('VXLAN', 'neutron.plugins.linuxbridge.common.config')
cfg.CONF.import_group('AGENT', 'neutron.plugins.ml2.drivers.openvswitch.'
'agent.common.config')
cfg.CONF.import_group('OVS', 'neutron.plugins.ml2.drivers.openvswitch.'
'agent.common.config')
cfg.CONF.import_group('VXLAN', 'neutron.plugins.ml2.drivers.linuxbridge.'
'agent.common.config')
cfg.CONF.import_group('ml2', 'neutron.plugins.ml2.config')
cfg.CONF.import_group('ml2_sriov',
'neutron.plugins.ml2.drivers.mech_sriov.mech_driver')

2
neutron/common/rpc.py

@ -18,10 +18,10 @@ from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging
from oslo_messaging import serializer as om_serializer
from oslo_service import service
from neutron.common import exceptions
from neutron import context
from neutron.openstack.common import service
LOG = logging.getLogger(__name__)

42
neutron/common/test_lib.py

@ -0,0 +1,42 @@
# Copyright (c) 2010 OpenStack Foundation
# 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.
# Colorizer Code is borrowed from Twisted:
# Copyright (c) 2001-2010 Twisted Matrix Laboratories.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# describes parameters used by different unit/functional tests
# a plugin-specific testing mechanism should import this dictionary
# and override the values in it if needed (e.g., run_tests.py in
# neutron/plugins/openvswitch/ )
test_config = {}

26
neutron/db/agents_db.py

@ -29,7 +29,7 @@ from neutron.common import constants
from neutron.db import model_base
from neutron.db import models_v2
from neutron.extensions import agent as ext_agent
from neutron.i18n import _LE, _LW
from neutron.i18n import _LE, _LI, _LW
from neutron import manager
LOG = logging.getLogger(__name__)
@ -203,22 +203,33 @@ class AgentDbMixin(ext_agent.AgentPluginBase):
agent = self._get_agent(context, id)
return self._make_agent_dict(agent, fields)
def _create_or_update_agent(self, context, agent):
def _log_heartbeat(self, state, agent_db, agent_conf):
if agent_conf.get('log_agent_heartbeats'):
delta = timeutils.utcnow() - agent_db.heartbeat_timestamp
LOG.info(_LI("Heartbeat received from %(type)s agent on "
"host %(host)s, uuid %(uuid)s after %(delta)s"),
{'type': agent_db.agent_type,
'host': agent_db.host,
'uuid': state.get('uuid'),
'delta': delta})
def _create_or_update_agent(self, context, agent_state):
with context.session.begin(subtransactions=True):
res_keys = ['agent_type', 'binary', 'host', 'topic']
res = dict((k, agent[k]) for k in res_keys)
res = dict((k, agent_state[k]) for k in res_keys)
configurations_dict = agent.get('configurations', {})
configurations_dict = agent_state.get('configurations', {})
res['configurations'] = jsonutils.dumps(configurations_dict)
res['load'] = self._get_agent_load(agent)
res['load'] = self._get_agent_load(agent_state)
current_time = timeutils.utcnow()
try:
agent_db = self._get_agent_by_type_and_host(
context, agent['agent_type'], agent['host'])
context, agent_state['agent_type'], agent_state['host'])
res['heartbeat_timestamp'] = current_time
if agent.get('start_flag'):
if agent_state.get('start_flag'):
res['started_at'] = current_time
greenthread.sleep(0)
self._log_heartbeat(agent_state, agent_db, configurations_dict)
agent_db.update(res)
except ext_agent.AgentNotFoundByTypeHost:
greenthread.sleep(0)
@ -229,6 +240,7 @@ class AgentDbMixin(ext_agent.AgentPluginBase):
agent_db = Agent(**res)
greenthread.sleep(0)
context.session.add(agent_db)
self._log_heartbeat(agent_state, agent_db, configurations_dict)
greenthread.sleep(0)
def create_or_update_agent(self, context, agent):

2
neutron/db/agentschedulers_db.py

@ -19,6 +19,7 @@ import time
from oslo_config import cfg
from oslo_log import log as logging
from oslo_service import loopingcall
from oslo_utils import timeutils
import sqlalchemy as sa
from sqlalchemy import orm
@ -32,7 +33,6 @@ from neutron.db import model_base
from neutron.extensions import agent as ext_agent
from neutron.extensions import dhcpagentscheduler
from neutron.i18n import _LE, _LI, _LW
from neutron.openstack.common import loopingcall
LOG = logging.getLogger(__name__)

21
neutron/db/api.py

@ -14,10 +14,13 @@
# under the License.
import contextlib
import six
from oslo_config import cfg
from oslo_db import exception as os_db_exception
from oslo_db.sqlalchemy import session
from sqlalchemy import exc
from sqlalchemy import orm
_FACADE = None
@ -64,3 +67,21 @@ def autonested_transaction(sess):
finally:
with session_context as tx:
yield tx
class convert_db_exception_to_retry(object):
"""Converts other types of DB exceptions into RetryRequests."""
def __init__(self, stale_data=False):
self.to_catch = ()
if stale_data:
self.to_catch += (orm.exc.StaleDataError, )
def __call__(self, f):
@six.wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except self.to_catch as e:
raise os_db_exception.RetryRequest(e)
return wrapper

11
neutron/db/db_base_plugin_common.py

@ -13,8 +13,6 @@
# License for the specific language governing permissions and limitations
# under the License.
import netaddr
from oslo_config import cfg
from oslo_log import log as logging
from sqlalchemy.orm import exc
@ -25,7 +23,6 @@ from neutron.common import exceptions as n_exc
from neutron.common import utils
from neutron.db import common_db_mixin
from neutron.db import models_v2
from neutron.ipam import utils as ipam_utils
LOG = logging.getLogger(__name__)
@ -75,14 +72,6 @@ class DbBasePluginCommon(common_db_mixin.CommonDbMixin):
)
context.session.add(allocated)
@classmethod
def _check_gateway_in_subnet(cls, cidr, gateway):
"""Validate that the gateway is on the subnet."""
ip = netaddr.IPAddress(gateway)
if ip.version == 4 or (ip.version == 6 and not ip.is_link_local()):
return ipam_utils.check_subnet_ip(cidr, gateway)
return True
def _make_subnet_dict(self, subnet, fields=None):
res = {'id': subnet['id'],
'name': subnet['name'],

39
neutron/db/db_base_plugin_v2.py

@ -31,7 +31,6 @@ from neutron.callbacks import resources
from neutron.common import constants
from neutron.common import exceptions as n_exc
from neutron.common import ipv6_utils
from neutron.common import utils
from neutron import context as ctx
from neutron.db import api as db_api
from neutron.db import ipam_non_pluggable_backend
@ -356,7 +355,7 @@ class NeutronDbPluginV2(ipam_non_pluggable_backend.IpamNonPluggableBackend,
if attributes.is_attr_set(s.get('gateway_ip')):
self._validate_ip_version(ip_ver, s['gateway_ip'], 'gateway_ip')
if (cfg.CONF.force_gateway_on_subnet and
not self._check_gateway_in_subnet(
not ipam.utils.check_gateway_in_subnet(
s['cidr'], s['gateway_ip'])):
error_message = _("Gateway is not valid on subnet")
raise n_exc.InvalidInput(error_message=error_message)
@ -440,32 +439,11 @@ class NeutronDbPluginV2(ipam_non_pluggable_backend.IpamNonPluggableBackend,
external_gateway_info}}
l3plugin.update_router(context, id, info)
def _make_subnet_request(self, tenant_id, subnet, subnetpool):
cidr = subnet.get('cidr')
subnet_id = subnet.get('id', uuidutils.generate_uuid())
is_any_subnetpool_request = not attributes.is_attr_set(cidr)
if is_any_subnetpool_request:
prefixlen = subnet['prefixlen']
if not attributes.is_attr_set(prefixlen):
prefixlen = int(subnetpool['default_prefixlen'])
return ipam.AnySubnetRequest(
tenant_id,
subnet_id,
utils.ip_version_from_int(subnetpool['ip_version']),
prefixlen)
else:
return ipam.SpecificSubnetRequest(tenant_id,
subnet_id,
cidr)
@oslo_db_api.wrap_db_retry(max_retries=db_api.MAX_RETRIES,
retry_on_request=True,
retry_on_deadlock=True)
def _create_subnet_from_pool(self, context, subnet, subnetpool_id):
s = subnet['subnet']
tenant_id = self._get_tenant_id_for_create(context, s)
self._validate_pools_with_subnetpool(s)
with context.session.begin(subtransactions=True):
@ -474,7 +452,7 @@ class NeutronDbPluginV2(ipam_non_pluggable_backend.IpamNonPluggableBackend,
network = self._get_network(context, s["network_id"])
allocator = subnet_alloc.SubnetAllocator(subnetpool, context)
req = self._make_subnet_request(tenant_id, s, subnetpool)
req = ipam.SubnetRequestFactory.get_request(context, s, subnetpool)
ipam_subnet = allocator.allocate_subnet(req)
detail = ipam_subnet.get_details()
@ -498,9 +476,8 @@ class NeutronDbPluginV2(ipam_non_pluggable_backend.IpamNonPluggableBackend,
def _create_subnet_from_implicit_pool(self, context, subnet):
s = subnet['subnet']
self._validate_subnet(context, s)
tenant_id = self._get_tenant_id_for_create(context, s)
id = s.get('id', uuidutils.generate_uuid())
detail = ipam.SpecificSubnetRequest(tenant_id,
detail = ipam.SpecificSubnetRequest(s['tenant_id'],
id,
s['cidr'])
with context.session.begin(subtransactions=True):
@ -571,6 +548,7 @@ class NeutronDbPluginV2(ipam_non_pluggable_backend.IpamNonPluggableBackend,
net = netaddr.IPNetwork(s['cidr'])
subnet['subnet']['cidr'] = '%s/%s' % (net.network, net.prefixlen)
s['tenant_id'] = self._get_tenant_id_for_create(context, s)
subnetpool_id = self._get_subnetpool_id(s)
if not subnetpool_id:
if not has_cidr:
@ -608,8 +586,13 @@ class NeutronDbPluginV2(ipam_non_pluggable_backend.IpamNonPluggableBackend,
self._validate_subnet(context, s, cur_subnet=db_subnet)
if s.get('gateway_ip') is not None:
allocation_pools = [{'start': p['first_ip'], 'end': p['last_ip']}
for p in db_subnet.allocation_pools]
if s.get('allocation_pools') is not None:
allocation_pools = [{'start': p['start'], 'end': p['end']}
for p in s['allocation_pools']]
else:
allocation_pools = [{'start': p['first_ip'],
'end': p['last_ip']}
for p in db_subnet.allocation_pools]
self._validate_gw_out_of_pools(s["gateway_ip"], allocation_pools)
with context.session.begin(subtransactions=True):

118
neutron/db/ipam_backend_mixin.py

@ -14,6 +14,7 @@
# under the License.
import collections
import itertools
import netaddr
from oslo_config import cfg
@ -27,6 +28,7 @@ from neutron.common import ipv6_utils
from neutron.db import db_base_plugin_common
from neutron.db import models_v2
from neutron.i18n import _LI
from neutron.ipam import utils as ipam_utils
LOG = logging.getLogger(__name__)
@ -174,24 +176,10 @@ class IpamBackendMixin(db_base_plugin_common.DbBasePluginCommon):
a list of dict objects with 'start' and 'end' keys for
defining the pool range.
"""
pools = []
# Auto allocate the pool around gateway_ip
net = netaddr.IPNetwork(subnet['cidr'])
first_ip = net.first + 1
last_ip = net.last - 1
gw_ip = int(netaddr.IPAddress(subnet['gateway_ip'] or net.last))
# Use the gw_ip to find a point for splitting allocation pools
# for this subnet
split_ip = min(max(gw_ip, net.first), net.last)
if split_ip > first_ip:
pools.append({'start': str(netaddr.IPAddress(first_ip)),
'end': str(netaddr.IPAddress(split_ip - 1))})
if split_ip < last_ip:
pools.append({'start': str(netaddr.IPAddress(split_ip + 1)),
'end': str(netaddr.IPAddress(last_ip))})
# return auto-generated pools
# no need to check for their validity
return pools
pools = ipam_utils.generate_pools(subnet['cidr'], subnet['gateway_ip'])
return [{'start': str(netaddr.IPAddress(pool.first)),
'end': str(netaddr.IPAddress(pool.last))}
for pool in pools]
def _validate_subnet_cidr(self, context, network, new_subnet_cidr):
"""Validate the CIDR for a subnet.
@ -251,7 +239,8 @@ class IpamBackendMixin(db_base_plugin_common.DbBasePluginCommon):
"""
subnet = netaddr.IPNetwork(subnet_cidr)
subnet_first_ip = netaddr.IPAddress(subnet.first + 1)
subnet_last_ip = netaddr.IPAddress(subnet.last - 1)
# last address is broadcast in v4
subnet_last_ip = netaddr.IPAddress(subnet.last - (subnet.version == 4))
LOG.debug("Performing IP validity checks on allocation pools")
ip_sets = []
@ -308,6 +297,16 @@ class IpamBackendMixin(db_base_plugin_common.DbBasePluginCommon):
pool_2=r_range,
subnet_cidr=subnet_cidr)
def _prepare_allocation_pools(self, context, allocation_pools, subnet):
if not attributes.is_attr_set(allocation_pools):
return self._allocate_pools_for_subnet(context, subnet)
self._validate_allocation_pools(allocation_pools, subnet['cidr'])
if subnet['gateway_ip']:
self._validate_gw_out_of_pools(subnet['gateway_ip'],
allocation_pools)
return allocation_pools
def _validate_gw_out_of_pools(self, gateway_ip, pools):
for allocation_pool in pools:
pool_range = netaddr.IPRange(
@ -318,6 +317,15 @@ class IpamBackendMixin(db_base_plugin_common.DbBasePluginCommon):
pool=pool_range,
ip_address=gateway_ip)
def _is_ip_required_by_subnet(self, context, subnet_id, device_owner):
# For ports that are not router ports, retain any automatic
# (non-optional, e.g. IPv6 SLAAC) addresses.
if device_owner in constants.ROUTER_INTERFACE_OWNERS:
return True
subnet = self._get_subnet(context, subnet_id)
return not ipv6_utils.is_auto_address_subnet(subnet)
def _get_changed_ips_for_port(self, context, original_ips,
new_ips, device_owner):
"""Calculate changes in IPs for the port."""
@ -326,30 +334,44 @@ class IpamBackendMixin(db_base_plugin_common.DbBasePluginCommon):
msg = _('Exceeded maximum amount of fixed ips per port')
raise n_exc.InvalidInput(error_message=msg)
# These ips are still on the port and haven't been removed
prev_ips = []
# Remove all of the intersecting elements
for original_ip in original_ips[:]:
for new_ip in new_ips[:]:
if ('ip_address' in new_ip and
original_ip['ip_address'] == new_ip['ip_address']):
original_ips.remove(original_ip)
new_ips.remove(new_ip)
prev_ips.append(original_ip)
break
add_ips = []
remove_ips = []
ips_map = {ip['ip_address']: ip
for ip in itertools.chain(new_ips, original_ips)
if 'ip_address' in ip}
new = set()
for ip in new_ips:
if 'ip_address' in ip:
new.add(ip['ip_address'])
else:
# For ports that are not router ports, retain any automatic
# (non-optional, e.g. IPv6 SLAAC) addresses.
if device_owner not in constants.ROUTER_INTERFACE_OWNERS:
subnet = self._get_subnet(context,
original_ip['subnet_id'])
if (ipv6_utils.is_auto_address_subnet(subnet)):
original_ips.remove(original_ip)
prev_ips.append(original_ip)
return self.Changes(add=new_ips,
add_ips.append(ip)
# Convert original ip addresses to sets
orig = set(ip['ip_address'] for ip in original_ips)
add = new - orig
unchanged = new & orig
remove = orig - new
# Convert results back to list of dicts
add_ips += [ips_map[ip] for ip in add]
prev_ips = [ips_map[ip] for ip in unchanged]
# Mark ip for removing if it is not found in new_ips
# and subnet requires ip to be set manually.
# For auto addresses leave ip unchanged
for ip in remove:
subnet_id = ips_map[ip]['subnet_id']
if self._is_ip_required_by_subnet(context, subnet_id,
device_owner):
remove_ips.append(ips_map[ip])
else:
prev_ips.append(ips_map[ip])
return self.Changes(add=add_ips,
original=prev_ips,
remove=original_ips)
remove=remove_ips)
def _delete_port(self, context, port_id):
query = (context.session.query(models_v2.Port).
@ -364,17 +386,9 @@ class IpamBackendMixin(db_base_plugin_common.DbBasePluginCommon):
dns_nameservers,
host_routes,
allocation_pools):
if not attributes.is_attr_set(allocation_pools):
allocation_pools = self._allocate_pools_for_subnet(context,
subnet_args)
else:
self._validate_allocation_pools(allocation_pools,
subnet_args['cidr'])
if subnet_args['gateway_ip']:
self._validate_gw_out_of_pools(subnet_args['gateway_ip'],
allocation_pools)
allocation_pools = self._prepare_allocation_pools(context,
allocation_pools,
subnet_args)
self._validate_subnet_cidr(context, network, subnet_args['cidr'])
self._validate_network_subnetpools(network,
subnet_args['subnetpool_id'],

3
neutron/db/migration/migrate_to_ml2.py

@ -101,7 +101,8 @@ def check_db_schema_version(engine, metadata):
)
# Duplicated from neutron.plugins.linuxbridge.common.constants to
# Duplicated from
# neutron.plugins.ml2.drivers.linuxbridge.agent.common.constants to
# avoid having any dependency on the linuxbridge plugin being
# installed.
def interpret_vlan_id(vlan_id):

5
neutron/db/migration/models/head.py

@ -50,7 +50,6 @@ from neutron.plugins.brocade.db import models as brocade_models # noqa
from neutron.plugins.cisco.db.l3 import l3_models # noqa
from neutron.plugins.cisco.db import n1kv_models_v2 # noqa
from neutron.plugins.cisco.db import network_models_v2 # noqa
from neutron.plugins.linuxbridge.db import l2network_models_v2 # noqa
from neutron.plugins.metaplugin import meta_models_v2 # noqa
from neutron.plugins.ml2.drivers.arista import db # noqa
from neutron.plugins.ml2.drivers.brocade.db import ( # noqa
@ -60,6 +59,9 @@ from neutron.plugins.ml2.drivers.cisco.n1kv import n1kv_models # noqa
from neutron.plugins.ml2.drivers.cisco.nexus import ( # noqa
nexus_models_v2 as ml2_nexus_models_v2)
from neutron.plugins.ml2.drivers.cisco.ucsm import ucsm_model # noqa
from neutron.plugins.ml2.drivers.linuxbridge.agent import ( # noqa
l2network_models_v2)
from neutron.plugins.ml2.drivers.openvswitch.agent import ovs_models_v2 # noqa
from neutron.plugins.ml2.drivers import type_flat # noqa
from neutron.plugins.ml2.drivers import type_gre # noqa
from neutron.plugins.ml2.drivers import type_vlan # noqa
@ -67,7 +69,6 @@ from neutron.plugins.ml2.drivers import type_vxlan # noqa
from neutron.plugins.ml2 import models # noqa
from neutron.plugins.nec.db import models as nec_models # noqa
from neutron.plugins.nuage import nuage_models # noqa
from neutron.plugins.openvswitch import ovs_models_v2 # noqa
from neutron.plugins.vmware.dbexts import nsx_models # noqa
from neutron.plugins.vmware.dbexts import nsxv_models # noqa
from neutron.plugins.vmware.dbexts import vcns_models # noqa

3
neutron/hacking/checks.py

@ -75,7 +75,8 @@ def use_jsonutils(logical_line, filename):
# Some files in the tree are not meant to be run from inside Neutron
# itself, so we should not complain about them not using jsonutils
json_check_skipped_patterns = [
"neutron/plugins/openvswitch/agent/xenapi/etc/xapi.d/plugins/netwrap",
"neutron/plugins/ml2/drivers/openvswitch/agent/xenapi/etc/xapi.d/"
"plugins/netwrap",
]
for pattern in json_check_skipped_patterns:

55
neutron/ipam/__init__.py

@ -14,10 +14,13 @@ import abc
import netaddr
from oslo_config import cfg
from oslo_utils import uuidutils
import six
from neutron.api.v2 import attributes
from neutron.common import constants
from neutron.common import ipv6_utils
from neutron.common import utils as common_utils
from neutron.ipam import exceptions as ipam_exc
@ -243,28 +246,42 @@ class RouterGatewayAddressRequest(AddressRequest):
"""Used to request allocating the special router gateway address."""
class BaseRequestFactory(object):
"""Factory class to create right request based on input"""
any_request = None
specific_request = None
address_index = 0
class AddressRequestFactory(object):
"""Builds request using ip info
Additional parameters(port and context) are not used in default
implementation, but planned to be used in sub-classes
provided by specific ipam driver,
"""
@classmethod
def get_request(cls, *args, **kwargs):
args_list = [a for a in args]
address = args_list.pop(cls.address_index)
if not address:
return cls.any_request(*args_list, **kwargs)
def get_request(cls, context, port, ip):
if not ip:
return AnyAddressRequest()
else:
return cls.specific_request(*args, **kwargs)
return SpecificAddressRequest(ip)
class AddressRequestFactory(BaseRequestFactory):
any_request = AnyAddressRequest
specific_request = SpecificAddressRequest
class SubnetRequestFactory(object):
"""Builds request using subnet info"""
class SubnetRequestFactory(BaseRequestFactory):
any_request = AnySubnetRequest
specific_request = SpecificSubnetRequest
address_index = 2
@classmethod
def get_request(cls, context, subnet, subnetpool):
cidr = subnet.get('cidr')
subnet_id = subnet.get('id', uuidutils.generate_uuid())
is_any_subnetpool_request = not attributes.is_attr_set(cidr)
if is_any_subnetpool_request:
prefixlen = subnet['prefixlen']
if not attributes.is_attr_set(prefixlen):
prefixlen = int(subnetpool['default_prefixlen'])
return AnySubnetRequest(
subnet['tenant_id'],
subnet_id,
common_utils.ip_version_from_int(subnetpool['ip_version']),
prefixlen)
else:
return SpecificSubnetRequest(subnet['tenant_id'],
subnet_id,
cidr)

36
neutron/ipam/utils.py

@ -21,28 +21,38 @@ def check_subnet_ip(cidr, ip_address):
ip = netaddr.IPAddress(ip_address)
net = netaddr.IPNetwork(cidr)
# Check that the IP is valid on subnet. This cannot be the
# network or the broadcast address
return (ip != net.network and ip != net.broadcast
# network or the broadcast address (which exists only in IPv4)
return (ip != net.network
and (net.version == 6 or ip != net.broadcast)
and net.netmask & ip == net.network)
def check_gateway_in_subnet(cidr, gateway):
"""Validate that the gateway is on the subnet."""
ip = netaddr.IPAddress(gateway)
if ip.version == 4 or (ip.version == 6 and not ip.is_link_local()):
return check_subnet_ip(cidr, gateway)
return True
def generate_pools(cidr, gateway_ip):
"""Create IP allocation pools for a specified subnet
The Neutron API defines a subnet's allocation pools as a list of
IPRange objects for defining the pool range.
"""
pools = []
# Auto allocate the pool around gateway_ip
net = netaddr.IPNetwork(cidr)
if net.first == net.last:
# handle single address subnet case
return [netaddr.IPRange(net.first, net.last)]
first_ip = net.first + 1
last_ip = net.last - 1
gw_ip = int(netaddr.IPAddress(gateway_ip or net.last))
# Use the gw_ip to find a point for splitting allocation pools
# for this subnet
split_ip = min(max(gw_ip, net.first), net.last)
if split_ip > first_ip:
pools.append(netaddr.IPRange(first_ip, split_ip - 1))
if split_ip < last_ip:
pools.append(netaddr.IPRange(split_ip + 1, last_ip))
return pools
# last address is broadcast in v4
last_ip = net.last - (net.version == 4)
if first_ip >= last_ip:
# /31 lands here
return []
ipset = netaddr.IPSet(netaddr.IPRange(first_ip, last_ip))
if gateway_ip:
ipset.remove(netaddr.IPAddress(gateway_ip))
return list(ipset.iter_ipranges())

5
neutron/manager.py

@ -18,12 +18,12 @@ import weakref
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging
from oslo_service import periodic_task
from oslo_utils import importutils
import six
from neutron.common import utils
from neutron.i18n import _LE, _LI
from neutron.openstack.common import periodic_task
from neutron.plugins.common import constants
from stevedore import driver
@ -43,7 +43,8 @@ class Manager(periodic_task.PeriodicTasks):
if not host:
host = cfg.CONF.host
self.host = host
super(Manager, self).__init__()
conf = getattr(self, "conf", cfg.CONF)
super(Manager, self).__init__(conf)
def periodic_tasks(self, context, raise_on_error=False):
self.run_periodic_tasks(context, raise_on_error=raise_on_error)

151
neutron/openstack/common/eventlet_backdoor.py

@ -1,151 +0,0 @@
# Copyright (c) 2012 OpenStack Foundation.
# Administrator of the National Aeronautics and Space Administration.
# 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 __future__ import print_function
import copy
import errno
import gc
import logging
import os
import pprint
import socket
import sys
import traceback
import eventlet.backdoor
import greenlet
from oslo_config import cfg
from neutron.openstack.common._i18n import _LI
help_for_backdoor_port = (
"Acceptable values are 0, <port>, and <start>:<end>, where 0 results "
"in listening on a random tcp port number; <port> results in listening "
"on the specified port number (and not enabling backdoor if that port "
"is in use); and <start>:<end> results in listening on the smallest "
"unused port number within the specified range of port numbers. The "
"chosen port is displayed in the service's log file.")
eventlet_backdoor_opts = [
cfg.StrOpt('backdoor_port',
help="Enable eventlet backdoor. %s" % help_for_backdoor_port)
]
CONF = cfg.CONF
CONF.register_opts(eventlet_backdoor_opts)
LOG = logging.getLogger(__name__)
def list_opts():
"""Entry point for oslo-config-generator.
"""
return [(None, copy.deepcopy(eventlet_backdoor_opts))]
class EventletBackdoorConfigValueError(Exception):
def __init__(self, port_range, help_msg, ex):
msg = ('Invalid backdoor_port configuration %(range)s: %(ex)s. '
'%(help)s' %
{'range': port_range, 'ex': ex, 'help': help_msg})
super(EventletBackdoorConfigValueError, self).__init__(msg)
self.port_range = port_range
def _dont_use_this():
print("Don't use this, just disconnect instead")
def _find_objects(t):
return [o for o in gc.get_objects() if isinstance(o, t)]
def _print_greenthreads():
for i, gt in enumerate(_find_objects(greenlet.greenlet)):
print(i, gt)
traceback.print_stack(gt.gr_frame)
print()
def _print_nativethreads():
for threadId, stack in sys._current_frames().items():
print(threadId)
traceback.print_stack(stack)
print()
def _parse_port_range(port_range):
if ':' not in port_range:
start, end = port_range, port_range
else:
start, end = port_range.split(':', 1)
try:
start, end = int(start), int(end)
if end < start:
raise ValueError
return start, end
except ValueError as ex:
raise EventletBackdoorConfigValueError(port_range, ex,
help_for_backdoor_port)
def _listen(host, start_port, end_port, listen_func):
try_port = start_port
while True:
try:
return listen_func((host, try_port