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 #include <nlohmann/json.hpp>
28 #include <graphviz/cgraph.h>
31 XBT_LOG_NEW_DEFAULT_CATEGORY(dag_parsing, "Generation DAGs from files");
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)
36 const auto& child = comm->get_successors().front();
37 const auto& parent = *(comm->get_dependencies().begin());
39 std::string new_name = parent->get_name() + "_" + comm->get_name() + "_" + child->get_name();
41 comm->set_name(new_name)->start();
44 static bool check_for_cycle(const std::vector<simgrid::s4u::ActivityPtr>& dag)
46 std::vector<simgrid::s4u::ActivityPtr> current;
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();
52 while (not current.empty()) {
53 std::vector<simgrid::s4u::ActivityPtr> next;
54 for (auto const& a : current) {
56 for (auto const& pred : a->get_dependencies()) {
57 if (dynamic_cast<simgrid::s4u::Comm*>(pred.get()) != nullptr) {
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);
65 if (std::none_of(pred->get_successors().begin(), pred->get_successors().end(),
66 [](const simgrid::s4u::ActivityPtr& act) { return not act->is_marked(); }))
75 return not std::any_of(dag.begin(), dag.end(), [](const simgrid::s4u::ActivityPtr& a) { return not a->is_marked(); });
78 static YY_BUFFER_STATE input_buffer;
80 namespace simgrid::s4u {
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;
87 /** @brief loads a JSON file describing a DAG
89 * See https://github.com/wfcommons/wfformat for more details.
91 std::vector<ActivityPtr> create_DAG_from_json(const std::string& filename)
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 = {};
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"]));
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;
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());
126 XBT_DEBUG("Task type \"%s\" not supported.", task["type"]);
128 dag.push_back(current);
129 for (auto const& parent: task["parents"]) {
130 auto it = successors.find(parent);
131 if (it == successors.end())
132 successors[parent] = {};
133 successors[parent].push_back(current);
137 for (auto const& [parent, successors_list] : successors)
138 for (auto const& activity: dag)
139 if (activity->get_name() == parent) {
140 for (auto const& successor: successors_list)
141 activity->add_successor(successor);
144 // Assign destinations of Comms (if done before successors are assigned there is a bug)
145 for (auto const& [comm, destination]: comms_destinations)
146 dynamic_cast<Comm*>(comm.get())->set_destination(destination);
148 // Start only Activities with dependencies solved
149 for (auto const& activity: dag) {
150 if (dynamic_cast<Exec*>(activity.get()) != nullptr and activity->dependencies_solved())
155 xbt_die("JSON support was not compiled in, probably because nlohmann/json was not found. Please install "
156 "nlohmann-json3-dev and recompile SimGrid to use this feature.");
159 /** @brief loads a DAX file describing a DAG
161 * See https://confluence.pegasus.isi.edu/display/pegasus/WorkflowGenerator for more details.
163 std::vector<ActivityPtr> create_DAG_from_DAX(const std::string& filename)
165 FILE* in_file = fopen(filename.c_str(), "r");
166 xbt_assert(in_file, "Unable to open \"%s\"\n", filename.c_str());
167 input_buffer = dax__create_buffer(in_file, 10);
168 dax__switch_to_buffer(input_buffer);
171 auto root_task = Exec::init()->set_name("root")->set_flops_amount(0);
174 result.push_back(root_task);
176 auto end_task = Exec::init()->set_name("end")->set_flops_amount(0);
179 xbt_assert(dax_lex() == 0, "Parse error in %s: %s", filename.c_str(), dax__parse_err_msg());
180 dax__delete_buffer(input_buffer);
184 /* And now, post-process the files.
185 * We want a file task per pair of computation tasks exchanging the file. Duplicate on need
186 * Files not produced in the system are said to be produced by root task (top of DAG).
187 * Files not consumed in the system are said to be consumed by end task (bottom of DAG).
189 for (auto const& [_, elm] : files) {
192 if (file->dependencies_solved()) {
193 for (auto const& it : file->get_successors()) {
194 newfile = Comm::sendto_init()->set_name(file->get_name())->set_payload_size(file->get_remaining());
195 root_task->add_successor(newfile);
196 newfile->add_successor(it);
197 result.push_back(newfile);
200 if (file->has_no_successor()) {
201 for (auto const& it : file->get_dependencies()) {
202 newfile = Comm::sendto_init()->set_name(file->get_name())->set_payload_size(file->get_remaining());
203 it->add_successor(newfile);
204 newfile->add_successor(end_task);
205 result.push_back(newfile);
208 for (auto const& it : file->get_dependencies()) {
209 for (auto const& it2 : file->get_successors()) {
211 XBT_WARN("File %s is produced and consumed by task %s."
212 "This loop dependency will prevent the execution of the task.",
213 file->get_cname(), it->get_cname());
215 newfile = Comm::sendto_init()->set_name(file->get_name())->set_payload_size(file->get_remaining());
216 it->add_successor(newfile);
217 newfile->add_successor(it2);
218 result.push_back(newfile);
221 /* Free previous copy of the files */
225 /* Push end task last */
226 result.push_back(end_task);
228 for (const auto& a : result) {
229 auto* comm = dynamic_cast<Comm*>(a.get());
230 if (comm != nullptr) {
231 uniq_transfer_task_name(comm);
233 /* If some tasks do not take files as input, connect them to the root
234 * if they don't produce files, connect them to the end node.
236 if ((a != root_task) && (a != end_task)) {
237 if (a->dependencies_solved())
238 root_task->add_successor(a);
239 if (a->has_no_successor())
240 a->add_successor(end_task);
245 if (not check_for_cycle(result)) {
246 XBT_ERROR("The DAX described in %s is not a DAG. It contains a cycle.",
247 simgrid::xbt::Path(filename).get_base_name().c_str());
248 for (const auto& a : result)
257 std::vector<ActivityPtr> create_DAG_from_dot(const std::string& filename)
259 FILE* in_file = fopen(filename.c_str(), "r");
260 xbt_assert(in_file != nullptr, "Failed to open file: %s", filename.c_str());
262 Agraph_t* dag_dot = agread(in_file, nullptr);
264 std::unordered_map<std::string, ActivityPtr> activities;
265 std::vector<ActivityPtr> dag;
270 /* Create all the nodes */
271 Agnode_t* node = nullptr;
272 for (node = agfstnode(dag_dot); node; node = agnxtnode(dag_dot, node)) {
273 const std::string name = agnameof(node);
274 double amount = atof(agget(node, (char*)"size"));
276 if (activities.find(name) == activities.end()) {
277 XBT_DEBUG("See <Exec id = %s amount = %.0f>", name.c_str(), amount);
278 act = Exec::init()->set_name(name)->set_flops_amount(amount)->start();
279 activities.try_emplace(name, act);
280 if (name != "root" && name != "end")
283 XBT_WARN("Exec '%s' is defined more than once", name.c_str());
286 /*Check if 'root' and 'end' nodes have been explicitly declared. If not, create them. */
287 if (activities.find("root") == activities.end())
288 root = Exec::init()->set_name("root")->set_flops_amount(0)->start();
290 root = activities.at("root");
292 if (activities.find("end") == activities.end())
293 end = Exec::init()->set_name("end")->set_flops_amount(0)->start();
295 end = activities.at("end");
298 std::vector<Agedge_t*> edges;
299 for (node = agfstnode(dag_dot); node; node = agnxtnode(dag_dot, node)) {
301 for (Agedge_t* edge = agfstout(dag_dot, node); edge; edge = agnxtout(dag_dot, edge))
302 edges.push_back(edge);
304 /* Be sure edges are sorted */
305 std::sort(edges.begin(), edges.end(), [](const Agedge_t* a, const Agedge_t* b) { return AGSEQ(a) < AGSEQ(b); });
307 for (Agedge_t* edge : edges) {
308 const char* src_name = agnameof(agtail(edge));
309 const char* dst_name = agnameof(aghead(edge));
310 double size = atof(agget(edge, (char*)"size"));
312 ActivityPtr src = activities.at(src_name);
313 ActivityPtr dst = activities.at(dst_name);
315 std::string name = std::string(src_name) + "->" + dst_name;
316 XBT_DEBUG("See <Comm id=%s amount = %.0f>", name.c_str(), size);
317 if (activities.find(name) == activities.end()) {
318 act = Comm::sendto_init()->set_name(name)->set_payload_size(size)->start();
319 src->add_successor(act);
320 act->add_successor(dst);
321 activities.try_emplace(name, act);
324 XBT_WARN("Comm '%s' is defined more than once", name.c_str());
327 src->add_successor(dst);
332 XBT_DEBUG("All activities have been created, put %s at the beginning and %s at the end", root->get_cname(),
334 dag.insert(dag.begin(), root);
337 /* Connect entry tasks to 'root', and exit tasks to 'end'*/
338 for (const auto& a : dag) {
339 if (a->dependencies_solved() && a != root) {
340 XBT_DEBUG("Activity '%s' has no dependencies. Add dependency from 'root'", a->get_cname());
341 root->add_successor(a);
344 if (a->has_no_successor() && a != end) {
345 XBT_DEBUG("Activity '%s' has no successors. Add dependency to 'end'", a->get_cname());
346 a->add_successor(end);
352 if (not check_for_cycle(dag)) {
353 std::string base = simgrid::xbt::Path(filename).get_base_name();
354 XBT_ERROR("The DOT described in %s is not a DAG. It contains a cycle.", base.c_str());
355 for (const auto& a : dag)
364 std::vector<ActivityPtr> create_DAG_from_dot(const std::string& filename)
366 xbt_die("create_DAG_from_dot() is not usable because graphviz was not found.\n"
367 "Please install graphviz, graphviz-dev, and libgraphviz-dev (and erase CMakeCache.txt) before recompiling.");
370 } // namespace simgrid::s4u
372 void STag_dax__adag()
375 double version = std::stod(A_dax__adag_version);
376 xbt_assert(version == 2.1, "Expected version 2.1 in <adag> tag, got %f. Fix the parser or your file", version);
377 } catch (const std::invalid_argument&) {
378 throw std::invalid_argument(std::string("Parse error: ") + A_dax__adag_version + " is not a double");
385 double runtime = std::stod(A_dax__job_runtime);
387 std::string name = std::string(A_dax__job_id) + "@" + A_dax__job_name;
388 runtime *= 4200000000.; /* Assume that timings were done on a 4.2GFlops machine. I mean, why not? */
389 XBT_DEBUG("See <job id=%s runtime=%s %.0f>", A_dax__job_id, A_dax__job_runtime, runtime);
390 simgrid::s4u::current_job = simgrid::s4u::Exec::init()->set_name(name)->set_flops_amount(runtime)->start();
391 simgrid::s4u::jobs.try_emplace(A_dax__job_id, simgrid::s4u::current_job);
392 simgrid::s4u::result.push_back(simgrid::s4u::current_job);
393 } catch (const std::invalid_argument&) {
394 throw std::invalid_argument(std::string("Parse error: ") + A_dax__job_runtime + " is not a double");
398 void STag_dax__uses()
402 size = std::stod(A_dax__uses_size);
403 } catch (const std::invalid_argument&) {
404 throw std::invalid_argument(std::string("Parse error: ") + A_dax__uses_size + " is not a double");
406 bool is_input = (A_dax__uses_link == A_dax__uses_link_input);
408 XBT_DEBUG("See <uses file=%s %s>", A_dax__uses_file, (is_input ? "in" : "out"));
409 auto it = simgrid::s4u::files.find(A_dax__uses_file);
410 simgrid::s4u::CommPtr file;
411 if (it == simgrid::s4u::files.end()) {
412 file = simgrid::s4u::Comm::sendto_init()->set_name(A_dax__uses_file)->set_payload_size(size);
413 simgrid::s4u::files[A_dax__uses_file] = file.get();
416 if (file->get_remaining() < size || file->get_remaining() > size) {
417 XBT_WARN("Ignore file %s size redefinition from %.0f to %.0f", A_dax__uses_file, file->get_remaining(), size);
421 file->add_successor(simgrid::s4u::current_job);
423 simgrid::s4u::current_job->add_successor(file);
424 if (file->get_dependencies().size() > 1) {
425 XBT_WARN("File %s created at more than one location...", file->get_cname());
430 static simgrid::s4u::ExecPtr current_child;
431 void STag_dax__child()
433 auto job = simgrid::s4u::jobs.find(A_dax__child_ref);
434 if (job != simgrid::s4u::jobs.end()) {
435 current_child = job->second;
437 throw std::out_of_range("Parse error on line " + std::to_string(dax_lineno) +
438 ": Asked to add dependencies to the non-existent " + A_dax__child_ref + "task");
442 void ETag_dax__child()
444 current_child = nullptr;
447 void STag_dax__parent()
449 auto job = simgrid::s4u::jobs.find(A_dax__parent_ref);
450 if (job != simgrid::s4u::jobs.end()) {
451 auto parent = job->second;
452 parent->add_successor(current_child);
453 XBT_DEBUG("Control-flow dependency from %s to %s", current_child->get_cname(), parent->get_cname());
455 throw std::out_of_range("Parse error on line " + std::to_string(dax_lineno) + ": Asked to add a dependency from " +
456 current_child->get_name() + " to " + A_dax__parent_ref + ", but " + A_dax__parent_ref +
461 void ETag_dax__adag()
463 XBT_DEBUG("See </adag>");
468 simgrid::s4u::current_job = nullptr;
469 XBT_DEBUG("See </job>");
472 void ETag_dax__parent()
474 XBT_DEBUG("See </parent>");
477 void ETag_dax__uses()
479 XBT_DEBUG("See </uses>");