Logo AND Algorithmique Numérique Distribuée

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