Logo AND Algorithmique Numérique Distribuée

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