Logo AND Algorithmique Numérique Distribuée

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