Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
plug leak
[simgrid.git] / src / dag / loaders.cpp
1 /* Copyright (c) 2009-2021. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include "src/internal_config.h"
8 #include <algorithm>
9 #include <map>
10 #include <simgrid/s4u/Comm.hpp>
11 #include <simgrid/s4u/Engine.hpp>
12 #include <simgrid/s4u/Exec.hpp>
13 #include <stdexcept>
14 #include <xbt/asserts.h>
15 #include <xbt/file.hpp>
16 #include <xbt/log.h>
17 #include <xbt/misc.h>
18
19 #include "dax_dtd.h"
20 #include "dax_dtd.c"
21
22 #if HAVE_GRAPHVIZ
23 #include <graphviz/cgraph.h>
24 #endif
25
26 XBT_LOG_NEW_DEFAULT_CATEGORY(dag_parsing, "Generation DAGs from files");
27
28 /* Ensure that transfer tasks have unique names even though a file is used several times */
29 static void uniq_transfer_task_name(simgrid::s4u::Comm* comm)
30 {
31   const auto& child  = comm->get_successors().front();
32   const auto& parent = *(comm->get_dependencies().begin());
33
34   std::string new_name = parent->get_name() + "_" + comm->get_name() + "_" + child->get_name();
35
36   comm->set_name(new_name)->vetoable_start();
37 }
38
39 static bool check_for_cycle(const std::vector<simgrid::s4u::ActivityPtr>& dag)
40 {
41   std::vector<simgrid::s4u::ActivityPtr> current;
42
43   for (const auto& a : dag)
44     if (dynamic_cast<simgrid::s4u::Exec*>(a.get()) != nullptr && a->is_waited_by() == 0)
45       current.push_back(a);
46
47   while (not current.empty()) {
48     std::vector<simgrid::s4u::ActivityPtr> next;
49     for (auto const& a : current) {
50       a->mark();
51       for (auto const& pred : a->get_dependencies()) {
52         if (dynamic_cast<simgrid::s4u::Comm*>(pred.get()) != nullptr) {
53           pred->mark();
54           // Comms have only one predecessor
55           auto pred_pred = *(pred->get_dependencies().begin());
56           if (std::none_of(pred_pred->get_successors().begin(), pred_pred->get_successors().end(),
57                            [](const simgrid::s4u::ActivityPtr& act) { return not act->is_marked(); }))
58             next.push_back(pred_pred);
59         } else {
60           if (std::none_of(pred->get_successors().begin(), pred->get_successors().end(),
61                            [](const simgrid::s4u::ActivityPtr& act) { return not act->is_marked(); }))
62             next.push_back(pred);
63         }
64       }
65     }
66     current.clear();
67     current = next;
68   }
69
70   return not std::any_of(dag.begin(), dag.end(), [](const simgrid::s4u::ActivityPtr& a) { return not a->is_marked(); });
71 }
72
73 static YY_BUFFER_STATE input_buffer;
74
75 namespace simgrid {
76 namespace s4u {
77
78 static std::vector<ActivityPtr> result;
79 static std::map<std::string, ExecPtr, std::less<>> jobs;
80 static std::map<std::string, Comm*, std::less<>> files;
81 static ExecPtr current_job;
82
83 /** @brief loads a DAX file describing a DAG
84  *
85  * See https://confluence.pegasus.isi.edu/display/pegasus/WorkflowGenerator for more details.
86  */
87 std::vector<ActivityPtr> create_DAG_from_DAX(const std::string& filename)
88 {
89   FILE* in_file = fopen(filename.c_str(), "r");
90   xbt_assert(in_file, "Unable to open \"%s\"\n", filename.c_str());
91   input_buffer = dax__create_buffer(in_file, 10);
92   dax__switch_to_buffer(input_buffer);
93   dax_lineno = 1;
94
95   auto root_task = Exec::init()->set_name("root")->set_flops_amount(0);
96   root_task->vetoable_start();
97
98   result.push_back(root_task);
99
100   auto end_task = Exec::init()->set_name("end")->set_flops_amount(0);
101   end_task->vetoable_start();
102
103   xbt_assert(dax_lex() == 0, "Parse error in %s: %s", filename.c_str(), dax__parse_err_msg());
104   dax__delete_buffer(input_buffer);
105   fclose(in_file);
106   dax_lex_destroy();
107
108   /* And now, post-process the files.
109    * We want a file task per pair of computation tasks exchanging the file. Duplicate on need
110    * Files not produced in the system are said to be produced by root task (top of DAG).
111    * Files not consumed in the system are said to be consumed by end task (bottom of DAG).
112    */
113   CommPtr file;
114
115   for (auto const& elm : files) {
116     file = elm.second;
117     CommPtr newfile;
118     if (file->dependencies_solved()) {
119       for (auto const& it : file->get_successors()) {
120         newfile = Comm::sendto_init()->set_name(file->get_name())->set_payload_size(file->get_remaining());
121         root_task->add_successor(newfile);
122         newfile->add_successor(it);
123         result.push_back(newfile);
124       }
125     }
126     if (file->is_waited_by() == 0) {
127       for (auto const& it : file->get_dependencies()) {
128         newfile = Comm::sendto_init()->set_name(file->get_name())->set_payload_size(file->get_remaining());
129         it->add_successor(newfile);
130         newfile->add_successor(end_task);
131         result.push_back(newfile);
132       }
133     }
134     for (auto const& it : file->get_dependencies()) {
135       for (auto const& it2 : file->get_successors()) {
136         if (it == it2) {
137           XBT_WARN("File %s is produced and consumed by task %s."
138                    "This loop dependency will prevent the execution of the task.",
139                    file->get_cname(), it->get_cname());
140         }
141         newfile = Comm::sendto_init()->set_name(file->get_name())->set_payload_size(file->get_remaining());
142         it->add_successor(newfile);
143         newfile->add_successor(it2);
144         result.push_back(newfile);
145       }
146     }
147     /* Free previous copy of the files */
148     file->destroy();
149   }
150
151   /* Push end task last */
152   result.push_back(end_task);
153
154   for (const auto& a : result) {
155     auto* comm = dynamic_cast<Comm*>(a.get());
156     if (comm != nullptr) {
157       uniq_transfer_task_name(comm);
158     } else {
159       /* If some tasks do not take files as input, connect them to the root
160        * if they don't produce files, connect them to the end node.
161        */
162       if ((a != root_task) && (a != end_task)) {
163         if (a->dependencies_solved())
164           root_task->add_successor(a);
165         if (a->is_waited_by() == 0)
166           a->add_successor(end_task);
167       }
168     }
169   }
170
171   if (not check_for_cycle(result)) {
172     XBT_ERROR("The DAX described in %s is not a DAG. It contains a cycle.",
173               simgrid::xbt::Path(filename).get_base_name().c_str());
174     for (const auto& a : result)
175       a->destroy();
176     result.clear();
177   }
178
179   return result;
180 }
181
182 #if HAVE_GRAPHVIZ
183 std::vector<ActivityPtr> create_DAG_from_dot(const std::string& filename)
184 {
185   FILE* in_file = fopen(filename.c_str(), "r");
186   xbt_assert(in_file != nullptr, "Failed to open file: %s", filename.c_str());
187
188   Agraph_t* dag_dot = agread(in_file, NIL(Agdisc_t*));
189
190   std::unordered_map<std::string, ActivityPtr> activities;
191   std::vector<ActivityPtr> dag;
192
193   ActivityPtr root;
194   ActivityPtr end;
195   ActivityPtr act;
196   /* Create all the nodes */
197   Agnode_t* node = nullptr;
198   for (node = agfstnode(dag_dot); node; node = agnxtnode(dag_dot, node)) {
199     char* name    = agnameof(node);
200     double amount = atof(agget(node, (char*)"size"));
201
202     if (activities.find(name) == activities.end()) {
203       XBT_DEBUG("See <Exec id = %s amount = %.0f>", name, amount);
204       act = Exec::init()->set_name(name)->set_flops_amount(amount)->vetoable_start();
205       activities.insert({std::string(name), act});
206       if (strcmp(name, "root") && strcmp(name, "end"))
207         dag.push_back(act);
208     } else {
209       XBT_WARN("Exec '%s' is defined more than once", name);
210     }
211   }
212   /*Check if 'root' and 'end' nodes have been explicitly declared.  If not, create them. */
213   if (activities.find("root") == activities.end())
214     root = Exec::init()->set_name("root")->set_flops_amount(0)->vetoable_start();
215   else
216     root = activities.at("root");
217
218   if (activities.find("end") == activities.end())
219     end = Exec::init()->set_name("end")->set_flops_amount(0)->vetoable_start();
220   else
221     end = activities.at("end");
222
223   /* Create edges */
224   std::vector<Agedge_t*> edges;
225   for (node = agfstnode(dag_dot); node; node = agnxtnode(dag_dot, node)) {
226     edges.clear();
227     for (Agedge_t* edge = agfstout(dag_dot, node); edge; edge = agnxtout(dag_dot, edge))
228       edges.push_back(edge);
229
230     /* Be sure edges are sorted */
231     std::sort(edges.begin(), edges.end(), [](const Agedge_t* a, const Agedge_t* b) { return AGSEQ(a) < AGSEQ(b); });
232
233     for (Agedge_t* edge : edges) {
234       const char* src_name = agnameof(agtail(edge));
235       const char* dst_name = agnameof(aghead(edge));
236       double size          = atof(agget(edge, (char*)"size"));
237
238       ActivityPtr src = activities.at(src_name);
239       ActivityPtr dst = activities.at(dst_name);
240       if (size > 0) {
241         std::string name = std::string(src_name) + "->" + dst_name;
242         XBT_DEBUG("See <Comm id=%s amount = %.0f>", name.c_str(), size);
243         if (activities.find(name) == activities.end()) {
244           act = Comm::sendto_init()->set_name(name)->set_payload_size(size)->vetoable_start();
245           src->add_successor(act);
246           act->add_successor(dst);
247           activities.insert({name, act});
248           dag.push_back(act);
249         } else {
250           XBT_WARN("Comm '%s' is defined more than once", name.c_str());
251         }
252       } else {
253         src->add_successor(dst);
254       }
255     }
256   }
257
258   XBT_DEBUG("All activities have been created, put %s at the beginning and %s at the end", root->get_cname(),
259             end->get_cname());
260   dag.insert(dag.begin(), root);
261   dag.push_back(end);
262
263   /* Connect entry tasks to 'root', and exit tasks to 'end'*/
264   for (const auto& a : dag) {
265     if (a->dependencies_solved() && a != root) {
266       XBT_DEBUG("Activity '%s' has no dependencies. Add dependency from 'root'", a->get_cname());
267       root->add_successor(a);
268     }
269
270     if (a->is_waited_by() == 0 && a != end) {
271       XBT_DEBUG("Activity '%s' has no successors. Add dependency to 'end'", a->get_cname());
272       a->add_successor(end);
273     }
274   }
275   agclose(dag_dot);
276   fclose(in_file);
277
278   if (not check_for_cycle(dag)) {
279     std::string base = simgrid::xbt::Path(filename).get_base_name();
280     XBT_ERROR("The DOT described in %s is not a DAG. It contains a cycle.", base.c_str());
281     for (const auto& a : dag)
282       a->destroy();
283     dag.clear();
284     dag.shrink_to_fit();
285   }
286
287   return dag;
288 }
289 #else
290 std::vector<ActivityPtr> create_DAG_from_dot(const std::string& filename)
291 {
292   xbt_die("create_DAG_from_dot() is not usable because graphviz was not found.\n"
293           "Please install graphviz, graphviz-dev, and libgraphviz-dev (and erase CMakeCache.txt) before recompiling.");
294 }
295 #endif
296 } // namespace s4u
297 } // namespace simgrid
298
299 void STag_dax__adag()
300 {
301   try {
302     double version = std::stod(std::string(A_dax__adag_version));
303     xbt_assert(version == 2.1, "Expected version 2.1 in <adag> tag, got %f. Fix the parser or your file", version);
304   } catch (const std::invalid_argument&) {
305     throw std::invalid_argument(std::string("Parse error: ") + A_dax__adag_version + " is not a double");
306   }
307 }
308
309 void STag_dax__job()
310 {
311   try {
312     double runtime = std::stod(std::string(A_dax__job_runtime));
313
314     std::string name = std::string(A_dax__job_id) + "@" + A_dax__job_name;
315     runtime *= 4200000000.; /* Assume that timings were done on a 4.2GFlops machine. I mean, why not? */
316     XBT_DEBUG("See <job id=%s runtime=%s %.0f>", A_dax__job_id, A_dax__job_runtime, runtime);
317     simgrid::s4u::current_job = simgrid::s4u::Exec::init()->set_name(name)->set_flops_amount(runtime)->vetoable_start();
318     simgrid::s4u::jobs.insert({A_dax__job_id, simgrid::s4u::current_job});
319     simgrid::s4u::result.push_back(simgrid::s4u::current_job);
320   } catch (const std::invalid_argument&) {
321     throw std::invalid_argument(std::string("Parse error: ") + A_dax__job_runtime + " is not a double");
322   }
323 }
324
325 void STag_dax__uses()
326 {
327   double size;
328   try {
329     size = std::stod(std::string(A_dax__uses_size));
330   } catch (const std::invalid_argument&) {
331     throw std::invalid_argument(std::string("Parse error: ") + A_dax__uses_size + " is not a double");
332   }
333   bool is_input = (A_dax__uses_link == A_dax__uses_link_input);
334
335   XBT_DEBUG("See <uses file=%s %s>", A_dax__uses_file, (is_input ? "in" : "out"));
336   auto it = simgrid::s4u::files.find(A_dax__uses_file);
337   simgrid::s4u::CommPtr file;
338   if (it == simgrid::s4u::files.end()) {
339     file = simgrid::s4u::Comm::sendto_init()->set_name(A_dax__uses_file)->set_payload_size(size);
340     simgrid::s4u::files[A_dax__uses_file] = file.get();
341   } else {
342     file = it->second;
343     if (file->get_remaining() < size || file->get_remaining() > size) {
344       XBT_WARN("Ignore file %s size redefinition from %.0f to %.0f", A_dax__uses_file, file->get_remaining(), size);
345     }
346   }
347   if (is_input) {
348     file->add_successor(simgrid::s4u::current_job);
349   } else {
350     simgrid::s4u::current_job->add_successor(file);
351     if (file->get_dependencies().size() > 1) {
352       XBT_WARN("File %s created at more than one location...", file->get_cname());
353     }
354   }
355 }
356
357 static simgrid::s4u::ExecPtr current_child;
358 void STag_dax__child()
359 {
360   auto job = simgrid::s4u::jobs.find(A_dax__child_ref);
361   if (job != simgrid::s4u::jobs.end()) {
362     current_child = job->second;
363   } else {
364     throw std::out_of_range(std::string("Parse error on line ") + std::to_string(dax_lineno) +
365                             ": Asked to add dependencies to the non-existent " + A_dax__child_ref + "task");
366   }
367 }
368
369 void ETag_dax__child()
370 {
371   current_child = nullptr;
372 }
373
374 void STag_dax__parent()
375 {
376   auto job = simgrid::s4u::jobs.find(A_dax__parent_ref);
377   if (job != simgrid::s4u::jobs.end()) {
378     auto parent = job->second;
379     parent->add_successor(current_child);
380     XBT_DEBUG("Control-flow dependency from %s to %s", current_child->get_cname(), parent->get_cname());
381   } else {
382     throw std::out_of_range(std::string("Parse error on line ") + std::to_string(dax_lineno) +
383                             ": Asked to add a dependency from " + current_child->get_name() + " to " +
384                             A_dax__parent_ref + ", but " + A_dax__parent_ref + " does not exist");
385   }
386 }
387
388 void ETag_dax__adag()
389 {
390   XBT_DEBUG("See </adag>");
391 }
392
393 void ETag_dax__job()
394 {
395   simgrid::s4u::current_job = nullptr;
396   XBT_DEBUG("See </job>");
397 }
398
399 void ETag_dax__parent()
400 {
401   XBT_DEBUG("See </parent>");
402 }
403
404 void ETag_dax__uses()
405 {
406   XBT_DEBUG("See </uses>");
407 }