jobs.py 6.17 KB
Newer Older
Andreas Valder's avatar
Andreas Valder committed
1
2
from server import *
import traceback
Andreas Valder's avatar
Andreas Valder committed
3
import json
Andreas Valder's avatar
Andreas Valder committed
4
import random
5
from time import sleep
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

job_handlers = {}
def job_handler(*types, state='finished'):
	def wrapper(func):
		for jobtype in types:
			if jobtype not in job_handlers:
				job_handlers[jobtype] = {}
			if state not in job_handlers[jobtype]:
				job_handlers[jobtype][state] = []
			job_handlers[jobtype][state].append(func)
		return func
	return wrapper

def schedule_job(jobtype, data=None, priority=0, queue="default"):
	if not data:
		data = {}
Julian Rother's avatar
Julian Rother committed
22
	return modify('INSERT INTO jobs (type, priority, queue, data, time_created) VALUES (?, ?, ?, ?, ?)',
23
			jobtype, priority, queue, json.dumps(data, default=date_json_handler), datetime.now())
Andreas Valder's avatar
Andreas Valder committed
24

Julian Rother's avatar
Julian Rother committed
25
26
27
28
def cancel_job(job_id):
	modify('UPDATE jobs SET state = "deleted" WHERE id = ? AND state = "ready"', job_id)
	modify('UPDATE jobs SET canceled = 1 WHERE id = ?', job_id)

29
30
31
32
33
def restart_job(job_id, canceled=False):
	if canceled:
		modify('UPDATE jobs SET state = "ready", canceled = 0 WHERE id = ? AND state = "failed"', job_id)
	else:
		modify('UPDATE jobs SET state = "ready" WHERE id = ? AND state = "failed" AND NOT canceled', job_id)
Julian Rother's avatar
Julian Rother committed
34

35
@app.route('/internal/jobs/overview')
36
@register_navbar('Jobs', iconlib='fa', icon='suitcase')
Andreas Valder's avatar
Andreas Valder committed
37
38
@mod_required
def jobs_overview():
39
40
41
42
43
44
45
46
47
	if 'page' in request.args:
		page = max(0, int(request.args['page']))
	else:
		page = 0
	if 'pagesize' in request.args:
		pagesize = min(500, int(request.args['pagesize']))
	else:
		pagesize = 50

Andreas Valder's avatar
Andreas Valder committed
48
	worker = query('SELECT * FROM worker ORDER BY last_ping DESC')
49
50
51
52
53
54
55
56
57
58
59
60
61

	# get filter options
	filter_values = {
			'type': query('SELECT distinct type FROM jobs'),
			'state': query('SELECT distinct state FROM jobs'),
			'worker': query('SELECT distinct worker FROM jobs')}
	
	# parse filter
	filter = {
			'type': request.args.get('type','%'),
			'state': request.args.get('state','failed'),
			'worker': request.args.get('worker','%') }

62
	pagecount = math.ceil(query('SELECT count(id) as count FROM jobs WHERE (type like ?) AND (worker like ? OR (worker IS NULL AND ? = "%")) AND (state like ?)', filter['type'], filter['worker'], filter['worker'], filter['state'])[0]['count']/pagesize)
Andreas Valder's avatar
Andreas Valder committed
63
	jobs = query('SELECT * FROM jobs WHERE (type like ?) AND (worker like ? OR (worker IS NULL AND ? = "%")) AND (state like ?) ORDER BY `time_created` DESC LIMIT ? OFFSET ?', filter['type'], filter['worker'], filter['worker'], filter['state'], pagesize, page*pagesize)
64
	return render_template('jobs_overview.html',worker=worker,jobs=jobs, filter_values=filter_values, filter=filter, page=page, pagesize=pagesize, pagecount=pagecount)
Andreas Valder's avatar
Andreas Valder committed
65

66
67
@app.route('/internal/jobs/action/<action>', methods=['GET', 'POST'])
@app.route('/internal/jobs/action/<action>/<jobid>', methods=['GET', 'POST'])
68
69
@mod_required
@csrf_protect
70
def jobs_action(action, jobid=None):
71
	if action == 'clear_failed':
72
		query('UPDATE jobs SET state = "deleted" WHERE state = "failed" AND (id = ? OR ? IS NULL)', jobid, jobid)
73
	elif action == 'retry_failed':
74
		query('UPDATE jobs SET state = "ready", canceled = 0 WHERE state = "failed" AND (id = ? OR ? IS NULL)', jobid, jobid)
Julian Rother's avatar
Julian Rother committed
75
	elif action == 'copy' and jobid:
76
		query("INSERT INTO jobs (type, priority, queue, state, data, time_created) SELECT type, priority, queue, 'ready', data, ? FROM jobs where id = ?", datetime.now(), jobid)
Julian Rother's avatar
Julian Rother committed
77
	elif action == 'delete' and jobid:
78
		query('UPDATE jobs SET state = "deleted" WHERE id = ?', jobid)
Julian Rother's avatar
Julian Rother committed
79
80
	elif action == 'cancel' and jobid:
		cancel_job(jobid)
81
82
	return redirect(request.values.get('ref', url_for('jobs_overview')))

Andreas Valder's avatar
Andreas Valder committed
83
84
85
86
87
88
89
90
91
92
def jobs_api_token_required(func):
	@wraps(func)
	def decorator(*args, **kwargs):
		if 'apikey' in request.values:
			token = request.values['apikey']
		elif request.get_json() and ('apikey' in request.get_json()):
			token = request.get_json()['apikey']
		else:
			token = None
		
93
		if not token == config.get('JOBS_API_KEY', [None]):
Andreas Valder's avatar
Andreas Valder committed
94
95
96
97
98
			return 'Permission denied', 403
		else:
			return func(*args, **kwargs)
	return decorator

Andreas Valder's avatar
Andreas Valder committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
@sched_func(10)
def jobs_catch_broken():
	# scheduled but never pinged
	query('BEGIN')
	query('UPDATE jobs SET state="ready" WHERE state="scheduled" and time_scheduled < ?', datetime.now() - timedelta(seconds=10))
	try:
		query('COMMIT')
	except:
		pass
	# no pings since 60s
	query('BEGIN')
	query('UPDATE jobs SET state="failed" WHERE state="running" and last_ping < ?', datetime.now() - timedelta(seconds=60))
	try:
		query('COMMIT')
	except:
		pass

116
@app.route('/internal/jobs/api/job/<int:id>/ping', methods=['GET', 'POST'])
Andreas Valder's avatar
Andreas Valder committed
117
118
119
@jobs_api_token_required
def jobs_ping(id):
	hostname = request.values['host']
120
	status = json.dumps(json.loads(request.values['status']), default=date_json_handler)
Andreas Valder's avatar
Andreas Valder committed
121
	state = request.values['state']
122
123
	if state == 'finished':
		query('UPDATE jobs SET time_finished = ?, status = ?, state = "finished" where id = ?', datetime.now(), status, id)
Andreas Valder's avatar
Andreas Valder committed
124
	else:
125
		query('UPDATE jobs SET worker = ?, last_ping = ?, status = ?, state = ? where id = ?', hostname, datetime.now(), status, state, id)
126
	job = query('SELECT * FROM jobs WHERE id = ?', id, nlfix=False)[0]
127
128
129
130
131
	for func in job_handlers.get(job['type'], {}).get(state, []):
		try:
			func(id, job['type'], json.loads(job['data']), state, json.loads(job['status']))
		except Exception:
			traceback.print_exc()
Julian Rother's avatar
Julian Rother committed
132
133
134
135
	if job['canceled']:
		return 'Job canceled', 205
	else:
		return 'OK', 200
Andreas Valder's avatar
Andreas Valder committed
136

137
@app.route('/internal/jobs/api/worker/<hostname>/schedule', methods=['POST'])
Andreas Valder's avatar
Andreas Valder committed
138
@jobs_api_token_required
Andreas Valder's avatar
Andreas Valder committed
139
def jobs_schedule(hostname):
140
	query('REPLACE INTO worker (hostname, last_ping) values (?, ?)', hostname, datetime.now())
141
	hostdata = request.get_json()
Andreas Valder's avatar
Andreas Valder committed
142
	if not hostdata:
Andreas Valder's avatar
Andreas Valder committed
143
		return 'no hostdata sent', 400
Andreas Valder's avatar
Andreas Valder committed
144
	job = None
145
	tries = 0
Andreas Valder's avatar
Andreas Valder committed
146
	jobtypes = hostdata['jobtypes'] if 'jobtypes' in hostdata else []
Andreas Valder's avatar
Andreas Valder committed
147
148
	while (not job):
		try:
149
150
			query("BEGIN")
			for i in query('SELECT * FROM jobs WHERE state = "ready" ORDER BY priority DESC'):
151
				if i['type'] in hostdata['jobtypes'] and i['queue'] in hostdata['queues']:
152
153
154
155
156
					job = i
					break
			if not job:
				return 'no jobs', 503
			modify('UPDATE jobs SET state="scheduled", worker = ?, time_scheduled = ? WHERE id = ?', hostname, datetime.now(), job['id']) 
Andreas Valder's avatar
Andreas Valder committed
157
			query("COMMIT")
158
		except:
159
			tries += 1
Andreas Valder's avatar
Andreas Valder committed
160
			job = None
161
			sleep(random.random())
162
163
164
			if tries > 10:
				return 'no jobs', 503

165
	return Response(json.dumps(job, default=date_json_handler), mimetype='application/json')