Logo AND Algorithmique Numérique Distribuée

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