Logo AND Algorithmique Numérique Distribuée

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