forked from mattjr/structured
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runtp_dist.py
executable file
·228 lines (198 loc) · 7.19 KB
/
runtp_dist.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
#!/usr/bin/env python
# structured - Tools for the Generation and Visualization of Large-scale
# Three-dimensional Reconstructions from Image Data. This software includes
# source code from other projects, which is subject to different licensing,
# see COPYING for details. If this project is used for research see COPYING
# for making the appropriate citations.
# Copyright (C) 2013 Matthew Johnson-Roberson <mattkjr@gmail.com>
#
# This file is part of structured.
#
# structured is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# structured 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with structured. If not, see <http://www.gnu.org/licenses/>.
# -*- coding: utf-8 -*-
# structured - Tools for the Generation and Visualization of Large-scale
# Three-dimensional Reconstructions from Image Data. This software includes
# source code from other projects, which is subject to different licensing,
# see COPYING for details. If this project is used for research see COPYING
# for making the appropriate citations.
# Copyright (C) 2013 Matthew Johnson-Roberson <mattkjr@gmail.com>
#
# This file is part of structured.
#
# structured is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# structured 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with structured. If not, see <http://www.gnu.org/licenses/>.
from threadpool_dist import *
from progressbar import *
from time import sleep
from random import random
import sys
import os
import thread
import commands
import string
import random
import re
import getpass
def detectCPUs():
"""
Detects the number of CPUs on a system. Cribbed from pp.
"""
# Linux, Unix and MacOS:
if hasattr(os, "sysconf"):
if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
# Linux & Unix:
ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
if isinstance(ncpus, int) and ncpus > 0:
return ncpus
else: # OSX:
return int(os.popen2("sysctl -n hw.ncpu")[1].read())
# Windows:
if os.environ.has_key("NUMBER_OF_PROCESSORS"):
ncpus = int(os.environ["NUMBER_OF_PROCESSORS"]);
if ncpus > 0:
return ncpus
return 1 # Default
main = ThreadPool(0)
if len(sys.argv) > 3:
title = sys.argv[3]
else:
title = 'Cmds: '
if len(sys.argv) > 2:
try:
cfgfile = open(sys.argv[2], 'r')
except IOError:
print 'Cannot open file %s for reading. Check file exists and try again.' % sys.argv[2]
sys.exit(0)
for line in cfgfile:
words = string.split(line, ' ')
if len(words) >= 2:
if(words[0] == 'LOCAL'):
main.createWorkersLocal(int(words[1]))
print 'ThreadPool spawning %d local threads' % len(main.workers)
elif(words[0] == 'REMOTE'):
main.createWorkersRemote(int(words[1]),words[2])
print 'ThreadPool spawning %d remote threads on %s' % (int(words[1]),words[2])
elif(words[0] == 'SLURM'):
if len(words) == 4:
main.createWorkersSLURM(int(words[1]),words[2],words[3],title=title)
print 'ThreadPool spawning %d slurm threads using host %s' % (int(words[1]),words[3])
else:
main.createWorkersSLURM(int(words[1]),words[2],title=title)
print 'ThreadPool spawning %d slurm threads all hosts' % (int(words[1]))
else:
print 'Must pass cfg file'
sys.exit(0)
print 'ThreadPool spawning %d total threads' % len(main.workers)
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
def runcmd_threadpool(cm,runwith):
shell = 'bash'
#runwith ='ssh auv@archipelago srun /bin/bash '
if len(runwith) > 0:
match = re.search('([\w.-]+)@([\w.-]+)', runwith)
if match:
username = match.group(1)
curruser = getpass.getuser()
if curruser != username:
reps = {curruser:username}
cm = replace_all(cm, reps)
cmd= '%s "%s -c \'%s\' "' % (runwith[:-1],shell,cm[:-1])
else:
cmd= '%s -c \'%s\' ' % (shell,cm[:-1])
s,o = commands.getstatusoutput(cmd)
if s != 0:
print 'problem running: ', cmd
print 'output : ',o
errfn='./%s/%d-cmd-%03d.txt'% ('.',os.getpid(),random.random())
print 'wrote log to %s ' % errfn
f = open(errfn, 'w')
f.write( 'problem running: %s' % cmd)
f.write('output : %s' % o)
f.close()
return 0
# this will be called each time a result is available
def print_result(request, result):
pbar.inc()
# this will be called when an exception occurs within a thread
# this example exception handler does little more than the default handler
def handle_exception(request, exc_info):
if not isinstance(exc_info, tuple):
# Something is seriously wrong...
print request
print exc_info
raise SystemExit
print "**** Exception occured in request #%s: %s" % \
(request.requestID, exc_info)
class Curr(ProgressBarWidget):
"Just the percentage done."
def update(self, pbar):
return '%03d' % pbar.currval
class Max(ProgressBarWidget):
"Just the percentage done."
def update(self, pbar):
return '%03d' % pbar.maxval
fname = sys.argv[1];
cmd_counter = 0
widgets = [title, ' ',Percentage(), ' ',Curr(),'/',Max(),' ', Bar(),
' ', ETA()]
dir,end = os.path.split(fname)
try:
cmdfile = open(fname, 'r')
except IOError:
print 'Cannot open file %s for reading. Check file exists and try again.' % fname
sys.exit(0)
total=0
i=0
total=sum(1 for line in cmdfile)
cmdfile.close()
cmdfile = open(fname, 'r')
pbar = ProgressBar(widgets=widgets, maxval=total)
pbar.start()
data = []
for line in cmdfile:
data.append(line)
# runcmd_threadpool(line,i,total,dir)
i=i+1;
requests = makeRequests(runcmd_threadpool, data, print_result, handle_exception)
for req in requests:
main.putRequest(req)
# print "Work request #%s added." % req.requestID
pbar.start()
main.wait()
pbar.finish()
print ''
f = open('timing.txt', 'a')
f.write('%s %f\n' % (title,pbar.seconds_elapsed))
f.close()
#@threaded
#def test_threaded(i):
# print 'threaded %i enter' % i
# sleep(random())
# print 'threaded %i exit' % i
#print 'threaded example'
#for i in range(5):
# test_threaded(i)
#print 'done'