-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdagr.py
335 lines (256 loc) · 8.09 KB
/
dagr.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
#!/usr/bin/env python3
####################
# Node
class DagrNode(object):
nodes_by_name = dict()
def __init__(self, name, parents=[], cmd=None):
self.name = name
self.parents = set(parents)
assert name not in DagrNode.nodes_by_name
DagrNode.nodes_by_name[name] = self
self.cmds = []
if cmd:
self.cmds.append(cmd)
return
####################
# Traverse!
DAGR_FILENAME = '.dagr'
with open(DAGR_FILENAME) as f:
code = compile(f.read(), DAGR_FILENAME, 'exec')
exec(code)
####################
# Now include
import multiprocessing
import shlex
import subprocess
import sys
import threading
import time
####################
# Privates
class Task(object):
def __init__(self, target, args=(), kwargs={}):
self.target = target
self.args = args
self.kwargs = kwargs
def run(self):
self.target(*self.args, **self.kwargs)
class ThreadPool(object):
def __init__(self, name, num_threads):
self.name = name
self.cond = threading.Condition()
self.is_alive = True
self.task_queue = []
self.threads = set()
for i in range(num_threads):
t_name = '{}[{}]'.format(self.name, i)
t = threading.Thread(name=t_name, target=self.thread, args=(i,))
self.threads.add(t)
t.start()
def enqueue(self, task):
assert self.is_alive
with self.cond:
self.task_queue.append(task)
self.cond.notify_all()
def thread(self, thread_i):
while self.is_alive:
with self.cond:
try:
task = self.task_queue.pop(0)
except IndexError:
self.cond.wait()
continue
task.run()
def kill(self):
self.is_alive = False
with self.cond:
self.cond.notify_all()
def join(self):
for t in self.threads:
t.join()
####################
class ExDagHasCycle(Exception):
def __init__(self, stack, cycle):
self.stack = stack
self.cycle = cycle
def map_dag(roots, map_func):
mapped_nodes = dict()
stack = []
def recurse(node):
if node in stack:
cycle = stack[stack.index(cur):] + [cur]
raise ExDagHasCycle(stack, cycle)
try:
mapped = mapped_nodes[node]
return mapped
except KeyError:
pass
# --
stack.append(node)
parents = node.parents
mapped_parents = set()
for parent in parents:
mapped_parent = recurse(parent)
if mapped_parent:
mapped_parents.add(mapped_parent)
stack.pop()
# --
mapped = map_func(node, mapped_parents, stack)
mapped_nodes[node] = mapped
return mapped
mapped_roots = set()
for x in roots:
mapped = recurse(x)
if mapped:
mapped_roots.add(mapped)
return mapped_roots
####################
class PromiseGraphNode(object):
def __init__(self, parents, info=''):
self.info = str(info)
#print 'PromiseGraphNode {}: '.format(self.info) + ', '.join(map(lambda x: x.info, parents))
self.lock = threading.Lock()
self.pending_parents = set(parents)
self.children = set()
for parent in self.pending_parents:
with parent.lock:
parent.children.add(self)
self.result = None
def run(self):
self.resolve(True)
def on_resolve(self):
pass
def resolve(self, result):
assert result in (True, False)
with self.lock:
if self.result != None:
return
self.result = result
self.pending_parents.clear()
self.on_resolve()
assert self.result in (True, False)
if not self.result:
for child in self.children:
child.resolve(False)
else:
for child in self.children:
with child.lock:
try:
child.pending_parents.remove(self)
except KeyError:
continue
if child.pending_parents:
continue
assert child.result == None
child.run()
####################
def quote_args(args):
if os.name == 'nt':
return subprocess.list2cmdline(args)
return shlex.quote(args)
class SubprocCallNode(PromiseGraphNode):
ECHO = False
def __init__(self, parents, info, pool, call):
PromiseGraphNode.__init__(self, parents, info)
self.pool = pool
self.call = call
def run(self):
self.pool.enqueue(Task(self.task_run))
def task_run(self):
shell = type(self.call) is str
if SubprocCallNode.ECHO:
call = self.call
if not shell:
call = quote_args(call)
sys.stdout.write(call + '\n')
self.resolve(True)
return
result = False
try:
p = subprocess.Popen(self.call, shell=shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
stdout = stdout.decode(errors='replace')
stderr = stderr.decode(errors='replace')
if p.returncode == 0:
result = True
except OSError:
stdout = ''
stderr = 'Binary not found: {}'.format(self.call[0])
if not result:
stderr += '\n{} FAILED: {}\n'.format(self.info, self.call)
sys.stdout.write(stdout)
sys.stderr.write(stderr)
self.resolve(result)
####################
class EventNode(PromiseGraphNode):
def __init__(self, parents, info=''):
PromiseGraphNode.__init__(self, parents, info)
self.event = threading.Event()
def on_resolve(self):
self.event.set()
####################
NUM_THREADS = multiprocessing.cpu_count()
#NUM_THREADS = 1
def run_dagr(roots, thread_count=NUM_THREADS):
pool = ThreadPool('run_dagr pool', thread_count)
mapped_leaves = set()
def map_dagr_node(node, mapped_parents, stack):
if not node.cmds:
begin = PromiseGraphNode(mapped_parents, node.name)
end = begin
elif len(node.cmds) == 1:
begin = SubprocCallNode(mapped_parents, node.name, pool, node.cmds[0])
end = begin
else:
begin = PromiseGraphNode(mapped_parents, node.name + '.begin')
subs = set()
for i, cmd in enumerate(node.cmds):
info = node.name + '.{}'.format(i)
sub = SubprocCallNode([begin], info, pool, cmd)
subs.add(sub)
end = PromiseGraphNode(subs, node.name + '.end')
if not mapped_parents:
mapped_leaves.add(begin)
return end
mapped_roots = map_dag(roots, map_dagr_node)
# --
terminal_root = EventNode(mapped_roots, '<terminal_root>')
for x in mapped_leaves:
x.run()
terminal_root.event.wait()
pool.kill()
pool.join()
return terminal_root.result
if __name__ == '__main__':
start_time = time.time()
args = sys.argv[1:]
while True:
try:
cur = args.pop(0)
except IndexError:
break
if cur == '--dump':
SubprocCallNode.ECHO = True
continue
if cur == '--':
break
args.insert(0, cur)
break
root_names = args
if not root_names:
root_names = ['DEFAULT']
roots = []
for x in root_names:
try:
roots.append(DagrNode.nodes_by_name[x])
except KeyError:
sys.stderr.write('No such DagrNode: {}\n'.format(x))
exit(1)
success = run_dagr(roots)
elapsed_time = time.time() - start_time
if success:
sys.stderr.write('BUILD SUCCEEDED (in {:.4}s)\n'.format(elapsed_time))
else:
sys.stderr.write('BUILD FAILED\n\n\n')
assert len(threading.enumerate()) == 1, str(threading.enumerate())
exit(int(not success))