示例#1
0
def post_pg_control(http_context, app):
    # Control instance
    validate_parameters(http_context['post'], [
        ('action', T_CONTROL, False)
    ])
    action = http_context['post']['action']
    logger.info("PostgreSQL '%s' requested." % action)
    NotificationMgmt.push(app.config,
                          Notification(username=http_context['username'],
                                       message="PostgreSQL %s" % action))

    cmd = app.config.administration.pg_ctl % action
    cmd_args = oneline_cmd_to_array(cmd)
    (rcode, stdout, stderr) = exec_script(cmd_args)
    if rcode != 0:
        raise Exception(str(stderr))
    # Let's check if PostgreSQL is up & running after having executed
    # 'start' or 'restart' action.
    if action in ['start', 'restart']:
        # When a start/restart operation is requested, after the
        # startup/pg_ctl script has been executed then we check that
        # postgres is up & running:
        # while the PG conn. is not working then, for 10 seconds (max)
        # we'll check (connect/SELECT 1/disconnect) the connection, every
        # 0.5 second.
        retry = True
        t_start = time.time()
        while retry:
            try:
                with app.postgres.connect() as conn:
                    conn.execute('SELECT 1')
                    logger.info("Done.")
                    return dict(action=action, state='ok')
            except error:
                if (time.time() - t_start) > 10:
                    logger.info("Failed.")
                    return dict(action=action, state='ko')
            logger.info("Retrying...")
            time.sleep(0.5)

    elif action == 'stop':
        # Check the PG conn is not working anymore.
        try:
            retry = True
            t_start = time.time()
            while retry:
                with app.postgres.connect() as conn:
                    conn.execute('SELECT 1')
                time.sleep(0.5)
                if (time.time() - t_start) > 10:
                    retry = False
            logger.info("Failed.")
            return dict(action=action, state='ko')
        except error:
            logger.info("Done.")
            return dict(action=action, state='ok')

    elif action == 'reload':
        logger.info("Done.")
        return dict(action=action, state='ok')
示例#2
0
def say_hello_something4(config, http_context):
    """
    "Hello <something>" using slug & exec_command.

    Usage:
    $ export XSESSION=`curl -s -k -X POST --data '{"username":"******", "password":"******"}' https://localhost:2345/login | sed -E "s/^.+\"([a-f0-9]+)\".+$/\1/"`
    $ curl -s -k -H "X-Session:$XSESSION" "https://localhost:2345/hello4/toto" | python -m json.tool
    {
        "content": "Hello toto"
    }
    """
    from temboardagent.command import exec_command, oneline_cmd_to_array
    (return_code, stdout, stderr) = exec_command(oneline_cmd_to_array("echo 'Hello %s'" % (http_context['urlvars'][0])))
    return {"content": stdout[:-1]}
示例#3
0
def post_pg_control(http_context, queue_in = None, config = None, sessions = None, commands = None):
    # NOTE: in this case we don't want to use api functions wrapper, it leads
    # to "Broken pipe" error with debian init.d on start/restart. This is
    # probably due to getattr() call.
    set_logger_name("administration")
    # Get a new logger.
    logger = get_logger(config)
    check_sessionid(http_context['headers'], sessions)
    post = http_context['post']
    # Check POST parameters.
    validate_parameters(post, [
        ('action', T_CONTROL, False)
    ])

    try:
        session = sessions.get_by_sessionid(http_context['headers']['X-Session'].encode('utf-8'))
        NotificationMgmt.push(config, Notification(
                                        username = session.username,
                                        message = "PostgreSQL %s" % (post['action'])))
    except NotificationError as e:
        logger.error(e.message)

    cmd_args = oneline_cmd_to_array(config.plugins['administration']['pg_ctl'] % (post['action']))
    (rcode, stdout, stderr) = exec_script(cmd_args)
    if rcode != 0:
        raise HTTPError(408, str(stderr))
    # Let's check if postgresql is up & running on 'start' or 'restart' action.
    if post['action'] in ['start', 'restart']:
        conn = connector(
            host = config.postgresql['host'],
            port = config.postgresql['port'],
            user = config.postgresql['user'],
            password = config.postgresql['password'],
            database = config.postgresql['dbname']
        )
        # When a start/restart operation is requested, after the startup/pg_ctl
        # script is executed we check that postgres is up & running: while the
        # PG connection is not working, during 10 seconds (max) we'll check
        # (connect/SELECT 1/disconnect) the connection, every 0.5 second.
        retry = True
        t_start = time.time()
        while retry:
            try:
                conn.connect()
                conn.execute('SELECT 1')
                conn.close()
                return {'action': post['action'], 'state': 'ok'}
            except error as e:
                if (time.time() - t_start) > 10:
                    try:
                        conn.close()
                    except error as e:
                        pass
                    except Exception:
                        pass
                    return {'action': post['action'], 'state': 'ko'}
            time.sleep(0.5)

    elif post['action'] == 'stop':
        conn = connector(
            host = config.postgresql['host'],
            port = config.postgresql['port'],
            user = config.postgresql['user'],
            password = config.postgresql['password'],
            database = config.postgresql['dbname']
        )
        # Check the PG conn is not working anymore.
        try:
            retry = True
            t_start = time.time()
            while retry:
                conn.connect()
                conn.execute('SELECT 1')
                conn.close()
                time.sleep(0.5)
                if (time.time() - t_start) > 10:
                    retry = False
            return {'action': post['action'], 'state': 'ko'}
        except error as e:
            return {'action': post['action'], 'state': 'ok'}
    return {'action': post['action'], 'state': 'ok'}
示例#4
0
def post_pg_control(http_context, config=None, sessions=None):
    # NOTE: in this case we don't want to use api functions wrapper, it leads
    # to "Broken pipe" error with debian init.d script on start/restart.
    # This is probably due to getattr() call.
    post = http_context['post']

    try:
        check_sessionid(http_context['headers'], sessions)
        # Check POST parameters.
        validate_parameters(post, [('action', T_CONTROL, False)])
        session = sessions.get_by_sessionid(
            http_context['headers']['X-Session'].encode('utf-8'))
    except (Exception, HTTPError) as e:
        logger.exception(str(e))
        logger.debug(http_context)
        if isinstance(e, HTTPError):
            raise e
        else:
            raise HTTPError(500, "Internal error.")

    try:
        NotificationMgmt.push(
            config,
            Notification(username=session.username,
                         message="PostgreSQL %s" % post['action']))
    except (NotificationError, Exception) as e:
        logger.exception(str(e))

    try:
        logger.info("PostgreSQL '%s' requested." % (post['action']))
        cmd_args = oneline_cmd_to_array(
            config.plugins['administration']['pg_ctl'] % (post['action']))
        (rcode, stdout, stderr) = exec_script(cmd_args)
        if rcode != 0:
            raise Exception(str(stderr))
        # Let's check if PostgreSQL is up & running after having executed
        # 'start' or 'restart' action.
        if post['action'] in ['start', 'restart']:
            conn = connector(host=config.postgresql['host'],
                             port=config.postgresql['port'],
                             user=config.postgresql['user'],
                             password=config.postgresql['password'],
                             database=config.postgresql['dbname'])
            # When a start/restart operation is requested, after the
            # startup/pg_ctl script has been executed then we check that
            # postgres is up & running:
            # while the PG conn. is not working then, for 10 seconds (max)
            # we'll check (connect/SELECT 1/disconnect) the connection, every
            # 0.5 second.
            retry = True
            t_start = time.time()
            while retry:
                try:
                    conn.connect()
                    conn.execute('SELECT 1')
                    conn.close()
                    logger.info("Done.")
                    return {'action': post['action'], 'state': 'ok'}
                except error:
                    if (time.time() - t_start) > 10:
                        try:
                            conn.close()
                        except error:
                            pass
                        except Exception:
                            pass
                        logger.info("Failed.")
                        return {'action': post['action'], 'state': 'ko'}
                time.sleep(0.5)

        elif post['action'] == 'stop':
            conn = connector(host=config.postgresql['host'],
                             port=config.postgresql['port'],
                             user=config.postgresql['user'],
                             password=config.postgresql['password'],
                             database=config.postgresql['dbname'])
            # Check the PG conn is not working anymore.
            try:
                retry = True
                t_start = time.time()
                while retry:
                    conn.connect()
                    conn.execute('SELECT 1')
                    conn.close()
                    time.sleep(0.5)
                    if (time.time() - t_start) > 10:
                        retry = False
                logger.info("Failed.")
                return {'action': post['action'], 'state': 'ko'}
            except error:
                logger.info("Done.")
                return {'action': post['action'], 'state': 'ok'}
        logger.info("Done.")
        return {'action': post['action'], 'state': 'ok'}
    except (Exception, error, HTTPError) as e:
        logger.exception(str(e))
        logger.info("Failed")
        if isinstance(e, HTTPError):
            raise e
        else:
            raise HTTPError(500, "Internal error.")