Logo AND Algorithmique Numérique Distribuée

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