Beispiel #1
0
def _update_segment_host_mapping_for_agent(resource, event, trigger,
                                           payload=None):
    plugin = payload.metadata.get('plugin')
    agent = payload.desired_state
    host = payload.metadata.get('host')
    context = payload.context

    check_segment_for_agent = getattr(plugin, 'check_segment_for_agent', None)
    if (not check_user_configured_segment_plugin() or
            not check_segment_for_agent):
        return
    phys_nets = _get_phys_nets(agent)
    if not phys_nets:
        return
    start_flag = agent.get('start_flag', None)
    if host in reported_hosts and not start_flag:
        return
    reported_hosts.add(host)
    segments = get_segments_with_phys_nets(context, phys_nets)
    current_segment_ids = {
        segment['id'] for segment in segments
        if check_segment_for_agent(segment, agent)}
    update_segment_host_mapping(context, host, current_segment_ids)
    registry.notify(resources.SEGMENT_HOST_MAPPING, events.AFTER_CREATE,
                    plugin, context=context, host=host,
                    current_segment_ids=current_segment_ids)
Beispiel #2
0
    def record_resource_update(self, context, rtype, resource):
        """Takes in an OVO and generates an event on relevant changes.

        A change is deemed to be relevant if it is not stale and if any
        fields changed beyond the revision number and update time.

        Both creates and updates are handled in this function.
        """
        if self._is_stale(rtype, resource):
            LOG.debug("Ignoring stale update for %s: %s", rtype, resource)
            return
        existing = self._type_cache(rtype).get(resource.id)
        self._type_cache(rtype)[resource.id] = resource
        changed_fields = self._get_changed_fields(existing, resource)
        if not changed_fields:
            LOG.debug("Received resource %s update without any changes: %s",
                      rtype, resource.id)
            return
        if existing:
            LOG.debug("Resource %s %s updated (revision_number %s->%s). "
                      "Old fields: %s New fields: %s",
                      rtype, existing.id, existing.revision_number,
                      resource.revision_number,
                      {f: existing.get(f) for f in changed_fields},
                      {f: resource.get(f) for f in changed_fields})
        else:
            LOG.debug("Received new resource %s: %s", rtype, resource)
        # local notification for agent internals to subscribe to
        registry.notify(rtype, events.AFTER_UPDATE, self,
                        context=context, changed_fields=changed_fields,
                        existing=existing, updated=resource,
                        resource_id=resource.id)
Beispiel #3
0
    def delete_segment(self, context, uuid, for_net_delete=False):
        """Delete an existing segment."""
        segment_dict = self.get_segment(context, uuid)
        # Do some preliminary operations before deleting the segment
        registry.publish(resources.SEGMENT, events.BEFORE_DELETE,
                         self.delete_segment,
                         payload=events.DBEventPayload(
                             context, metadata={
                                 'for_net_delete': for_net_delete},
                             states=(segment_dict,),
                             resource_id=uuid))

        # Delete segment in DB
        with db_api.CONTEXT_WRITER.using(context):
            if not network.NetworkSegment.delete_objects(context, id=uuid):
                raise exceptions.SegmentNotFound(segment_id=uuid)
            # Do some preliminary operations before deleting segment in db
            registry.notify(resources.SEGMENT, events.PRECOMMIT_DELETE,
                            self.delete_segment, context=context,
                            segment=segment_dict)

        registry.publish(resources.SEGMENT, events.AFTER_DELETE,
                         self.delete_segment,
                         payload=events.DBEventPayload(
                             context, states=(segment_dict,),
                             resource_id=uuid))
Beispiel #4
0
    def _validate_router_migration(self, context, router_db, router_res):
        """Allow transition only when admin_state_up=False"""
        original_distributed_state = router_db.extra_attributes.distributed
        requested_distributed_state = router_res.get('distributed', None)

        distributed_changed = (
            requested_distributed_state is not None and
            requested_distributed_state != original_distributed_state)
        if not distributed_changed:
            return False
        if router_db.admin_state_up:
            msg = _("Cannot change the 'distributed' attribute of active "
                    "routers. Please set router admin_state_up to False "
                    "prior to upgrade")
            raise n_exc.BadRequest(resource='router', msg=msg)

        # Notify advanced services of the imminent state transition
        # for the router.
        try:
            kwargs = {'context': context, 'router': router_db}
            registry.notify(
                resources.ROUTER, events.BEFORE_UPDATE, self, **kwargs)
        except exceptions.CallbackFailure as e:
            # NOTE(armax): preserve old check's behavior
            if len(e.errors) == 1:
                raise e.errors[0].error
            raise l3.RouterInUse(router_id=router_db['id'], reason=e)
        return True
Beispiel #5
0
 def test_subscribe_address_scope_of_subnetpool(self, gp):
     l3_db.L3RpcNotifierMixin()
     registry.notify(resources.SUBNETPOOL_ADDRESS_SCOPE,
                     events.AFTER_UPDATE, mock.ANY,
                     context=mock.MagicMock(),
                     subnetpool_id='fake_id')
     self.assertTrue(gp.return_value.notify_routers_updated.called)
Beispiel #6
0
    def update_security_group(self, context, id, security_group):
        s = security_group['security_group']

        kwargs = {
            'context': context,
            'security_group_id': id,
            'security_group': s,
        }
        self._registry_notify(resources.SECURITY_GROUP, events.BEFORE_UPDATE,
                              exc_cls=ext_sg.SecurityGroupConflict, **kwargs)

        with db_api.CONTEXT_WRITER.using(context):
            sg = self._get_security_group(context, id)
            if sg.name == 'default' and 'name' in s:
                raise ext_sg.SecurityGroupCannotUpdateDefault()
            sg_dict = self._make_security_group_dict(sg)
            kwargs['original_security_group'] = sg_dict
            sg.update_fields(s)
            sg.update()
            sg_dict = self._make_security_group_dict(sg)
            kwargs['security_group'] = sg_dict
            self._registry_notify(
                    resources.SECURITY_GROUP,
                    events.PRECOMMIT_UPDATE,
                    exc_cls=ext_sg.SecurityGroupConflict,
                    payload=events.DBEventPayload(
                        context, request_body=s,
                        states=(kwargs['original_security_group'],),
                        resource_id=id, desired_state=sg_dict))
        registry.notify(resources.SECURITY_GROUP, events.AFTER_UPDATE, self,
                        **kwargs)
        return sg_dict
Beispiel #7
0
 def treat_devices_removed(self, devices):
     resync = False
     self.sg_agent.remove_devices_filter(devices)
     for device in devices:
         LOG.info(_LI("Attachment %s removed"), device)
         details = None
         try:
             details = self.plugin_rpc.update_device_down(self.context,
                                                          device,
                                                          self.agent_id,
                                                          cfg.CONF.host)
         except Exception:
             LOG.exception(_LE("Error occurred while removing port %s"),
                           device)
             resync = True
         if details and details['exists']:
             LOG.info(_LI("Port %s updated."), device)
         else:
             LOG.debug("Device %s not defined on plugin", device)
         port_id = self._clean_network_ports(device)
         self.ext_manager.delete_port(self.context,
                                      {'device': device,
                                       'port_id': port_id})
         registry.notify(local_resources.PORT_DEVICE, events.AFTER_DELETE,
                         self, context=self.context, device=device,
                         port_id=port_id)
     if self.prevent_arp_spoofing:
         self.mgr.delete_arp_spoofing_protection(devices)
     return resync
    def update_security_group(self, context, id, security_group):
        s = security_group['security_group']

        kwargs = {
            'context': context,
            'security_group_id': id,
            'security_group': s,
        }
        self._registry_notify(resources.SECURITY_GROUP, events.BEFORE_UPDATE,
                              exc_cls=ext_sg.SecurityGroupConflict, **kwargs)

        with db_api.context_manager.writer.using(context):
            sg = self._get_security_group(context, id)
            if sg.name == 'default' and 'name' in s:
                raise ext_sg.SecurityGroupCannotUpdateDefault()
            sg_dict = self._make_security_group_dict(sg)
            kwargs['original_security_group'] = sg_dict
            sg.update_fields(s)
            sg.update()
            sg_dict = self._make_security_group_dict(sg)
            kwargs['security_group'] = sg_dict
            self._registry_notify(
                    resources.SECURITY_GROUP,
                    events.PRECOMMIT_UPDATE,
                    exc_cls=ext_sg.SecurityGroupConflict, **kwargs)

        registry.notify(resources.SECURITY_GROUP, events.AFTER_UPDATE, self,
                        **kwargs)
        return sg_dict
Beispiel #9
0
    def _setup_test_create_floatingip(
        self, fip, floatingip_db, router_db):
        port = {
            'id': '1234',
            portbindings.HOST_ID: 'myhost',
            'network_id': 'external_net'
        }

        with mock.patch.object(self.mixin, 'get_router') as grtr,\
                mock.patch.object(self.mixin,
                                  '_get_dvr_service_port_hostid') as vmp,\
                mock.patch.object(
                    self.mixin,
                    '_get_dvr_migrating_service_port_hostid'
                                 ) as mvmp,\
                mock.patch.object(
                    self.mixin,
                    'create_fip_agent_gw_port_if_not_exists') as c_fip,\
                mock.patch.object(l3_dvr_db.l3_db.L3_NAT_db_mixin,
                                  '_update_fip_assoc'):
            grtr.return_value = router_db
            vmp.return_value = 'my-host'
            mvmp.return_value = 'my-future-host'
            registry.notify(resources.FLOATING_IP, events.AFTER_UPDATE, self,
                            context=mock.Mock(), router_id=router_db['id'],
                            fixed_port_id=port['id'], floating_ip_id=fip['id'],
                            floating_network_id=fip['floating_network_id'],
                            fixed_ip_address='1.2.3.4')
            return c_fip
Beispiel #10
0
    def _update(self, request, id, body, **kwargs):
        body = Controller.prepare_request_body(request.context,
                                               body, False,
                                               self._resource, self._attr_info,
                                               allow_bulk=self._allow_bulk)
        action = self._plugin_handlers[self.UPDATE]
        # Load object to check authz
        # but pass only attributes in the original body and required
        # by the policy engine to the policy 'brain'
        field_list = [name for (name, value) in self._attr_info.items()
                      if (value.get('required_by_policy') or
                          value.get('primary_key') or
                          'default' not in value)]
        # Ensure policy engine is initialized
        policy.init()
        parent_id = kwargs.get(self._parent_id_name)
        orig_obj = self._item(request, id, field_list=field_list,
                              parent_id=parent_id)
        orig_object_copy = copy.copy(orig_obj)
        orig_obj.update(body[self._resource])
        # Make a list of attributes to be updated to inform the policy engine
        # which attributes are set explicitly so that it can distinguish them
        # from the ones that are set to their default values.
        orig_obj[n_const.ATTRIBUTES_TO_UPDATE] = body[self._resource].keys()
        try:
            policy.enforce(request.context,
                           action,
                           orig_obj,
                           pluralized=self._collection)
        except oslo_policy.PolicyNotAuthorized:
            # To avoid giving away information, pretend that it
            # doesn't exist if policy does not authorize SHOW
            with excutils.save_and_reraise_exception() as ctxt:
                if not policy.check(request.context,
                                    self._plugin_handlers[self.SHOW],
                                    orig_obj,
                                    pluralized=self._collection):
                    ctxt.reraise = False
            msg = _('The resource could not be found.')
            raise webob.exc.HTTPNotFound(msg)

        obj_updater = getattr(self._plugin, action)
        kwargs = {self._resource: body}
        if parent_id:
            kwargs[self._parent_id_name] = parent_id
        obj = obj_updater(request.context, id, **kwargs)
        # Usually an update operation does not alter resource usage, but as
        # there might be side effects it might be worth checking for changes
        # in resource usage here as well (e.g: a tenant port is created when a
        # router interface is added)
        resource_registry.set_resources_dirty(request.context)

        result = {self._resource: self._view(request.context, obj)}
        notifier_method = self._resource + '.update.end'
        self._notifier.info(request.context, notifier_method, result)
        registry.notify(self._resource, events.BEFORE_RESPONSE, self,
                        context=request.context, data=result,
                        method_name=notifier_method, action=action,
                        original=orig_object_copy)
        return result
Beispiel #11
0
 def _process_added_router(self, router):
     self._router_added(router['id'], router)
     ri = self.router_info[router['id']]
     ri.router = router
     ri.process()
     registry.notify(resources.ROUTER, events.AFTER_CREATE, self, router=ri)
     self.l3_ext_manager.add_router(self.context, router)
Beispiel #12
0
    def _sync_entry(self, context, entry):
        _log_entry(LOG_PROCESSING, entry)
        method, urlpath, to_send = self._json_data(entry)

        # TODO(mkolesni): This logic is weirdly written, need to refactor it.
        try:
            self.client.sendjson(method, urlpath, to_send)
            registry.notify(entry.object_type, odl_const.BEFORE_COMPLETE,
                            self, context=context, operation=entry.operation,
                            row=entry)
            entry_complete(context, entry)
            self._retry_reset()
            _log_entry(LOG_COMPLETED, entry)
        except exceptions.ConnectionError:
            # Don't raise the retry count, just log an error & break
            entry_reset(context, entry)
            LOG.error("Cannot connect to the OpenDaylight Controller,"
                      " will not process additional entries")
            self._retry_sleep()
            return True
        except Exception:
            _log_entry(LOG_ERROR_PROCESSING, entry,
                       log_level=logging.ERROR, exc_info=True)
            entry_update_state_by_retry_count(
                context, entry, self._max_retry_count)

        return False
Beispiel #13
0
    def create_or_update_agent(self, context, agent_state):
        """Registers new agent in the database or updates existing.

        Returns tuple of agent status and state.
        Status is from server point of view: alive, new or revived.
        It could be used by agent to do some sync with the server if needed.
        """
        status = agent_consts.AGENT_ALIVE
        with context.session.begin(subtransactions=True):
            res_keys = ['agent_type', 'binary', 'host', 'topic']
            res = dict((k, agent_state[k]) for k in res_keys)
            if 'availability_zone' in agent_state:
                res['availability_zone'] = agent_state['availability_zone']
            configurations_dict = agent_state.get('configurations', {})
            res['configurations'] = jsonutils.dumps(configurations_dict)
            resource_versions_dict = agent_state.get('resource_versions')
            if resource_versions_dict:
                res['resource_versions'] = jsonutils.dumps(
                    resource_versions_dict)
            res['load'] = self._get_agent_load(agent_state)
            current_time = timeutils.utcnow()
            try:
                agent = self._get_agent_by_type_and_host(
                    context, agent_state['agent_type'], agent_state['host'])
                if not agent.is_active:
                    status = agent_consts.AGENT_REVIVED
                    if 'resource_versions' not in agent_state:
                        # updating agent_state with resource_versions taken
                        # from db so that
                        # _update_local_agent_resource_versions() will call
                        # version_manager and bring it up to date
                        agent_state['resource_versions'] = self._get_dict(
                            agent, 'resource_versions', ignore_missing=True)
                res['heartbeat_timestamp'] = current_time
                if agent_state.get('start_flag'):
                    res['started_at'] = current_time
                greenthread.sleep(0)
                self._log_heartbeat(agent_state, agent, configurations_dict)
                agent.update_fields(res)
                agent.update()
                event_type = events.AFTER_UPDATE
            except agent_exc.AgentNotFoundByTypeHost:
                greenthread.sleep(0)
                res['created_at'] = current_time
                res['started_at'] = current_time
                res['heartbeat_timestamp'] = current_time
                res['admin_state_up'] = cfg.CONF.enable_new_agents
                agent = agent_obj.Agent(context=context, **res)
                greenthread.sleep(0)
                agent.create()
                event_type = events.AFTER_CREATE
                self._log_heartbeat(agent_state, agent, configurations_dict)
                status = agent_consts.AGENT_NEW
            greenthread.sleep(0)

        registry.notify(resources.AGENT, event_type, self, context=context,
                        host=agent_state['host'], plugin=self,
                        agent=agent_state)
        return status, agent_state
 def create_bgp_speaker(self, context, bgp_speaker):
     bgp_speaker = super(BgpPlugin, self).create_bgp_speaker(context,
                                                             bgp_speaker)
     payload = {'plugin': self, 'context': context,
                'bgp_speaker': bgp_speaker}
     registry.notify(dr_resources.BGP_SPEAKER, events.AFTER_CREATE,
                     self, payload=payload)
     return bgp_speaker
Beispiel #15
0
 def _process_updated_router(self, router):
     ri = self.router_info[router['id']]
     ri.router = router
     registry.notify(resources.ROUTER, events.BEFORE_UPDATE,
                     self, router=ri)
     ri.process()
     registry.notify(resources.ROUTER, events.AFTER_UPDATE, self, router=ri)
     self.l3_ext_manager.update_router(self.context, router)
Beispiel #16
0
 def test_vif_details_bridge_name_handler_registration(self,
                                                       mock_gen_br_name):
     driver.register()
     mock_gen_br_name.return_value = 'fake-trunk-br-name'
     test_trigger = mock.Mock()
     registry.notify(agent_consts.OVS_BRIDGE_NAME, events.BEFORE_READ,
                     test_trigger, **{'port': {'trunk_details':
                                               {'trunk_id': 'foo'}}})
     test_trigger.assert_called_once_with('fake-trunk-br-name')
 def _call_before_port_binding(self, host):
     kwargs = {
         'context': mock.Mock(),
         'port': {
             portbindings.HOST_ID: host
         }
     }
     registry.notify(resources.PORT, events.BEFORE_CREATE, self.ml2_plugin,
                     **kwargs)
Beispiel #18
0
 def _clear_router_provider(self, resource, event, trigger, context,
                            router_id, **kwargs):
     """Remove the association between a router and a service provider."""
     drv = self.get_provider_for_router(context, router_id)
     registry.notify(
         resources.ROUTER_CONTROLLER, events.PRECOMMIT_DELETE_ASSOCIATIONS,
         trigger, context=context, router_id=router_id,
         old_driver=drv, new_driver=None, **kwargs)
     self._stm.del_resource_associations(context, [router_id])
Beispiel #19
0
 def _registry_notify(self, res, event, id=None, exc_cls=None, **kwargs):
     # NOTE(armax): a callback exception here will prevent the request
     # from being processed. This is a hook point for backend's validation;
     # we raise to propagate the reason for the failure.
     try:
         registry.notify(res, event, self, **kwargs)
     except exceptions.CallbackFailure as e:
         if exc_cls:
             reason = (_('cannot perform %(event)s due to %(reason)s') %
                       {'event': event, 'reason': e})
             raise exc_cls(reason=reason, id=id)
Beispiel #20
0
    def _set_bridge_name(port, vif_details):
        # REVISIT(rawlin): add BridgeName as a nullable column to the Port
        # model and simply check here if it's set and insert it into the
        # vif_details.

        def set_bridge_name_inner(bridge_name):
            vif_details[portbindings.VIF_DETAILS_BRIDGE_NAME] = bridge_name

        registry.notify(
            a_const.OVS_BRIDGE_NAME, events.BEFORE_READ,
            set_bridge_name_inner, port=port)
Beispiel #21
0
 def create_segment(self, context, segment):
     """Create a segment."""
     segment = segment['segment']
     segment_id = segment.get('id') or uuidutils.generate_uuid()
     try:
         new_segment = self._create_segment_db(context, segment_id, segment)
     except db_exc.DBReferenceError:
         raise n_exc.NetworkNotFound(net_id=segment['network_id'])
     registry.notify(resources.SEGMENT, events.AFTER_CREATE, self,
                     context=context, segment=new_segment)
     return self._make_segment_dict(new_segment)
Beispiel #22
0
    def test_handle_event(self, mock_sg_cb):
        fake_register()
        self.driver_manager.register_driver(FAKE_DRIVER)

        registry.notify(
            resources.SECURITY_GROUP_RULE, events.AFTER_CREATE, mock.ANY)
        mock_sg_cb.assert_called_once_with(
            resources.SECURITY_GROUP_RULE, events.AFTER_CREATE, mock.ANY)
        mock_sg_cb.reset_mock()
        registry.notify('fake_resource', events.AFTER_DELETE, mock.ANY)
        mock_sg_cb.assert_not_called()
Beispiel #23
0
    def __init__(self):
        self._drivers = []
        self.notification_api = resources_rpc.ResourcesPushRpcApi()
        self.rpc_notifications_required = False
        rpc_registry.provide(self._get_qos_policy_cb, resources.QOS_POLICY)
        # notify any registered QoS driver that we're ready, those will
        # call the driver manager back with register_driver if they
        # are enabled
        registry.notify(qos_consts.QOS_PLUGIN, events.AFTER_INIT, self)

        if self.rpc_notifications_required:
            self.push_api = resources_rpc.ResourcesPushRpcApi()
Beispiel #24
0
def serve_wsgi(cls):

    try:
        service = cls.create()
        service.start()
    except Exception:
        with excutils.save_and_reraise_exception():
            LOG.exception(_LE('Unrecoverable error: please check log '
                              'for details.'))

    registry.notify(resources.PROCESS, events.BEFORE_SPAWN, service)
    return service
Beispiel #25
0
 def __init__(self):
     self._rpc_backend = None
     self._drivers = []
     self._segmentation_types = {}
     self._interfaces = set()
     self._agent_types = set()
     drivers.register()
     registry.subscribe(rules.enforce_port_deletion_rules,
                        resources.PORT, events.BEFORE_DELETE)
     registry.notify(constants.TRUNK_PLUGIN, events.AFTER_INIT, self)
     for driver in self._drivers:
         LOG.debug('Trunk plugin loaded with driver %s', driver.name)
     self.check_compatibility()
 def test_mac_not_cleared_on_agent_delete_event_with_remaining_agents(self):
     plugin = directory.get_plugin()
     self._create_dvr_mac_entry('host_1', 'mac_1')
     self._create_dvr_mac_entry('host_2', 'mac_2')
     agent1 = {'host': 'host_1', 'id': 'a1'}
     agent2 = {'host': 'host_1', 'id': 'a2'}
     with mock.patch.object(plugin, 'get_agents', return_value=[agent2]):
         with mock.patch.object(plugin, 'notifier') as notifier:
             registry.notify(resources.AGENT, events.BEFORE_DELETE, self,
                             context=self.ctx, agent=agent1)
     mac_list = self.mixin.get_dvr_mac_address_list(self.ctx)
     self.assertEqual(2, len(mac_list))
     self.assertFalse(notifier.dvr_mac_address_update.called)
Beispiel #27
0
 def delete_rbac_policy(self, context, id):
     entry = self._get_rbac_policy(context, id)
     object_type = entry['object_type']
     try:
         registry.notify(RBAC_POLICY, events.BEFORE_DELETE, self,
                         context=context, object_type=object_type,
                         policy=entry)
     except c_exc.CallbackFailure as ex:
         raise ext_rbac.RbacPolicyInUse(object_id=entry['object_id'],
                                        details=ex)
     with context.session.begin(subtransactions=True):
         context.session.delete(entry)
     self.object_type_cache.pop(id, None)
Beispiel #28
0
    def add_subports(self, context, trunk_id, subports):
        """Add one or more subports to trunk."""
        with db_api.context_manager.writer.using(context):
            trunk = self._get_trunk(context, trunk_id)

            # Check for basic validation since the request body here is not
            # automatically validated by the API layer.
            subports = subports['sub_ports']
            subports_validator = rules.SubPortsValidator(
                self._segmentation_types, subports, trunk['port_id'])
            subports = subports_validator.validate(
                context, basic_validation=True)
            added_subports = []

            rules.trunk_can_be_managed(context, trunk)
            original_trunk = copy.deepcopy(trunk)
            # NOTE(status_police): the trunk status should transition to
            # DOWN (and finally in ACTIVE or ERROR), only if it is not in
            # ERROR status already. A user should attempt to resolve the ERROR
            # condition before adding more subports to the trunk. Should a
            # trunk be in DOWN or BUILD state (e.g. when dealing with
            # multiple concurrent requests), the status is still forced to
            # DOWN and thus can potentially overwrite an interleaving state
            # change to ACTIVE. Eventually the driver should bring the status
            # back to ACTIVE or ERROR.
            if trunk.status == constants.ERROR_STATUS:
                raise trunk_exc.TrunkInErrorState(trunk_id=trunk_id)
            else:
                trunk.update(status=constants.DOWN_STATUS)

            for subport in subports:
                obj = trunk_objects.SubPort(
                               context=context,
                               trunk_id=trunk_id,
                               port_id=subport['port_id'],
                               segmentation_type=subport['segmentation_type'],
                               segmentation_id=subport['segmentation_id'])
                obj.create()
                trunk['sub_ports'].append(obj)
                added_subports.append(obj)
            payload = callbacks.TrunkPayload(context, trunk_id,
                                             current_trunk=trunk,
                                             original_trunk=original_trunk,
                                             subports=added_subports)
            if added_subports:
                registry.notify(constants.SUBPORTS, events.PRECOMMIT_CREATE,
                                self, payload=payload)
        if added_subports:
            registry.notify(
                constants.SUBPORTS, events.AFTER_CREATE, self, payload=payload)
        return trunk
Beispiel #29
0
    def remove_subports(self, context, trunk_id, subports):
        """Remove one or more subports from trunk."""
        subports = subports['sub_ports']
        with db_api.context_manager.writer.using(context):
            trunk = self._get_trunk(context, trunk_id)
            original_trunk = copy.deepcopy(trunk)
            rules.trunk_can_be_managed(context, trunk)

            subports_validator = rules.SubPortsValidator(
                self._segmentation_types, subports)
            # the subports are being removed, therefore we do not need to
            # enforce any specific trunk rules, other than basic validation
            # of the request body.
            subports = subports_validator.validate(
                context, basic_validation=True,
                trunk_validation=False)

            current_subports = {p.port_id: p for p in trunk.sub_ports}
            removed_subports = []

            for subport in subports:
                subport_obj = current_subports.pop(subport['port_id'], None)

                if not subport_obj:
                    raise trunk_exc.SubPortNotFound(trunk_id=trunk_id,
                                                    port_id=subport['port_id'])
                subport_obj.delete()
                removed_subports.append(subport_obj)

            del trunk.sub_ports[:]
            trunk.sub_ports.extend(current_subports.values())
            # NOTE(status_police): the trunk status should transition to
            # DOWN irrespective of the status in which it is in to allow
            # the user to resolve potential conflicts due to prior add_subports
            # operations.
            # Should a trunk be in DOWN or BUILD state (e.g. when dealing
            # with multiple concurrent requests), the status is still forced
            # to DOWN. See add_subports() for more details.
            trunk.update(status=constants.DOWN_STATUS)
            payload = callbacks.TrunkPayload(context, trunk_id,
                                             current_trunk=trunk,
                                             original_trunk=original_trunk,
                                             subports=removed_subports)
            if removed_subports:
                registry.notify(constants.SUBPORTS, events.PRECOMMIT_DELETE,
                                self, payload=payload)
        if removed_subports:
            registry.notify(
                constants.SUBPORTS, events.AFTER_DELETE, self, payload=payload)
        return trunk
Beispiel #30
0
 def record_resource_delete(self, context, rtype, resource_id):
     # deletions are final, record them so we never
     # accept new data for the same ID.
     LOG.debug("Resource %s deleted: %s", rtype, resource_id)
     # TODO(kevinbenton): we need a way to expire items from the set at
     # some TTL so it doesn't grow indefinitely with churn
     if resource_id in self._deleted_ids_by_type[rtype]:
         LOG.debug("Skipped duplicate delete event for %s", resource_id)
         return
     self._deleted_ids_by_type[rtype].add(resource_id)
     existing = self._type_cache(rtype).pop(resource_id, None)
     # local notification for agent internals to subscribe to
     registry.notify(rtype, events.AFTER_DELETE, self, context=context,
                     existing=existing, resource_id=resource_id)
Beispiel #31
0
 def _registry_notify(self, res, event, id=None, exc_cls=None, **kwargs):
     # NOTE(armax): a callback exception here will prevent the request
     # from being processed. This is a hook point for backend's validation;
     # we raise to propagate the reason for the failure.
     try:
         if 'payload' in kwargs:
             # TODO(boden): remove shim once all callbacks use payloads
             registry.publish(res, event, self, payload=kwargs['payload'])
         else:
             registry.notify(res, event, self, **kwargs)
     except exceptions.CallbackFailure as e:
         if exc_cls:
             reason = (_('cannot perform %(event)s due to %(reason)s') % {
                 'event': event,
                 'reason': e
             })
             raise exc_cls(reason=reason, id=id)
    def update_security_group(self, context, id, security_group):
        s = security_group['security_group']

        if 'stateful' in s:
            with db_api.CONTEXT_READER.using(context):
                sg = self._get_security_group(context, id)
                if s['stateful'] != sg['stateful']:
                    filters = {'security_group_id': [id]}
                    ports = self._get_port_security_group_bindings(
                        context, filters)
                    if ports:
                        raise ext_sg.SecurityGroupInUse(id=id)

        kwargs = {
            'context': context,
            'security_group_id': id,
            'security_group': s,
        }
        self._registry_notify(resources.SECURITY_GROUP,
                              events.BEFORE_UPDATE,
                              exc_cls=ext_sg.SecurityGroupConflict,
                              **kwargs)

        with db_api.CONTEXT_WRITER.using(context):
            sg = self._get_security_group(context, id)
            if sg.name == 'default' and 'name' in s:
                raise ext_sg.SecurityGroupCannotUpdateDefault()
            sg_dict = self._make_security_group_dict(sg)
            kwargs['original_security_group'] = sg_dict
            sg.update_fields(s)
            sg.update()
            sg_dict = self._make_security_group_dict(sg)
            kwargs['security_group'] = sg_dict
            self._registry_notify(
                resources.SECURITY_GROUP,
                events.PRECOMMIT_UPDATE,
                exc_cls=ext_sg.SecurityGroupConflict,
                payload=events.DBEventPayload(
                    context,
                    request_body=s,
                    states=(kwargs['original_security_group'], ),
                    resource_id=id,
                    desired_state=sg_dict))
        registry.notify(resources.SECURITY_GROUP, events.AFTER_UPDATE, self,
                        **kwargs)
        return sg_dict
Beispiel #33
0
    def delete_security_group(self, context, id):
        filters = {'security_group_id': [id]}
        with db_api.CONTEXT_READER.using(context):
            ports = self._get_port_security_group_bindings(context, filters)
            if ports:
                raise ext_sg.SecurityGroupInUse(id=id)
            # confirm security group exists
            sg = self._get_security_group(context, id, fields=['id', 'name'])

            if sg['name'] == 'default' and not context.is_admin:
                raise ext_sg.SecurityGroupCannotRemoveDefault()
        kwargs = {
            'context': context,
            'security_group_id': id,
            'security_group': sg,
        }
        self._registry_notify(resources.SECURITY_GROUP,
                              events.BEFORE_DELETE,
                              exc_cls=ext_sg.SecurityGroupInUse,
                              id=id,
                              payload=events.DBEventPayload(context,
                                                            states=(sg, ),
                                                            resource_id=id))

        with db_api.CONTEXT_WRITER.using(context):
            # pass security_group_rule_ids to ensure
            # consistency with deleted rules
            # get security_group_bindings and security_group one more time
            # so that they will be attached for session where sg will be
            # deleted
            ports = self._get_port_security_group_bindings(context, filters)
            sg = self._get_security_group(context, id)
            kwargs['security_group_rule_ids'] = [r['id'] for r in sg.rules]
            kwargs['security_group'] = self._make_security_group_dict(sg)
            self._registry_notify(resources.SECURITY_GROUP,
                                  events.PRECOMMIT_DELETE,
                                  exc_cls=ext_sg.SecurityGroupInUse,
                                  id=id,
                                  **kwargs)
            sg.delete()

        kwargs.pop('security_group')
        kwargs['name'] = sg['name']
        registry.notify(resources.SECURITY_GROUP, events.AFTER_DELETE, self,
                        **kwargs)
Beispiel #34
0
    def record_resource_update(self,
                               context,
                               rtype,
                               resource,
                               agent_restarted=False):
        LOG.info('%s(): caller(): %s', log_utils.get_fname(1),
                 log_utils.get_fname(2))
        """Takes in an OVO and generates an event on relevant changes.

        A change is deemed to be relevant if it is not stale and if any
        fields changed beyond the revision number and update time.

        Both creates and updates are handled in this function.
        """
        if self._is_stale(rtype, resource):
            LOG.debug("Ignoring stale update for %s: %s", rtype, resource)
            return
        existing = self._type_cache(rtype).get(resource.id)
        self._type_cache(rtype)[resource.id] = resource
        changed_fields = self._get_changed_fields(existing, resource)
        if not changed_fields:
            LOG.debug("Received resource %s update without any changes: %s",
                      rtype, resource.id)
            return
        if existing:
            LOG.debug(
                "Resource %s %s updated (revision_number %s->%s). "
                "Old fields: %s New fields: %s", rtype, existing.id,
                existing.revision_number, resource.revision_number,
                {f: existing.get(f)
                 for f in changed_fields},
                {f: resource.get(f)
                 for f in changed_fields})
        else:
            LOG.debug("Received new resource %s: %s", rtype, resource)
        # local notification for agent internals to subscribe to
        registry.notify(rtype,
                        events.AFTER_UPDATE,
                        self,
                        context=context,
                        changed_fields=changed_fields,
                        existing=existing,
                        updated=resource,
                        resource_id=resource.id,
                        agent_restarted=agent_restarted)
 def create_security_group_rule_bulk_native(self, context,
                                            security_group_rules):
     rules = security_group_rules['security_group_rules']
     scoped_session(context.session)
     security_group_id = self._validate_security_group_rules(
         context, security_group_rules)
     with db_api.CONTEXT_WRITER.using(context):
         self._check_for_duplicate_rules(context, security_group_id, rules)
         ret = []
         for rule_dict in rules:
             res_rule_dict = self._create_security_group_rule(
                 context, rule_dict, validate=False)
             ret.append(res_rule_dict)
     for rdict in ret:
         registry.notify(
             resources.SECURITY_GROUP_RULE, events.AFTER_CREATE, self,
             context=context, security_group_rule=rdict)
     return ret
Beispiel #36
0
    def _router_removed(self, router_id):
        ri = self.router_info.get(router_id)
        if ri is None:
            LOG.warning(
                "Info for router %s was not found. "
                "Performing router cleanup", router_id)
            self.namespaces_manager.ensure_router_cleanup(router_id)
            return

        registry.notify(resources.ROUTER,
                        events.BEFORE_DELETE,
                        self,
                        router=ri)

        ri.delete()
        del self.router_info[router_id]

        registry.notify(resources.ROUTER, events.AFTER_DELETE, self, router=ri)
Beispiel #37
0
    def delete_floatingip_port_forwarding(self, context, id, floatingip_id):
        pf_obj = pf.PortForwarding.get_object(context, id=id)

        if not pf_obj or pf_obj.floatingip_id != floatingip_id:
            raise pf_exc.PortForwardingNotFound(id=id)
        with db_api.CONTEXT_WRITER.using(context):
            fip_obj = self._get_fip_obj(context, pf_obj.floatingip_id)
            pf_objs = pf.PortForwarding.get_objects(
                context, floatingip_id=pf_obj.floatingip_id)
            if len(pf_objs) == 1 and pf_objs[0].id == pf_obj.id:
                fip_obj.update_fields({'router_id': None})
                fip_obj.update()
            pf_obj.delete()
        if self._rpc_notifications_required:
            self.push_api.push(context, [pf_obj], rpc_events.DELETED)
        registry.notify(pf_consts.PORT_FORWARDING, events.AFTER_DELETE, self,
                        payload=[callbacks.PortForwardingPayload(
                            context, original_pf=pf_obj)])
Beispiel #38
0
 def _process_updated_router(self, router):
     is_dvr_only_agent = (self.conf.agent_mode in [
         lib_const.L3_AGENT_MODE_DVR,
         l3_constants.L3_AGENT_MODE_DVR_NO_EXTERNAL
     ])
     # For HA routers check that DB state matches actual state
     if router.get('ha') and not is_dvr_only_agent:
         self.check_ha_state_for_router(
             router['id'], router.get(l3_constants.HA_ROUTER_STATE_KEY))
     ri = self.router_info[router['id']]
     ri.router = router
     registry.notify(resources.ROUTER,
                     events.BEFORE_UPDATE,
                     self,
                     router=ri)
     ri.process()
     registry.notify(resources.ROUTER, events.AFTER_UPDATE, self, router=ri)
     self.l3_ext_manager.update_router(self.context, router)
Beispiel #39
0
    def start(self, name="neutron-server", desc=None):
        """Start the worker.

        If worker_process_count is greater than 0, a callback notification
        is sent. Subclasses should call this method before doing their
        own start() work.

        Automatically sets the process title to indicate that this is a
        child worker, customizable via the name and desc arguments.

        :returns: None
        """

        # If we are a child process, set our proctitle to something useful
        desc = desc or self.desc
        self.setproctitle(name, desc)
        if self.worker_process_count > 0:
            registry.notify(resources.PROCESS, events.AFTER_INIT, self.start)
Beispiel #40
0
    def test_mac_cleared_on_agent_delete_event(self):
        plugin = directory.get_plugin()

        with db_api.context_manager.writer.using(self.ctx):
            self._create_dvr_mac_entry('host_1', 'mac_1')
            self._create_dvr_mac_entry('host_2', 'mac_2')
            agent = {'host': 'host_1', 'id': 'a1'}
            with mock.patch.object(plugin, 'notifier') as notifier:
                registry.notify(resources.AGENT,
                                events.BEFORE_DELETE,
                                self,
                                context=self.ctx,
                                agent=agent)
            mac_list = self.mixin.get_dvr_mac_address_list(self.ctx)
        self.assertEqual(1, len(mac_list))
        self.assertEqual('host_2', mac_list[0]['host'])
        notifier.dvr_mac_address_update.assert_called_once_with(
            self.ctx, mac_list)
Beispiel #41
0
 def update_rbac_policy(self, context, id, rbac_policy):
     pol = rbac_policy['rbac_policy']
     entry = self._get_rbac_policy(context, id)
     object_type = entry.db_model.object_type
     try:
         registry.notify(resources.RBAC_POLICY,
                         events.BEFORE_UPDATE,
                         self,
                         context=context,
                         policy=entry,
                         object_type=object_type,
                         policy_update=pol)
     except c_exc.CallbackFailure as ex:
         raise ext_rbac.RbacPolicyInUse(object_id=entry.object_id,
                                        details=ex)
     entry.update_fields(pol)
     entry.update()
     return self._make_rbac_policy_dict(entry)
Beispiel #42
0
 def record_resource_delete(self, context, rtype, resource_id):
     # deletions are final, record them so we never
     # accept new data for the same ID.
     LOG.debug("Resource %s deleted: %s", rtype, resource_id)
     # TODO(kevinbenton): we need a way to expire items from the set at
     # some TTL so it doesn't grow indefinitely with churn
     if resource_id in self._deleted_ids_by_type[rtype]:
         LOG.debug("Skipped duplicate delete event for %s", resource_id)
         return
     self._deleted_ids_by_type[rtype].add(resource_id)
     existing = self._type_cache(rtype).pop(resource_id, None)
     # local notification for agent internals to subscribe to
     registry.notify(rtype,
                     events.AFTER_DELETE,
                     self,
                     context=context,
                     existing=existing,
                     resource_id=resource_id)
Beispiel #43
0
 def update_rbac_policy(self, context, id, rbac_policy):
     pol = rbac_policy['rbac_policy']
     entry = self._get_rbac_policy(context, id)
     object_type = entry['object_type']
     try:
         registry.notify(resources.RBAC_POLICY,
                         events.BEFORE_UPDATE,
                         self,
                         context=context,
                         policy=entry,
                         object_type=object_type,
                         policy_update=pol)
     except c_exc.CallbackFailure as ex:
         raise ext_rbac.RbacPolicyInUse(object_id=entry['object_id'],
                                        details=ex)
     with context.session.begin(subtransactions=True):
         entry.update(pol)
     return self._make_rbac_policy_dict(entry)
Beispiel #44
0
 def update_address_group(self, context, id, address_group):
     fields = address_group['address_group']
     ag = self._get_address_group(context, id)
     kwargs = {'original_address_group': self._make_address_group_dict(ag)}
     ag.update_fields(fields)
     ag.update()
     ag_dict = self._make_address_group_dict(ag)
     kwargs['address_group'] = ag_dict
     # TODO(mlavalle) this notification should be updated to publish when
     # the callback handler handle_event, class _ObjectChangeHandler in
     # neutron.plugins.ml2.ovo_rpc is updated to receive notifications with
     # new style payload objects as argument.
     registry.notify(resources.ADDRESS_GROUP,
                     events.AFTER_UPDATE,
                     self,
                     context=context,
                     **kwargs)
     return ag_dict
Beispiel #45
0
 def remove_addresses(self, context, address_group_id, addresses):
     ag = self._get_address_group(context, address_group_id)
     addrs_in_ag, addrs_not_in_ag = self._process_requested_addresses(
         ag, addresses['addresses'])
     if addrs_not_in_ag:
         raise ag_exc.AddressesNotFound(
             addresses=addrs_not_in_ag, address_group_id=address_group_id)
     for addr in addrs_in_ag:
         ag_obj.AddressAssociation.delete_objects(
             context, address_group_id=address_group_id, address=addr)
     ag.update()  # reload synthetic fields
     # TODO(hangyang) this notification should be updated to publish when
     # the callback handler handle_event, class _ObjectChangeHandler in
     # neutron.plugins.ml2.ovo_rpc is updated to receive notifications with
     # new style payload objects as argument.
     registry.notify(ADDRESS_GROUP, events.AFTER_UPDATE, self,
                     context=context, address_group_id=ag.id)
     return {'address_group': self._make_address_group_dict(ag)}
Beispiel #46
0
    def _set_router_provider(self, resource, event, trigger, context, router,
                             router_db, **kwargs):
        """Associates a router with a service provider.

        Association is done by flavor_id if it's specified, otherwise it will
        fallback to determining which loaded driver supports the ha/distributed
        attributes associated with the router.
        """
        if _flavor_specified(router):
            router_db.flavor_id = router['flavor_id']
        drv = self._get_provider_for_create(context, router)
        self._stm.add_resource_association(context, plugin_constants.L3,
                                           drv.name, router['id'])
        registry.notify(
            resources.ROUTER_CONTROLLER, events.PRECOMMIT_ADD_ASSOCIATION,
            trigger, context=context, router=router,
            router_db=router_db, old_driver=None,
            new_driver=drv, **kwargs)
Beispiel #47
0
 def create_address_group(self, context, address_group):
     """Create an address group."""
     fields = address_group['address_group']
     args = {'project_id': fields['project_id'],
             'id': uuidutils.generate_uuid(),
             'name': fields['name'],
             'description': fields['description']}
     ag = ag_obj.AddressGroup(context, **args)
     ag.create()
     if fields.get('addresses') is not constants.ATTR_NOT_SPECIFIED:
         self.add_addresses(context, ag.id, fields)
     ag.update()  # reload synthetic fields
     # TODO(mlavalle) this notification should be updated to publish when
     # the callback handler handle_event, class _ObjectChangeHandler in
     # neutron.plugins.ml2.ovo_rpc is updated to receive notifications with
     # new style payload objects as argument.
     registry.notify(ADDRESS_GROUP, events.AFTER_CREATE, self,
                     context=context, address_group_id=ag.id)
     return self._make_address_group_dict(ag)
Beispiel #48
0
def main(argv=sys.argv[1:]):
    _init_cfg()
    nsx_plugin_in_use = resources.get_plugin()
    LOG.info('NSX Plugin in use: %s', nsx_plugin_in_use)

    # the user can select the specific plugin
    selected_plugin = _validate_plugin_choice(cfg.CONF.plugin,
                                              nsx_plugin_in_use)

    resources.init_resource_plugin(
        selected_plugin,
        resources.get_plugin_dir(selected_plugin))

    _validate_resource_choice(cfg.CONF.resource, selected_plugin)
    _validate_op_choice(cfg.CONF.operation, selected_plugin)

    registry.notify(cfg.CONF.resource, cfg.CONF.operation, 'nsxadmin',
                    force=cfg.CONF.force, property=cfg.CONF.property,
                    verbose=cfg.CONF.verbose)
Beispiel #49
0
    def _router_removed(self, ri, router_id):
        if ri is None:
            LOG.warning(
                "Info for router %s was not found. "
                "Performing router cleanup", router_id)
            self.namespaces_manager.ensure_router_cleanup(router_id)
            return

        registry.publish(resources.ROUTER,
                         events.BEFORE_DELETE,
                         self,
                         payload=events.DBEventPayload(self.context,
                                                       states=(ri, ),
                                                       resource_id=router_id))

        ri.delete()
        del self.router_info[router_id]

        registry.notify(resources.ROUTER, events.AFTER_DELETE, self, router=ri)
Beispiel #50
0
    def _delete(self, request, id, **kwargs):
        action = self._plugin_handlers[self.DELETE]

        # Check authz
        policy.init()
        parent_id = kwargs.get(self._parent_id_name)
        obj = self._item(request, id, parent_id=parent_id)
        try:
            policy.enforce(request.context,
                           action,
                           obj,
                           pluralized=self._collection)
        except oslo_policy.PolicyNotAuthorized:
            # To avoid giving away information, pretend that it
            # doesn't exist if policy does not authorize SHOW
            with excutils.save_and_reraise_exception() as ctxt:
                if not policy.check(request.context,
                                    self._plugin_handlers[self.SHOW],
                                    obj,
                                    pluralized=self._collection):
                    ctxt.reraise = False
            msg = _('The resource could not be found.')
            raise webob.exc.HTTPNotFound(msg)

        obj_deleter = getattr(self._plugin, action)
        obj_deleter(request.context, id, **kwargs)
        # A delete operation usually alters resource usage, so mark affected
        # usage trackers as dirty
        resource_registry.set_resources_dirty(request.context)
        notifier_method = self._resource + '.delete.end'
        result = {self._resource: self._view(request.context, obj)}
        notifier_payload = {self._resource + '_id': id}
        notifier_payload.update(result)
        self._notifier.info(request.context, notifier_method, notifier_payload)
        registry.notify(self._resource,
                        events.BEFORE_RESPONSE,
                        self,
                        context=request.context,
                        data=result,
                        method_name=notifier_method,
                        action=action,
                        original={})
Beispiel #51
0
 def test_mac_cleared_on_agent_delete_event(self):
     plugin = directory.get_plugin()
     mac_1 = tools.get_random_EUI()
     mac_2 = tools.get_random_EUI()
     self._create_dvr_mac_entry('host_1', mac_1)
     self._create_dvr_mac_entry('host_2', mac_2)
     agent = {'host': 'host_1', 'id': 'a1'}
     with mock.patch.object(plugin, 'notifier') as notifier:
         registry.notify(resources.AGENT,
                         events.BEFORE_DELETE,
                         self,
                         context=self.ctx,
                         agent=agent)
     mac_list = self.mixin.get_dvr_mac_address_list(self.ctx)
     self.assertEqual(1, len(mac_list))
     for mac in mac_list:
         self.assertIsInstance(mac, dict)
     self.assertEqual('host_2', mac_list[0]['host'])
     notifier.dvr_mac_address_update.assert_called_once_with(
         self.ctx, mac_list)
Beispiel #52
0
 def get_provider_for_router(self, context, router_id):
     """Return the provider driver handle for a router id."""
     driver_name = self._stm.get_provider_names_by_resource_ids(
         context, [router_id]).get(router_id)
     if not driver_name:
         # this is an old router that hasn't been mapped to a provider
         # yet so we do this now
         router = self.l3_plugin.get_router(context, router_id)
         driver = self._attrs_to_driver(router)
         driver_name = driver.name
         with context.session.begin(subtransactions=True):
             self._stm.add_resource_association(
                 context, plugin_constants.L3,
                 driver_name, router_id)
             registry.notify(
                 resources.ROUTER_CONTROLLER,
                 events.PRECOMMIT_ADD_ASSOCIATION,
                 self, context=context, router_id=router_id,
                 router=router, old_driver=None, new_driver=driver)
     return self.drivers[driver_name]
Beispiel #53
0
 def update_trunk(self, context, trunk_id, trunk):
     """Update information for the specified trunk."""
     trunk_data = trunk['trunk']
     with db_api.context_manager.writer.using(context):
         trunk_obj = self._get_trunk(context, trunk_id)
         original_trunk = copy.deepcopy(trunk_obj)
         # NOTE(status_police): a trunk status should not change during an
         # update_trunk(), even in face of PRECOMMIT failures. This is
         # because only name and admin_state_up are being affected, and
         # these are DB properties only.
         trunk_obj.update_fields(trunk_data, reset_changes=True)
         trunk_obj.update()
         payload = callbacks.TrunkPayload(context, trunk_id,
                                          original_trunk=original_trunk,
                                          current_trunk=trunk_obj)
         registry.notify(constants.TRUNK, events.PRECOMMIT_UPDATE, self,
                         payload=payload)
     registry.notify(constants.TRUNK, events.AFTER_UPDATE, self,
                     payload=payload)
     return trunk_obj
Beispiel #54
0
def _update_segment_host_mapping_for_agent(resource, event, trigger,
                                           context, host, plugin, agent):
    check_segment_for_agent = getattr(plugin, 'check_segment_for_agent', None)
    if not check_segment_for_agent:
        return
    phys_nets = _get_phys_nets(agent)
    if not phys_nets:
        return
    start_flag = agent.get('start_flag', None)
    if host in reported_hosts and not start_flag:
        return
    reported_hosts.add(host)
    segments = get_segments_with_phys_nets(context, phys_nets)
    current_segment_ids = {
        segment['id'] for segment in segments
        if check_segment_for_agent(segment, agent)}
    update_segment_host_mapping(context, host, current_segment_ids)
    registry.notify(resources.SEGMENT_HOST_MAPPING, events.AFTER_CREATE,
                    plugin, context=context, host=host,
                    current_segment_ids=current_segment_ids)
Beispiel #55
0
 def test_mac_not_cleared_on_agent_delete_event_with_remaining_agents(self):
     plugin = directory.get_plugin()
     mac_1 = tools.get_random_EUI()
     mac_2 = tools.get_random_EUI()
     self._create_dvr_mac_entry('host_1', mac_1)
     self._create_dvr_mac_entry('host_2', mac_2)
     agent1 = {'host': 'host_1', 'id': 'a1'}
     agent2 = {'host': 'host_1', 'id': 'a2'}
     with mock.patch.object(plugin, 'get_agents', return_value=[agent2]):
         with mock.patch.object(plugin, 'notifier') as notifier:
             registry.notify(resources.AGENT,
                             events.BEFORE_DELETE,
                             self,
                             context=self.ctx,
                             agent=agent1)
     mac_list = self.mixin.get_dvr_mac_address_list(self.ctx)
     for mac in mac_list:
         self.assertIsInstance(mac, dict)
     self.assertEqual(2, len(mac_list))
     self.assertFalse(notifier.dvr_mac_address_update.called)
Beispiel #56
0
        def notify(create_result):
            # Ensure usage trackers for all resources affected by this API
            # operation are marked as dirty
            with db_api.context_manager.writer.using(request.context):
                # Commit the reservation(s)
                for reservation in reservations:
                    quota.QUOTAS.commit_reservation(
                        request.context, reservation.reservation_id)
                resource_registry.set_resources_dirty(request.context)

            notifier_method = self._resource + '.create.end'
            self._notifier.info(request.context,
                                notifier_method,
                                create_result)
            registry.notify(self._resource, events.BEFORE_RESPONSE, self,
                            context=request.context, data=create_result,
                            method_name=notifier_method,
                            collection=self._collection,
                            action=action, original={})
            return create_result
Beispiel #57
0
 def test_create_default_l2_gateway(self):
     def_bridge_cluster_name = nsx_v3_mocks.NSX_BRIDGE_CLUSTER_NAME
     cfg.CONF.set_override("default_bridge_cluster",
                           def_bridge_cluster_name, "nsx_v3")
     nsx_v3_driver.NsxV3Driver(mock.MagicMock())
     # fake the callback invoked after init
     registry.notify(resources.PROCESS, events.BEFORE_SPAWN,
                     mock.MagicMock())
     l2gws = self.driver._get_l2_gateways(self.context)
     def_bridge_cluster_id = (self.nsxlib.bridge_cluster.
                              get_id_by_name_or_id(def_bridge_cluster_name))
     def_l2gw = None
     for l2gw in l2gws:
         for device in l2gw['devices']:
             if device['device_name'] == def_bridge_cluster_id:
                 def_l2gw = l2gw
     self.assertIsNotNone(def_l2gw)
     self.assertTrue(def_l2gw.devices[0].device_name, def_bridge_cluster_id)
     self.assertTrue(def_l2gw.devices[0].interfaces[0].interface_name,
                     'default-bridge-cluster')
Beispiel #58
0
    def delete_security_group_rule(self, context, id):
        kwargs = {'context': context, 'security_group_rule_id': id}
        self._registry_notify(resources.SECURITY_GROUP_RULE,
                              events.BEFORE_DELETE,
                              id=id,
                              exc_cls=ext_sg.SecurityGroupRuleInUse,
                              **kwargs)

        with db_api.CONTEXT_WRITER.using(context):
            sgr = self._get_security_group_rule(context, id)
            kwargs['security_group_id'] = sgr['security_group_id']
            self._registry_notify(resources.SECURITY_GROUP_RULE,
                                  events.PRECOMMIT_DELETE,
                                  exc_cls=ext_sg.SecurityGroupRuleInUse,
                                  id=id,
                                  **kwargs)
            sgr.delete()

        registry.notify(resources.SECURITY_GROUP_RULE, events.AFTER_DELETE,
                        self, **kwargs)
Beispiel #59
0
 def delete_trunk(self, context, trunk_id):
     """Delete the specified trunk."""
     with db_api.context_manager.writer.using(context):
         trunk = self._get_trunk(context, trunk_id)
         rules.trunk_can_be_managed(context, trunk)
         trunk_port_validator = rules.TrunkPortValidator(trunk.port_id)
         if not trunk_port_validator.is_bound(context):
             # NOTE(status_police): when a trunk is deleted, the logical
             # object disappears from the datastore, therefore there is no
             # status transition involved. If PRECOMMIT failures occur,
             # the trunk remains in the status where it was.
             trunk.delete()
             payload = callbacks.TrunkPayload(context, trunk_id,
                                              original_trunk=trunk)
             registry.notify(constants.TRUNK, events.PRECOMMIT_DELETE, self,
                             payload=payload)
         else:
             raise trunk_exc.TrunkInUse(trunk_id=trunk_id)
     registry.notify(constants.TRUNK, events.AFTER_DELETE, self,
                     payload=payload)
Beispiel #60
0
 def create_trunk(self, context, trunk):
     """Create a trunk."""
     trunk = self.validate(context, trunk['trunk'])
     sub_ports = [
         trunk_objects.SubPort(context=context,
                               port_id=p['port_id'],
                               segmentation_id=p['segmentation_id'],
                               segmentation_type=p['segmentation_type'])
         for p in trunk['sub_ports']
     ]
     admin_state_up = trunk.get('admin_state_up', True)
     # NOTE(status_police): a trunk is created in DOWN status. Depending
     # on the nature of the create request, a driver may set the status
     # immediately to ACTIVE if no physical provisioning is required.
     # Otherwise a transition to BUILD (or ERROR) should be expected
     # depending on how the driver reacts. PRECOMMIT failures prevent the
     # trunk from being created altogether.
     trunk_description = trunk.get('description', "")
     trunk_obj = trunk_objects.Trunk(context=context,
                                     admin_state_up=admin_state_up,
                                     id=uuidutils.generate_uuid(),
                                     name=trunk.get('name', ""),
                                     description=trunk_description,
                                     project_id=trunk['tenant_id'],
                                     port_id=trunk['port_id'],
                                     status=constants.DOWN_STATUS,
                                     sub_ports=sub_ports)
     with db_api.autonested_transaction(context.session):
         trunk_obj.create()
         payload = callbacks.TrunkPayload(context,
                                          trunk_obj.id,
                                          current_trunk=trunk_obj)
         registry.notify(resources.TRUNK,
                         events.PRECOMMIT_CREATE,
                         self,
                         payload=payload)
     registry.notify(resources.TRUNK,
                     events.AFTER_CREATE,
                     self,
                     payload=payload)
     return trunk_obj