1 /* Copyright (c) 2018-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 <pybind11/pybind11.h> // Must come before our own stuff
8 #include <pybind11/functional.h>
9 #include <pybind11/stl.h>
11 #include "simgrid/kernel/ProfileBuilder.hpp"
12 #include "simgrid/kernel/routing/NetPoint.hpp"
13 #include "simgrid/plugins/load.h"
14 #include <simgrid/Exception.hpp>
15 #include <simgrid/s4u/ActivitySet.hpp>
16 #include <simgrid/s4u/Actor.hpp>
17 #include <simgrid/s4u/Barrier.hpp>
18 #include <simgrid/s4u/Comm.hpp>
19 #include <simgrid/s4u/Disk.hpp>
20 #include <simgrid/s4u/Engine.hpp>
21 #include <simgrid/s4u/Exec.hpp>
22 #include <simgrid/s4u/Host.hpp>
23 #include <simgrid/s4u/Io.hpp>
24 #include <simgrid/s4u/Link.hpp>
25 #include <simgrid/s4u/Mailbox.hpp>
26 #include <simgrid/s4u/Mutex.hpp>
27 #include <simgrid/s4u/NetZone.hpp>
28 #include <simgrid/s4u/Semaphore.hpp>
29 #include <simgrid/s4u/Task.hpp>
30 #include <simgrid/version.h>
37 namespace py = pybind11;
38 using simgrid::s4u::Activity;
39 using simgrid::s4u::ActivityPtr;
40 using simgrid::s4u::ActivitySet;
41 using simgrid::s4u::ActivitySetPtr;
42 using simgrid::s4u::Actor;
43 using simgrid::s4u::ActorPtr;
44 using simgrid::s4u::Barrier;
45 using simgrid::s4u::BarrierPtr;
46 using simgrid::s4u::Comm;
47 using simgrid::s4u::CommPtr;
48 using simgrid::s4u::CommTask;
49 using simgrid::s4u::CommTaskPtr;
50 using simgrid::s4u::Disk;
51 using simgrid::s4u::Engine;
52 using simgrid::s4u::ExecTask;
53 using simgrid::s4u::ExecTaskPtr;
54 using simgrid::s4u::Host;
55 using simgrid::s4u::Io;
56 using simgrid::s4u::IoTask;
57 using simgrid::s4u::IoTaskPtr;
58 using simgrid::s4u::Link;
59 using simgrid::s4u::Mailbox;
60 using simgrid::s4u::Mutex;
61 using simgrid::s4u::MutexPtr;
62 using simgrid::s4u::Semaphore;
63 using simgrid::s4u::SemaphorePtr;
64 using simgrid::s4u::Task;
65 using simgrid::s4u::TaskPtr;
67 XBT_LOG_NEW_DEFAULT_CATEGORY(python, "python");
71 std::string get_simgrid_version()
76 sg_version_get(&major, &minor, &patch);
77 return simgrid::xbt::string_printf("%i.%i.%i", major, minor, patch);
80 /** @brief Wrap for mailbox::get_async */
82 std::unique_ptr<PyObject*> data = std::make_unique<PyObject*>();
85 PyObject** get() const { return data.get(); }
90 PYBIND11_DECLARE_HOLDER_TYPE(T, boost::intrusive_ptr<T>)
92 PYBIND11_MODULE(simgrid, m)
94 m.doc() = "SimGrid userspace API";
96 m.attr("simgrid_version") = get_simgrid_version();
98 // Swapped contexts are broken, starting from pybind11 v2.8.0. Use thread contexts by default.
99 simgrid::s4u::Engine::set_config("contexts/factory:thread");
101 // Internal exception used to kill actors and sweep the RAII chimney (free objects living on the stack)
102 static py::object pyForcefulKillEx(py::register_exception<simgrid::ForcefulKillException>(m, "ActorKilled"));
104 py::register_exception<simgrid::NetworkFailureException>(m, "NetworkFailureException");
105 py::register_exception<simgrid::TimeoutException>(m, "TimeoutException");
106 py::register_exception<simgrid::HostFailureException>(m, "HostFailureException");
107 py::register_exception<simgrid::StorageFailureException>(m, "StorageFailureException");
108 py::register_exception<simgrid::VmFailureException>(m, "VmFailureException");
109 py::register_exception<simgrid::CancelException>(m, "CancelException");
110 py::register_exception<simgrid::AssertionError>(m, "AssertionError");
112 /* this_actor namespace */
113 m.def_submodule("this_actor", "Bindings of the s4u::this_actor namespace. See the C++ documentation for details.")
115 "debug", [](const char* s) { XBT_DEBUG("%s", s); }, "Display a logging message of 'debug' priority.")
117 "info", [](const char* s) { XBT_INFO("%s", s); }, "Display a logging message of 'info' priority.")
119 "warning", [](const char* s) { XBT_WARN("%s", s); }, "Display a logging message of 'warning' priority.")
121 "error", [](const char* s) { XBT_ERROR("%s", s); }, "Display a logging message of 'error' priority.")
122 .def("execute", py::overload_cast<double, double>(&simgrid::s4u::this_actor::execute),
123 py::call_guard<py::gil_scoped_release>(),
124 "Block the current actor, computing the given amount of flops at the given priority.", py::arg("flops"),
125 py::arg("priority") = 1)
126 .def("exec_init", py::overload_cast<double>(&simgrid::s4u::this_actor::exec_init),
127 py::call_guard<py::gil_scoped_release>())
128 .def("exec_async", py::overload_cast<double>(&simgrid::s4u::this_actor::exec_async),
129 py::call_guard<py::gil_scoped_release>())
130 .def("parallel_execute", &simgrid::s4u::this_actor::parallel_execute, py::call_guard<py::gil_scoped_release>(),
131 "Run a parallel task (requires the 'ptask_L07' model)")
133 py::overload_cast<const std::vector<simgrid::s4u::Host*>&, const std::vector<double>&,
134 const std::vector<double>&>(&simgrid::s4u::this_actor::exec_init),
135 py::call_guard<py::gil_scoped_release>(), "Initiate a parallel task (requires the 'ptask_L07' model)")
136 .def("get_host", &simgrid::s4u::this_actor::get_host, "Retrieves host on which the current actor is located")
137 .def("set_host", &simgrid::s4u::this_actor::set_host, py::call_guard<py::gil_scoped_release>(),
138 "Moves the current actor to another host.", py::arg("dest"))
139 .def("sleep_for", static_cast<void (*)(double)>(&simgrid::s4u::this_actor::sleep_for),
140 py::call_guard<py::gil_scoped_release>(), "Block the actor sleeping for that amount of seconds.",
142 .def("sleep_until", static_cast<void (*)(double)>(&simgrid::s4u::this_actor::sleep_until),
143 py::call_guard<py::gil_scoped_release>(), "Block the actor sleeping until the specified timestamp.",
145 .def("suspend", &simgrid::s4u::this_actor::suspend, py::call_guard<py::gil_scoped_release>(),
146 "Suspend the current actor, that is blocked until resume()ed by another actor.")
147 .def("yield_", &simgrid::s4u::this_actor::yield, py::call_guard<py::gil_scoped_release>(), "Yield the actor")
148 .def("exit", &simgrid::s4u::this_actor::exit, py::call_guard<py::gil_scoped_release>(), "kill the current actor")
152 fun.inc_ref(); // keep alive after return
153 const py::gil_scoped_release gil_release;
154 simgrid::s4u::this_actor::on_exit([fun_p = fun.ptr()](bool failed) {
155 const py::gil_scoped_acquire py_context; // need a new context for callback
157 const auto fun = py::reinterpret_borrow<py::function>(fun_p);
159 } catch (const py::error_already_set& e) {
160 xbt_die("Error while executing the on_exit lambda: %s", e.what());
164 "Define a lambda to be called when the actor ends. It takes a bool parameter indicating whether the actor "
165 "was killed. If False, the actor finished peacefully.")
166 .def("get_pid", &simgrid::s4u::this_actor::get_pid, "Retrieves PID of the current actor")
167 .def("get_ppid", &simgrid::s4u::this_actor::get_ppid,
168 "Retrieves PPID of the current actor (i.e., the PID of its parent).");
171 py::class_<Engine>(m, "Engine", "Simulation Engine")
172 .def(py::init([](std::vector<std::string> args) {
173 auto argc = static_cast<int>(args.size());
174 std::vector<char*> argv(args.size() + 1); // argv[argc] is nullptr
175 std::transform(begin(args), end(args), begin(argv), [](std::string& s) { return &s.front(); });
176 // Currently this can be dangling, we should wrap this somehow.
177 return new simgrid::s4u::Engine(&argc, argv.data());
179 "The constructor should take the parameters from the command line, as is ")
180 .def_property_readonly_static(
181 "clock", [](py::object /* self */) { return Engine::get_clock(); },
182 "The simulation time, ie the amount of simulated seconds since the simulation start.")
183 .def_property_readonly_static(
184 "instance", [](py::object /* self */) { return Engine::get_instance(); }, "Retrieve the simulation engine")
185 .def("host_by_name", &Engine::host_by_name_or_null,
186 "Retrieve a host by its name, or None if it does not exist in the platform.")
187 .def_property_readonly("all_hosts", &Engine::get_all_hosts, "Returns the list of all hosts found in the platform")
188 .def_property_readonly("all_links", &Engine::get_all_links, "Returns the list of all links found in the platform")
189 .def_property_readonly("all_netpoints", &Engine::get_all_netpoints)
190 .def_property_readonly("netzone_root", &Engine::get_netzone_root,
191 "Retrieve the root netzone, containing all others.")
192 .def("netpoint_by_name", &Engine::netpoint_by_name_or_null)
193 .def("netzone_by_name", &Engine::netzone_by_name_or_null)
194 .def("set_config", py::overload_cast<const std::string&>(&Engine::set_config),
195 "Change one of SimGrid's configurations")
196 .def("load_platform", &Engine::load_platform, "Load a platform file describing the environment")
197 .def("load_deployment", &Engine::load_deployment, "Load a deployment file and launch the actors that it contains")
198 .def("mailbox_by_name_or_create", &Engine::mailbox_by_name_or_create, py::call_guard<py::gil_scoped_release>(),
199 py::arg("name"), "Find a mailbox from its name or create one if it does not exist")
200 .def("run", &Engine::run, py::call_guard<py::gil_scoped_release>(), "Run the simulation until its end")
201 .def("run_until", py::overload_cast<double>(&Engine::run_until, py::const_),
202 py::call_guard<py::gil_scoped_release>(), "Run the simulation until the given date",
203 py::arg("max_date") = -1)
206 [](Engine* e, const std::string& name, py::object fun_or_class) {
207 fun_or_class.inc_ref(); // keep alive after return
208 const py::gil_scoped_release gil_release;
209 e->register_actor(name, [fun_or_class_p = fun_or_class.ptr()](std::vector<std::string> args) {
210 const py::gil_scoped_acquire py_context;
212 /* Convert the std::vector into a py::tuple */
213 py::tuple params(args.size() - 1);
214 for (size_t i = 1; i < args.size(); i++)
215 params[i - 1] = py::cast(args[i]);
217 const auto fun_or_class = py::reinterpret_borrow<py::object>(fun_or_class_p);
218 py::object res = fun_or_class(*params);
219 /* If I was passed a class, I just built an instance, so I need to call it now */
220 if (py::isinstance<py::function>(res))
222 } catch (const py::error_already_set& ex) {
223 if (ex.matches(pyForcefulKillEx)) {
224 XBT_VERB("Actor killed");
225 simgrid::ForcefulKillException::do_throw(); // Forward that ForcefulKill exception
231 "Registers the main function of an actor")
232 .def("set_log_control", [](Engine*, const std::string& settings) { xbt_log_control_set(settings.c_str()); });
235 py::class_<simgrid::s4u::NetZone, std::unique_ptr<simgrid::s4u::NetZone, py::nodelete>> netzone(
236 m, "NetZone", "Networking Zones. See the C++ documentation for details.");
237 netzone.def_static("create_full_zone", &simgrid::s4u::create_full_zone, "Creates a zone of type FullZone")
238 .def_static("create_torus_zone", &simgrid::s4u::create_torus_zone, "Creates a cluster of type Torus")
239 .def_static("create_fatTree_zone", &simgrid::s4u::create_fatTree_zone, "Creates a cluster of type Fat-Tree")
240 .def_static("create_dragonfly_zone", &simgrid::s4u::create_dragonfly_zone, "Creates a cluster of type Dragonfly")
241 .def_static("create_star_zone", &simgrid::s4u::create_star_zone, "Creates a zone of type Star")
242 .def_static("create_floyd_zone", &simgrid::s4u::create_floyd_zone, "Creates a zone of type Floyd")
243 .def_static("create_dijkstra_zone", &simgrid::s4u::create_floyd_zone, "Creates a zone of type Dijkstra")
244 .def_static("create_vivaldi_zone", &simgrid::s4u::create_vivaldi_zone, "Creates a zone of type Vivaldi")
245 .def_static("create_empty_zone", &simgrid::s4u::create_empty_zone, "Creates a zone of type Empty")
246 .def_static("create_wifi_zone", &simgrid::s4u::create_wifi_zone, "Creates a zone of type Wi-Fi")
248 py::overload_cast<simgrid::kernel::routing::NetPoint*, simgrid::kernel::routing::NetPoint*,
249 simgrid::kernel::routing::NetPoint*, simgrid::kernel::routing::NetPoint*,
250 const std::vector<simgrid::s4u::LinkInRoute>&, bool>(&simgrid::s4u::NetZone::add_route),
251 "Add a route between 2 netpoints")
253 py::overload_cast<const simgrid::s4u::Host*, const simgrid::s4u::Host*,
254 const std::vector<simgrid::s4u::LinkInRoute>&, bool>(&simgrid::s4u::NetZone::add_route),
255 "Add a route between 2 netpoints")
257 py::overload_cast<const simgrid::s4u::Host*, const simgrid::s4u::Host*,
258 const std::vector<const simgrid::s4u::Link*>&>(&simgrid::s4u::NetZone::add_route),
259 "Add a route between 2 netpoints")
260 .def("create_host", py::overload_cast<const std::string&, double>(&simgrid::s4u::NetZone::create_host),
263 py::overload_cast<const std::string&, const std::string&>(&simgrid::s4u::NetZone::create_host),
266 py::overload_cast<const std::string&, const std::vector<double>&>(&simgrid::s4u::NetZone::create_host),
269 py::overload_cast<const std::string&, const std::vector<std::string>&>(&simgrid::s4u::NetZone::create_host),
271 .def("create_link", py::overload_cast<const std::string&, double>(&simgrid::s4u::NetZone::create_link),
272 "Creates a network link")
274 py::overload_cast<const std::string&, const std::string&>(&simgrid::s4u::NetZone::create_link),
275 "Creates a network link")
277 py::overload_cast<const std::string&, const std::vector<double>&>(&simgrid::s4u::NetZone::create_link),
278 "Creates a network link")
280 py::overload_cast<const std::string&, const std::vector<std::string>&>(&simgrid::s4u::NetZone::create_link),
281 "Creates a network link")
282 .def("create_split_duplex_link",
283 py::overload_cast<const std::string&, double>(&simgrid::s4u::NetZone::create_split_duplex_link),
284 "Creates a split-duplex link")
285 .def("create_split_duplex_link",
286 py::overload_cast<const std::string&, const std::string&>(&simgrid::s4u::NetZone::create_split_duplex_link),
287 "Creates a split-duplex link")
288 .def("create_router", &simgrid::s4u::NetZone::create_router, "Create a router")
289 .def("set_parent", &simgrid::s4u::NetZone::set_parent, "Set the parent of this zone")
290 .def("set_property", &simgrid::s4u::NetZone::set_property, "Add a property to this zone")
291 .def_property_readonly("netpoint", &simgrid::s4u::NetZone::get_netpoint,
292 "Retrieve the netpoint associated to this zone")
293 .def("seal", &simgrid::s4u::NetZone::seal, "Seal this NetZone")
294 .def_property_readonly("name", &simgrid::s4u::NetZone::get_name,
295 "The name of this network zone (read-only property).")
297 "__repr__", [](const simgrid::s4u::NetZone net) { return "NetZone(" + net.get_name() + ")"; },
298 "Textual representation of the NetZone");
300 /* Class ClusterCallbacks */
301 py::class_<simgrid::s4u::ClusterCallbacks>(m, "ClusterCallbacks", "Callbacks used to create cluster zones")
302 .def(py::init<const std::function<simgrid::s4u::ClusterCallbacks::ClusterNetPointCb>&,
303 const std::function<simgrid::s4u::ClusterCallbacks::ClusterLinkCb>&,
304 const std::function<simgrid::s4u::ClusterCallbacks::ClusterLinkCb>&>());
306 /* Class FatTreeParams */
307 py::class_<simgrid::s4u::FatTreeParams>(m, "FatTreeParams", "Parameters to create a Fat-Tree zone")
308 .def(py::init<unsigned int, const std::vector<unsigned int>&, const std::vector<unsigned int>&,
309 const std::vector<unsigned int>&>());
311 /* Class DragonflyParams */
312 py::class_<simgrid::s4u::DragonflyParams>(m, "DragonflyParams", "Parameters to create a Dragonfly zone")
313 .def(py::init<const std::pair<unsigned int, unsigned int>&, const std::pair<unsigned int, unsigned int>&,
314 const std::pair<unsigned int, unsigned int>&, unsigned int>());
317 py::class_<simgrid::s4u::Host, std::unique_ptr<Host, py::nodelete>> host(
318 m, "Host", "Simulated host. See the C++ documentation for details.");
319 host.def_static("by_name", &Host::by_name, py::arg("name"), "Retrieves a host from its name, or die")
322 [](const simgrid::s4u::Host* h, const simgrid::s4u::Host* to) {
323 auto* list = new std::vector<Link*>();
325 h->route_to(to, *list, &bw);
326 return make_tuple(list, bw);
328 "Retrieves the list of links and the bandwidth between two hosts.")
331 [](Host* h, const std::string& profile, double period) {
332 h->set_speed_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
334 py::call_guard<py::gil_scoped_release>(),
335 "Specify a profile modeling the external load according to an exhaustive list. "
336 "Each line of the profile describes timed events as ``date ratio``. "
337 "For example, the following content describes an host which computational speed is initially 1 (i.e, 100%) "
338 "and then halved after 42 seconds:\n\n"
339 ".. code-block:: python\n\n"
344 ".. warning:: Don't get fooled: bandwidth and latency profiles of links contain absolute values,"
345 " while speed profiles of hosts contain ratios.\n\n"
346 "The second function parameter is the periodicity: the time to wait after the last event to start again over "
347 "the list. Set it to -1 to not loop over.")
350 [](Host* h, const std::string& profile, double period) {
351 h->set_state_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
353 py::call_guard<py::gil_scoped_release>(),
354 "Specify a profile modeling the churn. "
355 "Each line of the profile describes timed events as ``date boolean``, where the boolean (0 or 1) tells "
356 "whether the host is on. "
357 "For example, the following content describes a link which turns off at t=1 and back on at t=2:\n\n"
358 ".. code-block:: python\n\n"
363 "The second function parameter is the periodicity: the time to wait after the last event to start again over "
364 "the list. Set it to -1 to not loop over.")
365 .def_property_readonly("pstate_count", &Host::get_pstate_count, "Retrieve the count of defined pstate levels")
366 .def("pstate_speed", &Host::get_pstate_speed, "Retrieve the maximal speed at the given pstate")
367 .def_property_readonly("netpoint", &Host::get_netpoint, "Retrieve the netpoint associated to this zone")
368 .def_property_readonly("disks", &Host::get_disks, "The list of disks on this host (read-only).")
369 .def("get_disks", &Host::get_disks, "Retrieve the list of disks in this host")
370 .def_property("core_count", &Host::get_core_count,
371 py::cpp_function(&Host::set_core_count, py::call_guard<py::gil_scoped_release>()),
372 "Manage the number of cores in the CPU")
373 .def("set_coordinates", &Host::set_coordinates, py::call_guard<py::gil_scoped_release>(),
374 "Set the coordinates of this host")
375 .def("set_sharing_policy", &simgrid::s4u::Host::set_sharing_policy, py::call_guard<py::gil_scoped_release>(),
376 "Describe how the CPU is shared", py::arg("policy"), py::arg("cb") = simgrid::s4u::NonLinearResourceCb())
377 .def("create_disk", py::overload_cast<const std::string&, double, double>(&Host::create_disk),
378 py::call_guard<py::gil_scoped_release>(), "Create a disk")
380 py::overload_cast<const std::string&, const std::string&, const std::string&>(&Host::create_disk),
381 py::call_guard<py::gil_scoped_release>(), "Create a disk")
382 .def("seal", &Host::seal, py::call_guard<py::gil_scoped_release>(), "Seal this host")
383 .def("turn_off", &Host::turn_off, py::call_guard<py::gil_scoped_release>(), "Turn off this host")
384 .def("turn_on", &Host::turn_on, py::call_guard<py::gil_scoped_release>(), "Turn on this host")
385 .def_property("pstate", &Host::get_pstate,
386 py::cpp_function(&Host::set_pstate, py::call_guard<py::gil_scoped_release>()),
387 "The current pstate (read/write property).")
388 .def_static("current", &Host::current, py::call_guard<py::gil_scoped_release>(),
389 "Retrieves the host on which the running actor is located.")
390 .def_property_readonly("name", &Host::get_name, "The name of this host (read-only property).")
391 .def_property_readonly("load", &Host::get_load,
392 "Returns the current computation load (in flops per second), NOT taking the external load "
393 "into account. This is the currently achieved speed (read-only property).")
394 .def_property_readonly(
395 "speed", &Host::get_speed,
396 "The peak computing speed in flops/s at the current pstate, NOT taking the external load into account. "
397 "This is the max potential speed (read-only property).")
398 .def_property_readonly("available_speed", &Host::get_available_speed,
399 "Get the available speed ratio, between 0 and 1.\n"
400 "This accounts for external load (see :py:func:`set_speed_profile() "
401 "<simgrid.Host.set_speed_profile>`) (read-only property).")
405 cb.inc_ref(); // keep alive after return
406 const py::gil_scoped_release gil_release;
407 Host::on_creation_cb([cb_p = cb.ptr()](Host& h) {
408 const py::gil_scoped_acquire py_context; // need a new context for callback
410 const auto fun = py::reinterpret_borrow<py::function>(cb_p);
412 } catch (const py::error_already_set& e) {
413 xbt_die("Error while executing the on_creation lambda : %s", e.what());
419 "__repr__", [](const Host* h) { return "Host(" + h->get_name() + ")"; },
420 "Textual representation of the Host.");
422 m.def("sg_host_load_plugin_init", [host]() {
423 sg_host_load_plugin_init();
425 static_cast<pybind11::class_<simgrid::s4u::Host, std::unique_ptr<simgrid::s4u::Host, pybind11::nodelete>>>(host)
427 "reset_load", [](const Host* h) { sg_host_load_reset(h); }, py::call_guard<py::gil_scoped_release>(),
428 "Reset counters of the host load plugin for this host.")
429 .def_property_readonly(
430 "current_load", [](const Host* h) { return sg_host_get_current_load(h); }, "Current load of the host.")
431 .def_property_readonly(
432 "avg_load", [](const Host* h) { return sg_host_get_avg_load(h); }, "Average load of the host.")
433 .def_property_readonly(
434 "idle_time", [](const Host* h) { return sg_host_get_idle_time(h); }, "Idle time of the host")
435 .def_property_readonly(
436 "total_idle_time", [](const Host* h) { return sg_host_get_total_idle_time(h); },
437 "Total idle time of the host.")
438 .def_property_readonly(
439 "computed_flops", [](const Host* h) { return sg_host_get_computed_flops(h); },
440 "Computed flops of the host.");
443 py::enum_<simgrid::s4u::Host::SharingPolicy>(host, "SharingPolicy")
444 .value("NONLINEAR", simgrid::s4u::Host::SharingPolicy::NONLINEAR)
445 .value("LINEAR", simgrid::s4u::Host::SharingPolicy::LINEAR)
449 py::class_<simgrid::s4u::Disk, std::unique_ptr<simgrid::s4u::Disk, py::nodelete>> disk(
450 m, "Disk", "Simulated disk. See the C++ documentation for details.");
451 disk.def("read", py::overload_cast<sg_size_t, double>(&simgrid::s4u::Disk::read, py::const_),
452 py::call_guard<py::gil_scoped_release>(), "Read data from disk", py::arg("size"), py::arg("priority") = 1)
453 .def("write", py::overload_cast<sg_size_t, double>(&simgrid::s4u::Disk::write, py::const_),
454 py::call_guard<py::gil_scoped_release>(), "Write data in disk", py::arg("size"), py::arg("priority") = 1)
455 .def("read_async", &simgrid::s4u::Disk::read_async, py::call_guard<py::gil_scoped_release>(),
456 "Non-blocking read data from disk")
457 .def("write_async", &simgrid::s4u::Disk::write_async, py::call_guard<py::gil_scoped_release>(),
458 "Non-blocking write data in disk")
459 .def("set_sharing_policy", &simgrid::s4u::Disk::set_sharing_policy, py::call_guard<py::gil_scoped_release>(),
460 "Set sharing policy for this disk", py::arg("op"), py::arg("policy"),
461 py::arg("cb") = simgrid::s4u::NonLinearResourceCb())
462 .def("seal", &simgrid::s4u::Disk::seal, py::call_guard<py::gil_scoped_release>(), "Seal this disk")
463 .def_property_readonly("name", &simgrid::s4u::Disk::get_name, "The name of this disk (read-only property).")
465 "__repr__", [](const Disk* d) { return "Disk(" + d->get_name() + ")"; },
466 "Textual representation of the Disk");
467 py::enum_<simgrid::s4u::Disk::SharingPolicy>(disk, "SharingPolicy")
468 .value("NONLINEAR", simgrid::s4u::Disk::SharingPolicy::NONLINEAR)
469 .value("LINEAR", simgrid::s4u::Disk::SharingPolicy::LINEAR)
471 py::enum_<simgrid::s4u::Disk::Operation>(disk, "Operation")
472 .value("READ", simgrid::s4u::Disk::Operation::READ)
473 .value("WRITE", simgrid::s4u::Disk::Operation::WRITE)
474 .value("READWRITE", simgrid::s4u::Disk::Operation::READWRITE)
478 py::class_<simgrid::kernel::routing::NetPoint, std::unique_ptr<simgrid::kernel::routing::NetPoint, py::nodelete>>
479 netpoint(m, "NetPoint", "NetPoint object");
482 py::class_<Link, std::unique_ptr<Link, py::nodelete>> link(m, "Link",
483 "Network link. See the C++ documentation for details.");
484 link.def("set_latency", py::overload_cast<const std::string&>(&Link::set_latency),
485 py::call_guard<py::gil_scoped_release>(),
486 "Set the latency as a string. Accepts values with units, such as ‘1s’ or ‘7ms’.\nFull list of accepted "
487 "units: w (week), d (day), h, s, ms, us, ns, ps.")
488 .def("set_latency", py::overload_cast<double>(&Link::set_latency), py::call_guard<py::gil_scoped_release>(),
489 "Set the latency as a float (in seconds).")
490 .def("set_bandwidth", &Link::set_bandwidth, py::call_guard<py::gil_scoped_release>(),
491 "Set the bandwidth (in byte per second).")
493 "set_bandwidth_profile",
494 [](Link* l, const std::string& profile, double period) {
495 l->set_bandwidth_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
497 py::call_guard<py::gil_scoped_release>(),
498 "Specify a profile modeling the external load according to an exhaustive list. "
499 "Each line of the profile describes timed events as ``date bandwidth`` (in bytes per second). "
500 "For example, the following content describes a link which bandwidth changes to 40 Mb/s at t=4, and to 6 "
502 ".. code-block:: python\n\n"
507 ".. warning:: Don't get fooled: bandwidth and latency profiles of links contain absolute values,"
508 " while speed profiles of hosts contain ratios.\n\n"
509 "The second function parameter is the periodicity: the time to wait after the last event to start again over "
510 "the list. Set it to -1 to not loop over.")
512 "set_latency_profile",
513 [](Link* l, const std::string& profile, double period) {
514 l->set_latency_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
516 py::call_guard<py::gil_scoped_release>(),
517 "Specify a profile modeling the external load according to an exhaustive list. "
518 "Each line of the profile describes timed events as ``date latency`` (in seconds). "
519 "For example, the following content describes a link which latency changes to 1ms (0.001s) at t=1, and to 2s "
521 ".. code-block:: python\n\n"
526 ".. warning:: Don't get fooled: bandwidth and latency profiles of links contain absolute values,"
527 " while speed profiles of hosts contain ratios.\n\n"
528 "The second function parameter is the periodicity: the time to wait after the last event to start again over "
529 "the list. Set it to -1 to not loop over.")
532 [](Link* l, const std::string& profile, double period) {
533 l->set_state_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
535 "Specify a profile modeling the churn. "
536 "Each line of the profile describes timed events as ``date boolean``, where the boolean (0 or 1) tells "
537 "whether the link is on. "
538 "For example, the following content describes a link which turns off at t=1 and back on at t=2:\n\n"
539 ".. code-block:: python\n\n"
544 "The second function parameter is the periodicity: the time to wait after the last event to start again over "
545 "the list. Set it to -1 to not loop over.")
547 .def("turn_on", &Link::turn_on, py::call_guard<py::gil_scoped_release>(), "Turns the link on.")
548 .def("turn_off", &Link::turn_off, py::call_guard<py::gil_scoped_release>(), "Turns the link off.")
549 .def("is_on", &Link::is_on, "Check whether the link is on.")
551 .def("set_sharing_policy", &Link::set_sharing_policy, py::call_guard<py::gil_scoped_release>(),
552 "Set sharing policy for this link")
553 .def("set_concurrency_limit", &Link::set_concurrency_limit, py::call_guard<py::gil_scoped_release>(),
554 "Set concurrency limit for this link")
555 .def("set_host_wifi_rate", &Link::set_host_wifi_rate, py::call_guard<py::gil_scoped_release>(),
556 "Set level of communication speed of given host on this Wi-Fi link")
557 .def_static("by_name", &Link::by_name, "Retrieves a Link from its name, or dies")
558 .def("seal", &Link::seal, py::call_guard<py::gil_scoped_release>(), "Seal this link")
559 .def_property_readonly("name", &Link::get_name, "The name of this link")
560 .def_property_readonly("bandwidth", &Link::get_bandwidth,
561 "The bandwidth (in bytes per second) (read-only property).")
562 .def_property_readonly("latency", &Link::get_latency, "The latency (in seconds) (read-only property).")
564 "__repr__", [](const Link* l) { return "Link(" + l->get_name() + ")"; },
565 "Textual representation of the Link");
566 py::enum_<Link::SharingPolicy>(link, "SharingPolicy")
567 .value("NONLINEAR", Link::SharingPolicy::NONLINEAR)
568 .value("WIFI", Link::SharingPolicy::WIFI)
569 .value("SPLITDUPLEX", Link::SharingPolicy::SPLITDUPLEX)
570 .value("SHARED", Link::SharingPolicy::SHARED)
571 .value("FATPIPE", Link::SharingPolicy::FATPIPE)
574 /* Class LinkInRoute */
575 py::class_<simgrid::s4u::LinkInRoute> linkinroute(m, "LinkInRoute", "Abstraction to add link in routes");
576 linkinroute.def(py::init<const Link*>());
577 linkinroute.def(py::init<const Link*, simgrid::s4u::LinkInRoute::Direction>());
578 py::enum_<simgrid::s4u::LinkInRoute::Direction>(linkinroute, "Direction")
579 .value("UP", simgrid::s4u::LinkInRoute::Direction::UP)
580 .value("DOWN", simgrid::s4u::LinkInRoute::Direction::DOWN)
581 .value("NONE", simgrid::s4u::LinkInRoute::Direction::NONE)
584 /* Class Split-Duplex Link */
585 py::class_<simgrid::s4u::SplitDuplexLink, Link, std::unique_ptr<simgrid::s4u::SplitDuplexLink, py::nodelete>>(
586 m, "SplitDuplexLink", "Network split-duplex link")
587 .def_property_readonly("link_up", &simgrid::s4u::SplitDuplexLink::get_link_up, "Get link direction up")
588 .def_property_readonly("link_down", &simgrid::s4u::SplitDuplexLink::get_link_down, "Get link direction down");
591 py::class_<simgrid::s4u::Mailbox, std::unique_ptr<Mailbox, py::nodelete>>(
592 m, "Mailbox", "Mailbox. See the C++ documentation for details.")
594 "__repr__", [](const Mailbox* self) { return "Mailbox(" + self->get_name() + ")"; },
595 "Textual representation of the Mailbox")
596 .def_static("by_name", &Mailbox::by_name, py::call_guard<py::gil_scoped_release>(), py::arg("name"),
597 "Retrieve a Mailbox from its name")
598 .def_property_readonly("name", &Mailbox::get_name, "The name of that mailbox (read-only property).")
599 .def_property_readonly("ready", &Mailbox::ready,
600 "Check if there is a communication ready to be consumed from a mailbox.")
603 [](Mailbox* self, py::object data, uint64_t size, double timeout) {
604 auto* data_ptr = data.inc_ref().ptr();
605 const py::gil_scoped_release gil_release;
606 self->put(data_ptr, size, timeout);
608 "Blocking data transmission with a timeout")
611 [](Mailbox* self, py::object data, uint64_t size) {
612 auto* data_ptr = data.inc_ref().ptr();
613 const py::gil_scoped_release gil_release;
614 self->put(data_ptr, size);
616 "Blocking data transmission")
619 [](Mailbox* self, py::object data, uint64_t size) {
620 auto* data_ptr = data.inc_ref().ptr();
621 const py::gil_scoped_release gil_release;
622 return self->put_async(data_ptr, size);
624 "Non-blocking data transmission")
627 [](Mailbox* self, py::object data, uint64_t size) {
628 auto* data_ptr = data.inc_ref().ptr();
629 const py::gil_scoped_release gil_release;
630 return self->put_init(data_ptr, size);
632 "Creates (but don’t start) a data transmission to that mailbox.")
634 "get", [](Mailbox* self) { return py::reinterpret_steal<py::object>(self->get<PyObject>()); },
635 py::call_guard<py::gil_scoped_release>(), "Blocking data reception")
638 [](Mailbox* self) -> std::tuple<CommPtr, PyGetAsync> {
640 auto comm = self->get_async(wrap.get());
641 return std::make_tuple(std::move(comm), std::move(wrap));
643 py::call_guard<py::gil_scoped_release>(),
644 "Non-blocking data reception. Use data.get() to get the python object after the communication has finished")
645 .def("set_receiver", &Mailbox::set_receiver, py::call_guard<py::gil_scoped_release>(),
646 "Sets the actor as permanent receiver");
648 /* Class PyGetAsync */
649 py::class_<PyGetAsync>(m, "PyGetAsync", "Wrapper for async get communications")
652 "get", [](const PyGetAsync* self) { return py::reinterpret_steal<py::object>(*(self->get())); },
653 "Get python object after async communication in receiver side");
656 py::class_<Activity, ActivityPtr>(m, "Activityy", "Activity. See the C++ documentation for details.");
659 py::class_<Comm, CommPtr, Activity>(m, "Comm", "Communication. See the C++ documentation for details.")
660 .def_property_readonly("dst_data_size", &Comm::get_dst_data_size, py::call_guard<py::gil_scoped_release>(),
661 "Retrieve the size of the received data.")
662 .def_property_readonly("mailbox", &Comm::get_mailbox, py::call_guard<py::gil_scoped_release>(),
663 "Retrieve the mailbox on which this comm acts.")
664 .def_property_readonly("sender", &Comm::get_sender, py::call_guard<py::gil_scoped_release>())
665 .def_property_readonly("state_str", &Comm::get_state_str, py::call_guard<py::gil_scoped_release>(),
666 "Retrieve the Comm state as string")
667 .def_property_readonly("remaining", &Comm::get_remaining, py::call_guard<py::gil_scoped_release>(),
668 "Remaining amount of work that this Comm entails")
669 .def_property_readonly("start_time", &Comm::get_start_time, py::call_guard<py::gil_scoped_release>(),
670 "Time at which this Comm started")
671 .def_property_readonly("finish_time", &Comm::get_finish_time, py::call_guard<py::gil_scoped_release>(),
672 "Time at which this Comm finished")
673 .def_property_readonly("is_suspended", &Comm::is_suspended, py::call_guard<py::gil_scoped_release>(),
674 "Whether this Comm is suspended")
675 .def("set_payload_size", &Comm::set_payload_size, py::call_guard<py::gil_scoped_release>(), py::arg("bytes"),
676 "Specify the amount of bytes which exchange should be simulated.")
677 .def("set_rate", &Comm::set_rate, py::call_guard<py::gil_scoped_release>(), py::arg("rate"),
678 "Sets the maximal communication rate (in byte/sec). Must be done before start")
679 .def("cancel", &Comm::cancel, py::call_guard<py::gil_scoped_release>(),
680 py::return_value_policy::reference_internal, "Cancel the activity.")
681 .def("start", &Comm::start, py::call_guard<py::gil_scoped_release>(), py::return_value_policy::reference_internal,
682 "Starts a previously created activity. This function is optional: you can call wait() even if you didn't "
684 .def("suspend", &Comm::suspend, py::call_guard<py::gil_scoped_release>(),
685 py::return_value_policy::reference_internal, "Suspend the activity.")
686 .def("resume", &Comm::resume, py::call_guard<py::gil_scoped_release>(),
687 py::return_value_policy::reference_internal, "Resume the activity.")
688 .def("test", &Comm::test, py::call_guard<py::gil_scoped_release>(),
689 "Test whether the communication is terminated.")
690 .def("wait", &Comm::wait, py::call_guard<py::gil_scoped_release>(),
691 "Block until the completion of that communication.")
692 .def("wait_for", &Comm::wait_for, py::call_guard<py::gil_scoped_release>(), py::arg("timeout"),
693 "Block until the completion of that communication, or raises TimeoutException after the specified timeout.")
694 .def("wait_until", &Comm::wait_until, py::call_guard<py::gil_scoped_release>(), py::arg("time_limit"),
695 "Block until the completion of that communication, or raises TimeoutException after the specified time.")
696 .def("detach", py::overload_cast<>(&Comm::detach), py::return_value_policy::reference_internal,
697 py::call_guard<py::gil_scoped_release>(),
698 "Start the comm, and ignore its result. It can be completely forgotten after that.")
699 .def_static("sendto", &Comm::sendto, py::call_guard<py::gil_scoped_release>(), py::arg("from"), py::arg("to"),
700 py::arg("simulated_size_in_bytes"), "Do a blocking communication between two arbitrary hosts.")
701 .def_static("sendto_init", py::overload_cast<Host*, Host*>(&Comm::sendto_init),
702 py::call_guard<py::gil_scoped_release>(), py::arg("from"), py::arg("to"),
703 "Creates a communication between the two given hosts, bypassing the mailbox mechanism.")
704 .def_static("sendto_async", &Comm::sendto_async, py::call_guard<py::gil_scoped_release>(), py::arg("from"),
705 py::arg("to"), py::arg("simulated_size_in_bytes"),
706 "Do a blocking communication between two arbitrary hosts.\n\nThis initializes a communication that "
707 "completely bypass the mailbox and actors mechanism. There is really no limit on the hosts involved. "
708 "In particular, the actor does not have to be on one of the involved hosts.")
709 .def_static("test_any", &Comm::test_any, py::call_guard<py::gil_scoped_release>(), py::arg("comms"),
710 "take a vector s4u::CommPtr and return the rank of the first finished one (or -1 if none is done)")
711 .def_static("wait_all", &Comm::wait_all, py::call_guard<py::gil_scoped_release>(), py::arg("comms"),
712 "Block until the completion of all communications in the list.")
713 .def_static("wait_all_for", &Comm::wait_all_for, py::call_guard<py::gil_scoped_release>(), py::arg("comms"),
715 "Block until the completion of all communications in the list, or raises TimeoutException after "
716 "the specified timeout.")
717 .def_static("wait_any", &Comm::wait_any, py::call_guard<py::gil_scoped_release>(), py::arg("comms"),
718 "Block until the completion of any communication in the list and return the index of the "
720 .def_static("wait_any_for", &Comm::wait_any_for, py::call_guard<py::gil_scoped_release>(), py::arg("comms"),
722 "Block until the completion of any communication in the list and return the index of the terminated "
723 "one, or -1 if a timeout occurred.");
726 py::class_<simgrid::s4u::Io, simgrid::s4u::IoPtr, Activity>(m, "Io",
727 "I/O activities. See the C++ documentation for details.")
728 .def("test", &simgrid::s4u::Io::test, py::call_guard<py::gil_scoped_release>(),
729 "Test whether the I/O is terminated.")
730 .def("wait", &simgrid::s4u::Io::wait, py::call_guard<py::gil_scoped_release>(),
731 "Block until the completion of that I/O operation")
733 "wait_any_for", &simgrid::s4u::Io::wait_any_for, py::call_guard<py::gil_scoped_release>(),
734 "Block until the completion of any I/O in the list (or timeout) and return the index of the terminated one.")
735 .def_static("wait_any", &simgrid::s4u::Io::wait_any, py::call_guard<py::gil_scoped_release>(),
736 "Block until the completion of any I/O in the list and return the index of the terminated one.");
739 py::class_<simgrid::s4u::Exec, simgrid::s4u::ExecPtr, Activity>(m, "Exec",
740 "Execution. See the C++ documentation for details.")
741 .def_property_readonly("remaining", &simgrid::s4u::Exec::get_remaining, py::call_guard<py::gil_scoped_release>(),
742 "Amount of flops that remain to be computed until completion (read-only property).")
743 .def_property_readonly("remaining_ratio", &simgrid::s4u::Exec::get_remaining_ratio,
744 py::call_guard<py::gil_scoped_release>(),
745 "Amount of work remaining until completion from 0 (completely done) to 1 (nothing done "
746 "yet) (read-only property).")
747 .def_property("host", &simgrid::s4u::Exec::get_host, &simgrid::s4u::Exec::set_host,
748 "Host on which this execution runs. Only the first host is returned for parallel executions. "
749 "Changing this value migrates the execution.")
750 .def_property_readonly("is_suspended", &simgrid::s4u::Exec::is_suspended,
751 py::call_guard<py::gil_scoped_release>(), "Whether this Exec is suspended")
752 .def("test", &simgrid::s4u::Exec::test, py::call_guard<py::gil_scoped_release>(),
753 "Test whether the execution is terminated.")
754 .def("cancel", &simgrid::s4u::Exec::cancel, py::call_guard<py::gil_scoped_release>(), "Cancel that execution.")
755 .def("start", &simgrid::s4u::Exec::start, py::call_guard<py::gil_scoped_release>(), "Start that execution.")
756 .def("suspend", &simgrid::s4u::Exec::suspend, py::call_guard<py::gil_scoped_release>(), "Suspend that execution.")
757 .def("resume", &simgrid::s4u::Exec::resume, py::call_guard<py::gil_scoped_release>(), "Resume that execution.")
758 .def("wait", &simgrid::s4u::Exec::wait, py::call_guard<py::gil_scoped_release>(),
759 "Block until the completion of that execution.")
760 .def("wait_for", &simgrid::s4u::Exec::wait_for, py::call_guard<py::gil_scoped_release>(), py::arg("timeout"),
761 "Block until the completion of that activity, or raises TimeoutException after the specified timeout.");
763 /* Class Semaphore */
764 py::class_<Semaphore, SemaphorePtr>(m, "Semaphore",
765 "A classical semaphore, but blocking in the simulation world. See the C++ "
766 "documentation for details.")
767 .def(py::init<>(&Semaphore::create), py::call_guard<py::gil_scoped_release>(), py::arg("capacity"),
768 "Semaphore constructor.")
769 .def("acquire", &Semaphore::acquire, py::call_guard<py::gil_scoped_release>(),
770 "Acquire on the semaphore object with no timeout. Blocks until the semaphore is acquired.")
771 .def("acquire_timeout", &Semaphore::acquire_timeout, py::call_guard<py::gil_scoped_release>(), py::arg("timeout"),
772 "Acquire on the semaphore object with no timeout. Blocks until the semaphore is acquired or return "
773 "true if it has not been acquired after the specified timeout.")
774 .def("release", &Semaphore::release, py::call_guard<py::gil_scoped_release>(), "Release the semaphore.")
775 .def_property_readonly("capacity", &Semaphore::get_capacity, py::call_guard<py::gil_scoped_release>(),
776 "Get the semaphore capacity.")
777 .def_property_readonly("would_block", &Semaphore::would_block, py::call_guard<py::gil_scoped_release>(),
778 "Check whether trying to acquire the semaphore would block (in other word, checks whether "
779 "this semaphore has capacity).")
780 // Allow semaphores to be automatically acquired/released with a context manager: `with semaphore: ...`
781 .def("__enter__", &Semaphore::acquire, py::call_guard<py::gil_scoped_release>())
783 [](Semaphore* self, const py::object&, const py::object&, const py::object&) { self->release(); });
786 py::class_<Mutex, MutexPtr>(m, "Mutex",
787 "A classical mutex, but blocking in the simulation world."
788 "See the C++ documentation for details.")
789 .def(py::init<>(&Mutex::create), py::call_guard<py::gil_scoped_release>(), "Mutex constructor.")
790 .def("lock", &Mutex::lock, py::call_guard<py::gil_scoped_release>(), "Block until the mutex is acquired.")
791 .def("try_lock", &Mutex::try_lock, py::call_guard<py::gil_scoped_release>(),
792 "Try to acquire the mutex. Return true if the mutex was acquired, false otherwise.")
793 .def("unlock", &Mutex::unlock, py::call_guard<py::gil_scoped_release>(), "Release the mutex.")
794 // Allow mutexes to be automatically acquired/released with a context manager: `with mutex: ...`
795 .def("__enter__", &Mutex::lock, py::call_guard<py::gil_scoped_release>())
797 "__exit__", [](Mutex* self, const py::object&, const py::object&, const py::object&) { self->unlock(); },
798 py::call_guard<py::gil_scoped_release>());
801 py::class_<Barrier, BarrierPtr>(m, "Barrier", "A classical barrier, but blocking in the simulation world.")
802 .def(py::init<>(&Barrier::create), py::call_guard<py::gil_scoped_release>(), py::arg("expected_actors"),
803 "Barrier constructor.")
804 .def("wait", &Barrier::wait, py::call_guard<py::gil_scoped_release>(),
805 "Blocks into the barrier. Every waiting actors will be unlocked once the expected amount of actors reaches "
809 py::class_<simgrid::s4u::Actor, ActorPtr>(m, "Actor",
810 "An actor is an independent stream of execution in your distributed "
811 "application. See the C++ documentation for details.")
814 [](const std::string& name, Host* h, py::object fun, py::args args) {
815 fun.inc_ref(); // keep alive after return
816 args.inc_ref(); // keep alive after return
817 const py::gil_scoped_release gil_release;
818 return simgrid::s4u::Actor::create(name, h, [fun_p = fun.ptr(), args_p = args.ptr()]() {
819 const py::gil_scoped_acquire py_context;
821 const auto fun = py::reinterpret_borrow<py::object>(fun_p);
822 const auto args = py::reinterpret_borrow<py::args>(args_p);
824 } catch (const py::error_already_set& ex) {
825 if (ex.matches(pyForcefulKillEx)) {
826 XBT_VERB("Actor killed");
827 simgrid::ForcefulKillException::do_throw(); // Forward that ForcefulKill exception
833 "Create an actor from a function or an object. See the :ref:`example <s4u_ex_actors_create>`.")
835 "host", &Actor::get_host, py::cpp_function(&Actor::set_host, py::call_guard<py::gil_scoped_release>()),
836 "The host on which this actor is located. Changing this value migrates the actor.\n\n"
837 "If the actor is currently blocked on an execution activity, the activity is also migrated to the new host. "
838 "If it’s blocked on another kind of activity, an error is raised as the mandated code is not written yet. "
839 "Please report that bug if you need it.\n\n"
840 "Asynchronous activities started by the actor are not migrated automatically, so you have to take care of "
841 "this yourself (only you knows which ones should be migrated). ")
842 .def_property_readonly("name", &Actor::get_cname, "The name of this actor (read-only property).")
843 .def_property_readonly("pid", &Actor::get_pid, "The PID (unique identifier) of this actor (read-only property).")
844 .def_property_readonly("ppid", &Actor::get_ppid,
845 "The PID (unique identifier) of the actor that created this one (read-only property).")
846 .def_static("by_pid", &Actor::by_pid, py::arg("pid"), "Retrieve an actor by its PID")
847 .def("set_auto_restart", &Actor::set_auto_restart, py::call_guard<py::gil_scoped_release>(),
848 "Specify whether the actor shall restart when its host reboots.")
849 .def("daemonize", &Actor::daemonize, py::call_guard<py::gil_scoped_release>(),
850 "This actor will be automatically terminated when the last non-daemon actor finishes (more info in the C++ "
852 .def("is_daemon", &Actor::is_daemon,
853 "Returns True if that actor is a daemon and will be terminated automatically when the last non-daemon actor "
855 .def("join", py::overload_cast<double>(&Actor::join, py::const_), py::call_guard<py::gil_scoped_release>(),
856 "Wait for the actor to finish (more info in the C++ documentation).", py::arg("timeout") = -1)
857 .def("kill", &Actor::kill, py::call_guard<py::gil_scoped_release>(), "Kill that actor")
858 .def("self", &Actor::self, "Retrieves the current actor.")
859 .def("is_suspended", &Actor::is_suspended, "Returns True if that actor is currently suspended.")
860 .def("suspend", &Actor::suspend, py::call_guard<py::gil_scoped_release>(),
861 "Suspend that actor, that is blocked until resume()ed by another actor.")
862 .def("resume", &Actor::resume, py::call_guard<py::gil_scoped_release>(),
863 "Resume that actor, that was previously suspend()ed.")
864 .def_static("kill_all", &Actor::kill_all, py::call_guard<py::gil_scoped_release>(),
865 "Kill all actors but the caller.")
867 "__repr__", [](const ActorPtr a) { return "Actor(" + a->get_name() + ")"; },
868 "Textual representation of the Actor");
870 /* Enum Class IoOpType */
871 py::enum_<simgrid::s4u::Io::OpType>(m, "IoOpType")
872 .value("READ", simgrid::s4u::Io::OpType::READ)
873 .value("WRITE", simgrid::s4u::Io::OpType::WRITE);
876 py::class_<Task, TaskPtr>(m, "Task", "Task. See the C++ documentation for details.")
880 cb.inc_ref(); // keep alive after return
881 const py::gil_scoped_release gil_release;
882 Task::on_start_cb([cb_p = cb.ptr()](Task* op) {
883 const py::gil_scoped_acquire py_context; // need a new context for callback
884 py::reinterpret_borrow<py::function>(cb_p)(op);
887 "Add a callback called when each task starts.")
891 cb.inc_ref(); // keep alive after return
892 const py::gil_scoped_release gil_release;
893 Task::on_completion_cb([cb_p = cb.ptr()](Task* op) {
894 const py::gil_scoped_acquire py_context; // need a new context for callback
895 py::reinterpret_borrow<py::function>(cb_p)(op);
898 "Add a callback called when each task ends.")
899 .def_property_readonly("name", &Task::get_name, "The name of this task (read-only).")
900 .def_property_readonly("count", &Task::get_count, "The execution count of this task (read-only).")
901 .def_property_readonly("successors", &Task::get_successors, "The successors of this task (read-only).")
902 .def_property("amount", &Task::get_amount, &Task::set_amount, "The amount of work to do for this task.")
903 .def("enqueue_firings", py::overload_cast<int>(&Task::enqueue_firings), py::call_guard<py::gil_scoped_release>(),
904 py::arg("n"), "Enqueue firings for this task.")
905 .def("add_successor", py::overload_cast<TaskPtr>(&Task::add_successor), py::call_guard<py::gil_scoped_release>(),
906 py::arg("op"), "Add a successor to this task.")
907 .def("remove_successor", py::overload_cast<TaskPtr>(&Task::remove_successor),
908 py::call_guard<py::gil_scoped_release>(), py::arg("op"), "Remove a successor of this task.")
909 .def("remove_all_successors", &Task::remove_all_successors, py::call_guard<py::gil_scoped_release>(),
910 "Remove all successors of this task.")
911 .def("on_this_start_cb", py::overload_cast<const std::function<void(Task*)>&>(&Task::on_this_start_cb),
912 py::arg("func"), "Add a callback called when this task starts.")
913 .def("on_this_completion_cb", py::overload_cast<const std::function<void(Task*)>&>(&Task::on_this_completion_cb),
914 py::arg("func"), "Add a callback called when this task ends.")
916 "__repr__", [](const TaskPtr op) { return "Task(" + op->get_name() + ")"; },
917 "Textual representation of the Task");
920 py::class_<CommTask, CommTaskPtr, Task>(m, "CommTask", "Communication Task. See the C++ documentation for details.")
921 .def_static("init", py::overload_cast<const std::string&>(&CommTask::init),
922 py::call_guard<py::gil_scoped_release>(), py::arg("name"), "CommTask constructor")
923 .def_static("init", py::overload_cast<const std::string&, double, Host*, Host*>(&CommTask::init),
924 py::call_guard<py::gil_scoped_release>(), py::arg("name"), py::arg("bytes"), py::arg("source"),
925 py::arg("destination"), "CommTask constructor")
926 .def_property("source", &CommTask::get_source, &CommTask::set_source, "The source of the communication.")
927 .def_property("destination", &CommTask::get_destination, &CommTask::set_destination,
928 "The destination of the communication.")
929 .def_property("bytes", &CommTask::get_bytes, &CommTask::set_bytes, "The amount of bytes to send.")
931 "__repr__", [](const CommTaskPtr c) { return "CommTask(" + c->get_name() + ")"; },
932 "Textual representation of the CommTask");
935 py::class_<ExecTask, ExecTaskPtr, Task>(m, "ExecTask", "Execution Task. See the C++ documentation for details.")
936 .def_static("init", py::overload_cast<const std::string&>(&ExecTask::init),
937 py::call_guard<py::gil_scoped_release>(), py::arg("name"), "ExecTask constructor")
938 .def_static("init", py::overload_cast<const std::string&, double, Host*>(&ExecTask::init),
939 py::call_guard<py::gil_scoped_release>(), py::arg("name"), py::arg("flops"), py::arg("host"),
940 "CommTask constructor.")
941 .def_property("host", &ExecTask::get_host, &ExecTask::set_host, "The host of the execution.")
942 .def_property("flops", &ExecTask::get_flops, &ExecTask::set_flops, "The amount of flops to execute.")
944 "__repr__", [](const ExecTaskPtr e) { return "ExecTask(" + e->get_name() + ")"; },
945 "Textual representation of the ExecTask");
948 py::class_<IoTask, IoTaskPtr, Task>(m, "IoTask", "IO Task. See the C++ documentation for details.")
949 .def_static("init", py::overload_cast<const std::string&>(&IoTask::init),
950 py::call_guard<py::gil_scoped_release>(), py::arg("name"), "IoTask constructor")
951 .def_static("init", py::overload_cast<const std::string&, double, Disk*, Io::OpType>(&IoTask::init),
952 py::call_guard<py::gil_scoped_release>(), py::arg("name"), py::arg("bytes"), py::arg("disk"),
953 py::arg("type"), "IoTask constructor.")
954 .def_property("disk", &IoTask::get_disk, &IoTask::set_disk, "The disk of the IO.")
955 .def_property("bytes", &IoTask::get_bytes, &IoTask::set_bytes, "The amount of bytes to process.")
956 .def_property("type", &IoTask::get_bytes, &IoTask::set_bytes, "The type of IO.")
958 "__repr__", [](const IoTaskPtr io) { return "IoTask(" + io->get_name() + ")"; },
959 "Textual representation of the IoTask");
961 /* Class ActivitySet */
962 py::class_<ActivitySet, ActivitySetPtr>(m, "ActivitySet", "ActivitySet. See the C++ documentation for details.")
963 .def(py::init([](std::vector<simgrid::s4u::ActivityPtr> activities) {
964 auto* ret = new ActivitySet();
965 for (auto a : activities)
967 return ActivitySetPtr(ret);
969 "The constructor should take the parameters from the command line, as is ")
970 .def(py::init([]() { return ActivitySetPtr(new ActivitySet()); }),
971 "The constructor should take the parameters from the command line, as is ")
973 .def("push", &ActivitySet::push, py::call_guard<py::gil_scoped_release>(), py::arg("activity"),
974 "Add an activity to the set")
975 .def("erase", &ActivitySet::erase, py::call_guard<py::gil_scoped_release>(), py::arg("activity"),
976 "Remove that activity from the set")
977 .def_property_readonly("size", &ActivitySet::size, "Count of activities in the set")
978 .def("empty", &ActivitySet::empty, "Returns whether the set is empty")
979 .def("has_failed_activities", &ActivitySet::has_failed_activities,
980 "Returns whether there is any failed activities")
981 .def("get_failed_activity", &ActivitySet::get_failed_activity, "Returns a failed activity from the set, or None")
983 .def("wait_all_for", &ActivitySet::wait_all_for, py::call_guard<py::gil_scoped_release>(), py::arg("timeout"),
984 "Wait for the completion of all activities in the set, but not longer than the provided timeout")
985 .def("wait_all", &ActivitySet::wait_all, py::call_guard<py::gil_scoped_release>(),
986 "Wait for the completion of all activities in the set, endlessly")
987 .def("test_any", &ActivitySet::test_any, py::call_guard<py::gil_scoped_release>(),
988 "Returns the first terminated activity if any, or None if no activity is terminated")
989 .def("wait_any_for", &ActivitySet::wait_any_for, py::call_guard<py::gil_scoped_release>(), py::arg("timeout"),
990 "Wait for the completion of one activity in the set, but not longer than the provided timeout")
991 .def("wait_any", &ActivitySet::wait_any, py::call_guard<py::gil_scoped_release>(),
992 "Wait for the completion of one activity in the set, endlessly")
995 "__repr__", [](const ActivitySetPtr as) { return "ActivitySet([...])"; },
996 "Textual representation of the ActivitySet");