Logo AND Algorithmique Numérique Distribuée

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