Logo AND Algorithmique Numérique Distribuée

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