-
Notifications
You must be signed in to change notification settings - Fork 2
/
gxp_js.py
3593 lines (3310 loc) · 125 KB
/
gxp_js.py
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# in order to support join/leave
# we need to update session.peer_tree
import errno,heapq,math,os,random,re,select,signal,socket,string,sys,time,types
import gxpc,gxpm,ioman,opt
import cPickle,cStringIO
dbg=0
def Ws(s):
sys.stdout.write(s)
def Es(s):
sys.stderr.write(s)
class jobsched_cmd_opts(opt.cmd_opts):
"""
command line options we accept
"""
def __init__(self):
# (type, default)
# types supported
# s : string
# i : int
# f : float
# l : list of strings
# None : flag
opt.cmd_opts.__init__(self)
self.conf = ("s", "gxp_js.conf") # config file
self.attrs = ("s*", []) # --attr x=y
self.help = (None, 0)
self.c = "conf"
self.a = "attrs"
self.h = "help"
class jobsched_tokenizer:
"""
config file tokenizer
"""
def __init__(self):
self.elem_reg_str = self.elem_regexp()
self.elem_reg = re.compile(self.elem_reg_str)
self.eq_reg_str = "(?P<eq>\+?\=)"
self.eq_reg = re.compile(self.eq_reg_str)
def elem_regexp(self):
# not white space, not double quote character (")
non_ws_non_quote_non_equal_char = '[^\s\"\+\=]'
# not double quote character (")
non_quote_char = '[^\"]'
# element: either a non-quoted list of chars containing no
# white spaces nor double quotes, or a quoted string
elem = ('(?P<raw>%s+)|\"(?P<quoted>%s*)\"'
% (non_ws_non_quote_non_equal_char, non_quote_char))
return elem
def init(self, filename, lineno, line):
self.filename = filename
self.lineno = lineno
self.line = line
self.rest = line
self.s = None
self.val = None
return self.next()
def warn_parse_error(self):
Es("%s:%d: parse error [%s]"
% (self.filename, self.lineno, self.line))
def next(self):
self.rest = self.rest.lstrip()
# EOF
if self.rest == "":
self.s = ""
self.val = None
if dbg>=2:
Es(" EOF\n")
return self
# += or =
m = self.eq_reg.match(self.rest)
if m:
self.s = self.val = m.group("eq")
if dbg>=2:
Es(" next token from [%s] -> %s\n" % (self.rest, self.s))
self.rest = self.rest[m.end():]
return self
# should be element+
E = []
any_quoted = 0
orig_rest = self.rest
while self.rest != "":
if dbg>=2:
Es(" next element from [%s]\n" % self.rest)
m = self.elem_reg.match(self.rest)
if m:
r,q = m.group("raw", "quoted")
if r is None:
any_quoted = 1
E.append(q)
else:
E.append(r)
self.rest = self.rest[m.end():]
else:
break
if len(E) == 0:
self.warn_parse_error()
self.s = ""
self.val = None
return self
self.s = "".join(E)
if dbg>=2:
Es(" next token from [%s] -> %s\n"
% (orig_rest, self.s))
if any_quoted:
self.val = self.s
else:
self.val = self.token_val(self.s)
return self
def safe_atoi(self, s):
try:
return string.atoi(s)
except ValueError:
return None
def safe_atof(self, s):
try:
return string.atof(s)
except ValueError:
return None
def token_val(self, s):
"""
convert a string s into an 'appropriate'
python object.
if it looks like an int or a float, it returns
the converted number.
if it looks like 1M 1.5G, etc., it returns the
appropriate number.
otherwise it returns the string.
"""
i = self.safe_atoi(s)
if i is not None: return i
f = self.safe_atof(s)
if f is not None: return f
m = s[-1:].lower()
if m in "kmgtpez":
x = self.safe_atoi(s[:-1])
if x is None: x = self.safe_atof(s[:-1])
if x is not None:
if m == "k": return x * (2**10)
if m == "m": return x * (2**20)
if m == "g": return x * (2**30)
if m == "t": return x * (2**40)
if m == "p": return x * (2**50)
if m == "e": return x * (2**60)
if m == "z": return x * (2**70)
bomb
return s
class jobsched_config:
"""
object representing configuration
"""
db_fields = [ "opts",
"work_file", "work_fd", "work_py_module",
"work_proc_pipe", "work_proc_pipe2",
"work_proc_sock", "work_proc_sock2",
"work_server_sock", "work_server_sock2",
"work_db_type",
"worker_prof_cmd",
"work_list_limit", "state_dir", "template_html",
"gen_html_overhead", "refresh_interval",
"no_dispatch_after", "interrupt_at",
"cpu_factor", "mem_factor", "translate_dir", "job_output",
"make_cmd",
"gnu_parallel_cmd",
"make_exit_status_no_throw",
"make_exit_status_connect_failed",
"make_exit_status_server_died",
"make_local_exec_cmd",
"redirect_output",
"conf_file", "log_file", "host_job_attrs" ]
def __init__(self, opts):
self.opts = opts
self.work_file = [] # list of strings
self.work_fd = [] # list of ints
self.work_py_module = [] # list of strings
self.work_proc_pipe = []
self.work_proc_pipe2 = []
self.work_proc_sock = []
self.work_proc_sock2 = []
self.work_server_sock = []
self.work_server_sock2= []
self.work_db_type = "text"
self.worker_prof_cmd = "${GXP_DIR}/gxpbin/worker_prof"
self.work_list_limit = 100
self.state_dir = "state"
self.template_html = "${GXP_DIR}/gxpbin/gxp_js_template.html"
self.gen_html_overhead = 0.05
self.refresh_interval = 60
self.no_dispatch_after = float("inf")
self.interrupt_at = float("inf")
self.cpu_factor = 1.0
self.mem_factor = 0.9
self.translate_dir = []
self.job_output = [ 1, 2 ]
# "x" : x through
# "x," : x > /dev/null
# "x,file" : x > file
# self.redirect_output = [ "1", "2" ]
self.echo_job_output = 1
self.deliver_job_output = 0
# it must go away at some point and become default
self.new_notification_format = 1
# some make specific ones
self.make_cmd = "make"
self.make_exit_status_no_throw = 124
self.make_exit_status_connect_failed = 125
self.make_exit_status_server_died = 126
self.make_local_exec_cmd = None
self.gnu_parallel_cmd = "parallel"
self.ctl = None
# probably you will not be interested in
# the following configs, but just for the
# sake of flexibiliy
self.conf_file = "gxp_js.conf"
self.log_file = "gxp_js.log"
# attrs["host","cpu"] = ...
self.host_job_attrs = {}
self.set_scope("host", ".*", re.compile(".*"))
def __str__(self):
S = []
items = self.__dict__.items()
items.sort()
for k,v in items:
if k != "host_job_attrs":
S.append(("%s : %s" % (k, v)))
host_job_items = self.host_job_attrs.items()
host_job_items.sort()
for k,V in host_job_items:
S.append(" %s,%s :" % k)
for reg_str,reg,val in V:
S.append(" %s : %s" % (reg_str, val))
return "\n".join(S)
def warn(self, filename, lineno, line, msg):
Es("%s:%d: warning: %s (%s)\n"
% (filename, lineno, msg, string.rstrip(line)))
def set_scope(self, scope, reg_str, reg):
self.cur_scope = scope
self.cur_reg_str = reg_str
# FIXIT: handle exception
self.cur_reg = reg
def set_host_job_attr(self, scope, reg_str, reg, key, val):
if dbg>=2:
Es(" host_job_attr %s %s : %s = %s\n" % (scope, reg_str, key, val))
if not self.host_job_attrs.has_key((scope,key)):
self.host_job_attrs[scope,key] = []
self.host_job_attrs[scope,key].append((reg_str, reg, val))
def set_host_job_attrs(self, scope, reg_str, reg, tok):
n = 0
while tok.s != "":
key = tok.s
eq = tok.next().s
if eq == "=" or eq == "+=":
val = tok.next().val
else:
val = tok.val
self.set_host_job_attr(scope, reg_str, reg, key, val)
tok.next()
n = n + 1
return n
def parse_line(self, filename, lineno, line, tok):
"""
parse a single line
"""
if dbg>=2:
Es("parse_line: %s:%d [%s]\n" % (filename, lineno, line))
ls = line.lstrip()
if ls[:1] == "#": return
if ls.rstrip() == "": return
tok.init(filename, lineno, line)
x = tok.s
if dbg>=2:
Es(" 1st token: %s\n" % x)
if x == "host" or x == "job":
# host REGEXP KEY VAL KEY VAL ...
scope = x
reg_str = tok.next().s
# FIXIT: exception handling
reg = re.compile(reg_str)
tok.next()
if dbg>=2:
Es(" setting attributes %s %s\n" % (scope, reg_str))
if self.set_host_job_attrs(scope, reg_str, reg, tok) == 0:
self.set_scope(scope, reg_str, reg)
elif x in [ "trans_dir", "trans_dirs", "translate_dir" ]:
tok.next()
if tok.s == "=": tok.next()
rhs_items = []
while tok.s != "":
rhs_items.append(tok.val)
tok.next()
assert (len(rhs_items) > 0), tok.rest
self.translate_dir.append((rhs_items[0], rhs_items[1:]))
elif hasattr(self, x):
# generic attributes (cpu_factor, mem_factor, etc)
orig = getattr(self, x)
rest = tok.rest
eq = tok.next().s
if type(orig) is types.ListType:
# this attribute is a list attribute
if eq == "=" or eq == "+=":
tok.next()
else:
eq = "="
rhs_items = []
while tok.s != "":
rhs_items.append(tok.val)
tok.next()
if eq == "=":
if dbg>=2:
Es(" setting global attributes %s = %s\n"
% (x, rhs_items))
setattr(self, x, rhs_items)
else:
if dbg>=2:
Es(" setting global attributes %s += %s\n"
% (x, rhs_items))
setattr(self, x, orig + rhs_items)
else:
if eq == "=" or eq == "+=":
rest = tok.rest
tok.next()
else:
eq = "="
v = tok.token_val(rest.strip())
if dbg>=2:
Es(" setting global attributes %s = '%s'\n" % (x, v))
setattr(self, x, v)
else:
self.set_host_job_attrs(self.cur_scope, self.cur_reg_str,
self.cur_reg, tok)
def parse_list(self, filename, lines, tok):
i = 1
for line in lines:
if self.parse_line(filename, i, line, tok) == -1:
return -1
i = i + 1
return 0
def parse_fp(self, filename, fp, tok):
return self.parse_list(filename, fp.readlines(), tok)
def parse_file(self, filename, tok):
x = []
if os.path.exists(filename):
fp = open(filename, "rb")
x = self.parse_fp(filename, fp, tok)
fp.close()
else:
Es("warning: config file %s does not exist\n"
% filename)
return x
def parse_cmdline(self, attrs, tok):
# attrs : attributes given in the command line
return self.parse_list("<cmdline>", attrs, tok)
def parse(self):
tok = jobsched_tokenizer()
# process attributes given in the command line
# via --attrs x=y (or simply -a x=y) first
if self.parse_file(self.opts.conf, tok) == -1:
return -1
if self.parse_cmdline(self.opts.attrs, tok) == -1:
return -1
return 0
def get_host_or_job_attr(self, host_or_job, attr, name, default):
attrs = self.host_job_attrs.get((host_or_job,attr))
if attrs is None: return default
for regexp_str,regexp,val in attrs:
if regexp.match(name): return val
return default
def get_man_attr(self, gupid, key, default):
"""
gupid : worker unique name
key : like "cpu", "mem", etc.
"""
return self.get_host_or_job_attr("host", key, gupid, default)
def get_job_attr(self, cmd, key, default):
"""
cmd : cmd line
key : like "cpu", "mem", etc.
"""
return self.get_host_or_job_attr("job", key, cmd, default)
def mk_man_capacity(self, gupid):
D = {}
for host_or_job,key in self.host_job_attrs.keys():
if host_or_job == "host":
x = self.get_man_attr(gupid, key, None)
if x is not None: D[key] = x
return D
def dbg_jobsched_config():
o = jobsched_cmd_opts()
if o.parse([ "-a", "conf_file=gxp_js.conf" ]) == -1:
return -1
Es("\n")
c = jobsched_config(o)
c.parse()
Ws("%s\n" % c)
return c
# --------------------
# main things
# --------------------
class man_state:
"""
worker (man) state
"""
active = "0_active"
leaving = "1_leaving"
gone = "2_gone"
class man_join_leave_record:
"""
whenever a man joins or leaves, the user does
gxpc js -a ctl=join or gxpc js -a ctl=leave
this creates a process and gxp_js.py will receive
its IO and exit status. for each join/leave operation,
we record them
"""
def __init__(self):
self.io = { 1 : cStringIO.StringIO(),
2 : cStringIO.StringIO() }
self.done_io = {}
self.wait_status = None
def completed(self):
if len(self.io) > 0: return 0
if self.wait_status is None: return 0
return 1
def record_die(self, wait_status):
"""
called when gxp got notificatin that
the initial hello process exited (gxpd 'waited' it).
some outputs from the process may still be coming.
"""
# assert wait_status is not None
if self.wait_status is None:
self.wait_status = wait_status
def record_io(self, fd, payload, eof):
"""
called when gxp got notificatin that
the initial hello process outputs something
(payload) to its file descriptor (fd).
eof = 1 iff this is the last data (we can
assume no more data will be coming from the
same fd)
"""
# record whatever we got.
# this is normally a string telling us
# about the spec of this worker (e.g.,
# cpu 5 mem 4g
# if io[fd] does not exist, this man
# has already been working, so we ignore
# it
# if not self.io.has_key(fd): return
if payload != "":
ioo = self.io.get(fd) # cStringIO object
if ioo:
ioo.write(payload)
else:
Es("BUG: could not get IO object for fd=%s payload=%s\n" % (fd, payload))
if eof:
# this is the last msg. we indicate
# it by moving the record from io to
# done_io.
ioo = self.io.get(fd) # cStringIO object
if ioo is None:
Es("BUG: could not get IO object for fd=%s eof=1 payload=%s\n" % (fd, payload))
else:
s = ioo.getvalue()
del self.io[fd]
if self.done_io.has_key(fd):
Es("BUG: done_io has already fd=%s s=%s\n" % (fd, self.done_io[fd]))
self.done_io[fd] = s
class Man:
"""
a worker, or a man
"""
db_fields = [ "man_idx", "name", "n_runs", "capacity",
"time_last_heartbeat" ]
default_capacity = { "cpu" : 1 }
def __init__(self, man_idx, name, capacity, cur_time, server):
self.man_idx = man_idx # serial number
self.name = name # name (gupid)
self.capacity = capacity # dictionary of label : integer
self.capacity_left = {} # set in finalize_capacity
self.state = man_state.active
# created time
self.create_time = cur_time
# last time at which I heard from him
self.time_last_heartbeat = cur_time
self.runs_running = {} # run_idx -> run
self.n_runs = 0
# volatile
self.server = server
# join/leave records (rid -> man_join_leave_record)
self.jl_recs = {}
def reinit(self):
self.state = man_state.active
def __str__(self):
S = []
S.append("%s" % self.name)
for k,v in self.capacity.items():
vl = self.capacity_left.get(k)
S.append(" %s: %s/%s" % (k, vl, v))
return "\n".join(S)
def ensure_jl_rec(self, rid):
if not self.jl_recs.has_key(rid):
self.jl_recs[rid] = man_join_leave_record()
def completed(self, rid):
self.ensure_jl_rec(rid)
return self.jl_recs[rid].completed()
def n_completed(self):
x = 0
for jl_rec in self.jl_recs.values():
if jl_rec.completed():
x += 1
return x
def record_io(self, rid, fd, payload, eof):
self.ensure_jl_rec(rid)
self.jl_recs[rid].record_io(fd, payload, eof)
def record_die(self, rid, status):
self.ensure_jl_rec(rid)
self.jl_recs[rid].record_die(status)
def finalize_capacity(self, conf, rid):
"""
called when we detect that the initial hello process
completely terminated (got the wait notification and
all outpupt fds got EOFs)
"""
if self.server.logfp:
self.server.LOG("finalize_capacity of %s\n"
% self.name)
# parse its standard output, expecting worker spec
# like "cpu 8 mem 4g"
# get its standard output
fields = self.jl_recs[rid].done_io[1].split()
n = len(fields)
if n % 2 == 1: n = n - 1
# split into key-value pairs
# assuming key1 val1 key2 val3 ...
for i in range(0, n, 2):
key = fields[i]
val = int(fields[i + 1])
# use this value only when not given
# in the config file
if not self.capacity.has_key(key):
if self.server.logfp:
self.server.LOG("setting %s %s to %d\n"
% (self.name, key, val))
self.capacity[key] = val
# supply global default
for k,v in Man.default_capacity.items():
if not self.capacity.has_key(k):
self.capacity[k] = v
# multiply xxx_factor
for k,v in self.capacity.items():
# cpu or mem
k_factor = ("%s_factor" % k)
if hasattr(conf, k_factor):
factor = getattr(conf, k_factor)
if type(v) is types.IntType:
self.capacity[k] = int(v * factor)
else:
self.capacity[k] = v * factor
self.capacity_left = self.capacity.copy()
def modify_resource(self, requirement, sign):
for k,v in requirement.items():
self.capacity_left[k] = self.capacity_left[k] + sign * v
def has_affinity(self, affinity):
for a,p in affinity.items():
if hasattr(self, a):
av = getattr(self, a)
if p.match(av) is None: return 0
return 1
def has_resource(self, requirement):
for k,v in requirement.items():
x = self.capacity_left.get(k)
if x is None or x < v: return 0
return 1
def get_td_name(self):
"""
called by html generator to generate an element
of the table indicating its name and the status
(by <td class="...">)
"""
if self.state == man_state.active \
and len(self.runs_running) == 0:
return ("man_free", self.name)
else:
return (("man_%s" % self.state), self.name)
def get_td_capacity(self):
C = []
keys = self.capacity.keys()
keys.sort()
for k in keys:
c = self.capacity[k]
cl = self.capacity_left.get(k)
C.append("%s: %s / %s" % (k, cl, c))
return "\n".join(C)
class man_generator:
"""
generate a new man
"""
def __init__(self, conf, server):
self.next_man_idx = 0
self.conf = conf # jobsched_config object
self.server = server
def make_man(self, gupid):
man_idx = self.next_man_idx
self.next_man_idx = man_idx + 1
capacity = self.conf.mk_man_capacity(gupid)
man = Man(man_idx, gupid, capacity,
self.server.cur_time(), self.server)
return man
class men_monitor:
def __init__(self, conf, server):
self.conf = conf
self.server = server
self.time_last_ping = 0.0
class run_status:
queued = "queued"
running = "running"
finished = "finished"
worker_died = "worker_died"
worker_left = "worker_left"
no_throw = "no_throw"
interrupted = "interrupted"
class Run:
"""
state of a running task
"""
def init(self, work, run_idx, io_dir, job_output):
self.work_idx = work.work_idx # work idx
self.run_idx = run_idx
self.status = run_status.queued
self.exit_status = None
self.term_sig = None
self.man_name = None # set by find_matches (Man object)
self.time_start = None # set when thrown
self.time_end = None # set when returned
self.time_since_start = None # set whenever profiled
# following are all set when returned
self.worker_time_start = None # time when started by worker
self.worker_time_end = None # time when finished by worker
self.utime = None # user time
self.stime = None # sys time
self.maxrss = None
self.ixrss = None
self.idrss = None
self.isrss = None
self.minflt = None # minor faults
self.majflt = None # major faults
self.io_dir = io_dir
# volatile (not persistent) fields. not put in database
self.work = work
self.man = None
# FIXIT: make them configurable??
self.job_output = job_output
self.io = {}
self.done_io = {}
self.hold_limit = float("inf")
return self
def __str__(self):
return "%s" % self.work.cmd
def record_die(self, wait_status, rusage,
worker_time_start, worker_time_end):
"""
called when we receive die notification of the process.
outputs may still follow so at this point we cannot abandon
this object.
"""
exit_status = term_sig = None
if os.WIFEXITED(wait_status):
exit_status = os.WEXITSTATUS(wait_status)
elif os.WIFSIGNALED(wait_status):
term_sig = os.WTERMSIG(wait_status)
self.status = run_status.finished
self.exit_status = exit_status
self.term_sig = term_sig
self.worker_time_start = worker_time_start
self.worker_time_end = worker_time_end
if rusage:
self.utime = rusage[0]
self.stime = rusage[1]
self.maxrss = rusage[2]
self.ixrss = rusage[3]
self.idrss = rusage[4]
self.isrss = rusage[5]
self.minflt = rusage[6]
self.majflt = rusage[7]
def record_running(self, cur_time):
assert (self.time_start is None), self.time_start
self.time_start = cur_time
self.status = run_status.running
for fd in self.job_output:
self.io[fd] = (cStringIO.StringIO(), None, None)
def add_io(self, fd, payload, eof):
"""
called when we got notificatiion that
the process emitted something (payload)
from its file descriptor (fd).
eof = 1 iff this is the last data from
the fd.
"""
# inline : string IO object
# filename : filename or None
# wp : file object for filename or None
if self.work.server.logfp:
self.work.server.LOG("add_io : run=%s fd=%d eof=%d payload=[%s]\n"
% (self, fd, eof, payload))
inline,filename,wp = self.io[fd]
if payload != "":
# record whatever is output
inline.write(payload)
s = inline.getvalue()
max_inline_io = 128 * 1024 # 128KB
if len(s) > max_inline_io:
# on-memory data too large, flush into file
if wp is None:
filename = "run_%d_%d_%d" % (self.work_idx, self.run_idx, fd)
filename = os.path.join(self.io_dir, filename)
wp = open(filename, "wb")
wp.write(s)
wp.flush()
# and free the memory
inline.truncate()
self.io[fd] = (inline, filename, wp)
if eof:
# got EOF, so we indicate it by deleting
# the entry from io and move the record
# to done_io
s = inline.getvalue()
if wp:
wp.write(s)
wp.close()
inline.truncate()
# mark io from fd has done
del self.io[fd]
s = inline.getvalue()
self.done_io[fd] = (s, filename)
if self.work.server.conf.deliver_job_output:
self.work.add_io(fd, payload, eof, self.man_name)
def get_io_filenames(self):
fds = {}
for fd in self.io.keys(): fds[fd] = None
for fd in self.done_io.keys(): fds[fd] = None
fds = fds.keys()
fds.sort()
S = {}
for fd in fds:
x = self.io.get(fd)
if x:
_,filename,_ = x
else:
_,filename = self.done_io.get(fd)
S[fd] = filename
return S
def get_io_inline(self):
"""
FIXIT: should merge stdio and stderr
"""
fds = {}
for fd in self.io.keys(): fds[fd] = None
for fd in self.done_io.keys(): fds[fd] = None
fds = fds.keys()
fds.sort()
S = {}
for fd in fds:
x = self.io.get(fd)
if x:
inline,_,_ = x
s = inline.getvalue()
else:
s,_ = self.done_io.get(fd)
S[fd] = s
return S
def is_finished(self):
"""
check if this guy has really finished
('wait'ed by gxpd and their out fds closed)
"""
if len(self.io) > 0: return 0
if self.status == run_status.queued: return 0
if self.status == run_status.running: return 0
return 1
def record_no_throw(self, cur_time):
self.status = run_status.no_throw
self.finish(cur_time)
def finish(self, cur_time):
self.time_end = cur_time
if self.time_start is None:
# none if the job has not started.
# we consider them just started now
self.time_start = cur_time
self.time_since_start = self.time_end - self.time_start
return self.work.finish_or_retry(self.status, self.exit_status,
self.term_sig, self.man_name)
def sync(self, cur_time):
self.time_since_start = cur_time - self.time_start
self.work.server.works.update_run(self)
# db-related stuff
# following fields of this object will go to database/csv file/html
# for field x for which get_td_x method exists,
# get_td_worker_time method is called and its return value used .
# so result column will be obtained by self.get_td_result(), etc.
db_fields_1 = [ "run_idx", "result", "time_since_start", "man_name" ]
db_fields_2 = [ "time_start", "time_end",
"worker_time_start", "worker_time_end", "worker_time",
"utime", "stime", "maxrss", "ixrss", "idrss", "isrss",
"minflt", "majflt", "io", "io_filename" ]
def get_td_result(self):
if self.status == run_status.finished:
if self.exit_status is not None:
if self.exit_status == 0:
return ("job_success", "exit 0")
else:
return ("job_failed", ("exit %d" % self.exit_status))
elif self.term_sig is not None:
return ("job_killed", ("killed %d" % self.term_sig))
else:
assert 0, (self.status, self.exit_status, self.term_sig)
else:
return (("job_%s" % self.status), self.status)
def get_td_worker_time(self):
s = self.worker_time_start
e = self.worker_time_end
if s is None or e is None:
assert s is None
assert e is None
return "-"
else:
return e - s
def get_td_io(self):
io = []
for fd,(inline,_,_) in self.io.items():
io.append(inline.getvalue())
for fd,(inline_s,_) in self.done_io.items():
io.append(inline_s)
x = "".join(io)
# if len(x) == 0: return "<br>"
return x
def get_td_io_filename(self):
filenames = []
for fd,(_,filename,_) in self.io.items():
if filename is not None:
filenames.append('<a href="%s">%d</a>'
% (filename, fd))
x = ",".join(filenames)
if len(x) == 0: return "-"
return x
class Work:
"""
a work or a job sent from clients
"""
db_fields_1 = [ "work_idx", "cmd", ]
db_fields_2 = [ "pid", "dirs", "time_req" ]
def init(self, cmd, pid, dirs, envs, req, affinity):
# command line (string)
self.cmd = cmd
# pid (or None if not applicable/relevant)
self.pid = pid
# directories that should be tried for job's cwd
self.dirs = dirs
# environments that must be set for the job
self.envs = envs.copy()
# resource requirement of the work
self.requirement = req
self.affinity = affinity
self.next_run_idx = 0
return self
def init2(self, work_idx, cur_time, server):
self.envs["GXP_JOBSCHED_WORK_IDX"] = ("%d" % work_idx)
self.envs["GXP_MAKE_WORK_IDX"] = ("%d" % work_idx)
self.work_idx = work_idx
self.time_req = cur_time # time requested
# volatile fields
self.server = server
return self
def make_run(self):
"""
create a new run for this work
"""
run_idx = self.next_run_idx
self.next_run_idx = run_idx + 1
run = Run().init(self, run_idx,
self.server.conf.state_dir,
self.server.conf.job_output)
self.server.runs_todo.append(run)
# add run to DB
self.server.works.add_run(self.work_idx, run)
def retry(self):
# retry
msg = ("work '%s' will be retried\n" % self.cmd)
if self.server.logfp: self.server.LOG(msg)
self.make_run()
def add_io(self, fd, payload, eof, man_name):
self.server.wkg.add_io(self.work_idx, fd, payload, eof, man_name)
def finish_or_retry(self, status, exit_status, term_sig, man_name):
if status == run_status.worker_died \
or status == run_status.worker_left:
self.retry()
return 0
else:
msg = ("work '%s' finished\n" % self.cmd)
if self.server.logfp: self.server.LOG(msg)
return self.server.wkg.finish_work(self.work_idx, exit_status, term_sig, man_name)
#
# work generation framework
#
#