Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use structured binding declarations (sonar, c++17).
[simgrid.git] / src / dag / loaders.cpp
1 /* Copyright (c) 2009-2022. 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->has_no_successor())
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   for (auto const& [_, elm] : files) {
114     CommPtr file = elm;
115     CommPtr newfile;
116     if (file->dependencies_solved()) {
117       for (auto const& it : file->get_successors()) {
118         newfile = Comm::sendto_init()->set_name(file->get_name())->set_payload_size(file->get_remaining());
119         root_task->add_successor(newfile);
120         newfile->add_successor(it);
121         result.push_back(newfile);
122       }
123     }
124     if (file->has_no_successor()) {
125       for (auto const& it : file->get_dependencies()) {
126         newfile = Comm::sendto_init()->set_name(file->get_name())->set_payload_size(file->get_remaining());
127         it->add_successor(newfile);
128         newfile->add_successor(end_task);
129         result.push_back(newfile);
130       }
131     }
132     for (auto const& it : file->get_dependencies()) {
133       for (auto const& it2 : file->get_successors()) {
134         if (it == it2) {
135           XBT_WARN("File %s is produced and consumed by task %s."
136                    "This loop dependency will prevent the execution of the task.",
137                    file->get_cname(), it->get_cname());
138         }
139         newfile = Comm::sendto_init()->set_name(file->get_name())->set_payload_size(file->get_remaining());
140         it->add_successor(newfile);
141         newfile->add_successor(it2);
142         result.push_back(newfile);
143       }
144     }
145     /* Free previous copy of the files */
146     file->destroy();
147   }
148
149   /* Push end task last */
150   result.push_back(end_task);
151
152   for (const auto& a : result) {
153     auto* comm = dynamic_cast<Comm*>(a.get());
154     if (comm != nullptr) {
155       uniq_transfer_task_name(comm);
156     } else {
157       /* If some tasks do not take files as input, connect them to the root
158        * if they don't produce files, connect them to the end node.
159        */
160       if ((a != root_task) && (a != end_task)) {
161         if (a->dependencies_solved())
162           root_task->add_successor(a);
163         if (a->has_no_successor())
164           a->add_successor(end_task);
165       }
166     }
167   }
168
169   if (not check_for_cycle(result)) {
170     XBT_ERROR("The DAX described in %s is not a DAG. It contains a cycle.",
171               simgrid::xbt::Path(filename).get_base_name().c_str());
172     for (const auto& a : result)
173       a->destroy();
174     result.clear();
175   }
176
177   return result;
178 }
179
180 #if HAVE_GRAPHVIZ
181 std::vector<ActivityPtr> create_DAG_from_dot(const std::string& filename)
182 {
183   FILE* in_file = fopen(filename.c_str(), "r");
184   xbt_assert(in_file != nullptr, "Failed to open file: %s", filename.c_str());
185
186   Agraph_t* dag_dot = agread(in_file, NIL(Agdisc_t*));
187
188   std::unordered_map<std::string, ActivityPtr> activities;
189   std::vector<ActivityPtr> dag;
190
191   ActivityPtr root;
192   ActivityPtr end;
193   ActivityPtr act;
194   /* Create all the nodes */
195   Agnode_t* node = nullptr;
196   for (node = agfstnode(dag_dot); node; node = agnxtnode(dag_dot, node)) {
197     const std::string name = agnameof(node);
198     double amount = atof(agget(node, (char*)"size"));
199
200     if (activities.find(name) == activities.end()) {
201       XBT_DEBUG("See <Exec id = %s amount = %.0f>", name.c_str(), amount);
202       act = Exec::init()->set_name(name)->set_flops_amount(amount)->vetoable_start();
203       activities.try_emplace(name, act);
204       if (name != "root" && name != "end")
205         dag.push_back(act);
206     } else {
207       XBT_WARN("Exec '%s' is defined more than once", name.c_str());
208     }
209   }
210   /*Check if 'root' and 'end' nodes have been explicitly declared.  If not, create them. */
211   if (activities.find("root") == activities.end())
212     root = Exec::init()->set_name("root")->set_flops_amount(0)->vetoable_start();
213   else
214     root = activities.at("root");
215
216   if (activities.find("end") == activities.end())
217     end = Exec::init()->set_name("end")->set_flops_amount(0)->vetoable_start();
218   else
219     end = activities.at("end");
220
221   /* Create edges */
222   std::vector<Agedge_t*> edges;
223   for (node = agfstnode(dag_dot); node; node = agnxtnode(dag_dot, node)) {
224     edges.clear();
225     for (Agedge_t* edge = agfstout(dag_dot, node); edge; edge = agnxtout(dag_dot, edge))
226       edges.push_back(edge);
227
228     /* Be sure edges are sorted */
229     std::sort(edges.begin(), edges.end(), [](const Agedge_t* a, const Agedge_t* b) { return AGSEQ(a) < AGSEQ(b); });
230
231     for (Agedge_t* edge : edges) {
232       const char* src_name = agnameof(agtail(edge));
233       const char* dst_name = agnameof(aghead(edge));
234       double size          = atof(agget(edge, (char*)"size"));
235
236       ActivityPtr src = activities.at(src_name);
237       ActivityPtr dst = activities.at(dst_name);
238       if (size > 0) {
239         std::string name = std::string(src_name) + "->" + dst_name;
240         XBT_DEBUG("See <Comm id=%s amount = %.0f>", name.c_str(), size);
241         if (activities.find(name) == activities.end()) {
242           act = Comm::sendto_init()->set_name(name)->set_payload_size(size)->vetoable_start();
243           src->add_successor(act);
244           act->add_successor(dst);
245           activities.try_emplace(name, act);
246           dag.push_back(act);
247         } else {
248           XBT_WARN("Comm '%s' is defined more than once", name.c_str());
249         }
250       } else {
251         src->add_successor(dst);
252       }
253     }
254   }
255
256   XBT_DEBUG("All activities have been created, put %s at the beginning and %s at the end", root->get_cname(),
257             end->get_cname());
258   dag.insert(dag.begin(), root);
259   dag.push_back(end);
260
261   /* Connect entry tasks to 'root', and exit tasks to 'end'*/
262   for (const auto& a : dag) {
263     if (a->dependencies_solved() && a != root) {
264       XBT_DEBUG("Activity '%s' has no dependencies. Add dependency from 'root'", a->get_cname());
265       root->add_successor(a);
266     }
267
268     if (a->has_no_successor() && a != end) {
269       XBT_DEBUG("Activity '%s' has no successors. Add dependency to 'end'", a->get_cname());
270       a->add_successor(end);
271     }
272   }
273   agclose(dag_dot);
274   fclose(in_file);
275
276   if (not check_for_cycle(dag)) {
277     std::string base = simgrid::xbt::Path(filename).get_base_name();
278     XBT_ERROR("The DOT described in %s is not a DAG. It contains a cycle.", base.c_str());
279     for (const auto& a : dag)
280       a->destroy();
281     dag.clear();
282     dag.shrink_to_fit();
283   }
284
285   return dag;
286 }
287 #else
288 std::vector<ActivityPtr> create_DAG_from_dot(const std::string& filename)
289 {
290   xbt_die("create_DAG_from_dot() is not usable because graphviz was not found.\n"
291           "Please install graphviz, graphviz-dev, and libgraphviz-dev (and erase CMakeCache.txt) before recompiling.");
292 }
293 #endif
294 } // namespace s4u
295 } // namespace simgrid
296
297 void STag_dax__adag()
298 {
299   try {
300     double version = std::stod(std::string(A_dax__adag_version));
301     xbt_assert(version == 2.1, "Expected version 2.1 in <adag> tag, got %f. Fix the parser or your file", version);
302   } catch (const std::invalid_argument&) {
303     throw std::invalid_argument(std::string("Parse error: ") + A_dax__adag_version + " is not a double");
304   }
305 }
306
307 void STag_dax__job()
308 {
309   try {
310     double runtime = std::stod(std::string(A_dax__job_runtime));
311
312     std::string name = std::string(A_dax__job_id) + "@" + A_dax__job_name;
313     runtime *= 4200000000.; /* Assume that timings were done on a 4.2GFlops machine. I mean, why not? */
314     XBT_DEBUG("See <job id=%s runtime=%s %.0f>", A_dax__job_id, A_dax__job_runtime, runtime);
315     simgrid::s4u::current_job = simgrid::s4u::Exec::init()->set_name(name)->set_flops_amount(runtime)->vetoable_start();
316     simgrid::s4u::jobs.try_emplace(A_dax__job_id, simgrid::s4u::current_job);
317     simgrid::s4u::result.push_back(simgrid::s4u::current_job);
318   } catch (const std::invalid_argument&) {
319     throw std::invalid_argument(std::string("Parse error: ") + A_dax__job_runtime + " is not a double");
320   }
321 }
322
323 void STag_dax__uses()
324 {
325   double size;
326   try {
327     size = std::stod(std::string(A_dax__uses_size));
328   } catch (const std::invalid_argument&) {
329     throw std::invalid_argument(std::string("Parse error: ") + A_dax__uses_size + " is not a double");
330   }
331   bool is_input = (A_dax__uses_link == A_dax__uses_link_input);
332
333   XBT_DEBUG("See <uses file=%s %s>", A_dax__uses_file, (is_input ? "in" : "out"));
334   auto it = simgrid::s4u::files.find(A_dax__uses_file);
335   simgrid::s4u::CommPtr file;
336   if (it == simgrid::s4u::files.end()) {
337     file = simgrid::s4u::Comm::sendto_init()->set_name(A_dax__uses_file)->set_payload_size(size);
338     simgrid::s4u::files[A_dax__uses_file] = file.get();
339   } else {
340     file = it->second;
341     if (file->get_remaining() < size || file->get_remaining() > size) {
342       XBT_WARN("Ignore file %s size redefinition from %.0f to %.0f", A_dax__uses_file, file->get_remaining(), size);
343     }
344   }
345   if (is_input) {
346     file->add_successor(simgrid::s4u::current_job);
347   } else {
348     simgrid::s4u::current_job->add_successor(file);
349     if (file->get_dependencies().size() > 1) {
350       XBT_WARN("File %s created at more than one location...", file->get_cname());
351     }
352   }
353 }
354
355 static simgrid::s4u::ExecPtr current_child;
356 void STag_dax__child()
357 {
358   auto job = simgrid::s4u::jobs.find(A_dax__child_ref);
359   if (job != simgrid::s4u::jobs.end()) {
360     current_child = job->second;
361   } else {
362     throw std::out_of_range(std::string("Parse error on line ") + std::to_string(dax_lineno) +
363                             ": Asked to add dependencies to the non-existent " + A_dax__child_ref + "task");
364   }
365 }
366
367 void ETag_dax__child()
368 {
369   current_child = nullptr;
370 }
371
372 void STag_dax__parent()
373 {
374   auto job = simgrid::s4u::jobs.find(A_dax__parent_ref);
375   if (job != simgrid::s4u::jobs.end()) {
376     auto parent = job->second;
377     parent->add_successor(current_child);
378     XBT_DEBUG("Control-flow dependency from %s to %s", current_child->get_cname(), parent->get_cname());
379   } else {
380     throw std::out_of_range(std::string("Parse error on line ") + std::to_string(dax_lineno) +
381                             ": Asked to add a dependency from " + current_child->get_name() + " to " +
382                             A_dax__parent_ref + ", but " + A_dax__parent_ref + " does not exist");
383   }
384 }
385
386 void ETag_dax__adag()
387 {
388   XBT_DEBUG("See </adag>");
389 }
390
391 void ETag_dax__job()
392 {
393   simgrid::s4u::current_job = nullptr;
394   XBT_DEBUG("See </job>");
395 }
396
397 void ETag_dax__parent()
398 {
399   XBT_DEBUG("See </parent>");
400 }
401
402 void ETag_dax__uses()
403 {
404   XBT_DEBUG("See </uses>");
405 }