-
Notifications
You must be signed in to change notification settings - Fork 99
/
Job.py
executable file
·3227 lines (2809 loc) · 119 KB
/
Job.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
import copy
import glob
import inspect
import os
import sys
import time
import uuid
import GangaCore.Core.FileWorkspace
from GangaCore.Core import Sandbox
from GangaCore.Core.exceptions import (
GangaException,
IncompleteJobSubmissionError,
JobManagerError,
SplitterError,
TypeMismatchError,
)
from GangaCore.Core.GangaRepository import getRegistry
from GangaCore.GPIDev.Adapters.ApplicationRuntimeHandlers import allHandlers
from GangaCore.GPIDev.Adapters.IApplication import PostprocessStatusUpdate
from GangaCore.GPIDev.Adapters.IPostProcessor import MultiPostProcessor
from GangaCore.GPIDev.Adapters.ISplitter import ISplitter
from GangaCore.GPIDev.Base import GangaObject
from GangaCore.GPIDev.Base.Objects import synchronised
from GangaCore.GPIDev.Base.Proxy import (
addProxy,
getName,
isType,
runtimeEvalString,
stripProxy,
)
from GangaCore.GPIDev.Lib.File import MassStorageFile, getFileConfigKeys
from GangaCore.GPIDev.Lib.GangaList.GangaList import GangaList
from GangaCore.GPIDev.Lib.Job.MetadataDict import MetadataDict
from GangaCore.GPIDev.MonitoringServices import getMonitoringObject
from GangaCore.GPIDev.Schema import (
ComponentItem,
FileItem,
GangaFileItem,
Schema,
SimpleItem,
Version,
)
from GangaCore.Lib.Executable import Executable
from GangaCore.Lib.Localhost import Localhost
from GangaCore.Utility.Config import ConfigError, getConfig
from GangaCore.Utility.logging import getLogger, log_user_exception
from .Error import JobError, JobStatusError
from .JobTime import JobTime
from .utils import (
lazyLoadJobApplication,
lazyLoadJobBackend,
lazyLoadJobFQID,
lazyLoadJobStatus,
)
logger = getLogger()
config = getConfig("Configuration")
if config["repositorytype"] == "Database":
from GangaCore.Core.GangaRepository.SubJobJsonList import SubJobJsonList
else:
from GangaCore.Core.GangaRepository.SubJobXMLList import (
SubJobXMLList as SubJobJsonList,
)
class Job(GangaObject):
"""Job is an interface for submision, killing and querying the jobs :-).
Basic configuration:
The "application" attribute defines what should be
run. Applications may be generic arbitrary executable scripts or
complex, predefined objects.
The "backend" attribute defines where and how to run. Backend
object represents a resource or a batch system with various
configuration parameters.
Available applications, backends and other job components may be listed
using the plugins() function. See help on plugins() function.
The "status" attribute represents the state of Ganga job object.
It is automatically updated by the monitoring loop. Note that
typically at the backends the jobs have their own, more detailed
status. This information is typically available via
"job.backend.status" attribute.
Bookkeeping and persistency:
Job objects contain basic book-keeping information: "id", "status"
and "name". Job objects are automatically saved in a job
repository which may be a special directory on a local filesystem
or a remote database.
Input/output and file workspace:
There is an input/output directory called file workspace
associated with each job ("inputdir" and "outputdir" properties).
When a job is submitted, all input files are copied to the file
workspace to keep consistency of the input while the job is
running. Ganga then ships all files in the input workspace to the
backend systems in a sandbox.
The list of input files is defined by the application
(implicitly). Additional files may be explicitly specified in the
"inputsandbox" attribute.
Job splitting:
The "splitter" attributes defines how a large job may be divided into
smaller subjobs. The subjobs are automatically created when the main
(master) job is submitted. The "subjobs" attribute gives access to
individual subjobs. The "master" attribute of a subjob points back to the
master job.
Postprocessors:
The "postprocessors" attribute is a list of actions to perform once the job has completed.
This includes how the output of the subjobs may be merged, user defined checks which may fail
the job, and an email notification.
Datasets: PENDING
Datasets are highly application and virtual organisation specific.
"""
_schema = Schema(
Version(1, 6),
{
"inputsandbox": FileItem(
defvalue=[],
sequence=1,
doc="list of File objects shipped to the worker node ",
),
"outputsandbox": SimpleItem(
defvalue=[],
typelist=[str],
sequence=1,
copyable=False,
doc="list of filenames or patterns shipped from the worker node",
),
"info": ComponentItem("jobinfos", defvalue=None, doc="JobInfo "),
"comment": SimpleItem(
"", protected=0, changable_at_resubmit=1, doc="comment of the job"
),
"time": ComponentItem(
"jobtime",
defvalue=JobTime(),
protected=1,
comparable=0,
doc="provides timestamps for status transitions",
),
"application": ComponentItem(
"applications",
defvalue=Executable(),
doc="specification of the application to be executed",
),
"backend": ComponentItem(
"backends",
defvalue=Localhost(),
doc="specification of the resources to be used (e.g. batch system)",
),
"inputfiles": GangaFileItem(
defvalue=[],
sequence=1,
doc="list of file objects that will act as input files for a job",
),
"outputfiles": GangaFileItem(
defvalue=[],
sequence=1,
doc="list of file objects decorating what have to be done with the output files after job is completed",
),
"non_copyable_outputfiles": GangaFileItem(
defvalue=[],
hidden=1,
sequence=1,
doc="list of file objects that are not to be copied accessed via proxy through outputfiles",
copyable=0,
),
"id": SimpleItem(
"",
protected=1,
comparable=0,
doc="unique Ganga job identifier generated automatically",
),
"status": SimpleItem(
"new",
protected=1,
checkset="_checkset_status",
doc='current state of the job, one of "new", "submitted", "running", "completed", '
'"completed_frozen", "failed_frozen", "killed", "unknown", "incomplete"',
copyable=False,
),
"name": SimpleItem(
"",
doc="optional label which may be any combination of ASCII characters",
typelist=[str],
),
"inputdir": SimpleItem(
getter="getStringInputDir",
defvalue=None,
transient=1,
protected=1,
comparable=0,
load_default=0,
optional=1,
copyable=0,
typelist=[str],
doc="location of input directory (file workspace)",
),
"outputdir": SimpleItem(
getter="getStringOutputDir",
defvalue=None,
transient=1,
protected=1,
comparable=0,
load_default=0,
optional=1,
copyable=0,
typelist=[str],
doc="location of output directory (file workspace)",
),
"inputdata": ComponentItem(
"datasets",
defvalue=None,
load_default=0,
optional=1,
doc="dataset definition "
"(typically this is specific either to an application, a site or the virtual organization",
),
"outputdata": ComponentItem(
"datasets",
defvalue=None,
load_default=0,
optional=1,
copyable=False,
doc="dataset definition "
"(typically this is specific either to an application, a site or the virtual organization",
),
"splitter": ComponentItem(
"splitters",
defvalue=None,
load_default=0,
optional=1,
doc="optional splitter",
),
"subjobs": ComponentItem(
"jobs",
defvalue=GangaList(),
sequence=1,
protected=1,
load_default=0,
copyable=0,
comparable=0,
optional=1,
proxy_get="_subjobs_proxy",
doc="list of subjobs (if splitting)",
summary_print="_subjobs_summary_print",
),
"master": ComponentItem(
"jobs",
getter="_getMasterJob",
transient=1,
protected=1,
load_default=0,
defvalue=None,
optional=1,
copyable=0,
comparable=0,
doc="master job",
visitable=0,
),
"postprocessors": ComponentItem(
"postprocessor",
defvalue=MultiPostProcessor(),
doc="list of postprocessors to run after job has finished",
),
"virtualization": ComponentItem(
"virtualization",
defvalue=None,
load_default=0,
optional=1,
doc="optional virtualization to be used",
),
"merger": ComponentItem(
"mergers",
defvalue=None,
hidden=1,
copyable=0,
load_default=0,
optional=1,
doc="optional output merger",
),
"do_auto_resubmit": SimpleItem(
defvalue=False, doc="Automatically resubmit failed subjobs"
),
"metadata": ComponentItem(
"metadata",
defvalue=MetadataDict(),
doc="the metadata",
protected=1,
copyable=0,
),
"fqid": SimpleItem(
getter="getStringFQID",
transient=1,
protected=1,
load_default=0,
defvalue=None,
optional=1,
copyable=0,
comparable=0,
typelist=[str],
doc="fully qualified job identifier",
visitable=0,
),
"been_queued": SimpleItem(
transient=1,
hidden=1,
defvalue=False,
optional=0,
copyable=0,
comparable=0,
typelist=[bool],
doc="flag to show job has been queued for postprocessing",
visitable=0,
),
"parallel_submit": SimpleItem(
transient=1,
defvalue=True,
doc="Enable Submission of subjobs in parallel",
),
},
)
_category = "jobs"
_name = "Job"
_exportmethods = [
"prepare",
"unprepare",
"submit",
"remove",
"kill",
"freeze",
"unfreeze",
"resubmit",
"peek",
"force_status",
"runPostProcessors",
"returnSubjobStatuses",
"resplit",
]
default_registry = "jobs"
_additional_slots = [
"_storedRTHandler",
"_storedJobSubConfig",
"_storedAppSubConfig",
"_storedJobMasterConfig",
"_storedAppMasterConfig",
"_stored_subjobs_proxy",
]
# TODO: usage of **kwds may be envisaged at this level to optimize the
# overriding of values, this must be reviewed
def __init__(self, prev_job=None, **kwds):
"""
This constructs a new job object
Args:
prev_job (Job, JobTemplate):
This is assumed to be an old job or a job template which we're hoping to copy the configuration of
"""
# WE WILL ONLY EVER ACCEPT Job or JobTemplate by design
if prev_job:
try:
assert isinstance(prev_job, (Job, JobTemplate))
except AssertionError:
raise TypeMismatchError(
"Can only constuct a Job with 1 non-keyword argument which is another Job, or JobTemplate"
)
# START INIT OF SELF
# TODO add the kwds as a pass through so that they're handled in a sane/consistent way.
super(Job, self).__init__()
# Finished initializing 'special' objects which are used in getter methods and alike
self.time.newjob() # <-----------NEW: timestamp method
# logger.debug("__init__")
for i in Job._additional_slots:
if not hasattr(self, i):
setattr(self, i, None)
# FINISH INIT OF SELF
# If we're copying data from an existing Job/JobTemplate
if prev_job:
# We don't want to clone the time data of an existing job
self.copyFrom(prev_job, ["time"])
if prev_job.master is not None:
if getConfig("Output")["ForbidLegacyInput"]:
if not prev_job.inputfiles:
self.inputfiles = prev_job.master.inputfiles
else:
self.inputfiles = prev_job.inputfiles
self.inputsandbox = []
else:
if not prev_job.inputsandbox:
self.inputsandbox = prev_job.master.inputsandbox
else:
self.inputsandbox = prev_job.inputsandbox
self.inputfiles = []
if getConfig("Preparable")["unprepare_on_copy"] is True:
self.unprepare()
def __hash__(self):
return hash(self.fqid)
def __lt__(self, other):
return self.id < other.id
def __gt__(self, other):
return self.id > other.id
def _getMasterJob(self):
parent = self._getParent()
while parent is not None:
if isType(parent, Job):
break
parent = self._getParent()
return parent
def _readonly(self):
return self.status != "new"
# on the deepcopy reattach the outputfiles to call their
# _on_attribute__set__
def __deepcopy__(self, memo=None):
# Due to problems on Hammercloud due to uncopyable object lets
# explicitly stop these objects going anywhere near the __deepcopy__
c = Job()
c.time.newjob()
c.backend = copy.deepcopy(self.backend)
c.application = copy.deepcopy(self.application)
c.inputdata = copy.deepcopy(self.inputdata)
c.name = self.name
c.comment = self.comment
c.postprocessors = copy.deepcopy(self.postprocessors)
c.splitter = copy.deepcopy(self.splitter)
c.virtualization = copy.deepcopy(self.virtualization)
c.parallel_submit = self.parallel_submit
# Continue as before
c.outputfiles = []
for f in self.outputfiles:
if hasattr(f, "_on_attribute__set__"):
c.outputfiles.append(f._on_attribute__set__(self, "outputfiles"))
continue
c.outputfiles.append(copy.deepcopy(f))
if getConfig("Output")["ForbidLegacyInput"]:
# Want to move EVERYTHING into the inputfiles and leave the
# inputsandbox empty
c.inputfiles = []
if self.inputfiles != []:
for i in self.inputfiles:
c.inputfiles.append(copy.deepcopy(i))
else:
if self.master and self.master.inputfiles != []:
for i in self.master.inputfiles:
c.inputfiles.append(copy.deepcopy(i))
# Apply needed transform to move Sandbox item to the
if self.inputsandbox != []:
from GangaCore.GPIDev.Lib.File.FileUtils import safeTransformFile
for i in self.inputsandbox:
c.inputfiles.append(safeTransformFile(i))
else:
if self.master and self.master.inputsandbox != []:
from GangaCore.GPIDev.Lib.File.FileUtils import safeTransformFile
for i in self.master.inputsandbox:
c.inputfiles.append(safeTransformFile(i))
c.inputsandbox = []
else:
if self.inputsandbox != []:
c.inputsandbox = copy.deepcopy(self.inputsandbox)
elif self.master and self.master.inputsandbox != []:
c.inputsandbox = copy.deepcopy(self.master.inputsandbox)
else:
c.inputsandbox = []
if self.inputfiles != []:
c.inputfiles = copy.deepcopy(self.inputfiles)
elif self.master and self.master.inputfiles != []:
c.inputfiles = copy.deepcopy(self.inputfiles)
else:
c.inputfiles = []
if self.master is not None:
if getConfig("Output")["ForbidLegacyInput"]:
if self.inputfiles == []:
logger.debug("Copying Master inputfiles")
c.inputsandbox = []
c.inputfiles = copy.deepcopy(self.master.inputfiles)
else:
logger.debug("Keeping own inputfiles")
else:
# elif (not getConfig('Output')['ForbidLegacyInput']):
if self.inputsandbox == []:
logger.debug("Copying Master inputfiles")
c.inputsandbox = copy.deepcopy(self.master.inputsandbox)
c.inputfiles = []
else:
logger.debug("Keeping own inputsandbox")
logger.debug("Intercepted __deepcopy__")
return c
def _attribute_filter__get__(self, name):
# logger.debug( "Intercepting _attribute_filter__get__" )
# Attempt to spend too long loading un-needed objects into memory in
# order to read job status
if name == "status":
return object.__getattribute__(self, "status")
# FIXME Add some method of checking what objects are known in advance of calling the __getattribute__ method
# Pref one that doesn't involve loading the job object if not needed
special_list = []
special_list.append("outputfiles")
special_list.append("inputfiles")
special_list.append("subjobs")
if name not in special_list:
return object.__getattribute__(self, name)
if name == "outputfiles":
currentOutputFiles = object.__getattribute__(self, name)
currentUnCopyableOutputFiles = object.__getattribute__(
self, "non_copyable_outputfiles"
)
files = []
files2 = []
for f in currentOutputFiles:
if f.containsWildcards() and hasattr(f, "subfiles") and f.subfiles:
files.extend(f.subfiles)
else:
files.append(f)
for f in currentUnCopyableOutputFiles:
if f.containsWildcards() and hasattr(f, "subfiles") and f.subfiles:
files2.extend(f.subfiles)
else:
files2.append(f)
files3 = GangaList()
files3.extend(files)
files3.extend(files2)
# FIXME THIS SHOULD NOT HAVE TO BE HERE! (It does else we end up with really bad errors and this is wrong!)
files3._setParent(self)
return addProxy(files3)
# If we ask for 'inputfiles', return the expanded list of subfiles
if name == "inputfiles":
return object.__getattribute__(self, name)
if name == "subjobs":
return self._subjobs_proxy()
if name == "fqid":
return self.getFQID(".")
return object.__getattribute__(self, name)
# status may only be set directly using updateStatus() method
# only modules comming from GangaCore.GPIDev package may change it directly
def _checkset_status(self, value):
try:
id = self.getFQID(".")
except KeyError:
try:
id = self.id
except KeyError:
id = None
if hasattr(self, "status"):
oldstat = self.status
else:
oldstat = None
logger.debug('job %s "%s" setting raw status to "%s"', id, oldstat, value)
# This code appears to mimic the fact that we have a protected status within the Schema.
# This looks like it's supposed to prevent direct manipulation of the job.status property
# but this is done through stack manipulation, probably not the best way to achieve this.
# We may want to drop this code in future I'm leaving this in for historical purposes. rcurrie
# import inspect
# frame = inspect.stack()[2]
# if not frame[0].f_code.co_name == 'updateStatus' and
# if (
# frame[0].f_code.co_filename.find("/Ganga/GPIDev/") == -1
# and frame[0].f_code.co_filename.find("/Ganga/Core/") == -1
# ):
# raise AttributeError(
# "cannot modify job.status directly, use job.updateStatus() method instead..."
# )
# del frame
# TODO: Make sure that if a component is in ignore_subs it is not visited at all
@synchronised
def to_json(self):
"""Special Implementation of to_json for Job object
- A simple attribute: will not have the to_json function and thus we have to manually assign the value
- A componenet attribute: will have the to_json function and thus we can automatically generate the json dict
for that and then assign it
"""
node_info = {
"type": self._schema.name,
"version": f"{self._schema.version.major}.{self._schema.version.minor}",
"category": self._schema.category,
}
if self._schema is None:
return node_info
for name, item in self._schema.allItems():
value = getattr(self, name)
if item["visitable"]:
if hasattr(value, "to_json"):
node_info[name] = value.to_json()
else:
node_info[name] = value
return node_info
class State(object):
def __init__(self, state, transition_comment="", hook=None):
self.state = state
self.transition_comment = transition_comment
self.hook = hook
class Transitions(dict):
def __init__(self, *states):
self.states = {}
for s in states:
assert s.state not in self
self[s.state] = s
status_graph = {
"new": Transitions(
State("submitting", "j.submit()", hook="monitorSubmitting_hook"),
State("removed", "j.remove()"),
),
"submitting": Transitions(
State("new", "submission failed", hook="rollbackToNewState"),
State("submitted", hook="monitorSubmitted_hook"),
State("unknown", "forced remove OR remote jobmgr error"),
State(
"failed",
"manually forced or keep_on_failed=True",
hook="monitorFailed_hook",
),
),
"submitted": Transitions(
State("running"),
State("killed", "j.kill()", hook="monitorKilled_hook"),
State("unknown", "forced remove"),
State("failed", "j.fail(force=1)", hook="monitorFailed_hook"),
State("completing"),
State("completed", hook="postprocess_hook"),
State("submitting", "j.resubmit(force=1)"),
),
"running": Transitions(
State("completing"),
State(
"completed", "job output already in outputdir", hook="postprocess_hook"
),
State(
"failed",
"backend reported failure OR j.fail(force=1)",
hook="monitorFailed_hook",
),
State("killed", "j.kill()", hook="monitorKilled_hook"),
State("unknown", "forced remove"),
State("submitting", "j.resubmit(force=1)"),
State("submitted", "j.resubmit(force=1)"),
),
"completing": Transitions(
State("completed", hook="postprocess_hook"),
State(
"failed",
"postprocessing error OR j.fail(force=1)",
hook="postprocess_hook_failed",
),
State("unknown", "forced remove"),
State("submitting", "j.resubmit(force=1)"),
State("submitted", "j.resubmit(force=1)"),
),
"killed": Transitions(
State("removed", "j.remove()"),
State("failed", "j.fail()"),
State("submitting", "j.resubmit()"),
State("submitted", "j.resubmit()"),
State("failed_frozen", "j.freeze()"),
),
"failed": Transitions(
State("removed", "j.remove()"),
State("submitting", "j.resubmit()"),
State("completed", hook="postprocess_hook"),
State("submitted", "j.resubmit()"),
State("failed_frozen", "j.freeze()"),
),
"completed": Transitions(
State("removed", "j.remove()"),
State("failed", "j.fail()"),
State("submitting", "j.resubmit()"),
State("submitted", "j.resubmit()"),
State("completed_frozen", "j.freeze()"),
),
"completed_frozen": Transitions(State("completed", "j.unfreeze()")),
"failed_frozen": Transitions(State("failed", "j.unfreeze()")),
"incomplete": Transitions(State("removed", "j.remove()")),
"unknown": Transitions(State("removed", "forced remove")),
"template": Transitions(State("removed")),
}
transient_states = ["incomplete", "removed", "unknown"]
initial_states = ["new", "incomplete", "template"]
def updateStatus(
self,
newstatus,
transition_update=True,
update_master=True,
ignore_failures=False,
):
"""Move job to the new status. according to the state transition graph (Job.status_graph).
If transition is allowed:
- call the specific transition hook (if exists)
- call the general transition update hook (triggers the auto merger and application hooks)
- commit the job
If job cannot be commited, then revert to old status and raise JobStatusError.
If transition is not allowed then raise JobStatusError.
Transitions from to the current state are allowed by default
(so you can updateStatus('running') if job is 'running').
Such default transitions do not have hooks.
"""
# For debugging to trace Failures and such
fqid = self.getFQID(".")
initial_status = self.status
logger.debug(
'attempt to change job %s status from "%s" to "%s"',
fqid,
initial_status,
newstatus,
)
try:
state = self.status_graph[initial_status][newstatus]
except KeyError:
# allow default transitions: s->s, no hook
if newstatus == initial_status:
state = Job.State(newstatus)
else:
raise JobStatusError(
'forbidden status transition of job %s from "%s" to "%s"'
% (fqid, initial_status, newstatus)
)
try:
if state.hook:
try:
getattr(self, state.hook)()
except PostprocessStatusUpdate as x:
newstatus = x.status
if transition_update:
# we call this even if there was a hook
newstatus = self.transition_update(newstatus)
if (
(newstatus == "completed")
and (initial_status != "completed")
and (ignore_failures is not True)
):
if self.outputFilesFailures():
logger.info("Job %s outputfile Failure" % self.getFQID("."))
self.updateStatus("failed")
return
if initial_status != newstatus:
self.time.timenow(newstatus)
else:
logger.debug(
"Status changed from '%s' to '%s'. No new timestamp was written",
initial_status,
newstatus,
)
# move to the new state AFTER hooks are called
self.status = newstatus
logger.debug(
"Status changed from '%s' to '%s'" % (initial_status, self.status)
)
except Exception as x:
self.status = initial_status
log_user_exception()
raise JobStatusError(x)
final_status = self.status
if final_status != initial_status and self.master is None:
logger.info(
'job %s status changed to "%s"', self.getFQID("."), final_status
)
if update_master and self.master is not None:
self.master.updateMasterJobStatus()
def transition_update(self, new_status):
"""Propagate status transitions"""
if new_status in ["completed", "failed", "killed"]:
if len(self.postprocessors) > 0:
if self.master:
logger.debug("Running postprocessor for Job %s" % self.getFQID("."))
else:
logger.info("Running postprocessor for Job %s" % self.getFQID("."))
passed = self.postprocessors.execute(self, new_status)
if passed is not True:
new_status = "failed"
# Propagate transition updates to applications
if self.application:
self.application.transition_update(new_status)
return new_status
def getBackendOutputPostprocessDict(self):
"""Return a 'live' version of the output post processing map.
Can't be done at load/global namespace because then user modules are ignored."""
backend_output_postprocess = {}
keys = getFileConfigKeys()
for key in keys:
try:
for configEntry in getConfig("Output")[key]["backendPostprocess"]:
if configEntry not in backend_output_postprocess:
backend_output_postprocess[configEntry] = {}
backend_output_postprocess[configEntry][key] = getConfig("Output")[
key
]["backendPostprocess"][configEntry]
except ConfigError as err:
logger.debug("ConfigError: %s" % err)
pass
return backend_output_postprocess
def postprocessoutput(self, outputfiles, outputdir):
if len(outputfiles) == 0:
return
for outputfile in outputfiles:
backendClass = getName(self.backend)
outputfileClass = getName(outputfile)
# on Batch backends these files can be compressed only on the
# client
if backendClass == "LSF":
if outputfile.compressed and (
outputfile.namePattern == "stdout"
or outputfile.namePattern == "stderr"
):
for currentFile in glob.glob(
os.path.join(outputdir, outputfile.namePattern)
):
os.system("gzip %s" % currentFile)
backend_output_postprocess = self.getBackendOutputPostprocessDict()
if backendClass in backend_output_postprocess:
if outputfileClass in backend_output_postprocess[backendClass]:
if not self.subjobs:
logger.debug(
"Job %s Setting Location of %s: %s"
% (
self.getFQID("."),
getName(outputfile),
outputfile.namePattern,
)
)
try:
outputfile.setLocation()
except Exception as err:
logger.error("Error: %s" % err)
if (
backend_output_postprocess[backendClass][outputfileClass]
== "client"
):
try:
logger.debug(
"Job %s Putting File %s: %s"
% (
self.getFQID("."),
getName(outputfile),
outputfile.namePattern,
)
)
outputfile.put()
logger.debug("Cleaning up after put")
outputfile.cleanUpClient()
except Exception as err:
logger.error(
"Error Putting or cleaning up file: %s, err::%s"
% (outputfile.namePattern, err)
)
# leave it for the moment for debugging
# os.system('rm %s' % postprocessLocationsPath)
def validateOutputfilesOnSubmit(self):
for outputfile in self.outputfiles:
if isType(outputfile, MassStorageFile):
(validOutputFiles, errorMsg) = outputfile.validate()
if validOutputFiles is False:
return (validOutputFiles, errorMsg)
return True, ""
def outputFilesFailures(self):
postprocessFailure = False
# check if any output was matched - be careful about master jobs
if getConfig("Output")["FailJobIfNoOutputMatched"] and not self.subjobs:
for outputfile in self.outputfiles:
if not outputfile.hasMatchedFiles():
logger.warning(
"Job: %s OutputFile failed to match file type %s: %s"
% (
self.getFQID("."),
getName(outputfile),
outputfile.namePattern,
)
)
postprocessFailure = True
# check for failure reasons
for outputfile in self.outputfiles:
if hasattr(outputfile, "failureReason") and outputfile.failureReason != "":
logger.warning(
"Job %s OutputFile failed for file: %s"
% (self.getFQID("."), outputfile.namePattern)
)
postprocessFailure = True
else:
for subfile in outputfile.subfiles:
if (
hasattr(subfile, "failureReason")
and subfile.failureReason != ""
):
logger.warning(
"Job%s OutputFile failed due to reason: %s"
% (self.getFQID("."), outputfile.namePattern)
)
postprocessFailure = True
return postprocessFailure
def getSubJobStatuses(self):
"""
This returns a set of all of the different subjob statuses whilst respecting lazy loading
"""
if isinstance(self.subjobs, SubJobJsonList):
stats = set(self.subjobs.getAllSJStatus())