Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'stable'
[simgrid.git] / src / bindings / python / simgrid_python.cpp
1 /* Copyright (c) 2018-2022. 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 #ifdef _WIN32
7 #warning Try to work around https://bugs.python.org/issue11566
8 #define _hypot hypot
9 #endif
10
11 #if defined(__GNUG__)
12 #pragma GCC diagnostic push
13 #pragma GCC diagnostic ignored "-Wunused-value"
14 #endif
15
16 #include <pybind11/pybind11.h> // Must come before our own stuff
17
18 #include <pybind11/functional.h>
19 #include <pybind11/stl.h>
20
21 #if defined(__GNUG__)
22 #pragma GCC diagnostic pop
23 #endif
24
25 #include "simgrid/kernel/ProfileBuilder.hpp"
26 #include "simgrid/kernel/routing/NetPoint.hpp"
27 #include "src/kernel/context/Context.hpp"
28 #include <simgrid/Exception.hpp>
29 #include <simgrid/s4u/Actor.hpp>
30 #include <simgrid/s4u/Comm.hpp>
31 #include <simgrid/s4u/Disk.hpp>
32 #include <simgrid/s4u/Engine.hpp>
33 #include <simgrid/s4u/Exec.hpp>
34 #include <simgrid/s4u/Host.hpp>
35 #include <simgrid/s4u/Link.hpp>
36 #include <simgrid/s4u/Mailbox.hpp>
37 #include <simgrid/s4u/NetZone.hpp>
38 #include <simgrid/version.h>
39
40 #include <algorithm>
41 #include <memory>
42 #include <string>
43 #include <vector>
44
45 namespace py = pybind11;
46 using simgrid::s4u::Actor;
47 using simgrid::s4u::ActorPtr;
48 using simgrid::s4u::Engine;
49 using simgrid::s4u::Host;
50 using simgrid::s4u::Link;
51 using simgrid::s4u::Mailbox;
52
53 XBT_LOG_NEW_DEFAULT_CATEGORY(python, "python");
54
55 namespace {
56
57 std::string get_simgrid_version()
58 {
59   int major;
60   int minor;
61   int patch;
62   sg_version_get(&major, &minor, &patch);
63   return simgrid::xbt::string_printf("%i.%i.%i", major, minor, patch);
64 }
65
66 /** @brief Wrap for mailbox::get_async */
67 class PyGetAsync {
68   std::unique_ptr<PyObject*> data = std::make_unique<PyObject*>();
69
70 public:
71   PyObject** get() const { return data.get(); }
72 };
73
74 } // namespace
75
76 PYBIND11_DECLARE_HOLDER_TYPE(T, boost::intrusive_ptr<T>)
77
78 PYBIND11_MODULE(simgrid, m)
79 {
80   m.doc() = "SimGrid userspace API";
81
82   m.attr("simgrid_version") = get_simgrid_version();
83
84   // Swapped contexts are broken, starting from pybind11 v2.8.0.  Use thread contexts by default.
85   simgrid::s4u::Engine::set_config("contexts/factory:thread");
86
87   // Internal exception used to kill actors and sweep the RAII chimney (free objects living on the stack)
88   static py::object pyForcefulKillEx(py::register_exception<simgrid::ForcefulKillException>(m, "ActorKilled"));
89
90   py::register_exception<simgrid::NetworkFailureException>(m, "NetworkFailureException");
91   py::register_exception<simgrid::TimeoutException>(m, "TimeoutException");
92
93   /* this_actor namespace */
94   m.def_submodule("this_actor", "Bindings of the s4u::this_actor namespace. See the C++ documentation for details.")
95       .def(
96           "debug", [](const char* s) { XBT_DEBUG("%s", s); }, "Display a logging message of 'debug' priority.")
97       .def(
98           "info", [](const char* s) { XBT_INFO("%s", s); }, "Display a logging message of 'info' priority.")
99       .def(
100           "error", [](const char* s) { XBT_ERROR("%s", s); }, "Display a logging message of 'error' priority.")
101       .def("execute", py::overload_cast<double, double>(&simgrid::s4u::this_actor::execute),
102            py::call_guard<py::gil_scoped_release>(),
103            "Block the current actor, computing the given amount of flops at the given priority.", py::arg("flops"),
104            py::arg("priority") = 1)
105       .def("exec_init", py::overload_cast<double>(&simgrid::s4u::this_actor::exec_init),
106            py::call_guard<py::gil_scoped_release>())
107       .def("get_host", &simgrid::s4u::this_actor::get_host, "Retrieves host on which the current actor is located")
108       .def("set_host", &simgrid::s4u::this_actor::set_host, py::call_guard<py::gil_scoped_release>(),
109            "Moves the current actor to another host.", py::arg("dest"))
110       .def("sleep_for", static_cast<void (*)(double)>(&simgrid::s4u::this_actor::sleep_for),
111            py::call_guard<py::gil_scoped_release>(), "Block the actor sleeping for that amount of seconds.",
112            py::arg("duration"))
113       .def("sleep_until", static_cast<void (*)(double)>(&simgrid::s4u::this_actor::sleep_until),
114            py::call_guard<py::gil_scoped_release>(), "Block the actor sleeping until the specified timestamp.",
115            py::arg("duration"))
116       .def("suspend", &simgrid::s4u::this_actor::suspend, py::call_guard<py::gil_scoped_release>(),
117            "Suspend the current actor, that is blocked until resume()ed by another actor.")
118       .def("yield_", &simgrid::s4u::this_actor::yield, py::call_guard<py::gil_scoped_release>(), "Yield the actor")
119       .def("exit", &simgrid::s4u::this_actor::exit, py::call_guard<py::gil_scoped_release>(), "kill the current actor")
120       .def(
121           "on_exit",
122           [](py::object cb) {
123             py::function fun = py::reinterpret_borrow<py::function>(cb);
124             fun.inc_ref(); // FIXME: why is this needed for tests like actor-kill and actor-lifetime?
125             simgrid::s4u::this_actor::on_exit([fun](bool /*failed*/) {
126               try {
127                 py::gil_scoped_acquire py_context; // need a new context for callback
128                 fun();
129               } catch (const py::error_already_set& e) {
130                 xbt_die("Error while executing the on_exit lambda: %s", e.what());
131               }
132             });
133           },
134           py::call_guard<py::gil_scoped_release>(), "")
135       .def("get_pid", &simgrid::s4u::this_actor::get_pid, "Retrieves PID of the current actor")
136       .def("get_ppid", &simgrid::s4u::this_actor::get_ppid,
137            "Retrieves PPID of the current actor (i.e., the PID of its parent).");
138
139   /* Class Engine */
140   py::class_<Engine>(m, "Engine", "Simulation Engine")
141       .def(py::init([](std::vector<std::string> args) {
142              auto argc = static_cast<int>(args.size());
143              std::vector<char*> argv(args.size() + 1); // argv[argc] is nullptr
144              std::transform(begin(args), end(args), begin(argv), [](std::string& s) { return &s.front(); });
145              // Currently this can be dangling, we should wrap this somehow.
146              return new simgrid::s4u::Engine(&argc, argv.data());
147            }),
148            "The constructor should take the parameters from the command line, as is ")
149       .def_static("get_clock",
150                   []() // XBT_ATTRIB_DEPRECATED_v334
151                   {
152                     PyErr_WarnEx(PyExc_DeprecationWarning,
153                                  "get_clock() is deprecated and  will be dropped after v3.33, use clock instead.", 1);
154                     return Engine::get_clock();
155                   })
156       .def_property_readonly_static(
157           "clock", [](py::object /* self */) { return Engine::get_clock(); },
158           "The simulation time, ie the amount of simulated seconds since the simulation start.")
159       .def_property_readonly_static(
160           "instance", [](py::object /* self */) { return Engine::get_instance(); }, "Retrieve the simulation engine")
161       .def("get_all_hosts",
162            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
163            {
164              PyErr_WarnEx(PyExc_DeprecationWarning,
165                           "get_all_hosts() is deprecated and  will be dropped after v3.33, use all_hosts instead.", 1);
166              return self.attr("all_hosts");
167            })
168       .def_property_readonly("all_hosts", &Engine::get_all_hosts, "Returns the list of all hosts found in the platform")
169       .def("get_all_links",
170            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
171            {
172              PyErr_WarnEx(PyExc_DeprecationWarning,
173                           "get_all_links() is deprecated and  will be dropped after v3.33, use all_links instead.", 1);
174              return self.attr("all_links");
175            })
176       .def_property_readonly("all_links", &Engine::get_all_links, "Returns the list of all links found in the platform")
177       .def("get_all_netpoints",
178            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
179            {
180              PyErr_WarnEx(
181                  PyExc_DeprecationWarning,
182                  "get_all_netpoints() is deprecated and  will be dropped after v3.33, use all_netpoints instead.", 1);
183              return self.attr("all_netpoints");
184            })
185       .def_property_readonly("all_netpoints", &Engine::get_all_netpoints)
186       .def("get_netzone_root",
187            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
188            {
189              PyErr_WarnEx(PyExc_DeprecationWarning,
190                           "get_netzone_root() is deprecated and  will be dropped after v3.3, use netzone_root instead.",
191                           1);
192              return self.attr("netzone_root");
193            })
194       .def_property_readonly("netzone_root", &Engine::get_netzone_root,
195                              "Retrieve the root netzone, containing all others.")
196       .def("netpoint_by_name", &Engine::netpoint_by_name_or_null)
197       .def("netzone_by_name", &Engine::netzone_by_name_or_null)
198       .def("load_platform", &Engine::load_platform, "Load a platform file describing the environment")
199       .def("load_deployment", &Engine::load_deployment, "Load a deployment file and launch the actors that it contains")
200       .def("run", &Engine::run, py::call_guard<py::gil_scoped_release>(), "Run the simulation until its end")
201       .def("run_until", py::overload_cast<double>(&Engine::run_until, py::const_),
202            py::call_guard<py::gil_scoped_release>(), "Run the simulation until the given date",
203            py::arg("max_date") = -1)
204       .def(
205           "register_actor",
206           [](Engine* e, const std::string& name, py::object fun_or_class) {
207             e->register_actor(name, [fun_or_class](std::vector<std::string> args) {
208               try {
209                 py::gil_scoped_acquire py_context;
210                 /* Convert the std::vector into a py::tuple */
211                 py::tuple params(args.size() - 1);
212                 for (size_t i = 1; i < args.size(); i++)
213                   params[i - 1] = py::cast(args[i]);
214
215                 py::object res = fun_or_class(*params);
216                 /* If I was passed a class, I just built an instance, so I need to call it now */
217                 if (py::isinstance<py::function>(res))
218                   res();
219               } catch (const py::error_already_set& ex) {
220                 if (ex.matches(pyForcefulKillEx)) {
221                   XBT_VERB("Actor killed");
222                   simgrid::ForcefulKillException::do_throw(); // Forward that ForcefulKill exception
223                 }
224                 throw;
225               }
226             });
227           },
228           "Registers the main function of an actor");
229
230   /* Class Netzone */
231   py::class_<simgrid::s4u::NetZone, std::unique_ptr<simgrid::s4u::NetZone, py::nodelete>> netzone(
232       m, "NetZone", "Networking Zones. See the C++ documentation for details.");
233   netzone.def_static("create_full_zone", &simgrid::s4u::create_full_zone, "Creates a zone of type FullZone")
234       .def_static("create_torus_zone", &simgrid::s4u::create_torus_zone, "Creates a cluster of type Torus")
235       .def_static("create_fatTree_zone", &simgrid::s4u::create_fatTree_zone, "Creates a cluster of type Fat-Tree")
236       .def_static("create_dragonfly_zone", &simgrid::s4u::create_dragonfly_zone, "Creates a cluster of type Dragonfly")
237       .def_static("create_star_zone", &simgrid::s4u::create_star_zone, "Creates a zone of type Star")
238       .def_static("create_floyd_zone", &simgrid::s4u::create_floyd_zone, "Creates a zone of type Floyd")
239       .def_static("create_dijkstra_zone", &simgrid::s4u::create_floyd_zone, "Creates a zone of type Dijkstra")
240       .def_static("create_vivaldi_zone", &simgrid::s4u::create_vivaldi_zone, "Creates a zone of type Vivaldi")
241       .def_static("create_empty_zone", &simgrid::s4u::create_empty_zone, "Creates a zone of type Empty")
242       .def_static("create_wifi_zone", &simgrid::s4u::create_wifi_zone, "Creates a zone of type Wi-Fi")
243       .def("add_route",
244            py::overload_cast<simgrid::kernel::routing::NetPoint*, simgrid::kernel::routing::NetPoint*,
245                              simgrid::kernel::routing::NetPoint*, simgrid::kernel::routing::NetPoint*,
246                              const std::vector<simgrid::s4u::LinkInRoute>&, bool>(&simgrid::s4u::NetZone::add_route),
247            "Add a route between 2 netpoints")
248       .def("create_host", py::overload_cast<const std::string&, double>(&simgrid::s4u::NetZone::create_host),
249            "Creates a host")
250       .def("create_host",
251            py::overload_cast<const std::string&, const std::string&>(&simgrid::s4u::NetZone::create_host),
252            "Creates a host")
253       .def("create_host",
254            py::overload_cast<const std::string&, const std::vector<double>&>(&simgrid::s4u::NetZone::create_host),
255            "Creates a host")
256       .def("create_host",
257            py::overload_cast<const std::string&, const std::vector<std::string>&>(&simgrid::s4u::NetZone::create_host),
258            "Creates a host")
259       .def("create_link", py::overload_cast<const std::string&, double>(&simgrid::s4u::NetZone::create_link),
260            "Creates a network link")
261       .def("create_link",
262            py::overload_cast<const std::string&, const std::string&>(&simgrid::s4u::NetZone::create_link),
263            "Creates a network link")
264       .def("create_link",
265            py::overload_cast<const std::string&, const std::vector<double>&>(&simgrid::s4u::NetZone::create_link),
266            "Creates a network link")
267       .def("create_link",
268            py::overload_cast<const std::string&, const std::vector<std::string>&>(&simgrid::s4u::NetZone::create_link),
269            "Creates a network link")
270       .def("create_split_duplex_link",
271            py::overload_cast<const std::string&, double>(&simgrid::s4u::NetZone::create_split_duplex_link),
272            "Creates a split-duplex link")
273       .def("create_split_duplex_link",
274            py::overload_cast<const std::string&, const std::string&>(&simgrid::s4u::NetZone::create_split_duplex_link),
275            "Creates a split-duplex link")
276       .def("create_router", &simgrid::s4u::NetZone::create_router, "Create a router")
277       .def("set_parent", &simgrid::s4u::NetZone::set_parent, "Set the parent of this zone")
278       .def("set_property", &simgrid::s4u::NetZone::set_property, "Add a property to this zone")
279       .def("get_netpoint",
280            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
281            {
282              PyErr_WarnEx(PyExc_DeprecationWarning,
283                           "get_netpoint() is deprecated and  will be dropped after v3.33, use netpoint instead.", 1);
284              return self.attr("netpoint");
285            })
286       .def_property_readonly("netpoint", &simgrid::s4u::NetZone::get_netpoint,
287                              "Retrieve the netpoint associated to this zone")
288       .def("seal", &simgrid::s4u::NetZone::seal, "Seal this NetZone")
289       .def_property_readonly(
290           "name", [](const simgrid::s4u::NetZone* self) { return self->get_name(); },
291           "The name of this network zone (read-only property).");
292
293   /* Class ClusterCallbacks */
294   py::class_<simgrid::s4u::ClusterCallbacks>(m, "ClusterCallbacks", "Callbacks used to create cluster zones")
295       .def(py::init<const std::function<simgrid::s4u::ClusterCallbacks::ClusterNetPointCb>&,
296                     const std::function<simgrid::s4u::ClusterCallbacks::ClusterLinkCb>&,
297                     const std::function<simgrid::s4u::ClusterCallbacks::ClusterLinkCb>&>());
298
299   /* Class FatTreeParams */
300   py::class_<simgrid::s4u::FatTreeParams>(m, "FatTreeParams", "Parameters to create a Fat-Tree zone")
301       .def(py::init<unsigned int, const std::vector<unsigned int>&, const std::vector<unsigned int>&,
302                     const std::vector<unsigned int>&>());
303
304   /* Class DragonflyParams */
305   py::class_<simgrid::s4u::DragonflyParams>(m, "DragonflyParams", "Parameters to create a Dragonfly zone")
306       .def(py::init<const std::pair<unsigned int, unsigned int>&, const std::pair<unsigned int, unsigned int>&,
307                     const std::pair<unsigned int, unsigned int>&, unsigned int>());
308
309   /* Class Host */
310   py::class_<simgrid::s4u::Host, std::unique_ptr<Host, py::nodelete>> host(
311       m, "Host", "Simulated host. See the C++ documentation for details.");
312   host.def("by_name", &Host::by_name, "Retrieves a host from its name, or die")
313       .def(
314           "route_to",
315           [](const simgrid::s4u::Host* h, const simgrid::s4u::Host* to) {
316             auto* list = new std::vector<Link*>();
317             double bw  = 0;
318             h->route_to(to, *list, &bw);
319             return make_tuple(list, bw);
320           },
321           "Retrieves the list of links and the bandwidth between two hosts.")
322       .def(
323           "set_speed_profile",
324           [](Host* h, const std::string& profile, double period) {
325             h->set_speed_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
326           },
327           py::call_guard<py::gil_scoped_release>(),
328           "Specify a profile modeling the external load according to an exhaustive list. "
329           "Each line of the profile describes timed events as ``date ratio``. "
330           "For example, the following content describes an host which computational speed is initially 1 (i.e, 100%) "
331           "and then halved after 42 seconds:\n\n"
332           ".. code-block:: python\n\n"
333           "   \"\"\"\n"
334           "   0 1.0\n"
335           "   42 0.5\n"
336           "   \"\"\"\n\n"
337           ".. warning:: Don't get fooled: bandwidth and latency profiles of links contain absolute values,"
338           " while speed profiles of hosts contain ratios.\n\n"
339           "The second function parameter is the periodicity: the time to wait after the last event to start again over "
340           "the list. Set it to -1 to not loop over.")
341       .def(
342           "set_state_profile",
343           [](Host* h, const std::string& profile, double period) {
344             h->set_state_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
345           },
346           py::call_guard<py::gil_scoped_release>(),
347           "Specify a profile modeling the churn. "
348           "Each line of the profile describes timed events as ``date boolean``, where the boolean (0 or 1) tells "
349           "whether the host is on. "
350           "For example, the following content describes a link which turns off at t=1 and back on at t=2:\n\n"
351           ".. code-block:: python\n\n"
352           "   \"\"\"\n"
353           "   1.0 0\n"
354           "   2.0 1\n"
355           "   \"\"\"\n\n"
356           "The second function parameter is the periodicity: the time to wait after the last event to start again over "
357           "the list. Set it to -1 to not loop over.")
358       .def("get_pstate_count",
359            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
360            {
361              PyErr_WarnEx(
362                  PyExc_DeprecationWarning,
363                  "get_pstate_count() is deprecated and  will be dropped after v3.33, use pstate_count instead.", 1);
364              return self.attr("pstate_count");
365            })
366       .def_property_readonly("pstate_count", &Host::get_pstate_count, "Retrieve the count of defined pstate levels")
367       .def("get_pstate_speed",
368            [](py::object self, int state) // XBT_ATTRIB_DEPRECATED_v334
369            {
370              PyErr_WarnEx(
371                  PyExc_DeprecationWarning,
372                  "get_pstate_speed() is deprecated and  will be dropped after v3.33, use pstate_speed instead.", 1);
373              return self.attr("pstate_speed")(state);
374            })
375       .def("pstate_speed", &Host::get_pstate_speed, py::call_guard<py::gil_scoped_release>(),
376            "Retrieve the maximal speed at the given pstate")
377       .def("get_netpoint",
378            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
379            {
380              PyErr_WarnEx(PyExc_DeprecationWarning,
381                           "get_netpoint() is deprecated and  will be dropped after v3.33, use netpoint instead.", 1);
382              return self.attr("netpoint");
383            })
384       .def_property_readonly("netpoint", &Host::get_netpoint, "Retrieve the netpoint associated to this zone")
385       .def("get_disks", &Host::get_disks, "Retrieve the list of disks in this host")
386       .def("set_core_count",
387            [](py::object self, double count) // XBT_ATTRIB_DEPRECATED_v334
388            {
389              PyErr_WarnEx(PyExc_DeprecationWarning,
390                           "set_core_count() is deprecated and  will be dropped after v3.33, use core_count instead.",
391                           1);
392              self.attr("core_count")(count);
393            })
394       .def_property(
395           "core_count", &Host::get_core_count,
396           [](Host* h, int count) {
397             py::gil_scoped_release gil_guard;
398             return h->set_core_count(count);
399           },
400           "Manage the number of cores in the CPU")
401       .def("set_coordinates", &Host::set_coordinates, py::call_guard<py::gil_scoped_release>(),
402            "Set the coordinates of this host")
403       .def("set_sharing_policy", &simgrid::s4u::Host::set_sharing_policy, py::call_guard<py::gil_scoped_release>(),
404            "Describe how the CPU is shared", py::arg("policy"), py::arg("cb") = simgrid::s4u::NonLinearResourceCb())
405       .def("create_disk", py::overload_cast<const std::string&, double, double>(&Host::create_disk),
406            py::call_guard<py::gil_scoped_release>(), "Create a disk")
407       .def("create_disk",
408            py::overload_cast<const std::string&, const std::string&, const std::string&>(&Host::create_disk),
409            py::call_guard<py::gil_scoped_release>(), "Create a disk")
410       .def("seal", &Host::seal, py::call_guard<py::gil_scoped_release>(), "Seal this host")
411       .def_property(
412           "pstate", &Host::get_pstate,
413           [](Host* h, int i) {
414             py::gil_scoped_release gil_guard;
415             h->set_pstate(i);
416           },
417           "The current pstate (read/write property).")
418       .def("current", &Host::current, py::call_guard<py::gil_scoped_release>(),
419            "Retrieves the host on which the running actor is located.")
420       .def_property_readonly(
421           "name",
422           [](const Host* self) {
423             return std::string(self->get_name().c_str()); // Convert from xbt::string because of MC
424           },
425           "The name of this host (read-only property).")
426       .def_property_readonly("load", &Host::get_load,
427                              "Returns the current computation load (in flops per second), NOT taking the external load "
428                              "into account. This is the currently achieved speed (read-only property).")
429       .def_property_readonly(
430           "speed", &Host::get_speed,
431           "The peak computing speed in flops/s at the current pstate, NOT taking the external load into account. "
432           "This is the max potential speed (read-only property).")
433       .def_property_readonly("available_speed", &Host::get_available_speed,
434                              "Get the available speed ratio, between 0 and 1.\n"
435                              "This accounts for external load (see :py:func:`set_speed_profile() "
436                              "<simgrid.Host.set_speed_profile>`) (read-only property).")
437       .def(
438           "on_creation_cb",
439           [](py::object cb) {
440             Host::on_creation_cb([cb](Host& h) {
441               py::function fun = py::reinterpret_borrow<py::function>(cb);
442               try {
443                 py::gil_scoped_acquire py_context; // need a new context for callback
444                 fun(&h);
445               } catch (const py::error_already_set& e) {
446                 xbt_die("Error while executing the on_creation lambda : %s", e.what());
447               }
448             });
449           },
450           py::call_guard<py::gil_scoped_release>(), "");
451
452   py::enum_<simgrid::s4u::Host::SharingPolicy>(host, "SharingPolicy")
453       .value("NONLINEAR", simgrid::s4u::Host::SharingPolicy::NONLINEAR)
454       .value("LINEAR", simgrid::s4u::Host::SharingPolicy::LINEAR)
455       .export_values();
456
457   /* Class Disk */
458   py::class_<simgrid::s4u::Disk, std::unique_ptr<simgrid::s4u::Disk, py::nodelete>> disk(
459       m, "Disk", "Simulated disk. See the C++ documentation for details.");
460   disk.def("read", py::overload_cast<sg_size_t, double>(&simgrid::s4u::Disk::read, py::const_),
461            py::call_guard<py::gil_scoped_release>(), "Read data from disk", py::arg("size"), py::arg("priority") = 1)
462       .def("write", py::overload_cast<sg_size_t, double>(&simgrid::s4u::Disk::write, py::const_),
463            py::call_guard<py::gil_scoped_release>(), "Write data in disk", py::arg("size"), py::arg("priority") = 1)
464       .def("read_async", &simgrid::s4u::Disk::read_async, py::call_guard<py::gil_scoped_release>(),
465            "Non-blocking read data from disk")
466       .def("write_async", &simgrid::s4u::Disk::write_async, py::call_guard<py::gil_scoped_release>(),
467            "Non-blocking write data in disk")
468       .def("set_sharing_policy", &simgrid::s4u::Disk::set_sharing_policy, py::call_guard<py::gil_scoped_release>(),
469            "Set sharing policy for this disk", py::arg("op"), py::arg("policy"),
470            py::arg("cb") = simgrid::s4u::NonLinearResourceCb())
471       .def("seal", &simgrid::s4u::Disk::seal, py::call_guard<py::gil_scoped_release>(), "Seal this disk")
472       .def_property_readonly(
473           "name", [](const simgrid::s4u::Disk* self) { return self->get_name(); },
474           "The name of this disk (read-only property).");
475   py::enum_<simgrid::s4u::Disk::SharingPolicy>(disk, "SharingPolicy")
476       .value("NONLINEAR", simgrid::s4u::Disk::SharingPolicy::NONLINEAR)
477       .value("LINEAR", simgrid::s4u::Disk::SharingPolicy::LINEAR)
478       .export_values();
479   py::enum_<simgrid::s4u::Disk::Operation>(disk, "Operation")
480       .value("READ", simgrid::s4u::Disk::Operation::READ)
481       .value("WRITE", simgrid::s4u::Disk::Operation::WRITE)
482       .value("READWRITE", simgrid::s4u::Disk::Operation::READWRITE)
483       .export_values();
484
485   /* Class NetPoint */
486   py::class_<simgrid::kernel::routing::NetPoint, std::unique_ptr<simgrid::kernel::routing::NetPoint, py::nodelete>>
487       netpoint(m, "NetPoint", "NetPoint object");
488
489   /* Class Link */
490   py::class_<Link, std::unique_ptr<Link, py::nodelete>> link(m, "Link",
491                                                              "Network link. See the C++ documentation for details.");
492   link.def("set_latency", py::overload_cast<const std::string&>(&Link::set_latency),
493            py::call_guard<py::gil_scoped_release>(),
494            "Set the latency as a string. Accepts values with units, such as â€˜1s’ or â€˜7ms’.\nFull list of accepted "
495            "units: w (week), d (day), h, s, ms, us, ns, ps.")
496       .def("set_latency", py::overload_cast<double>(&Link::set_latency), py::call_guard<py::gil_scoped_release>(),
497            "Set the latency as a float (in seconds).")
498       .def("set_bandwidth", &Link::set_bandwidth, py::call_guard<py::gil_scoped_release>(),
499            "Set the bandwidth (in byte per second).")
500       .def(
501           "set_bandwidth_profile",
502           [](Link* l, const std::string& profile, double period) {
503             l->set_bandwidth_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
504           },
505           py::call_guard<py::gil_scoped_release>(),
506           "Specify a profile modeling the external load according to an exhaustive list. "
507           "Each line of the profile describes timed events as ``date bandwidth`` (in bytes per second). "
508           "For example, the following content describes a link which bandwidth changes to 40 Mb/s at t=4, and to 6 "
509           "Mb/s at t=8:\n\n"
510           ".. code-block:: python\n\n"
511           "   \"\"\"\n"
512           "   4.0 40000000\n"
513           "   8.0 60000000\n"
514           "   \"\"\"\n\n"
515           ".. warning:: Don't get fooled: bandwidth and latency profiles of links contain absolute values,"
516           " while speed profiles of hosts contain ratios.\n\n"
517           "The second function parameter is the periodicity: the time to wait after the last event to start again over "
518           "the list. Set it to -1 to not loop over.")
519       .def(
520           "set_latency_profile",
521           [](Link* l, const std::string& profile, double period) {
522             l->set_latency_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
523           },
524           py::call_guard<py::gil_scoped_release>(),
525           "Specify a profile modeling the external load according to an exhaustive list. "
526           "Each line of the profile describes timed events as ``date latency`` (in seconds). "
527           "For example, the following content describes a link which latency changes to 1ms (0.001s) at t=1, and to 2s "
528           "at t=2:\n\n"
529           ".. code-block:: python\n\n"
530           "   \"\"\"\n"
531           "   1.0 0.001\n"
532           "   2.0 2\n"
533           "   \"\"\"\n\n"
534           ".. warning:: Don't get fooled: bandwidth and latency profiles of links contain absolute values,"
535           " while speed profiles of hosts contain ratios.\n\n"
536           "The second function parameter is the periodicity: the time to wait after the last event to start again over "
537           "the list. Set it to -1 to not loop over.")
538       .def(
539           "set_state_profile",
540           [](Link* l, const std::string& profile, double period) {
541             l->set_state_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
542           },
543           "Specify a profile modeling the churn. "
544           "Each line of the profile describes timed events as ``date boolean``, where the boolean (0 or 1) tells "
545           "whether the link is on. "
546           "For example, the following content describes a link which turns off at t=1 and back on at t=2:\n\n"
547           ".. code-block:: python\n\n"
548           "   \"\"\"\n"
549           "   1.0 0\n"
550           "   2.0 1\n"
551           "   \"\"\"\n\n"
552           "The second function parameter is the periodicity: the time to wait after the last event to start again over "
553           "the list. Set it to -1 to not loop over.")
554
555       .def("turn_on", &Link::turn_on, py::call_guard<py::gil_scoped_release>(), "Turns the link on.")
556       .def("turn_off", &Link::turn_off, py::call_guard<py::gil_scoped_release>(), "Turns the link off.")
557       .def("is_on", &Link::is_on, "Check whether the link is on.")
558
559       .def("set_sharing_policy", &Link::set_sharing_policy, py::call_guard<py::gil_scoped_release>(),
560            "Set sharing policy for this link")
561       .def("set_concurrency_limit", &Link::set_concurrency_limit, py::call_guard<py::gil_scoped_release>(),
562            "Set concurrency limit for this link")
563       .def("set_host_wifi_rate", &Link::set_host_wifi_rate, py::call_guard<py::gil_scoped_release>(),
564            "Set level of communication speed of given host on this Wi-Fi link")
565       .def_static("by_name", &Link::by_name, "Retrieves a Link from its name, or dies")
566       .def("seal", &Link::seal, py::call_guard<py::gil_scoped_release>(), "Seal this link")
567       .def_property_readonly(
568           "name",
569           [](const Link* self) {
570             return std::string(self->get_name().c_str()); // Convert from xbt::string because of MC
571           },
572           "The name of this link")
573       .def_property_readonly("bandwidth", &Link::get_bandwidth,
574                              "The bandwidth (in bytes per second) (read-only property).")
575       .def_property_readonly("latency", &Link::get_latency, "The latency (in seconds) (read-only property).");
576
577   py::enum_<Link::SharingPolicy>(link, "SharingPolicy")
578       .value("NONLINEAR", Link::SharingPolicy::NONLINEAR)
579       .value("WIFI", Link::SharingPolicy::WIFI)
580       .value("SPLITDUPLEX", Link::SharingPolicy::SPLITDUPLEX)
581       .value("SHARED", Link::SharingPolicy::SHARED)
582       .value("FATPIPE", Link::SharingPolicy::FATPIPE)
583       .export_values();
584
585   /* Class LinkInRoute */
586   py::class_<simgrid::s4u::LinkInRoute> linkinroute(m, "LinkInRoute", "Abstraction to add link in routes");
587   linkinroute.def(py::init<const Link*>());
588   linkinroute.def(py::init<const Link*, simgrid::s4u::LinkInRoute::Direction>());
589   py::enum_<simgrid::s4u::LinkInRoute::Direction>(linkinroute, "Direction")
590       .value("UP", simgrid::s4u::LinkInRoute::Direction::UP)
591       .value("DOWN", simgrid::s4u::LinkInRoute::Direction::DOWN)
592       .value("NONE", simgrid::s4u::LinkInRoute::Direction::NONE)
593       .export_values();
594
595   /* Class Split-Duplex Link */
596   py::class_<simgrid::s4u::SplitDuplexLink, Link, std::unique_ptr<simgrid::s4u::SplitDuplexLink, py::nodelete>>(
597       m, "SplitDuplexLink", "Network split-duplex link")
598       .def("get_link_up",
599            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
600            {
601              PyErr_WarnEx(PyExc_DeprecationWarning,
602                           "get_link_up() is deprecated and  will be dropped after v3.33, use link_up instead.", 1);
603              return self.attr("link_up");
604            })
605       .def_property_readonly("link_up", &simgrid::s4u::SplitDuplexLink::get_link_up, "Get link direction up")
606       .def("get_link_down",
607            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
608            {
609              PyErr_WarnEx(PyExc_DeprecationWarning,
610                           "get_link_down() is deprecated and  will be dropped after v3.33, use link_down instead.", 1);
611              return self.attr("link_down");
612            })
613       .def_property_readonly("link_down", &simgrid::s4u::SplitDuplexLink::get_link_down, "Get link direction down");
614
615   /* Class Mailbox */
616   py::class_<simgrid::s4u::Mailbox, std::unique_ptr<Mailbox, py::nodelete>>(
617       m, "Mailbox", "Mailbox. See the C++ documentation for details.")
618       .def(
619           "__str__", [](const Mailbox* self) { return std::string("Mailbox(") + self->get_cname() + ")"; },
620           "Textual representation of the Mailbox`")
621       .def("by_name", &Mailbox::by_name, py::call_guard<py::gil_scoped_release>(), "Retrieve a Mailbox from its name")
622       .def_property_readonly(
623           "name",
624           [](const Mailbox* self) {
625             return std::string(self->get_name().c_str()); // Convert from xbt::string because of MC
626           },
627           "The name of that mailbox (read-only property).")
628       .def(
629           "put",
630           [](Mailbox* self, py::object data, int size, double timeout) {
631             data.inc_ref();
632             self->put(data.ptr(), size, timeout);
633           },
634           py::call_guard<py::gil_scoped_release>(), "Blocking data transmission with a timeout")
635       .def(
636           "put",
637           [](Mailbox* self, py::object data, int size) {
638             data.inc_ref();
639             self->put(data.ptr(), size);
640           },
641           py::call_guard<py::gil_scoped_release>(), "Blocking data transmission")
642       .def(
643           "put_async",
644           [](Mailbox* self, py::object data, int size) {
645             data.inc_ref();
646             return self->put_async(data.ptr(), size);
647           },
648           py::call_guard<py::gil_scoped_release>(), "Non-blocking data transmission")
649       .def(
650           "get",
651           [](Mailbox* self) {
652             py::object data = py::reinterpret_steal<py::object>(self->get<PyObject>());
653             // data.dec_ref(); // FIXME: why does it break python-actor-create?
654             return data;
655           },
656           py::call_guard<py::gil_scoped_release>(), "Blocking data reception")
657       .def(
658           "get_async",
659           [](Mailbox* self) -> std::tuple<simgrid::s4u::CommPtr, PyGetAsync> {
660             PyGetAsync wrap;
661             auto comm = self->get_async(wrap.get());
662             return std::make_tuple(std::move(comm), std::move(wrap));
663           },
664           py::call_guard<py::gil_scoped_release>(),
665           "Non-blocking data reception. Use data.get() to get the python object after the communication has finished")
666       .def(
667           "set_receiver", [](Mailbox* self, ActorPtr actor) { self->set_receiver(actor); },
668           py::call_guard<py::gil_scoped_release>(), "Sets the actor as permanent receiver");
669
670   /* Class PyGetAsync */
671   py::class_<PyGetAsync>(m, "PyGetAsync", "Wrapper for async get communications")
672       .def(py::init<>())
673       .def(
674           "get", [](const PyGetAsync* self) { return py::reinterpret_steal<py::object>(*(self->get())); },
675           "Get python object after async communication in receiver side");
676
677   /* Class Comm */
678   py::class_<simgrid::s4u::Comm, simgrid::s4u::CommPtr>(m, "Comm",
679                                                         "Communication. See the C++ documentation for details.")
680       .def("test", &simgrid::s4u::Comm::test, py::call_guard<py::gil_scoped_release>(),
681            "Test whether the communication is terminated.")
682       .def("wait", &simgrid::s4u::Comm::wait, py::call_guard<py::gil_scoped_release>(),
683            "Block until the completion of that communication.")
684       // use py::overload_cast for wait_all/wait_any, until the overload marked XBT_ATTRIB_DEPRECATED_v332 is removed
685       .def_static(
686           "wait_all", py::overload_cast<const std::vector<simgrid::s4u::CommPtr>&>(&simgrid::s4u::Comm::wait_all),
687           py::call_guard<py::gil_scoped_release>(), "Block until the completion of all communications in the list.")
688       .def_static(
689           "wait_any", py::overload_cast<const std::vector<simgrid::s4u::CommPtr>&>(&simgrid::s4u::Comm::wait_any),
690           py::call_guard<py::gil_scoped_release>(),
691           "Block until the completion of any communication in the list and return the index of the terminated one.");
692
693   /* Class Io */
694   py::class_<simgrid::s4u::Io, simgrid::s4u::IoPtr>(m, "Io", "I/O activities. See the C++ documentation for details.")
695       .def("test", &simgrid::s4u::Io::test, py::call_guard<py::gil_scoped_release>(),
696            "Test whether the I/O is terminated.")
697       .def("wait", &simgrid::s4u::Io::wait, py::call_guard<py::gil_scoped_release>(),
698            "Block until the completion of that I/O operation")
699       .def_static(
700           "wait_any_for", &simgrid::s4u::Io::wait_any_for, py::call_guard<py::gil_scoped_release>(),
701           "Block until the completion of any I/O in the list (or timeout) and return the index of the terminated one.")
702       .def_static("wait_any", &simgrid::s4u::Io::wait_any, py::call_guard<py::gil_scoped_release>(),
703                   "Block until the completion of any I/O in the list and return the index of the terminated one.");
704
705   /* Class Exec */
706   py::class_<simgrid::s4u::Exec, simgrid::s4u::ExecPtr>(m, "Exec", "Execution. See the C++ documentation for details.")
707       .def_property_readonly(
708           "remaining",
709           [](simgrid::s4u::ExecPtr self) {
710             py::gil_scoped_release gil_guard;
711             return self->get_remaining();
712           },
713           "Amount of flops that remain to be computed until completion (read-only property).")
714       .def_property_readonly(
715           "remaining_ratio",
716           [](simgrid::s4u::ExecPtr self) {
717             py::gil_scoped_release gil_guard;
718             return self->get_remaining_ratio();
719           },
720           "Amount of work remaining until completion from 0 (completely done) to 1 (nothing done "
721           "yet) (read-only property).")
722       .def_property("host", &simgrid::s4u::Exec::get_host, &simgrid::s4u::Exec::set_host,
723                     "Host on which this execution runs. Only the first host is returned for parallel executions. "
724                     "Changing this value migrates the execution.")
725       .def("test", &simgrid::s4u::Exec::test, py::call_guard<py::gil_scoped_release>(),
726            "Test whether the execution is terminated.")
727       .def("cancel", &simgrid::s4u::Exec::cancel, py::call_guard<py::gil_scoped_release>(), "Cancel that execution.")
728       .def("start", &simgrid::s4u::Exec::start, py::call_guard<py::gil_scoped_release>(), "Start that execution.")
729       .def("wait", &simgrid::s4u::Exec::wait, py::call_guard<py::gil_scoped_release>(),
730            "Block until the completion of that execution.");
731
732   /* Class Actor */
733   py::class_<simgrid::s4u::Actor, ActorPtr>(m, "Actor",
734                                             "An actor is an independent stream of execution in your distributed "
735                                             "application. See the C++ documentation for details.")
736       .def(
737           "create",
738           [](py::str name, Host* h, py::object fun, py::args args) {
739             fun.inc_ref();  // FIXME: why is this needed for tests like exec-async, exec-dvfs and exec-remote?
740             args.inc_ref(); // FIXME: why is this needed for tests like actor-migrate?
741             return simgrid::s4u::Actor::create(name, h, [fun, args]() {
742               try {
743                 py::gil_scoped_acquire py_context;
744                 fun(*args);
745               } catch (const py::error_already_set& ex) {
746                 if (ex.matches(pyForcefulKillEx)) {
747                   XBT_VERB("Actor killed");
748                   simgrid::ForcefulKillException::do_throw(); // Forward that ForcefulKill exception
749                 }
750                 throw;
751               }
752             });
753           },
754           py::call_guard<py::gil_scoped_release>(),
755           "Create an actor from a function or an object. See the :ref:`example <s4u_ex_actors_create>`.")
756       .def_property(
757           "host", &Actor::get_host,
758           [](Actor* a, Host* h) {
759             py::gil_scoped_release gil_guard;
760             a->set_host(h);
761           },
762           "The host on which this actor is located. Changing this value migrates the actor.\n\n"
763           "If the actor is currently blocked on an execution activity, the activity is also migrated to the new host. "
764           "If it’s blocked on another kind of activity, an error is raised as the mandated code is not written yet. "
765           "Please report that bug if you need it.\n\n"
766           "Asynchronous activities started by the actor are not migrated automatically, so you have to take care of "
767           "this yourself (only you knows which ones should be migrated). ")
768       .def_property_readonly("name", &Actor::get_cname, "The name of this actor (read-only property).")
769       .def_property_readonly("pid", &Actor::get_pid, "The PID (unique identifier) of this actor (read-only property).")
770       .def_property_readonly("ppid", &Actor::get_ppid,
771                              "The PID (unique identifier) of the actor that created this one (read-only property).")
772       .def("by_pid", &Actor::by_pid, "Retrieve an actor by its PID")
773       .def("set_auto_restart", &Actor::set_auto_restart, py::call_guard<py::gil_scoped_release>(),
774            "Specify whether the actor shall restart when its host reboots.")
775       .def("daemonize", &Actor::daemonize, py::call_guard<py::gil_scoped_release>(),
776            "This actor will be automatically terminated when the last non-daemon actor finishes (more info in the C++ "
777            "documentation).")
778       .def("is_daemon", &Actor::is_daemon,
779            "Returns True if that actor is a daemon and will be terminated automatically when the last non-daemon actor "
780            "terminates.")
781       .def("join", py::overload_cast<double>(&Actor::join, py::const_), py::call_guard<py::gil_scoped_release>(),
782            "Wait for the actor to finish (more info in the C++ documentation).", py::arg("timeout"))
783       .def("kill", &Actor::kill, py::call_guard<py::gil_scoped_release>(), "Kill that actor")
784       .def("kill_all", &Actor::kill_all, py::call_guard<py::gil_scoped_release>(), "Kill all actors but the caller.")
785       .def("self", &Actor::self, "Retrieves the current actor.")
786       .def("is_suspended", &Actor::is_suspended, "Returns True if that actor is currently suspended.")
787       .def("suspend", &Actor::suspend, py::call_guard<py::gil_scoped_release>(),
788            "Suspend that actor, that is blocked until resume()ed by another actor.")
789       .def("resume", &Actor::resume, py::call_guard<py::gil_scoped_release>(),
790            "Resume that actor, that was previously suspend()ed.");
791 }