Ejemplo n.º 1
0
def monitoring_probe_cpu(http_context, config=None, sessions=None):
    check_sessionid(http_context['headers'], sessions)

    try:
        output = api_run_probe(probe_cpu(config.plugins['monitoring']), config)
        return output
    except Exception as e:
        logger.error(str(e.message))
        raise HTTPError(500, "Internal error.")
Ejemplo n.º 2
0
def api_function_wrapper(config, http_context, sessions, module, function_name):
    """
    API function wrapper in charge of:
        - instanciate a new logger;
        - check the user session id;
        - call a function named 'function_name' from 'module_name' module and return its result;
    """
    logger = get_logger(config)
    logger.debug("Calling %s.%s()." % (module.__name__, function_name,))
    logger.debug(http_context)

    try:
        username = check_sessionid(http_context['headers'], sessions)
        http_context['username'] = username
        dm = getattr(module, function_name)(config, http_context)
        logger.debug("Done.")
        return dm

    except (Exception, HTTPError) as e:
        logger.traceback(get_tb())
        logger.error(str(e))
        logger.debug("Failed.")
        if isinstance(e, HTTPError):
            raise e
        else:
            raise HTTPError(500, "Internal error.")
Ejemplo n.º 3
0
def supervision_probe_blocks(http_context,
                             queue_in=None,
                             config=None,
                             sessions=None,
                             commands=None):
    set_logger_name("supervision")
    logger = get_logger(config)
    check_sessionid(http_context['headers'], sessions)

    try:
        output = api_run_probe(probe_blocks(config.plugins['supervision']),
                               config)
        return output
    except (Exception, error) as e:
        logger.error(str(e.message))
        raise HTTPError(500, "Internal error.")
Ejemplo n.º 4
0
def api_function_wrapper(config, http_context, sessions, module,
                         function_name):
    """
    Simple API function wrapper in charge of:
        - instanciate a new logger;
        - check the user session id;
        - call a function named 'function_name' from 'module_name' module and return its result;
    """
    logger = get_logger(config)
    logger.info("%s - %s" % (
        module.__name__,
        function_name,
    ))
    username = check_sessionid(http_context['headers'], sessions)

    http_context['username'] = username
    try:
        dm = getattr(module, function_name)(config, http_context)
        return dm
    except HTTPError as e:
        logger.error(format_exc())
        raise HTTPError(e.code, e.message['error'])
    except Exception as e:
        logger.error(format_exc())
        raise HTTPError(500, "Internal error.")
Ejemplo n.º 5
0
def api_function_wrapper_pg(config, http_context, sessions, module,
                            function_name):
    """
    API function wrapper in charge of:
        - instanciating a new logger;
        - check the user session id;
        - start a new PostgreSQL connection;
        - call the function 'function_name' from 'module_name' module and
          return its result;
        - close PG connection.
    """
    logger.debug("Calling %s.%s()." % (
        module.__name__,
        function_name,
    ))
    logger.debug(http_context)

    try:
        username = check_sessionid(http_context['headers'], sessions)
        http_context['username'] = username
        conn = connector(host=config.postgresql['host'],
                         port=config.postgresql['port'],
                         user=config.postgresql['user'],
                         password=config.postgresql['password'],
                         database=config.postgresql['dbname'])
        conn.connect()
        dm = getattr(module, function_name)(conn, config, http_context)
        conn.close()
        logger.debug("Done.")
        return dm

    except (error, Exception, HTTPError) as e:
        logger.exception(str(e))
        logger.debug("Failed.")
        try:
            conn.close()
        except Exception:
            pass
        if isinstance(e, HTTPError):
            raise e
        else:
            raise HTTPError(500, "Internal error.")
Ejemplo n.º 6
0
def api_function_wrapper_pg(config, http_context, sessions, module,
                            function_name):
    """
    Simple API function wrapper in charge of:
        - instanciate a new logger;
        - check the user session id;
        - start a new PostgreSQL connexion;
        - call a function named 'function_name' from 'module_name' module and return its result;
        - close the PG connexion.
    """
    logger = get_logger(config)
    logger.info("%s - %s" % (
        module.__name__,
        function_name,
    ))
    username = check_sessionid(http_context['headers'], sessions)

    http_context['username'] = username

    conn = connector(host=config.postgresql['host'],
                     port=config.postgresql['port'],
                     user=config.postgresql['user'],
                     password=config.postgresql['password'],
                     database=config.postgresql['dbname'])
    try:
        conn.connect()
        dm = getattr(module, function_name)(conn, config, http_context)
        conn.close()
        return dm

    except (error, Exception, HTTPError) as e:
        logger.error(format_exc())
        try:
            conn.close()
        except Exception:
            pass
        if isinstance(e, HTTPError):
            raise HTTPError(e.code, e.message['error'])
        else:
            raise HTTPError(500, "Internal error.")
Ejemplo n.º 7
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.")