Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add new entry in Release_Notes.
[simgrid.git] / src / plugins / host_load.cpp
1 /* Copyright (c) 2010-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 <simgrid/plugins/load.h>
7 #include <simgrid/s4u/Engine.hpp>
8 #include <simgrid/s4u/Exec.hpp>
9 #include <simgrid/s4u/Host.hpp>
10 #include <simgrid/s4u/VirtualMachine.hpp>
11
12 #include "src/kernel/activity/ExecImpl.hpp"
13 #include "src/simgrid/module.hpp" // SIMGRID_REGISTER_PLUGIN
14
15 // Makes sure that this plugin can be activated from the command line with ``--cfg=plugin:host_load``
16 SIMGRID_REGISTER_PLUGIN(host_load, "Cpu load", &sg_host_load_plugin_init)
17
18 /** @defgroup plugin_host_load Simple plugin that monitors the current load for each host.
19
20   @beginrst
21 In addition, this constitutes a good introductory example on how to write a plugin.
22 It attaches an extension to each host to store some data, and places callbacks in the following signals:
23
24   - :cpp:func:`simgrid::s4u::Host::on_creation_cb`: Attach a new extension to the newly created host.
25   - :cpp:func:`simgrid::s4u::Exec::on_start_cb`: Make note that a new execution started, increasing the load.
26   - :cpp:func:`simgrid::s4u::Exec::on_completion_cb`: Make note that an execution completed, decreasing the load.
27   - :cpp:func:`simgrid::s4u::Host::on_onoff_cb`: Do what is appropriate when the host gets turned off or on.
28   - :cpp:func:`simgrid::s4u::Host::on_speed_change_cb`: Do what is appropriate when the DVFS is modified.
29
30   Note that extensions are automatically destroyed when the host gets destroyed.
31   @endrst
32 */
33
34 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(host_load, plugin, "Logging specific to the HostLoad plugin");
35
36 namespace simgrid::plugin {
37
38 static const double activity_uninitialized_remaining_cost = -1;
39
40 /** This class stores the extra data needed by this plugin about a given host
41  *
42  * It is stored as an extension of s4u::Host. Such extensions are retrieved by type as follows:
43  *
44  * @verbatim
45  * simgrid::s4u::Host* this_host = ???;
46  * this_extension = host->extension<HostLoad>();
47  * @endverbatim
48  *
49  * If no extension of that type was ever attached to the inspected object, the ``extension<X>()`` template returns
50  * nullptr.
51  *
52  * Please refer to the implementation of ``sg_host_load_plugin_init()`` to see the extension objects are attached to
53  * hosts at initialization time.
54  */
55 class HostLoad {
56 public:
57   static simgrid::xbt::Extension<simgrid::s4u::Host, HostLoad> EXTENSION_ID;
58
59   explicit HostLoad(simgrid::s4u::Host* ptr)
60       : host_(ptr)
61       , last_updated_(simgrid_get_clock())
62       , last_reset_(simgrid_get_clock())
63       , current_speed_(host_->get_speed())
64       , current_flops_(host_->get_load())
65   {
66   }
67   HostLoad() = delete;
68   explicit HostLoad(simgrid::s4u::Host& ptr) = delete;
69   explicit HostLoad(simgrid::s4u::Host&& ptr) = delete;
70
71   double get_current_load() const;
72   /** Get the the average load since last reset(), as a ratio
73    *
74    * That's the ratio (amount of flops that were actually computed) / (amount of flops that could have been computed at full speed)
75    */
76   double get_average_load() { update(); return (theor_max_flops_ == 0) ? 0 : computed_flops_ / theor_max_flops_; };
77   /** Amount of flops computed since last reset() */
78   double get_computed_flops() { update(); return computed_flops_; }
79   /** Return idle time since last reset() */
80   double get_idle_time() { update(); return idle_time_; }
81   /** Return idle time over the whole simulation */
82   double get_total_idle_time() { update(); return total_idle_time_; }
83   void update();
84   void add_activity(simgrid::kernel::activity::ExecImpl* activity);
85   void reset();
86
87 private:
88   simgrid::s4u::Host* host_ = nullptr;
89   /* Stores all currently ongoing activities (computations) on this machine */
90   std::map<simgrid::kernel::activity::ExecImpl*, /* cost still remaining*/ double> current_activities;
91   double last_updated_      = 0;
92   double last_reset_        = 0;
93   /**
94    * current_speed each core is running at; we need to store this as the speed
95    * will already have changed once we get notified
96    */
97   double current_speed_     = 0;
98   /**
99    * How many flops are currently used by all the processes running on this
100    * host?
101    */
102   double current_flops_     = 0;
103   double computed_flops_    = 0;
104   double idle_time_         = 0;
105   double total_idle_time_   = 0; /* This updated but never gets reset */
106   double theor_max_flops_   = 0;
107 };
108
109 // Create the static field that the extension mechanism needs
110 simgrid::xbt::Extension<simgrid::s4u::Host, HostLoad> HostLoad::EXTENSION_ID;
111
112 void HostLoad::add_activity(simgrid::kernel::activity::ExecImpl* activity)
113 {
114   current_activities.insert({activity, activity_uninitialized_remaining_cost});
115 }
116
117 void HostLoad::update()
118 {
119   double now = simgrid_get_clock();
120
121   // This loop updates the flops that the host executed for the ongoing computations
122   auto iter = begin(current_activities);
123   while (iter != end(current_activities)) {
124     const auto& activity                   = iter->first;  // Just an alias
125     auto& remaining_cost_after_last_update = iter->second; // Just an alias
126     auto& action                           = activity->model_action_;
127     auto current_iter                      = iter;
128     ++iter;
129
130     if (action != nullptr && action->get_finish_time() != now &&
131         activity->get_state() == kernel::activity::State::RUNNING) {
132       if (remaining_cost_after_last_update == activity_uninitialized_remaining_cost) {
133         remaining_cost_after_last_update = action->get_cost();
134       }
135       double computed_flops_since_last_update = remaining_cost_after_last_update - /*remaining now*/activity->get_remaining();
136       computed_flops_                        += computed_flops_since_last_update;
137       remaining_cost_after_last_update        = activity->get_remaining();
138     } else if (activity->get_state() == kernel::activity::State::DONE) {
139       computed_flops_ += remaining_cost_after_last_update;
140       current_activities.erase(current_iter);
141     }
142   }
143
144   /* Current flop per second computed by the cpu; current_flops = k * pstate_speed_in_flops, k @in {0, 1, ..., cores-1}
145    * designates number of active cores; will be 0 if CPU is currently idle */
146   current_flops_ = host_->get_load();
147
148   if (current_flops_ == 0) {
149     idle_time_ += (now - last_updated_);
150     total_idle_time_ += (now - last_updated_);
151     XBT_DEBUG("[%s]: Currently idle -> Added %f seconds to idle time (totaling %fs)", host_->get_cname(), (now - last_updated_), idle_time_);
152   }
153
154   theor_max_flops_ += current_speed_ * host_->get_core_count() * (now - last_updated_);
155   current_speed_ = host_->get_speed();
156   last_updated_  = now;
157 }
158
159 /** @brief Get the current load as a ratio = achieved_flops / (core_current_speed * core_amount)
160  *
161  * You may also want to check simgrid::s4u::Host::get_load() that simply returns
162  * the achieved flop rate (in flops per seconds), ie the load that a new action arriving on
163  * that host would suffer.
164  *
165  * Please note that this function only returns an instantaneous load that may be deceiving
166  * in some scenarios. For example, imagine that an activity terminates at time t, and that
167  * another activity is created on the same host at the exact same timestamp. The load was
168  * never 0 on the simulated machine since the time did not advance between the two events.
169  * But still, if you call this function between the two events (in the simulator course), it
170  * returns 0 although there is no time (in the simulated time) where this value is valid.
171  */
172 double HostLoad::get_current_load() const
173 {
174   // We don't need to call update() here because it is called every time an action terminates or starts
175   return current_flops_ / (host_->get_speed() * host_->get_core_count());
176 }
177
178 /*
179  * Resets the counters
180  */
181 void HostLoad::reset()
182 {
183   last_updated_    = simgrid_get_clock();
184   last_reset_      = simgrid_get_clock();
185   idle_time_       = 0;
186   computed_flops_  = 0;
187   theor_max_flops_ = 0;
188   current_flops_   = host_->get_load();
189   current_speed_   = host_->get_speed();
190 }
191 } // namespace simgrid::plugin
192
193 using simgrid::plugin::HostLoad;
194
195 /* **************************** events  callback *************************** */
196 /* This callback is fired either when the host changes its state (on/off) or its speed
197  * (because the user changed the pstate, or because of external trace events) */
198 static void on_host_change(simgrid::s4u::Host const& host)
199 {
200   if (dynamic_cast<simgrid::s4u::VirtualMachine const*>(&host)) // Ignore virtual machines
201     return;
202
203   host.extension<HostLoad>()->update();
204 }
205
206 /* **************************** Public interface *************************** */
207
208 /** @brief Initializes the HostLoad plugin
209  *  @ingroup plugin_host_load
210  */
211 void sg_host_load_plugin_init()
212 {
213   if (HostLoad::EXTENSION_ID.valid()) // Don't do the job twice
214     return;
215
216   // First register our extension of Hosts properly
217   HostLoad::EXTENSION_ID = simgrid::s4u::Host::extension_create<HostLoad>();
218
219   // If SimGrid is already initialized, we need to attach an extension to each existing host
220   if (simgrid::s4u::Engine::is_initialized()) {
221     const simgrid::s4u::Engine* e = simgrid::s4u::Engine::get_instance();
222     for (auto& host : e->get_all_hosts()) {
223       host->extension_set(new HostLoad(host));
224     }
225   }
226
227   // Make sure that every future host also gets an extension (in case the platform is not loaded yet)
228   simgrid::s4u::Host::on_creation_cb([](simgrid::s4u::Host& host) {
229     if (dynamic_cast<simgrid::s4u::VirtualMachine*>(&host)) // Ignore virtual machines
230       return;
231     host.extension_set(new HostLoad(&host));
232   });
233
234   simgrid::s4u::Exec::on_start_cb([](simgrid::s4u::Exec const& activity) {
235     if (activity.get_host_number() == 1) { // We only run on one host
236       simgrid::s4u::Host* host         = activity.get_host();
237       if (const auto* vm = dynamic_cast<simgrid::s4u::VirtualMachine*>(host))
238         host = vm->get_pm();
239       xbt_assert(host != nullptr);
240       host->extension<HostLoad>()->add_activity(static_cast<simgrid::kernel::activity::ExecImpl*>(activity.get_impl()));
241       host->extension<HostLoad>()->update(); // If the system was idle until now, we need to update *before*
242                                              // this computation starts running so we can keep track of the
243                                              // idle time. (Communication operations don't trigger this hook!)
244     }
245     else { // This runs on multiple hosts
246       XBT_WARN("HostLoad plugin currently does not support executions on several hosts");
247     }
248   });
249   simgrid::s4u::Exec::on_completion_cb([](simgrid::s4u::Exec const& exec) {
250     if (exec.get_host_number() == 1) { // We only run on one host
251       simgrid::s4u::Host* host = exec.get_host();
252       if (const auto* vm = dynamic_cast<simgrid::s4u::VirtualMachine*>(host))
253         host = vm->get_pm();
254       xbt_assert(host != nullptr);
255       host->extension<HostLoad>()->update();
256     } else { // This runs on multiple hosts
257       XBT_WARN("HostLoad plugin currently does not support executions on several hosts");
258     }
259   });
260   simgrid::s4u::Host::on_onoff_cb(&on_host_change);
261   simgrid::s4u::Host::on_speed_change_cb(&on_host_change);
262 }
263
264 /** @brief Returns the current load of that host, as a ratio = achieved_flops / (core_current_speed * core_amount)
265  *  @ingroup plugin_host_load
266  */
267 double sg_host_get_current_load(const_sg_host_t host)
268 {
269   xbt_assert(HostLoad::EXTENSION_ID.valid(), "Please sg_host_load_plugin_init() to initialize this plugin.");
270
271   return host->extension<HostLoad>()->get_current_load();
272 }
273
274 /** @brief Returns the current load of that host
275  *  @ingroup plugin_host_load
276  */
277 double sg_host_get_avg_load(const_sg_host_t host)
278 {
279   xbt_assert(HostLoad::EXTENSION_ID.valid(), "Please sg_host_load_plugin_init() to initialize this plugin.");
280
281   return host->extension<HostLoad>()->get_average_load();
282 }
283
284 /** @brief Returns the time this host was idle since the last reset
285  *  @ingroup plugin_host_load
286  */
287 double sg_host_get_idle_time(const_sg_host_t host)
288 {
289   xbt_assert(HostLoad::EXTENSION_ID.valid(), "Please sg_host_load_plugin_init() to initialize this plugin.");
290
291   return host->extension<HostLoad>()->get_idle_time();
292 }
293
294 /** @brief Returns the time this host was idle since the beginning of the simulation
295  *  @ingroup plugin_host_load
296  */
297 double sg_host_get_total_idle_time(const_sg_host_t host)
298 {
299   xbt_assert(HostLoad::EXTENSION_ID.valid(), "Please sg_host_load_plugin_init() to initialize this plugin.");
300
301   return host->extension<HostLoad>()->get_total_idle_time();
302 }
303
304 /** @brief Returns the amount of flops computed by that host since the last reset
305  *  @ingroup plugin_host_load
306  */
307 double sg_host_get_computed_flops(const_sg_host_t host)
308 {
309   xbt_assert(HostLoad::EXTENSION_ID.valid(), "Please sg_host_load_plugin_init() to initialize this plugin.");
310
311   return host->extension<HostLoad>()->get_computed_flops();
312 }
313
314 /** @brief Resets the idle time and flops amount of that host
315  *  @ingroup plugin_host_load
316  */
317 void sg_host_load_reset(const_sg_host_t host)
318 {
319   xbt_assert(HostLoad::EXTENSION_ID.valid(), "Please sg_host_load_plugin_init() to initialize this plugin.");
320
321   host->extension<HostLoad>()->reset();
322 }