diff --git a/PKG-INFO b/PKG-INFO index 680a338..5c734d8 100644 --- a/PKG-INFO +++ b/PKG-INFO @@ -1,10 +1,10 @@ Metadata-Version: 1.0 Name: swh.scheduler -Version: 0.0.25 +Version: 0.0.26 Summary: Software Heritage Scheduler Home-page: https://forge.softwareheritage.org/diffusion/DSCH/ Author: Software Heritage developers Author-email: swh-devel@inria.fr License: UNKNOWN Description: UNKNOWN Platform: UNKNOWN diff --git a/debian/control b/debian/control index 0c5167f..82c3ef3 100644 --- a/debian/control +++ b/debian/control @@ -1,23 +1,24 @@ Source: swh-scheduler Maintainer: Software Heritage developers Section: python Priority: optional Build-Depends: debhelper (>= 9), dh-python (>= 2), python3-all, python3-arrow, python3-celery, python3-click, python3-elasticsearch (>= 5.4.0), + python3-flask, python3-nose, python3-psycopg2, python3-setuptools, - python3-swh.core (>= 0.0.34), + python3-swh.core (>= 0.0.38~), python3-vcversioner Standards-Version: 3.9.6 Homepage: https://forge.softwareheritage.org/diffusion/DSCH/ Package: python3-swh.scheduler Architecture: all -Depends: python3-swh.core (>= 0.0.34), ${misc:Depends}, ${python3:Depends} +Depends: python3-swh.core (>= 0.0.38~), ${misc:Depends}, ${python3:Depends} Description: Software Heritage Scheduler diff --git a/debian/rules b/debian/rules index 4fe0cf9..d5e8b00 100755 --- a/debian/rules +++ b/debian/rules @@ -1,11 +1,11 @@ #!/usr/bin/make -f export PYBUILD_NAME=swh.scheduler -export PYBUILD_TEST_ARGS=--with-doctest -sv -a !db,!fs +export PYBUILD_TEST_ARGS=-sv -a !db,!fs %: dh $@ --with python3 --buildsystem=pybuild override_dh_install: dh_install rm -v $(CURDIR)/debian/python3-*/usr/lib/python*/dist-packages/swh/__init__.py diff --git a/requirements-swh.txt b/requirements-swh.txt index aaeccaa..a152b02 100644 --- a/requirements-swh.txt +++ b/requirements-swh.txt @@ -1 +1 @@ -swh.core >= 0.0.34 +swh.core >= 0.0.38 diff --git a/requirements.txt b/requirements.txt index f889ee0..df47e53 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,10 +1,11 @@ # Add here external Python modules dependencies, one per line. Module names # should match https://pypi.python.org/pypi names. For the full spec or # dependency lines, see https://pip.readthedocs.org/en/1.1/requirements.html arrow celery Click +elasticsearch>5.4 +flask psycopg2 vcversioner -elasticsearch>5.4 diff --git a/sql/swh-scheduler-schema.sql b/sql/swh-scheduler-schema.sql index 92c79f4..f1f0d14 100644 --- a/sql/swh-scheduler-schema.sql +++ b/sql/swh-scheduler-schema.sql @@ -1,361 +1,357 @@ create table dbversion ( version int primary key, release timestamptz not null, description text not null ); comment on table dbversion is 'Schema update tracking'; insert into dbversion (version, release, description) values (8, now(), 'Work In Progress'); create table task_type ( type text primary key, description text not null, backend_name text not null, default_interval interval, min_interval interval, max_interval interval, backoff_factor float, max_queue_length bigint, num_retries bigint, retry_delay interval ); comment on table task_type is 'Types of schedulable tasks'; comment on column task_type.type is 'Short identifier for the task type'; comment on column task_type.description is 'Human-readable task description'; comment on column task_type.backend_name is 'Name of the task in the job-running backend'; comment on column task_type.default_interval is 'Default interval for newly scheduled tasks'; comment on column task_type.min_interval is 'Minimum interval between two runs of a task'; comment on column task_type.max_interval is 'Maximum interval between two runs of a task'; comment on column task_type.backoff_factor is 'Adjustment factor for the backoff between two task runs'; comment on column task_type.max_queue_length is 'Maximum length of the queue for this type of tasks'; comment on column task_type.num_retries is 'Default number of retries on transient failures'; comment on column task_type.retry_delay is 'Retry delay for the task'; create type task_status as enum ('next_run_not_scheduled', 'next_run_scheduled', 'completed', 'disabled'); comment on type task_status is 'Status of a given task'; create type task_policy as enum ('recurring', 'oneshot'); comment on type task_policy is 'Recurrence policy of the given task'; create table task ( id bigserial primary key, type text not null references task_type(type), arguments jsonb not null, next_run timestamptz not null, current_interval interval, status task_status not null, policy task_policy not null default 'recurring', retries_left bigint not null default 0, check (policy <> 'recurring' or current_interval is not null) ); comment on table task is 'Schedule of recurring tasks'; comment on column task.arguments is 'Arguments passed to the underlying job scheduler. ' 'Contains two keys, ''args'' (list) and ''kwargs'' (object).'; comment on column task.next_run is 'The next run of this task should be run on or after that time'; comment on column task.current_interval is 'The interval between two runs of this task, ' 'taking into account the backoff factor'; comment on column task.policy is 'Whether the task is one-shot or recurring'; comment on column task.retries_left is 'The number of "short delay" retries of the task in case of ' 'transient failure'; create index on task(type); create index on task(next_run); create index task_args on task using btree ((arguments -> 'args')); create index task_kwargs on task using gin ((arguments -> 'kwargs')); create type task_run_status as enum ('scheduled', 'started', 'eventful', 'uneventful', 'failed', 'permfailed', 'lost'); comment on type task_run_status is 'Status of a given task run'; create table task_run ( id bigserial primary key, task bigint not null references task(id), backend_id text, scheduled timestamptz, started timestamptz, ended timestamptz, metadata jsonb, status task_run_status not null default 'scheduled' ); comment on table task_run is 'History of task runs sent to the job-running backend'; comment on column task_run.backend_id is 'id of the task run in the job-running backend'; comment on column task_run.metadata is 'Useful metadata for the given task run. ' 'For instance, the worker that took on the job, ' 'or the logs for the run.'; create index on task_run(task); create index on task_run(backend_id); create or replace function swh_scheduler_mktemp_task () returns void language sql as $$ create temporary table tmp_task ( like task excluding indexes ) on commit drop; alter table tmp_task drop column id, drop column current_interval, drop column status, alter column policy drop not null, alter column retries_left drop not null; $$; comment on function swh_scheduler_mktemp_task () is 'Create a temporary table for bulk task creation'; create or replace function swh_scheduler_create_tasks_from_temp () returns setof task language plpgsql as $$ begin return query insert into task (type, arguments, next_run, status, current_interval, policy, retries_left) select type, arguments, next_run, 'next_run_not_scheduled', (select default_interval from task_type tt where tt.type = tmp_task.type), coalesce(policy, 'recurring'), coalesce(retries_left, (select num_retries from task_type tt where tt.type = tmp_task.type), 0) from tmp_task returning task.*; end; $$; comment on function swh_scheduler_create_tasks_from_temp () is 'Create tasks in bulk from the temporary table'; create or replace function swh_scheduler_peek_ready_tasks (task_type text, ts timestamptz default now(), num_tasks bigint default NULL) returns setof task language sql stable as $$ select * from task where next_run <= ts and type = task_type and status = 'next_run_not_scheduled' order by next_run limit num_tasks; $$; create or replace function swh_scheduler_grab_ready_tasks (task_type text, ts timestamptz default now(), num_tasks bigint default NULL) returns setof task language sql as $$ update task set status='next_run_scheduled' from ( select id from task where next_run <= ts and type = task_type and status='next_run_not_scheduled' order by next_run limit num_tasks for update skip locked ) next_tasks where task.id = next_tasks.id returning task.*; $$; create or replace function swh_scheduler_schedule_task_run (task_id bigint, backend_id text, metadata jsonb default '{}'::jsonb, ts timestamptz default now()) returns task_run language sql as $$ insert into task_run (task, backend_id, metadata, scheduled, status) values (task_id, backend_id, metadata, ts, 'scheduled') returning *; $$; create or replace function swh_scheduler_mktemp_task_run () returns void language sql as $$ create temporary table tmp_task_run ( like task_run excluding indexes ) on commit drop; alter table tmp_task_run drop column id, drop column status; $$; comment on function swh_scheduler_mktemp_task_run () is 'Create a temporary table for bulk task run scheduling'; create or replace function swh_scheduler_schedule_task_run_from_temp () returns void language plpgsql as $$ begin insert into task_run (task, backend_id, metadata, scheduled, status) select task, backend_id, metadata, scheduled, 'scheduled' from tmp_task_run; return; end; $$; create or replace function swh_scheduler_start_task_run (backend_id text, metadata jsonb default '{}'::jsonb, ts timestamptz default now()) returns task_run language sql as $$ update task_run set started = ts, status = 'started', metadata = coalesce(task_run.metadata, '{}'::jsonb) || swh_scheduler_start_task_run.metadata where task_run.backend_id = swh_scheduler_start_task_run.backend_id returning *; $$; create or replace function swh_scheduler_end_task_run (backend_id text, status task_run_status, metadata jsonb default '{}'::jsonb, ts timestamptz default now()) returns task_run language sql as $$ update task_run set ended = ts, status = swh_scheduler_end_task_run.status, metadata = coalesce(task_run.metadata, '{}'::jsonb) || swh_scheduler_end_task_run.metadata where task_run.backend_id = swh_scheduler_end_task_run.backend_id returning *; $$; create type task_record as ( task_id bigint, task_policy task_policy, task_status task_status, task_run_id bigint, arguments jsonb, type text, backend_id text, metadata jsonb, scheduled timestamptz, started timestamptz, ended timestamptz ); create index task_run_id_asc_idx on task_run(task asc, ended asc); -drop function swh_scheduler_task_to_archive(timestamptz, bigint, bigint); - create or replace function swh_scheduler_task_to_archive( ts_after timestamptz, ts_before timestamptz, last_id bigint default -1, lim bigint default 10) returns setof task_record language sql stable as $$ select t.id as task_id, t.policy as task_policy, t.status as task_status, tr.id as task_run_id, t.arguments, t.type, tr.backend_id, tr.metadata, tr.scheduled, tr.started, tr.ended from task_run tr inner join task t on tr.task=t.id where ((t.policy = 'oneshot' and t.status ='completed') or (t.policy = 'recurring' and t.status ='disabled')) and ts_after <= tr.ended and tr.ended < ts_before and t.id > last_id order by tr.task, tr.ended limit lim; $$; comment on function swh_scheduler_task_to_archive is 'Read archivable tasks function'; -drop function swh_scheduler_delete_archive_tasks(bigint[]); - create or replace function swh_scheduler_delete_archived_tasks( task_ids bigint[], task_run_ids bigint[]) returns void language sql as $$ -- clean up task_run_ids delete from task_run where id in (select * from unnest(task_run_ids)); -- clean up only tasks whose associated task_run are all cleaned up. -- Remaining tasks will stay there and will be cleaned up when -- remaining data have been indexed delete from task where id in (select t.id from task t left outer join task_run tr on t.id=tr.task where t.id in (select * from unnest(task_ids)) and tr.task is null); $$; comment on function swh_scheduler_delete_archived_tasks is 'Clean up archived tasks function'; create or replace function swh_scheduler_update_task_on_task_end () returns trigger language plpgsql as $$ declare cur_task task%rowtype; cur_task_type task_type%rowtype; adjustment_factor float; new_interval interval; begin select * from task where id = new.task into cur_task; select * from task_type where type = cur_task.type into cur_task_type; case when new.status = 'permfailed' then update task set status = 'disabled' where id = cur_task.id; when new.status in ('eventful', 'uneventful') then case when cur_task.policy = 'oneshot' then update task set status = 'completed' where id = cur_task.id; when cur_task.policy = 'recurring' then if new.status = 'uneventful' then adjustment_factor := 1/cur_task_type.backoff_factor; else adjustment_factor := 1/cur_task_type.backoff_factor; end if; new_interval := greatest( cur_task_type.min_interval, least( cur_task_type.max_interval, adjustment_factor * cur_task.current_interval)); update task set status = 'next_run_not_scheduled', next_run = now() + new_interval, current_interval = new_interval, retries_left = coalesce(cur_task_type.num_retries, 0) where id = cur_task.id; end case; else -- new.status in 'failed', 'lost' if cur_task.retries_left > 0 then update task set status = 'next_run_not_scheduled', next_run = now() + coalesce(cur_task_type.retry_delay, interval '1 hour'), retries_left = cur_task.retries_left - 1 where id = cur_task.id; else -- no retries left case when cur_task.policy = 'oneshot' then update task set status = 'disabled' where id = cur_task.id; when cur_task.policy = 'recurring' then update task set status = 'next_run_not_scheduled', next_run = now() + cur_task.current_interval, retries_left = coalesce(cur_task_type.num_retries, 0) where id = cur_task.id; end case; end if; -- retries end case; return null; end; $$; create trigger update_task_on_task_end after update of status on task_run for each row when (new.status NOT IN ('scheduled', 'started')) execute procedure swh_scheduler_update_task_on_task_end (); diff --git a/swh.scheduler.egg-info/PKG-INFO b/swh.scheduler.egg-info/PKG-INFO index 680a338..5c734d8 100644 --- a/swh.scheduler.egg-info/PKG-INFO +++ b/swh.scheduler.egg-info/PKG-INFO @@ -1,10 +1,10 @@ Metadata-Version: 1.0 Name: swh.scheduler -Version: 0.0.25 +Version: 0.0.26 Summary: Software Heritage Scheduler Home-page: https://forge.softwareheritage.org/diffusion/DSCH/ Author: Software Heritage developers Author-email: swh-devel@inria.fr License: UNKNOWN Description: UNKNOWN Platform: UNKNOWN diff --git a/swh.scheduler.egg-info/SOURCES.txt b/swh.scheduler.egg-info/SOURCES.txt index 4945f7f..c7827d8 100644 --- a/swh.scheduler.egg-info/SOURCES.txt +++ b/swh.scheduler.egg-info/SOURCES.txt @@ -1,58 +1,62 @@ .gitignore AUTHORS LICENSE LICENSE.Celery MANIFEST.in Makefile requirements-swh.txt requirements.txt setup.py version.txt bin/swh-worker-control data/README.md data/elastic-template.json data/update-index-settings.json debian/changelog debian/compat debian/control debian/copyright debian/rules debian/source/format docs/.gitignore docs/Makefile docs/conf.py docs/index.rst docs/_static/.placeholder docs/_templates/.placeholder sql/.gitignore sql/Makefile sql/swh-scheduler-data.sql sql/swh-scheduler-schema.sql sql/swh-scheduler-testdata.sql sql/updates/02.sql sql/updates/03.sql sql/updates/04.sql sql/updates/05.sql sql/updates/06.sql sql/updates/07.sql sql/updates/08.sql swh/__init__.py swh.scheduler.egg-info/PKG-INFO swh.scheduler.egg-info/SOURCES.txt swh.scheduler.egg-info/dependency_links.txt swh.scheduler.egg-info/entry_points.txt swh.scheduler.egg-info/requires.txt swh.scheduler.egg-info/top_level.txt swh/scheduler/__init__.py swh/scheduler/backend.py swh/scheduler/backend_es.py swh/scheduler/cli.py swh/scheduler/task.py swh/scheduler/utils.py +swh/scheduler/api/__init__.py +swh/scheduler/api/client.py +swh/scheduler/api/server.py swh/scheduler/celery_backend/__init__.py swh/scheduler/celery_backend/config.py swh/scheduler/celery_backend/listener.py swh/scheduler/celery_backend/runner.py swh/scheduler/tests/__init__.py +swh/scheduler/tests/test_api_client.py swh/scheduler/tests/test_scheduler.py swh/scheduler/tests/test_task.py \ No newline at end of file diff --git a/swh.scheduler.egg-info/requires.txt b/swh.scheduler.egg-info/requires.txt index e757eaf..5d329b8 100644 --- a/swh.scheduler.egg-info/requires.txt +++ b/swh.scheduler.egg-info/requires.txt @@ -1,7 +1,8 @@ Click arrow celery elasticsearch>5.4 +flask psycopg2 -swh.core>=0.0.34 +swh.core>=0.0.38 vcversioner diff --git a/swh/scheduler/__init__.py b/swh/scheduler/__init__.py index e69de29..99bb31c 100644 --- a/swh/scheduler/__init__.py +++ b/swh/scheduler/__init__.py @@ -0,0 +1,36 @@ +# Copyright (C) 2018 The Software Heritage developers +# See the AUTHORS file at the top-level directory of this distribution +# License: GNU General Public License version 3, or any later version +# See top-level LICENSE file for more information + + +def get_scheduler(cls, args={}): + """ + Get a scheduler object of class `scheduler_class` with arguments + `scheduler_args`. + + Args: + scheduler (dict): dictionary with keys: + + cls (str): scheduler's class, either 'local' or 'remote' + args (dict): dictionary with keys, default to empty. + + Returns: + an instance of swh.scheduler, either local or remote: + + local: swh.scheduler.backend.SchedulerBackend + remote: swh.scheduler.api.client.RemoteScheduler + + Raises: + ValueError if passed an unknown storage class. + + """ + + if cls == 'remote': + from .api.client import RemoteScheduler as SchedulerBackend + elif cls == 'local': + from .backend import SchedulerBackend + else: + raise ValueError('Unknown swh.scheduler class `%s`' % cls) + + return SchedulerBackend(**args) diff --git a/swh/scheduler/__init__.py b/swh/scheduler/api/__init__.py similarity index 100% copy from swh/scheduler/__init__.py copy to swh/scheduler/api/__init__.py diff --git a/swh/scheduler/api/client.py b/swh/scheduler/api/client.py new file mode 100644 index 0000000..a73cd68 --- /dev/null +++ b/swh/scheduler/api/client.py @@ -0,0 +1,103 @@ +# Copyright (C) 2018 The Software Heritage developers +# See the AUTHORS file at the top-level directory of this distribution +# License: GNU General Public License version 3, or any later version +# See top-level LICENSE file for more information + + +from swh.core.api import SWHRemoteAPI + + +class SchedulerAPIError(Exception): + """Specific internal scheduler api issue (mainly connection) + + """ + + def __str__(self): + args = self.args + return 'An unexpected error occurred in the api backend: %s' % args + + +class RemoteScheduler(SWHRemoteAPI): + """Proxy to a remote scheduler API + + """ + def __init__(self, url): + super().__init__(api_exception=SchedulerAPIError, url=url) + + def close_connection(self): + return self.post('close_connection', {}) + + def set_status_tasks(self, task_ids, status='disabled'): + return self.post('set_status_tasks', {'task_ids': task_ids, + 'status': status}) + + def create_task_type(self, task_type): + return self.post('create_task_type', {'task_type': task_type}) + + def get_task_type(self, task_type_name): + return self.post('get_task_type', {'task_type_name': task_type_name}) + + def get_task_types(self): + return self.post('get_task_types', {}) + + def create_tasks(self, tasks): + return self.post('create_tasks', {'tasks': tasks}) + + def disable_tasks(self, task_ids): + return self.post('disable_tasks', {'task_ids': task_ids}) + + def get_tasks(self, task_ids): + return self.post('get_tasks', {'task_ids': task_ids}) + + def peek_ready_tasks(self, task_type, timestamp=None, num_tasks=None): + return self.post('peek_ready_tasks', { + 'task_type': task_type, + 'timestamp': timestamp, + 'num_tasks': num_tasks, + }) + + def grab_ready_tasks(self, task_type, timestamp=None, num_tasks=None): + return self.post('grab_ready_tasks', { + 'task_type': task_type, + 'timestamp': timestamp, + 'num_tasks': num_tasks, + }) + + def schedule_task_run(self, task_id, backend_id, metadata=None, + timestamp=None): + return self.post('schedule_task_run', { + 'task_id': task_id, + 'backend_id': backend_id, + 'metadata': metadata, + 'timestamp': timestamp, + }) + + def mass_schedule_task_runs(self, task_runs): + return self.post('mass_schedule_task_runs', {'task_runs': task_runs}) + + def start_task_run(self, backend_id, metadata=None, timestamp=None): + return self.post('start_task_run', { + 'backend_id': backend_id, + 'metadata': metadata, + 'timestamp': timestamp, + }) + + def end_task_run(self, backend_id, status, metadata=None, timestamp=None): + return self.post('end_task_run', { + 'backend_id': backend_id, + 'status': status, + 'metadata': metadata, + 'timestamp': timestamp, + }) + + def filter_task_to_archive(self, after_ts, before_ts, limit=10, + last_id=-1): + return self.post('filter_task_to_archive', { + 'after_ts': after_ts, + 'before_ts': before_ts, + 'limit': limit, + 'last_id': last_id, + }) + + def delete_archived_tasks(self, task_ids): + return self.post('delete_archived_tasks', {'task_ids': task_ids}) diff --git a/swh/scheduler/api/server.py b/swh/scheduler/api/server.py new file mode 100644 index 0000000..c7f1de8 --- /dev/null +++ b/swh/scheduler/api/server.py @@ -0,0 +1,154 @@ +# Copyright (C) 2018 The Software Heritage developers +# See the AUTHORS file at the top-level directory of this distribution +# License: GNU General Public License version 3, or any later version +# See top-level LICENSE file for more information + +import logging +import click + +from flask import g, request + +from swh.core import config +from swh.scheduler import get_scheduler +from swh.core.api import (SWHServerAPIApp, decode_request, + error_handler, + encode_data_server as encode_data) + +DEFAULT_CONFIG_PATH = 'backend/scheduler' +DEFAULT_CONFIG = { + 'scheduler': ('dict', { + 'cls': 'local', + 'args': { + 'scheduling_db': 'dbname=softwareheritage-scheduler-dev', + }, + }) +} + + +app = SWHServerAPIApp(__name__) + + +@app.errorhandler(Exception) +def my_error_handler(exception): + return error_handler(exception, encode_data) + + +@app.before_request +def before_request(): + g.scheduler = get_scheduler(**app.config['scheduler']) + + +@app.route('/') +def index(): + return 'SWH Scheduler API server' + + +@app.route('/close_connection', methods=['POST']) +def close_connection(): + return encode_data(g.scheduler.close_connection()) + + +@app.route('/set_status_tasks', methods=['POST']) +def set_status_tasks(): + return encode_data(g.scheduler.set_status_tasks(**decode_request(request))) + + +@app.route('/create_task_type', methods=['POST']) +def create_task_type(): + return encode_data(g.scheduler.create_task_type(**decode_request(request))) + + +@app.route('/get_task_type', methods=['POST']) +def get_task_type(): + return encode_data(g.scheduler.get_task_type(**decode_request(request))) + + +@app.route('/get_task_types', methods=['POST']) +def get_task_types(): + return encode_data(g.scheduler.get_task_types(**decode_request(request))) + + +@app.route('/create_tasks', methods=['POST']) +def create_tasks(): + return encode_data(g.scheduler.create_tasks(**decode_request(request))) + + +@app.route('/disable_tasks', methods=['POST']) +def disable_tasks(): + return encode_data(g.scheduler.disable_tasks(**decode_request(request))) + + +@app.route('/get_tasks', methods=['POST']) +def get_tasks(): + return encode_data(g.scheduler.get_tasks(**decode_request(request))) + + +@app.route('/peek_ready_tasks', methods=['POST']) +def peek_ready_tasks(): + return encode_data(g.scheduler.peek_ready_tasks(**decode_request(request))) + + +@app.route('/grab_ready_tasks', methods=['POST']) +def grab_ready_tasks(): + return encode_data(g.scheduler.grab_ready_tasks(**decode_request(request))) + + +@app.route('/schedule_task_run', methods=['POST']) +def schedule_task_run(): + return encode_data(g.scheduler.schedule_task_run( + **decode_request(request))) + + +@app.route('/mass_schedule_task_runs', methods=['POST']) +def mass_schedule_task_runs(): + return encode_data( + g.scheduler.mass_schedule_task_runs(**decode_request(request))) + + +@app.route('/start_task_run', methods=['POST']) +def start_task_run(): + return encode_data(g.scheduler.start_task_run(**decode_request(request))) + + +@app.route('/end_task_run', methods=['POST']) +def end_task_run(): + return encode_data(g.scheduler.end_task_run(**decode_request(request))) + + +@app.route('/filter_task_to_archive', methods=['POST']) +def filter_task_to_archive(): + return encode_data( + g.scheduler.filter_task_to_archive(**decode_request(request))) + + +@app.route('/delete_archived_tasks', methods=['POST']) +def delete_archived_tasks(): + return encode_data( + g.scheduler.delete_archived_tasks(**decode_request(request))) + + +def run_from_webserver(environ, start_response, + config_path=DEFAULT_CONFIG_PATH): + """Run the WSGI app from the webserver, loading the configuration.""" + cfg = config.load_named_config(config_path, DEFAULT_CONFIG) + app.config.update(cfg) + handler = logging.StreamHandler() + app.logger.addHandler(handler) + return app(environ, start_response) + + +@click.command() +@click.argument('config-path', required=1) +@click.option('--host', default='0.0.0.0', + help="Host to run the scheduler server api") +@click.option('--port', default=5008, type=click.INT, + help="Binding port of the server") +@click.option('--debug/--nodebug', default=True, + help="Indicates if the server should run in debug mode") +def launch(config_path, host, port, debug): + app.config.update(config.read(config_path, DEFAULT_CONFIG)) + app.run(host, port=port, debug=bool(debug)) + + +if __name__ == '__main__': + launch() diff --git a/swh/scheduler/backend.py b/swh/scheduler/backend.py index 7b37d73..a288a5c 100644 --- a/swh/scheduler/backend.py +++ b/swh/scheduler/backend.py @@ -1,482 +1,493 @@ # Copyright (C) 2015-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import binascii import datetime from functools import wraps import json import tempfile from arrow import Arrow, utcnow import psycopg2 import psycopg2.extras from psycopg2.extensions import AsIs from swh.core.config import SWHConfig def adapt_arrow(arrow): return AsIs("'%s'::timestamptz" % arrow.isoformat()) psycopg2.extensions.register_adapter(dict, psycopg2.extras.Json) psycopg2.extensions.register_adapter(Arrow, adapt_arrow) def autocommit(fn): @wraps(fn) def wrapped(self, *args, **kwargs): autocommit = False if 'cursor' not in kwargs or not kwargs['cursor']: autocommit = True kwargs['cursor'] = self.cursor() try: ret = fn(self, *args, **kwargs) except Exception: if autocommit: self.rollback() raise if autocommit: self.commit() return ret return wrapped class SchedulerBackend(SWHConfig): - """ - Backend for the Software Heritage scheduling database. - """ + """Backend for the Software Heritage scheduling database. - CONFIG_BASE_FILENAME = 'scheduler.ini' + """ + CONFIG_BASE_FILENAME = 'scheduler' DEFAULT_CONFIG = { 'scheduling_db': ('str', 'dbname=softwareheritage-scheduler-dev'), } def __init__(self, **override_config): self.config = self.parse_config_file(global_config=False) self.config.update(override_config) self.db = None self.reconnect() def reconnect(self): if not self.db or self.db.closed: self.db = psycopg2.connect( dsn=self.config['scheduling_db'], cursor_factory=psycopg2.extras.RealDictCursor, ) def cursor(self): - """Return a fresh cursor on the database, with auto-reconnection in case of - failure""" + """Return a fresh cursor on the database, with auto-reconnection in + case of failure + + """ cur = None # Get a fresh cursor and reconnect at most three times tries = 0 while True: tries += 1 try: cur = self.db.cursor() cur.execute('select 1') break except psycopg2.OperationalError: if tries < 3: self.reconnect() else: raise return cur def commit(self): """Commit a transaction""" self.db.commit() def rollback(self): """Rollback a transaction""" self.db.rollback() + def close_connection(self): + """Close db connection""" + if self.db and not self.db.closed: + self.db.close() + def copy_to(self, items, tblname, columns, cursor=None, item_cb=None): def escape(data): if data is None: return '' if isinstance(data, bytes): return '\\x%s' % binascii.hexlify(data).decode('ascii') elif isinstance(data, str): return '"%s"' % data.replace('"', '""') elif isinstance(data, (datetime.datetime, Arrow)): # We escape twice to make sure the string generated by # isoformat gets escaped return escape(data.isoformat()) elif isinstance(data, dict): return escape(json.dumps(data)) elif isinstance(data, list): return escape("{%s}" % ','.join(escape(d) for d in data)) elif isinstance(data, psycopg2.extras.Range): # We escape twice here too, so that we make sure # everything gets passed to copy properly return escape( '%s%s,%s%s' % ( '[' if data.lower_inc else '(', '-infinity' if data.lower_inf else escape(data.lower), 'infinity' if data.upper_inf else escape(data.upper), ']' if data.upper_inc else ')', ) ) else: # We don't escape here to make sure we pass literals properly return str(data) with tempfile.TemporaryFile('w+') as f: for d in items: if item_cb is not None: item_cb(d) line = [escape(d.get(k)) for k in columns] f.write(','.join(line)) f.write('\n') f.seek(0) cursor.copy_expert('COPY %s (%s) FROM STDIN CSV' % ( tblname, ', '.join(columns)), f) task_type_keys = [ 'type', 'description', 'backend_name', 'default_interval', 'min_interval', 'max_interval', 'backoff_factor', 'max_queue_length', 'num_retries', 'retry_delay', ] def _format_query(self, query, keys): """Format a query with the given keys""" query_keys = ', '.join(keys) placeholders = ', '.join(['%s'] * len(keys)) return query.format(keys=query_keys, placeholders=placeholders) def _format_multiquery(self, query, keys, values): """Format a query with placeholders generated for multiple values""" query_keys = ', '.join(keys) placeholders = '), ('.join( [', '.join(['%s'] * len(keys))] * len(values) ) ret_values = sum([[value[key] for key in keys] for value in values], []) return ( query.format(keys=query_keys, placeholders=placeholders), ret_values, ) @autocommit def create_task_type(self, task_type, cursor=None): """Create a new task type ready for scheduling. Args: task_type (dict): a dictionary with the following keys: - type (str): an identifier for the task type - description (str): a human-readable description of what the task does - backend_name (str): the name of the task in the job-scheduling backend - default_interval (datetime.timedelta): the default interval between two task runs - min_interval (datetime.timedelta): the minimum interval between two task runs - max_interval (datetime.timedelta): the maximum interval between two task runs - backoff_factor (float): the factor by which the interval changes at each run - max_queue_length (int): the maximum length of the task queue for this task type """ query = self._format_query( """insert into task_type ({keys}) values ({placeholders})""", self.task_type_keys, ) cursor.execute(query, [task_type[key] for key in self.task_type_keys]) @autocommit def get_task_type(self, task_type_name, cursor=None): """Retrieve the task type with id task_type_name""" query = self._format_query( "select {keys} from task_type where type=%s", self.task_type_keys, ) cursor.execute(query, (task_type_name,)) ret = cursor.fetchone() return ret @autocommit def get_task_types(self, cursor=None): query = self._format_query( "select {keys} from task_type", self.task_type_keys, ) cursor.execute(query) ret = cursor.fetchall() return ret task_create_keys = [ 'type', 'arguments', 'next_run', 'policy', 'retries_left', ] task_keys = task_create_keys + ['id', 'current_interval', 'status'] @autocommit def create_tasks(self, tasks, cursor=None): """Create new tasks. Args: tasks (list): each task is a dictionary with the following keys: - type (str): the task type - arguments (dict): the arguments for the task runner, keys: - args (list of str): arguments - kwargs (dict str -> str): keyword arguments - next_run (datetime.datetime): the next scheduled run for the task Returns: a list of created tasks. """ cursor.execute('select swh_scheduler_mktemp_task()') self.copy_to(tasks, 'tmp_task', self.task_create_keys, cursor) query = self._format_query( 'select {keys} from swh_scheduler_create_tasks_from_temp()', self.task_keys, ) cursor.execute(query) return cursor.fetchall() + @autocommit + def set_status_tasks(self, task_ids, status='disabled', cursor=None): + """Set the tasks' status whose ids are listed.""" + query = "UPDATE task SET status = %s WHERE id IN %s" + cursor.execute(query, (status, tuple(task_ids),)) + return None + @autocommit def disable_tasks(self, task_ids, cursor=None): """Disable the tasks whose ids are listed.""" - query = "UPDATE task SET status = 'disabled' WHERE id IN %s" - cursor.execute(query, (tuple(task_ids),)) - return None + return self.set_status_tasks(task_ids) @autocommit def get_tasks(self, task_ids, cursor=None): """Retrieve the info of tasks whose ids are listed.""" query = self._format_query('select {keys} from task where id in %s', self.task_keys) cursor.execute(query, (tuple(task_ids),)) return cursor.fetchall() @autocommit def peek_ready_tasks(self, task_type, timestamp=None, num_tasks=None, cursor=None): """Fetch the list of ready tasks Args: task_type (str): filtering task per their type timestamp (datetime.datetime): peek tasks that need to be executed before that timestamp num_tasks (int): only peek at num_tasks tasks Returns: a list of tasks """ if timestamp is None: timestamp = utcnow() cursor.execute( 'select * from swh_scheduler_peek_ready_tasks(%s, %s, %s)', (task_type, timestamp, num_tasks) ) return cursor.fetchall() @autocommit def grab_ready_tasks(self, task_type, timestamp=None, num_tasks=None, cursor=None): """Fetch the list of ready tasks, and mark them as scheduled Args: task_type (str): filtering task per their type timestamp (datetime.datetime): grab tasks that need to be executed before that timestamp num_tasks (int): only grab num_tasks tasks Returns: a list of tasks """ if timestamp is None: timestamp = utcnow() cursor.execute( 'select * from swh_scheduler_grab_ready_tasks(%s, %s, %s)', (task_type, timestamp, num_tasks) ) return cursor.fetchall() task_run_create_keys = ['task', 'backend_id', 'scheduled', 'metadata'] @autocommit def schedule_task_run(self, task_id, backend_id, metadata=None, timestamp=None, cursor=None): """Mark a given task as scheduled, adding a task_run entry in the database. Args: task_id (int): the identifier for the task being scheduled backend_id (str): the identifier of the job in the backend metadata (dict): metadata to add to the task_run entry timestamp (datetime.datetime): the instant the event occurred Returns: a fresh task_run entry """ if metadata is None: metadata = {} if timestamp is None: timestamp = utcnow() cursor.execute( 'select * from swh_scheduler_schedule_task_run(%s, %s, %s, %s)', (task_id, backend_id, metadata, timestamp) ) return cursor.fetchone() @autocommit def mass_schedule_task_runs(self, task_runs, cursor=None): """Schedule a bunch of task runs. Args: task_runs (list): a list of dicts with keys: - task (int): the identifier for the task being scheduled - backend_id (str): the identifier of the job in the backend - metadata (dict): metadata to add to the task_run entry - scheduled (datetime.datetime): the instant the event occurred Returns: None """ cursor.execute('select swh_scheduler_mktemp_task_run()') self.copy_to(task_runs, 'tmp_task_run', self.task_run_create_keys, cursor) cursor.execute('select swh_scheduler_schedule_task_run_from_temp()') @autocommit def start_task_run(self, backend_id, metadata=None, timestamp=None, cursor=None): """Mark a given task as started, updating the corresponding task_run entry in the database. Args: backend_id (str): the identifier of the job in the backend metadata (dict): metadata to add to the task_run entry timestamp (datetime.datetime): the instant the event occurred Returns: the updated task_run entry """ if metadata is None: metadata = {} if timestamp is None: timestamp = utcnow() cursor.execute( 'select * from swh_scheduler_start_task_run(%s, %s, %s)', (backend_id, metadata, timestamp) ) return cursor.fetchone() @autocommit def end_task_run(self, backend_id, status, metadata=None, timestamp=None, result=None, cursor=None): """Mark a given task as ended, updating the corresponding task_run entry in the database. Args: backend_id (str): the identifier of the job in the backend status (str): how the task ended; one of: 'eventful', 'uneventful', 'failed' metadata (dict): metadata to add to the task_run entry timestamp (datetime.datetime): the instant the event occurred Returns: the updated task_run entry """ if metadata is None: metadata = {} if timestamp is None: timestamp = utcnow() cursor.execute( 'select * from swh_scheduler_end_task_run(%s, %s, %s, %s)', (backend_id, status, metadata, timestamp) ) return cursor.fetchone() @autocommit def filter_task_to_archive(self, after_ts, before_ts, limit=10, last_id=-1, cursor=None): """Returns the list of task/task_run prior to a given date to archive. """ last_task_run_id = None while True: row = None cursor.execute( "select * from swh_scheduler_task_to_archive(%s, %s, %s, %s)", (after_ts, before_ts, last_id, limit) ) for row in cursor: # nested type index does not accept bare values # transform it as a dict to comply with this row['arguments']['args'] = { i: v for i, v in enumerate(row['arguments']['args']) } kwargs = row['arguments']['kwargs'] row['arguments']['kwargs'] = json.dumps(kwargs) yield row if not row: break _id = row.get('task_id') _task_run_id = row.get('task_run_id') if last_id == _id and last_task_run_id == _task_run_id: break last_id = _id last_task_run_id = _task_run_id @autocommit def delete_archived_tasks(self, task_ids, cursor=None): """Delete archived tasks as much as possible. Only the task_ids whose complete associated task_run have been cleaned up will be. """ _task_ids = _task_run_ids = [] for task_id in task_ids: _task_ids.append(task_id['task_id']) - _task_run_ids.add(task_id['task_run_id']) + _task_run_ids.append(task_id['task_run_id']) cursor.execute( "select * from swh_scheduler_delete_archived_tasks(%s, %s)", (_task_ids, _task_run_ids)) diff --git a/swh/scheduler/celery_backend/listener.py b/swh/scheduler/celery_backend/listener.py index 0430d67..e497afa 100644 --- a/swh/scheduler/celery_backend/listener.py +++ b/swh/scheduler/celery_backend/listener.py @@ -1,156 +1,178 @@ -# Copyright (C) 2015 The Software Heritage developers +# Copyright (C) 2015-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information +import click import datetime import socket from arrow import utcnow from kombu import Queue from celery.events import EventReceiver +from swh.scheduler import get_scheduler from .config import app as main_app -from ..backend import SchedulerBackend class ReliableEventReceiver(EventReceiver): def __init__(self, channel, handlers=None, routing_key='#', node_id=None, app=None, queue_prefix='celeryev', accept=None): super(ReliableEventReceiver, self).__init__( channel, handlers, routing_key, node_id, app, queue_prefix, accept) self.queue = Queue('.'.join([self.queue_prefix, self.node_id]), exchange=self.exchange, routing_key=self.routing_key, auto_delete=False, durable=True, queue_arguments=self._get_queue_arguments()) def get_consumers(self, consumer, channel): return [consumer(queues=[self.queue], callbacks=[self._receive], no_ack=False, accept=self.accept)] def _receive(self, body, message): type, body = self.event_from_message(body) self.process(type, body, message) def process(self, type, event, message): """Process the received event by dispatching it to the appropriate handler.""" handler = self.handlers.get(type) or self.handlers.get('*') handler and handler(event, message) ACTION_SEND_DELAY = datetime.timedelta(seconds=1.0) ACTION_QUEUE_MAX_LENGTH = 1000 def event_monitor(app, backend): actions = { 'last_send': utcnow() - 2*ACTION_SEND_DELAY, 'queue': [], } def try_perform_actions(actions=actions): if not actions['queue']: return if utcnow() - actions['last_send'] > ACTION_SEND_DELAY or \ len(actions['queue']) > ACTION_QUEUE_MAX_LENGTH: perform_actions(actions) def perform_actions(actions, backend=backend): action_map = { 'start_task_run': backend.start_task_run, 'end_task_run': backend.end_task_run, } messages = [] cursor = backend.cursor() for action in actions['queue']: messages.append(action['message']) function = action_map[action['action']] args = action.get('args', ()) kwargs = action.get('kwargs', {}) kwargs['cursor'] = cursor function(*args, **kwargs) backend.commit() for message in messages: message.ack() actions['queue'] = [] actions['last_send'] = utcnow() def queue_action(action, actions=actions): actions['queue'].append(action) try_perform_actions() def catchall_event(event, message): message.ack() try_perform_actions() def task_started(event, message): queue_action({ 'action': 'start_task_run', 'args': [event['uuid']], 'kwargs': { 'timestamp': utcnow(), 'metadata': { 'worker': event['hostname'], }, }, 'message': message, }) def task_succeeded(event, message): result = event['result'] try: status = result.get('status') if status == 'success': status = 'eventful' if result.get('eventful') else 'uneventful' except Exception: status = 'eventful' if result else 'uneventful' queue_action({ 'action': 'end_task_run', 'args': [event['uuid']], 'kwargs': { 'timestamp': utcnow(), 'status': status, 'result': result, }, 'message': message, }) def task_failed(event, message): queue_action({ 'action': 'end_task_run', 'args': [event['uuid']], 'kwargs': { 'timestamp': utcnow(), 'status': 'failed', }, 'message': message, }) recv = ReliableEventReceiver( main_app.connection(), app=main_app, handlers={ 'task-started': task_started, 'task-result': task_succeeded, 'task-failed': task_failed, '*': catchall_event, }, node_id='listener-%s' % socket.gethostname(), ) recv.capture(limit=None, timeout=None, wakeup=True) +@click.command() +@click.option('--cls', '-c', default='local', + help="Scheduler's class, default to 'local'") +@click.option( + '--database', '-d', help='Scheduling database DSN', + default='host=db.internal.softwareheritage.org ' + 'dbname=softwareheritage-scheduler user=guest') +@click.option('--url', '-u', default='http://localhost:5008', + help="(Optional) Scheduler's url access") +def main(cls, database, url): + scheduler = None + if cls == 'local': + scheduler = get_scheduler(cls, args={'scheduling_db': database}) + elif cls == 'remote': + scheduler = get_scheduler(cls, args={'url': url}) + + if not scheduler: + raise ValueError('Scheduler class (local/remote) must be instantiated') + + event_monitor(main_app, backend=scheduler) + + if __name__ == '__main__': - main_backend = SchedulerBackend() - event_monitor(main_app, main_backend) + main() diff --git a/swh/scheduler/celery_backend/runner.py b/swh/scheduler/celery_backend/runner.py index 81f54fb..6e271b5 100644 --- a/swh/scheduler/celery_backend/runner.py +++ b/swh/scheduler/celery_backend/runner.py @@ -1,84 +1,84 @@ -# Copyright (C) 2015-2017 The Software Heritage developers +# Copyright (C) 2015-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import time import arrow from celery import group -from ..backend import SchedulerBackend +from swh.scheduler import get_scheduler from .config import app as main_app # Max batch size for tasks MAX_NUM_TASKS = 10000 def run_ready_tasks(backend, app): """Run all tasks that are ready""" while True: throttled = False cursor = backend.cursor() task_types = {} pending_tasks = [] for task_type in backend.get_task_types(cursor=cursor): task_type_name = task_type['type'] task_types[task_type_name] = task_type max_queue_length = task_type['max_queue_length'] if max_queue_length: backend_name = task_type['backend_name'] queue_name = app.tasks[backend_name].task_queue queue_length = app.get_queue_length(queue_name) num_tasks = min(max_queue_length - queue_length, MAX_NUM_TASKS) else: num_tasks = MAX_NUM_TASKS if num_tasks > 0: pending_tasks.extend( backend.grab_ready_tasks(task_type_name, num_tasks=num_tasks, cursor=cursor)) if not pending_tasks: break celery_tasks = [] for task in pending_tasks: args = task['arguments']['args'] kwargs = task['arguments']['kwargs'] celery_task = app.tasks[ task_types[task['type']]['backend_name'] ].s(*args, **kwargs) celery_tasks.append(celery_task) group_result = group(celery_tasks).delay() backend_tasks = [{ 'task': task['id'], 'backend_id': group_result.results[i].id, 'scheduled': arrow.utcnow(), } for i, task in enumerate(pending_tasks)] backend.mass_schedule_task_runs(backend_tasks, cursor=cursor) backend.commit() if throttled: time.sleep(10) if __name__ == '__main__': for module in main_app.conf.CELERY_IMPORTS: __import__(module) - main_backend = SchedulerBackend() + main_backend = get_scheduler('local') try: run_ready_tasks(main_backend, main_app) except Exception: main_backend.rollback() raise diff --git a/swh/scheduler/cli.py b/swh/scheduler/cli.py index ed4a901..69bb124 100644 --- a/swh/scheduler/cli.py +++ b/swh/scheduler/cli.py @@ -1,276 +1,290 @@ # Copyright (C) 2016-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import arrow import click import csv import itertools import json import locale import logging from swh.core import utils -from .backend import SchedulerBackend from .backend_es import SWHElasticSearchClient locale.setlocale(locale.LC_ALL, '') ARROW_LOCALE = locale.getlocale(locale.LC_TIME)[0] class DateTimeType(click.ParamType): name = 'time and date' def convert(self, value, param, ctx): if not isinstance(value, arrow.Arrow): value = arrow.get(value) return value DATETIME = DateTimeType() CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) def pretty_print_list(list, indent): """Pretty-print a list""" return ''.join('%s%s\n' % (' ' * indent, item) for item in list) def pretty_print_dict(dict, indent): """Pretty-print a list""" return ''.join('%s%s: %s\n' % (' ' * indent, click.style(key, bold=True), value) for key, value in dict.items()) def pretty_print_task(task): """Pretty-print a task""" next_run = arrow.get(task['next_run']) lines = [ '%s %s\n' % (click.style('Task', bold=True), task['id']), click.style(' Next run: ', bold=True), "%s (%s)" % (next_run.humanize(locale=ARROW_LOCALE), next_run.format()), '\n', click.style(' Interval: ', bold=True), str(task['current_interval']), '\n', click.style(' Type: ', bold=True), task['type'], '\n', click.style(' Args:\n', bold=True), pretty_print_list(task['arguments']['args'], indent=4), click.style(' Keyword args:\n', bold=True), pretty_print_dict(task['arguments']['kwargs'], indent=4), ] return ''.join(lines) @click.group(context_settings=CONTEXT_SETTINGS) -@click.option( - '--database', '-d', help='Scheduling database DSN', - default='host=db.internal.softwareheritage.org ' - 'dbname=softwareheritage-scheduler user=guest') +@click.option('--cls', '-c', default='local', + help="Scheduler's class, default to 'local'") +@click.option('--database', '-d', + default='host=db.internal.softwareheritage.org ' + 'dbname=softwareheritage-scheduler user=guest', + help='Scheduling database DSN') +@click.option('--url', '-u', default='http://localhost:5008', + help="(Optional) Scheduler's url access") @click.pass_context -def cli(ctx, database): - """Software Heritage Scheduler CLI interface""" - override_config = {} - if database: - override_config['scheduling_db'] = database +def cli(ctx, cls, database, url): + """Software Heritage Scheduler CLI interface - ctx.obj = SchedulerBackend(**override_config) + Default to use the the local scheduler instance (plugged to the + main scheduler db). + + """ + scheduler = None + from . import get_scheduler + if cls == 'local': + scheduler = get_scheduler(cls, args={'scheduling_db': database}) + elif cls == 'remote': + scheduler = get_scheduler(cls, args={'url': url}) + + if not scheduler: + raise ValueError('Scheduler class (local/remote) must be instantiated') + + ctx.obj = scheduler @cli.group('task') @click.pass_context def task(ctx): """Manipulate tasks.""" pass @task.command('schedule') @click.option('--columns', '-c', multiple=True, default=['type', 'args', 'kwargs', 'next_run'], type=click.Choice([ 'type', 'args', 'kwargs', 'policy', 'next_run']), help='columns present in the CSV file') @click.option('--delimiter', '-d', default=',') @click.argument('file', type=click.File(encoding='utf-8')) @click.pass_context def schedule_tasks(ctx, columns, delimiter, file): """Schedule tasks from a CSV input file. The following columns are expected, and can be set through the -c option: - type: the type of the task to be scheduled (mandatory) - args: the arguments passed to the task (JSON list, defaults to an empty list) - kwargs: the keyword arguments passed to the task (JSON object, defaults to an empty dict) - next_run: the date at which the task should run (datetime, defaults to now) The CSV can be read either from a named file, or from stdin (use - as filename). Use sample: cat scheduling-task.txt | \ python3 -m swh.scheduler.cli \ --database 'service=swh-scheduler-dev' \ task schedule \ --columns type --columns kwargs --columns policy \ --delimiter ';' - """ tasks = [] now = arrow.utcnow() reader = csv.reader(file, delimiter=delimiter) for line in reader: task = dict(zip(columns, line)) args = json.loads(task.pop('args', '[]')) kwargs = json.loads(task.pop('kwargs', '{}')) task['arguments'] = { 'args': args, 'kwargs': kwargs, } task['next_run'] = DATETIME.convert(task.get('next_run', now), None, None) tasks.append(task) created = ctx.obj.create_tasks(tasks) output = [ 'Created %d tasks\n' % len(created), ] for task in created: output.append(pretty_print_task(task)) click.echo_via_pager('\n'.join(output)) @task.command('list-pending') @click.option('--task-type', '-t', required=True, help='The tasks\' type concerned by the listing') @click.option('--limit', '-l', required=False, type=click.INT, help='The maximum number of tasks to fetch') @click.option('--before', '-b', required=False, type=DATETIME, help='List all jobs supposed to run before the given date') @click.pass_context def list_pending_tasks(ctx, task_type, limit, before): """List the tasks that are going to be run. You can override the number of tasks to fetch """ pending = ctx.obj.peek_ready_tasks(task_type, timestamp=before, num_tasks=limit) output = [ 'Found %d tasks\n' % len(pending) ] for task in pending: output.append(pretty_print_task(task)) click.echo_via_pager('\n'.join(output)) @task.command('archive') @click.option('--before', '-b', default=None, help='''Task whose ended date is anterior will be archived. Default to current month's first day.''') @click.option('--after', '-a', default=None, help='''Task whose ended date is after the specified date will be archived. Default to prior month's first day.''') @click.option('--batch-index', default=1000, type=click.INT, help='Batch size of tasks to read from db to archive') @click.option('--bulk-index', default=200, type=click.INT, help='Batch size of tasks to bulk index') @click.option('--batch-clean', default=1000, type=click.INT, help='Batch size of task to clean after archival') @click.option('--dry-run/--no-dry-run', is_flag=True, default=False, help='Default to list only what would be archived.') @click.option('--verbose', is_flag=True, default=False, help='Default to list only what would be archived.') @click.option('--cleanup/--no-cleanup', is_flag=True, default=True, help='Clean up archived tasks (default)') @click.option('--start-from', type=click.INT, default=-1, help='(Optional) default task id to start from. Default is -1.') @click.pass_context def archive_tasks(ctx, before, after, batch_index, bulk_index, batch_clean, dry_run, verbose, cleanup, start_from): """Archive task/task_run whose (task_type is 'oneshot' and task_status is 'completed') or (task_type is 'recurring' and task_status is 'disabled'). With --dry-run flag set (default), only list those. """ es_client = SWHElasticSearchClient() logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) log = logging.getLogger('swh.scheduler.cli.archive') logging.getLogger('urllib3').setLevel(logging.WARN) logging.getLogger('elasticsearch').setLevel(logging.WARN) if dry_run: log.info('**DRY-RUN** (only reading db)') if not cleanup: log.info('**NO CLEANUP**') now = arrow.utcnow() # Default to archive all tasks prior to now's last month if not before: before = now.format('YYYY-MM-01') if not after: after = now.shift(months=-1).format('YYYY-MM-01') log.debug('index: %s; cleanup: %s; period: [%s ; %s]' % ( not dry_run, not dry_run and cleanup, after, before)) def group_by_index_name(data, es_client=es_client): ended = data['ended'] return es_client.compute_index_name(ended.year, ended.month) def index_data(before, last_id, batch_index, backend=ctx.obj): tasks_in = backend.filter_task_to_archive( after, before, last_id=last_id, limit=batch_index) for index_name, tasks_group in itertools.groupby( tasks_in, key=group_by_index_name): log.debug('Send for indexation to index %s' % index_name) if dry_run: for task in tasks_group: yield task continue yield from es_client.streaming_bulk( index_name, tasks_group, source=['task_id', 'task_run_id'], chunk_size=bulk_index, log=log) gen = index_data(before, last_id=start_from, batch_index=batch_index) if cleanup: for task_ids in utils.grouper(gen, n=batch_clean): task_ids = list(task_ids) log.info('Clean up %s tasks: [%s, ...]' % ( len(task_ids), task_ids[0])) if dry_run: # no clean up continue ctx.obj.delete_archived_tasks(task_ids) else: for task_ids in utils.grouper(gen, n=batch_index): task_ids = list(task_ids) log.info('Indexed %s tasks: [%s, ...]' % ( len(task_ids), task_ids[0])) @cli.group('task-run') @click.pass_context def task_run(ctx): """Manipulate task runs.""" pass if __name__ == '__main__': cli() diff --git a/swh/scheduler/tests/test_api_client.py b/swh/scheduler/tests/test_api_client.py new file mode 100644 index 0000000..c395e8c --- /dev/null +++ b/swh/scheduler/tests/test_api_client.py @@ -0,0 +1,36 @@ +# Copyright (C) 2018 The Software Heritage developers +# See the AUTHORS file at the top-level directory of this distribution +# License: GNU General Public License version 3, or any later version +# See top-level LICENSE file for more information + +import unittest + +from swh.core.tests.server_testing import ServerTestFixture +from swh.scheduler import get_scheduler +from swh.scheduler.tests.test_scheduler import CommonSchedulerTest +from swh.scheduler.api.server import app + + +class RemoteSchedulerTest(CommonSchedulerTest, ServerTestFixture, + unittest.TestCase): + """Test the remote scheduler API. + + This class doesn't define any tests as we want identical + functionality between local and remote scheduler. All the tests are + therefore defined in CommonSchedulerTest. + """ + + def setUp(self): + self.config = { + 'scheduler': { + 'cls': 'local', + 'args': { + 'scheduling_db': 'dbname=%s' % self.TEST_DB_NAME, + } + } + } + self.app = app # this will setup the local scheduler... + super().setUp() + # accessible through a remote scheduler accessible on the + # given port + self.backend = get_scheduler('remote', {'url': self.url()}) diff --git a/swh/scheduler/tests/test_scheduler.py b/swh/scheduler/tests/test_scheduler.py index 67d7f2a..43edfc5 100644 --- a/swh/scheduler/tests/test_scheduler.py +++ b/swh/scheduler/tests/test_scheduler.py @@ -1,238 +1,358 @@ -# Copyright (C) 2017 The Software Heritage developers +# Copyright (C) 2017-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import copy import datetime import os import random import unittest +import uuid from arrow import utcnow +from collections import defaultdict from nose.plugins.attrib import attr from nose.tools import istest import psycopg2 from swh.core.tests.db_testing import SingleDbTestFixture -from swh.scheduler.backend import SchedulerBackend +from swh.scheduler import get_scheduler TEST_DIR = os.path.dirname(os.path.abspath(__file__)) TEST_DATA_DIR = os.path.join(TEST_DIR, '../../../../swh-storage-testdata') @attr('db') -class Scheduler(SingleDbTestFixture, unittest.TestCase): +class CommonSchedulerTest(SingleDbTestFixture): TEST_DB_NAME = 'softwareheritage-scheduler-test' TEST_DB_DUMP = os.path.join(TEST_DATA_DIR, 'dumps/swh-scheduler.dump') def setUp(self): super().setUp() - self.config = {'scheduling_db': 'dbname=' + self.TEST_DB_NAME} - self.backend = SchedulerBackend(**self.config) tt = { 'type': 'update-git', 'description': 'Update a git repository', 'backend_name': 'swh.loader.git.tasks.UpdateGitRepository', 'default_interval': datetime.timedelta(days=64), 'min_interval': datetime.timedelta(hours=12), 'max_interval': datetime.timedelta(days=64), 'backoff_factor': 2, 'max_queue_length': None, 'num_retries': 7, 'retry_delay': datetime.timedelta(hours=2), } tt2 = tt.copy() tt2['type'] = 'update-hg' tt2['description'] = 'Update a mercurial repository' tt2['backend_name'] = 'swh.loader.mercurial.tasks.UpdateHgRepository' tt2['max_queue_length'] = 42 tt2['num_retries'] = None tt2['retry_delay'] = None self.task_types = { tt['type']: tt, tt2['type']: tt2, } self.task1_template = t1_template = { 'type': tt['type'], 'arguments': { 'args': [], 'kwargs': {}, }, 'next_run': None, } self.task2_template = t2_template = copy.deepcopy(t1_template) t2_template['type'] = tt2['type'] t2_template['policy'] = 'oneshot' def tearDown(self): - self.backend.db.close() + self.backend.close_connection() self.empty_tables() super().tearDown() def empty_tables(self): self.cursor.execute("""SELECT table_name FROM information_schema.tables WHERE table_schema = %s""", ('public',)) tables = set(table for (table,) in self.cursor.fetchall()) for table in tables: self.cursor.execute('truncate table %s cascade' % table) self.conn.commit() @istest def add_task_type(self): tt, tt2 = self.task_types.values() self.backend.create_task_type(tt) self.assertEqual(tt, self.backend.get_task_type(tt['type'])) with self.assertRaisesRegex(psycopg2.IntegrityError, '\(type\)=\(%s\)' % tt['type']): self.backend.create_task_type(tt) self.backend.create_task_type(tt2) self.assertEqual(tt, self.backend.get_task_type(tt['type'])) self.assertEqual(tt2, self.backend.get_task_type(tt2['type'])) @istest def get_task_types(self): tt, tt2 = self.task_types.values() self.backend.create_task_type(tt) self.backend.create_task_type(tt2) self.assertCountEqual([tt2, tt], self.backend.get_task_types()) @staticmethod def _task_from_template(template, next_run, *args, **kwargs): ret = copy.deepcopy(template) ret['next_run'] = next_run if args: ret['arguments']['args'] = list(args) if kwargs: ret['arguments']['kwargs'] = kwargs return ret def _tasks_from_template(self, template, max_timestamp, num): return [ self._task_from_template( template, max_timestamp - datetime.timedelta(microseconds=i), 'argument-%03d' % i, **{'kwarg%03d' % i: 'bogus-kwarg'} ) for i in range(num) ] def _create_task_types(self): for tt in self.task_types.values(): self.backend.create_task_type(tt) @istest def create_tasks(self): self._create_task_types() tasks = ( self._tasks_from_template(self.task1_template, utcnow(), 100) + self._tasks_from_template(self.task2_template, utcnow(), 100) ) ret = self.backend.create_tasks(tasks) ids = set() for task, orig_task in zip(ret, tasks): task = copy.deepcopy(task) task_type = self.task_types[orig_task['type']] self.assertNotIn(task['id'], ids) self.assertEqual(task['status'], 'next_run_not_scheduled') self.assertEqual(task['current_interval'], task_type['default_interval']) self.assertEqual(task['policy'], orig_task.get('policy', 'recurring')) self.assertEqual(task['retries_left'], task_type['num_retries'] or 0) ids.add(task['id']) del task['id'] del task['status'] del task['current_interval'] del task['retries_left'] if 'policy' not in orig_task: del task['policy'] self.assertEqual(task, orig_task) @istest def peek_ready_tasks(self): self._create_task_types() t = utcnow() task_type = self.task1_template['type'] tasks = self._tasks_from_template(self.task1_template, t, 100) random.shuffle(tasks) self.backend.create_tasks(tasks) ready_tasks = self.backend.peek_ready_tasks(task_type) self.assertEqual(len(ready_tasks), len(tasks)) for i in range(len(ready_tasks) - 1): self.assertLessEqual(ready_tasks[i]['next_run'], ready_tasks[i+1]['next_run']) # Only get the first few ready tasks limit = random.randrange(5, 5 + len(tasks)//2) ready_tasks_limited = self.backend.peek_ready_tasks( task_type, num_tasks=limit) self.assertEqual(len(ready_tasks_limited), limit) self.assertCountEqual(ready_tasks_limited, ready_tasks[:limit]) # Limit by timestamp max_ts = tasks[limit-1]['next_run'] ready_tasks_timestamped = self.backend.peek_ready_tasks( task_type, timestamp=max_ts) for ready_task in ready_tasks_timestamped: self.assertLessEqual(ready_task['next_run'], max_ts) # Make sure we get proper behavior for the first ready tasks self.assertCountEqual( ready_tasks[:len(ready_tasks_timestamped)], ready_tasks_timestamped, ) # Limit by both ready_tasks_both = self.backend.peek_ready_tasks( task_type, timestamp=max_ts, num_tasks=limit//3) self.assertLessEqual(len(ready_tasks_both), limit//3) for ready_task in ready_tasks_both: self.assertLessEqual(ready_task['next_run'], max_ts) self.assertIn(ready_task, ready_tasks[:limit//3]) @istest def grab_ready_tasks(self): self._create_task_types() t = utcnow() task_type = self.task1_template['type'] tasks = self._tasks_from_template(self.task1_template, t, 100) random.shuffle(tasks) self.backend.create_tasks(tasks) first_ready_tasks = self.backend.peek_ready_tasks( task_type, num_tasks=10) grabbed_tasks = self.backend.grab_ready_tasks(task_type, num_tasks=10) for peeked, grabbed in zip(first_ready_tasks, grabbed_tasks): self.assertEqual(peeked['status'], 'next_run_not_scheduled') del peeked['status'] self.assertEqual(grabbed['status'], 'next_run_scheduled') del grabbed['status'] self.assertEqual(peeked, grabbed) @istest def get_tasks(self): self._create_task_types() t = utcnow() tasks = self._tasks_from_template(self.task1_template, t, 100) tasks = self.backend.create_tasks(tasks) random.shuffle(tasks) while len(tasks) > 1: length = random.randrange(1, len(tasks)) cur_tasks = tasks[:length] tasks[:length] = [] ret = self.backend.get_tasks(task['id'] for task in cur_tasks) self.assertCountEqual(ret, cur_tasks) + + @istest + def filter_task_to_archive(self): + """Filtering only list disabled recurring or completed oneshot tasks + + """ + self._create_task_types() + _time = utcnow() + recurring = self._tasks_from_template(self.task1_template, _time, 12) + oneshots = self._tasks_from_template(self.task2_template, _time, 12) + total_tasks = len(recurring) + len(oneshots) + + # simulate scheduling tasks + pending_tasks = self.backend.create_tasks(recurring + oneshots) + backend_tasks = [{ + 'task': task['id'], + 'backend_id': str(uuid.uuid4()), + 'scheduled': utcnow(), + } for task in pending_tasks] + self.backend.mass_schedule_task_runs(backend_tasks) + + # we simulate the task are being done + _tasks = [] + for task in backend_tasks: + t = self.backend.end_task_run( + task['backend_id'], status='eventful') + _tasks.append(t) + + # Randomly update task's status per policy + status_per_policy = {'recurring': 0, 'oneshot': 0} + status_choice = { + # policy: [tuple (1-for-filtering, 'associated-status')] + 'recurring': [(1, 'disabled'), + (0, 'completed'), + (0, 'next_run_not_scheduled')], + 'oneshot': [(0, 'next_run_not_scheduled'), + (0, 'disabled'), + (1, 'completed')] + } + + tasks_to_update = defaultdict(list) + _task_ids = defaultdict(list) + # randomize 'disabling' recurring task or 'complete' oneshot task + for task in pending_tasks: + policy = task['policy'] + _task_ids[policy].append(task['id']) + status = random.choice(status_choice[policy]) + if status[0] != 1: + continue + # elected for filtering + status_per_policy[policy] += status[0] + tasks_to_update[policy].append(task['id']) + + self.backend.disable_tasks(tasks_to_update['recurring']) + # hack: change the status to something else than completed + self.backend.set_status_tasks( + _task_ids['oneshot'], status='disabled') + self.backend.set_status_tasks( + tasks_to_update['oneshot'], status='completed') + + total_tasks_filtered = (status_per_policy['recurring'] + + status_per_policy['oneshot']) + + # retrieve tasks to archive + after = _time.shift(days=-1).format('YYYY-MM-DD') + before = utcnow().shift(days=1).format('YYYY-MM-DD') + tasks_to_archive = list(self.backend.filter_task_to_archive( + after_ts=after, before_ts=before, limit=total_tasks)) + + self.assertEqual(len(tasks_to_archive), total_tasks_filtered) + + actual_filtered_per_status = {'recurring': 0, 'oneshot': 0} + for task in tasks_to_archive: + actual_filtered_per_status[task['task_policy']] += 1 + + self.assertEqual(actual_filtered_per_status, status_per_policy) + + @istest + def delete_archived_tasks(self): + self._create_task_types() + _time = utcnow() + recurring = self._tasks_from_template( + self.task1_template, _time, 12) + oneshots = self._tasks_from_template( + self.task2_template, _time, 12) + total_tasks = len(recurring) + len(oneshots) + pending_tasks = self.backend.create_tasks(recurring + oneshots) + backend_tasks = [{ + 'task': task['id'], + 'backend_id': str(uuid.uuid4()), + 'scheduled': utcnow(), + } for task in pending_tasks] + self.backend.mass_schedule_task_runs(backend_tasks) + + _tasks = [] + percent = random.randint(0, 100) # random election removal boundary + for task in backend_tasks: + t = self.backend.end_task_run( + task['backend_id'], status='eventful') + c = random.randint(0, 100) + if c <= percent: + _tasks.append({'task_id': t['task'], 'task_run_id': t['id']}) + + self.backend.delete_archived_tasks(_tasks) + + self.cursor.execute('select count(*) from task') + tasks_count = self.cursor.fetchone() + + self.cursor.execute('select count(*) from task_run') + tasks_run_count = self.cursor.fetchone() + + self.assertEqual(tasks_count[0], total_tasks - len(_tasks)) + self.assertEqual(tasks_run_count[0], total_tasks - len(_tasks)) + + +class LocalSchedulerTest(CommonSchedulerTest, unittest.TestCase): + def setUp(self): + super().setUp() + self.config = {'scheduling_db': 'dbname=' + self.TEST_DB_NAME} + self.backend = get_scheduler('local', self.config) diff --git a/version.txt b/version.txt index 2c5c848..be0983c 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -v0.0.25-0-g8124229 \ No newline at end of file +v0.0.26-0-gffd2dda \ No newline at end of file