Logo AND Algorithmique Numérique Distribuée

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