def bind(self, context, agents, network_id): """Bind the network to the agents.""" # customize the bind logic bound_agents = agents[:] for agent in agents: # saving agent_id to use it after rollback to avoid # DetachedInstanceError agent_id = agent.id binding = ndab_model.NetworkDhcpAgentBinding() binding.dhcp_agent_id = agent_id binding.network_id = network_id try: with db_api.autonested_transaction(context.session): context.session.add(binding) # try to actually write the changes and catch integrity # DBDuplicateEntry except db_exc.DBDuplicateEntry: # it's totally ok, someone just did our job! bound_agents.remove(agent) LOG.info('Agent %s already present', agent_id) LOG.debug( 'Network %(network_id)s is scheduled to be ' 'hosted by DHCP agent %(agent_id)s', { 'network_id': network_id, 'agent_id': agent_id }) super(DhcpFilter, self).bind(context, bound_agents, network_id)
def test_filter_bindings(self): bindings = [ ndab_model.NetworkDhcpAgentBinding(network_id='foo1', dhcp_agent={'id': 'id1'}), ndab_model.NetworkDhcpAgentBinding(network_id='foo2', dhcp_agent={'id': 'id1'}), ndab_model.NetworkDhcpAgentBinding(network_id='foo3', dhcp_agent={'id': 'id2'}), ndab_model.NetworkDhcpAgentBinding(network_id='foo4', dhcp_agent={'id': 'id2'})] with mock.patch.object(self, 'agent_starting_up', side_effect=[True, False]): res = [b for b in self._filter_bindings(None, bindings)] # once per each agent id1 and id2 self.assertEqual(2, len(res)) res_ids = [b.network_id for b in res] self.assertIn('foo3', res_ids) self.assertIn('foo4', res_ids)
def add_network_to_dhcp_agent(self, context, id, network_id): self._get_network(context, network_id) with context.session.begin(subtransactions=True): agent_db = self._get_agent(context, id) if (agent_db['agent_type'] != constants.AGENT_TYPE_DHCP or not services_available(agent_db['admin_state_up'])): raise dhcpagentscheduler.InvalidDHCPAgent(id=id) dhcp_agents = self.get_dhcp_agents_hosting_networks( context, [network_id]) for dhcp_agent in dhcp_agents: if id == dhcp_agent.id: raise dhcpagentscheduler.NetworkHostedByDHCPAgent( network_id=network_id, agent_id=id) binding = ndab_model.NetworkDhcpAgentBinding() binding.dhcp_agent_id = id binding.network_id = network_id context.session.add(binding) dhcp_notifier = self.agent_notifiers.get(constants.AGENT_TYPE_DHCP) if dhcp_notifier: dhcp_notifier.network_added_to_agent( context, network_id, agent_db.host)