-
Notifications
You must be signed in to change notification settings - Fork 2
/
condor_watch_q.py
executable file
·1402 lines (1145 loc) · 41.2 KB
/
condor_watch_q.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/python3
# Copyright 2020 HTCondor Team, Computer Sciences Department,
# University of Wisconsin-Madison, WI.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import argparse
import collections
import getpass
import itertools
import sys
import textwrap
import enum
import datetime
import os
import time
import operator
import re
import contextlib
import shutil
import struct
import htcondor
import classad
try:
from colorama import init
init()
HAS_COLORAMA = True
except ImportError:
HAS_COLORAMA = False
IS_WINDOWS = os.name == "nt"
def parse_args():
parser = argparse.ArgumentParser(
prog="condor_watch_q",
description=textwrap.dedent(
"""
Track the status of jobs over time without repeatedly querying the condor_schedd.
If no users, cluster ids, event logs, or batch names are given,
condor_watch_q will default to tracking all of the current user's jobs.
By default, condor_watch_q will never exit on its own
(unless it encounters an error or it is not tracking any jobs).
You can tell it to exit when certain conditions are met. For example,
to exit with status 0 when all of the jobs it is tracking are done
or with status 1 when any job is held, you could run
condor_watch_q -exit all,done,0 -exit any,held,1
"""
),
formatter_class=argparse.RawDescriptionHelpFormatter,
add_help=False,
)
# GENERAL OPTIONS
parser.add_argument(
"-help",
action="help",
default=argparse.SUPPRESS,
help="Show this help message and exit.",
)
parser.add_argument(
"-debug", action="store_true", help="Turn on HTCondor debug printing."
)
# TRACKING OPTIONS
parser.add_argument(
"-users", nargs="+", metavar="USER", help="Which users to track."
)
parser.add_argument(
"-clusters", nargs="+", metavar="CLUSTER_ID", help="Which cluster IDs to track."
)
parser.add_argument(
"-files", nargs="+", metavar="FILE", help="Which event logs to track."
)
parser.add_argument(
"-batches", nargs="+", metavar="BATCH_NAME", help="Which batch names to track."
)
parser.add_argument(
"-collector",
action="store",
nargs=1,
default=None,
help="Which collector to contact to find the schedd, if needed. Defaults to the local collector.",
)
parser.add_argument(
"-schedd",
action="store",
nargs=1,
default=None,
help="Which schedd to contact for queries, if needed. Defaults to the local schedd.",
)
# BEHAVIOR OPTIONS
parser.add_argument(
"-exit",
action=ExitConditions,
metavar="GROUPER,JOB_STATUS[,EXIT_STATUS]",
help=textwrap.dedent(
"""
Specify conditions under which condor_watch_q should exit.
GROUPER is one of {{{exit_groupers}}}.
JOB_STATUS is one of {{{job_statuses}}}.
The "active" status means "in the queue",
and includes jobs in the idle, running, and held states.
``EXIT_STATUS`` may be any valid exit status integer.
To specify multiple exit conditions, pass this option multiple times.
condor_watch_q will exit when any of the conditions are satisfied.
""".format(
exit_groupers=", ".join(EXIT_GROUPERS.keys()),
job_statuses=", ".join(EXIT_JOB_STATUS_CHECK.keys()),
)
),
)
# DISPLAY OPTIONS
parser.add_argument(
"-groupby",
action="store",
default="batch",
choices=("batch", "log", "cluster"),
help=textwrap.dedent(
"""
Select what attribute to group jobs by.
Note that batch names can only be determined if the tracked jobs were
found in the queue; if they were not, a default batch name is used.
"""
),
)
parser.add_argument(
"-table",
"-no-table",
action=NegateAction,
nargs=0,
default=True,
help="Enable/disable the table. Enabled by default.",
)
parser.add_argument(
"-progress",
"-no-progress",
action=NegateAction,
nargs=0,
default=True,
help="Enable/disable the progress bar. Enabled by default.",
)
parser.add_argument(
"-row-progress",
"-no-row-progress",
action=NegateAction,
nargs=0,
default=True,
help="Enable/disable the progress bar for each row. Enabled by default.",
)
parser.add_argument(
"-summary",
"-no-summary",
action=NegateAction,
nargs=0,
default=True,
help="Enable/disable the summary line. Enabled by default.",
)
parser.add_argument(
"-summary-type",
action="store",
choices=("totals", "percentages"),
default="totals",
help="Choose what to display on the summary line. By default, show totals.",
)
parser.add_argument(
"-updated-at",
"-no-updated-at",
action=NegateAction,
nargs=0,
default=True,
help='Enable/disable the "updated at" line. Enabled by default.',
)
parser.add_argument(
"-abbreviate",
"-no-abbreviate",
action=NegateAction,
nargs=0,
default=True,
help="Enable/disable abbreviating path components to the shortest somewhat-unique prefix. Disabled by default.",
)
parser.add_argument(
"-color",
"-no-color",
action=NegateAction,
nargs=0,
default=sys.stdout.isatty() and (not IS_WINDOWS or HAS_COLORAMA),
help="Enable/disable colored output. Enabled by default if connected to a tty. Disabled on Windows if colorama is not available.",
)
parser.add_argument(
"-refresh",
"-no-refresh",
action=NegateAction,
nargs=0,
default=sys.stdout.isatty(),
help="Enable/disable refreshing output (instead of appending). Enabled by default if connected to a tty.",
)
args, unknown = parser.parse_known_args()
if len(unknown) != 0:
check_unknown_args_for_known_errors(parser, unknown)
# because we're in this branch, this will fail, printing out the
# original errors argparse would have printed for the unknown args
# if we didn't catch them ourselves
args = parser.parse_args()
args.groupby = {
"log": "event_log_path",
"cluster": "cluster_id",
"batch": "batch_name",
}[args.groupby]
return args
def check_unknown_args_for_known_errors(parser, unknown_args):
"""
This function tries to capture known errors in the arguments that
argparse fails to parse and emit our own error messages.
Individual args are passed to _check_unknown_arg for processing.
Common errors are trying to use condor_q-like arguments.
"""
unknown_args = iter(unknown_args)
for arg in unknown_args:
error_message = _check_unknown_arg(arg, unknown_args)
if error_message is None:
continue
parser.print_usage()
print(
"{}: error: argument {}: {}".format(parser.prog, arg, error_message),
file=sys.stderr,
)
sys.exit(1)
def _check_unknown_arg(arg, unknown_args):
if arg.isdigit():
cluster_ids = [arg]
for next_arg in unknown_args:
if next_arg.startswith("-"):
break
if not next_arg.isdigit():
continue
cluster_ids.append(next_arg)
return "to track specific cluster IDs, try -clusters {}".format(
" ".join(cluster_ids)
)
elif "-totals" in arg:
return "to only print totals, try -no-table"
elif "-userlog" in arg:
files = []
for next_arg in unknown_args:
if next_arg.startswith("-"):
break
files.append(next_arg)
return "to track jobs from specific event logs, try -files {}".format(
" ".join(files)
)
elif "-nobatch" in arg:
return "to group by something other than batch name, try -groupby {{batch,log,cluster}}"
elif not arg.startswith("-"):
users = [arg]
for next_arg in unknown_args:
if next_arg.startswith("-"):
break
if next_arg.isdigit():
continue
users.append(next_arg)
return "to track jobs from specific users, try -users {}".format(
" ".join(users)
)
class ExitConditions(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
v = values.split(",")
if len(v) == 3:
grouper, status, exit_status = v
elif len(v) == 2:
grouper, status = v
exit_status = 0
else:
parser.error(message="invalid -exit specification")
if grouper not in EXIT_GROUPERS:
parser.error(
message='invalid GROUPER "{grouper}", must be one of {{{groupers}}}'.format(
grouper=grouper, groupers=", ".join(EXIT_GROUPERS.keys())
)
)
if status not in EXIT_JOB_STATUS_CHECK:
parser.error(
message='invalid JOB_STATUS "{status}", must be one of {{{statuses}}}'.format(
status=status, statuses=", ".join(EXIT_JOB_STATUS_CHECK.keys())
)
)
try:
exit_status = int(exit_status)
except ValueError:
parser.error(
message='exit_status must be an integer, but was "{}"'.format(
exit_status
)
)
if getattr(args, self.dest, None) is None:
setattr(args, self.dest, [])
getattr(args, self.dest).append((grouper, status, exit_status))
class NegateAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
setattr(args, self.dest, option_string.rstrip("-").startswith("no"))
def cli():
args = parse_args()
if args.debug:
warning("Debug mode enabled...")
htcondor.enable_debug()
try:
return watch_q(
users=args.users,
cluster_ids=args.clusters,
event_logs=args.files,
batches=args.batches,
collector=args.collector,
schedd=args.schedd,
exit_conditions=args.exit,
group_by=args.groupby,
table=args.table,
progress_bar=args.progress,
row_progress_bar=args.row_progress,
summary=args.summary,
summary_type=args.summary_type,
updated_at=args.updated_at,
color=args.color,
refresh=args.refresh,
abbreviate_path_components=args.abbreviate,
)
except Exception as e:
if args.debug:
raise
error(
"Unhandled error: {}. Re-run with -debug for a full stack trace.".format(e)
)
sys.exit(1)
EXIT_GROUPERS = {"all": all, "any": any, "none": lambda _: not any(_)}
EXIT_JOB_STATUS_CHECK = {
"active": lambda s: s in ACTIVE_STATES,
"done": lambda s: s is JobStatus.COMPLETED,
"idle": lambda s: s is JobStatus.IDLE,
"held": lambda s: s is JobStatus.HELD,
}
TOTAL = "TOTAL"
ACTIVE_JOBS = "JOB_IDS"
EVENT_LOG = "LOG"
CLUSTER_ID = "CLUSTER"
BATCH_NAME = "BATCH"
# attribute is the Python attribute name of the Cluster object
# key is the key in the events and job rows
GROUPBY_ATTRIBUTE_TO_AD_KEY = {
"event_log_path": EVENT_LOG,
"cluster_id": CLUSTER_ID,
"batch_name": BATCH_NAME,
}
GROUPBY_AD_KEY_TO_ATTRIBUTE = {v: k for k, v in GROUPBY_ATTRIBUTE_TO_AD_KEY.items()}
def watch_q(
users=None,
cluster_ids=None,
event_logs=None,
batches=None,
collector=None,
schedd=None,
exit_conditions=None,
group_by="batch_name",
table=True,
progress_bar=True,
row_progress_bar=True,
summary=True,
summary_type="totals",
updated_at=True,
color=True,
refresh=True,
abbreviate_path_components=False,
):
if users is None and cluster_ids is None and event_logs is None and batches is None:
users = [getpass.getuser()]
if exit_conditions is None:
exit_conditions = []
key = GROUPBY_ATTRIBUTE_TO_AD_KEY[group_by]
row_fmt = (lambda s, r: colorize(s, determine_row_color(r))) if color else None
(
cluster_ids,
constraint,
event_logs,
batch_names,
dagman_clusters_to_paths,
dagman_job_cluster_ids,
) = find_job_event_logs(
users, cluster_ids, event_logs, batches, collector=collector, schedd=schedd,
)
tracker = JobStateTracker(event_logs, batch_names)
if len(event_logs) == 0:
warning("No jobs found, exiting...")
sys.exit(0)
exit_checks = []
for grouper, checker, exit_status in exit_conditions:
disp = "{} {}".format(grouper, checker)
exit_grouper = EXIT_GROUPERS[grouper.lower()]
exit_check = EXIT_JOB_STATUS_CHECK[checker.lower()]
exit_checks.append((exit_grouper, exit_check, exit_status, disp))
try:
msg, move, clear = None, None, None
batch_name_to_nodes_total, cluster_ids_with_nodes_total = find_nodes_total(
constraint, collector, schedd
)
last_nodes_total_check_time = time.time()
while True:
with display_temporary_message("Processing new events...", enabled=refresh):
processing_messages = tracker.process_events()
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if (
not all(
cluster_id in cluster_ids_with_nodes_total
for cluster_id in dagman_job_cluster_ids
)
and time.time() - last_nodes_total_check_time > 60
):
last_nodes_total_check_time = datetime.datetime.now()
(
batch_name_to_nodes_total,
cluster_ids_with_nodes_total,
) = find_nodes_total(constraint, collector, schedd)
# "if msg is not None" skips the first iteration, when there's nothing to clear
if msg is not None and refresh:
msg = strip_ansi(msg)
prev_lines = list(msg.splitlines())
prev_len_lines = [len(line) for line in prev_lines]
move = "\033[{}A\r".format(len(prev_len_lines))
clear = "\n".join(" " * len(line) for line in prev_lines) + "\n"
groups, batch_name_to_nodes_total = group_clusters(
tracker.clusters,
key,
dagman_clusters_to_paths,
batch_names,
dagman_job_cluster_ids,
batch_name_to_nodes_total,
)
rows_by_key, totals = make_rows_from_groups(
groups, key, batch_name_to_nodes_total
)
headers, rows_by_key = strip_empty_columns(rows_by_key)
# strip out 0 values
rows_by_key = {
key: {k: v for k, v in row.items() if v != 0}
for key, row in rows_by_key.items()
}
if key == EVENT_LOG and abbreviate_path_components:
for row in rows_by_key.values():
row[key] = abbreviate_path(row[key])
rows_by_key = sorted(
rows_by_key.items(),
key=lambda key_row: min(
cluster.cluster_id for cluster in groups[key_row[0]]
),
)
msg = []
terminal_columns, terminal_rows = get_terminal_size()
if table:
msg += make_table(
row_progress_bar=row_progress_bar,
terminal_columns=terminal_columns,
headers=[key] + headers,
rows=[row for _, row in rows_by_key],
row_fmt=row_fmt,
alignment=TABLE_ALIGNMENT,
fill="-",
)
msg += [""]
if progress_bar:
msg += make_progress_bar(
totals=totals, width=terminal_columns, color=color
)
msg += [""]
if summary:
if summary_type == "totals":
msg += make_summary_with_totals(totals, width=terminal_columns)
elif summary_type == "percentages":
msg += make_summary_with_percentages(
totals, width=terminal_columns
)
msg += [""]
if updated_at:
msg += ["Updated at {}".format(now)] + [""]
if len(msg) > terminal_rows:
msg = msg[: terminal_rows - 1]
msg = (
"\n".join(msg[:-1])
+ "\nInsufficient terminal height to display full output!"
)
else:
# msg[:-1] because we need to strip the last blank section delimiter line off
msg = "\n".join(msg[:-1])
if not refresh:
msg += "\n..."
if not exit_conditions:
msg += "\nInput ^C to exit"
if clear and move:
sys.stdout.write(move + clear + move)
sys.stdout.flush()
if len(processing_messages) > 0:
print(
"\n".join("{} | {}".format(now, m) for m in processing_messages),
file=sys.stderr,
)
print(msg)
for grouper, checker, exit_status, disp in exit_checks:
if grouper((checker(s) for s in tracker.job_states)):
print(
'Exiting with code {} because of condition "{}" at {}'.format(
exit_status, disp, now
)
)
sys.exit(exit_status)
time.sleep(2)
except KeyboardInterrupt:
sys.exit(0)
terminal_size = collections.namedtuple("terminal_size", ["columns", "lines"])
def get_terminal_size():
try:
return shutil.get_terminal_size()
# TODO: remove this once we don't support Python 2 anymore
except AttributeError: # Python 2 doesn't have shutil.get_terminal_size
try:
if IS_WINDOWS:
# https://stackoverflow.com/questions/566746/how-to-get-linux-console-window-width-in-python
from ctypes import windll, create_string_buffer
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if res:
(_, _, _, _, _, left, top, right, bottom, _, _,) = struct.unpack(
"hhhhHhhhhhh", csbi.raw
)
return terminal_size(right - left + 1, bottom - top + 1)
else:
raise OSError("Failed to get Windows terminal size")
else:
rows, cols = os.popen("stty size", "r").read().split()
return terminal_size(int(cols), int(rows))
except Exception:
return terminal_size(80, 24)
@contextlib.contextmanager
def display_temporary_message(msg, enabled=True):
"""Display a single-line message until the context ends."""
if enabled:
print(msg, end="")
sys.stdout.flush()
yield
print("\r{}\r".format(" " * len(msg)), end="")
sys.stdout.flush()
else:
yield
PROJECTION = [
"ClusterId",
"Owner",
"UserLog",
"DAGManNodesLog",
"JobBatchName",
"Iwd",
"DAG_NodesTotal",
"OtherJobRemoveRequirements",
]
def find_job_event_logs(
users=None, cluster_ids=None, files=None, batches=None, collector=None, schedd=None,
):
"""
Discover job event logs to read events from based on various methods.
Parameters
----------
users
Find job event logs for these user's active jobs.
cluster_ids
Find job event logs for these clusters.
files
Find these job event logs (basically, these just get passed straight through).
batches
Find job event logs for these batch names.
collector
Query this collector to find the schedd.
Defaults to the local collector.
schedd
Query this schedd for users, cluster_ids, and batches.
Defaults to the local schedd.
"""
if users is None:
users = []
if cluster_ids is None:
cluster_ids = []
if files is None:
files = []
if batches is None:
batches = []
constraint = " || ".join(
itertools.chain(
("Owner == {}".format(classad.quote(u)) for u in users),
("ClusterId == {}".format(cid) for cid in cluster_ids),
("JobBatchName == {}".format(b) for b in batches),
)
)
clusters = set()
event_logs = set()
batch_names = {}
already_warned_missing_log = set()
dagman_job_cluster_id_to_log_path = {}
dagman_job_cluster_ids = set()
for file in files:
event_logs.add(os.path.abspath(file))
for ad in get_ads(constraint, collector, schedd):
cluster_id = ad["ClusterId"]
clusters.add(cluster_id)
batch_names[cluster_id] = ad.get("JobBatchName")
if "DAGManNodesLog" in ad:
log_path = dagman_job_cluster_id_to_log_path[cluster_id] = ad[
"DAGManNodesLog"
]
elif "UserLog" in ad:
log_path = ad["UserLog"]
else:
if cluster_id not in already_warned_missing_log:
warning(
"Cluster {} does not have a job event log file (set log=<path> in the submit description)".format(
cluster_id
)
)
already_warned_missing_log.add(cluster_id)
continue
if not os.path.isabs(log_path):
log_path = os.path.abspath(os.path.join(ad["Iwd"], log_path))
event_logs.add(log_path)
# this job is the actual DAGMan controller job
if "OtherJobRemoveRequirements" in ad:
dagman_job_cluster_ids.add(cluster_id)
return (
clusters,
constraint,
event_logs,
batch_names,
dagman_job_cluster_id_to_log_path,
dagman_job_cluster_ids,
)
def find_nodes_total(constraint, collector, schedd):
batch_name_to_nodes_total = {}
cluster_ids_with_nodes_total = set()
for ad in get_ads(constraint, collector, schedd):
try:
job_batch_name = ad["JobBatchName"]
cluster_id = ad["ClusterId"]
except KeyError:
continue
if "DAG_NodesTotal" in ad and ad["DAG_NodesTotal"]:
batch_name_to_nodes_total[job_batch_name] = ad["DAG_NodesTotal"]
cluster_ids_with_nodes_total.add(cluster_id)
return batch_name_to_nodes_total, cluster_ids_with_nodes_total
def get_ads(constraint, collector, schedd):
if constraint == "":
return []
try:
return get_schedd(collector=collector, schedd=schedd).query(
constraint, PROJECTION
)
except Exception as e:
warning("Was not able to query to discover job event logs due to: {}".format(e))
return []
def get_schedd(collector=None, schedd=None):
if collector is None and schedd is None:
schedd = htcondor.Schedd()
else:
coll = htcondor.Collector(collector)
schedd_ad = coll.locate(htcondor.DaemonTypes.Schedd, schedd)
schedd = htcondor.Schedd(schedd_ad)
return schedd
class Cluster:
"""Holds the job state for a singe cluster."""
def __init__(self, cluster_id, event_log_path, batch_name):
self.cluster_id = cluster_id
self.event_log_path = event_log_path
self._batch_name = batch_name
self.job_to_state = {}
@property
def batch_name(self):
return self._batch_name or "ID: {}".format(self.cluster_id)
def __setitem__(self, key, value):
self.job_to_state[key] = value
def __getitem__(self, item):
return self.job_to_state[item]
def items(self):
return self.job_to_state.items()
def __iter__(self):
return iter(self.items())
class JobStateTracker:
"""
Tracks the job state from many event logs,
maintaining a mapping of cluster_id to Cluster
(available as the state attribute).
"""
def __init__(self, event_log_paths, batch_names):
event_readers = {}
for event_log_path in event_log_paths:
try:
reader = htcondor.JobEventLog(event_log_path).events(0)
event_readers[event_log_path] = reader
except (OSError, IOError) as e:
warning(
"Could not open event log at {} for reading, so it will be ignored. Reason: {}".format(
event_log_path, e
)
)
self.event_readers = event_readers
self.state = collections.defaultdict(lambda: collections.defaultdict(dict))
self.batch_names = batch_names
self.cluster_id_to_cluster = {}
def process_events(self):
"""
Process all currently-available events in all event logs.
"""
messages = []
for event_log_path, events in self.event_readers.items():
while True:
try:
event = next(events)
except StopIteration:
break
except Exception as e:
messages.append(
fmt_error(
"Failed to parse event from {}. Reason: {}".format(
event_log_path, e
)
)
)
continue
new_status = JOB_EVENT_STATUS_TRANSITIONS.get(event.type, None)
if new_status is None:
continue
cluster = self.cluster_id_to_cluster.setdefault(
event.cluster,
Cluster(
cluster_id=event.cluster,
event_log_path=event_log_path,
batch_name=self.batch_names.get(event.cluster),
),
)
cluster[event.proc] = new_status
return messages
@property
def clusters(self):
return self.cluster_id_to_cluster.values()
@property
def job_states(self):
for cluster in self.clusters:
for job, state in cluster:
yield state
def group_clusters(
clusters,
key,
dagman_job_cluster_id_to_log_path,
batch_names,
dagman_job_cluster_ids,
dag_nodes_total,
):
groups = collections.defaultdict(list)
getter = operator.attrgetter(GROUPBY_AD_KEY_TO_ATTRIBUTE[key])
group_nodes_total = {}
dag_batch_names_by_nodes_log = {
nodes_log_path: batch_names[cluster]
for cluster, nodes_log_path in dagman_job_cluster_id_to_log_path.items()
}
for cluster in clusters:
# find cluster according to cluster path
dag_batch_name = dag_batch_names_by_nodes_log.get(cluster.event_log_path)
if key == BATCH_NAME and dag_batch_name is not None:
groups[dag_batch_name].append(cluster)
group_nodes_total[dag_batch_name] = dag_nodes_total.get(dag_batch_name)
else:
if cluster.cluster_id not in dagman_job_cluster_ids:
groups[getter(cluster)].append(cluster)
if not dag_nodes_total:
group_nodes_total = dag_nodes_total
return groups, group_nodes_total
def make_rows_from_groups(groups, key, cluster_id_to_nodes_total):
totals = collections.defaultdict(int)
rows = {}
for attribute_value, clusters in groups.items():
row_data = row_data_from_job_state(
clusters, cluster_id_to_nodes_total.get(attribute_value)
)
totals[TOTAL] += row_data[TOTAL]
for status in JobStatus:
totals[status] += row_data[status]
if key == EVENT_LOG:
row_data[key] = nice_path(attribute_value)
else:
row_data[key] = attribute_value
rows[attribute_value] = row_data
return rows, totals
class Color(str, enum.Enum):
BLACK = "\033[30m"
RED = "\033[31m"
BRIGHT_RED = "\033[31;1m"
GREEN = "\033[32m"
BRIGHT_GREEN = "\033[32;1m"
YELLOW = "\033[33m"
BRIGHT_YELLOW = "\033[33;1m"
BLUE = "\033[34m"
BRIGHT_BLUE = "\033[34;1m"
MAGENTA = "\033[35m"
BRIGHT_MAGENTA = "\033[35;1m"
CYAN = "\033[36m"
BRIGHT_CYAN = "\033[36;1m"
WHITE = "\033[37m"
BRIGHT_WHITE = "\033[37;1m"
RESET = "\033[0m"
def colorize(string, color):
return color + string + Color.RESET
def determine_row_color(row):
if row.get(JobStatus.HELD, 0) > 0:
return Color.RED
elif row.get(JobStatus.COMPLETED) == row.get("TOTAL"):
return Color.GREEN
elif row.get(JobStatus.RUNNING, 0) > 0:
return Color.CYAN
elif row.get(JobStatus.IDLE, 0) > 0:
return Color.YELLOW
else:
return Color.BRIGHT_WHITE
def strip_empty_columns(rows_by_key):
dont_include = set()