Logo AND Algorithmique Numérique Distribuée

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