-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathexecution_plan.cpp
More file actions
485 lines (424 loc) · 13.1 KB
/
execution_plan.cpp
File metadata and controls
485 lines (424 loc) · 13.1 KB
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
// Copyright (C) 2017-2019 Egor Pugin <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "execution_plan.h"
#include <sw/support/exceptions.h>
#include <nlohmann/json.hpp>
#include <primitives/exceptions.h>
namespace sw
{
ExecutionPlan::~ExecutionPlan()
{
auto break_commands = [](auto &a)
{
// FIXME: clear() may destroy our next pointer in 'a' variable,
// so we make a copy of everything :(
std::vector<std::shared_ptr<T>> copy;
copy.reserve(a.size());
for (auto &c : a)
copy.emplace_back(c->shared_from_this());
for (auto &c : a)
c->clear();
};
break_commands(commands);
break_commands(unprocessed_commands);
break_commands(unprocessed_commands_set);
}
void ExecutionPlan::execute(Executor &e) const
{
if (commands.empty())
return;
std::mutex m;
std::vector<Future<void>> fs;
std::vector<Future<void>> all;
std::atomic_bool stopped = false;
std::atomic_int running = 0;
std::atomic_int64_t askip_errors = skip_errors;
bool build_commands = dynamic_cast<builder::Command *>(*commands.begin());
// set numbers
std::atomic_size_t current_command = 1;
std::atomic_size_t total_commands = commands.size();
for (auto &c : commands)
{
c->total_commands = &total_commands;
c->current_command = ¤t_command;
if (build_commands)
{
static_cast<builder::Command*>(c)->silent |= silent;
static_cast<builder::Command*>(c)->show_output |= show_output;
static_cast<builder::Command*>(c)->write_output_to_file |= write_output_to_file;
static_cast<builder::Command*>(c)->always |= build_always;
}
}
std::function<void(PtrT)> run;
run = [this, &askip_errors, &e, &run, &fs, &all, &m, &stopped, &running](T *c)
{
if (stopped)
return;
try
{
running++;
c->execute();
running--;
}
catch (...)
{
running--;
if (--askip_errors < 1)
stopped = true;
if (throw_on_errors)
throw; // don't go futher on DAG by default
}
for (auto &d : c->dependent_commands)
{
if (--d->dependencies_left == 0)
{
std::unique_lock<std::mutex> lk(m);
fs.push_back(e.push([&run, d] {run((T *)d.get()); }));
all.push_back(fs.back());
}
}
if (stop_time && Clock::now() > *stop_time)
stopped = true;
};
// we cannot know exact number of commands to be executed,
// because some of them might use write_file_if_different idiom,
// so actual number is known only at runtime
// we can just skip some amount of numbers
// TODO: check non-outdated commands and lower total_commands
// total_commands -= non outdated;
// run commands without deps
{
std::unique_lock<std::mutex> lk(m);
for (auto &c : commands)
{
if (!c->dependencies.empty())
//continue;
break;
fs.push_back(e.push([&run, c] {run(c); }));
all.push_back(fs.back());
}
}
// wait for all commands until exception
int i = 0;
auto sz = commands.size();
std::vector<std::exception_ptr> eptrs;
while (i != sz)
{
std::vector<Future<void>> fs2;
{
std::unique_lock<std::mutex> lk(m);
fs2 = fs;
fs.clear();
}
for (auto &f : fs2)
{
i++;
f.wait();
}
if (stopped || fs2.empty())
break;
}
// wait other jobs to finish or it will crash
while (running)
std::this_thread::sleep_for(std::chrono::milliseconds(50));
// gather exceptions
for (auto &f : all)
{
if (f.state->eptr)
eptrs.push_back(f.state->eptr);
}
// ... or it will crash here in throw
if (!eptrs.empty() && throw_on_errors)
throw ExceptionVector(eptrs);
if (i != sz/* && !stopped*/)
{
if (stop_time && Clock::now() > *stop_time && stopped)
throw SW_RUNTIME_ERROR("Time limit exceeded");
throw SW_RUNTIME_ERROR("Executor did not perform all steps");
}
}
void ExecutionPlan::saveChromeTrace(const path &p) const
{
// calculate minimal time
auto min = decltype (builder::Command::t_begin)::clock::now();
for (auto &c : commands)
{
if (static_cast<builder::Command*>(c)->t_begin.time_since_epoch().count() == 0)
continue;
min = std::min(static_cast<builder::Command*>(c)->t_begin, min);
}
auto tid_to_ll = [](auto &id)
{
std::ostringstream ss;
ss << id;
return ss.str();
};
nlohmann::json trace;
nlohmann::json events;
for (auto &c : commands)
{
if (static_cast<builder::Command*>(c)->t_begin.time_since_epoch().count() == 0)
continue;
nlohmann::json b;
b["name"] = c->getName();
b["cat"] = "BUILD";
b["pid"] = 1;
b["tid"] = tid_to_ll(static_cast<builder::Command*>(c)->tid);
b["ts"] = std::chrono::duration_cast<std::chrono::microseconds>(static_cast<builder::Command*>(c)->t_begin - min).count();
b["ph"] = "B";
events.push_back(b);
nlohmann::json e;
e["name"] = c->getName();
e["cat"] = "BUILD";
e["pid"] = 1;
e["tid"] = tid_to_ll(static_cast<builder::Command*>(c)->tid);
e["ts"] = std::chrono::duration_cast<std::chrono::microseconds>(static_cast<builder::Command*>(c)->t_end - min).count();
e["ph"] = "E";
events.push_back(e);
}
trace["traceEvents"] = events;
write_file(p, trace.dump(2));
}
ExecutionPlan::operator bool() const
{
return unprocessed_commands.empty();
}
ExecutionPlan::Graph ExecutionPlan::getGraph() const
{
return getGraph(commands);
}
ExecutionPlan::Graph ExecutionPlan::getGraphUnprocessed() const
{
return getGraph(unprocessed_commands);
}
ExecutionPlan::Graph ExecutionPlan::getGraph(const VecT &v)
{
auto gm = getGraphMapping(v);
return getGraph(v, gm);
}
std::tuple<size_t, ExecutionPlan::StrongComponents> ExecutionPlan::getStrongComponents(const Graph &g)
{
StrongComponents components(num_vertices(g));
auto num = boost::strong_components(g, boost::make_iterator_property_map(components.begin(), get(boost::vertex_index, g)));
return std::tuple{ num, components };
}
/// returns true if removed something
ExecutionPlan::Graph ExecutionPlan::getGraphSkeleton(const Graph &in)
{
//
throw SW_RUNTIME_ERROR("not implemented");
// make an algorithm here
auto g = in;
while (1)
{
bool removed = false;
typename boost::graph_traits<Graph>::vertex_iterator vi, vi_end, next;
boost::tie(vi, vi_end) = boost::vertices(g);
for (next = vi; vi != vi_end; vi = next)
{
++next;
if (g.m_vertices[(*vi)].m_in_edges.size() == 1 && g.m_vertices[(*vi)].m_out_edges.empty())
{
boost::remove_vertex(*vi, g);
removed = true;
break; // iterators were invalidated, as we use vecS and not listS
}
}
}
return g;
}
ExecutionPlan::Graph ExecutionPlan::getGraphSkeleton()
{
return getGraphSkeleton(getGraph());
}
std::tuple<ExecutionPlan::Graph, size_t, ExecutionPlan::StrongComponents> ExecutionPlan::getStrongComponents()
{
auto g = getGraphUnprocessed();
auto [num, components] = getStrongComponents(g);
return std::tuple{ g, num, components };
}
template <class G>
void ExecutionPlan::printGraph(const G &g, const path &base, const VecT &names, bool mangle_names)
{
auto p = base;
p += ".dot";
std::ofstream o(p);
if (names.empty())
boost::write_graphviz(o, g);
else
{
write_graphviz(o, g, [&names, mangle_names](auto &o, auto v)
{
if (mangle_names)
o << " [" << "label=\"" << std::to_string(v) << "\"]";
else
o << " [" << "label=" << names[v]->getName(true) << "]";
});
if (mangle_names)
{
auto p = base;
p += ".txt";
std::ofstream o(p);
int i = 0;
for (auto &n : names)
o << i++ << " = " << n->getName(true) << "\n";
}
}
}
void ExecutionPlan::printGraph(path p) const
{
printGraph(getGraph(), p);
}
void ExecutionPlan::setup()
{
// potentially *should* speedup later execution
// TODO: measure and decide
// it reduses some memory usage,
// but influence on performance on execution stages is not very clear
//transitiveReduction();
// set number of deps and dependent commands
for (auto &c : commands)
{
c->dependencies_left = c->dependencies.size();
for (auto &d : c->dependencies)
d->dependent_commands.insert(c->shared_from_this());
}
std::sort(commands.begin(), commands.end(), [](const auto &c1, const auto &c2)
{
return c1->lessDuringExecution(*c2);
});
}
ExecutionPlan::GraphMapping ExecutionPlan::getGraphMapping(const VecT &v)
{
GraphMapping gm;
VertexNode i = 0;
for (auto &c : v)
gm[c] = i++;
return gm;
}
ExecutionPlan::Graph ExecutionPlan::getGraph(const VecT &v, GraphMapping &gm)
{
Graph g(v.size());
for (auto &c : v)
{
g.m_vertices[gm[c]].m_property = c;
for (auto &d : c->dependencies)
boost::add_edge(gm[c], gm[d.get()], g);
}
return g;
}
void ExecutionPlan::transitiveReduction()
{
auto gm = getGraphMapping(commands);
auto g = getGraph(commands, gm);
auto[tr, vm] = transitiveReduction(g);
// copy props
for (auto &[from, to] : vm)
tr.m_vertices[to].m_property = g.m_vertices[from].m_property;
// make new edges (dependencies)
for (auto &[from, to] : vm)
{
auto c = commands[from];
c->dependencies.clear();
for (auto &e : tr.m_vertices[to].m_out_edges)
c->dependencies.insert(tr.m_vertices[e.m_target].m_property->shared_from_this());
}
}
std::tuple<ExecutionPlan::Graph, ExecutionPlan::VertexMap> ExecutionPlan::transitiveReduction(const Graph &g)
{
Graph tr;
VertexMap vm;
std::vector<size_t> id_map(boost::num_vertices(g));
std::iota(id_map.begin(), id_map.end(), 0u);
boost::transitive_reduction(g, tr, boost::make_assoc_property_map(vm), id_map.data());
return { tr, vm };
}
void ExecutionPlan::prepare(USet &cmds)
{
// prepare all commands
// extract all deps commands
// try to lower number of rehashes
auto reserve = [](auto &a)
{
a.reserve((a.size() / 10000 + 1) * 20000);
};
reserve(cmds);
while (1)
{
size_t sz = cmds.size();
// initial prepare
for (auto &c : cmds)
c->prepare();
// some commands get its i/o deps in wrong order,
// so we explicitly call this once more
// do not remove!
for (auto &c : cmds)
{
if (auto c1 = dynamic_cast<builder::Command*>(c))
c1->addInputOutputDeps();
}
// separate loop for additional deps tracking (programs, inputs, outputs etc.)
auto cmds2 = cmds;
reserve(cmds2);
for (auto &c : cmds)
{
for (auto &d : c->dependencies)
{
cmds2.insert((T *)d.get());
for (auto &d2 : d->dependencies)
cmds2.insert((T *)d2.get());
}
// also take explicit dependent commands
for (auto &d : c->dependent_commands)
cmds2.insert((T *)d.get());
}
cmds = std::move(cmds2);
if (cmds.size() == sz)
break;
}
}
void ExecutionPlan::init(USet &cmds)
{
// remove self deps
for (auto &c : cmds)
c->dependencies.erase(c->shared_from_this());
while (!cmds.empty())
{
bool added = false;
for (auto it = cmds.begin(); it != cmds.end();)
{
if (std::all_of((*it)->dependencies.begin(), (*it)->dependencies.end(),
[this, &cmds](auto &d) { return cmds.find((T *)d.get()) == cmds.end(); }))
{
added = true;
commands.push_back(*it);
it = cmds.erase(it);
}
else
it++;
}
if (!added)
{
// We failed with stupid algorithm, now we must perform smarter.
// Shall we?
unprocessed_commands.insert(unprocessed_commands.end(), cmds.begin(), cmds.end());
unprocessed_commands_set = cmds;
return;
}
}
}
ExecutionPlan ExecutionPlan::create(USet &cmds)
{
ExecutionPlan ep;
ep.init(cmds);
ep.setup();
return ep;
}
void ExecutionPlan::setTimeLimit(const Clock::duration &d)
{
stop_time = Clock::now() + d;
}
}