1 /* Copyright (c) 2018-2022. The SimGrid Team. All rights reserved. */
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. */
7 #warning Try to work around https://bugs.python.org/issue11566
12 #pragma GCC diagnostic push
13 #pragma GCC diagnostic ignored "-Wunused-value"
16 #include <pybind11/pybind11.h> // Must come before our own stuff
18 #include <pybind11/functional.h>
19 #include <pybind11/stl.h>
22 #pragma GCC diagnostic pop
25 #include "simgrid/kernel/ProfileBuilder.hpp"
26 #include "simgrid/kernel/routing/NetPoint.hpp"
27 #include <simgrid/Exception.hpp>
28 #include <simgrid/s4u/Actor.hpp>
29 #include <simgrid/s4u/Barrier.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/Mutex.hpp>
38 #include <simgrid/s4u/NetZone.hpp>
39 #include <simgrid/s4u/Semaphore.hpp>
40 #include <simgrid/version.h>
47 namespace py = pybind11;
48 using simgrid::s4u::Actor;
49 using simgrid::s4u::ActorPtr;
50 using simgrid::s4u::Barrier;
51 using simgrid::s4u::BarrierPtr;
52 using simgrid::s4u::Engine;
53 using simgrid::s4u::Host;
54 using simgrid::s4u::Link;
55 using simgrid::s4u::Mailbox;
56 using simgrid::s4u::Mutex;
57 using simgrid::s4u::MutexPtr;
58 using simgrid::s4u::Semaphore;
59 using simgrid::s4u::SemaphorePtr;
61 XBT_LOG_NEW_DEFAULT_CATEGORY(python, "python");
65 std::string get_simgrid_version()
70 sg_version_get(&major, &minor, &patch);
71 return simgrid::xbt::string_printf("%i.%i.%i", major, minor, patch);
74 /** @brief Wrap for mailbox::get_async */
76 std::unique_ptr<PyObject*> data = std::make_unique<PyObject*>();
79 PyObject** get() const { return data.get(); }
84 PYBIND11_DECLARE_HOLDER_TYPE(T, boost::intrusive_ptr<T>)
86 PYBIND11_MODULE(simgrid, m)
88 m.doc() = "SimGrid userspace API";
90 m.attr("simgrid_version") = get_simgrid_version();
92 // Swapped contexts are broken, starting from pybind11 v2.8.0. Use thread contexts by default.
93 simgrid::s4u::Engine::set_config("contexts/factory:thread");
95 // Internal exception used to kill actors and sweep the RAII chimney (free objects living on the stack)
96 static py::object pyForcefulKillEx(py::register_exception<simgrid::ForcefulKillException>(m, "ActorKilled"));
98 py::register_exception<simgrid::NetworkFailureException>(m, "NetworkFailureException");
99 py::register_exception<simgrid::TimeoutException>(m, "TimeoutException");
100 py::register_exception<simgrid::HostFailureException>(m, "HostFailureException");
101 py::register_exception<simgrid::StorageFailureException>(m, "StorageFailureException");
102 py::register_exception<simgrid::VmFailureException>(m, "VmFailureException");
103 py::register_exception<simgrid::CancelException>(m, "CancelException");
105 /* this_actor namespace */
106 m.def_submodule("this_actor", "Bindings of the s4u::this_actor namespace. See the C++ documentation for details.")
108 "debug", [](const char* s) { XBT_DEBUG("%s", s); }, "Display a logging message of 'debug' priority.")
110 "info", [](const char* s) { XBT_INFO("%s", s); }, "Display a logging message of 'info' priority.")
112 "warning", [](const char* s) { XBT_WARN("%s", s); }, "Display a logging message of 'warning' priority.")
114 "error", [](const char* s) { XBT_ERROR("%s", s); }, "Display a logging message of 'error' priority.")
115 .def("execute", py::overload_cast<double, double>(&simgrid::s4u::this_actor::execute),
116 py::call_guard<py::gil_scoped_release>(),
117 "Block the current actor, computing the given amount of flops at the given priority.", py::arg("flops"),
118 py::arg("priority") = 1)
119 .def("exec_init", py::overload_cast<double>(&simgrid::s4u::this_actor::exec_init),
120 py::call_guard<py::gil_scoped_release>())
121 .def("get_host", &simgrid::s4u::this_actor::get_host, "Retrieves host on which the current actor is located")
122 .def("set_host", &simgrid::s4u::this_actor::set_host, py::call_guard<py::gil_scoped_release>(),
123 "Moves the current actor to another host.", py::arg("dest"))
124 .def("sleep_for", static_cast<void (*)(double)>(&simgrid::s4u::this_actor::sleep_for),
125 py::call_guard<py::gil_scoped_release>(), "Block the actor sleeping for that amount of seconds.",
127 .def("sleep_until", static_cast<void (*)(double)>(&simgrid::s4u::this_actor::sleep_until),
128 py::call_guard<py::gil_scoped_release>(), "Block the actor sleeping until the specified timestamp.",
130 .def("suspend", &simgrid::s4u::this_actor::suspend, py::call_guard<py::gil_scoped_release>(),
131 "Suspend the current actor, that is blocked until resume()ed by another actor.")
132 .def("yield_", &simgrid::s4u::this_actor::yield, py::call_guard<py::gil_scoped_release>(), "Yield the actor")
133 .def("exit", &simgrid::s4u::this_actor::exit, py::call_guard<py::gil_scoped_release>(), "kill the current actor")
137 py::function fun = py::reinterpret_borrow<py::function>(cb);
138 fun.inc_ref(); // FIXME: why is this needed for tests like actor-kill and actor-lifetime?
139 simgrid::s4u::this_actor::on_exit([fun](bool failed) {
140 py::gil_scoped_acquire py_context; // need a new context for callback
143 } catch (const py::error_already_set& e) {
144 xbt_die("Error while executing the on_exit lambda: %s", e.what());
148 py::call_guard<py::gil_scoped_release>(),
149 "Define a lambda to be called when the actor ends. It takes a bool parameter indicating whether the actor "
150 "was killed. If False, the actor finished peacefully.")
151 .def("get_pid", &simgrid::s4u::this_actor::get_pid, "Retrieves PID of the current actor")
152 .def("get_ppid", &simgrid::s4u::this_actor::get_ppid,
153 "Retrieves PPID of the current actor (i.e., the PID of its parent).");
156 py::class_<Engine>(m, "Engine", "Simulation Engine")
157 .def(py::init([](std::vector<std::string> args) {
158 auto argc = static_cast<int>(args.size());
159 std::vector<char*> argv(args.size() + 1); // argv[argc] is nullptr
160 std::transform(begin(args), end(args), begin(argv), [](std::string& s) { return &s.front(); });
161 // Currently this can be dangling, we should wrap this somehow.
162 return new simgrid::s4u::Engine(&argc, argv.data());
164 "The constructor should take the parameters from the command line, as is ")
165 .def_static("get_clock",
166 []() // XBT_ATTRIB_DEPRECATED_v334
169 PyExc_DeprecationWarning,
170 "get_clock() is deprecated and will be dropped after v3.33, use `Engine.clock` instead.", 1);
171 return Engine::get_clock();
173 .def_property_readonly_static(
174 "clock", [](py::object /* self */) { return Engine::get_clock(); },
175 "The simulation time, ie the amount of simulated seconds since the simulation start.")
176 .def_property_readonly_static(
177 "instance", [](py::object /* self */) { return Engine::get_instance(); }, "Retrieve the simulation engine")
178 .def("get_all_hosts",
179 [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
181 PyErr_WarnEx(PyExc_DeprecationWarning,
182 "get_all_hosts() is deprecated and will be dropped after v3.33, use all_hosts instead.", 1);
183 return self.attr("all_hosts");
185 .def_property_readonly("all_hosts", &Engine::get_all_hosts, "Returns the list of all hosts found in the platform")
186 .def("get_all_links",
187 [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
189 PyErr_WarnEx(PyExc_DeprecationWarning,
190 "get_all_links() is deprecated and will be dropped after v3.33, use all_links instead.", 1);
191 return self.attr("all_links");
193 .def_property_readonly("all_links", &Engine::get_all_links, "Returns the list of all links found in the platform")
194 .def("get_all_netpoints",
195 [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
198 PyExc_DeprecationWarning,
199 "get_all_netpoints() is deprecated and will be dropped after v3.33, use all_netpoints instead.", 1);
200 return self.attr("all_netpoints");
202 .def_property_readonly("all_netpoints", &Engine::get_all_netpoints)
203 .def("get_netzone_root",
204 [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
206 PyErr_WarnEx(PyExc_DeprecationWarning,
207 "get_netzone_root() is deprecated and will be dropped after v3.3, use netzone_root instead.",
209 return self.attr("netzone_root");
211 .def_property_readonly("netzone_root", &Engine::get_netzone_root,
212 "Retrieve the root netzone, containing all others.")
213 .def("netpoint_by_name", &Engine::netpoint_by_name_or_null)
214 .def("netzone_by_name", &Engine::netzone_by_name_or_null)
215 .def("load_platform", &Engine::load_platform, "Load a platform file describing the environment")
216 .def("load_deployment", &Engine::load_deployment, "Load a deployment file and launch the actors that it contains")
217 .def("run", &Engine::run, py::call_guard<py::gil_scoped_release>(), "Run the simulation until its end")
218 .def("run_until", py::overload_cast<double>(&Engine::run_until, py::const_),
219 py::call_guard<py::gil_scoped_release>(), "Run the simulation until the given date",
220 py::arg("max_date") = -1)
223 [](Engine* e, const std::string& name, py::object fun_or_class) {
224 e->register_actor(name, [fun_or_class](std::vector<std::string> args) {
225 py::gil_scoped_acquire py_context;
227 /* Convert the std::vector into a py::tuple */
228 py::tuple params(args.size() - 1);
229 for (size_t i = 1; i < args.size(); i++)
230 params[i - 1] = py::cast(args[i]);
232 py::object res = fun_or_class(*params);
233 /* If I was passed a class, I just built an instance, so I need to call it now */
234 if (py::isinstance<py::function>(res))
236 } catch (const py::error_already_set& ex) {
237 if (ex.matches(pyForcefulKillEx)) {
238 XBT_VERB("Actor killed");
239 simgrid::ForcefulKillException::do_throw(); // Forward that ForcefulKill exception
245 "Registers the main function of an actor");
248 py::class_<simgrid::s4u::NetZone, std::unique_ptr<simgrid::s4u::NetZone, py::nodelete>> netzone(
249 m, "NetZone", "Networking Zones. See the C++ documentation for details.");
250 netzone.def_static("create_full_zone", &simgrid::s4u::create_full_zone, "Creates a zone of type FullZone")
251 .def_static("create_torus_zone", &simgrid::s4u::create_torus_zone, "Creates a cluster of type Torus")
252 .def_static("create_fatTree_zone", &simgrid::s4u::create_fatTree_zone, "Creates a cluster of type Fat-Tree")
253 .def_static("create_dragonfly_zone", &simgrid::s4u::create_dragonfly_zone, "Creates a cluster of type Dragonfly")
254 .def_static("create_star_zone", &simgrid::s4u::create_star_zone, "Creates a zone of type Star")
255 .def_static("create_floyd_zone", &simgrid::s4u::create_floyd_zone, "Creates a zone of type Floyd")
256 .def_static("create_dijkstra_zone", &simgrid::s4u::create_floyd_zone, "Creates a zone of type Dijkstra")
257 .def_static("create_vivaldi_zone", &simgrid::s4u::create_vivaldi_zone, "Creates a zone of type Vivaldi")
258 .def_static("create_empty_zone", &simgrid::s4u::create_empty_zone, "Creates a zone of type Empty")
259 .def_static("create_wifi_zone", &simgrid::s4u::create_wifi_zone, "Creates a zone of type Wi-Fi")
261 py::overload_cast<simgrid::kernel::routing::NetPoint*, simgrid::kernel::routing::NetPoint*,
262 simgrid::kernel::routing::NetPoint*, simgrid::kernel::routing::NetPoint*,
263 const std::vector<simgrid::s4u::LinkInRoute>&, bool>(&simgrid::s4u::NetZone::add_route),
264 "Add a route between 2 netpoints")
265 .def("create_host", py::overload_cast<const std::string&, double>(&simgrid::s4u::NetZone::create_host),
268 py::overload_cast<const std::string&, const std::string&>(&simgrid::s4u::NetZone::create_host),
271 py::overload_cast<const std::string&, const std::vector<double>&>(&simgrid::s4u::NetZone::create_host),
274 py::overload_cast<const std::string&, const std::vector<std::string>&>(&simgrid::s4u::NetZone::create_host),
276 .def("create_link", py::overload_cast<const std::string&, double>(&simgrid::s4u::NetZone::create_link),
277 "Creates a network link")
279 py::overload_cast<const std::string&, const std::string&>(&simgrid::s4u::NetZone::create_link),
280 "Creates a network link")
282 py::overload_cast<const std::string&, const std::vector<double>&>(&simgrid::s4u::NetZone::create_link),
283 "Creates a network link")
285 py::overload_cast<const std::string&, const std::vector<std::string>&>(&simgrid::s4u::NetZone::create_link),
286 "Creates a network link")
287 .def("create_split_duplex_link",
288 py::overload_cast<const std::string&, double>(&simgrid::s4u::NetZone::create_split_duplex_link),
289 "Creates a split-duplex link")
290 .def("create_split_duplex_link",
291 py::overload_cast<const std::string&, const std::string&>(&simgrid::s4u::NetZone::create_split_duplex_link),
292 "Creates a split-duplex link")
293 .def("create_router", &simgrid::s4u::NetZone::create_router, "Create a router")
294 .def("set_parent", &simgrid::s4u::NetZone::set_parent, "Set the parent of this zone")
295 .def("set_property", &simgrid::s4u::NetZone::set_property, "Add a property to this zone")
297 [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
299 PyErr_WarnEx(PyExc_DeprecationWarning,
300 "get_netpoint() is deprecated and will be dropped after v3.33, use netpoint instead.", 1);
301 return self.attr("netpoint");
303 .def_property_readonly("netpoint", &simgrid::s4u::NetZone::get_netpoint,
304 "Retrieve the netpoint associated to this zone")
305 .def("seal", &simgrid::s4u::NetZone::seal, "Seal this NetZone")
306 .def_property_readonly(
307 "name", [](const simgrid::s4u::NetZone* self) { return self->get_name(); },
308 "The name of this network zone (read-only property).");
310 /* Class ClusterCallbacks */
311 py::class_<simgrid::s4u::ClusterCallbacks>(m, "ClusterCallbacks", "Callbacks used to create cluster zones")
312 .def(py::init<const std::function<simgrid::s4u::ClusterCallbacks::ClusterNetPointCb>&,
313 const std::function<simgrid::s4u::ClusterCallbacks::ClusterLinkCb>&,
314 const std::function<simgrid::s4u::ClusterCallbacks::ClusterLinkCb>&>());
316 /* Class FatTreeParams */
317 py::class_<simgrid::s4u::FatTreeParams>(m, "FatTreeParams", "Parameters to create a Fat-Tree zone")
318 .def(py::init<unsigned int, const std::vector<unsigned int>&, const std::vector<unsigned int>&,
319 const std::vector<unsigned int>&>());
321 /* Class DragonflyParams */
322 py::class_<simgrid::s4u::DragonflyParams>(m, "DragonflyParams", "Parameters to create a Dragonfly zone")
323 .def(py::init<const std::pair<unsigned int, unsigned int>&, const std::pair<unsigned int, unsigned int>&,
324 const std::pair<unsigned int, unsigned int>&, unsigned int>());
327 py::class_<simgrid::s4u::Host, std::unique_ptr<Host, py::nodelete>> host(
328 m, "Host", "Simulated host. See the C++ documentation for details.");
329 host.def_static("by_name", &Host::by_name, py::arg("name"), "Retrieves a host from its name, or die")
332 [](const simgrid::s4u::Host* h, const simgrid::s4u::Host* to) {
333 auto* list = new std::vector<Link*>();
335 h->route_to(to, *list, &bw);
336 return make_tuple(list, bw);
338 "Retrieves the list of links and the bandwidth between two hosts.")
341 [](Host* h, const std::string& profile, double period) {
342 h->set_speed_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
344 py::call_guard<py::gil_scoped_release>(),
345 "Specify a profile modeling the external load according to an exhaustive list. "
346 "Each line of the profile describes timed events as ``date ratio``. "
347 "For example, the following content describes an host which computational speed is initially 1 (i.e, 100%) "
348 "and then halved after 42 seconds:\n\n"
349 ".. code-block:: python\n\n"
354 ".. warning:: Don't get fooled: bandwidth and latency profiles of links contain absolute values,"
355 " while speed profiles of hosts contain ratios.\n\n"
356 "The second function parameter is the periodicity: the time to wait after the last event to start again over "
357 "the list. Set it to -1 to not loop over.")
360 [](Host* h, const std::string& profile, double period) {
361 h->set_state_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
363 py::call_guard<py::gil_scoped_release>(),
364 "Specify a profile modeling the churn. "
365 "Each line of the profile describes timed events as ``date boolean``, where the boolean (0 or 1) tells "
366 "whether the host is on. "
367 "For example, the following content describes a link which turns off at t=1 and back on at t=2:\n\n"
368 ".. code-block:: python\n\n"
373 "The second function parameter is the periodicity: the time to wait after the last event to start again over "
374 "the list. Set it to -1 to not loop over.")
375 .def("get_pstate_count",
376 [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
379 PyExc_DeprecationWarning,
380 "get_pstate_count() is deprecated and will be dropped after v3.33, use pstate_count instead.", 1);
381 return self.attr("pstate_count");
383 .def_property_readonly("pstate_count", &Host::get_pstate_count, "Retrieve the count of defined pstate levels")
384 .def("get_pstate_speed",
385 [](py::object self, int state) // XBT_ATTRIB_DEPRECATED_v334
388 PyExc_DeprecationWarning,
389 "get_pstate_speed() is deprecated and will be dropped after v3.33, use pstate_speed instead.", 1);
390 return self.attr("pstate_speed")(state);
392 .def("pstate_speed", &Host::get_pstate_speed, py::call_guard<py::gil_scoped_release>(),
393 "Retrieve the maximal speed at the given pstate")
395 [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
397 PyErr_WarnEx(PyExc_DeprecationWarning,
398 "get_netpoint() is deprecated and will be dropped after v3.33, use netpoint instead.", 1);
399 return self.attr("netpoint");
401 .def_property_readonly("netpoint", &Host::get_netpoint, "Retrieve the netpoint associated to this zone")
402 .def("get_disks", &Host::get_disks, "Retrieve the list of disks in this host")
403 .def("set_core_count",
404 [](py::object self, double count) // XBT_ATTRIB_DEPRECATED_v334
406 PyErr_WarnEx(PyExc_DeprecationWarning,
407 "set_core_count() is deprecated and will be dropped after v3.33, use core_count instead.",
409 self.attr("core_count")(count);
412 "core_count", &Host::get_core_count,
413 [](Host* h, int count) {
414 py::gil_scoped_release gil_guard;
415 return h->set_core_count(count);
417 "Manage the number of cores in the CPU")
418 .def("set_coordinates", &Host::set_coordinates, py::call_guard<py::gil_scoped_release>(),
419 "Set the coordinates of this host")
420 .def("set_sharing_policy", &simgrid::s4u::Host::set_sharing_policy, py::call_guard<py::gil_scoped_release>(),
421 "Describe how the CPU is shared", py::arg("policy"), py::arg("cb") = simgrid::s4u::NonLinearResourceCb())
422 .def("create_disk", py::overload_cast<const std::string&, double, double>(&Host::create_disk),
423 py::call_guard<py::gil_scoped_release>(), "Create a disk")
425 py::overload_cast<const std::string&, const std::string&, const std::string&>(&Host::create_disk),
426 py::call_guard<py::gil_scoped_release>(), "Create a disk")
427 .def("seal", &Host::seal, py::call_guard<py::gil_scoped_release>(), "Seal this host")
429 "pstate", &Host::get_pstate,
431 py::gil_scoped_release gil_guard;
434 "The current pstate (read/write property).")
435 .def_static("current", &Host::current, py::call_guard<py::gil_scoped_release>(),
436 "Retrieves the host on which the running actor is located.")
437 .def_property_readonly(
439 [](const Host* self) {
440 return std::string(self->get_name().c_str()); // Convert from xbt::string because of MC
442 "The name of this host (read-only property).")
443 .def_property_readonly("load", &Host::get_load,
444 "Returns the current computation load (in flops per second), NOT taking the external load "
445 "into account. This is the currently achieved speed (read-only property).")
446 .def_property_readonly(
447 "speed", &Host::get_speed,
448 "The peak computing speed in flops/s at the current pstate, NOT taking the external load into account. "
449 "This is the max potential speed (read-only property).")
450 .def_property_readonly("available_speed", &Host::get_available_speed,
451 "Get the available speed ratio, between 0 and 1.\n"
452 "This accounts for external load (see :py:func:`set_speed_profile() "
453 "<simgrid.Host.set_speed_profile>`) (read-only property).")
457 Host::on_creation_cb([cb](Host& h) {
458 py::function fun = py::reinterpret_borrow<py::function>(cb);
459 py::gil_scoped_acquire py_context; // need a new context for callback
462 } catch (const py::error_already_set& e) {
463 xbt_die("Error while executing the on_creation lambda : %s", e.what());
467 py::call_guard<py::gil_scoped_release>(), "");
469 py::enum_<simgrid::s4u::Host::SharingPolicy>(host, "SharingPolicy")
470 .value("NONLINEAR", simgrid::s4u::Host::SharingPolicy::NONLINEAR)
471 .value("LINEAR", simgrid::s4u::Host::SharingPolicy::LINEAR)
475 py::class_<simgrid::s4u::Disk, std::unique_ptr<simgrid::s4u::Disk, py::nodelete>> disk(
476 m, "Disk", "Simulated disk. See the C++ documentation for details.");
477 disk.def("read", py::overload_cast<sg_size_t, double>(&simgrid::s4u::Disk::read, py::const_),
478 py::call_guard<py::gil_scoped_release>(), "Read data from disk", py::arg("size"), py::arg("priority") = 1)
479 .def("write", py::overload_cast<sg_size_t, double>(&simgrid::s4u::Disk::write, py::const_),
480 py::call_guard<py::gil_scoped_release>(), "Write data in disk", py::arg("size"), py::arg("priority") = 1)
481 .def("read_async", &simgrid::s4u::Disk::read_async, py::call_guard<py::gil_scoped_release>(),
482 "Non-blocking read data from disk")
483 .def("write_async", &simgrid::s4u::Disk::write_async, py::call_guard<py::gil_scoped_release>(),
484 "Non-blocking write data in disk")
485 .def("set_sharing_policy", &simgrid::s4u::Disk::set_sharing_policy, py::call_guard<py::gil_scoped_release>(),
486 "Set sharing policy for this disk", py::arg("op"), py::arg("policy"),
487 py::arg("cb") = simgrid::s4u::NonLinearResourceCb())
488 .def("seal", &simgrid::s4u::Disk::seal, py::call_guard<py::gil_scoped_release>(), "Seal this disk")
489 .def_property_readonly(
490 "name", [](const simgrid::s4u::Disk* self) { return self->get_name(); },
491 "The name of this disk (read-only property).");
492 py::enum_<simgrid::s4u::Disk::SharingPolicy>(disk, "SharingPolicy")
493 .value("NONLINEAR", simgrid::s4u::Disk::SharingPolicy::NONLINEAR)
494 .value("LINEAR", simgrid::s4u::Disk::SharingPolicy::LINEAR)
496 py::enum_<simgrid::s4u::Disk::Operation>(disk, "Operation")
497 .value("READ", simgrid::s4u::Disk::Operation::READ)
498 .value("WRITE", simgrid::s4u::Disk::Operation::WRITE)
499 .value("READWRITE", simgrid::s4u::Disk::Operation::READWRITE)
503 py::class_<simgrid::kernel::routing::NetPoint, std::unique_ptr<simgrid::kernel::routing::NetPoint, py::nodelete>>
504 netpoint(m, "NetPoint", "NetPoint object");
507 py::class_<Link, std::unique_ptr<Link, py::nodelete>> link(m, "Link",
508 "Network link. See the C++ documentation for details.");
509 link.def("set_latency", py::overload_cast<const std::string&>(&Link::set_latency),
510 py::call_guard<py::gil_scoped_release>(),
511 "Set the latency as a string. Accepts values with units, such as ‘1s’ or ‘7ms’.\nFull list of accepted "
512 "units: w (week), d (day), h, s, ms, us, ns, ps.")
513 .def("set_latency", py::overload_cast<double>(&Link::set_latency), py::call_guard<py::gil_scoped_release>(),
514 "Set the latency as a float (in seconds).")
515 .def("set_bandwidth", &Link::set_bandwidth, py::call_guard<py::gil_scoped_release>(),
516 "Set the bandwidth (in byte per second).")
518 "set_bandwidth_profile",
519 [](Link* l, const std::string& profile, double period) {
520 l->set_bandwidth_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
522 py::call_guard<py::gil_scoped_release>(),
523 "Specify a profile modeling the external load according to an exhaustive list. "
524 "Each line of the profile describes timed events as ``date bandwidth`` (in bytes per second). "
525 "For example, the following content describes a link which bandwidth changes to 40 Mb/s at t=4, and to 6 "
527 ".. code-block:: python\n\n"
532 ".. warning:: Don't get fooled: bandwidth and latency profiles of links contain absolute values,"
533 " while speed profiles of hosts contain ratios.\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.")
537 "set_latency_profile",
538 [](Link* l, const std::string& profile, double period) {
539 l->set_latency_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
541 py::call_guard<py::gil_scoped_release>(),
542 "Specify a profile modeling the external load according to an exhaustive list. "
543 "Each line of the profile describes timed events as ``date latency`` (in seconds). "
544 "For example, the following content describes a link which latency changes to 1ms (0.001s) at t=1, and to 2s "
546 ".. code-block:: python\n\n"
551 ".. warning:: Don't get fooled: bandwidth and latency profiles of links contain absolute values,"
552 " while speed profiles of hosts contain ratios.\n\n"
553 "The second function parameter is the periodicity: the time to wait after the last event to start again over "
554 "the list. Set it to -1 to not loop over.")
557 [](Link* l, const std::string& profile, double period) {
558 l->set_state_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
560 "Specify a profile modeling the churn. "
561 "Each line of the profile describes timed events as ``date boolean``, where the boolean (0 or 1) tells "
562 "whether the link is on. "
563 "For example, the following content describes a link which turns off at t=1 and back on at t=2:\n\n"
564 ".. code-block:: python\n\n"
569 "The second function parameter is the periodicity: the time to wait after the last event to start again over "
570 "the list. Set it to -1 to not loop over.")
572 .def("turn_on", &Link::turn_on, py::call_guard<py::gil_scoped_release>(), "Turns the link on.")
573 .def("turn_off", &Link::turn_off, py::call_guard<py::gil_scoped_release>(), "Turns the link off.")
574 .def("is_on", &Link::is_on, "Check whether the link is on.")
576 .def("set_sharing_policy", &Link::set_sharing_policy, py::call_guard<py::gil_scoped_release>(),
577 "Set sharing policy for this link")
578 .def("set_concurrency_limit", &Link::set_concurrency_limit, py::call_guard<py::gil_scoped_release>(),
579 "Set concurrency limit for this link")
580 .def("set_host_wifi_rate", &Link::set_host_wifi_rate, py::call_guard<py::gil_scoped_release>(),
581 "Set level of communication speed of given host on this Wi-Fi link")
582 .def_static("by_name", &Link::by_name, "Retrieves a Link from its name, or dies")
583 .def("seal", &Link::seal, py::call_guard<py::gil_scoped_release>(), "Seal this link")
584 .def_property_readonly(
586 [](const Link* self) {
587 return std::string(self->get_name().c_str()); // Convert from xbt::string because of MC
589 "The name of this link")
590 .def_property_readonly("bandwidth", &Link::get_bandwidth,
591 "The bandwidth (in bytes per second) (read-only property).")
592 .def_property_readonly("latency", &Link::get_latency, "The latency (in seconds) (read-only property).");
594 py::enum_<Link::SharingPolicy>(link, "SharingPolicy")
595 .value("NONLINEAR", Link::SharingPolicy::NONLINEAR)
596 .value("WIFI", Link::SharingPolicy::WIFI)
597 .value("SPLITDUPLEX", Link::SharingPolicy::SPLITDUPLEX)
598 .value("SHARED", Link::SharingPolicy::SHARED)
599 .value("FATPIPE", Link::SharingPolicy::FATPIPE)
602 /* Class LinkInRoute */
603 py::class_<simgrid::s4u::LinkInRoute> linkinroute(m, "LinkInRoute", "Abstraction to add link in routes");
604 linkinroute.def(py::init<const Link*>());
605 linkinroute.def(py::init<const Link*, simgrid::s4u::LinkInRoute::Direction>());
606 py::enum_<simgrid::s4u::LinkInRoute::Direction>(linkinroute, "Direction")
607 .value("UP", simgrid::s4u::LinkInRoute::Direction::UP)
608 .value("DOWN", simgrid::s4u::LinkInRoute::Direction::DOWN)
609 .value("NONE", simgrid::s4u::LinkInRoute::Direction::NONE)
612 /* Class Split-Duplex Link */
613 py::class_<simgrid::s4u::SplitDuplexLink, Link, std::unique_ptr<simgrid::s4u::SplitDuplexLink, py::nodelete>>(
614 m, "SplitDuplexLink", "Network split-duplex link")
616 [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
618 PyErr_WarnEx(PyExc_DeprecationWarning,
619 "get_link_up() is deprecated and will be dropped after v3.33, use link_up instead.", 1);
620 return self.attr("link_up");
622 .def_property_readonly("link_up", &simgrid::s4u::SplitDuplexLink::get_link_up, "Get link direction up")
623 .def("get_link_down",
624 [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
626 PyErr_WarnEx(PyExc_DeprecationWarning,
627 "get_link_down() is deprecated and will be dropped after v3.33, use link_down instead.", 1);
628 return self.attr("link_down");
630 .def_property_readonly("link_down", &simgrid::s4u::SplitDuplexLink::get_link_down, "Get link direction down");
633 py::class_<simgrid::s4u::Mailbox, std::unique_ptr<Mailbox, py::nodelete>>(
634 m, "Mailbox", "Mailbox. See the C++ documentation for details.")
636 "__str__", [](const Mailbox* self) { return std::string("Mailbox(") + self->get_cname() + ")"; },
637 "Textual representation of the Mailbox`")
638 .def_static("by_name", &Mailbox::by_name,
639 py::call_guard<py::gil_scoped_release>(),
641 "Retrieve a Mailbox from its name")
642 .def_property_readonly(
644 [](const Mailbox* self) {
645 return std::string(self->get_name().c_str()); // Convert from xbt::string because of MC
647 "The name of that mailbox (read-only property).")
650 [](Mailbox* self, py::object data, int size, double timeout) {
652 self->put(data.ptr(), size, timeout);
654 py::call_guard<py::gil_scoped_release>(), "Blocking data transmission with a timeout")
657 [](Mailbox* self, py::object data, int size) {
659 self->put(data.ptr(), size);
661 py::call_guard<py::gil_scoped_release>(), "Blocking data transmission")
664 [](Mailbox* self, py::object data, int size) {
666 return self->put_async(data.ptr(), size);
668 py::call_guard<py::gil_scoped_release>(), "Non-blocking data transmission")
671 [](Mailbox* self, py::object data, int size) {
673 return self->put_init(data.ptr(), size);
675 py::call_guard<py::gil_scoped_release>(),
676 "Creates (but don’t start) a data transmission to that mailbox.")
680 py::object data = py::reinterpret_steal<py::object>(self->get<PyObject>());
681 // data.dec_ref(); // FIXME: why does it break python-actor-create?
684 py::call_guard<py::gil_scoped_release>(), "Blocking data reception")
687 [](Mailbox* self) -> std::tuple<simgrid::s4u::CommPtr, PyGetAsync> {
689 auto comm = self->get_async(wrap.get());
690 return std::make_tuple(std::move(comm), std::move(wrap));
692 py::call_guard<py::gil_scoped_release>(),
693 "Non-blocking data reception. Use data.get() to get the python object after the communication has finished")
695 "set_receiver", [](Mailbox* self, ActorPtr actor) { self->set_receiver(actor); },
696 py::call_guard<py::gil_scoped_release>(), "Sets the actor as permanent receiver");
698 /* Class PyGetAsync */
699 py::class_<PyGetAsync>(m, "PyGetAsync", "Wrapper for async get communications")
702 "get", [](const PyGetAsync* self) { return py::reinterpret_steal<py::object>(*(self->get())); },
703 "Get python object after async communication in receiver side");
706 py::class_<simgrid::s4u::Comm, simgrid::s4u::CommPtr>(m, "Comm",
707 "Communication. See the C++ documentation for details.")
708 .def("test", &simgrid::s4u::Comm::test, py::call_guard<py::gil_scoped_release>(),
709 "Test whether the communication is terminated.")
710 .def("wait", &simgrid::s4u::Comm::wait, py::call_guard<py::gil_scoped_release>(),
711 "Block until the completion of that communication.")
712 .def("wait_for", &simgrid::s4u::Comm::wait_for,
714 py::call_guard<py::gil_scoped_release>(),
715 "Block until the completion of that communication, or raises TimeoutException after the specified timeout.")
716 .def("detach", [](simgrid::s4u::Comm* self) {
717 return self->detach();
719 py::return_value_policy::reference_internal,
720 py::call_guard<py::gil_scoped_release>(),
721 "Start the comm, and ignore its result. It can be completely forgotten after that.")
722 // use py::overload_cast for wait_all/wait_any, until the overload marked XBT_ATTRIB_DEPRECATED_v332 is removed
724 "wait_all", py::overload_cast<const std::vector<simgrid::s4u::CommPtr>&>(&simgrid::s4u::Comm::wait_all),
726 py::call_guard<py::gil_scoped_release>(),
727 "Block until the completion of all communications in the list.")
728 .def_static("wait_all_for", &simgrid::s4u::Comm::wait_all_for,
729 py::arg("comms"), py::arg("timeout"),
730 py::call_guard<py::gil_scoped_release>(),
731 "Block until the completion of all communications in the list, or raises TimeoutException after "
732 "the specified timeout.")
734 "wait_any", py::overload_cast<const std::vector<simgrid::s4u::CommPtr>&>(&simgrid::s4u::Comm::wait_any),
736 py::call_guard<py::gil_scoped_release>(),
737 "Block until the completion of any communication in the list and return the index of the terminated one.")
740 py::overload_cast<const std::vector<simgrid::s4u::CommPtr>&, double>(&simgrid::s4u::Comm::wait_any_for),
741 py::arg("comms"), py::arg("timeout"),
742 py::call_guard<py::gil_scoped_release>(),
743 "Block until the completion of any communication in the list and return the index of the terminated "
744 "one, or -1 if a timeout occurred."
748 py::class_<simgrid::s4u::Io, simgrid::s4u::IoPtr>(m, "Io", "I/O activities. See the C++ documentation for details.")
749 .def("test", &simgrid::s4u::Io::test, py::call_guard<py::gil_scoped_release>(),
750 "Test whether the I/O is terminated.")
751 .def("wait", &simgrid::s4u::Io::wait, py::call_guard<py::gil_scoped_release>(),
752 "Block until the completion of that I/O operation")
754 "wait_any_for", &simgrid::s4u::Io::wait_any_for, py::call_guard<py::gil_scoped_release>(),
755 "Block until the completion of any I/O in the list (or timeout) and return the index of the terminated one.")
756 .def_static("wait_any", &simgrid::s4u::Io::wait_any, py::call_guard<py::gil_scoped_release>(),
757 "Block until the completion of any I/O in the list and return the index of the terminated one.");
760 py::class_<simgrid::s4u::Exec, simgrid::s4u::ExecPtr>(m, "Exec", "Execution. See the C++ documentation for details.")
761 .def_property_readonly(
763 [](simgrid::s4u::ExecPtr self) {
764 py::gil_scoped_release gil_guard;
765 return self->get_remaining();
767 "Amount of flops that remain to be computed until completion (read-only property).")
768 .def_property_readonly(
770 [](simgrid::s4u::ExecPtr self) {
771 py::gil_scoped_release gil_guard;
772 return self->get_remaining_ratio();
774 "Amount of work remaining until completion from 0 (completely done) to 1 (nothing done "
775 "yet) (read-only property).")
776 .def_property("host", &simgrid::s4u::Exec::get_host, &simgrid::s4u::Exec::set_host,
777 "Host on which this execution runs. Only the first host is returned for parallel executions. "
778 "Changing this value migrates the execution.")
779 .def("test", &simgrid::s4u::Exec::test, py::call_guard<py::gil_scoped_release>(),
780 "Test whether the execution is terminated.")
781 .def("cancel", &simgrid::s4u::Exec::cancel, py::call_guard<py::gil_scoped_release>(), "Cancel that execution.")
782 .def("start", &simgrid::s4u::Exec::start, py::call_guard<py::gil_scoped_release>(), "Start that execution.")
783 .def("wait", &simgrid::s4u::Exec::wait, py::call_guard<py::gil_scoped_release>(),
784 "Block until the completion of that execution.");
786 /* Class Semaphore */
787 py::class_<Semaphore, SemaphorePtr>(m, "Semaphore",
788 "A classical semaphore, but blocking in the simulation world. See the C++ "
789 "documentation for details.")
790 .def(py::init<>(&Semaphore::create), py::call_guard<py::gil_scoped_release>(), py::arg("capacity"),
791 "Semaphore constructor.")
792 .def("acquire", &Semaphore::acquire, py::call_guard<py::gil_scoped_release>(),
793 "Acquire on the semaphore object with no timeout. Blocks until the semaphore is acquired.")
794 .def("acquire_timeout", &Semaphore::acquire_timeout, py::call_guard<py::gil_scoped_release>(), py::arg("timeout"),
795 "Acquire on the semaphore object with no timeout. Blocks until the semaphore is acquired or return "
796 "true if it has not been acquired after the specified timeout.")
797 .def("release", &Semaphore::release, py::call_guard<py::gil_scoped_release>(),
798 "Release the semaphore.")
799 .def_property_readonly("capacity", &Semaphore::get_capacity, py::call_guard<py::gil_scoped_release>(),
800 "Get the semaphore capacity.")
801 .def_property_readonly("would_block", &Semaphore::would_block, py::call_guard<py::gil_scoped_release>(),
802 "Check whether trying to acquire the semaphore would block (in other word, checks whether "
803 "this semaphore has capacity).")
804 // Allow semaphores to be automatically acquired/released with a context manager: `with semaphore: ...`
805 .def("__enter__", [](Semaphore* self){ self->acquire(); }, py::call_guard<py::gil_scoped_release>())
806 .def("__exit__", [](Semaphore* self){ self->release(); }, py::call_guard<py::gil_scoped_release>());
809 py::class_<Mutex, MutexPtr>(m, "Mutex",
810 "A classical mutex, but blocking in the simulation world."
811 "See the C++ documentation for details.")
812 .def(py::init<>(&Mutex::create), py::call_guard<py::gil_scoped_release>(), "Mutex constructor.")
813 .def("lock", &Mutex::lock, py::call_guard<py::gil_scoped_release>(), "Block until the mutex is acquired.")
814 .def("try_lock", &Mutex::try_lock, py::call_guard<py::gil_scoped_release>(),
815 "Try to acquire the mutex. Return true if the mutex was acquired, false otherwise.")
816 .def("unlock", &Mutex::unlock, py::call_guard<py::gil_scoped_release>(), "Release the mutex.")
817 // Allow mutexes to be automatically acquired/released with a context manager: `with mutex: ...`
818 .def("__enter__", [](Mutex* self){ self->lock(); }, py::call_guard<py::gil_scoped_release>())
819 .def("__exit__", [](Mutex* self, const py::object&, const py::object&, const py::object&) { self->unlock(); },
820 py::call_guard<py::gil_scoped_release>());
823 py::class_<Barrier, BarrierPtr>(m, "Barrier",
824 "A classical barrier, but blocking in the simulation world.")
825 .def(py::init<>(&Barrier::create), py::call_guard<py::gil_scoped_release>(), py::arg("expected_actors"),
826 "Barrier constructor.")
827 .def("wait", &Barrier::wait, py::call_guard<py::gil_scoped_release>(),
828 "Blocks into the barrier. Every waiting actors will be unlocked once the expected amount of actors reaches "
832 py::class_<simgrid::s4u::Actor, ActorPtr>(m, "Actor",
833 "An actor is an independent stream of execution in your distributed "
834 "application. See the C++ documentation for details.")
837 [](py::str name, Host* h, py::object fun, py::args args) {
838 fun.inc_ref(); // FIXME: why is this needed for tests like exec-async, exec-dvfs and exec-remote?
839 args.inc_ref(); // FIXME: why is this needed for tests like actor-migrate?
840 return simgrid::s4u::Actor::create(name, h, [fun, args]() {
841 py::gil_scoped_acquire py_context;
844 } catch (const py::error_already_set& ex) {
845 if (ex.matches(pyForcefulKillEx)) {
846 XBT_VERB("Actor killed");
847 simgrid::ForcefulKillException::do_throw(); // Forward that ForcefulKill exception
853 py::call_guard<py::gil_scoped_release>(),
854 "Create an actor from a function or an object. See the :ref:`example <s4u_ex_actors_create>`.")
856 "host", &Actor::get_host,
857 [](Actor* a, Host* h) {
858 py::gil_scoped_release gil_guard;
861 "The host on which this actor is located. Changing this value migrates the actor.\n\n"
862 "If the actor is currently blocked on an execution activity, the activity is also migrated to the new host. "
863 "If it’s blocked on another kind of activity, an error is raised as the mandated code is not written yet. "
864 "Please report that bug if you need it.\n\n"
865 "Asynchronous activities started by the actor are not migrated automatically, so you have to take care of "
866 "this yourself (only you knows which ones should be migrated). ")
867 .def_property_readonly("name", &Actor::get_cname, "The name of this actor (read-only property).")
868 .def_property_readonly("pid", &Actor::get_pid, "The PID (unique identifier) of this actor (read-only property).")
869 .def_property_readonly("ppid", &Actor::get_ppid,
870 "The PID (unique identifier) of the actor that created this one (read-only property).")
871 .def_static("by_pid", &Actor::by_pid, py::arg("pid"), "Retrieve an actor by its PID")
872 .def("set_auto_restart", &Actor::set_auto_restart, py::call_guard<py::gil_scoped_release>(),
873 "Specify whether the actor shall restart when its host reboots.")
874 .def("daemonize", &Actor::daemonize, py::call_guard<py::gil_scoped_release>(),
875 "This actor will be automatically terminated when the last non-daemon actor finishes (more info in the C++ "
877 .def("is_daemon", &Actor::is_daemon,
878 "Returns True if that actor is a daemon and will be terminated automatically when the last non-daemon actor "
880 .def("join", py::overload_cast<double>(&Actor::join, py::const_), py::call_guard<py::gil_scoped_release>(),
881 "Wait for the actor to finish (more info in the C++ documentation).", py::arg("timeout") = -1)
882 .def("kill", &Actor::kill, py::call_guard<py::gil_scoped_release>(), "Kill that actor")
883 .def("self", &Actor::self, "Retrieves the current actor.")
884 .def("is_suspended", &Actor::is_suspended, "Returns True if that actor is currently suspended.")
885 .def("suspend", &Actor::suspend, py::call_guard<py::gil_scoped_release>(),
886 "Suspend that actor, that is blocked until resume()ed by another actor.")
887 .def("resume", &Actor::resume, py::call_guard<py::gil_scoped_release>(),
888 "Resume that actor, that was previously suspend()ed.")
889 .def_static("kill_all", &Actor::kill_all, py::call_guard<py::gil_scoped_release>(), "Kill all actors but the caller.");