-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.py
More file actions
389 lines (274 loc) · 10.4 KB
/
Copy pathqueue.py
File metadata and controls
389 lines (274 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
############################################################
#
# Copyright (c) 2010, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
import tacticenv
from pyasm.security import Batch
from pyasm.common import Common, Config, Environment, jsonloads, jsondumps, TacticException
from pyasm.biz import Project
from pyasm.search import Search, DbContainer
from pyasm.command import Command
from tactic.command import Scheduler, SchedulerTask
import os
__all__ = ['JobTask']
# create a task from the job
class JobTask(SchedulerTask):
def __init__(my):
#print "JobTask: init"
my.job = None
my.jobs = []
my.check_interval = 1
my.max_jobs = 2
super(JobTask, my).__init__()
def set_check_interval(my, interval):
my.check_interval = interval
def get_process_key(my):
import platform;
host = platform.uname()[1]
pid = os.getpid()
return "%s:%s" % (host, pid)
def get_job_search_type(my):
return "sthpw/queue"
def get_next_job(my):
from pyasm.prod.queue import Queue
return Queue.get_next_job();
def cleanup_db_jobs(my):
# clean up the jobs that this host previously had
process_key = my.get_process_key()
job_search = Search(my.get_job_search_type())
job_search.add_filter("host", process_key)
my.jobs = job_search.get_sobjects()
my.cleanup()
def cleanup(my, count=0):
#print "Cleaning up ..."
if count >= 3:
return
try:
for job in my.jobs:
# reset all none complete jobs to pending
current_state = job.get_value("state")
if current_state not in ['locked']:
continue
#print "setting to pending"
job.set_value("state", "pending")
job.set_value("host", "")
job.commit()
my.jobs = []
except Exception, e:
print "Exception: ", e.message
count += 1
my.cleanup(count)
def execute(my):
import atexit
import time
atexit.register( my.cleanup )
while 1:
my.check_existing_jobs()
my.check_new_job()
time.sleep(my.check_interval)
#DbContainer.close_thread_sql()
def check_existing_jobs(my):
my.keep_jobs = []
for job in my.jobs:
job_code = job.get_code()
search = Search(my.get_job_search_type())
search.add_filter("code", job_code)
job = search.get_sobject()
if not job:
print "Cancel ...."
scheduler = Scheduler.get()
scheduler.cancel_task(job_code)
continue
state = job.get_value("state")
if state == 'cancel':
print "Cancel task [%s] ...." % job_code
scheduler = Scheduler.get()
scheduler.cancel_task(job_code)
job.set_value("state", "terminated")
job.commit()
continue
my.keep_jobs.append(job)
my.jobs = my.keep_jobs
def check_new_job(my):
num_jobs = len(my.jobs)
if num_jobs >= my.max_jobs:
print "Already at max jobs [%s]" % my.max_jobs
return
my.job = my.get_next_job()
if not my.job:
return
# set the process key
process_key = my.get_process_key()
my.job.set_value("host", process_key)
my.job.commit()
my.jobs.append(my.job)
# get some info from the job
command = my.job.get_value("command")
job_code = my.job.get_value("code")
#print "Grabbing job [%s] ... " % job_code
try:
kwargs = my.job.get_json_value("data")
except:
try:
kwargs = my.job.get_json_value("serialized")
except:
kwargs = {}
project_code = my.job.get_value("project_code")
login = my.job.get_value("login")
script_path = my.job.get_value("script_path", no_exception=True)
if script_path:
Project.set_project(project_code)
command = 'tactic.command.PythonCmd'
folder = os.path.dirname(script_path)
title = os.path.basename(script_path)
search = Search("config/custom_script")
search.add_filter("folder", folder)
search.add_filter("title", title)
custom_script = search.get_sobject()
script_code = custom_script.get_value("script")
kwargs['code'] = script_code
# add the job to the kwargs
kwargs['job'] = my.job
#print "command: ", command
#print "kwargs: ", kwargs
# Because we started a new thread, the environment may not
# yet be initialized
try:
from pyasm.common import Environment
Environment.get_env_object()
except:
print "running batch"
Batch()
queue = my.job.get_value("queue", no_exception=True)
queue_type = 'repeat'
print "running job: ", my.job.get_value("code")
if queue_type == 'inline':
cmd = Common.create_from_class_path(command, kwargs=kwargs)
try:
Command.execute_cmd(cmd)
# set job to complete
my.job.set_value("state", "complete")
except Exception, e:
my.job.set_value("state", "error")
my.job.commit()
my.jobs.remove(my.job)
my.job = None
elif queue_type == 'repeat':
cmd = Common.create_from_class_path(command, kwargs=kwargs)
attempts = 0
max_attempts = 5
retry_interval = 10
while 1:
try:
#Command.execute_cmd(cmd)
cmd.execute()
# set job to complete
my.job.set_value("state", "complete")
break
except TacticException, e:
# This is an error on this server, so just exit
# and don't bother retrying
print "Error: ", e
my.job.set_value("state", "error")
break
except Exception, e:
raise
print "WARNING in Queue: ", e
import time
time.sleep(retry_interval)
attempts += 1
print "Retrying [%s]...." % attempts
if attempts >= max_attempts:
print "ERROR: reached max attempts"
my.job.set_value("state", "error")
break
my.job.commit()
my.jobs.remove(my.job)
my.job = None
else:
class ForkedTask(SchedulerTask):
def __init__(my, **kwargs):
super(ForkedTask, my).__init__(**kwargs)
def execute(my):
# check to see the status of this job
"""
job = my.kwargs.get('job')
job_code = job.get_code()
search = Search("sthpw/queue")
search.add_filter("code", job_code)
my.kwargs['job'] = search.get_sobject()
if not job:
print "Cancelling ..."
return
state = job.get_value("state")
if state == "cancel":
print "Cancelling 2 ...."
return
"""
subprocess_kwargs = {
'login': login,
'project_code': project_code,
'command': command,
'kwargs': kwargs
}
subprocess_kwargs_str = jsondumps(subprocess_kwargs)
install_dir = Environment.get_install_dir()
python = Config.get_value("services", "python")
if not python:
python = 'python'
args = ['%s' % python, '%s/src/tactic/command/queue.py' % install_dir]
args.append(subprocess_kwargs_str)
import subprocess
p = subprocess.Popen(args)
DbContainer.close_thread_sql()
return
# can't use a forked task ... need to use a system call
#Command.execute_cmd(cmd)
# register this as a forked task
task = ForkedTask(name=job_code, job=my.job)
scheduler = Scheduler.get()
scheduler.start_thread()
# FIXME: the queue should not be inline
if queue == 'interval':
interval = my.job.get_value("interval")
if not interval:
interval = 60
scheduler.add_interval_task(task, interval=interval,mode='threaded')
else:
scheduler.add_single_task(task, mode='threaded')
def start():
scheduler = Scheduler.get()
scheduler.start_thread()
task = JobTask()
task.cleanup_db_jobs()
scheduler.add_single_task(task, mode='threaded', delay=1)
start = staticmethod(start)
def run_batch(kwargs):
command = k.get("command")
kwargs = k.get("kwargs")
login = k.get("login")
project_code = k.get("project_code")
from pyasm.security import Batch
Batch(project_code=project_code, login_code=login)
cmd = Common.create_from_class_path(command, kwargs=kwargs)
Command.execute_cmd(cmd)
__all__.append("QueueTest")
class QueueTest(Command):
def execute(my):
# this command has only a one in 10 chance of succeeding
import random
value = random.randint(0, 10)
if value != 5:
sdaffsfda
if __name__ == '__main__':
import sys
args = sys.argv[1:]
k = args[0]
k = jsonloads(k)
run_batch(k)