-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhook_cgroups.py
6633 lines (6342 loc) · 289 KB
/
hook_cgroups.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
# Copyright (C) 1994-2021 Altair Engineering, Inc.
# For more information, contact Altair at www.altair.com.
#
# This file is part of both the OpenPBS software ("OpenPBS")
# and the PBS Professional ("PBS Pro") software.
#
# Open Source License Information:
#
# OpenPBS is free software. You can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# OpenPBS is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Commercial License Information:
#
# PBS Pro is commercially licensed software that shares a common core with
# the OpenPBS software. For a copy of the commercial license terms and
# conditions, go to: (http://www.pbspro.com/agreement.html) or contact the
# Altair Legal Department.
#
# Altair's dual-license business model allows companies, individuals, and
# organizations to create proprietary derivative works of OpenPBS and
# distribute them - whether embedded or bundled with other software -
# under a commercial license agreement.
#
# Use of Altair's trademarks, including but not limited to "PBS™",
# "OpenPBS®", "PBS Professional®", and "PBS Pro™" and Altair's logos is
# subject to Altair's trademark licensing policies.
"""
PBS hook for managing cgroups on Linux execution hosts.
This hook contains the handlers required for PBS to support
cgroups on Linux hosts that support them (kernel 2.6.28 and higher)
This hook services the following events:
- exechost_periodic
- exechost_startup
- execjob_attach
- execjob_begin
- execjob_end
- execjob_epilogue
- execjob_launch
- execjob_resize
- execjob_abort
- execjob_postsuspend
- execjob_preresume
"""
# NOTES:
#
# When soft_limit is true for memory, memsw represents the hard limit.
#
# The resources value in sched_config must contain entries for mem and
# vmem if those subsystems are enabled in the hook configuration file. The
# amount of resource requested will not be avaiable to the hook if they
# are not present.
# if we are not on a Linux system then the hook should always do nothing
# and accept, and certainly not try Linux-only module imports
import platform
# Module imports
#
# This one is needed to log messages
import pbs
if platform.system() != 'Linux':
pbs.logmsg(pbs.EVENT_DEBUG,
'Cgroup hook not on supported OS '
'-- just accepting event')
pbs.event().accept()
# we're on Linux, but does the kernel support cgroups?
rel = list(map(int, (platform.release().split('-')[0].split('.'))))
pbs.logmsg(pbs.EVENT_DEBUG4,
'Cgroup hook: detected Linux kernel version %d.%d.%d' %
(rel[0], rel[1], rel[2]))
supported = False
if rel[0] > 2:
supported = True
elif rel[0] == 2:
if rel[1] > 6:
supported = True
elif rel[1] == 6:
if rel[2] >= 28:
supported = True
if not supported:
pbs.logmsg(pbs.EVENT_DEBUG,
'Cgroup hook: kernel %s.%s.%s < 2.6.28; not supported'
% (rel[0], rel[1], rel[2]))
pbs.event.accept()
else:
# Now we know that at least the hook might do something useful
# so import other modules (some of them Linux-specific)
# Note the else is needed to be PEP8-compliant: the imports must
# not be unindented since they are not top-of-file
import sys
import os
import stat
import errno
import signal
import subprocess
import re
import glob
import time
import string
import traceback
import copy
import operator
import fnmatch
import math
import types
try:
import json
except Exception:
import simplejson as json
multiprocessing = None
try:
# will fail in Python 2.5
import multiprocessing
except Exception:
# but we can use isinstance(multiprocessing, types.ModuleType) later
# to find out if it worked
pass
import fcntl
import pwd
PYTHON2 = sys.version_info[0] < 3
try:
bytearray
BYTEARRAY_EXISTS = True
except NameError:
BYTEARRAY_EXISTS = False
# Define some globals that get set in main
PBS_EXEC = ''
PBS_HOME = ''
PBS_MOM_HOME = ''
PBS_MOM_JOBS = ''
# ============================================================================
# Derived error classes
# ============================================================================
class AdminError(Exception):
"""
Base class for errors fixable only by administrative action.
"""
pass
class ProcessingError(Exception):
"""
Base class for errors in processing, unknown cause.
"""
pass
class UserError(Exception):
"""
Base class for errors fixable by the user.
"""
pass
class JobValueError(Exception):
"""
Errors in PBS job resource values.
"""
pass
class CgroupBusyError(ProcessingError):
"""
Errors when the cgroup is busy.
"""
pass
class CgroupConfigError(AdminError):
"""
Errors in configuring cgroup.
"""
pass
class CgroupLimitError(AdminError):
"""
Errors in configuring cgroup.
"""
pass
class CgroupProcessingError(ProcessingError):
"""
Errors processing cgroup.
"""
pass
class TimeoutError(ProcessingError):
"""
Timeout encountered.
"""
pass
# ============================================================================
# Utility functions
# ============================================================================
#
# FUNCTION stringified_output
#
def stringified_output(out):
if PYTHON2:
if isinstance(out, str):
return(out)
elif isinstance(out, unicode):
return(out.encode('utf-8'))
else:
return(str(out))
else:
if isinstance(out, str):
return(out)
elif isinstance(out, (bytes, bytearray)):
return(out.decode('utf-8'))
else:
return(str(out))
#
# FUNCTION caller_name
#
def caller_name():
"""
Return the name of the calling function or method.
"""
return str(sys._getframe(1).f_code.co_name)
#
# FUNCTION systemd_escape
#
def systemd_escape(buf):
"""
Escape strings for usage in system unit names
Some distros don't provide the systemd-escape command
"""
pbs.logmsg(pbs.EVENT_DEBUG4, '%s: Method called' % caller_name())
if not isinstance(buf, str):
raise ValueError('Not a basetype string')
ret = ''
for i, char in enumerate(buf):
if i < 1 and char == '.':
if PYTHON2:
ret += '\\x' + '.'.encode('hex')
else:
ret += '\\x' + b'.'.hex()
elif char.isalnum() or char in '_.':
ret += char
elif char == '/':
ret += '-'
else:
# Will turn non-ASCII into UTF-8 hex sequence on both Py2/3
if PYTHON2:
hexval = char.encode('hex')
else:
hexval = char.encode('utf-8').hex()
for j in range(0, len(hexval), 2):
ret += '\\x' + hexval[j:j + 2]
return ret
#
# FUNCTION convert_size
#
def convert_size(value, units='b'):
"""
Convert a string containing a size specification (e.g. "1m") to a
string using different units (e.g. "1024k").
This function only interprets a decimal number at the start of the string,
stopping at any unrecognized character and ignoring the rest of the string.
When down-converting (e.g. MB to KB), all calculations involve integers and
the result returned is exact. When up-converting (e.g. KB to MB) floating
point numbers are involved. The result is rounded up. For example:
1023MB -> GB yields 1g
1024MB -> GB yields 1g
1025MB -> GB yields 2g <-- This value was rounded up
Pattern matching or conversion may result in exceptions.
"""
logs = {'b': 0, 'k': 10, 'm': 20, 'g': 30,
't': 40, 'p': 50, 'e': 60, 'z': 70, 'y': 80}
try:
new = units[0].lower()
if new not in logs:
raise ValueError('Invalid unit value')
result = re.match(r'([-+]?\d+)([bkmgtpezy]?)',
str(value).lower())
if not result:
raise ValueError('Unrecognized value')
val, old = result.groups()
if int(val) < 0:
raise ValueError('Value may not be negative')
if old not in logs:
old = 'b'
factor = logs[old] - logs[new]
val = float(val)
val *= 2 ** factor
if (val - int(val)) > 0.0:
val += 1.0
val = int(val)
# pbs.size() does not like units following zero
if val <= 0:
return '0'
return str(val) + new
except Exception:
return None
#
# FUNCTION size_as_int
#
def size_as_int(value):
"""
Convert a size string to an integer representation of size in bytes
"""
in_bytes = convert_size(value, units='b')
if in_bytes is not None:
return int(convert_size(value).rstrip(string.ascii_lowercase))
else:
pbs.logmsg(pbs.EVENT_ERROR, "size_as_int: Value %s "
"does not convert to int, returning None" % value)
return None
#
# FUNCTION convert_time
#
def convert_time(value, units='s'):
"""
Converts a integer value for time into the value of the return unit
A valid decimal number, with optional sign, may be followed by a character
representing a scaling factor. Scaling factors may be either upper or
lower case. Examples include:
250ms
40s
+15min
Valid scaling factors are:
ns = 10**-9
us = 10**-6
ms = 10**-3
s = 1
min = 60
hr = 3600
Pattern matching or conversion may result in exceptions.
"""
multipliers = {'': 1, 'ns': 10 ** -9, 'us': 10 ** -6,
'ms': 10 ** -3, 's': 1, 'min': 60, 'hr': 3600}
new = units.lower()
if new not in multipliers:
raise ValueError('Invalid unit value')
result = re.match(r'([-+]?\d+)\s*([a-zA-Z]+)',
str(value).lower())
if not result:
raise ValueError('Unrecognized value')
num, factor = result.groups()
# Check to see if there was not unit of time specified
if factor is None:
factor = ''
# Check to see if the unit is valid
if str.lower(factor) not in multipliers:
raise ValueError('Time unit not recognized')
# Convert the value to seconds
value = float(num) * float(multipliers[str.lower(factor)])
if units != 's':
value = value / multipliers[new]
# _pbs_v1.validate_input breaks with very small time values
# because Python converts them to values like 1e-05
if value < 0.001:
value = 0.0
return value
def decode_list(data):
"""
json hook to convert lists from non string type to str
"""
ret = []
for item in data:
if isinstance(item, str):
pass
if isinstance(item, list):
item = decode_list(item)
elif isinstance(item, dict):
item = decode_dict(item)
elif PYTHON2:
if isinstance(item, unicode):
item = item.encode('utf-8')
elif BYTEARRAY_EXISTS and isinstance(item, bytearray):
item = str(item)
elif isinstance(item, (bytes, bytearray)):
item = str(item, 'utf-8')
ret.append(item)
return ret
def decode_dict(data):
"""
json hook to convert dictionaries from non string type to str
"""
ret = {}
for key, value in list(data.items()):
# first the key
if isinstance(key, str):
pass
elif PYTHON2:
if isinstance(key, unicode):
key = key.encode('utf-8')
elif BYTEARRAY_EXISTS and isinstance(key, bytearray):
key = str(key)
elif isinstance(key, (bytes, bytearray)):
key = str(key, 'utf-8')
# now the value
if isinstance(value, str):
pass
if isinstance(value, list):
value = decode_list(value)
elif isinstance(value, dict):
value = decode_dict(value)
elif PYTHON2:
if isinstance(value, unicode):
value = value.encode('utf-8')
elif BYTEARRAY_EXISTS and isinstance(key, bytearray):
value = str(value)
elif isinstance(value, (bytes, bytearray)):
value = str(value, 'utf-8')
# add stringified (key, value) pair to result
ret[key] = value
return ret
def merge_dict(base, new):
"""
Merge together two multilevel dictionaries where new
takes precedence over base
"""
if not isinstance(base, dict):
raise ValueError('base must be type dict')
if not isinstance(new, dict):
raise ValueError('new must be type dict')
newkeys = list(new.keys())
merged = {}
for key in base:
if key in newkeys and isinstance(base[key], dict):
# Take it off the list of keys to copy
newkeys.remove(key)
merged[key] = merge_dict(base[key], new[key])
else:
merged[key] = copy.deepcopy(base[key])
# Copy the remaining unique keys from new
for key in newkeys:
merged[key] = copy.deepcopy(new[key])
return merged
def expand_list(old):
"""
Convert condensed list format (with ranges) to an expanded Python list.
The input string is a comma separated list of digits and ranges.
Examples include:
0-3,8-11
0,2,4,6
2,5-7,10
"""
new = []
if isinstance(old, list):
old = ",".join(list(map(str, old)))
stripped = old.strip()
if not stripped:
return new
for entry in stripped.split(','):
if '-' in entry[1:]:
start, end = entry.split('-', 1)
for i in range(int(start), int(end) + 1):
new.append(i)
else:
new.append(int(entry))
return new
def find_files(path, pattern='*', kind='',
follow_links=False, follow_mounts=True):
"""
Return a list of files similar to the find command
"""
if isinstance(pattern, str):
pattern = [pattern]
if isinstance(kind, str):
if not kind:
kind = []
else:
kind = [kind]
if not isinstance(pattern, list):
raise TypeError('Pattern must be a string or list')
if not isinstance(kind, list):
raise TypeError('Kind must be a string or list')
# Top level not excluded if it is a mount point
mounts = []
for root, dirs, files in os.walk(path, followlinks=follow_links):
for name in [os.path.join(root, x) for x in dirs + files]:
if not follow_mounts:
if os.path.isdir(name) and os.path.ismount(name):
mounts.append(os.path.join(name, ''))
continue
undermount = False
for mountpoint in mounts:
if name.startswith(mountpoint):
undermount = True
break
if undermount:
continue
pattern_matched = False
for pat in pattern:
if fnmatch.fnmatchcase(os.path.basename(name), pat):
pattern_matched = True
break
if not pattern_matched:
continue
if not kind:
yield name
continue
try:
statinfo = os.lstat(name).st_mode
except FileNotFoundError:
continue
for entry in kind:
if not entry:
yield name
break
for letter in entry:
if letter == 'f' and stat.S_ISREG(statinfo):
yield name
break
elif letter == 'l' and stat.S_ISLNK(statinfo):
yield name
break
elif letter == 'c' and stat.S_ISCHR(statinfo):
yield name
break
elif letter == 'b' and stat.S_ISBLK(statinfo):
yield name
break
elif letter == 'p' and stat.S_ISFIFO(statinfo):
yield name
break
elif letter == 's' and stat.S_ISSOCK(statinfo):
yield name
break
elif letter == 'd' and stat.S_ISDIR(statinfo):
yield name
break
def initialize_resource(resc):
"""
Return a properly cast zero value
"""
if isinstance(resc, pbs.pbs_int):
ret = pbs.pbs_int(0)
elif isinstance(resc, pbs.pbs_float):
ret = pbs.pbs_float(0)
elif isinstance(resc, pbs.size):
ret = pbs.size('0')
elif isinstance(resc, int):
ret = 0
elif isinstance(resc, float):
ret = 0.0
elif isinstance(resc, list):
ret = []
elif isinstance(resc, dict):
ret = {}
elif isinstance(resc, tuple):
ret = ()
elif isinstance(resc, str):
ret = ''
else:
raise ValueError('Unable to initialize unknown resource type')
return ret
def printjob_info(jobid, include_attributes=False):
"""
Use printjob to acquire the job information
"""
info = {}
jobfile = os.path.join(PBS_MOM_JOBS, '%s.JB' % jobid)
if not os.path.isfile(jobfile):
pbs.logmsg(pbs.EVENT_DEBUG4, 'File not found: %s' % (jobfile))
return info
cmd = [os.path.join(PBS_EXEC, 'bin', 'printjob')]
if not include_attributes:
cmd.append('-a')
cmd.append(jobfile)
try:
pbs.logmsg(pbs.EVENT_DEBUG4, 'Running: %s' % cmd)
process = subprocess.Popen(cmd, shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
out, err = process.communicate()
if process.returncode != 0:
pbs.logmsg(pbs.EVENT_DEBUG4,
'command return code non-zero: %s'
% str(process.returncode))
pbs.logmsg(pbs.EVENT_DEBUG4,
'command stderr: %s'
% stringified_output(err))
except Exception as exc:
pbs.logmsg(pbs.EVENT_DEBUG2, 'Error running command: %s' % cmd)
pbs.logmsg(pbs.EVENT_DEBUG2, 'Exception: %s' % exc)
return {}
# if we get a non-str type then convert before calling splitlines
# should not happen since we pass universal_newlines True
out_split = stringified_output(out).splitlines()
pattern = re.compile(r'^(\w.*):\s*(\S+)')
for line in out_split:
result = re.match(pattern, line)
if not result:
continue
key, val = result.groups()
if not key or not val:
continue
if val.startswith('0x'):
info[key] = int(val, 16)
elif val.isdigit():
info[key] = int(val)
else:
info[key] = val
pbs.logmsg(pbs.EVENT_DEBUG4, 'JB file info returned: %s' % repr(info))
return info
def job_is_suspended(jobid):
"""
Returns True if job is in a suspended or unknown substate
"""
jobinfo = printjob_info(jobid)
if 'substate' in jobinfo:
return jobinfo['substate'] in [43, 45, 'unknown']
return False
def job_is_running(jobid):
"""
Returns True if job shows a running state and substate
"""
jobinfo = printjob_info(jobid)
if 'substate' in jobinfo:
return jobinfo['substate'] == 42
return False
def fetch_vnode_comments_nomp(vnode_list, timeout=10):
comment_dict = {}
failure = False
pbs.logmsg(pbs.EVENT_DEBUG4,
"vnode list in fetch_vnode_comment is %s"
% vnode_list)
try:
with Timeout(timeout, 'Timed out contacting server'):
for vn in vnode_list:
comment_dict[vn] = pbs.server().vnode(vn).comment
pbs.logmsg(pbs.EVENT_DEBUG4,
"comment for vnode %s fetched from server is %s"
% (str(vn), comment_dict[vn]))
except TimeoutError:
# pbs.server().vnode(xx).comment got stuck, or the timeout
# was too short for the number of nodes supplied
pbs.logmsg(pbs.EVENT_ERROR,
'Timed out while fetching comments from server, '
'timeout was %s' % str(timeout))
failure = True
except Exception as exc:
# other exception, like e.g. wrong vnode name
pbs.logmsg(pbs.EVENT_ERROR,
'Unexpected error in fetch_vnode_comments: %s'
% repr(exc))
failure = True
# only return a full dictionary if you got the comment for all vnodes
if not failure:
return (comment_dict, failure)
else:
return ({}, failure)
def fetch_vnode_comments_queue(vnode_list, commq):
comment_dict = {}
failure = False
pbs.logmsg(pbs.EVENT_DEBUG4,
"vnode list in fetch_vnode_comment is %s"
% vnode_list)
try:
for vn in vnode_list:
comment_dict[vn] = pbs.server().vnode(vn).comment
pbs.logmsg(pbs.EVENT_DEBUG4,
"comment for vnode %s fetched from server is %s"
% (str(vn), comment_dict[vn]))
except Exception as exc:
# other exception, like e.g. wrong vnode name
pbs.logmsg(pbs.EVENT_ERROR,
'Unexpected error in fetch_vnode_comments: %s'
% repr(exc))
failure = True
# only return a full dictionary if you got the comment for all vnodes
if not failure:
commq.put(comment_dict)
else:
commq.put({})
return True
def fetch_vnode_comments_mp(vnode_list, timeout=10):
worker_comment_dict = {}
commq = multiprocessing.Queue()
worker = multiprocessing.Process(target=fetch_vnode_comments_queue,
args=(vnode_list, commq))
worker.start()
worker.join(timeout)
if worker.is_alive():
pbs.logmsg(pbs.EVENT_ERROR,
"comment fetcher for %s timed out after %s seconds"
% (str(vnode_list), timeout))
# will mess up the commq Queue but we don't care
# will send SIGTERM, but it's possible that is masked
# while in a SWIG function
# we don't really care since unline in threading,
# in multiprocessing we can exit and orphan the worker
worker.terminate()
pbs.logmsg(pbs.EVENT_ERROR,
'Timed out while fetching comments from server,'
'timeout was %s' % str(timeout))
return ({}, True)
else:
pbs.logmsg(pbs.EVENT_DEBUG4,
"comments fetched from server without timeout")
comment_dict = {}
try:
comment_dict = commq.get()
except Exception:
# Treat failure to get comments dictionary from queue
# as a timeout
return ({}, True)
pbs.logmsg(pbs.EVENT_DEBUG4,
"worker comment_dict is %r" % comment_dict)
return (comment_dict, False)
def fetch_vnode_comments(vnode_list, timeout=10):
if not isinstance(multiprocessing, types.ModuleType):
pbs.logmsg(pbs.EVENT_DEBUG4, "multiprocessing not available, "
"fetch_vnode_comment will use SIGALRM timeout")
return fetch_vnode_comments_nomp(vnode_list, timeout)
else:
pbs.logmsg(pbs.EVENT_DEBUG4, "multiprocessing available, "
"fetch_vnode_comment will use mp for timeout")
return fetch_vnode_comments_mp(vnode_list, timeout)
# ============================================================================
# Utility classes
# ============================================================================
#
# CLASS Lock
#
class Lock(object):
"""
Implement a simple locking mechanism using a file lock
"""
def __init__(self, path):
self.path = path
self.lockfd = None
def getpath(self):
"""
Return the path of the lock file.
"""
return self.path
def getlockfd(self):
"""
Return the file descriptor of the lock file.
"""
return self.lockfd
def __enter__(self):
self.lockfd = open(self.path, 'w')
fcntl.flock(self.lockfd, fcntl.LOCK_EX)
pbs.logmsg(pbs.EVENT_DEBUG4, '%s file lock acquired by %s' %
(self.path, str(sys._getframe(1).f_code.co_name)))
def __exit__(self, exc, val, trace):
if self.lockfd:
fcntl.flock(self.lockfd, fcntl.LOCK_UN)
self.lockfd.close()
pbs.logmsg(pbs.EVENT_DEBUG4, '%s file lock released by %s' %
(self.path, str(sys._getframe(1).f_code.co_name)))
#
# CLASS Timeout
#
class Timeout(object):
"""
Implement a timeout mechanism via SIGALRM
"""
def __init__(self, duration=1, message='Operation timed out'):
self.duration = duration
self.message = message
def handler(self, sig, frame):
"""
Throw a timeout error when SIGALRM is received
"""
raise TimeoutError(self.message)
def getduration(self):
"""
Return the timeout duration
"""
return self.duration
def getmessage(self):
"""
Return the timeout message
"""
return self.message
def __enter__(self):
if signal.getsignal(signal.SIGALRM):
raise RuntimeError('Alarm handler already registered')
signal.signal(signal.SIGALRM, self.handler)
signal.alarm(self.duration)
def __exit__(self, exc, val, trace):
signal.alarm(0)
signal.signal(signal.SIGALRM, signal.SIG_DFL)
#
# CLASS HookUtils
#
class HookUtils(object):
"""
Hook utility methods
"""
def __init__(self, hook_events=None):
if hook_events is not None:
self.hook_events = hook_events
else:
# Defined in the order they appear in module_pbs_v1.c
# if adding new events that may not exist in all PBS versions,
# use hasattr() to prevent exceptions when the hook is used
# on older PBS versions - see e.g. EXECJOB_ABORT
self.hook_events = {}
self.hook_events[pbs.QUEUEJOB] = {
'name': 'queuejob',
'handler': None
}
self.hook_events[pbs.MODIFYJOB] = {
'name': 'modifyjob',
'handler': None
}
self.hook_events[pbs.RESVSUB] = {
'name': 'resvsub',
'handler': None
}
if hasattr(pbs, "MODIFYRESV"):
self.hook_events[pbs.MODIFYRESV] = {
'name': 'modifyresv',
'handler': None
}
self.hook_events[pbs.MOVEJOB] = {
'name': 'movejob',
'handler': None
}
self.hook_events[pbs.RUNJOB] = {
'name': 'runjob',
'handler': None
}
if hasattr(pbs, "MANAGEMENT"):
self.hook_events[pbs.MANAGEMENT] = {
'name': 'management',
'handler': None
}
if hasattr(pbs, "MODIFYVNODE"):
self.hook_events[pbs.MODIFYVNODE] = {
'name': 'modifyvnode',
'handler': None
}
self.hook_events[pbs.PROVISION] = {
'name': 'provision',
'handler': None
}
if hasattr(pbs, "RESV_END"):
self.hook_events[pbs.RESV_END] = {
'name': 'resv_end',
'handler': None
}
if hasattr(pbs, "RESV_BEGIN"):
self.hook_events[pbs.RESV_BEGIN] = {
'name': 'resv_begin',
'handler': None
}
if hasattr(pbs, "RESV_CONFIRM"):
self.hook_events[pbs.RESV_CONFIRM] = {
'name': 'resv_confirm',
'handler': None
}
self.hook_events[pbs.EXECJOB_BEGIN] = {
'name': 'execjob_begin',
'handler': self._execjob_begin_handler
}
self.hook_events[pbs.EXECJOB_PROLOGUE] = {
'name': 'execjob_prologue',
'handler': None
}
self.hook_events[pbs.EXECJOB_EPILOGUE] = {
'name': 'execjob_epilogue',
'handler': self._execjob_epilogue_handler
}
self.hook_events[pbs.EXECJOB_PRETERM] = {
'name': 'execjob_preterm',
'handler': None
}
self.hook_events[pbs.EXECJOB_END] = {
'name': 'execjob_end',
'handler': self._execjob_end_handler
}
self.hook_events[pbs.EXECJOB_LAUNCH] = {
'name': 'execjob_launch',
'handler': self._execjob_launch_handler
}
self.hook_events[pbs.EXECHOST_PERIODIC] = {
'name': 'exechost_periodic',
'handler': self._exechost_periodic_handler
}
self.hook_events[pbs.EXECHOST_STARTUP] = {
'name': 'exechost_startup',
'handler': self._exechost_startup_handler
}
self.hook_events[pbs.EXECJOB_ATTACH] = {
'name': 'execjob_attach',
'handler': self._execjob_attach_handler
}
if hasattr(pbs, "EXECJOB_RESIZE"):
self.hook_events[pbs.EXECJOB_RESIZE] = {
'name': 'execjob_resize',
'handler': self._execjob_resize_handler
}
if hasattr(pbs, "EXECJOB_ABORT"):
self.hook_events[pbs.EXECJOB_ABORT] = {
'name': 'execjob_abort',
'handler': self._execjob_end_handler
}
if hasattr(pbs, "EXECJOB_POSTSUSPEND"):
self.hook_events[pbs.EXECJOB_POSTSUSPEND] = {
'name': 'execjob_postsuspend',
'handler': self._execjob_postsuspend_handler
}