Example #1
0
def cancel_scheduled_operation(id, app):
    # Cancel one scheduled operation. If the operation is running, the task
    # is going to be aborted.

    # Check the id
    if id not in [
            t['id'] for t in list_scheduled_vacuum(app) +
            list_scheduled_analyze(app) + list_scheduled_reindex(app)
    ]:
        raise HTTPError(404, "Scheduled operation not found")

    try:
        # Ask it to the task manager
        taskmanager.TaskManager.send_message(
            str(os.path.join(app.config.temboard.home, '.tm.socket')),
            taskmanager.Message(
                taskmanager.MSG_TYPE_TASK_CANCEL,
                dict(task_id=id),
            ),
            authkey=None,
        )
    except Exception as e:
        logger.exception(str(e))
        raise HTTPError(500, "Unable to cancel operation")

    return dict(response="ok")
Example #2
0
def get_hello_from_worker(http_context, app):
    """
    "Hello <something>" using configuration.

    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/hello/from_worker" | python -m json.tool
    {
        "content": "Hello toto"
    }
    """  # noqa
    tm_sock_path = os.path.join(
        app.config.temboard['home'], '.tm.socket').encode('ascii')
    logger.info("Listing tasks.")
    task_list_resp = taskmanager.TaskManager.send_message(
        tm_sock_path,
        taskmanager.Message(taskmanager.MSG_TYPE_TASK_LIST, None),
        authkey=None,
    )
    for task_data in task_list_resp:
        if task_data['worker_name'] == worker_hello.__name__:
            break
    else:
        raise Exception("Worker didn't run")

    return task_data['output']
def post_cancel_backup(http_context, app):
    task_id = http_context['urlvars'][0]

    tasks = functions.list_backup_tasks(
        str(os.path.join(app.config.temboard.home, '.tm.socket')))

    task = None
    for t in tasks:
        if task_id == t['id']:
            task = t

    if task is None:
        raise HTTPError(404, "Operation not found in current task list")

    # Cancel or abort the task depending on its status
    if task.status < taskmanager.TASK_STATUS_DOING:
        msg = taskmanager.MSG_TYPE_TASK_CANCEL
        response = "cancel signal sent"
    elif task.status == taskmanager.TASK_STATUS_DOING:
        msg = taskmanager.MSG_TYPE_TASK_ABORT
        response = "abort signal sent"
    else:
        # Send a 410 Gone when the task is done or already cancelled or aborted
        raise HTTPError(410, "Operation has already completed")

    taskmanager.TaskManager.send_message(
        str(os.path.join(app.config.temboard.home, '.tm.socket')),
        taskmanager.Message(msg, dict(task_id=task_id)),
        authkey=None,
    )

    return {'response': response}
Example #4
0
def list_backup_tasks(socket):
    task_list = []
    tasks = taskmanager.TaskManager.send_message(
        socket,
        taskmanager.Message(taskmanager.MSG_TYPE_TASK_LIST, ''),
        authkey=None,
    )

    for task in tasks:
        logger.debug(task)
        if task.worker_name in ('backup_worker', 'purge_worker'):
            task_list.append(task)

    return task_list
Example #5
0
def list_scheduled_operation(app, operation_type, **kwargs):
    # Get list of scheduled vacuum operations
    ret = []
    try:
        # Ask it to the task manager
        tasks = taskmanager.TaskManager.send_message(
            str(os.path.join(app.config.temboard.home, '.tm.socket')),
            taskmanager.Message(taskmanager.MSG_TYPE_TASK_LIST, ''),
            authkey=None,
        )
    except Exception as e:
        logger.exception(str(e))
        raise HTTPError(500, "Unable to get scheduled vacuum list")

    for task in tasks:

        # We only want tasks for the operation type ('vacuum', 'analyze',
        # 'reindex')
        if task['worker_name'] != operation_type + '_worker':
            continue

        options = task['options']
        # Filter by db/schema/table if provided
        if (all(k in kwargs for k in ['dbname', 'schema'])
                and (kwargs.get('dbname') != options.get('dbname')
                     or kwargs.get('schema') != options.get('schema'))):
            continue

        if ('table' in kwargs and kwargs.get('table') != options.get('table')):
            continue
        if ('index' in kwargs and kwargs.get('index') != options.get('index')):
            continue

        ret.append(
            dict(
                id=task['id'],
                dbname=options.get('dbname'),
                schema=options.get('schema'),
                table=options.get('table'),
                index=options.get('index'),
                mode=options.get('mode'),
                datetime=task['start_datetime'].strftime("%Y-%m-%dT%H:%M:%SZ"),
                status=task_status_label(task['status'])))
    return ret