Logo AND Algorithmique Numérique Distribuée

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