Prepare the message to be sent to Event queue for VDP trigger.

        This is actually called for a subnet add to a router. This function
        prepares a VM's VNIC create/delete message.
321340
def prepare_router_vm_msg(self, tenant_id, tenant_name, router_id, net_id,
                              subnet_id, seg, status):
        
        max_get_router_info_retry = True
        attempt = 0
        while max_get_router_info_retry:
            port_data = self.os_helper.get_router_port_subnet(subnet_id)
            if port_data is None:
                LOG.error("Unable to get router port data")
                return None
            if port_data.get('binding:host_id') == '':
                time.sleep(3)
                attempt += 1
                if attempt > 3:
                    max_get_router_info_retry = False
                    LOG.error("Unable to get router binding host data, "
                              "Max attempts reached")
            else:
                max_get_router_info_retry = False
        if status is 'up':
            event_type = 'service.vnic.create'
        else:
            event_type = 'service.vnic.delete'
        vnic_data = {'status': status, 'mac': port_data.get('mac_address'),
                     'segid': seg, 'host': port_data.get('binding:host_id')}
        if vnic_data['host'] == '':
            LOG.error("Null host for seg %(seg)s subnet %(subnet)s",
                      {'seg': seg, 'subnet': subnet_id})
            if self.tenant_dict.get(tenant_id).get('host') is None:
                LOG.error("Null host for tenant %(tenant)s seg %(seg)s "
                          "subnet %(subnet)s",
                          {'tenant': tenant_id, 'seg': seg,
                           'subnet': subnet_id})
                return None
            else:
                vnic_data['host'] = self.tenant_dict.get(tenant_id).get('host')
        else:
            self.tenant_dict[tenant_id]['host'] = vnic_data['host']
        vm_ip = port_data.get('fixed_ips')[0].get('ip_address')
        vnic_data.update({'port_id': port_data.get('id'), 'network_id': net_id,
                          'vm_name': 'FW_SRVC_RTR_' + tenant_name,
                          'vm_ip': vm_ip, 'vm_uuid': router_id, 'gw_mac': None,
                          'fwd_mod': 'anycast_gateway'})
        payload = {'service': vnic_data}
        data = (event_type, payload)
        return data
1202383
function(router, pathname, handler, msg_, preMsg, msg2) {

const msg = (msg2 && ` ${msg2}`) || (msg_ && `@${msg_}`) || '';

if (msg) {
  console.log(`${pad(preMsg, 35)} ${lpad(pathname,55)} ${msg}`);
}

  router.addRoute(pathname, function(req, res, params) {

    if (getDumpReqVerbosity() > 0) {
      dumpReq(req, res, `--------vvvvv\n${msg2} handling`, {skipBody:true, verbosity:getDumpReqVerbosity(), postMsg: '------^^^^^'});
    }

    return handler.apply(this, arguments);
  });
}
1251053
def _domain_event_device_added_cb(conn, domain, dev, opaque):
    '''
    
    '''
    _salt_send_domain_event(opaque, conn, domain, opaque['event'], {
        'dev': dev
    })
1030898
def create(vm_):
    '''
    
    '''
    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(
                __opts__,
                __active_provider_name__ or 'dimensiondata',
                vm_['profile']) is False:
            return False
    except AttributeError:
        pass

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    log.info('Creating Cloud VM %s', vm_['name'])
    conn = get_conn()

    location = conn.ex_get_location_by_id(vm_['location'])
    images = conn.list_images(location=location)
    image = [x for x in images if x.id == vm_['image']][0]
    network_domains = conn.ex_list_network_domains(location=location)
    try:
        network_domain = [y for y in network_domains
                          if y.name == vm_['network_domain']][0]
    except IndexError:
        network_domain = conn.ex_create_network_domain(
            location=location,
            name=vm_['network_domain'],
            plan='ADVANCED',
            description=''
        )

    try:
        vlan = [y for y in conn.ex_list_vlans(
            location=location,
            network_domain=network_domain)
                if y.name == vm_['vlan']][0]
    except (IndexError, KeyError):
        # Use the first VLAN in the network domain
        vlan = conn.ex_list_vlans(
            location=location,
            network_domain=network_domain)[0]

    kwargs = {
        'name': vm_['name'],
        'image': image,
        'ex_description': vm_['description'],
        'ex_network_domain': network_domain,
        'ex_vlan': vlan,
        'ex_is_started': vm_['is_started']
    }

    event_data = _to_event_data(kwargs)

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('requesting', event_data, list(event_data)),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    # Initial password (excluded from event payload)
    initial_password = NodeAuthPassword(vm_['auth'])
    kwargs['auth'] = initial_password

    try:
        data = conn.create_node(**kwargs)
    except Exception as exc:
        log.error(
            'Error creating %s on DIMENSIONDATA\n\n'
            'The following exception was thrown by libcloud when trying to '
            'run the initial deployment: \n%s',
            vm_['name'], exc,
            exc_info_on_loglevel=logging.DEBUG
        )
        return False

    try:
        data = __utils__['cloud.wait_for_ip'](
            _query_node_data,
            update_args=(vm_, data),
            timeout=config.get_cloud_config_value(
                'wait_for_ip_timeout', vm_, __opts__, default=25 * 60),
            interval=config.get_cloud_config_value(
                'wait_for_ip_interval', vm_, __opts__, default=30),
            max_failures=config.get_cloud_config_value(
                'wait_for_ip_max_failures', vm_, __opts__, default=60),
        )
    except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
        try:
            # It might be already up, let's destroy it!
            destroy(vm_['name'])  # pylint: disable=not-callable
        except SaltCloudSystemExit:
            pass
        finally:
            raise SaltCloudSystemExit(six.text_type(exc))

    log.debug('VM is now running')
    if ssh_interface(vm_) == 'private_ips':
        ip_address = preferred_ip(vm_, data.private_ips)
    else:
        ip_address = preferred_ip(vm_, data.public_ips)
    log.debug('Using IP address %s', ip_address)

    if __utils__['cloud.get_salt_interface'](vm_, __opts__) == 'private_ips':
        salt_ip_address = preferred_ip(vm_, data.private_ips)
        log.info('Salt interface set to: %s', salt_ip_address)
    else:
        salt_ip_address = preferred_ip(vm_, data.public_ips)
        log.debug('Salt interface set to: %s', salt_ip_address)

    if not ip_address:
        raise SaltCloudSystemExit(
            'No IP addresses could be found.'
        )

    vm_['salt_host'] = salt_ip_address
    vm_['ssh_host'] = ip_address
    vm_['password'] = vm_['auth']

    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    ret.update(data.__dict__)

    if 'password' in data.extra:
        del data.extra['password']

    log.info('Created Cloud VM \'%s\'', vm_['name'])
    log.debug(
        '\'%s\' VM creation details:\n%s',
        vm_['name'], pprint.pformat(data.__dict__)
    )

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return ret
199988
def _domain_event_pmsuspend_cb(conn, domain, reason, opaque):
    '''
    
    '''
    _salt_send_domain_event(opaque, conn, domain, opaque['event'], {
        'reason': 'unknown'  # currently unused
    })
1170293
def run_once(self):
        
        packet = _parse_irc_packet(next(self.lines)) #Get next line from generator

        for event_handler in list(self.on_packet_received):
            event_handler(self, packet)

        if packet.command == "PRIVMSG":
            if packet.arguments[0].startswith("#"):
                for event_handler in list(self.on_public_message):
                    event_handler(self, packet.arguments[0], packet.prefix.split("!")[0], packet.arguments[1])
            else:
                for event_handler in list(self.on_private_message):
                    event_handler(self, packet.prefix.split("!")[0], packet.arguments[1])
        elif packet.command == "PING":
            self.send_line("PONG :{}".format(packet.arguments[0]))

            for event_handler in list(self.on_ping):
                event_handler(self)
        elif packet.command == "433" or packet.command == "437":
            #Command 433 is "Nick in use"
            #Add underscore to the nick

            self.set_nick("{}_".format(self.nick))
        elif packet.command == "001":
            for event_handler in list(self.on_welcome):
                event_handler(self)
        elif packet.command == "JOIN":
            for event_handler in list(self.on_join):
                event_handler(self, packet.arguments[0], packet.prefix.split("!")[0])
        elif packet.command == "PART":
            for event_handler in list(self.on_leave):
                event_handler(self, packet.arguments[0], packet.prefix.split("!")[0])
511928
def _prepare_connection(**kwargs):
    '''
    
    '''
    pyeapi_kwargs = __salt__['config.get']('pyeapi', {})
    pyeapi_kwargs.update(kwargs)  # merge the CLI args with the opts/pillar
    init_kwargs, fun_kwargs = __utils__['args.prepare_kwargs'](pyeapi_kwargs, PYEAPI_INIT_KWARGS)
    if 'transport' not in init_kwargs:
        init_kwargs['transport'] = 'https'
    conn = pyeapi.client.connect(**init_kwargs)
    node = pyeapi.client.Node(conn, enablepwd=init_kwargs.get('enablepwd'))
    return node, fun_kwargs
32131
function () {
            var i;
            var self = this;

            /*  determine parameters  */
            var params = $cs.params("publish", arguments, {
                name:         { pos: 0,     req: true            },
                spec:         {             def: {}              },
                async:        {             def: false           },
                capturing:    {             def: true            },
                spreading:    {             def: false           },
                bubbling:     {             def: true            },
                completed:    {             def: _cs.nop         },
                resultinit:   {             def: undefined       },
                resultstep:   {             def: function (a, b) { return b; } },
                directresult: {             def: false           },
                noresult:     {             def: false           },
                firstonly:    {             def: false           },
                silent:       {             def: false           },
                args:         { pos: "...", def: []              }
            });

            /*  short-circuit processing (1/2) to speed up cases
                where no subscribers exist for a local event  */
            var short_circuit = false;
            if (!params.capturing && !params.spreading && !params.bubbling) {
                var subscribers = false;
                for (var id in this.__subscription) {
                    if (!_cs.isown(this.__subscription, id))
                        continue;
                    subscribers = true;
                    break;
                }
                if (!subscribers) {
                    if (params.noresult)
                        return undefined;
                    else if (params.directresult)
                        return params.resultinit;
                    else
                        short_circuit = true;
                }
            }

            /*  create event  */
            var ev = $cs.event({
                name:        params.name,
                spec:        params.spec,
                async:       params.async,
                result:      params.resultinit,
                target:      self,
                propagation: true,
                processing:  true,
                dispatched:  false
            });

            /*  short-circuit processing (2/2)  */
            if (short_circuit)
                return ev;

            /*  tracing  */
            if (!params.silent) {
                $cs.debug(1, "event:" +
                    " " + ev.target().path("/") + ": publish:" +
                    " name=" + ev.name() +
                    " async=" + ev.async() +
                    " capturing=" + params.capturing +
                    " spreading=" + params.spreading +
                    " bubbling=" + params.bubbling +
                    " directresult=" + params.directresult +
                    " noresult=" + params.noresult +
                    " firstonly=" + params.firstonly
                );
            }

            /*  helper function for dispatching event to single component  */
            var event_dispatch_single = function (ev, comp, params, state) {
                for (var id in comp.__subscription) {
                    if (!_cs.isown(comp.__subscription, id))
                        continue;
                    var s = comp.__subscription[id];
                    if (   (   (state === "capturing" && s.capturing)
                            || (state === "targeting"               )
                            || (state === "spreading" && s.spreading)
                            || (state === "bubbling"  && s.bubbling ))
                        && ev.matches(s.name, s.spec)                 ) {

                        /*  verbosity  */
                        if (!params.silent)
                            $cs.debug(1, "event: " + comp.path("/") + ": dispatch " + ev.name() + " to subscriber on " + state);

                        /*  further annotate event object  */
                        ev.state(state);
                        ev.decline(false);

                        /*  call subscription method  */
                        var args = _cs.concat(
                            s.noevent ? [] : [ ev ],
                            s.args,
                            params.args
                        );
                        var result = s.func.apply(s.ctx, args);

                        /*  process return value  */
                        if (s.noevent && _cs.isdefined(result))
                            ev.result(params.resultstep(ev.result(), result));

                        /*  control the further dispatching  */
                        if (!ev.decline()) {
                            ev.dispatched(true);
                            if (params.firstonly)
                                ev.propagation(false);
                        }
                    }
                }
            };

            /*  helper function for dispatching event to all components on hierarchy path  */
            var event_dispatch_all = function (ev, comp, params) {
                /*  determine component tree path  */
                var comp_path;
                if (params.capturing || params.bubbling)
                    comp_path = comp.path();

                /*  phase 1: CAPTURING
                    optionally dispatch event downwards from root component
                    towards target component for capturing subscribers  */
                if (params.capturing) {
                    for (i = comp_path.length - 1; i >= 1; i--) {
                        event_dispatch_single(ev, comp_path[i], params, "capturing");
                        if (!ev.propagation())
                            break;
                    }
                }

                /*  phase 2: TARGETING
                    dispatch event to target component  */
                if (ev.propagation())
                    event_dispatch_single(ev, comp, params, "targeting");

                /*  phase 3: SPREADING
                    dispatch event to all descendant components  */
                if (params.spreading && ev.propagation()) {
                    var visit = function (comp, isTarget) {
                        var cont = true;
                        if (!isTarget) {
                            /*  dispatch on non-target component  */
                            event_dispatch_single(ev, comp, params, "spreading");
                            if (!ev.propagation()) {
                                /*  if propagation should stop, reset the flag again
                                    as in the spreading phase propagation stops only(!)
                                    for the particular sub-tree, not the propagation
                                    process as a whole!  */
                                ev.propagation(true);
                                cont = false;
                            }
                        }
                        if (cont) {
                            /*  dispatch onto all direct child components  */
                            var children = comp.children();
                            for (var i = 0; i < children.length; i++)
                                visit(children[i], false);
                        }
                    };
                    visit(comp, true);
                }

                /*  phase 4: BUBBLING
                    dispatch event upwards from target component towards
                    root component for bubbling (regular) subscribers  */
                if (params.bubbling && ev.propagation()) {
                    for (i = 1; i < comp_path.length; i++) {
                        event_dispatch_single(ev, comp_path[i], params, "bubbling");
                        if (!ev.propagation())
                            break;
                    }
                }

                /*  notify publisher on dispatch completion  */
                params.completed.call(comp, ev);
            };

            /*  perform event publishing,
                either asynchronous or synchronous  */
            if (ev.async())
                /* global setTimeout:false */
                setTimeout(_cs.hook("ComponentJS:settimeout:func", "pass", function () {
                    event_dispatch_all(ev, self, params);
                }), 0);
            else
                event_dispatch_all(ev, self, params);

            /*  return the event, directly the result value or no result value at all  */
            if (params.noresult)
                return undefined;
            else if (params.directresult)
                return ev.result();
            else
                return ev;
        }
633217
def session_prepare(self, session, _):
        
        if not hasattr(session, 'meepo_unique_id'):
            self._session_init(session)

        evt = collections.defaultdict(set)
        for action in ("write", "update", "delete"):
            objs = getattr(session, "pending_%s" % action)
            # filter tables if possible
            if self.tables:
                objs = [o for o in objs
                        if o.__table__.fullname in self.tables]
            for obj in objs:
                evt_name = "%s_%s" % (obj.__table__.fullname, action)
                evt[evt_name].add(obj)
                self.logger.debug("%s - session_prepare: %s -> %s" % (
                    session.meepo_unique_id, evt_name, evt))

        # only trigger signal when event exists
        if evt:
            signal("session_prepare").send(session, event=evt)
28418
@Override
    public void prepare ( CommonServerMessageBlockRequest next ) {
        if ( isReceived() ) {
            next.setSessionId(getSessionId());
        }
        super.prepare(next);
    }
499143
def _process_added_port_event(self, port_name):
        """"""
        LOG.info("Hyper-V VM vNIC added: %s", port_name)
        self._added_ports.add(port_name)
108010
private void dispatchEditEvent(MessageEditEvent event) {
        Optional<Server> optionalServer =
                event.getChannel().asServerChannel().map(ServerChannel::getServer);
        api.getEventDispatcher().dispatchMessageEditEvent(
                optionalServer.map(DispatchQueueSelector.class::cast).orElse(api),
                event.getMessageId(),
                optionalServer.orElse(null),
                event.getChannel(),
                event);
    }
76493
@SuppressWarnings("rawtypes")
    public void prepare(Map stormConf) {
        this.stormConf = stormConf;

        int maxWorkers = Utils.getInt(stormConf.get(Config.STORM_MESSAGING_NETTY_CLIENT_WORKER_THREADS));
        ThreadFactory bossFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "boss");
        ThreadFactory workerFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "worker");

        if (maxWorkers > 0) {
            clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory),
                    Executors.newCachedThreadPool(workerFactory), maxWorkers);
        } else {
            clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory),
                    Executors.newCachedThreadPool(workerFactory));
        }

        reconnector = new ReconnectRunnable();
        new AsyncLoopThread(reconnector, true, Thread.MIN_PRIORITY, true);
    }
1038617
void triggerBasicEvent(Event.EventType type,
                         String message,
                         boolean flushBuffer)
  {
    Event triggeredEvent = new BasicEvent(type, message);

    pushEvent(triggeredEvent, flushBuffer);
  }
716171
def network_delete_event(self, network_info):
        """"""

        net_id = network_info['network_id']
        if net_id not in self.network:
            LOG.error('network_delete_event: net_id %s does not exist.',
                      net_id)
            return

        segid = self.network[net_id].get('segmentation_id')
        tenant_id = self.network[net_id].get('tenant_id')
        tenant_name = self.get_project_name(tenant_id)
        net = utils.Dict2Obj(self.network[net_id])
        if not tenant_name:
            LOG.error('Project %(tenant_id)s does not exist.',
                      {'tenant_id': tenant_id})
            self.update_network_db(net.id, constants.DELETE_FAIL)
            return

        try:
            self.dcnm_client.delete_network(tenant_name, net)
            # Put back the segmentation id into the pool.
            self.seg_drvr.release_segmentation_id(segid)

            # Remove entry from database and cache.
            self.delete_network_db(net_id)
            del self.network[net_id]
            snets = [k for k in self.subnet if (
                self.subnet[k].get('network_id') == net_id)]
            [self.subnet.pop(s) for s in snets]
        except dexc.DfaClientRequestFailed:
            LOG.error('Failed to create network %(net)s.',
                      {'net': net.name})
            self.update_network_db(net_id, constants.DELETE_FAIL)
        # deleting all related VMs
        instances = self.get_vms()
        instances_related = [k for k in instances if k.network_id == net_id]
        for vm in instances_related:
            LOG.debug("deleting vm %s because network is deleted", vm.name)
            self.delete_vm_function(vm.port_id, vm)
        self.network_del_notif(tenant_id, tenant_name, net_id)
919947
def announce(self, msg):
        
        self.print_if_verbose("{} -> {}".format(self.network_uid, msg.__class__.__name__))
        self.__trigger_event__(
            event_class=self.MessageAnnounced,
            msg=msg,
        )
851548
def _create_event_listeners(self):
        """"""
        LOG.debug("Create the event listeners.")
        for event_type, callback in self._event_callback_pairs:
            LOG.debug("Create listener for %r event", event_type)
            listener = self._utils.get_vnic_event_listener(event_type)
            eventlet.spawn_n(listener, callback)