forked from mfisk/filemap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fm
executable file
·3846 lines (3119 loc) · 129 KB
/
fm
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
#
# FileMap - http://mfisk.github.com/filemap
#
# Public Domain License:
#
# This program was prepared by Los Alamos National Security, LLC at
# Los Alamos National Laboratory (LANL) under contract
# No. DE-AC52-06NA25396 with the U.S. Department of Energy (DOE). All
# rights in the program are reserved by the DOE and Los Alamos
# National Security, LLC. Permission is granted to the public to copy
# and use this software without charge, provided that this Notice and
# any statement of authorship are reproduced on all copies. Neither
# the U.S. Government nor LANS makes any warranty, express or implied,
# or assumes any liability or responsibility for the use of this
# software.
#
# Author: Mike Fisk <mfisk@lanl.gov>
#
import ConfigParser
import copy
import base64
import bisect
import cPickle
import cStringIO
import errno
import fcntl
import glob
import grp
import gzip
import itertools
import math
import optparse
import os
import pwd
import pydoc
import random
import re
import select
import shlex
import shutil
import signal
import socket
import stat
import string
import subprocess
import sys
import tempfile
import time
import traceback
import urlparse
try:
import hashlib # New for python 2.5
sha = hashlib.sha1
except:
import sha
sha = sha.sha
# Globals
Verbose = 0
RegressionTest = False
Locations = None
ConfigApply = {
"ssh": os.path.expanduser,
"syncdir": os.path.expanduser,
"rootdir": os.path.expanduser,
"python": os.path.expanduser,
"fm": os.path.expanduser,
"share": float,
"cpusperjob": int,
"processes": int,
"dynamicload": float,
}
ConfigDefaults = {
"ssh": "ssh -o GSSAPIDelegateCredentials=yes -o ConnectTimeout=5 -o StrictHostKeyChecking=no -Ax",
"rsync": "rsync -tO",
"share": "1",
"syncdir": "/tmp/fmsync",
"python": "python",
"processes": "1000",
"dynamicload": "2",
"inactive": False,
"queuebyhost": False,
"hostname": None,
"cpusperjob": "1",
}
try:
select.poll
except:
print >>sys.stderr, "select.poll() not implemented. If MacOS, use DarwinPorts python."
sys.exit(1)
nonalphanumre = re.compile('\W')
def dictListAppend(map, key, value):
if not map.has_key(key):
map[key] = [value]
else:
map[key].append(value)
def printableHash(s):
h = sha(s).digest()
h = base64.b64encode(h, '+_') # Normal b64 but / is _
h = h.rstrip('\n\r =')
return h
me = socket.gethostname().split('.')[0]
def isremote(hname):
if not hname:
return False
hname = hname.split('.')[0]
if me == hname:
return False
else:
return True
nonalphanumre = re.compile('[^\w\.\-]')
def escape(s):
(s, num) = nonalphanumre.subn(lambda m: "=%02X" % ord(m.group()), string.join(s))
return s
quoprire = re.compile('=([0-9a-fA-F]{2})')
def lsUnescapeChr(m):
c = m.group(1).decode('hex')
if c == '/':
c = '\\/'
if c == '\\':
c = '\\\\'
return c
def tabulate(lst, width, ncols=None):
if not lst:
return None
smallest = min([len(l) for l in lst])
if ncols == None:
# Initial case, start with each column being as wide as narrowest element
ncols = (width+2) / (smallest+2)
ncols = max(1, ncols)
# See if we can build a table with this many columns
minwidths = [smallest] * ncols
nrows = int(math.ceil(len(lst)*1.0 / ncols))
for c in range(0, ncols):
colwidth = minwidths[c]
for r in range(0, nrows):
i = c * nrows + r
if i > (len(lst)-1): break
lel = len(lst[c*nrows + r])
if lel > colwidth:
colwidth = lel
minwidths[c] = lel
# But expanding this one may mean we can have fewer columns
startcol = c
if ncols > 1 and (sum(minwidths) + 2*len(minwidths)) > (width+2):
return tabulate(lst, width, ncols-1)
# If we got here, then the sizes fit!
for r in range(0, nrows):
line = []
for c in range(0, ncols):
i = c*nrows + r
if i > (len(lst)-1):
break
line.append("%-*s" % (minwidths[c], lst[i]))
line = string.join(line, ' ')
line = line.rstrip()
print line
def rewriteList(lst, f):
"""Apply a function to each element in a list.
If the function returns None, use the original item.
If the function returns a Tuple, replace with _contents_ of tuple.
Else replace the element with what the function returns.
"""
ret = []
for l in lst:
out = f(l)
if out == None:
ret.append(l)
elif type(out) == type(()):
for i in out:
ret.append(i)
else:
ret.append(out)
return ret
if RegressionTest:
def rewriteTest(item):
if item == 1: return 2
if item == 2: return 'a','b'
if item == 3: return ['a', 'b']
if item == 4: return ()
return
assert( rewriteList([1,2,3,4,5], rewriteTest1) == [2, 'a', 'b', ['a', 'b'], 5])
def collapseIntervals(lst):
"""Take list of (start,end) interval tuples and return a similar list with all overlapping intervals combined."""
intervals = []
for (sstart,send) in lst:
found = False
for i in range(0, len(intervals)):
(start,end) = intervals[i]
if (sstart <= end and send > end) or (send >= start and sstart < start):
# Expand interval (note this may make this interval overlap with one of the ones already in the list)
start=min(start,sstart)
end=max(end,send)
#print >>sys.stderr, "Changing", intervals[i], "to", (start,end)
intervals[i] = (start,end)
found = True
break
elif send <= end and start >=start:
# Already encompassed
found = True
if not found:
# Add new interval to list
intervals.append((sstart,send))
#print >>sys.stderr, "Adding", (sstart,send), intervals
# Repeat until no more merges left
while lst != intervals:
lst = intervals
intervals = collapseIntervals(lst)
return intervals
if RegressionTest:
assert(collapseIntervals([(1,3), (2,4), (2,3), (1,4), (0,2), (5,6), (4,4.5)]) == [(0,4.5), (5,6)])
def tallyStats(statlist, starttime, wallclock, nodecount):
# Tally the stats
errcodes = {}
wtime = [0.0, 0.0]
utime = [0.0, 0.0]
stime = [0.0, 0.0]
bytes = [0.0, 0.0]
nodewtime = [{}, {}]
nodebytes = [{}, {}]
allstats = []
maxend = 0
minstart = starttime
for stats in statlist:
ec = os.WEXITSTATUS(stats['status'])
errcodes[ec] = errcodes.get(ec, 0) + 1
if stats['timestamp'] < starttime:
cached = 1
else:
cached = 0
wtime[cached] += stats['time']
utime[cached] += stats['utime']
stime[cached] += stats['stime']
bytes[cached] += stats['inputsize']
minstart = min(minstart, stats['timestamp'] - stats['time'])
maxend = max(maxend, stats['timestamp'])
nodename = stats['nodename']
nodewtime[cached][nodename] = nodewtime[cached].get(nodename, 0) + stats['time']
nodebytes[cached][nodename] = nodebytes[cached].get(nodename, 0) + stats['inputsize']
# Print out summary info
errstr = ''
for k in errcodes.keys():
if not errstr:
errstr = "%d processes returned %d" % (errcodes[k], k)
else:
errstr += "; %d x %s" % (errcodes[k], k)
if not errstr:
errstr = 'No processes completed'
print >>sys.stderr, errstr
if Verbose > 0:
for n in nodebytes[0]:
if nodewtime[0][n]:
print >>sys.stderr, "Node %s %s/s new work" % (n, bytecount2str(nodebytes[0][n]/nodewtime[0][n]))
swtime = sum(wtime)
if swtime:
sbytes = sum(bytes)
sutime = sum(utime)
sstime = sum(stime)
print >>sys.stderr, "Serial performance: %s, %s/s, %s (%.0f%% User, %.0f%% System, %.0f%% Wait)" \
% (bytecount2str(sbytes), bytecount2str(sbytes/swtime), seconds2human(swtime), 100*sutime/swtime, 100*sstime/swtime, 100*(swtime-sstime-sutime)/swtime)
if bytes[0] and wallclock:
rate = bytecount2str(bytes[0]/wallclock)
scaling = (stime[0]+utime[0])/wallclock
print >>sys.stderr, "New: %s/s, %.1f/%dx CPU scaling." % (rate, scaling, nodecount)
# Find intervals we were computing over
intervals = [(s['timestamp'] - s['time'], s['timestamp']) for s in statlist]
intervals = collapseIntervals(intervals)
#print >>sys.stderr, intervals
if bytes[1]:
# Find intervals that were before starttime (cached)
cacheduration = 0
for (start,end) in intervals:
if end < starttime:
cacheduration += (end-start)
if cacheduration:
rate = bytecount2str(bytes[1]/cacheduration)
scaling = swtime/cacheduration
print >>sys.stderr, "Cached: %s/s, %s, %.1fx" % (rate, seconds2human(cacheduration), scaling)
if sbytes and wallclock:
rate = bytecount2str(sbytes/wallclock)
cached = 100*bytes[1]/sbytes
print >>sys.stderr, "Filemap: %s/s, %.1fs, %.0f%% cached." % (rate, wallclock, cached)
def mkdirexist(path):
try:
os.makedirs(path)
except OSError, e:
if e.errno == errno.EEXIST:
pass
else:
raise
def coallesce(outputs, labels):
"""Take a list of multi-line strings and an equally long list of labels and return a string summarizing which labels had what output."""
assert(len(outputs) == len(labels))
sameas = {}
result = ""
for i in range(0, len(outputs)):
if outputs[i]:
header = [labels[i]]
for j in range(i+1, len(outputs)):
if outputs[j] and outputs[i].getvalue() == outputs[j].getvalue():
header.append(labels[j])
outputs[j] = None
header.sort(cmp=numcmp)
header = string.join(header, ',')
header += ": "
for line in outputs[i]:
result += header + line
return result
def multiglob(globs):
"""Take a list of globs and return a list of all of the files that match any of those globs."""
assert(type(globs) == type([]))
ret = []
for g in globs:
ret += glob.glob(g)
return ret
num_re = re.compile('^(([\D]+)|(\d+))')
def numcmptokenize(x):
xlist = []
while x:
xn = num_re.match(x)
if not xn:
return x
xlen = len(xn.group(0))
token = x[:xlen]
try:
token = int(token)
except:
pass
xlist.append(token)
x = x[xlen:]
return xlist
def numcmp(x, y):
"""Determine order of x and y (like cmp()), but with special handling for
strings that have non-numeric and/or numeric substrings. Numeric
substrings are ordered numerically even if they have differing numbers
of digits."""
# Turn each input in to a tokenized list that we can cmp() natively
xlist = numcmptokenize(x)
ylist = numcmptokenize(y)
r = cmp(xlist, ylist)
return r
def statOverlap(joba, jobb):
"""Return true iff duration of joba does not overlap with duration of jobb."""
if jobb['start'] > joba['finish'] or joba['start'] > jobb['finish']:
return False
return True
def makeVnodes(nodes):
# We may have multiple jobs at a time per node (e.g. SMP nodes), so
# treat those as multiple nodes. Since we don't have an explicit thread id,
# just assign them arbitrarily in a non-overlapping way
newnodes = {}
for nodename in nodes.keys():
vnodes = []
nodes[nodename].sort(lambda a,b: cmp(a['start'], b['start']))
for job in nodes[nodename]:
found = False
for vnode in vnodes:
if not statOverlap(job, vnode[-1]):
# Does not overlap with last job in this vnode, so append it here
vnode.append(job)
found = True
break
if not found:
# Make new node
vnodes.append([job])
#print "now", vnodes
if len(vnodes) < 2:
# It was serial, so no virtual nodes required
continue
#print "Replacing", nodename, "with", len(vnodes)
for i in range(0, len(vnodes)):
newnodes[nodename + ";" + str(i)] = vnodes[i]
#print nodes.keys()
return newnodes
def plot(inputfile, pngfile, options):
import matplotlib.figure
import matplotlib.collections
import matplotlib.backends.backend_agg
stats = cPickle.load(inputfile)
inputfile.close()
# Load all stats and keep track of min and max inputsizes along the way
nodes = {}
jobs = set()
filenames = {}
minsize = 2**31
mintime = 2**31
maxsize = 0
maxtime = 0
totalsize = 0
nodename = 'nodename'
if options.group_host:
nodename = 'hostname'
for s in stats:
s['start'] = s['timestamp'] - s['time']
s['finish'] = s['timestamp']
if not nodes.get(s[nodename]):
nodes[s[nodename]] = []
nodes[s[nodename]].append(s)
minsize = min(minsize, s['inputsize'])
maxsize = max(maxsize, s['inputsize'])
mintime = min(mintime, s['start'])
maxtime = max(maxtime, s['finish'])
totalsize += s['inputsize']
if 'cmd' not in s:
s['cmd'] = s['jobname']
jobs.add(s['cmd'])
# Reduce to overlapping windows
stats.sort(lambda a,b: cmp(a['start'], b['start']))
intervals = [(i['start'], i['finish']) for i in stats]
intervals = collapseIntervals(intervals)
active = sum([i[1] - i[0] for i in intervals])
gaps = []
if intervals:
prev = intervals.pop(0)
for i in intervals:
# If more than 10% of the total duration is skipped here, then edit it out
if i[0] - prev[1] > 0.1*(active):
# A noticeable gap occurs between these
gaps.append((prev[1], i[0]))
#print >>sys.stderr, "Gap between", prev[1], i[0]
prev = i
nodes = makeVnodes(nodes)
if Verbose > 1:
print >>sys.stderr, "Data spans", seconds2human(maxtime-mintime), "with", seconds2human(active), "active"
print >>sys.stderr, "Packed into", len(nodes), "timelines"
jobs = list(jobs)
if Verbose > 2:
print >>sys.stderr, "Assigning colors to", len(jobs), "jobs"
colormap = ['red','green','blue','cyan','magenta','black','yellow','purple']
color = {}
for j in jobs:
color[j] = jobs.index(j)
color[j] = colormap[color[j] % len(colormap)]
if Verbose > 1:
print >>sys.stderr, "Job %s %s" % (color[j],j)
nodenames = nodes.keys()
nodenames.sort(cmp=numcmp)
# Build map of nodenames to y coordinates
nodes2y = {}
i = 0
for n in nodenames:
nodes2y[n] = i
i += 1
fig = matplotlib.figure.Figure(figsize=(8,10.5))
ax = fig.add_subplot(111)
ax.set_autoscale_on(True)
lines = []
if not maxsize:
maxsize = 0
else:
maxsize = math.log(maxsize)
if not minsize:
minsize = 0
else:
minsize = math.log(minsize)
for node in nodenames:
y = nodes2y[node]
if Verbose > 2:
print >>sys.stderr, "Plotting line", node, "with", len(nodes[node]), "elements"
for s in nodes[node]:
finish = s['finish']
start = s['start']
# Size is a log-scale number between 0 and 1 where 0 is the minimum size seen in this run and 1 is the max size seen in this run
insize = s['inputsize']
if insize:
insize = math.log(insize)
else:
insize = 0
size = (insize-minsize)/(maxsize-minsize)
size = size * 0.7 + 0.3 #Makem min size be 30%
# CPU is % of wallclock time in user or system CPU time
if s['time'] == 0:
cpu = 1
else:
cpu = (s['utime'] + s['stime']) / s['time']
# Adjust for time gaps
delta = 0
for g in gaps:
if g[1] < start:
delta += g[1] - g[0]
if options.redundant:
filenames.setdefault(s['statusfile'],-1)
filenames[s['statusfile']] += 1
ax.broken_barh([(start-mintime-delta, finish-start)], [y-0.5*size,size], alpha=(1.0*filenames[s['statusfile']])/len(colormap), lw=0, color=colormap[min(len(colormap), filenames[s['statusfile']])])
else:
ax.broken_barh([(start-mintime-delta, finish-start)], [y-0.5*size,size], alpha=0.3+cpu, lw=0, color=color[s['cmd']])
#ax.errorbar(finish, y, yerr=1, fmt=None, elinewidth=(1 + 2*size), color=color[s['jobname']])
ax.autoscale_view()
xticks = [0]
xlabels = [0]
delta = 0
for g in gaps:
xticks.append(g[0] - delta - mintime)
xlabels.append(seconds2human(g[1]-g[0]) + " idle")
delta += g[1] - g[0]
xticks.append(maxtime-mintime-delta)
xlabels.append(seconds2human(maxtime-mintime-delta))
ax.set_xlim(xmin=0, xmax=maxtime-mintime-delta)
ax.set_xticks(xticks)
ax.set_xticklabels(xlabels, rotation=30, ha='right')
#matplotlib.rc('xtick', labelsize=
majorlabels = []
majorlocs = []
minorlabels = []
minorlocs = []
majors = []
for n in nodenames:
if n.endswith(";0"):
name = n[:-2]
if "." in n:
major,minor = name.split(".", 1)
else:
major = name
minor = None
if major in majors:
if minor:
minorlabels.append("." + minor)
minorlocs.append(nodes2y[n])
else:
minorlabels.append(name)
minorlocs.append(nodes2y[n])
else:
majors.append(major)
majorlabels.append(name)
majorlocs.append(nodes2y[n])
#print >>sys.stderr, "Yticks", majorlocs, majorlabels
ax.set_yticks(majorlocs)
ax.set_yticklabels(majorlabels, size=6)
ax.set_yticks(minorlocs, minor=True)
ax.set_yticklabels(minorlabels, size=4, minor=True)
ax.set_ylim(ymin=-2, ymax=len(nodenames)+2)
ax.set_title("%s processed" % (bytecount2str(totalsize)))
canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(fig)
canvas.print_figure(pngfile, antialias=False, dpi=600)
def bytecount2str(n):
unit = 'B'
units = ['kB', 'MB', 'GB', 'TB', 'PB']
while n >= 1000 and len(units):
n /= 1000.0
unit = units.pop(0)
return ("%3.1f" % n) + ' ' + unit
def seconds2human(s):
if s < 60:
return "%.0fs" % s
if s < 3600:
return "%.0fm" % (s/60.)
if s < 86400:
return "%.1fh" % (s/3600.)
if s < 864000:
return "%.1fd" % (s/86400.)
else:
return "%.1fwk" % (s/604800.)
class MethodOptionParser(optparse.OptionParser):
"""OptionParser to be instantiated by dispatch methods of a class. Sets %prog to be the calling function name and epilog to be the doc string for that function. Also prints options in usage string more like man conventions instead of just [options]."""
def __init__(self, *args, **kwargs):
if not kwargs.has_key('epilog'):
caller = sys._getframe(1)
pmethod = caller.f_code.co_name
pself = caller.f_locals['self']
method = pself.__class__.__dict__[pmethod]
kwargs['prog'] = pmethod
self.Epilog = method.__doc__ or ""
if kwargs.has_key('fixed'):
self.fixed = kwargs['fixed']
del kwargs['fixed']
else:
self.fixed = None
self.numrequired = 0
if self.fixed:
for i in self.fixed:
if i[0] != "[":
self.numrequired += 1
optparse.OptionParser.__init__(self, *args, **kwargs)
self.disable_interspersed_args()
def parse_args(self, args):
(options, args) = optparse.OptionParser.parse_args(self, args)
if len(args) < self.numrequired:
print >>sys.stderr, "Required argument(s) missing"
self.print_help()
sys.exit(1)
return (options, args)
def get_usage(self):
if self.fixed != None:
flags = []
options = ''
for o in self.option_list:
if o.action == 'store_true':
flags += o._short_opts[0].lstrip('-')
elif o.action == 'help':
pass
else:
options += "[%s %s]" % (o._short_opts[0], o._long_opts[0].lstrip('-').upper())
if o.action == 'append':
options += '...'
options += ' '
flags = string.join(flags, '')
if flags:
options += "[-" + flags + "] "
self.usage = "%prog " + options + string.join(self.fixed)
return optparse.OptionParser.get_usage(self)
def print_help(self):
r = optparse.OptionParser.print_help(self)
# For python < 2.5, we have to print our own epilog
print
print self.Epilog
return r
class SmartDict(dict):
def __getattr__(self, name):
try:
return self[name]
except KeyError, e:
raise AttributeError(e)
def __setattr__(self, name, value):
self[name] = value
class FmLocations:
def __init__(self, copyFrom=None, locs={}, slave=False):
self.procs = None
self.locker = None
self.cleanup = None
self.cached_dstnodes = {}
if copyFrom and not slave:
assert(locs)
self.config = copy.deepcopy(copyFrom.config)
self.config.locs = locs
self.procs = copyFrom.procs
self.locker = copyFrom.locker
#self.thisis(copyFrom.thisname)
elif slave:
assert(copyFrom)
self.config = copyFrom.config
self.thisis(slave)
# Keep a copy of the config around so our children (like redistribute) can reference it
fd, name = tempfile.mkstemp(prefix="tmp-fm-locations-", suffix=".pickle")
#print >>sys.stderr, "locations is", name
self.cleanup = name
os.environ['FMCONFIG'] = name
fh = os.fdopen(fd, 'w')
fh.write(cPickle.dumps(self.config))
fh.close()
else:
self.config = SmartDict() # like a named tuple but for older python
self.config.locs = {}
filename = os.environ.get('FMCONFIG')
#print >>sys.stderr, "Env filename is", filename
if not filename:
if os.path.isfile("filemap.conf"):
filename = "filemap.conf"
elif os.path.isfile(os.path.expanduser("~/.filemap.conf")):
filename = os.path.expanduser("~/.filemap.conf")
else:
filename = "/etc/filemap.conf"
os.environ['FMCONFIG'] = filename
try:
fh = open(filename)
except:
raise Exception("Unable to locate config file. Set FMCONFIG or place filemap.conf in . or /etc")
if filename.endswith('.pickle'):
self.config = cPickle.load(fh)
else:
self.parseConfigFile(fh)
#self.thisis('global')
if self.config.pathextras:
os.environ['PATH'] += ":" + self.config.pathextras
if self.config.environ:
for pair in self.config.environ.split():
k,v = pair.split('=')
os.environ[k] = v
if self.config.umask:
os.umask(self.config.umask)
if not self.locker:
self.locker = FileSynchronizer(self)
if not self.procs:
self.procs = Procs()
def parseConfigFile(self, fh):
"""Populate self.config from config file."""
# Read from file
self.configparser = ConfigParser.SafeConfigParser()
#print >>sys.stderr, "Reading config", filename, self.configparser.sections()
self.configparser.readfp(fh)
self.config.replication = int(self.config_get("global", "replication", "1"))
#All-to-all can hit sshd's MaxStartups limit, so retry a lot
self.config.all2all_retries = int(self.config_get("global", "all2all_retries", "7"))
self.config.slurmfe = self.config_get("global", "slurmfe", None)
if self.config.slurmfe == "localhost":
self.config.slurmfe = "sh -c"
self.config.umask = int(self.config_get("global", "umask", "0002"))
self.config.pathextras = self.config_get("global", "pathextras")
self.config.environ = self.config_get("global", "environ")
# Unless we were passed an explicit list of locations, grab all
# from the config file.
if not self.config.locs:
nl = self._getSlurmNodes(self)
for s in self.configparser.sections():
if s == "global":
continue
r = self._expandList(s)
for (vals,name) in r:
self.parseLocation(s, name=name, listvalues=vals)
# Use global config values by default (thisis() can override later)
self.parseLocation("global")
# Once all config files settings are imported, pre the location for use (apply defaults, etc.)
for l in self.config.locs.values():
self.prepLocation(l)
if nl:
# Check SLURM_JOB_NODELIST to make sure we've been allocated this node
if l.hostname not in nl:
l.inactive = True
#print "Marking", l.name, "inactive per SLURM", l.hostname, nl
# Also prep the global section
self.prepLocation(self.this)
def _getSlurmNodes(self, alloc=True):
nl = os.environ.get("SLURM_JOB_NODELIST")
if not nl and not self.config.slurmfe:
# Must not be running under SLURM
return None
if not nl:
nl = subprocess.Popen(self.config.slurmfe.split() + ["squeue -t RUNNING -u $USER -o %i/%j/%N"], stdout=subprocess.PIPE, stdin=None)
for line in nl.stdout:
line = line.strip()
(id,name,nl) = line.split('/')
#print >> sys.stderr, "SLURM jobid", id, name, nl
if name != "FM":
nl = None
continue
os.environ["SLURM_JOB_NODELIST"] = nl
os.environ["SLURM_JOB_ID"] = str(id)
#print >> sys.stderr, "SLURM jobid", id, nl
break
if not nl:
if alloc:
if Verbose > 0: print >>sys.stderr, "Starting new FM job in SLURM"
subprocess.Popen(self.config.slurmfe.split() + ["salloc -k -J FM --nodes 1-9999 --overcommit --share --ntasks-per-node 2 --no-shell"], stdout=sys.stdout, stderr=sys.stderr, stdin=None).wait()
return self._getSlurmNodes(alloc=False)
else:
print >>sys.stderr, "Unable to find or start FM job found in SLURM"
sys.exit(2)
assert(nl)
# Check SLURM_JOB_NODELIST to make sure we've been allocated this node
if Verbose > 0: print >>sys.stderr, "Active SLURM nodes: ", nl
nl = self._expandList(nl)
nl = [i[1] for i in nl]
return nl
def __del__(self):
if self.cleanup:
os.unlink(self.cleanup)
def _expandList(self, liststr, values=[]):
"""Returns a list of tuples where each tuple contains a list of 0 or more interval values and the resulting string from those values."""
#Support () or [] syntax for SLURM or ConfigParser cases
range_re = re.compile("([^\(\[]*)[\(\[]([^\)\]]*)[\)\]](.*)$")
r = range_re.match(liststr)
if not r:
return [(values, liststr)]
prefix = r.group(1)
lst = r.group(2)
expanded = []
suffix = r.group(3)
first = None
for interval in lst.split(","):
if "-" in interval:
(min,max) = interval.split("-")
expanded += range(int(min), int(max)+1)
if not first: first = min
else:
#singleton
expanded.append(interval)
if not first: first = interval
# First is the first example node number string.
# It may be padded with leading zeros, the following will preserve that formatting:
# Recrusively try expanding each result (which may have a second list in it) and flatten the resulting lists
ret = []
for i in expanded:
ret += self._expandList(prefix + first[:-len(str(i))] + str(i) + suffix, values+[i])
return ret
def parseLocation(self, stanza, name=None, listvalues=[]):
if name:
nodename = str(name)
else:
nodename = str(stanza)
# Reuse (add attributes to) existing Location if we already saw this nodename
l = self.config.locs.get(nodename)
if not l:
l = FmLocation()
if stanza != "global":
self.config.locs[nodename] = l
else:
self.this = l # Assume by default that we're the head node and use global defaults
l.name = nodename
l.config = {}
l.listvalues = listvalues
# Import all configparser settings into a dictionary
for opt,val in self.configparser.items(stanza, raw=True):
l[opt] = val
def prepLocation(self, l):
# Inherit all global defaults if not over-ridden
for k,v in self.configparser.items("global", raw=True):
if not l.has_key(k):
l[k] = v
# Inherit all hard-coded defaults if not over-ridden
for k,v in ConfigDefaults.items():
if not l.has_key(k):
l[k] = v
# Apply conversion/expansion functions
for k,f in ConfigApply.items():
if l.has_key(k):
l[k] = f(l[k])
l.sshcmd = shlex.split(l.ssh, comments=True)
l.rsynccmd = shlex.split(l.rsync, comments=True)
l.rsynccmd[0] = os.path.expanduser(l.rsynccmd[0])
if l.name != "global":
if l.values:
#if '%' not in l.hostname:
#print >>sys.stderr, "Warning %s does not reference given instance %s" % (l.hostname, str(l.values))
l.hostname = l.hostname.format(*l.listvalues)
l.rootdir = l.rootdir.format(*l.listvalues)
l.jobdir = l.rootdir + "/jobs"
if l.queuebyhost:
l.qname = l.hostname
else:
l.qname = l.name
if 'fm' not in l:
l.fm = l.rootdir + "/sys/fm"
l.fmcmd = [l.python, l.fm]
def config_get(self, section, key, defval=None, raw=False, merge=False, expanduser=False):
if self.configparser.has_option(section, key):
val = self.configparser.get(section, key, raw=raw)
elif merge:
# Use previous value
pass
else:
if self.configparser.has_option("global", key):
val = self.configparser.get("global", key, raw=raw)
else:
val = defval