Logo AND Algorithmique Numérique Distribuée

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