-
Notifications
You must be signed in to change notification settings - Fork 0
/
qtop.py
executable file
·2462 lines (2091 loc) · 115 KB
/
qtop.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
################################################
# qtop #
# Licensed under MIT license #
# Sotiris Fragkiskos #
# Fotis Georgatos #
################################################
import sys
here = sys.path[0]
from operator import itemgetter
from itertools import izip, izip_longest, cycle
import subprocess
import select
import os
import re
import json
import datetime
try:
from collections import namedtuple, OrderedDict, Counter
except ImportError:
from qtop_py.legacy.namedtuple import namedtuple
from qtop_py.legacy.ordereddict import OrderedDict
from qtop_py.legacy.counter import Counter
import os
from os.path import realpath
from signal import signal, SIGPIPE, SIG_DFL
import termios
import contextlib
import glob
import tempfile
import sys
import logging
from qtop_py.constants import (SYSTEMCONFDIR, QTOPCONF_YAML, QTOP_LOGFILE, USERPATH, MAX_CORE_ALLOWED,
MAX_UNIX_ACCOUNTS, KEYPRESS_TIMEOUT, FALLBACK_TERMSIZE)
from qtop_py import fileutils
from qtop_py import utils
from qtop_py.plugins import *
from math import ceil
from qtop_py.colormap import user_to_color_default, color_to_code, queue_to_color, nodestate_to_color_default
import qtop_py.yaml_parser as yaml
from qtop_py.ui.viewport import Viewport
from qtop_py.serialiser import GenericBatchSystem
from qtop_py.web import Web
from qtop_py import __version__
import time
# TODO make the following work with py files instead of qtop.colormap files
# if not options.COLORFILE:
# options.COLORFILE = os.path.expandvars('$HOME/qtop/qtop/qtop.colormap')
def compress_colored_line(s):
## TODO: black sheep
t = [item for item in re.split(r'\x1b\[0;m', s) if item != '']
sts = []
st = []
colors = []
prev_code = t[0][:-1]
colors.append(prev_code)
for idx, code_letter in enumerate(t):
code, letter = code_letter[:-1], code_letter[-1]
if prev_code == code:
st.append(letter)
else:
sts.append(st)
st = []
st.append(letter)
colors.append(code)
prev_code = code
sts.append(st)
final_t = []
for color, seq in zip(colors, sts):
final_t.append(color + "".join(seq) + '\x1b[0;m')
return "".join(final_t)
def gauge_core_vectors(core_user_map, print_char_start, print_char_stop, coreline_notthere_or_unused, non_existent_symbol,
remove_corelines):
"""
generator that loops over each core user vector and yields a boolean stating whether the core vector can be omitted via
REM_EMPTY_CORELINES or its respective switch
"""
delta = print_char_stop - print_char_start
for ind, k in enumerate(core_user_map):
core_x_vector = core_user_map['Core' + str(ind) + 'vector'][print_char_start:print_char_stop]
core_x_str = ''.join(str(x) for x in core_x_vector)
yield core_x_vector, ind, k, coreline_notthere_or_unused(non_existent_symbol, remove_corelines, delta, core_x_str)
def get_date_obj_from_str(s, now):
"""
Expects string s to be in either of the following formats:
yyyymmddTHHMMSS, e.g. 20161118T182300
HHMM, e.g. 1823 (current day is implied)
mmddTHHMM, e.g. 1118T1823 (current year is implied)
If it's in format #3, the the current year is assumed.
If it's in format #2, either the current or the previous day is assumed,
depending on whether the time provided is future or past.
Optional ":/-" separators are also accepted between pretty much anywhere.
returns a datetime object
"""
s = ''.join([x for x in s if x not in ':/-'])
if 'T' in s and len(s) == 15:
inp_datetime = datetime.datetime.strptime(s, "%Y%m%dT%H%M%S")
elif len(s) == 4:
_inp_datetime = datetime.datetime.strptime(s, "%H%M")
_inp_datetime = now.replace(hour=_inp_datetime.hour, minute=_inp_datetime.minute, second=0)
inp_datetime = _inp_datetime if now > _inp_datetime else _inp_datetime.replace(day=_inp_datetime.day-1)
elif len(s) == 9:
_inp_datetime = datetime.datetime.strptime(s, "%m%dT%H%M")
inp_datetime = _inp_datetime.replace(year=now.year, second=0)
else:
logging.critical('The datetime format provided is incorrect.\n'
'Try one of the formats: yyyymmddTHHMMSS, HHMM, mmddTHHMM.')
return inp_datetime
@contextlib.contextmanager
def raw_mode(file):
"""
Simple key listener implementation
Taken from http://stackoverflow.com/questions/11918999/key-listeners-in-python/11919074#11919074
Exits program with ^C or ^D
"""
if options.ONLYSAVETOFILE:
yield
else:
if options.WATCH:
try:
old_attrs = termios.tcgetattr(file.fileno())
except:
yield
else:
new_attrs = old_attrs[:]
new_attrs[3] = new_attrs[3] & ~(termios.ECHO | termios.ICANON)
try:
termios.tcsetattr(file.fileno(), termios.TCSADRAIN, new_attrs)
yield
finally:
termios.tcsetattr(file.fileno(), termios.TCSADRAIN, old_attrs)
else:
yield
def load_yaml_config():
"""
Loads ./QTOPCONF_YAML into a dictionary and then tries to update the dictionary
with the same-named conf file found in:
/env
$HOME/.local/qtop/
in that order.
"""
# TODO: conversion to int should be handled internally in native yaml parser
# TODO: fix_config_list should be handled internally in native yaml parser
config = yaml.parse(os.path.join(realpath(QTOPPATH), QTOPCONF_YAML))
logging.info('Default configuration dictionary loaded. Length: %s items' % len(config))
try:
config_env = yaml.parse(os.path.join(SYSTEMCONFDIR, QTOPCONF_YAML))
except IOError:
config_env = {}
logging.info('%s could not be found in %s/' % (QTOPCONF_YAML, SYSTEMCONFDIR))
else:
logging.info('Env %s found in %s/' % (QTOPCONF_YAML, SYSTEMCONFDIR))
logging.info('Env configuration dictionary loaded. Length: %s items' % len(config_env))
try:
config_user = yaml.parse(os.path.join(USERPATH, QTOPCONF_YAML))
except IOError:
config_user = {}
logging.info('User %s could not be found in %s/' % (QTOPCONF_YAML, USERPATH))
else:
logging.info('User %s found in %s/' % (QTOPCONF_YAML, USERPATH))
logging.info('User configuration dictionary loaded. Length: %s items' % len(config_user))
config.update(config_env)
config.update(config_user)
if options.CONFFILE:
try:
config_user_custom = yaml.parse(os.path.join(USERPATH, options.CONFFILE))
except IOError:
try:
config_user_custom = yaml.parse(os.path.join(CURPATH, options.CONFFILE))
except IOError:
config_user_custom = {}
logging.info('Custom User %s could not be found in %s/ or current dir' % (options.CONFFILE, CURPATH))
else:
logging.info('Custom User %s found in %s/' % (QTOPCONF_YAML, CURPATH))
logging.info('Custom User configuration dictionary loaded. Length: %s items' % len(config_user_custom))
else:
logging.info('Custom User %s found in %s/' % (QTOPCONF_YAML, USERPATH))
logging.info('Custom User configuration dictionary loaded. Length: %s items' % len(config_user_custom))
config.update(config_user_custom)
logging.info('Updated main dictionary. Length: %s items' % len(config))
config['possible_ids'] = list(config['possible_ids'])
symbol_map = dict([(chr(x), x) for x in range(33, 48) + range(58, 64) + range(91, 96) + range(123, 126)])
if config['user_color_mappings']:
user_to_color = user_to_color_default.copy()
[user_to_color.update(d) for d in config['user_color_mappings']]
else:
config['user_color_mappings'] = list()
if config['nodestate_color_mappings']:
nodestate_to_color = nodestate_to_color_default.copy()
[nodestate_to_color.update(d) for d in config['nodestate_color_mappings']]
else:
config['nodestate_color_mappings'] = list()
if config['remapping']:
pass
else:
config['remapping'] = list()
for symbol in symbol_map:
config['possible_ids'].append(symbol)
_savepath = os.path.realpath(os.path.expandvars(config['savepath']))
if not os.path.exists(_savepath):
fileutils.mkdir_p(_savepath)
logging.debug('Directory %s created.' % _savepath)
else:
logging.debug('%s files will be saved in directory %s.' % (config['scheduler'], _savepath))
config['savepath'] = _savepath
for key in ('transpose_wn_matrices',
'fill_with_user_firstletter',
'faster_xml_parsing',
'vertical_separator_every_X_columns',
'overwrite_sample_file'):
config[key] = eval(config[key]) # TODO config should not be writeable!!
config['sorting']['reverse'] = eval(config['sorting'].get('reverse', "0")) # TODO config should not be writeable!!
config['ALT_LABEL_COLORS'] = yaml.fix_config_list(config['workernodes_matrix'][0]['wn id lines']['alt_label_colors'])
config['SEPARATOR'] = config['vertical_separator'].translate(None, "'")
config['USER_CUT_MATRIX_WIDTH'] = int(config['workernodes_matrix'][0]['wn id lines']['user_cut_matrix_width'])
return config, user_to_color, nodestate_to_color
def calculate_term_size(config, FALLBACK_TERM_SIZE):
"""
Gets the dimensions of the terminal window where qtop will be displayed.
"""
fallback_term_size = config.get('term_size', FALLBACK_TERM_SIZE)
_command = subprocess.Popen('stty size', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
tty_size, error = _command.communicate()
if not error:
term_height, term_columns = [int(x) for x in tty_size.strip().split()]
logging.debug('terminal size v, h from "stty size": %s, %s' % (term_height, term_columns))
else:
logging.warn("Failed to autodetect terminal size. (Running in an IDE?in a pipe?) Trying values in %s." % QTOPCONF_YAML)
try:
term_height, term_columns = viewport.get_term_size()
if not all(term_height, term_columns):
raise ValueError
except ValueError:
try:
term_height, term_columns = yaml.fix_config_list(viewport.get_term_size())
except KeyError:
term_height, term_columns = fallback_term_size
logging.debug('(hardcoded) fallback terminal size v, h:%s, %s' % (term_height, term_columns))
else:
logging.debug('fallback terminal size v, h:%s, %s' % (term_height, term_columns))
except (KeyError, TypeError): # TypeError if None was returned i.e. no setting in QTOPCONF_YAML
term_height, term_columns = fallback_term_size
logging.debug('(hardcoded) fallback terminal size v, h:%s, %s' % (term_height, term_columns))
return int(term_height), int(term_columns)
def finalize_filepaths_schedulercommands(options, config):
"""
returns a dictionary with contents of the form
{fn : (filepath, schedulercommand)}, e.g.
{'pbsnodes_file': ('savepath/pbsnodes_a.txt', 'pbsnodes -a')}
if the -s switch (set sourcedir) has been invoked, or
{'pbsnodes_file': ('savepath/pbsnodes_a<some_pid>.txt', 'pbsnodes -a')}
if ran without the -s switch.
"""
d = dict()
fn_append = "_" + str(os.getpid()) if not options.SOURCEDIR else ""
for fn, path_command in config['schedulers'][scheduler].items():
path, command = path_command.strip().split(', ')
path = path % {"savepath": options.workdir, "pid": fn_append}
command = command % {"savepath": options.workdir}
d[fn] = (path, command)
return d
def auto_get_avail_batch_system(config):
"""
If the auto option is set in either env variable QTOP_SCHEDULER, QTOPCONF_YAML or in cmdline switch -b,
qtop tries to determine which of the known batch commands are available in the current system.
"""
# TODO pbsnodes etc should not be hardcoded!
for (system, batch_command) in config['signature_commands'].items():
NOT_FOUND = subprocess.call(['which', batch_command], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if not NOT_FOUND:
if system != 'demo':
logging.debug('Auto-detected scheduler: %s' % system)
return system
raise SchedulerNotSpecified
def execute_shell_batch_commands(batch_system_commands, filenames, _file, _savepath):
"""
scheduler-specific commands are invoked from the shell and their output is saved *atomically* to files,
as defined by the user in QTOPCONF_YAML
"""
_batch_system_command = batch_system_commands[_file].strip()
with tempfile.NamedTemporaryFile('w', dir=_savepath, delete=False) as fin:
logging.debug('Command: "%s" -- result will be saved in: %s' % (_batch_system_command, filenames[_file]))
logging.debug('\tFile state before subprocess call: %(fin)s' % {"fin": fin})
logging.debug('\tWaiting on subprocess.call...')
command = subprocess.Popen(_batch_system_command, stdout=fin, stderr=subprocess.PIPE, shell=True)
error = command.communicate()[1]
command.wait()
if error:
logging.exception('A message from your shell: %s' % error)
logging.critical('%s could not be executed. Maybe try "module load %s"?' % (_batch_system_command, scheduler))
web.stop()
sys.exit(1)
tempname = fin.name
logging.debug('File state after subprocess call: %(fin)s' % {"fin": fin})
os.rename(tempname, filenames[_file])
return filenames[_file]
def get_detail_of_name(account_jobs_table):
"""
Reads file $HOME/.local/qtop/getent_passwd.txt or whatever is put in QTOPCONF_YAML
and extracts the fullname of the users. This shall be printed in User Accounts
and Pool Mappings.
"""
extract_info = config.get('extract_info', None)
if not extract_info:
return dict()
sep = ':'
field_idx = int(extract_info.get('field_to_use', 5))
regex = extract_info.get('regex', None)
if options.GET_GECOS:
users = ' '.join([line[4] for line in account_jobs_table])
passwd_command = extract_info.get('user_details_realtime') % users
passwd_command = passwd_command.split()
else:
passwd_command = extract_info.get('user_details_cache').split()
passwd_command[-1] = os.path.expandvars(passwd_command[-1])
try:
p = subprocess.Popen(passwd_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
logging.critical('\nCommand "%s" could not be found in your system. \nEither remove -G switch or modify the command in '
'qtopconf.yaml (value of key: %s).\nExiting...' % (colorize(passwd_command[0], color_func='Red_L'),
'user_details_realtime'))
sys.exit(0)
else:
output, err = p.communicate("something here")
if 'No such file or directory' in err:
logging.warn('You have to set a proper command to get the passwd file in your %s file.' % QTOPCONF_YAML)
logging.warn('Error returned by getent: %s\nCommand issued: %s' % (err, passwd_command))
detail_of_name = dict()
for line in output.split('\n'):
try:
user, field = line.strip().split(sep)[0:field_idx:field_idx - 1]
except ValueError:
break
else:
try:
detail = eval(regex)
except (AttributeError, TypeError):
detail = field.strip()
finally:
detail_of_name[user] = detail
return detail_of_name
def get_input_filenames(INPUT_FNs_commands, config):
"""
If the user didn't specify --via the -s switch-- a dir where ready-made data files already exist,
the appropriate batch commands are executed, as indicated in QTOPCONF,
and results are saved with the respective filenames.
"""
filenames = dict()
batch_system_commands = dict()
for _file in INPUT_FNs_commands:
filenames[_file], batch_system_commands[_file] = INPUT_FNs_commands[_file]
if not options.SOURCEDIR:
_savepath = os.path.realpath(os.path.expandvars(config['savepath']))
filenames[_file] = execute_shell_batch_commands(batch_system_commands, filenames, _file, _savepath)
if not os.path.isfile(filenames[_file]):
raise fileutils.FileNotFound(filenames[_file])
return filenames
def get_key_val_from_option_string(string):
key, val = string.split('=')
return key, val
def check_python_version():
try:
assert sys.version_info[0] == 2
assert sys.version_info[1] in (6,7)
except AssertionError:
logging.critical("Only python versions 2.6.x and 2.7.x are supported. Exiting")
web.stop()
sys.exit(1)
def control_qtop(viewport, read_char, cluster, new_attrs):
"""
Basic vi-like movement is implemented for the -w switch (linux watch-like behaviour for qtop).
h, j, k, l for left, down, up, right, respectively.
Both g/G and Shift+j/k go to top/bottom of the matrices
0 and $ go to far left/right of the matrix, respectively.
r resets the screen to its initial position (if you've drifted away from the vieweable part of a matrix).
q quits qtop.
"""
pressed_char_hex = '%02x' % ord(read_char) # read_char has an initial value that resets the display ('72')
if pressed_char_hex in ['6a', '20']: # j, spacebar
logging.debug('v_start: %s' % viewport.v_start)
if viewport.scroll_down():
# TODO make variable for **s, maybe factorize whole print line
print '%s Going down...' % colorize('***', 'Green_L')
else:
print '%s Staying put' % colorize('***', 'Green_L')
elif pressed_char_hex in ['6b', '7f']: # k, Backspace
if viewport.scroll_up():
print '%s Going up...' % colorize('***', 'Green_L')
else:
print '%s Staying put' % colorize('***', 'Green_L')
elif pressed_char_hex in ['6c']: # l
print '%s Going right...' % colorize('***', 'Green_L')
viewport.scroll_right()
elif pressed_char_hex in ['24']: # $
print '%s Going far right...' % colorize('***', 'Green_L')
viewport.scroll_far_right()
logging.info('h_start: %s' % viewport.h_start)
logging.info('max_line_len: %s' % max_line_len)
logging.info('config["term_size"][1] %s' % viewport.h_term_size)
logging.info('h_stop: %s' % viewport.h_stop)
elif pressed_char_hex in ['68']: # h
print '%s Going left...' % colorize('***', 'Green_L')
viewport.scroll_left()
elif pressed_char_hex in ['30']: # 0
print '%s Going far left...' % colorize('***', 'Green_L')
viewport.scroll_far_left()
elif pressed_char_hex in ['4a', '47']: # S-j, G
logging.debug('v_start: %s' % viewport.v_start)
if viewport.scroll_bottom():
print '%s Going to the bottom...' % colorize('***', 'Green_L')
else:
print '%s Staying put' % colorize('***', 'Green_L')
elif pressed_char_hex in ['4b', '67']: # S-k, g
print '%s Going to the top...' % colorize('***', 'Green_L')
logging.debug('v_start: %s' % viewport.v_start)
viewport.scroll_top()
elif pressed_char_hex in ['52']: # R
print '%s Resetting display...' % colorize('***', 'Green_L')
viewport.reset_display()
elif pressed_char_hex in ['74']: # t
print '%s Transposing matrix...' % colorize('***', 'Green_L')
dynamic_config['transpose_wn_matrices'] = not dynamic_config.get('transpose_wn_matrices',
config['transpose_wn_matrices'])
viewport.reset_display()
elif pressed_char_hex in ['6d']: # m
new_mapping, msg = change_mapping.next()
dynamic_config['core_coloring'] = new_mapping
print '%s Changing to %s' % (colorize('***', 'Green_L'), msg)
elif pressed_char_hex in ['71']: # q
print colorize('\nExiting. Thank you for ..watching ;)\n', 'Cyan_L')
web.stop()
sys.exit(0)
elif pressed_char_hex in ['46']: # F
dynamic_config['force_names'] = not dynamic_config['force_names']
print '%s Toggling full-name/incremental nr WN labels' % colorize('***', 'Green_L')
elif pressed_char_hex in ['73']: # s
sort_map = OrderedDict()
sort_map['0'] = ("sort reset", [])
sort_map['1'] = ("sort by nodename-notnum", [])
sort_map['2'] = ("sort by nodename-notnum length", [])
sort_map['3'] = ("sort by all numbers", [])
sort_map['4'] = ("sort by first letter", [])
sort_map['5'] = ("sort by node state", [])
sort_map['6'] = ("sort by nr of cores", [])
sort_map['7'] = ("sort by core occupancy", [])
sort_map['8'] = ("sort by custom definition", [])
custom_choice = '8'
print 'Type in sort order. This can be a single number or a sequence of numbers,\n' \
'e.g. to sort first by first word, then by all numbers then by first name length, type 132, then <enter>.'
for nr, sort_method in sort_map.items():
print '(%s): %s' % (colorize(nr, color_func='Red_L'), sort_method[0])
new_attrs[3] = new_attrs[3] & ~(termios.ECHO | termios.ICANON)
termios.tcsetattr(sys.__stdin__.fileno(), termios.TCSADRAIN, old_attrs)
dynamic_config['user_sort'] = []
while True:
sort_choice = raw_input('\nChoose sorting order, or Enter to exit:-> ', )
if not sort_choice:
break
if custom_choice in sort_choice:
custom = raw_input('\nType in custom sorting (python RegEx, for examples check configuration file): ')
sort_map[custom_choice][1].append(custom)
try:
sort_order = [m for m in sort_choice]
except ValueError:
break
else:
if not set(sort_order).issubset(set(sort_map.keys())):
continue
sort_args = [sort_map[i] for i in sort_order]
dynamic_config['user_sort'] = sort_args
break
termios.tcsetattr(sys.__stdin__.fileno(), termios.TCSADRAIN, new_attrs)
viewport.reset_display()
elif pressed_char_hex in ['66']: # f
cluster.wn_filter = cluster.WNFilter(cluster.worker_nodes)
filter_map = {
1: 'exclude_node_states',
2: 'exclude_numbers',
3: 'exclude_name_patterns',
4: 'or_include_node_states',
5: 'or_include_numbers',
6: 'or_include_name_patterns',
7: 'include_node_states',
8: 'include_numbers',
9: 'include_name_patterns',
10: 'include_queues'
}
print 'Filter out nodes by:\n%(one)s state %(two)s number' \
' %(three)s name substring or RegEx pattern' % {
'one': colorize("(1)", color_func='Red_L'),
'two': colorize("(2)", color_func='Red_L'),
'three': colorize("(3)", color_func='Red_L'),
}
print 'Filter in nodes by:\n(any) %(four)s state %(five)s number %(six)s name substring or RegEx pattern\n' \
'(all) %(seven)s state %(eight)s number %(nine)s name substring or RegEx pattern %(ten)s queue' \
% {'four': colorize("(4)", color_func='Red_L'),
'five': colorize("(5)", color_func='Red_L'),
'six': colorize("(6)", color_func='Red_L'),
'seven': colorize("(7)", color_func='Red_L'),
'eight': colorize("(8)", color_func='Red_L'),
'nine': colorize("(9)", color_func='Red_L'),
'ten': colorize("(10)", color_func='Red_L'),
}
new_attrs[3] = new_attrs[3] & ~(termios.ECHO | termios.ICANON)
termios.tcsetattr(sys.__stdin__.fileno(), termios.TCSADRAIN, old_attrs)
dynamic_config['filtering'] = []
while True:
filter_choice = raw_input('\nChoose Filter command, or Enter to exit:-> ',)
if not filter_choice:
break
try:
filter_choice = int(filter_choice)
except ValueError:
break
else:
if filter_choice not in filter_map:
break
filter_args = []
while True:
user_input = raw_input('\nEnter argument, or Enter to exit:-> ')
if not user_input:
break
filter_args.append(user_input)
dynamic_config['filtering'].append({filter_map[filter_choice]: filter_args})
termios.tcsetattr(sys.__stdin__.fileno(), termios.TCSADRAIN, new_attrs)
viewport.reset_display()
elif pressed_char_hex in ['48']: # H
cluster.wn_filter = cluster.WNFilter(cluster.worker_nodes)
filter_map = {
1: 'or_include_user_id',
2: 'or_include_user_pat',
3: 'or_include_queue',
4: 'include_user_id',
5: 'include_user_pat',
6: 'include_queue',
}
print 'Highlight cores by:\n' \
'(any) %(one)s userID %(two)s user name (regex) %(three)s queue\n' \
'(all) %(four)s userID %(five)s user name (regex) %(six)s queue' \
% {'one': colorize("(1)", color_func='Red_L'),
'two': colorize("(2)", color_func='Red_L'),
'three': colorize("(3)", color_func='Red_L'),
'four': colorize("(4)", color_func='Red_L'),
'five': colorize("(5)", color_func='Red_L'),
'six': colorize("(6)", color_func='Red_L'),
}
new_attrs[3] = new_attrs[3] & ~(termios.ECHO | termios.ICANON)
termios.tcsetattr(sys.__stdin__.fileno(), termios.TCSADRAIN, old_attrs)
dynamic_config['highlight'] = []
while True:
filter_choice = raw_input('\nChoose Highlight command, or Enter to exit:-> ',)
if not filter_choice:
break
try:
filter_choice = int(filter_choice)
except ValueError:
break
else:
if filter_choice not in filter_map:
break
filter_args = []
while True:
user_input = raw_input('\nEnter argument, or Enter to exit:-> ')
if not user_input:
break
filter_args.append(user_input)
dynamic_config['highlight'].append({filter_map[filter_choice]: filter_args})
termios.tcsetattr(sys.__stdin__.fileno(), termios.TCSADRAIN, new_attrs)
viewport.reset_display()
elif pressed_char_hex in ['3f']: # ?
viewport.reset_display()
print '%s opening help...' % colorize('***', 'Green_L')
if not h_counter.next() % 2: # enter helpfile
dynamic_config['output_fp'] = help_main_switch[0]
else: # exit helpfile
del dynamic_config['output_fp']
elif pressed_char_hex in ['72']: # r
logging.debug('toggling corelines displayed')
dynamic_config['rem_empty_corelines'] = (dynamic_config.get('rem_empty_corelines', config['rem_empty_corelines']) +1) %3
if dynamic_config['rem_empty_corelines'] == 1:
print '%s Hiding not-really-there ("#") corelines' % colorize('***', 'Green_L')
elif dynamic_config['rem_empty_corelines'] == 2:
print '%s Hiding all unused ("#" and "_") corelines' % colorize('***', 'Green_L')
else:
print '%s Showing all corelines' % colorize('***', 'Green_L')
logging.debug('dynamic config corelines: %s' % dynamic_config['rem_empty_corelines'])
logging.debug('Area Displayed: (h_start, v_start) --> (h_stop, v_stop) '
'\n\t(%(h_start)s, %(v_start)s) --> (%(h_stop)s, %(v_stop)s)' %
{'v_start': viewport.v_start, 'v_stop': viewport.v_stop,
'h_start': viewport.h_start, 'h_stop': viewport.h_stop})
def fetch_scheduler_files(options, config):
INPUT_FNs_commands = finalize_filepaths_schedulercommands(options, config)
scheduler_output_filenames = get_input_filenames(INPUT_FNs_commands, config)
return scheduler_output_filenames
def decide_batch_system(cmdline_switch, env_var, config_file_batch_option, schedulers, available_batch_systems, config):
"""
Qtop first checks in cmdline switches, environmental variables and the config files, in this order,
for the scheduler type. If it's not indicated and "auto" is, it will attempt to guess the scheduler type
from the scheduler shell commands available in the linux system.
"""
avail_systems = available_batch_systems.keys() + ['auto']
if cmdline_switch and cmdline_switch.lower() not in avail_systems:
logging.critical("Selected scheduler system not supported. Available choices are %s." % ", ".join(avail_systems))
logging.critical("For help, try ./qtop.py --help")
logging.critical("Log file created in %s" % os.path.expandvars(QTOP_LOGFILE))
raise InvalidScheduler
for scheduler in (cmdline_switch, env_var, config_file_batch_option):
if scheduler is None:
continue
scheduler = scheduler.lower()
if scheduler == 'auto':
scheduler = auto_get_avail_batch_system(config)
logging.debug('Selected scheduler is %s' % scheduler)
return scheduler
elif scheduler in schedulers:
logging.info('User-selected scheduler: %s' % scheduler)
return scheduler
elif scheduler and scheduler not in schedulers: # a scheduler that does not exist is inputted
raise NoSchedulerFound
else:
raise NoSchedulerFound
def get_output_size(max_line_len, output_fp, max_height=0):
"""
Returns the char dimensions of the entirety of the qtop output file
"""
ansi_escape = re.compile(r'\x1b[^m]*m') # matches ANSI escape characters
if not max_height:
with open(output_fp, 'r') as f:
max_height = len(f.readlines())
if not max_height:
raise ValueError("There is no output from qtop *whatsoever*. Weird.")
max_line_len = max(len(ansi_escape.sub('', line.strip())) for line in open(output_fp, 'r')) \
if not max_line_len else max_line_len
logging.debug('Total nr of lines: %s' % max_height)
logging.debug('Max line length: %s' % max_line_len)
return max_height, max_line_len
def update_config_with_cmdline_vars(options, config):
config['rem_empty_corelines'] = int(config['rem_empty_corelines'])
for opt in options.OPTION:
key, val = get_key_val_from_option_string(opt)
val = eval(val) if ('True' in val or 'False' in val) else val
config[key] = val
if options.TRANSPOSE:
config['transpose_wn_matrices'] = not config['transpose_wn_matrices']
if options.REM_EMPTY_CORELINES:
config['rem_empty_corelines'] += options.REM_EMPTY_CORELINES
return config
def attempt_faster_xml_parsing(config):
if config['faster_xml_parsing']:
try:
from lxml import etree
except ImportError:
logging.warn('Module lxml is missing. Try issuing "pip install lxml". Reverting to xml module.')
from xml.etree import ElementTree as etree
def init_dirs(options, _savepath):
options.SOURCEDIR = realpath(options.SOURCEDIR) if options.SOURCEDIR else None
logging.debug("User-defined source directory: %s" % options.SOURCEDIR)
options.workdir = options.SOURCEDIR or _savepath
logging.debug('Working directory is now: %s' % options.workdir)
os.chdir(options.workdir)
return options
def wait_for_keypress_or_autorefresh(viewport, FALLBACK_TERMSIZE, KEYPRESS_TIMEOUT=1):
"""
This will make qtop wait for user input for a while,
otherwise it will auto-refresh the display
"""
_read_char = 'R' # initial value, resets view position to beginning
while sys.stdin in select.select([sys.stdin], [], [], KEYPRESS_TIMEOUT)[0]:
_read_char = sys.stdin.read(1)
if _read_char:
logging.debug('Pressed %s' % _read_char)
break
else:
state = viewport.get_term_size()
viewport.set_term_size(*calculate_term_size(config, FALLBACK_TERMSIZE))
new_state = viewport.get_term_size()
_read_char = '\n' if (state == new_state) else 'r'
logging.debug("Auto-advancing by pressing <Enter>")
return _read_char
def assign_color_to_each_qname(worker_nodes):
for worker_node in worker_nodes:
worker_node['qname'] = [q[0] for q in worker_node['qname']]
def keep_queue_initials_only_and_colorize(worker_nodes, queue_to_color):
# TODO remove monstrosity!
for worker_node in worker_nodes:
color_q_list = []
for queue in worker_node['qname']:
color_q = utils.ColorStr(queue, color=queue_to_color.get(queue, ''))
color_q_list.append(color_q)
worker_node['qname'] = color_q_list
return worker_nodes
def colorize_nodestate(worker_nodes, nodestate_to_color, ffunc):
# TODO remove monstrosity!
for worker_node in worker_nodes:
full_nodestate = worker_node['state'] # actual node state
total_color_nodestate = []
for nodestate in worker_node['state']: # split nodestate for displaying purposes
color_nodestate = utils.ColorStr(nodestate, color=nodestate_to_color.get(full_nodestate, ''))
total_color_nodestate.append(color_nodestate)
worker_node['state'] = total_color_nodestate
return worker_nodes
def discover_qtop_batch_systems():
batch_systems = set()
# Find all the classes that extend GenericBatchSystem
to_scan = [GenericBatchSystem]
while to_scan:
parent = to_scan.pop()
for child in parent.__subclasses__():
if child not in batch_systems:
batch_systems.add(child)
to_scan.append(child)
# Extract those class's mnemonics
available_batch_systems = {}
for batch_system in batch_systems:
mnemonic = batch_system.get_mnemonic()
assert mnemonic
assert mnemonic not in available_batch_systems, "Duplicate for mnemonic: '%s'" % mnemonic
available_batch_systems[mnemonic] = batch_system
return available_batch_systems
def process_options(options):
if options.COLOR == 'AUTO':
options.COLOR = 'ON' if (os.environ.get("QTOP_COLOR", sys.stdout.isatty()) in ("ON", True)) else 'OFF'
logging.debug("options.COLOR is now set to: %s" % options.COLOR)
options.REMAP = False # Default value
NAMED_WNS = 1 if options.FORCE_NAMES else 0
return options, NAMED_WNS
# def handle_exception(exc_type, exc_value, exc_traceback):
# """
# This, when replacing sys.excepthook,
# will log uncaught exceptions to the logging module instead
# of printing them to stdout.
# """
# if issubclass(exc_type, KeyboardInterrupt):
# sys.__excepthook__(exc_type, exc_value, exc_traceback)
# return
#
# logging.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
class WNOccupancy(object):
def __init__(self, cluster, config, document, user_to_color, job_ids):
self.cluster = cluster
self.config = config
self.document = document
self.account_jobs_table = list()
self.user_to_id = dict()
self.jobid_to_user_to_queue = dict()
self.user_names, self.job_states, self.job_queues = self._get_usernames_states_queues(document.jobs_dict)
self.job_ids = job_ids
self.calculate(document, user_to_color)
def _get_usernames_states_queues(self, jobs_dict):
user_names, job_states, job_queues = list(), list(), list()
for key, value in jobs_dict.items():
user_names.append(value.user_name)
job_states.append(value.job_state)
job_queues.append(value.job_queue)
return user_names, job_states, job_queues
def calculate(self, document, user_to_color):
"""
Prints the Worker Nodes Occupancy table.
if there are non-uniform WNs in pbsnodes.yaml, e.g. wn01, wn02, gn01, gn02, ..., remapping is performed.
Otherwise, for uniform WNs, i.e. all using the same numbering scheme, wn01, wn02, ... proceeds as normal.
Number of Extra tables needed is calculated inside the calc_all_wnid_label_lines function below
"""
if not self.cluster:
return self # TODO fix
# document.jobs_dict => job_id: job name/state/queue
self.jobid_to_user_to_queue = dict(izip(self.job_ids, izip(user_names, job_queues)))
self.user_machine_use = self.calculate_user_node_use(cluster, self.jobid_to_user_to_queue, self.job_ids, user_names,
job_queues)
user_alljobs_sorted_lot = self._produce_user_lot(self.user_names)
user_to_id = self._create_id_for_users(user_alljobs_sorted_lot)
user_job_per_state_counts = self._calculate_user_job_counts(self.user_names, self.job_states, user_alljobs_sorted_lot,
user_to_id)
_account_jobs_table = self._create_sort_acct_jobs_table(user_job_per_state_counts, user_alljobs_sorted_lot, user_to_id)
self.account_jobs_table, self.user_to_id = self._create_account_jobs_table(user_to_id, _account_jobs_table)
self.userid_to_userid_re_pat = self.make_pattern_out_of_mapping(mapping=user_to_color)
# TODO extract to another class?
self.print_char_start, self.print_char_stop, self.extra_matrices_nr = self.find_matrices_width()
self.wn_vert_labels = self.calc_all_wnid_label_lines(dynamic_config['force_names'])
# For-loop below only for user-inserted/customizeable values.
for yaml_key, part_name, systems in yaml.get_yaml_key_part(config, scheduler, outermost_key='workernodes_matrix'):
if scheduler in systems:
self.__setattr__(part_name, self.calc_general_mult_attr_line(part_name, yaml_key, config))
self.core_user_map = self._calc_core_matrix(self.user_to_id, self.jobid_to_user_to_queue)
def _create_account_jobs_table(self, user_to_id, account_jobs_table):
# TODO: unix account id needs to be recomputed at this point. fix.
for quintuplet, new_uid in zip(account_jobs_table, config['possible_ids']):
unix_account = quintuplet[4]
quintuplet[0] = user_to_id[unix_account] = utils.ColorStr(unix_account[0], color='Red_L') \
if config['fill_with_user_firstletter'] else utils.ColorStr(new_uid, color='Red_L')
return account_jobs_table, user_to_id
def _create_sort_acct_jobs_table(self, user_job_per_state_counts, user_all_jobs_sorted, user_to_id):
"""Calculates what is actually below the id| jobs>=R + Q | unix account etc line"""
account_jobs_table = []
for user_alljobs in user_all_jobs_sorted:
user, alljobs_of_user = user_alljobs
account_jobs_table.append(
[
user_to_id[user],
user_job_per_state_counts['running_of_user'][user],
user_job_per_state_counts['queued_of_user'][user],
alljobs_of_user,
user,
self.user_machine_use[user]
]
)
account_jobs_table.sort(key=itemgetter(3, 4), reverse=True) # sort by All jobs, then unix account
return account_jobs_table
def _create_user_job_counts(self, user_names, job_states, state_abbrevs):
"""
counting of e.g. R, Q, C, W, E attached to each user
"""
user_job_per_state_counts = dict()
for state_of_user in state_abbrevs.values():
user_job_per_state_counts[state_of_user] = dict()
for user_name, job_state in zip(user_names, job_states):
try:
x_of_user = state_abbrevs[job_state]
except KeyError:
raise JobNotFound(job_state)
user_job_per_state_counts[x_of_user][user_name] = user_job_per_state_counts[x_of_user].get(user_name, 0) + 1
for user_name in user_job_per_state_counts['running_of_user']:
[user_job_per_state_counts[x_of_user].setdefault(user_name, 0) for x_of_user in user_job_per_state_counts if
x_of_user != 'running_of_user']
return user_job_per_state_counts
def _produce_user_lot(self, _user_names):
"""
Produces a list of tuples (lot) of the form (user account, all jobs count) in descending order.
Used in the user accounts and poolmappings table
"""
user_to_alljobs_count = {}
for user_name in set(_user_names):
user_to_alljobs_count[user_name] = _user_names.count(user_name)
user_alljobs_sorted_lot = sorted(user_to_alljobs_count.items(), key=itemgetter(1), reverse=True)
return user_alljobs_sorted_lot
def _calculate_user_job_counts(self, user_names, job_states, user_alljobs_sorted_lot, user_to_id):
"""
Calculates and prints what is actually below the id| R + Q /all | unix account etc line
:param user_names: list
:param job_states: list
:return: (list, list, dict)