Logo AND Algorithmique Numérique Distribuée

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