Logo AND Algorithmique Numérique Distribuée

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