Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
include cleanups (mostly surf/surf.hpp)
[simgrid.git] / src / plugins / link_energy_wifi.cpp
1 /* Copyright (c) 2017-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/Exception.hpp>
7 #include <simgrid/plugins/energy.h>
8 #include <simgrid/s4u/Engine.hpp>
9 #include <simgrid/s4u/Host.hpp>
10 #include <simgrid/s4u/Link.hpp>
11 #include <xbt/config.hpp>
12
13 #include "src/surf/network_interface.hpp"
14 #include "src/surf/network_wifi.hpp"
15 #include "src/surf/surf_interface.hpp"
16 #include "src/kernel/lmm/maxmin.hpp"
17
18 #include <boost/algorithm/string/classification.hpp>
19 #include <boost/algorithm/string/split.hpp>
20 #include <map>
21
22 SIMGRID_REGISTER_PLUGIN(link_energy_wifi, "Energy wifi test", &sg_wifi_energy_plugin_init);
23 /** @defgroup plugin_link_energy_wifi Plugin WiFi energy
24  *
25  * This is the WiFi energy plugin, accounting for the dissipated energy of WiFi links.
26  */
27
28 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(link_energy_wifi, surf, "Logging specific to the link energy wifi plugin");
29
30 namespace simgrid {
31 namespace plugin {
32
33 class XBT_PRIVATE LinkEnergyWifi {
34   // associative array keeping size of data already sent for a given flow (required for interleaved actions)
35   std::map<kernel::resource::NetworkWifiAction*, std::pair<int, double>> flowTmp{};
36
37   // WiFi link the plugin instance is attached to
38   s4u::Link* link_{};
39
40   // dynamic energy accumulated since the simulation start (active durations consumption)
41   double eDyn_{0.0};
42   // static energy (no activity consumption)
43   double eStat_{0.0};
44
45   // duration since previous energy update
46   double prev_update_{0.0};
47
48   // Same energy calibration values as ns3 by default
49   // https://www.nsnam.org/docs/release/3.30/doxygen/classns3_1_1_wifi_radio_energy_model.html#details
50   double pIdle_{0.82};
51   double pTx_{1.14};
52   double pRx_{0.94};
53   double pSleep_{0.10};
54
55   // constant taking beacons into account (can be specified by the user)
56   double control_duration_{0.0036};
57
58   // Measurements for report
59   double dur_TxRx_{0}; // Duration of transmission
60   double dur_idle_{0}; // Duration of idle time
61   bool valuesInit_{false};
62
63 public:
64   static xbt::Extension<simgrid::s4u::Link, LinkEnergyWifi> EXTENSION_ID;
65
66   explicit LinkEnergyWifi(s4u::Link* ptr) : link_(ptr) {}
67   LinkEnergyWifi()  = delete;
68
69   /** Update the energy consumed by link_ when transmissions start or end */
70   void update(const simgrid::kernel::resource::NetworkAction &);
71
72   /** Update the energy consumed when link_ is destroyed */
73   void update_destroy();
74
75   /**
76    * Fetches energy consumption values from the platform file.
77    * The user can specify:
78    *  - wifi_watt_values: energy consumption in each state (IDLE:Tx:Rx:SLEEP)
79    *      default: 0.82:1.14:0.94:0.10
80    *  - controlDuration: duration of active beacon transmissions per second
81    *      default: 0.0036
82    */
83   void init_watts_range_list();
84
85   double get_consumed_energy(void) const { return eDyn_ + eStat_; }
86   /** Get the dynamic part of the energy for this link */
87   double get_energy_dynamic(void) const { return eDyn_; }
88   double get_energy_static(void) const { return eStat_; }
89   double get_duration_comm(void) const { return dur_TxRx_; }
90   double get_duration_idle(void) const { return dur_idle_; }
91
92   /** Set the power consumed by this link while idle */
93   void set_power_idle(double value) { pIdle_ = value; }
94   /** Set the power consumed by this link while transmitting */
95   void set_power_tx(double value) { pTx_ = value; }
96   /** Set the power consumed by this link while receiving */
97   void set_power_rx(double value) { pRx_ = value; }
98   /** Set the power consumed by this link while sleeping */
99   void set_power_sleep(double value) { pSleep_ = value; }
100 };
101
102 xbt::Extension<s4u::Link, LinkEnergyWifi> LinkEnergyWifi::EXTENSION_ID;
103
104 void LinkEnergyWifi::update_destroy()
105 {
106   auto const* wifi_link = static_cast<kernel::resource::NetworkWifiLink*>(link_->get_impl());
107   double duration       = simgrid::s4u::Engine::get_clock() - prev_update_;
108   prev_update_          = simgrid::s4u::Engine::get_clock();
109
110   dur_idle_ += duration;
111
112   // add IDLE energy usage, as well as beacons consumption since previous update
113   eDyn_ += duration * control_duration_ * wifi_link->get_host_count() * pRx_;
114   eStat_ += (duration - (duration * control_duration_)) * pIdle_ * (wifi_link->get_host_count() + 1);
115
116   XBT_DEBUG("finish eStat_ += %f * %f * (%d+1) | eStat = %f", duration, pIdle_, wifi_link->get_host_count(), eStat_);
117 }
118
119 void LinkEnergyWifi::update(const kernel::resource::NetworkAction&)
120 {
121   init_watts_range_list();
122
123   double duration = simgrid::s4u::Engine::get_clock() - prev_update_;
124   prev_update_    = simgrid::s4u::Engine::get_clock();
125
126   // we don't update for null durations
127   if(duration < 1e-6)
128     return;
129
130   auto const* wifi_link = static_cast<kernel::resource::NetworkWifiLink*>(link_->get_impl());
131
132   const kernel::lmm::Element* elem = nullptr;
133
134   /**
135    * We update the energy consumed by each flow active on the link since the previous update.
136    *
137    * To do this, we need to know how much time each flow has been effectively sending data on the WiFi link since the
138    * previous update (durUsage).  We compute this value using the size of the flow, the amount of data already spent
139    * (using flowTmp), as well as the bandwidth used by the flow since the previous update (using LMM variables).  Since
140    * flows are sharing the medium, the total active duration on the link is equal to the transmission/reception duration
141    * used by the flow with the longest active time since the previous update
142    */
143   double durUsage = 0;
144   while (const auto* var = wifi_link->get_constraint()->get_variable(&elem)) {
145     auto* action = static_cast<kernel::resource::NetworkWifiAction*>(var->get_id());
146     XBT_DEBUG("cost: %f action value: %f link rate 1: %f link rate 2: %f", action->get_cost(), action->get_rate(),
147               wifi_link->get_host_rate(&action->get_src()), wifi_link->get_host_rate(&action->get_dst()));
148
149     if (action->get_rate() != 0.0) {
150       auto it = flowTmp.find(action);
151
152       // if the flow has not been registered, initialize it: 0 bytes sent, and not updated since its creation timestamp
153       if(it == flowTmp.end())
154         flowTmp[action] = std::pair<int,double>(0, action->get_start_time());
155
156       it = flowTmp.find(action);
157
158       /**
159        * The active duration of the link is equal to the amount of data it had to send divided by the bandwidth on the link.
160        * If this is longer than the duration since the previous update, active duration = now - previous_update
161        */
162       double du = // durUsage on the current flow
163           (action->get_cost() - it->second.first) / action->get_rate();
164
165       if (du > simgrid::s4u::Engine::get_clock() - it->second.second)
166         du = simgrid::s4u::Engine::get_clock() - it->second.second;
167
168       // if the flow has been more active than the others
169       if(du > durUsage)
170         durUsage = du;
171
172       // update the amount of data already sent by the flow
173       it->second.first += du * action->get_rate();
174       it->second.second = simgrid::s4u::Engine::get_clock();
175
176       // important: if the transmission finished, remove it (needed for performance and multi-message flows)
177       if(it->second.first >= action->get_cost())
178         flowTmp.erase (it);
179     }
180   }
181
182   XBT_DEBUG("durUsage: %f", durUsage);
183
184   // beacons cost
185   eDyn_ += duration * control_duration_ * wifi_link->get_host_count() * pRx_;
186
187   /**
188    * Same principle as ns3:
189    *  - if tx or rx, update P_{dyn}
190    *  - if idle i.e. get_usage = 0, update P_{stat}
191    * P_{tot} = P_{dyn}+P_{stat}
192    */
193   if (link_->get_usage() != 0.0) {
194     eDyn_ += /*duration * */ durUsage * ((wifi_link->get_host_count() * pRx_) + pTx_);
195     eStat_ += (duration - durUsage) * pIdle_ * (wifi_link->get_host_count() + 1);
196     XBT_DEBUG("eDyn +=  %f * ((%d * %f) + %f) | eDyn = %f (durusage =%f)", durUsage, wifi_link->get_host_count(), pRx_,
197               pTx_, eDyn_, durUsage);
198     dur_TxRx_ += duration;
199   } else {
200     dur_idle_ += duration;
201     eStat_ += (duration - (duration * control_duration_)) * pIdle_ * (wifi_link->get_host_count() + 1);
202   }
203
204   XBT_DEBUG("eStat_ += %f * %f * (%d+1) | eStat = %f", duration, pIdle_, wifi_link->get_host_count(), eStat_);
205 }
206
207 void LinkEnergyWifi::init_watts_range_list()
208 {
209   if (valuesInit_)
210     return;
211   valuesInit_                      = true;
212
213   /* beacons factor
214   Set to 0 if you do not want to compute beacons,
215   otherwise to the duration of beacons transmissions per second
216   */
217   const char* beacons_factor = this->link_->get_property("control_duration");
218   if(beacons_factor != nullptr) {
219     try {
220       control_duration_ = std::stod(beacons_factor);
221     } catch (const std::invalid_argument&) {
222       throw std::invalid_argument(std::string("Invalid beacons factor value for link ") + this->link_->get_cname());
223     }
224   }
225
226   const char* all_power_values_str = this->link_->get_property("wifi_watt_values");
227   if (all_power_values_str != nullptr)
228   {
229     std::vector<std::string> all_power_values;
230     boost::split(all_power_values, all_power_values_str, boost::is_any_of(","));
231
232     for (auto current_power_values_str : all_power_values) {
233       /* retrieve the power values associated */
234       std::vector<std::string> current_power_values;
235       boost::split(current_power_values, current_power_values_str, boost::is_any_of(":"));
236       xbt_assert(current_power_values.size() == 4,
237                 "Power properties incorrectly defined - could not retrieve idle, Tx, Rx, Sleep power values for link %s",
238                 this->link_->get_cname());
239
240       /* min_power corresponds to the idle power (link load = 0) */
241       /* max_power is the power consumed at 100% link load       */
242       try {
243         pSleep_ = std::stod(current_power_values.at(3));
244       } catch (const std::invalid_argument&) {
245         throw std::invalid_argument(std::string("Invalid idle power value for link ") + this->link_->get_cname());
246       }
247       try {
248         pRx_ = std::stod(current_power_values.at(2));
249       } catch (const std::invalid_argument&) {
250         throw std::invalid_argument(std::string("Invalid idle power value for link ") + this->link_->get_cname());
251       }
252       try {
253         pTx_ = std::stod(current_power_values.at(1));
254       } catch (const std::invalid_argument&) {
255         throw std::invalid_argument(std::string("Invalid idle power value for link ") + this->link_->get_cname());
256       }
257       try {
258         pIdle_ = std::stod(current_power_values.at(0));
259       } catch (const std::invalid_argument&) {
260         throw std::invalid_argument(std::string("Invalid busy power value for link ") + this->link_->get_cname());
261       }
262
263       XBT_DEBUG("Values aa initialized with: pSleep=%f pIdle=%f pTx=%f pRx=%f", pSleep_, pIdle_, pTx_, pRx_);
264     }
265   }
266 }
267
268 } // namespace plugin
269 } // namespace simgrid
270
271 using simgrid::plugin::LinkEnergyWifi;
272
273 void sg_wifi_energy_plugin_init()
274 {
275   if (LinkEnergyWifi::EXTENSION_ID.valid())
276     return;
277
278   XBT_INFO("Activating the wifi_energy plugin.");
279   LinkEnergyWifi::EXTENSION_ID = simgrid::s4u::Link::extension_create<LinkEnergyWifi>();
280
281   /**
282    * Attaching to events:
283    * - on_creation to initialize the plugin
284    * - on_destruction to produce final energy results
285    * - on_communication_state_change: to account the energy when communications are updated
286    * - on_communicate: ''
287    */
288   simgrid::s4u::Link::on_creation.connect([](simgrid::s4u::Link& link) {
289     // verify the link is appropriate to WiFi energy computations
290     if (link.get_sharing_policy() == simgrid::s4u::Link::SharingPolicy::WIFI) {
291       XBT_DEBUG("Wifi Link: %s, initialization of wifi energy plugin", link.get_cname());
292       auto* plugin = new LinkEnergyWifi(&link);
293       link.extension_set(plugin);
294     } else {
295       XBT_DEBUG("Not Wifi Link: %s, wifi energy on link not computed", link.get_cname());
296     }
297   });
298
299   simgrid::s4u::Link::on_destruction.connect([](simgrid::s4u::Link const& link) {
300     // output energy values if WiFi link
301     if (link.get_sharing_policy() == simgrid::s4u::Link::SharingPolicy::WIFI) {
302       link.extension<LinkEnergyWifi>()->update_destroy();
303       XBT_INFO(
304           "Link %s destroyed, consumed: %f J dyn: %f stat: %f durIdle: %f durTxRx: %f", link.get_cname(),
305           link.extension<LinkEnergyWifi>()->get_consumed_energy(),
306           link.extension<LinkEnergyWifi>()->get_energy_dynamic(), link.extension<LinkEnergyWifi>()->get_energy_static(),
307           link.extension<LinkEnergyWifi>()->get_duration_idle(), link.extension<LinkEnergyWifi>()->get_duration_comm());
308     }
309   });
310
311   simgrid::s4u::Link::on_communication_state_change.connect(
312       [](simgrid::kernel::resource::NetworkAction const& action,
313          simgrid::kernel::resource::Action::State /* previous */) {
314         // update WiFi links encountered during the communication
315         for (auto const* link : action.get_links()) {
316           if (link != nullptr && link->get_sharing_policy() == simgrid::s4u::Link::SharingPolicy::WIFI) {
317             link->get_iface()->extension<LinkEnergyWifi>()->update(action);
318           }
319         }
320       });
321
322   simgrid::s4u::Link::on_communicate.connect([](const simgrid::kernel::resource::NetworkAction& action) {
323     auto const* actionWifi = dynamic_cast<const simgrid::kernel::resource::NetworkWifiAction*>(&action);
324
325     if (actionWifi == nullptr)
326       return;
327
328     auto const* link_src = actionWifi->get_src_link();
329     auto const* link_dst = actionWifi->get_dst_link();
330
331     if(link_src != nullptr)
332       link_src->get_iface()->extension<LinkEnergyWifi>()->update(action);
333     if(link_dst != nullptr)
334       link_dst->get_iface()->extension<LinkEnergyWifi>()->update(action);
335   });
336 }