Fire an event off up to the master server

    CLI Example:

    .. code-block:: bash

        salt '*' event.fire_master '{"data":"my event data"}' 'tag'
2022
def fire_master(data, tag, preload=None, timeout=60):
    '''
    
    '''
    if (__opts__.get('local', None) or __opts__.get('file_client', None) == 'local') and not __opts__.get('use_master_when_local', False):
        #  We can't send an event if we're in masterless mode
        log.warning('Local mode detected. Event with tag %s will NOT be sent.', tag)
        return False

    if preload or __opts__.get('__cli') == 'salt-call':
        # If preload is specified, we must send a raw event (this is
        # slower because it has to independently authenticate)
        if 'master_uri' not in __opts__:
            __opts__['master_uri'] = 'tcp://{ip}:{port}'.format(
                    ip=salt.utils.zeromq.ip_bracket(__opts__['interface']),
                    port=__opts__.get('ret_port', '4506')  # TODO, no fallback
                    )
        masters = list()
        ret = None
        if 'master_uri_list' in __opts__:
            for master_uri in __opts__['master_uri_list']:
                masters.append(master_uri)
        else:
            masters.append(__opts__['master_uri'])
        auth = salt.crypt.SAuth(__opts__)
        load = {'id': __opts__['id'],
                'tag': tag,
                'data': data,
                'tok': auth.gen_token(b'salt'),
                'cmd': '_minion_event'}

        if isinstance(preload, dict):
            load.update(preload)

        for master in masters:
            channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
            try:
                channel.send(load, timeout=timeout)
                # channel.send was successful.
                # Ensure ret is True.
                ret = True
            except Exception:
                # only set a False ret if it hasn't been sent atleast once
                if ret is None:
                    ret = False
            finally:
                channel.close()
        return ret
    else:
        # Usually, we can send the event via the minion, which is faster
        # because it is already authenticated
        try:
            me = salt.utils.event.MinionEvent(__opts__, listen=False, keep_loop=True)
            return me.fire_event({'data': data, 'tag': tag, 'events': None, 'pretag': None}, 'fire_master')
        except Exception:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
            log.debug(lines)
            return False
1333860
def handle_event(self, package):
        '''
        
        '''
        if not self.ready:
            raise tornado.gen.Return()
        tag, data = salt.utils.event.SaltEvent.unpack(package)
        log.debug(
            'Minion of \'%s\' is handling event tag \'%s\'',
            self.opts['master'], tag
        )
        tag_functions = {
                         'beacons_refresh': self._handle_tag_beacons_refresh,
                         'environ_setenv': self._handle_tag_environ_setenv,
                         'fire_master': self._handle_tag_fire_master,
                         'grains_refresh': self._handle_tag_grains_refresh,
                         'matchers_refresh': self._handle_tag_matchers_refresh,
                         'manage_schedule': self._handle_tag_manage_schedule,
                         'manage_beacons': self._handle_tag_manage_beacons,
                         '_minion_mine': self._handle_tag_minion_mine,
                         'module_refresh': self._handle_tag_module_refresh,
                         'pillar_refresh': self._handle_tag_pillar_refresh,
                         'salt/auth/creds': self._handle_tag_salt_auth_creds,
                         '_salt_error': self._handle_tag_salt_error,
                         '__schedule_return': self._handle_tag_schedule_return,
                         master_event(type='disconnected'): self._handle_tag_master_disconnected_failback,
                         master_event(type='failback'): self._handle_tag_master_disconnected_failback,
                         master_event(type='connected'): self._handle_tag_master_connected,
                         }

        # Run the appropriate function
        for tag_function in tag_functions:
            if tag.startswith(tag_function):
                tag_functions[tag_function](tag, data)
87498
def on_pubmsg(self, connection, event):
        
        for message in event.arguments():
            self.log(event, message)
            command_args = filter(None, message.split())
            command_name = command_args.pop(0)
            for handler in self.events["command"]:
                if handler.event.args["command"] == command_name:
                    self.handle_command_event(event, handler, command_args)
822958
private void fireEvent(ManagerEvent event)
    {
        synchronized (eventListeners)
        {
            for (ManagerEventListener listener : eventListeners)
            {
                try
                {
                    listener.onManagerEvent(event);
                }
                catch (RuntimeException e)
                {
                    logger.warn("Unexpected exception in eventHandler " + listener.getClass().getName(), e);
                }
            }
        }
    }
111533
def process_key_event(self, event_data):
        '''
        
        '''

        tag = event_data['tag']
        event_info = event_data['data']

        if event_info['act'] == 'delete':
            self.minions.pop(event_info['id'], None)
        elif event_info['act'] == 'accept':
            self.minions.setdefault(event_info['id'], {})

        self.publish_minions()
258306
def _fire_master(self, data=None, tag=None, events=None, pretag=None, timeout=60, sync=True, timeout_handler=None):
        '''
        
        '''
        load = {'id': self.opts['id'],
                'cmd': '_minion_event',
                'pretag': pretag,
                'tok': self.tok}
        if events:
            load['events'] = events
        elif data and tag:
            load['data'] = data
            load['tag'] = tag
        elif not data and tag:
            load['data'] = {}
            load['tag'] = tag
        else:
            return

        if sync:
            try:
                self._send_req_sync(load, timeout)
            except salt.exceptions.SaltReqTimeoutError:
                log.info('fire_master failed: master could not be contacted. Request timed out.')
                # very likely one of the masters is dead, status.master will flush it
                self.functions['status.master'](self.opts['master'])
                return False
            except Exception:
                log.info('fire_master failed: %s', traceback.format_exc())
                return False
        else:
            if timeout_handler is None:
                def handle_timeout(*_):
                    log.info('fire_master failed: master could not be contacted. Request timed out.')
                    # very likely one of the masters is dead, status.master will flush it
                    self.functions['status.master'](self.opts['master'])
                    return True
                timeout_handler = handle_timeout

            with tornado.stack_context.ExceptionStackContext(timeout_handler):
                self._send_req_async(load, timeout, callback=lambda f: None)  # pylint: disable=unexpected-keyword-arg
        return True
158644
private void handleCommand(MetaCommand cmd) throws IOException {
    if (cmd == null) {
      return;
    }
    switch (cmd) {
      case MetaCommand_Nothing:
        break;
      // Leader master requests re-registration
      case MetaCommand_Register:
        setIdAndRegister();
        break;
      // Unknown request
      case MetaCommand_Unknown:
        LOG.error("Master heartbeat sends unknown command {}", cmd);
        break;
      default:
        throw new RuntimeException("Un-recognized command from leader master " + cmd);
    }
  }
591804
def get_master_event(opts, sock_dir, listen=True, io_loop=None, raise_errors=False, keep_loop=False):
    '''
    
    '''
    # TODO: AIO core is separate from transport
    if opts['transport'] in ('zeromq', 'tcp', 'detect'):
        return MasterEvent(sock_dir, opts, listen=listen, io_loop=io_loop, raise_errors=raise_errors, keep_loop=keep_loop)
800891
def _minion_event(self, load):
        '''
        
        '''
        if 'id' not in load:
            return False
        if 'events' not in load and ('tag' not in load or 'data' not in load):
            return False
        if 'events' in load:
            for event in load['events']:
                if 'data' in event:
                    event_data = event['data']
                else:
                    event_data = event
                self.event.fire_event(event_data, event['tag'])  # old dup event
                if load.get('pretag') is not None:
                    self.event.fire_event(event_data, salt.utils.event.tagify(event['tag'], base=load['pretag']))
        else:
            tag = load['tag']
            self.event.fire_event(load, tag)
        return True
306171
def fire_on_load(name)
      procs = (self.callbacks['ANY'] || RConfig::EMPTY_ARRAY) + (self.callbacks[name] || RConfig::EMPTY_ARRAY)
      procs.uniq!
      logger.debug "fire_on_load(#{name.inspect}): callbacks[#{procs.inspect}]" unless procs.empty?
      procs.each { |proc| proc.call() }
    end
1133021
def handle_command_event(self, event, command, args):
        
        argspec = getargspec(command)
        num_all_args = len(argspec.args) - 2  # Ignore self/event args
        num_pos_args = num_all_args - len(argspec.defaults or [])
        if num_pos_args <= len(args) <= num_all_args:
            response = command(self, event, *args)
        elif num_all_args == num_pos_args:
            s = "s are" if num_all_args != 1 else " is"
            response = "%s arg%s required" % (num_all_args, s)
        else:
            bits = (num_pos_args, num_all_args)
            response = "between %s and %s args are required" % bits
        response = "%s: %s" % (self.get_nickname(event), response)
        self.message_channel(response)
533297
function(event, id, msg) {
      var self = this;
      var events = self['_on' + event];

      // Loop through event store and fire all functions.
      for (var i=events.length-1; i>=0; i--) {
        // Only fire the listener if the correct ID is used.
        if (!events[i].id || events[i].id === id || event === 'load') {
          setTimeout(function(fn) {
            fn.call(this, id, msg);
          }.bind(self, events[i].fn), 0);

          // If this event was setup with `once`, remove it.
          if (events[i].once) {
            self.off(event, events[i].fn, events[i].id);
          }
        }
      }

      // Pass the event type into load queue so that it can continue stepping.
      self._loadQueue(event);

      return self;
    }
647469
function _fireResume()
        {
            exec(
                    function ()
                    {
                        window.console.log(JS_HANDLE
                                + ": fired resume event to native plugin");
                    },
                    _logError,
                    CDV_HANDLE,
                    CDV_HANDLE_ACTIONS.APP_RESUMED,
                    []
            );
        }
1033478
private function fireEvent()
    {
        $status = isset($this->response['error_code']) ? VkRequest::STATUS_FAIL : VkRequest::STATUS_SUCCESS;
        $event = sprintf(VkRequest::EVENT_FORMAT, $status, $this->request->method, $this->request->tag);
        event($event, [$this->request, $this->response]);
    }
229387
def fire(self, exc=None, data=None):
        
        o = self._self

        if o is not None:
            handlers = self._handlers
            if self._onetime:
                self._handlers = None
                self._self = None

            if handlers:
                if exc is not None:
                    for hnd in handlers:
                        hnd(o, exc=exc)
                elif data is not None:
                    for hnd in handlers:
                        hnd(o, data=data)
                else:
                    for hnd in handlers:
                        hnd(o)

            if self._waiter:
                if exc:
                    self._waiter.set_exception(exc)
                else:
                    self._waiter.set_result(data if data is not None else o)
                self._waiter = None
565248
def fire_event(event, record, persist, *args)
      handle_state_exit_callback record
      if new_state = transition_to_new_state(record, event, *args)
        handle_state_enter_callback record, new_state
        handle_event_fired_callback record, new_state, event
        record.update_current_state(new_state, persist)
        handle_event_success_callback record, event
        return true
      else
        handle_event_failed_callback record, event
        return false
      end
    rescue => e
      raise e unless record.respond_to?(:event_failed)
      record.send(:event_failed, event)
      return false
    end
625674
def event_return(events):
    '''
    
    '''
    with _get_serv(events, commit=True) as cur:
        for event in events:
            tag = event.get('tag', '')
            data = event.get('data', '')
            sql = '''INSERT INTO `salt_events` (`tag`, `data`, `master_id`)
                     VALUES (%s, %s, %s)'''
            cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id']))