Logo AND Algorithmique Numérique Distribuée

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