Logo AND Algorithmique Numérique Distribuée

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