Logo AND Algorithmique Numérique Distribuée

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