Logo AND Algorithmique Numérique Distribuée

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