Logo AND Algorithmique Numérique Distribuée

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