Extenuate register_dhcp_agent code duplication in tests

Non-obvious changes:
* Change helpers.register_agent to use a slimmed down version
  of a plugin that knows how to register an agent. This allows
  the helper to be used with tests that do not register a core
  plugin.

Change-Id: Iefb1af676af6a984b01cdc1e9050541dffb5951a
This commit is contained in:
Assaf Muller 2015-05-01 13:29:26 -04:00
parent 8c7bc3536b
commit 801dedebbf
5 changed files with 133 additions and 263 deletions

View File

@ -12,13 +12,17 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import datetime
import os import os
from oslo_utils import timeutils
import neutron import neutron
from neutron.common import constants from neutron.common import constants
from neutron.common import topics from neutron.common import topics
from neutron import context from neutron import context
from neutron import manager from neutron.db import agents_db
from neutron.db import common_db_mixin
HOST = 'localhost' HOST = 'localhost'
@ -37,6 +41,11 @@ def find_sample_file(filename):
path=os.path.join(neutron.__path__[0], '..', 'etc')) path=os.path.join(neutron.__path__[0], '..', 'etc'))
class FakePlugin(common_db_mixin.CommonDbMixin,
agents_db.AgentDbMixin):
pass
def _get_l3_agent_dict(host, agent_mode, internal_only=True, def _get_l3_agent_dict(host, agent_mode, internal_only=True,
ext_net_id='', ext_bridge='', router_id=None): ext_net_id='', ext_bridge='', router_id=None):
return { return {
@ -53,13 +62,11 @@ def _get_l3_agent_dict(host, agent_mode, internal_only=True,
def _register_agent(agent): def _register_agent(agent):
core_plugin = manager.NeutronManager.get_plugin() plugin = FakePlugin()
admin_context = context.get_admin_context() admin_context = context.get_admin_context()
core_plugin.create_or_update_agent(admin_context, agent) plugin.create_or_update_agent(admin_context, agent)
return core_plugin.get_agents_db( return plugin._get_agent_by_type_and_host(
admin_context, admin_context, agent['agent_type'], agent['host'])
filters={'host': [agent['host']],
'agent_type': [agent['agent_type']]})[0]
def register_l3_agent(host=HOST, agent_mode=constants.L3_AGENT_MODE_LEGACY, def register_l3_agent(host=HOST, agent_mode=constants.L3_AGENT_MODE_LEGACY,
@ -68,3 +75,46 @@ def register_l3_agent(host=HOST, agent_mode=constants.L3_AGENT_MODE_LEGACY,
agent = _get_l3_agent_dict(host, agent_mode, internal_only, ext_net_id, agent = _get_l3_agent_dict(host, agent_mode, internal_only, ext_net_id,
ext_bridge, router_id) ext_bridge, router_id)
return _register_agent(agent) return _register_agent(agent)
def _get_dhcp_agent_dict(host, networks=0):
agent = {
'binary': 'neutron-dhcp-agent',
'host': host,
'topic': topics.DHCP_AGENT,
'agent_type': constants.AGENT_TYPE_DHCP,
'configurations': {'dhcp_driver': 'dhcp_driver',
'use_namespaces': True,
'networks': networks}}
return agent
def register_dhcp_agent(host=HOST, networks=0, admin_state_up=True,
alive=True):
agent = _register_agent(
_get_dhcp_agent_dict(host, networks))
if not admin_state_up:
set_agent_admin_state(agent['id'])
if not alive:
kill_agent(agent['id'])
return FakePlugin()._get_agent_by_type_and_host(
context.get_admin_context(), agent['agent_type'], agent['host'])
def kill_agent(agent_id):
hour_ago = timeutils.utcnow() - datetime.timedelta(hours=1)
FakePlugin().update_agent(
context.get_admin_context(),
agent_id,
{'agent': {
'started_at': hour_ago,
'heartbeat_timestamp': hour_ago}})
def set_agent_admin_state(agent_id, admin_state_up=False):
FakePlugin().update_agent(
context.get_admin_context(),
agent_id,
{'agent': {'admin_state_up': admin_state_up}})

View File

@ -167,8 +167,9 @@ class TestWeightScheduleNetwork(test_dhcp_sch.TestDhcpSchedulerBaseTestCase,
sorted_unscheduled_active_agents = sorted( sorted_unscheduled_active_agents = sorted(
unscheduled_active_agents, unscheduled_active_agents,
key=attrgetter('load'))[0:self.expected_scheduled_agent_count] key=attrgetter('load'))[0:self.expected_scheduled_agent_count]
self.assertItemsEqual(actual_scheduled_agents, self.assertItemsEqual(
sorted_unscheduled_active_agents) (agent['id'] for agent in actual_scheduled_agents),
(agent['id'] for agent in sorted_unscheduled_active_agents))
self.assertEqual(self.expected_scheduled_agent_count, self.assertEqual(self.expected_scheduled_agent_count,
len(actual_scheduled_agents)) len(actual_scheduled_agents))
hosted_agents = self.list_dhcp_agents_hosting_network( hosted_agents = self.list_dhcp_agents_hosting_network(

View File

@ -42,7 +42,6 @@ L3_HOSTA = 'hosta'
DHCP_HOSTA = 'hosta' DHCP_HOSTA = 'hosta'
L3_HOSTB = 'hostb' L3_HOSTB = 'hostb'
DHCP_HOSTC = 'hostc' DHCP_HOSTC = 'hostc'
DHCP_HOST1 = 'host1'
LBAAS_HOSTA = 'hosta' LBAAS_HOSTA = 'hosta'
LBAAS_HOSTB = 'hostb' LBAAS_HOSTB = 'hostb'
@ -89,36 +88,24 @@ class AgentDBTestMixIn(object):
L3_HOSTA, constants.L3_AGENT_MODE_LEGACY) L3_HOSTA, constants.L3_AGENT_MODE_LEGACY)
l3_hostb = helpers._get_l3_agent_dict( l3_hostb = helpers._get_l3_agent_dict(
L3_HOSTB, constants.L3_AGENT_MODE_LEGACY) L3_HOSTB, constants.L3_AGENT_MODE_LEGACY)
dhcp_hosta = { dhcp_hosta = helpers._get_dhcp_agent_dict(DHCP_HOSTA)
'binary': 'neutron-dhcp-agent', dhcp_hostc = helpers._get_dhcp_agent_dict(DHCP_HOSTC)
'host': DHCP_HOSTA,
'topic': 'DHCP_AGENT',
'configurations': {'dhcp_driver': 'dhcp_driver',
'use_namespaces': True,
},
'agent_type': constants.AGENT_TYPE_DHCP}
dhcp_hostc = copy.deepcopy(dhcp_hosta)
dhcp_hostc['host'] = DHCP_HOSTC
lbaas_hosta = {
'binary': 'neutron-loadbalancer-agent',
'host': LBAAS_HOSTA,
'topic': 'LOADBALANCER_AGENT',
'configurations': {'device_drivers': ['haproxy_ns']},
'agent_type': constants.AGENT_TYPE_LOADBALANCER}
lbaas_hostb = copy.deepcopy(lbaas_hosta)
lbaas_hostb['host'] = LBAAS_HOSTB
callback = agents_db.AgentExtRpcCallback()
helpers.register_l3_agent(host=L3_HOSTA) helpers.register_l3_agent(host=L3_HOSTA)
helpers.register_l3_agent(host=L3_HOSTB) helpers.register_l3_agent(host=L3_HOSTB)
callback.report_state(self.adminContext, helpers.register_dhcp_agent(host=DHCP_HOSTA)
agent_state={'agent_state': dhcp_hosta}, helpers.register_dhcp_agent(host=DHCP_HOSTC)
time=timeutils.strtime())
callback.report_state(self.adminContext,
agent_state={'agent_state': dhcp_hostc},
time=timeutils.strtime())
res = [l3_hosta, l3_hostb, dhcp_hosta, dhcp_hostc] res = [l3_hosta, l3_hostb, dhcp_hosta, dhcp_hostc]
if lbaas_agents: if lbaas_agents:
lbaas_hosta = {
'binary': 'neutron-loadbalancer-agent',
'host': LBAAS_HOSTA,
'topic': 'LOADBALANCER_AGENT',
'configurations': {'device_drivers': ['haproxy_ns']},
'agent_type': constants.AGENT_TYPE_LOADBALANCER}
lbaas_hostb = copy.deepcopy(lbaas_hosta)
lbaas_hostb['host'] = LBAAS_HOSTB
callback = agents_db.AgentExtRpcCallback()
callback.report_state(self.adminContext, callback.report_state(self.adminContext,
agent_state={'agent_state': lbaas_hosta}, agent_state={'agent_state': lbaas_hosta},
time=timeutils.strtime()) time=timeutils.strtime())
@ -129,22 +116,6 @@ class AgentDBTestMixIn(object):
return res return res
def _register_one_dhcp_agent(self):
"""Register one DHCP agent."""
dhcp_host = {
'binary': 'neutron-dhcp-agent',
'host': DHCP_HOST1,
'topic': 'DHCP_AGENT',
'configurations': {'dhcp_driver': 'dhcp_driver',
'use_namespaces': True,
},
'agent_type': constants.AGENT_TYPE_DHCP}
callback = agents_db.AgentExtRpcCallback()
callback.report_state(self.adminContext,
agent_state={'agent_state': dhcp_host},
time=timeutils.strtime())
return [dhcp_host]
class AgentDBTestCase(AgentDBTestMixIn, class AgentDBTestCase(AgentDBTestMixIn,
test_db_base_plugin_v2.NeutronDbPluginV2TestCase): test_db_base_plugin_v2.NeutronDbPluginV2TestCase):
@ -170,13 +141,6 @@ class AgentDBTestCase(AgentDBTestMixIn,
def test_list_agent(self): def test_list_agent(self):
agents = self._register_agent_states() agents = self._register_agent_states()
res = self._list('agents') res = self._list('agents')
for agt in res['agents']:
if (agt['host'] == DHCP_HOSTA and
agt['agent_type'] == constants.AGENT_TYPE_DHCP):
self.assertEqual(
'dhcp_driver',
agt['configurations']['dhcp_driver'])
break
self.assertEqual(len(agents), len(res['agents'])) self.assertEqual(len(agents), len(res['agents']))
def test_show_agent(self): def test_show_agent(self):

View File

@ -14,14 +14,12 @@
# limitations under the License. # limitations under the License.
import contextlib import contextlib
import copy
import datetime import datetime
import mock import mock
from oslo_config import cfg from oslo_config import cfg
from oslo_db import exception as db_exc from oslo_db import exception as db_exc
import oslo_messaging import oslo_messaging
from oslo_utils import timeutils
from webob import exc from webob import exc
from neutron.api import extensions from neutron.api import extensions
@ -182,46 +180,26 @@ class AgentSchedulerTestMixIn(object):
event_types = [event['event_type'] for event in notifications] event_types = [event['event_type'] for event in notifications]
self.assertIn(expected_event_type, event_types) self.assertIn(expected_event_type, event_types)
def _register_one_agent_state(self, agent_state):
callback = agents_db.AgentExtRpcCallback()
callback.report_state(self.adminContext,
agent_state={'agent_state': agent_state},
time=timeutils.strtime())
def test_agent_registration_bad_timestamp(self): def test_agent_registration_bad_timestamp(self):
dhcp_hosta = {
'binary': 'neutron-dhcp-agent',
'host': DHCP_HOSTA,
'start_flag': True,
'topic': 'DHCP_AGENT',
'configurations': {'dhcp_driver': 'dhcp_driver',
'use_namespaces': True,
},
'agent_type': constants.AGENT_TYPE_DHCP}
callback = agents_db.AgentExtRpcCallback() callback = agents_db.AgentExtRpcCallback()
delta_time = datetime.datetime.now() - datetime.timedelta(days=1) delta_time = datetime.datetime.now() - datetime.timedelta(days=1)
str_time = delta_time.strftime('%Y-%m-%dT%H:%M:%S.%f') str_time = delta_time.strftime('%Y-%m-%dT%H:%M:%S.%f')
callback.report_state(self.adminContext, callback.report_state(
agent_state={'agent_state': dhcp_hosta}, self.adminContext,
time=str_time) agent_state={
'agent_state': helpers._get_dhcp_agent_dict(DHCP_HOSTA)},
time=str_time)
def test_agent_registration_invalid_timestamp_allowed(self): def test_agent_registration_invalid_timestamp_allowed(self):
dhcp_hosta = {
'binary': 'neutron-dhcp-agent',
'host': DHCP_HOSTA,
'start_flag': True,
'topic': 'DHCP_AGENT',
'configurations': {'dhcp_driver': 'dhcp_driver',
'use_namespaces': True,
},
'agent_type': constants.AGENT_TYPE_DHCP}
callback = agents_db.AgentExtRpcCallback() callback = agents_db.AgentExtRpcCallback()
utc_time = datetime.datetime.utcnow() utc_time = datetime.datetime.utcnow()
delta_time = utc_time - datetime.timedelta(seconds=10) delta_time = utc_time - datetime.timedelta(seconds=10)
str_time = delta_time.strftime('%Y-%m-%dT%H:%M:%S.%f') str_time = delta_time.strftime('%Y-%m-%dT%H:%M:%S.%f')
callback.report_state(self.adminContext, callback.report_state(
agent_state={'agent_state': dhcp_hosta}, self.adminContext,
time=str_time) agent_state={
'agent_state': helpers._get_dhcp_agent_dict(DHCP_HOSTA)},
time=str_time)
def _disable_agent(self, agent_id, admin_state_up=False): def _disable_agent(self, agent_id, admin_state_up=False):
new_agent = {} new_agent = {}
@ -393,27 +371,17 @@ class OvsAgentSchedulerTestCase(OvsAgentSchedulerTestCaseBase):
def test_network_auto_schedule_with_hosted_2(self): def test_network_auto_schedule_with_hosted_2(self):
# one agent hosts one network # one agent hosts one network
dhcp_rpc_cb = dhcp_rpc.DhcpRpcCallback() dhcp_rpc_cb = dhcp_rpc.DhcpRpcCallback()
dhcp_hosta = {
'binary': 'neutron-dhcp-agent',
'host': DHCP_HOSTA,
'topic': 'DHCP_AGENT',
'configurations': {'dhcp_driver': 'dhcp_driver',
'use_namespaces': True,
},
'agent_type': constants.AGENT_TYPE_DHCP}
dhcp_hostc = copy.deepcopy(dhcp_hosta)
dhcp_hostc['host'] = DHCP_HOSTC
cfg.CONF.set_override('allow_overlapping_ips', True) cfg.CONF.set_override('allow_overlapping_ips', True)
with self.subnet() as sub1: with self.subnet() as sub1:
self._register_one_agent_state(dhcp_hosta) helpers.register_dhcp_agent(DHCP_HOSTA)
dhcp_rpc_cb.get_active_networks(self.adminContext, host=DHCP_HOSTA) dhcp_rpc_cb.get_active_networks(self.adminContext, host=DHCP_HOSTA)
hosta_id = self._get_agent_id(constants.AGENT_TYPE_DHCP, hosta_id = self._get_agent_id(constants.AGENT_TYPE_DHCP,
DHCP_HOSTA) DHCP_HOSTA)
self._disable_agent(hosta_id, admin_state_up=False) self._disable_agent(hosta_id, admin_state_up=False)
with self.subnet() as sub2: with self.subnet() as sub2:
self._register_one_agent_state(dhcp_hostc) helpers.register_dhcp_agent(DHCP_HOSTC)
dhcp_rpc_cb.get_active_networks(self.adminContext, dhcp_rpc_cb.get_active_networks(self.adminContext,
host=DHCP_HOSTC) host=DHCP_HOSTC)
dhcp_agents_1 = self._list_dhcp_agents_hosting_network( dhcp_agents_1 = self._list_dhcp_agents_hosting_network(
sub1['subnet']['network_id']) sub1['subnet']['network_id'])
dhcp_agents_2 = self._list_dhcp_agents_hosting_network( dhcp_agents_2 = self._list_dhcp_agents_hosting_network(
@ -474,7 +442,7 @@ class OvsAgentSchedulerTestCase(OvsAgentSchedulerTestCaseBase):
dhcp_agents = self._list_dhcp_agents_hosting_network( dhcp_agents = self._list_dhcp_agents_hosting_network(
port['port']['network_id']) port['port']['network_id'])
result1 = len(dhcp_agents['agents']) result1 = len(dhcp_agents['agents'])
self._register_one_dhcp_agent() helpers.register_dhcp_agent('host1')
with self.port(subnet=subnet, with self.port(subnet=subnet,
device_owner="compute:test:" + DHCP_HOSTA) as port: device_owner="compute:test:" + DHCP_HOSTA) as port:
dhcp_agents = self._list_dhcp_agents_hosting_network( dhcp_agents = self._list_dhcp_agents_hosting_network(
@ -485,15 +453,7 @@ class OvsAgentSchedulerTestCase(OvsAgentSchedulerTestCaseBase):
self.assertEqual(3, result2) self.assertEqual(3, result2)
def test_network_scheduler_with_disabled_agent(self): def test_network_scheduler_with_disabled_agent(self):
dhcp_hosta = { helpers.register_dhcp_agent(DHCP_HOSTA)
'binary': 'neutron-dhcp-agent',
'host': DHCP_HOSTA,
'topic': 'DHCP_AGENT',
'configurations': {'dhcp_driver': 'dhcp_driver',
'use_namespaces': True,
},
'agent_type': constants.AGENT_TYPE_DHCP}
self._register_one_agent_state(dhcp_hosta)
with self.port() as port1: with self.port() as port1:
dhcp_agents = self._list_dhcp_agents_hosting_network( dhcp_agents = self._list_dhcp_agents_hosting_network(
port1['port']['network_id']) port1['port']['network_id'])
@ -530,15 +490,7 @@ class OvsAgentSchedulerTestCase(OvsAgentSchedulerTestCaseBase):
None, None)) None, None))
def test_network_scheduler_with_down_agent(self): def test_network_scheduler_with_down_agent(self):
dhcp_hosta = { helpers.register_dhcp_agent(DHCP_HOSTA)
'binary': 'neutron-dhcp-agent',
'host': DHCP_HOSTA,
'topic': 'DHCP_AGENT',
'configurations': {'dhcp_driver': 'dhcp_driver',
'use_namespaces': True,
},
'agent_type': constants.AGENT_TYPE_DHCP}
self._register_one_agent_state(dhcp_hosta)
eligible_agent_str = ('neutron.db.agentschedulers_db.' eligible_agent_str = ('neutron.db.agentschedulers_db.'
'DhcpAgentSchedulerDbMixin.is_eligible_agent') 'DhcpAgentSchedulerDbMixin.is_eligible_agent')
with mock.patch(eligible_agent_str) as eligible_agent: with mock.patch(eligible_agent_str) as eligible_agent:
@ -560,15 +512,7 @@ class OvsAgentSchedulerTestCase(OvsAgentSchedulerTestCaseBase):
def test_network_scheduler_with_hosted_network(self): def test_network_scheduler_with_hosted_network(self):
plugin = manager.NeutronManager.get_plugin() plugin = manager.NeutronManager.get_plugin()
dhcp_hosta = { helpers.register_dhcp_agent(DHCP_HOSTA)
'binary': 'neutron-dhcp-agent',
'host': DHCP_HOSTA,
'topic': 'DHCP_AGENT',
'configurations': {'dhcp_driver': 'dhcp_driver',
'use_namespaces': True,
},
'agent_type': constants.AGENT_TYPE_DHCP}
self._register_one_agent_state(dhcp_hosta)
with self.port() as port1: with self.port() as port1:
dhcp_agents = self._list_dhcp_agents_hosting_network( dhcp_agents = self._list_dhcp_agents_hosting_network(
port1['port']['network_id']) port1['port']['network_id'])
@ -640,17 +584,8 @@ class OvsAgentSchedulerTestCase(OvsAgentSchedulerTestCaseBase):
self._test_network_add_to_dhcp_agent(admin_state_up=False) self._test_network_add_to_dhcp_agent(admin_state_up=False)
def test_network_remove_from_dhcp_agent(self): def test_network_remove_from_dhcp_agent(self):
dhcp_hosta = { agent = helpers.register_dhcp_agent(DHCP_HOSTA)
'binary': 'neutron-dhcp-agent', hosta_id = agent.id
'host': DHCP_HOSTA,
'topic': 'DHCP_AGENT',
'configurations': {'dhcp_driver': 'dhcp_driver',
'use_namespaces': True,
},
'agent_type': constants.AGENT_TYPE_DHCP}
self._register_one_agent_state(dhcp_hosta)
hosta_id = self._get_agent_id(constants.AGENT_TYPE_DHCP,
DHCP_HOSTA)
with self.port() as port1: with self.port() as port1:
num_before_remove = len( num_before_remove = len(
self._list_networks_hosted_by_dhcp_agent( self._list_networks_hosted_by_dhcp_agent(
@ -670,15 +605,7 @@ class OvsAgentSchedulerTestCase(OvsAgentSchedulerTestCaseBase):
self.assertEqual([], nets) self.assertEqual([], nets)
def test_reserved_port_after_network_remove_from_dhcp_agent(self): def test_reserved_port_after_network_remove_from_dhcp_agent(self):
dhcp_hosta = { helpers.register_dhcp_agent(DHCP_HOSTA)
'binary': 'neutron-dhcp-agent',
'host': DHCP_HOSTA,
'topic': 'DHCP_AGENT',
'configurations': {'dhcp_driver': 'dhcp_driver',
'use_namespaces': True,
},
'agent_type': constants.AGENT_TYPE_DHCP}
self._register_one_agent_state(dhcp_hosta)
hosta_id = self._get_agent_id(constants.AGENT_TYPE_DHCP, hosta_id = self._get_agent_id(constants.AGENT_TYPE_DHCP,
DHCP_HOSTA) DHCP_HOSTA)
with self.port(device_owner=constants.DEVICE_OWNER_DHCP, with self.port(device_owner=constants.DEVICE_OWNER_DHCP,
@ -698,15 +625,7 @@ class OvsAgentSchedulerTestCase(OvsAgentSchedulerTestCaseBase):
if keep_services: if keep_services:
cfg.CONF.set_override( cfg.CONF.set_override(
'enable_services_on_agents_with_admin_state_down', True) 'enable_services_on_agents_with_admin_state_down', True)
dhcp_hosta = { helpers.register_dhcp_agent(DHCP_HOSTA)
'binary': 'neutron-dhcp-agent',
'host': DHCP_HOSTA,
'topic': 'DHCP_AGENT',
'configurations': {'dhcp_driver': 'dhcp_driver',
'use_namespaces': True,
},
'agent_type': constants.AGENT_TYPE_DHCP}
self._register_one_agent_state(dhcp_hosta)
dhcp_rpc_cb = dhcp_rpc.DhcpRpcCallback() dhcp_rpc_cb = dhcp_rpc.DhcpRpcCallback()
with self.port(): with self.port():
nets = dhcp_rpc_cb.get_active_networks(self.adminContext, nets = dhcp_rpc_cb.get_active_networks(self.adminContext,
@ -1312,15 +1231,9 @@ class OvsDhcpAgentNotifierTestCase(test_l3.L3NatTestCaseMixin,
{'admin_state_up': False}, DHCP_HOSTA) {'admin_state_up': False}, DHCP_HOSTA)
def _network_port_create( def _network_port_create(
self, hosts, gateway=attributes.ATTR_NOT_SPECIFIED, owner=None): self, hosts, gateway=attributes.ATTR_NOT_SPECIFIED, owner=None):
for host in hosts: for host in hosts:
self._register_one_agent_state( helpers.register_dhcp_agent(host)
{'binary': 'neutron-dhcp-agent',
'host': host,
'topic': 'dhcp_agent',
'configurations': {'dhcp_driver': 'dhcp_driver',
'use_namespaces': True, },
'agent_type': constants.AGENT_TYPE_DHCP})
with self.network() as net1: with self.network() as net1:
with self.subnet(network=net1, with self.subnet(network=net1,
gateway_ip=gateway) as subnet1: gateway_ip=gateway) as subnet1:
@ -1493,12 +1406,10 @@ class OvsL3AgentNotifierTestCase(test_l3.L3NatTestCaseMixin,
) as ( ) as (
mock_prepare, mock_cast mock_prepare, mock_cast
): ):
self._register_agent_states() agent_id = helpers.register_l3_agent(L3_HOSTA).id
hosta_id = self._get_agent_id(constants.AGENT_TYPE_L3, self._disable_agent(agent_id, admin_state_up=False)
L3_HOSTA)
self._disable_agent(hosta_id, admin_state_up=False)
mock_prepare.assert_called_with(server='hosta') mock_prepare.assert_called_with(server=L3_HOSTA)
mock_cast.assert_called_with( mock_cast.assert_called_with(
mock.ANY, 'agent_updated', payload={'admin_state_up': False}) mock.ANY, 'agent_updated', payload={'admin_state_up': False})

View File

@ -14,27 +14,27 @@
# limitations under the License. # limitations under the License.
import contextlib import contextlib
import datetime
import mock import mock
from oslo_config import cfg from oslo_config import cfg
from oslo_utils import importutils from oslo_utils import importutils
from oslo_utils import timeutils
import testscenarios import testscenarios
from neutron.common import constants from neutron.common import constants
from neutron.common import topics
from neutron import context from neutron import context
from neutron.db import agents_db
from neutron.db import agentschedulers_db as sched_db from neutron.db import agentschedulers_db as sched_db
from neutron.db import models_v2 from neutron.db import models_v2
from neutron.extensions import dhcpagentscheduler from neutron.extensions import dhcpagentscheduler
from neutron.scheduler import dhcp_agent_scheduler from neutron.scheduler import dhcp_agent_scheduler
from neutron.tests.common import helpers
from neutron.tests.unit import testlib_api from neutron.tests.unit import testlib_api
# Required to generate tests from scenarios. Not compatible with nose. # Required to generate tests from scenarios. Not compatible with nose.
load_tests = testscenarios.load_tests_apply_scenarios load_tests = testscenarios.load_tests_apply_scenarios
HOST_C = 'host-c'
HOST_D = 'host-d'
class TestDhcpSchedulerBaseTestCase(testlib_api.SqlTestCase): class TestDhcpSchedulerBaseTestCase(testlib_api.SqlTestCase):
@ -45,37 +45,16 @@ class TestDhcpSchedulerBaseTestCase(testlib_api.SqlTestCase):
self.network_id = 'foo_network_id' self.network_id = 'foo_network_id'
self._save_networks([self.network_id]) self._save_networks([self.network_id])
def _get_agents(self, hosts): def _create_and_set_agents_down(self, hosts, down_agent_count=0,
return [ admin_state_up=True):
agents_db.Agent( agents = []
binary='neutron-dhcp-agent', for i, host in enumerate(hosts):
host=host, is_alive = i >= down_agent_count
topic=topics.DHCP_AGENT, agents.append(helpers.register_dhcp_agent(
configurations="", host,
agent_type=constants.AGENT_TYPE_DHCP, admin_state_up=admin_state_up,
created_at=timeutils.utcnow(), alive=is_alive))
started_at=timeutils.utcnow(), return agents
heartbeat_timestamp=timeutils.utcnow())
for host in hosts
]
def _save_agents(self, agents):
for agent in agents:
with self.ctx.session.begin(subtransactions=True):
self.ctx.session.add(agent)
def _create_and_set_agents_down(self, hosts, down_agent_count=0, **kwargs):
dhcp_agents = self._get_agents(hosts)
# bring down the specified agents
for agent in dhcp_agents[:down_agent_count]:
old_time = agent['heartbeat_timestamp']
hour_old = old_time - datetime.timedelta(hours=1)
agent['heartbeat_timestamp'] = hour_old
agent['started_at'] = hour_old
for agent in dhcp_agents:
agent.update(kwargs)
self._save_agents(dhcp_agents)
return dhcp_agents
def _save_networks(self, networks): def _save_networks(self, networks):
for network_id in networks: for network_id in networks:
@ -273,26 +252,6 @@ class TestNetworksFailover(TestDhcpSchedulerBaseTestCase,
class DHCPAgentWeightSchedulerTestCase(TestDhcpSchedulerBaseTestCase): class DHCPAgentWeightSchedulerTestCase(TestDhcpSchedulerBaseTestCase):
"""Unit test scenarios for WeightScheduler.schedule.""" """Unit test scenarios for WeightScheduler.schedule."""
hostc = {
'binary': 'neutron-dhcp-agent',
'host': 'host-c',
'topic': 'DHCP_AGENT',
'configurations': {'dhcp_driver': 'dhcp_driver',
'networks': 0,
'use_namespaces': True,
},
'agent_type': constants.AGENT_TYPE_DHCP}
hostd = {
'binary': 'neutron-dhcp-agent',
'host': 'host-d',
'topic': 'DHCP_AGENT',
'configurations': {'dhcp_driver': 'dhcp_driver',
'networks': 1,
'use_namespaces': True,
},
'agent_type': constants.AGENT_TYPE_DHCP}
def setUp(self): def setUp(self):
super(DHCPAgentWeightSchedulerTestCase, self).setUp() super(DHCPAgentWeightSchedulerTestCase, self).setUp()
DB_PLUGIN_KLASS = 'neutron.plugins.ml2.plugin.Ml2Plugin' DB_PLUGIN_KLASS = 'neutron.plugins.ml2.plugin.Ml2Plugin'
@ -313,10 +272,9 @@ class DHCPAgentWeightSchedulerTestCase(TestDhcpSchedulerBaseTestCase):
cfg.CONF.set_override("dhcp_load_type", "networks") cfg.CONF.set_override("dhcp_load_type", "networks")
def test_scheduler_one_agents_per_network(self): def test_scheduler_one_agents_per_network(self):
cfg.CONF.set_override('dhcp_agents_per_network', 1)
self._save_networks(['1111']) self._save_networks(['1111'])
agents = self._get_agents(['host-c', 'host-d']) helpers.register_dhcp_agent(HOST_C)
self._save_agents(agents) helpers.register_dhcp_agent(HOST_C)
self.plugin.network_scheduler.schedule(self.plugin, self.ctx, self.plugin.network_scheduler.schedule(self.plugin, self.ctx,
{'id': '1111'}) {'id': '1111'})
agents = self.plugin.get_dhcp_agents_hosting_networks(self.ctx, agents = self.plugin.get_dhcp_agents_hosting_networks(self.ctx,
@ -326,8 +284,8 @@ class DHCPAgentWeightSchedulerTestCase(TestDhcpSchedulerBaseTestCase):
def test_scheduler_two_agents_per_network(self): def test_scheduler_two_agents_per_network(self):
cfg.CONF.set_override('dhcp_agents_per_network', 2) cfg.CONF.set_override('dhcp_agents_per_network', 2)
self._save_networks(['1111']) self._save_networks(['1111'])
agents = self._get_agents(['host-c', 'host-d']) helpers.register_dhcp_agent(HOST_C)
self._save_agents(agents) helpers.register_dhcp_agent(HOST_D)
self.plugin.network_scheduler.schedule(self.plugin, self.ctx, self.plugin.network_scheduler.schedule(self.plugin, self.ctx,
{'id': '1111'}) {'id': '1111'})
agents = self.plugin.get_dhcp_agents_hosting_networks(self.ctx, agents = self.plugin.get_dhcp_agents_hosting_networks(self.ctx,
@ -343,37 +301,23 @@ class DHCPAgentWeightSchedulerTestCase(TestDhcpSchedulerBaseTestCase):
self.assertEqual(0, len(agents)) self.assertEqual(0, len(agents))
def test_scheduler_equal_distribution(self): def test_scheduler_equal_distribution(self):
cfg.CONF.set_override('dhcp_agents_per_network', 1)
self._save_networks(['1111', '2222', '3333']) self._save_networks(['1111', '2222', '3333'])
agents = self._get_agents(['host-c', 'host-d']) helpers.register_dhcp_agent(HOST_C)
self._save_agents(agents) helpers.register_dhcp_agent(HOST_D, networks=1)
callback = agents_db.AgentExtRpcCallback() self.plugin.network_scheduler.schedule(
callback.report_state(self.ctx, self.plugin, context.get_admin_context(), {'id': '1111'})
agent_state={'agent_state': self.hostc}, helpers.register_dhcp_agent(HOST_D, networks=2)
time=timeutils.strtime()) self.plugin.network_scheduler.schedule(
callback.report_state(self.ctx, self.plugin, context.get_admin_context(), {'id': '2222'})
agent_state={'agent_state': self.hostd}, helpers.register_dhcp_agent(HOST_C, networks=4)
time=timeutils.strtime()) self.plugin.network_scheduler.schedule(
self.plugin.network_scheduler.schedule(self.plugin, self.ctx, self.plugin, context.get_admin_context(), {'id': '3333'})
{'id': '1111'}) agent1 = self.plugin.get_dhcp_agents_hosting_networks(
agent1 = self.plugin.get_dhcp_agents_hosting_networks(self.ctx, self.ctx, ['1111'])
['1111']) agent2 = self.plugin.get_dhcp_agents_hosting_networks(
self.hostd['configurations']['networks'] = 2 self.ctx, ['2222'])
callback.report_state(self.ctx, agent3 = self.plugin.get_dhcp_agents_hosting_networks(
agent_state={'agent_state': self.hostd}, self.ctx, ['3333'])
time=timeutils.strtime())
self.plugin.network_scheduler.schedule(self.plugin, self.ctx,
{'id': '2222'})
agent2 = self.plugin.get_dhcp_agents_hosting_networks(self.ctx,
['2222'])
self.hostc['configurations']['networks'] = 4
callback.report_state(self.ctx,
agent_state={'agent_state': self.hostc},
time=timeutils.strtime())
self.plugin.network_scheduler.schedule(self.plugin, self.ctx,
{'id': '3333'})
agent3 = self.plugin.get_dhcp_agents_hosting_networks(self.ctx,
['3333'])
self.assertEqual('host-c', agent1[0]['host']) self.assertEqual('host-c', agent1[0]['host'])
self.assertEqual('host-c', agent2[0]['host']) self.assertEqual('host-c', agent2[0]['host'])
self.assertEqual('host-d', agent3[0]['host']) self.assertEqual('host-d', agent3[0]['host'])