-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathjob_handling.py
2839 lines (2433 loc) · 91.5 KB
/
job_handling.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
# coding: utf-8
""" Functions to handle jobs"""
import copy
import os
import random
import re
from typing import List
from procset import ProcSet
from sqlalchemy import distinct, func, insert, text
from sqlalchemy.orm import aliased
from sqlalchemy.orm.session import make_transient
from sqlalchemy.sql import case
from sqlalchemy.sql.expression import select
import oar.lib.tools as tools
from oar.kao.helpers import extract_find_assign_args
from oar.lib.event import add_new_event, add_new_event_with_host, is_an_event_exists
# from oar.lib.utils import render_query
from oar.lib.globals import get_logger, init_oar
from oar.lib.models import (
AssignedResource,
Challenge,
FragJob,
GanttJobsPrediction,
GanttJobsResource,
Job,
JobDependencie,
JobResourceDescription,
JobResourceGroup,
JobStateLog,
JobType,
MoldableJobDescription,
Resource,
WalltimeChange,
)
from oar.lib.plugins import find_plugin_function
from oar.lib.resource_handling import (
get_current_resources_with_suspended_job,
update_current_scheduler_priority,
)
from oar.lib.tools import (
TimeoutExpired,
format_ssh_pub_key,
get_private_ssh_key_file_name,
limited_dict2hash_perl,
)
logger = get_logger("oar.lib.job_handling")
""" Use
j1 = Job(1,"Waiting", 0, 0, "yop", "", "",{}, [], 0,
[
(1, 60,
[ ( [("node", 2)], [(1,32)] ) ]
)
]
)
Attributes:
mld_res_rqts: Resources requets by moldable instance
[ # first moldable instance
(1, 60, # moldable id, walltime
# list of requests composed of
[ ( [("node", 2), ("resource_id", 4)], [(1,32)] ) ]
) # list of hierarchy request and filtered
] # resources (Properties)
"""
NO_PLACEHOLDER = 0
PLACEHOLDER = 1
ALLOW = 2
class JobPseudo(object):
"""Define a simple job class without database counter part"""
types = {}
deps = []
key_cache = {}
ts = False
ph = 0
assign = False
assign_args = ()
assign_kwargs = {}
find = False
find_args = ()
find_kwargs = {}
queue_name = "default"
user = ""
project = ""
no_quotas = False
def __init__(self, **kwargs):
self.mld_res_rqts = []
for key, value in kwargs.items():
setattr(self, key, value)
def simple_req(self, resources_req, walltime, resources_constraint):
"""Allow declaration of simple resources request.
Examples:
- j.simple_req(('node', 2), 60, [(1, 32)])
- j.simple_req([('node', 2), ('core', 4)], 600, [(1, 64)])
"""
if type(resources_req) == tuple:
res_req = [resources_req]
else:
res_req = resources_req
self.mld_res_rqts = [(1, walltime, [(res_req, ProcSet(*resources_constraint))])]
def get_waiting_jobs(session, queues, reservation="None"):
# TODO fairsharing_nb_job_limit
waiting_jobs = {}
waiting_jids = []
nb_waiting_jobs = 0
query = session.query(Job).filter(Job.state == "Waiting")
if isinstance(queues, str):
query = query.filter(Job.queue_name == queues)
else:
query = query.filter(Job.queue_name.in_(tuple(queues)))
query = query.filter(Job.reservation == reservation).order_by(Job.id)
for j in query.all():
jid = int(j.id)
waiting_jobs[jid] = j
waiting_jids.append(jid)
nb_waiting_jobs += 1
return (waiting_jobs, waiting_jids, nb_waiting_jobs)
def get_jobs_types(session, jids, jobs):
jobs_types = {}
for j_type in session.query(JobType).filter(JobType.job_id.in_(tuple(jids))):
jid = j_type.job_id
job = jobs[jid]
t_v = j_type.type.split("=")
t = t_v[0]
if t == "timesharing":
job.ts = True
job.ts_user, job.ts_name = t_v[1].split(",")
elif t == "placeholder":
job.ph = PLACEHOLDER
job.ph_name = t_v[1]
elif t == "allow":
job.ph = ALLOW
job.ph_name = t_v[1]
elif t == "assign": # pragma: no cover
# Skip coverage for the two next elif because it should be used with plugins
job.assign = True
raw_args = "=".join(t_v[1:])
funcname, job.assign_args, job.assign_kwargs = extract_find_assign_args(
raw_args
)
job.assign_func = find_plugin_function("oar.assign_func", funcname)
elif t == "find": # pragma: no cover
job.find = True
raw_args = "=".join(t_v[1:])
funcname, job.find_args, job.find_kwargs = extract_find_assign_args(
raw_args
)
job.find_func = find_plugin_function("oar.find_func", funcname)
elif t == "no_quotas":
job.no_quotas = True
else:
if len(t_v) == 2:
v = t_v[1]
else:
v = ""
if jid not in jobs_types:
jobs_types[jid] = dict()
(jobs_types[jid])[t] = v
for job in jobs.values():
if job.id in jobs_types:
job.types = jobs_types[job.id]
else:
job.types = {}
def set_jobs_cache_keys(session, jobs):
"""
Set keys for job use by slot_set cache to speed up the search of suitable
slots.
Jobs with timesharing, placeholder or dependencies requirements are not
suitable for this cache feature. Jobs in container might leverage of cache
because container is link to a particular slot_set.
For jobs with dependencies, they do not update the cache entries.
"""
for job_id, job in jobs.items():
if (not job.ts) and (job.ph == NO_PLACEHOLDER):
for res_rqt in job.mld_res_rqts:
(moldable_id, walltime, hy_res_rqts) = res_rqt
job.key_cache[int(moldable_id)] = str(walltime) + str(hy_res_rqts)
def get_data_jobs(
session, jobs, jids, resource_set, job_security_time, besteffort_duration=0
):
"""
oarsub -q test \
-l "nodes=1+{network_address='node3'}/nodes=1/resource_id=1" \
sleep
job_id: 12 [(16L,
7200,
[
(
[(u'network_address', 1)],
[(0, 7)]
),
(
[(u'network_address', 1), (u'resource_id', 1)],
[(4, 7)]
)
])]
"""
result = (
session.query(
Job.id,
Job.properties,
MoldableJobDescription.id,
MoldableJobDescription.walltime,
JobResourceGroup.id,
JobResourceGroup.property,
JobResourceDescription.group_id,
JobResourceDescription.resource_type,
JobResourceDescription.value,
)
.filter(MoldableJobDescription.index == "CURRENT")
.filter(JobResourceGroup.index == "CURRENT")
.filter(JobResourceDescription.index == "CURRENT")
.filter(Job.id.in_(tuple(jids)))
.filter(Job.id == MoldableJobDescription.job_id)
.filter(JobResourceGroup.moldable_id == MoldableJobDescription.id)
.filter(JobResourceDescription.group_id == JobResourceGroup.id)
.order_by(
MoldableJobDescription.id, JobResourceGroup.id, JobResourceDescription.order
)
.all()
)
# .join(MoldableJobDescription)\
# .join(JobResourceGroup)\
# .join(JobResourceDescription)\
cache_constraints = {}
first_job = True
prev_j_id = 0
prev_mld_id = 0
prev_jrg_id = 0
prev_res_jrg_id = 0
mld_res_rqts = []
jrg = []
jr_descriptions = []
res_constraints = []
prev_mld_id_walltime = 0
job = None # Global
for x in result:
# remove res_order
(
j_id,
j_properties,
moldable_id,
mld_id_walltime,
jrg_id,
jrg_grp_property,
res_jrg_id,
res_type,
res_value,
) = x
#
# new job
#
if j_id != prev_j_id:
if first_job:
first_job = False
else:
jrg.append((jr_descriptions, res_constraints))
mld_res_rqts.append((prev_mld_id, prev_mld_id_walltime, jrg))
job.mld_res_rqts = mld_res_rqts
mld_res_rqts = []
jrg = []
jr_descriptions = []
job.key_cache = {}
job.deps = []
job.ts = False
job.ph = NO_PLACEHOLDER
job.assign = False
job.find = False
job.no_quotas = False
prev_mld_id = moldable_id
prev_j_id = j_id
job = jobs[j_id]
if besteffort_duration:
prev_mld_id_walltime = besteffort_duration
else:
prev_mld_id_walltime = mld_id_walltime + job_security_time
else:
#
# new moldable_id
#
if moldable_id != prev_mld_id:
if jrg != []:
mld_res_rqts.append((prev_mld_id, prev_mld_id_walltime, jrg))
prev_mld_id = moldable_id
jrg = []
jr_descriptions = []
if besteffort_duration:
prev_mld_id_walltime = besteffort_duration
else:
prev_mld_id_walltime = mld_id_walltime + job_security_time
#
# new set job descriptions
#
if res_jrg_id != prev_res_jrg_id:
prev_res_jrg_id = res_jrg_id
jr_descriptions = [(res_type, res_value)]
#
# determine resource constraints
#
if j_properties == "" and (
jrg_grp_property == "" or jrg_grp_property == "type = 'default'"
):
res_constraints = copy.copy(resource_set.default_itvs)
else:
and_sql = ""
if j_properties and jrg_grp_property:
and_sql = " AND "
if j_properties is None:
j_properties = ""
if jrg_grp_property is None:
jrg_grp_property = ""
sql_constraints = j_properties + and_sql + jrg_grp_property
if sql_constraints in cache_constraints:
res_constraints = cache_constraints[sql_constraints]
else:
request_constraints = (
session.query(Resource.id).filter(text(sql_constraints)).all()
)
roids = [
resource_set.rid_i2o[int(y[0])] for y in request_constraints
]
res_constraints = ProcSet(*roids)
cache_constraints[sql_constraints] = res_constraints
else:
# add next res_type , res_value
jr_descriptions.append((res_type, res_value))
#
# new job resources groupe_id
#
if jrg_id != prev_jrg_id:
prev_jrg_id = jrg_id
if jr_descriptions != []:
jrg.append((jr_descriptions, res_constraints))
# complete the last job
mld_res_rqts.append((prev_mld_id, prev_mld_id_walltime, jrg))
job.mld_res_rqts = mld_res_rqts
job.key_cache = {}
job.deps = []
job.ts = False
job.ph = NO_PLACEHOLDER
job.assign = False
job.find = False
job.no_quotas = False
get_jobs_types(session, jids, jobs)
get_current_jobs_dependencies(session, jobs)
set_jobs_cache_keys(session, jobs)
def get_job_suspended_sum_duration(session, jid, now):
suspended_duration = 0
for j_state_log in (
session.query(JobStateLog)
.filter(JobStateLog.job_id == jid)
.filter(
(JobStateLog.job_state == "Suspended")
| (JobStateLog.job_state == "Resuming")
)
):
date_stop = j_state_log.date_stop
date_start = j_state_log.date_start
if date_stop == 0:
res_time = now - date_start
else:
res_time = date_stop - date_start
if res_time > 0:
suspended_duration += res_time
return suspended_duration
# TODO available_suspended_res_itvs, now
def extract_scheduled_jobs(session, result, resource_set, job_security_time, now):
jids = []
jobs_lst = []
jobs = {}
prev_jid = 0
roids = []
rid2jid = {}
job = None # global job
# (job, a, b, c) = req[0]
if result:
for x in result:
j, moldable_id, start_time, walltime, r_id = x
if j.id != prev_jid:
if prev_jid != 0:
job.res_set = ProcSet(*roids)
jobs_lst.append(job)
jids.append(job.id)
jobs[job.id] = job
roids = []
prev_jid = j.id
job = j
job.start_time = start_time
job.walltime = walltime + job_security_time
job.moldable_id = moldable_id
job.ts = False
job.ph = NO_PLACEHOLDER
job.assign = False
job.find = False
job.no_quotas = False
if job.suspended == "YES":
job.walltime += get_job_suspended_sum_duration(session, job.id, now)
roid = resource_set.rid_i2o[r_id]
roids.append(roid)
rid2jid[roid] = j.id
job.res_set = ProcSet(*roids)
if job.state == "Suspended":
job.res_set = job.res_set - resource_set.suspendable_roid_itvs
jobs_lst.append(job)
jids.append(job.id)
jobs[job.id] = job
get_jobs_types(session, jids, jobs)
return (jobs, jobs_lst, jids, rid2jid)
# TODO available_suspended_res_itvs, now
def get_scheduled_jobs(session, resource_set, job_security_time, now):
result = (
session.query(
Job,
GanttJobsPrediction.moldable_id,
GanttJobsPrediction.start_time,
MoldableJobDescription.walltime,
GanttJobsResource.resource_id,
)
.filter(MoldableJobDescription.index == "CURRENT")
.filter(GanttJobsResource.moldable_id == GanttJobsPrediction.moldable_id)
.filter(MoldableJobDescription.id == GanttJobsPrediction.moldable_id)
.filter(Job.id == MoldableJobDescription.job_id)
.order_by(Job.start_time, Job.id)
.all()
)
jobs, jobs_lst, jids, rid2jid = extract_scheduled_jobs(
session, result, resource_set, job_security_time, now
)
return jobs_lst
def get_after_sched_no_AR_jobs(
session, queue_name, resource_set, job_security_time, now
):
"""Get waiting jobs which are not AR and after scheduler round"""
result = (
session.query(
Job,
GanttJobsPrediction.moldable_id,
GanttJobsPrediction.start_time,
MoldableJobDescription.walltime,
GanttJobsResource.resource_id,
)
.filter(MoldableJobDescription.index == "CURRENT")
.filter(Job.queue_name == queue_name)
.filter(Job.state == "Waiting")
.filter(Job.reservation == "None")
.filter(GanttJobsResource.moldable_id == GanttJobsPrediction.moldable_id)
.filter(MoldableJobDescription.id == GanttJobsPrediction.moldable_id)
.filter(Job.id == MoldableJobDescription.job_id)
.order_by(Job.start_time, Job.id)
.all()
)
_, jobs_lst, _, _ = extract_scheduled_jobs(
session, result, resource_set, job_security_time, now
)
return jobs_lst
def get_waiting_scheduled_AR_jobs(
session, queue_name, resource_set, job_security_time, now
):
result = (
session.query(
Job,
GanttJobsPrediction.moldable_id,
GanttJobsPrediction.start_time,
MoldableJobDescription.walltime,
GanttJobsResource.resource_id,
)
.filter(MoldableJobDescription.index == "CURRENT")
.filter(Job.queue_name == queue_name)
.filter(Job.reservation == "Scheduled")
.filter(Job.state == "Waiting")
.filter(GanttJobsResource.moldable_id == GanttJobsPrediction.moldable_id)
.filter(MoldableJobDescription.id == GanttJobsPrediction.moldable_id)
.filter(Job.id == MoldableJobDescription.job_id)
.order_by(Job.start_time, Job.id)
.all()
)
_, jobs_lst, _, _ = extract_scheduled_jobs(
session, result, resource_set, job_security_time, now
)
return jobs_lst
# TODO MOVE TO GANTT_HANDLING ???
def get_gantt_jobs_to_launch(
session, resource_set, job_security_time, now, kill_duration_before_reservation=0
):
# get unlaunchable jobs
# NOT USED launcher will manage these cases ??? (MUST BE CONFIRMED)
#
# result = session.query(distinct(Job.id))\
# .filter(GanttJobsPrediction.start_time <= now)\
# .filter(Job.state == "Waiting")\
# .filter(Job.id == MoldableJobDescription.job_id)\
# .filter(MoldableJobDescription.id == GanttJobsPrediction.moldable_id)\
# .filter(GanttJobsResource.moldable_id == GanttJobsPrediction.moldable_id)\
# AND (resources.state IN (\'Dead\',\'Suspected\',\'Absent\')
# OR resources.next_state IN (\'Dead\',\'Suspected\',\'Absent\'))
#
# .all()
date = now + kill_duration_before_reservation
result = (
session.query(
Job,
GanttJobsPrediction.moldable_id,
GanttJobsPrediction.start_time,
MoldableJobDescription.walltime,
GanttJobsResource.resource_id,
)
.filter(GanttJobsPrediction.start_time <= date)
.filter(Job.state == "Waiting")
.filter(Job.id == MoldableJobDescription.job_id)
.filter(MoldableJobDescription.id == GanttJobsPrediction.moldable_id)
.filter(GanttJobsResource.moldable_id == GanttJobsPrediction.moldable_id)
.all()
)
jobs, jobs_lst, _, rid2jid = extract_scheduled_jobs(
session, result, resource_set, job_security_time, now
)
return (jobs, jobs_lst, rid2jid)
def job_message(session, job, nb_resources=None):
"""
Gather information about a job, and return it as a string.
Part of this information is set during the scheduling phase, and gathered in this function as side effects (walltime and res_set).
As computing the number of resources for a job can be costly, it can be done out of this function and passed as a parameter,
otherwise it is computed from job.res_set.
The karma is a job value present when the fairsharing is enabled (JOB_PRIORITY=FAIRSHARE).
"""
message_list = []
if nb_resources:
message_list.append("R={}".format(nb_resources))
elif hasattr(job, "res_set"):
message_list.append("R={}".format(len(job.res_set)))
if hasattr(job, "walltime"):
message_list.append("W={}".format(job.walltime))
if job.type == "PASSIVE":
message_list.append("J=P")
else:
message_list.append("J=I")
message_list.append("Q={}".format(job.queue_name))
logger.info("save assignements")
message = ",".join(message_list)
if hasattr(job, "karma"):
message += " " + "(Karma={})".format(job.karma)
return message
def save_assigns(session, jobs, resource_set):
# http://docs.sqlalchemy.org/en/rel_0_9/core/dml.html#sqlalchemy.sql.expression.Insert.values
if len(jobs) > 0:
logger.debug("nb job to save: " + str(len(jobs)))
mld_id_start_time_s = []
mld_id_rid_s = []
message_updates = {}
for j in jobs.values() if isinstance(jobs, dict) else jobs:
if j.start_time > -1:
logger.debug("job_id to save: " + str(j.id))
mld_id_start_time_s.append(
{"moldable_job_id": j.moldable_id, "start_time": j.start_time}
)
riods = list(j.res_set)
mld_id_rid_s.extend(
[
{
"moldable_job_id": j.moldable_id,
"resource_id": resource_set.rid_o2i[rid],
}
for rid in riods
]
)
msg = job_message(session, j, nb_resources=len(riods))
message_updates[j.id] = msg
if message_updates:
logger.info("save job messages")
session.query(Job).filter(Job.id.in_(message_updates)).update(
{
Job.message: case(
message_updates,
value=Job.id,
)
},
synchronize_session=False,
)
logger.info("save assignements")
session.execute(GanttJobsPrediction.__table__.insert(), mld_id_start_time_s)
session.execute(GanttJobsResource.__table__.insert(), mld_id_rid_s)
session.commit()
# flake8: noqa: (TODO: write an equivalent, benchmark it)
def save_assigns_bulk(session, jobs, resource_set): # pragma: no cover
if len(jobs) > 0:
logger.debug("nb job to save: " + str(len(jobs)))
mld_id_start_time_s = []
mld_id_rid_s = []
for j in jobs.values():
if j.start_time > -1:
logger.debug("job_id to save: " + str(j.id))
mld_id_start_time_s.append((j.moldable_id, j.start_time))
riods = list(j.res_set)
mld_id_rid_s.extend(
[(j.moldable_id, resource_set.rid_o2i[rid]) for rid in riods]
)
logger.info("save assignements")
with session.engine.connect() as to_conn:
cursor = to_conn.connection.cursor()
pg_bulk_insert(
cursor,
db["gantt_jobs_predictions"],
mld_id_start_time_s,
("moldable_job_id", "start_time"),
binary=True,
)
pg_bulk_insert(
cursor,
db["queues"],
mld_id_rid_s,
("moldable_job_id", "resource_id"),
binary=True,
)
def get_current_jobs_dependencies(session, jobs):
# retrieve jobs dependencies *)
# return an hashtable, key = job_id, value = list of required jobs *)
req = (
session.query(JobDependencie, Job.state, Job.exit_code)
.filter(JobDependencie.index == "CURRENT")
.filter(Job.id == JobDependencie.job_id_required)
.all()
)
for x in req:
j_dep, state, exit_code = x
if j_dep.job_id not in jobs:
# This fact have no particular impact
logger.warning(
" during get dependencies for current job %s is not in waiting state"
% str(j_dep.job_id)
)
else:
jobs[j_dep.job_id].deps.append((j_dep.job_id_required, state, exit_code))
def get_current_not_waiting_jobs(
session,
):
jobs = (
session.query(Job)
.filter(
Job.state.in_(
(
"Hold",
"toLaunch",
"toError",
"toAckReservation",
"Launching",
"Running",
"Suspended",
"Resuming",
"Finishing",
)
)
)
.all()
)
jobs_by_state = {}
for job in jobs:
if job.state not in jobs_by_state:
jobs_by_state[job.state] = []
jobs_by_state[job.state].append(job)
return jobs_by_state
def set_job_start_time_assigned_moldable_id(session, jid, start_time, moldable_id):
# session.query(Job).update({Job.start_time:
# start_time,Job.assigned_moldable_job: moldable_id}).filter(Job.id ==
# jid)
session.query(Job).filter(Job.id == jid).update(
{Job.start_time: start_time, Job.assigned_moldable_job: moldable_id},
synchronize_session=False,
)
session.commit()
def set_jobs_start_time(session, tuple_jids, start_time):
session.query(Job).filter(Job.id.in_(tuple_jids)).update(
{Job.start_time: start_time}, synchronize_session=False
)
session.commit()
# NO USED
def add_resource_jobs_pairs(session, tuple_mld_ids): # pragma: no cover
resources_mld_ids = (
session.query(GanttJobsResource)
.filter(GanttJobsResource.job_id.in_(tuple_mld_ids))
.all()
)
assigned_resources = [
{
"moldable_job_id": res_mld_id.moldable_id,
"resource_id": res_mld_id.resource_id,
}
for res_mld_id in resources_mld_ids
]
session.execute(AssignedResource.__table__.insert(), assigned_resources)
session.commit()
def add_resource_job_pairs(session, moldable_id):
resources_mld_ids = (
session.query(GanttJobsResource)
.filter(GanttJobsResource.moldable_id == moldable_id)
.all()
)
assigned_resources = [
{
"moldable_job_id": res_mld_id.moldable_id,
"resource_id": res_mld_id.resource_id,
}
for res_mld_id in resources_mld_ids
]
session.execute(AssignedResource.__table__.insert(), assigned_resources)
session.commit()
# TODO MOVE TO gantt_handling
def get_gantt_waiting_interactive_prediction_date(
session,
):
req = (
session.query(
Job.id, Job.info_type, GanttJobsPrediction.start_time, Job.message
)
.filter(Job.state == "Waiting")
.filter(Job.type == "INTERACTIVE")
.filter(Job.reservation == "None")
.filter(MoldableJobDescription.job_id == Job.id)
.filter(GanttJobsPrediction.moldable_id == MoldableJobDescription.id)
.all()
)
return req
def insert_job(session, **kwargs):
"""Insert job in database
# "{ sql1 }/prop1=1/prop2=3+{sql2}/prop3=2/prop4=1/prop5=1+...,walltime=60"
#
# res = "/switch=2/nodes=10+{lic_type = 'mathlab'}/licence=20" types="besteffort, container"
#
insert_job(
res = [
( 60, [("switch=2/nodes=20", ""), ("licence=20", "lic_type = 'mathlab'")] ) ],
types = ["besteffort", "container"],
user= "")
"""
default_values = {
"launching_directory": "",
"checkpoint_signal": 0,
"properties": "",
}
for k, v in default_values.items():
if k not in kwargs:
kwargs[k] = v
if "res" in kwargs:
res = kwargs.pop("res")
else:
res = [(60, [("resource_id=1", "")])]
if "types" in kwargs:
types = kwargs.pop("types")
else:
types = []
if "queue_name" not in kwargs:
kwargs["queue_name"] = "default"
if "user" in kwargs:
kwargs["job_user"] = kwargs.pop("user")
# FIXME: Quickfix for _test_bipbip_toLaunch to requires the moldable id of the inserted job.
# It allows to be able to get the mld id from the function without changing its return type
# that will need to be changed in every test using this function.
return_modable = False
if "return_moldable" in kwargs:
return_modable = kwargs.pop("return_moldable")
ins = Job.__table__.insert().values(**kwargs)
result = session.execute(ins)
job_id = result.inserted_primary_key[0]
mld_jid_walltimes = []
res_grps = []
for res_mld in res:
w, res_grp = res_mld
mld_jid_walltimes.append({"moldable_job_id": job_id, "moldable_walltime": w})
res_grps.append(res_grp)
result = session.execute(
MoldableJobDescription.__table__.insert(), mld_jid_walltimes
)
if len(mld_jid_walltimes) == 1:
mld_ids = [result.inserted_primary_key[0]]
created_moldable = [result.inserted_primary_key[0]]
else:
r = (
session.query(MoldableJobDescription.id)
.filter(MoldableJobDescription.job_id == job_id)
.all()
)
mld_ids = [x for e in r for x in e]
created_moldable = mld_ids
for mld_idx, res_grp in enumerate(res_grps):
# job_resource_groups
mld_id_property = []
res_hys = []
moldable_id = mld_ids[mld_idx]
for r_hy_prop in res_grp:
(res_hy, properties) = r_hy_prop
mld_id_property.append(
{"res_group_moldable_id": moldable_id, "res_group_property": properties}
)
res_hys.append(res_hy)
result = session.execute(JobResourceGroup.__table__.insert(), mld_id_property)
if len(mld_id_property) == 1:
grp_ids = [result.inserted_primary_key[0]]
else:
r = (
session.query(JobResourceGroup.id)
.filter(JobResourceGroup.moldable_id == moldable_id)
.all()
)
grp_ids = [x for e in r for x in e]
# job_resource_descriptions
for grp_idx, res_hy in enumerate(res_hys):
res_description = []
for idx, val in enumerate(res_hy.split("/")):
tv = val.split("=")
res_description.append(
{
"res_job_group_id": grp_ids[grp_idx],
"res_job_resource_type": tv[0],
"res_job_value": tv[1],
"res_job_order": idx,
}
)
session.execute(JobResourceDescription.__table__.insert(), res_description)
if types:
for typ in types:
ins = [{"job_id": job_id, "type": typ} for typ in types]
session.execute(JobType.__table__.insert(), ins)
if return_modable:
return (job_id, created_moldable)
return job_id
def resubmit_job(session, job_id):
"""Resubmit a job and give the new job_id"""
if "OARDO_USER" in os.environ:
user = os.environ["OARDO_USER"]
else:
user = "oar"
job = get_job(session, job_id)
if job is None:
return ((-5, "Unable to retrieve initial job:" + str(job_id)), 0)
if job.type != "PASSIVE":
return (
(-1, "Interactive jobs and advance reservations cannot be resubmitted."),
0,
)
if (
(job.state != "Error")
and (job.state != "Terminated")
and (job.state != "Finishing")
):
return (
(-2, "Only jobs in the Error or Terminated state can be resubmitted."),
0,
)
if (user != job.user) and (user != "oar") and (user != "root"):
return ((-3, "Resubmitted job user mismatch."), 0)