1 /* Copyright (c) 2009-2023. The SimGrid Team. All rights reserved. */
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. */
6 #include "src/internal_config.h"
10 #include <simgrid/s4u/Host.hpp>
11 #include <simgrid/s4u/Comm.hpp>
12 #include <simgrid/s4u/Engine.hpp>
13 #include <simgrid/s4u/Exec.hpp>
15 #include <xbt/asserts.h>
16 #include <xbt/file.hpp>
24 // Disable implicit conversions. See https://github.com/nlohmann/json#implicit-conversions
25 #ifdef JSON_USE_IMPLICIT_CONVERSIONS
26 #undef JSON_USE_IMPLICIT_CONVERSIONS
28 #define JSON_USE_IMPLICIT_CONVERSIONS 0
29 #include <nlohmann/json.hpp>
34 #include <graphviz/cgraph.h>
37 XBT_LOG_NEW_DEFAULT_CATEGORY(dag_parsing, "Generation DAGs from files");
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)
42 const auto& child = comm->get_successors().front();
43 const auto& parent = *(comm->get_dependencies().begin());
45 std::string new_name = parent->get_name() + "_" + comm->get_name() + "_" + child->get_name();
47 comm->set_name(new_name)->start();
50 static bool check_for_cycle(const std::vector<simgrid::s4u::ActivityPtr>& dag)
52 std::vector<simgrid::s4u::ActivityPtr> current;
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();
58 while (not current.empty()) {
59 std::vector<simgrid::s4u::ActivityPtr> next;
60 for (auto const& a : current) {
62 for (auto const& pred : a->get_dependencies()) {
63 if (dynamic_cast<simgrid::s4u::Comm*>(pred.get()) != nullptr) {
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);
71 if (std::none_of(pred->get_successors().begin(), pred->get_successors().end(),
72 [](const simgrid::s4u::ActivityPtr& act) { return not act->is_marked(); }))
81 return not std::any_of(dag.begin(), dag.end(), [](const simgrid::s4u::ActivityPtr& a) { return not a->is_marked(); });
84 static YY_BUFFER_STATE input_buffer;
86 namespace simgrid::s4u {
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;
93 /** @brief loads a JSON file describing a DAG
95 * See https://github.com/wfcommons/wfformat for more details.
97 std::vector<ActivityPtr> create_DAG_from_json(const std::string& filename)
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 = {};
107 for (auto const& task: data["workflow"]["tasks"]) {
108 if (task["type"] == "compute") {
110 Exec::init()->set_name(task["name"].get<std::string>())->set_flops_amount(task["runtime"].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>()));
115 else if (task["type"] == "transfer"){
116 current = Comm::sendto_init()
117 ->set_name(task["name"].get<std::string>())
118 ->set_payload_size(task["bytesWritten"].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;
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());
135 } else if (XBT_LOG_ISENABLED(dag_parsing, xbt_log_priority_debug)) {
136 std::stringstream ss;
138 XBT_DEBUG("Task type \"%s\" not supported.", ss.str().c_str());
141 dag.push_back(current);
142 for (auto const& parent : task["parents"])
143 successors[parent.get<std::string>()].push_back(current);
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);
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);
157 // Start only Activities with dependencies solved
158 for (auto const& activity: dag) {
159 if (dynamic_cast<Exec*>(activity.get()) != nullptr && activity->dependencies_solved())
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.");
168 /** @brief loads a DAX file describing a DAG
170 * See https://confluence.pegasus.isi.edu/display/pegasus/WorkflowGenerator for more details.
172 std::vector<ActivityPtr> create_DAG_from_DAX(const std::string& filename)
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);
180 auto root_task = Exec::init()->set_name("root")->set_flops_amount(0);
183 result.push_back(root_task);
185 auto end_task = Exec::init()->set_name("end")->set_flops_amount(0);
188 xbt_assert(dax_lex() == 0, "Parse error in %s: %s", filename.c_str(), dax__parse_err_msg());
189 dax__delete_buffer(input_buffer);
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).
198 for (auto const& [_, elm] : files) {
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);
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);
217 for (auto const& it : file->get_dependencies()) {
218 for (auto const& it2 : file->get_successors()) {
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());
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);
230 /* Free previous copy of the files */
234 /* Push end task last */
235 result.push_back(end_task);
237 for (const auto& a : result) {
238 auto* comm = dynamic_cast<Comm*>(a.get());
239 if (comm != nullptr) {
240 uniq_transfer_task_name(comm);
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.
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);
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)
266 std::vector<ActivityPtr> create_DAG_from_dot(const std::string& filename)
268 FILE* in_file = fopen(filename.c_str(), "r");
269 xbt_assert(in_file != nullptr, "Failed to open file: %s", filename.c_str());
271 Agraph_t* dag_dot = agread(in_file, nullptr);
273 std::unordered_map<std::string, ActivityPtr> activities;
274 std::vector<ActivityPtr> dag;
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"));
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")
292 XBT_WARN("Exec '%s' is defined more than once", name.c_str());
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();
299 root = activities.at("root");
301 if (activities.find("end") == activities.end())
302 end = Exec::init()->set_name("end")->set_flops_amount(0)->start();
304 end = activities.at("end");
307 std::vector<Agedge_t*> edges;
308 for (node = agfstnode(dag_dot); node; node = agnxtnode(dag_dot, node)) {
310 for (Agedge_t* edge = agfstout(dag_dot, node); edge; edge = agnxtout(dag_dot, edge))
311 edges.push_back(edge);
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); });
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"));
321 ActivityPtr src = activities.at(src_name);
322 ActivityPtr dst = activities.at(dst_name);
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);
333 XBT_WARN("Comm '%s' is defined more than once", name.c_str());
336 src->add_successor(dst);
341 XBT_DEBUG("All activities have been created, put %s at the beginning and %s at the end", root->get_cname(),
343 dag.insert(dag.begin(), root);
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);
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);
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)
373 std::vector<ActivityPtr> create_DAG_from_dot(const std::string& filename)
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.");
379 } // namespace simgrid::s4u
381 void STag_dax__adag()
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");
394 double runtime = std::stod(A_dax__job_runtime);
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");
407 void STag_dax__uses()
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");
415 bool is_input = (A_dax__uses_link == A_dax__uses_link_input);
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();
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);
430 file->add_successor(simgrid::s4u::current_job);
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());
439 static simgrid::s4u::ExecPtr current_child;
440 void STag_dax__child()
442 auto job = simgrid::s4u::jobs.find(A_dax__child_ref);
443 if (job != simgrid::s4u::jobs.end()) {
444 current_child = job->second;
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");
451 void ETag_dax__child()
453 current_child = nullptr;
456 void STag_dax__parent()
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());
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 +
470 void ETag_dax__adag()
472 XBT_DEBUG("See </adag>");
477 simgrid::s4u::current_job = nullptr;
478 XBT_DEBUG("See </job>");
481 void ETag_dax__parent()
483 XBT_DEBUG("See </parent>");
486 void ETag_dax__uses()
488 XBT_DEBUG("See </uses>");