Return event to a postgres server

    Require that configuration be enabled via 'event_return'
    option in master config.
480418
def event_return(events):
    '''
    
    '''
    conn = _get_conn()
    if conn is None:
        return None
    cur = conn.cursor()
    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']))
    _close_conn(conn)
941785
def return_pub(self, ret):
        '''
        
        '''
        channel = salt.transport.client.ReqChannel.factory(self.opts, usage='salt_call')
        load = {'cmd': '_return', 'id': self.opts['id']}
        for key, value in six.iteritems(ret):
            load[key] = value
        try:
            channel.send(load)
        finally:
            channel.close()
1291486
def returner(ret):
    '''
    
    '''
    log.debug('sqlite3 returner <returner> called with data: %s', ret)
    conn = _get_conn(ret)
    cur = conn.cursor()
    sql = '''INSERT INTO salt_returns
             (fun, jid, id, fun_args, date, full_ret, success)
             VALUES (:fun, :jid, :id, :fun_args, :date, :full_ret, :success)'''
    cur.execute(sql,
                {'fun': ret['fun'],
                 'jid': ret['jid'],
                 'id': ret['id'],
                 'fun_args': six.text_type(ret['fun_args']) if ret.get('fun_args') else None,
                 'date': six.text_type(datetime.datetime.now()),
                 'full_ret': salt.utils.json.dumps(ret['return']),
                 'success': ret.get('success', '')})
    _close_conn(conn)
99715
def event_return(events):
    '''
    
    '''
    conn, mdb = _get_conn(ret=None)

    if isinstance(events, list):
        events = events[0]

    if isinstance(events, dict):
        log.debug(events)

        if PYMONGO_VERSION > _LooseVersion('2.3'):
            mdb.events.insert_one(events.copy())
        else:
            mdb.events.insert(events.copy())
369570
def _return_handler(self, ret_value, func, arguments):
        

        logger.debug('%s%s -> %r',
                     func.__name__, _args_to_str(arguments), ret_value,
                     extra=self._logging_extra)

        try:
            ret_value = StatusCode(ret_value)
        except ValueError:
            pass

        self._last_status = ret_value

        # The first argument of almost all registered visa functions is a session.
        # We store the error code per session
        session = None
        if func.__name__ not in ('viFindNext', ):
            try:
                session = arguments[0]
            except KeyError:
                raise Exception('Function %r does not seem to be a valid '
                                'visa function (len args %d)' % (func, len(arguments)))

            # Functions that use the first parameter to get a session value.
            if func.__name__ in ('viOpenDefaultRM', ):
                # noinspection PyProtectedMember
                session = session._obj.value

            if isinstance(session, integer_types):
                self._last_status_in_session[session] = ret_value
            else:
                # Functions that might or might have a session in the first argument.
                if func.__name__ not in ('viClose', 'viGetAttribute', 'viSetAttribute', 'viStatusDesc'):
                    raise Exception('Function %r does not seem to be a valid '
                                    'visa function (type args[0] %r)' % (func, type(session)))

        if ret_value < 0:
            raise errors.VisaIOError(ret_value)

        if ret_value in self.issue_warning_on:
            if session and ret_value not in self._ignore_warning_in_session[session]:
                warnings.warn(errors.VisaIOWarning(ret_value), stacklevel=2)

        return ret_value
1002806
function(sql, callback){
    pg.connect(this.conn, function(err, client, done) {
      if(err) {
        return console.error('!error fetching client from pool', err);
      }
      client.query(sql, function(err, result) {
        //call `done()` to release the client back to the pool
        done();
        if ( callback ) {
          callback(err, result);
        }
      });
    });

  }
807337
def permit_event(self, column=None, value=None, **kwargs):
        
        return self._resolve_call('PCS_PERMIT_EVENT', column, value, **kwargs)
168943
def returner(ret):
    '''
    
    '''

    _options = _get_options(ret)
    from_addr = _options.get('from')
    to_addrs = _options.get('to').split(',')
    host = _options.get('host')
    port = _options.get('port')
    user = _options.get('username')
    passwd = _options.get('password')
    subject = _options.get('subject') or 'Email from Salt'
    gpgowner = _options.get('gpgowner')
    fields = _options.get('fields').split(',') if 'fields' in _options else []
    smtp_tls = _options.get('tls')

    renderer = _options.get('renderer') or 'jinja'
    rend = salt.loader.render(__opts__, {})
    blacklist = __opts__.get('renderer_blacklist')
    whitelist = __opts__.get('renderer_whitelist')

    if not port:
        port = 25
    log.debug('SMTP port has been set to %s', port)

    for field in fields:
        if field in ret:
            subject += ' {0}'.format(ret[field])
    subject = compile_template(':string:',
                               rend,
                               renderer,
                               blacklist,
                               whitelist,
                               input_data=subject,
                               **ret)
    if isinstance(subject, six.moves.StringIO):
        subject = subject.read()
    log.debug("smtp_return: Subject is '%s'", subject)

    template = _options.get('template')
    if template:
        content = compile_template(template, rend, renderer, blacklist, whitelist, **ret)
    else:
        template = ('id: {{id}}\r\n'
                    'function: {{fun}}\r\n'
                    'function args: {{fun_args}}\r\n'
                    'jid: {{jid}}\r\n'
                    'return: {{return}}\r\n')
        content = compile_template(':string:',
                                   rend,
                                   renderer,
                                   blacklist,
                                   whitelist,
                                   input_data=template,
                                   **ret)

    if gpgowner:
        if HAS_GNUPG:
            gpg = gnupg.GPG(gnupghome=os.path.expanduser('~{0}/.gnupg'.format(gpgowner)),
                            options=['--trust-model always'])
            encrypted_data = gpg.encrypt(content, to_addrs)
            if encrypted_data.ok:
                log.debug('smtp_return: Encryption successful')
                content = six.text_type(encrypted_data)
            else:
                log.error('smtp_return: Encryption failed, only an error message will be sent')
                content = 'Encryption failed, the return data was not sent.\r\n\r\n{0}\r\n{1}'.format(
                    encrypted_data.status, encrypted_data.stderr)
        else:
            log.error("gnupg python module is required in order to user gpgowner in smtp returner ; ignoring gpgowner configuration for now")
    if isinstance(content, six.moves.StringIO):
        content = content.read()

    message = ('From: {0}\r\n'
               'To: {1}\r\n'
               'Date: {2}\r\n'
               'Subject: {3}\r\n'
               '\r\n'
               '{4}').format(from_addr,
                             ', '.join(to_addrs),
                             formatdate(localtime=True),
                             subject,
                             content)

    log.debug('smtp_return: Connecting to the server...')
    server = smtplib.SMTP(host, int(port))
    if smtp_tls is True:
        server.starttls()
        log.debug('smtp_return: TLS enabled')
    if user and passwd:
        server.login(user, passwd)
        log.debug('smtp_return: Authenticated')
    # enable logging SMTP session after the login credentials were passed
    server.set_debuglevel(1)
    server.sendmail(from_addr, to_addrs, message)
    log.debug('smtp_return: Message sent.')
    server.quit()
1254646
def returner(ret):
    '''
    
    '''
    try:
        with _get_serv(ret, commit=True) as cur:
            sql = '''INSERT INTO salt_returns
                    (fun, jid, return, id, success, full_ret, alter_time)
                    VALUES (%s, %s, %s, %s, %s, %s, to_timestamp(%s))'''

            cur.execute(sql, (ret['fun'], ret['jid'],
                              psycopg2.extras.Json(ret['return']),
                              ret['id'],
                              ret.get('success', False),
                              psycopg2.extras.Json(ret),
                              time.time()))
    except salt.exceptions.SaltMasterError:
        log.critical('Could not store return with pgjsonb returner. PostgreSQL server unavailable.')
1104518
def output(self):
        
        return PostgresTarget(
            host=self.host,
            database=self.database,
            user=self.user,
            password=self.password,
            table=self.table,
            update_id=self.update_id,
            port=self.port
        )
582269
def _get_serv(ret=None, commit=False):
    '''
    
    '''
    _options = _get_options(ret)
    try:
        conn = psycopg2.connect(host=_options.get('host'),
                                user=_options.get('user'),
                                password=_options.get('passwd'),
                                database=_options.get('db'),
                                port=_options.get('port'))

    except psycopg2.OperationalError as exc:
        raise salt.exceptions.SaltMasterError('postgres returner could not connect to database: {exc}'.format(exc=exc))

    cursor = conn.cursor()

    try:
        yield cursor
    except psycopg2.DatabaseError as err:
        error = err.args
        sys.stderr.write(six.text_type(error))
        cursor.execute("ROLLBACK")
        raise err
    else:
        if commit:
            cursor.execute("COMMIT")
        else:
            cursor.execute("ROLLBACK")
    finally:
        conn.close()
181240
def p_return(p):
    
    if not FUNCTION_LEVEL:  # At less one level, otherwise, this return is from a GOSUB
        p[0] = make_sentence('RETURN')
        return

    if FUNCTION_LEVEL[-1].kind != KIND.sub:
        syntax_error(p.lineno(1), 'Syntax Error: Functions must RETURN a value, or use EXIT FUNCTION instead.')
        p[0] = None
        return

    p[0] = make_sentence('RETURN', FUNCTION_LEVEL[-1])
1291975
def trigger_event(event=None, **kwargs):
    '''
    
    '''

    res = {'result': False, 'message': 'Something went wrong'}

    data = {}
    for value in ('value1', 'value2', 'value3',
                  'Value1', 'Value2', 'Value3'):
        if value in kwargs:
            data[value.lower()] = kwargs[value]
    data['occurredat'] = time.strftime("%B %d, %Y %I:%M%p", time.localtime())
    result = _query(event=event,
                    method='POST',
                    data=salt.utils.json.dumps(data)
                    )
    if 'status' in result:
        if result['status'] == 200:
            res['result'] = True
            res['message'] = result['text']
        else:
            if 'error' in result:
                res['message'] = result['error']
    return res
1114659
def event_return(events):
    '''
    
    '''
    if not events:
        # events is an empty list.
        # Don't open the logfile in vain.
        return
    opts = _get_options({})  # Pass in empty ret, since this is a list of events
    try:
        with salt.utils.files.flopen(opts['filename'], 'a') as logfile:
            for event in events:
                salt.utils.json.dump(event, logfile)
                logfile.write(str('\n'))  # future lint: disable=blacklisted-function
    except Exception:
        log.error('Could not write to rawdata_json file %s', opts['filename'])
        raise
1046050
def event_return(events):
    '''
    
    '''
    _options = _get_options()

    api_url = _options.get('api_url')
    channel = _options.get('channel')
    username = _options.get('username')
    hook = _options.get('hook')

    is_ok = True
    for event in events:
        log.debug('Event: %s', event)
        log.debug('Event data: %s', event['data'])
        message = 'tag: {0}\r\n'.format(event['tag'])
        for key, value in six.iteritems(event['data']):
            message += '{0}: {1}\r\n'.format(key, value)
        result = post_message(channel,
                              message,
                              username,
                              api_url,
                              hook)
        if not result:
            is_ok = False

    return is_ok
1329413
function pubServer(opts) {

  if (!(this instanceof pubServer)) return new pubServer(opts);
  events.EventEmitter.call(this);

  var server = this;

  // pass platform-specific ./node_modules path to resolve-opts for builtin packages
  server.opts = opts = require('pub-resolve-opts')(opts, path.join(__dirname, 'node_modules'));

  opts.production  = opts.production || (process.env.NODE_ENV === 'production');
  opts.port        = opts.port       || process.env.PORT || '3001';
  opts.appUrl      = opts.appUrl     || process.env.APP  || ('http://localhost:' + opts.port);

  server.run       = run;

  var generator = server.generator = require('pub-generator')(opts);

  u.each(opts.serverPlugins.reverse(), function(plugin) {
    debug('server plugin:', plugin.inspect());
    require(plugin.path)(server);
  });

  u.each(opts.generatorPlugins.reverse(), function(plugin) {
    debug('generator plugin:', plugin.path, plugin.inspect());
    require(plugin.path)(generator);
  });

  var log = opts.log;

  //--//--//--//--//--//--//--//--//--//--//--//

  function run() {
    generator.load(function(err) {
      if (err) return log(err);

      if (opts.outputOnly) {
        generator.outputPages(function(err, result) {
          if (err) { log(err); }
          log('output %s generated pages', u.flatten(result).length);
        });

        var statics = require('./server/serve-statics')(opts, function(){
          statics.outputAll();
        });
        require('./server/serve-scripts')(opts).outputAll(generator);
        generator.unload();
        return;
      }

      if (opts.logPages) {
        generator.logPages();
        generator.unload();
        return;
      }

      require('./server/watch-sources')(generator);
      generator.listen(true);

      if (!opts['no-server']) { expressApp(); }
    });
  }

  function expressApp() {

    server.app =  require('express')();
    server.http = require('http').Server(server.app);
    require('./server/serve-sockets')(server);

    server.app.disable('x-powered-by');

    // log(err) shouldn't throw anymore
    log.logger.noErrors = true;

    // sessions come with optional redis logger
    server.sessions = require('pub-serve-sessions')(server);
    log('starting up', opts.appUrl);

    // other default middleware
    var bodyParser = require('body-parser');
    server.app.use(bodyParser.json());
    server.app.use(bodyParser.urlencoded({ extended: false }));
    server.app.use(require('compression')());

    server.emit('init-app-first');
    server.sessions.authorizeRoutes();

    if (!opts.staticOnly) {
      require('./server/serve-pages')(server);
      server.scripts = require('./server/serve-scripts')(opts).serveRoutes(server);
    }
    server.statics = require('./server/serve-statics')(opts).serveRoutes(server);

    server.emit('init-app-last');

    require('./server/handle-errors')(server);

    server.http.listen(opts.port);
    log('listening on port', opts.port);

    process.on('SIGTERM', function() {
      log('shutting down');
      server.http.close(function() {
        generator.unload();
        server.emit('shutdown');
        process.exit();
      });
    });

  }

}
1299198
def make_event(event: Callable) -> Callable:
    """"""
    @property  # type: ignore
    @wraps(event)
    def actualevent(self):  # pylint: disable=missing-docstring
        name = event.__name__[3:]
        try:
            # the getter post processing function
            # is preserved with an underscore
            getter = event(self).__name__
        except AttributeError:
            getter = None
        return Event(name, self._uuid, getter)  # pylint: disable=protected-access

    return actualevent