forked from CESNET/pbs.hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhook_cgroups.py
3686 lines (3373 loc) · 158 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-2016 Altair Engineering, Inc.
# For more information, contact Altair at www.altair.com.
#
# This file is part of the PBS Professional ("PBS Pro") software.
#
# Open Source License Information:
#
# PBS Pro 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.
#
# PBS Pro 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:
#
# The PBS Pro software is licensed under the terms of the GNU Affero General
# Public License agreement ("AGPL"), except where a separate commercial license
# agreement for PBS Pro version 14 or later has been executed in writing with Altair.
#
# Altair’s dual-license business model allows companies, individuals, and
# organizations to create proprietary derivative works of PBS Pro 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™",
# "PBS Professional®", and "PBS Pro™" and Altair’s logos is subject to Altair's
# trademark licensing policies.
# 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.
# This hook handles all of the operations necessary 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
# Imports from __future__ must happen first
from __future__ import with_statement
# Additional imports
import sys
import os
import errno
import signal
import subprocess
import re
import glob
import time
import string
import platform
import traceback
import copy
from stat import S_ISBLK, S_ISCHR
import operator
import pwd
import pbs
import fnmatch
import socket
try:
import json
except:
import simplejson as json
CGROUP_KILL_ATTEMPTS = 12
# Flag to turn off features not in 12.2.40X branch
CRAY_12_BRANCH = False
# ============================================================================
# Derived error classes
# ============================================================================
# Base class for errors fixable only by administrative action.
class AdminError(Exception):
pass
# Base class for errors in processing, unknown cause.
class ProcessingError(Exception):
pass
# Base class for errors fixable by the user.
class UserError(Exception):
pass
# Errors in PBS job resource values.
class JobValueError(UserError):
pass
# Errors when the cgroup is busy.
class CgroupBusyError(ProcessingError):
pass
# Errors in configuring cgroup.
class CgroupConfigError(AdminError):
pass
# Errors in configuring cgroup.
class CgroupLimitError(AdminError):
pass
# Errors processing cgroup.
class CgroupProcessingError(ProcessingError):
pass
# ============================================================================
# Utility functions
# ============================================================================
#
# FUNCTION caller_name
#
# Return the name of the calling function or method.
#
def caller_name():
return str(sys._getframe(1).f_code.co_name)
#
# FUNCTION convert_size
#
# 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.
#
def convert_size(value, units='b'):
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.keys():
new = 'b'
val, old = re.match('([-+]?\d+)([bkmgtpezy]?)',
str(value).lower()).groups()
val = int(val)
if val < 0:
raise ValueError('Value may not be negative')
if old not in logs.keys():
old = 'b'
factor = logs[old] - logs[new]
val *= 2 ** factor
slop = val - int(val)
val = int(val)
if slop > 0:
val += 1
# pbs.size() does not like units following zero
if val <= 0:
return '0'
else:
return str(val) + new
except:
return None
#
# FUNCTION size_as_int
#
# Convert a size string to an integer representation of size in bytes
#
def size_as_int(value):
return int(convert_size(value).rstrip(string.ascii_lowercase))
#
# FUNCTION convert_time
#
# 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.
#
def convert_time(value, return_unit='s'):
multipliers = {'': 1, 'ns': 10 ** -9, 'us': 10 ** -6,
'ms': 10 ** -3, 's': 1, 'min': 60, 'hr': 3600}
n, factor = re.match('([-+]?\d+)(\w*[a-zA-Z])?',
str(value).lower()).groups(0)
# Check to see if there was not unit of time specified
if factor == 0:
factor = ''
# Check to see if the unit is valid
if str.lower(factor) not in multipliers.keys():
raise ValueError('Time unit not recognized.')
# Convert the value to seconds
value_in_sec = float(n) * float(multipliers[str.lower(factor)])
if return_unit != 's':
return value_in_sec / multipliers[str.lower(return_unit)]
else:
return float('%lf' % value_in_sec)
# simplejson hook to convert lists from unicode to utf-8
def decode_list(data):
rv = []
for item in data:
if isinstance(item, unicode):
item = item.encode('utf-8')
elif isinstance(item, list):
item = decode_list(item)
elif isinstance(item, dict):
item = decode_dict(item)
rv.append(item)
return rv
# simplejson hook to convert dictionaries from unicode to utf-8
def decode_dict(data):
rv = {}
for key, value in data.iteritems():
if isinstance(key, unicode):
key = key.encode('utf-8')
if isinstance(value, unicode):
value = value.encode('utf-8')
elif isinstance(value, list):
value = decode_list(value)
elif isinstance(value, dict):
value = decode_dict(value)
rv[key] = value
return rv
# Convert CPU list format (with ranges) to a Python list
def cpus2list(s):
# 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
cpus = []
if s.strip() == '':
return cpus
for r in s.split(','):
if '-' in r[1:]:
start, end = r.split('-', 1)
for i in range(int(start), int(end) + 1):
cpus.append(int(i))
else:
cpus.append(int(r))
return cpus
# Helper function to ignore suspended jobs when removing
# "already used" resources
def job_to_be_ignored(jobid):
# Get job substate from small utility that calls printjob
pbs_exec = ''
if not CRAY_12_BRANCH:
pbs_conf = pbs.get_pbs_conf()
pbs_exec = pbs_conf['PBS_EXEC']
else:
if 'PBS_EXEC' in self.cfg:
pbs_exec = self.cfg['PBS_EXEC']
else:
pbs.logmsg(pbs.EVENT_DEBUG,
"PBS_EXEC needs to be defined in the config file")
pbs.logmsg(pbs.EVENT_DEBUG,
"Exiting the cgroups hook")
pbs.event().accept()
printjob_cmd = pbs_exec+os.sep+'bin'+os.sep+'printjob'
cmd = [printjob_cmd, jobid]
substate = None
try:
pbs.logmsg(pbs.EVENT_DEBUG3, "cmd: %s" % cmd)
# Collect the job substate information
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(out, err) = process.communicate()
# Find the job substate
substate_re = re.compile(r"substate:\s+(?P<jobstate>\S+)\s+")
substate = substate_re.search(out)
except:
pbs.logmsg(pbs.EVENT_DEBUG,
"Unexpected error in job_to_be_ignored: %s" %
' '.join([repr(sys.exc_info()[0]),
repr(sys.exc_info()[1])]))
out = "Unknown: failed to run " + printjob_cmd
if substate is not None:
substate = substate.group().split(':')[1].strip()
pbs.logmsg(pbs.EVENT_DEBUG3,
"Job %s has substate %s" % (jobid, substate))
suspended_substates = ['0x2b', '0x2d', 'unknown']
return (substate in suspended_substates)
else:
return False
# ============================================================================
# Utility classes
# ============================================================================
#
# CLASS HookUtils
#
class HookUtils:
def __init__(self, hook_events=None):
if hook_events is not None:
self.hook_events = hook_events
else:
self.hook_events = {
# Defined in the order they appear in module_pbs_v1.c
pbs.QUEUEJOB: {
'name': 'queuejob',
'handler': None
},
pbs.MODIFYJOB: {
'name': 'modifyjob',
'handler': None
},
pbs.RESVSUB: {
'name': 'resvsub',
'handler': None
},
pbs.MOVEJOB: {
'name': 'movejob',
'handler': None
},
pbs.RUNJOB: {
'name': 'runjob',
'handler': None
},
pbs.PROVISION: {
'name': 'provision',
'handler': None
},
pbs.EXECJOB_BEGIN: {
'name': 'execjob_begin',
'handler': self.__execjob_begin_handler
},
pbs.EXECJOB_PROLOGUE: {
'name': 'execjob_prologue',
'handler': None
},
pbs.EXECJOB_EPILOGUE: {
'name': 'execjob_epilogue',
'handler': self.__execjob_epilogue_handler
},
pbs.EXECJOB_PRETERM: {
'name': 'execjob_preterm',
'handler': None
},
pbs.EXECJOB_END: {
'name': 'execjob_end',
'handler': self.__execjob_end_handler
},
pbs.EXECJOB_LAUNCH: {
'name': 'execjob_launch',
'handler': self.__execjob_launch_handler
},
pbs.EXECHOST_PERIODIC: {
'name': 'exechost_periodic',
'handler': self.__exechost_periodic_handler
},
pbs.EXECHOST_STARTUP: {
'name': 'exechost_startup',
'handler': self.__exechost_startup_handler
},
pbs.MOM_EVENTS: {
'name': 'mom_events',
'handler': None
},
}
if not CRAY_12_BRANCH:
pbs.logmsg(pbs.EVENT_DEBUG3,
"CRAY 12 Branch: %s" % (CRAY_12_BRANCH))
self.hook_events[pbs.EXECJOB_ATTACH] = {
'name': 'execjob_attach',
'handler': self.__execjob_attach_handler
}
def __repr__(self):
return "HookUtils(%s)" % (repr(self.hook_events))
def event_name(self, type):
if type in self.hook_events:
return self.hook_events[type]['name']
else:
pbs.logmsg(pbs.EVENT_DEBUG3,
"%s: Type: %s not found" % (caller_name(), type))
return None
def hashandler(self, type):
if type in self.hook_events:
return self.hook_events[type]['handler'] is not None
else:
return None
def invoke_handler(self, event, cgroup, jobutil, *args):
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Method called" % (caller_name()))
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: UID: real=%d, effective=%d" %
(caller_name(), os.getuid(), os.geteuid()))
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: GID: real=%d, effective=%d" %
(caller_name(), os.getgid(), os.getegid()))
if self.hashandler(event.type):
result = self.hook_events[event.type][
'handler'](event, cgroup, jobutil, *args)
return result
else:
pbs.logmsg(pbs.EVENT_DEBUG,
"%s: %s event not handled by this hook." %
(caller_name(), self.event_name(event.type)))
def __execjob_begin_handler(self, e, cgroup, jobutil):
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Method called" % (caller_name()))
# Instantiate the NodeConfig class for get_memory_on_node and
# get_vmem_on node
node = NodeConfig(cgroup.cfg)
pbs.logmsg(pbs.EVENT_DEBUG, "%s: NodeConfig class instantiated" %
(caller_name()))
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: %s" % (caller_name(), repr(node)))
pbs.logmsg(pbs.EVENT_DEBUG, "%s: Host assigned job resources: %s" %
(caller_name(), jobutil.host_resources))
# Make sure the parent cgroup directories exist
cgroup.create_paths()
# Make sure that any old cgroups created in an earlier attempt
# at creating or running the job are gone
cgroup.delete(e.job.id)
# Gather the assigned resources
cgroup.gather_assigned_resources()
# Create the cgroup(s) for the job
cgroup.create_job(e.job.id, node)
# Configure the new cgroup
cgroup.configure_job(e.job.id, jobutil.host_resources, node)
# Initialize resource usage for the job
cgroup.update_job_usage(e.job.id, e.job.resources_used)
# Write out the assigned resources
cgroup.write_out_cgroup_host_assigned_resources(e.job.id)
# Write out the environment variable for the host (pbs_attach)
if 'devices_name' in cgroup.host_assigned_resources:
pbs.logmsg(pbs.EVENT_DEBUG,
"Devices: %s" %
cgroup.host_assigned_resources['devices_name'])
env_list = list()
if len(cgroup.host_assigned_resources['devices_name']) > 0:
line = str()
mics = list()
gpus = list()
for key in cgroup.host_assigned_resources['devices_name']:
if key.startswith('mic'):
mics.append(key[3:])
elif key.startswith('nvidia'):
gpus.append(key[6:])
if len(mics) > 0:
env_list.append('OFFLOAD_DEVICES="%s"' %
string.join(mics, ','))
if len(gpus) > 0:
# don't put quotes around the values. ex "0" or "0,1".
# This will cause it to fail.
env_list.append('CUDA_VISIBLE_DEVICES=%s' %
string.join(gpus, '\,'))
pbs.logmsg(pbs.EVENT_DEBUG, "ENV_LIST: %s" % env_list)
cgroup.write_out_cgroup_host_job_env_file(e.job.id, env_list)
return True
def __execjob_epilogue_handler(self, e, cgroup, jobutil):
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Method called" % (caller_name()))
# The resources_used information has a base type of pbs_resource
# Set the usage data
cgroup.update_job_usage(e.job.id, e.job.resources_used)
return True
def __execjob_end_handler(self, e, cgroup, jobutil):
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Method called" % (caller_name()))
# Delete the cgroup(s) for the job
cgroup.delete(e.job.id)
# Remove the host_assigned_resources and job_env file
for filename in [cgroup.hook_storage_dir+os.sep+e.job.id,
cgroup.host_job_env_filename % e.job.id]:
try:
os.remove(filename)
except OSError:
pbs.logmsg(pbs.EVENT_DEBUG3, "File: %s not found" % (filename))
except:
pbs.logmsg(pbs.EVENT_DEBUG3,
"Error removing file: %s" % (filename))
pass
return True
def __execjob_launch_handler(self, e, cgroup, jobutil):
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Method called" % (caller_name()))
# Add the parent process id to the appropriate cgroups.
cgroup.add_pids(os.getppid(), jobutil.job.id)
# FUTURE: Add environment variable to the job environment
# if job requested mic or gpu
cgroup.read_in_cgroup_host_assigned_resources(e.job.id)
if cgroup.host_assigned_resources is not None:
pbs.logmsg(pbs.EVENT_DEBUG3,
"host_assigned_resources: %s" %
(cgroup.host_assigned_resources))
cgroup.setup_job_devices_env()
return True
def __exechost_periodic_handler(self, e, cgroup, jobutil):
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Method called" % (caller_name()))
# Cleanup cgroups for jobs not present on this node
count = cgroup.cleanup_orphans(e.job_list)
if ('periodic_resc_update' in cgroup.cfg and
cgroup.cfg['periodic_resc_update']):
for job in e.job_list.keys():
pbs.logmsg(pbs.EVENT_DEBUG, "%s: job is %s" %
(caller_name(), job))
cgroup.update_job_usage(job, e.job_list[job].resources_used)
# Online nodes that were offlined due to a cgroup not cleaning up
if count == 0 and cgroup.cfg['online_offlined_nodes']:
vnode = pbs.event().vnode_list[cgroup.hostname]
if os.path.isfile(cgroup.offline_file):
line = 'Orphan cgroup(s) have been cleaned up. '
# Check with the pbs server to see if the node comment matches
try:
tmp_comment = pbs.server().vnode(cgroup.hostname).comment
except:
pbs.logmsg(pbs.EVENT_DEBUG,
"Unable to contact server for node comment")
tmp_comment = None
if tmp_comment == cgroup.offline_msg:
line += 'Will bring the node back online'
vnode.state = pbs.ND_FREE
vnode.comment = None
else:
line += 'However, the comment has changed since the node '
line += 'was offlined. Node will remain offline'
pbs.logmsg(pbs.EVENT_DEBUG,
"%s: %s" % (caller_name(), line))
# Remove file
os.remove(cgroup.offline_file)
return True
def __exechost_startup_handler(self, e, cgroup, jobutil):
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Method called" % (caller_name()))
cgroup.create_paths()
node = NodeConfig(cgroup.cfg)
pbs.logmsg(pbs.EVENT_DEBUG, "%s: NodeConfig class instantiated" %
(caller_name()))
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: %s" % (caller_name(), repr(node)))
node.create_vnodes()
if 'memory' in cgroup.subsystems:
val = node.get_memory_on_node(cgroup.cfg)
if val is not None:
if 'vnode_per_numa_node' in cgroup.cfg:
if not cgroup.cfg['vnode_per_numa_node']:
hn = node.hostname
e.vnode_list[hn].resources_available['mem'] = \
pbs.size(val)
val_cpus = node.totalcpus
if val_cpus is not None:
e.vnode_list[hn].resources_available['ncpus'] = \
int(val_cpus)
cgroup.set_node_limit('mem', val)
if 'memsw' in cgroup.subsystems:
val = node.get_vmem_on_node(cgroup.cfg)
if val is not None:
e.vnode_list[node.hostname].resources_available['vmem'] = \
pbs.size(val)
cgroup.set_node_limit('vmem', val)
if 'hugetlb' in cgroup.subsystems:
val = node.get_hpmem_on_node(cgroup.cfg)
if val is not None:
e.vnode_list[node.hostname].resources_available['hpmem'] = \
pbs.size(val)
cgroup.set_node_limit('hpmem', val)
return True
def __execjob_attach_handler(self, e, cgroup, jobutil):
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Method called" % (caller_name()))
pbs.logjobmsg(jobutil.job.id, "%s: Attaching PID %s" %
(caller_name(), e.pid))
# Add the job process id to the appropriate cgroups.
cgroup.add_pids(e.pid, jobutil.job.id)
return True
#
# CLASS ShallIRunUtils
#
class ShallIRunUtils:
def __init__(self, hostname, cfg):
self.cfg = cfg
self.hostname = hostname
def allow_users(self, allow_users):
""" This still needs to be defined """
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Method called" % (caller_name()))
pass
def exclude_hosts(self, exclude_hosts):
"""
Gets the hostname for the node and checks to see if the hook should
run on this node
"""
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Method called" % (caller_name()))
hostname = pbs.get_local_nodename()
# check to see if hostname is in the exclude_hosts list
if self.hostname in exclude_hosts:
pbs.logmsg(pbs.EVENT_DEBUG,
"%s: exclude host %s is in %s" %
(caller_name(), self.hostname, exclude_hosts))
pbs.event().accept()
# check to see if it regex syntax is used
pass
def exclude_vntypes(self, exclude_vntypes):
"""
Gets the vntype for the node and checks to see if the hook should
run on this node
"""
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Method called" % (caller_name()))
vntype = None
# look for on file on the mom until we can pass the vntype to the hook
pbs_home = ''
if not CRAY_12_BRANCH:
pbs_conf = pbs.get_pbs_conf()
pbs_home = pbs_conf['PBS_HOME']
else:
if 'PBS_HOME' in self.cfg:
pbs_home = self.cfg['PBS_HOME']
else:
pbs.logmsg(pbs.EVENT_DEBUG,
"PBS_HOME needs to be defined in the config file")
pbs.logmsg(pbs.EVENT_DEBUG,
"Exiting the cgroups hook")
pbs.event().accept()
vntype_file = pbs_home+os.sep+'mom_priv'+os.sep+'vntype'
if os.path.isfile(vntype_file):
fdata = open(vntype_file).readlines()
if len(fdata) > 0:
vntype = fdata[0].strip()
pbs.logmsg(pbs.EVENT_DEBUG3, "vntype: %s" % vntype)
if vntype is None:
pbs.logmsg(pbs.EVENT_DEBUG3,
"vntype is set to %s" % (vntype))
elif vntype in exclude_vntypes:
pbs.logmsg(pbs.EVENT_DEBUG3,
"vntype: %s is in %s" % (vntype, exclude_vntypes))
pbs.logmsg(pbs.EVENT_DEBUG3, "Exiting Hook")
pbs.event().accept()
else:
pbs.logmsg(pbs.EVENT_DEBUG3,
"vntype: %s not in global exclude: %s" %
(vntype, exclude_vntypes))
pass
def run_only_on_hosts(self, approved_hosts):
"""
Gets the list of approved nodes to run on and checks to see if the hook
should run on this node
"""
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Method called" % (caller_name()))
pbs.logmsg(pbs.EVENT_DEBUG3,
"Approved hosts: %s, %s" %
(type(approved_hosts), approved_hosts))
# check to see if hostname is in the approved_hosts list
if approved_hosts == []:
pbs.logmsg(pbs.EVENT_DEBUG3,
"approved hosts list is empty: %s" % approved_hosts)
elif self.hostname not in approved_hosts:
pbs.logmsg(pbs.EVENT_DEBUG3,
"%s is not in the approved list of hosts: %s" %
(self.hostname, approved_hosts))
pbs.event().accept()
else:
pbs.logmsg(pbs.EVENT_DEBUG3,
"%s in list of approved hosts: %s" %
(self.hostname, approved_hosts))
#
# CLASS JobUtils
#
class JobUtils:
def __init__(self, job, hostname=None, resources=None):
self.job = job
self.host_vnodes = list()
if hostname is not None:
self.hostname = hostname
else:
self.hostname = pbs.get_local_nodename()
if resources is not None:
self.host_resources = resources
else:
self.host_resources = self.__host_assigned_resources()
def __repr__(self):
return "JobUtils(%s, %s, %s)" % (repr(self.job), repr(self.hostname),
repr(self.host_resources))
# Return a dictionary of resources assigned to the local node
def __host_assigned_resources(self):
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Method called" % (caller_name()))
# Bail out if no hostname was provided
if self.hostname is None:
raise CgroupProcessingError('No hostname available')
# Bail out if no job information is present
if self.job is None:
raise CgroupProcessingError('No job information available')
# Determine which vnodes are on this host, if any
if self.hostname is not None:
vnhost_pattern = "%s\[[\d+]\]" % self.hostname
pbs.logmsg(pbs.EVENT_DEBUG, "%s: vnhost pattern: %s" %
(caller_name(), vnhost_pattern))
pbs.logmsg(pbs.EVENT_DEBUG, "%s: Job exec_vnode list: %s" %
(caller_name(), self.job.exec_vnode))
for match in re.findall(vnhost_pattern, str(self.job.exec_vnode)):
self.host_vnodes.append(match)
if self.host_vnodes is not None:
pbs.logmsg(pbs.EVENT_DEBUG,
"%s: Associate %s to vnodes on %s" %
(caller_name(), self.host_vnodes, self.hostname))
# Collect host assigned resources
resources = {}
for chunk in self.job.exec_vnode.chunks:
vnode = False
if self.host_vnodes == [] and chunk.vnode_name != self.hostname:
continue
elif self.host_vnodes != [] and \
chunk.vnode_name not in self.host_vnodes:
continue
elif chunk.vnode_name in self.host_vnodes:
vnode = True
if 'vnodes' not in resources:
resources['vnodes'] = {}
if chunk.vnode_name not in resources['vnodes']:
resources['vnodes'][chunk.vnode_name] = {}
# This check is needed since not all resources are
# required to be in each chunk of a job
# i.e. exec_vnodes =
# (node1[0]:ncpus=4:mem=4gb+node1[1]:mem=2gb) +
# (node1[1]:ncpus=3+node[0]:ncpus=1:mem=4gb)
if all(resc in resources['vnodes'][chunk.vnode_name]
for resc in chunk.chunk_resources.keys()):
pbs.logmsg(pbs.EVENT_DEBUG,
"%s: resources already defined" %
(caller_name()))
pbs.logmsg(pbs.EVENT_DEBUG, "%s: %s,\t%s" %
(caller_name(),
chunk.chunk_resources.keys(),
resources['vnodes'][chunk.vnode_name].keys()))
else:
# Initialize resources for each vnode
for resc in chunk.chunk_resources.keys():
# Initialize the new value
if isinstance(chunk.chunk_resources[resc],
pbs.pbs_int):
resources['vnodes'][chunk.vnode_name][resc] = \
pbs.pbs_int(0)
elif isinstance(chunk.chunk_resources[resc],
pbs.pbs_float):
resources['vnodes'][chunk.vnode_name][resc] = \
pbs.pbs_float(0)
elif isinstance(chunk.chunk_resources[resc], pbs.size):
resources['vnodes'][chunk.vnode_name][resc] = \
pbs.size('0')
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Chunk %s" %
(caller_name(), chunk.vnode_name))
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: resources: %s" %
(caller_name(), resources))
for resc in chunk.chunk_resources.keys():
if resc not in resources.keys():
# Initialize the new value
if isinstance(chunk.chunk_resources[resc], pbs.pbs_int):
resources[resc] = pbs.pbs_int(0)
elif isinstance(chunk.chunk_resources[resc],
pbs.pbs_float):
resources[resc] = pbs.pbs_float(0.0)
elif isinstance(chunk.chunk_resources[resc], pbs.size):
resources[resc] = pbs.size('0')
# Add resource value to total
if type(chunk.chunk_resources[resc]) in \
[pbs.pbs_int, pbs.pbs_float, pbs.size]:
resources[resc] += chunk.chunk_resources[resc]
pbs.logmsg(pbs.EVENT_DEBUG3,
"%s: resources[%s][%s] is now %s" %
(caller_name(), self.hostname, resc,
resources[resc]))
if vnode is True:
resources['vnodes'][chunk.vnode_name][resc] += \
chunk.chunk_resources[resc]
else:
pbs.logmsg(pbs.EVENT_DEBUG,
"%s: Setting resource %s to string %s" %
(caller_name(), resc,
str(chunk.chunk_resources[resc])))
resources[resc] = str(chunk.chunk_resources[resc])
if vnode is True:
resources['vnodes'][chunk.vnode_name][resc] = \
str(chunk.chunk_resources[resc])
if not resources:
pbs.logmsg(pbs.EVENT_DEBUG,
"%s: No resources assigned to host %s" %
(caller_name(), self.hostname))
else:
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Resources for %s: %s" %
(caller_name(), self.hostname, repr(resources)))
# Return assigned resources for specified host
pbs.logmsg(pbs.EVENT_DEBUG3, "Job Resources: %s" % (resources))
return resources
# Write a message to the job stdout file
def write_to_stderr(self, job, msg):
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Method called" % (caller_name()))
try:
filename = job.stderr_file()
if filename is None:
return
fd = open(filename, 'a')
fd.write(msg)
except Exception, exc:
pass
# Write a message to the job stdout file
def write_to_stdout(self, job, msg):
pbs.logmsg(pbs.EVENT_DEBUG3, "%s: Method called" % (caller_name()))
try:
filename = job.stdout_file()
if filename is None:
return
fd = open(filename, 'a')
fd.write(msg)
except Exception, exc:
pass
#
# CLASS NodeConfig
#
class NodeConfig:
def __init__(self, cfg, **kwargs):
self.cfg = cfg
hostname = None
meminfo = None
numa_nodes = None
devices = None
hyperthreading = None
self.hyperthreads_per_core = 1
self.totalcpus = self.__discover_cpus()
pbs_home = ''
if not CRAY_12_BRANCH:
pbs_conf = pbs.get_pbs_conf()
pbs_home = pbs_conf['PBS_HOME']
else:
if 'PBS_HOME' in self.cfg:
pbs_home = self.cfg['PBS_HOME']
else:
pbs.logmsg(pbs.EVENT_DEBUG,
"PBS_HOME needs to be defined in the config file")
pbs.logmsg(pbs.EVENT_DEBUG,
"Exiting the cgroups hook")
pbs.event().accept()
self.host_mom_jobdir = pbs_home+'/mom_priv/jobs'
if kwargs:
for arg, val in kwargs.items():
if arg == 'cfg':
cfg = val
elif arg == 'hostname':
hostname = val
elif arg == 'meminfo':
meminfo = val
elif arg == 'numa_nodes':
numa_nodes = val
elif arg == 'devices':
devices = val
elif arg == 'hyperthreading':
hyperthreading = val
if hostname is not None:
self.hostname = hostname
else:
self.hostname = pbs.get_local_nodename()
if meminfo is not None:
self.meminfo = meminfo
else:
self.meminfo = self.__discover_meminfo()
if numa_nodes is not None:
self.numa_nodes = numa_nodes
else:
self.numa_nodes = self.__discover_numa_nodes()
if devices is not None:
self.devices = devices
else:
self.devices = self.__discover_devices()
if hyperthreading is not None:
self.hyperthreading = hyperthreading
else:
self.hyperthreading = self.__hyperthreading_enabled()
self.totalcpus = self.totalcpus / self.hyperthreads_per_core
# Add the devices count i.e. nmics and ngpus to the numa nodes
self.__add_devices_to_numa_node()
def __repr__(self):
return ("NodeConfig(%s, %s, %s, %s, %s, %s)" %
(repr(self.cfg), repr(self.hostname), repr(self.meminfo),
repr(self.numa_nodes), repr(self.devices),