Logo AND Algorithmique Numérique Distribuée

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