Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
NetworkModelIntf: Interface to dynamic factors
[simgrid.git] / src / surf / network_cm02.cpp
1 /* Copyright (c) 2013-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 "src/surf/network_cm02.hpp"
7 #include "simgrid/kernel/routing/NetZoneImpl.hpp"
8 #include "simgrid/s4u/Engine.hpp"
9 #include "simgrid/s4u/Host.hpp"
10 #include "simgrid/sg_config.hpp"
11 #include "src/kernel/EngineImpl.hpp"
12 #include "src/kernel/resource/profile/Event.hpp"
13 #include "src/surf/network_wifi.hpp"
14 #include "src/surf/surf_interface.hpp"
15 #include "surf/surf.hpp"
16
17 #include <algorithm>
18 #include <numeric>
19
20 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(res_network);
21
22 double sg_latency_factor     = 1.0; /* default value; can be set by model or from command line */
23 double sg_bandwidth_factor   = 1.0; /* default value; can be set by model or from command line */
24 double sg_weight_S_parameter = 0.0; /* default value; can be set by model or from command line */
25
26 /************************************************************************/
27 /* New model based on optimizations discussed during Pedro Velho's thesis*/
28 /************************************************************************/
29 /* @techreport{VELHO:2011:HAL-00646896:1, */
30 /*      url = {http://hal.inria.fr/hal-00646896/en/}, */
31 /*      title = {{Flow-level network models: have we reached the limits?}}, */
32 /*      author = {Velho, Pedro and Schnorr, Lucas and Casanova, Henri and Legrand, Arnaud}, */
33 /*      type = {Rapport de recherche}, */
34 /*      institution = {INRIA}, */
35 /*      number = {RR-7821}, */
36 /*      year = {2011}, */
37 /*      month = Nov, */
38 /*      pdf = {http://hal.inria.fr/hal-00646896/PDF/rr-validity.pdf}, */
39 /*  } */
40 void surf_network_model_init_LegrandVelho()
41 {
42   auto net_model = std::make_shared<simgrid::kernel::resource::NetworkCm02Model>("Network_LegrandVelho");
43   simgrid::kernel::EngineImpl::get_instance()->add_model(net_model);
44   simgrid::s4u::Engine::get_instance()->get_netzone_root()->get_impl()->set_network_model(net_model);
45
46   simgrid::config::set_default<double>("network/latency-factor", 13.01);
47   simgrid::config::set_default<double>("network/bandwidth-factor", 0.97);
48   simgrid::config::set_default<double>("network/weight-S", 20537);
49 }
50
51 /***************************************************************************/
52 /* The nice TCP sharing model designed by Loris Marchal and Henri Casanova */
53 /***************************************************************************/
54 /* @TechReport{      rr-lip2002-40, */
55 /*   author        = {Henri Casanova and Loris Marchal}, */
56 /*   institution   = {LIP}, */
57 /*   title         = {A Network Model for Simulation of Grid Application}, */
58 /*   number        = {2002-40}, */
59 /*   month         = {oct}, */
60 /*   year          = {2002} */
61 /* } */
62 void surf_network_model_init_CM02()
63 {
64   simgrid::config::set_default<double>("network/latency-factor", 1.0);
65   simgrid::config::set_default<double>("network/bandwidth-factor", 1.0);
66   simgrid::config::set_default<double>("network/weight-S", 0.0);
67
68   auto net_model = std::make_shared<simgrid::kernel::resource::NetworkCm02Model>("Network_CM02");
69   simgrid::kernel::EngineImpl::get_instance()->add_model(net_model);
70   simgrid::s4u::Engine::get_instance()->get_netzone_root()->get_impl()->set_network_model(net_model);
71 }
72
73 namespace simgrid {
74 namespace kernel {
75 namespace resource {
76
77 NetworkCm02Model::NetworkCm02Model(const std::string& name) : NetworkModel(name)
78 {
79   std::string optim = config::get_value<std::string>("network/optim");
80   bool select       = config::get_value<bool>("network/maxmin-selective-update");
81
82   if (optim == "Lazy") {
83     set_update_algorithm(Model::UpdateAlgo::LAZY);
84     xbt_assert(select || config::is_default("network/maxmin-selective-update"),
85                "You cannot disable network selective update when using the lazy update mechanism");
86     select = true;
87   }
88
89   set_maxmin_system(new lmm::System(select));
90   loopback_ = create_link("__loopback__", std::vector<double>{config::get_value<double>("network/loopback-bw")})
91                   ->set_sharing_policy(s4u::Link::SharingPolicy::FATPIPE)
92                   ->set_latency(config::get_value<double>("network/loopback-lat"));
93   loopback_->seal();
94 }
95
96 void NetworkCm02Model::check_lat_factor_cb()
97 {
98   if (not simgrid::config::is_default("network/latency-factor")) {
99     throw std::invalid_argument(
100         "NetworkModelIntf: Cannot mix network/latency-factor and callback configuration. Choose only one of them.");
101   }
102 }
103
104 void NetworkCm02Model::check_bw_factor_cb()
105 {
106   if (not simgrid::config::is_default("network/bandwidth-factor")) {
107     throw std::invalid_argument(
108         "NetworkModelIntf: Cannot mix network/bandwidth-factor and callback configuration. Choose only one of them.");
109   }
110 }
111
112 void NetworkCm02Model::set_lat_factor_cb(const std::function<NetworkFactorCb>& cb)
113 {
114   if (not cb)
115     throw std::invalid_argument("NetworkModelIntf: Invalid callback");
116   check_lat_factor_cb();
117
118   lat_factor_cb_ = cb;
119 }
120
121 void NetworkCm02Model::set_bw_factor_cb(const std::function<NetworkFactorCb>& cb)
122 {
123   if (not cb)
124     throw std::invalid_argument("NetworkModelIntf: Invalid callback");
125   check_bw_factor_cb();
126
127   bw_factor_cb_ = cb;
128 }
129
130 LinkImpl* NetworkCm02Model::create_link(const std::string& name, const std::vector<double>& bandwidths)
131 {
132   xbt_assert(bandwidths.size() == 1, "Non-WIFI links must use only 1 bandwidth.");
133   return (new NetworkCm02Link(name, bandwidths[0], get_maxmin_system()))->set_model(this);
134 }
135
136 LinkImpl* NetworkCm02Model::create_wifi_link(const std::string& name, const std::vector<double>& bandwidths)
137 {
138   return (new NetworkWifiLink(name, bandwidths, get_maxmin_system()))->set_model(this);
139 }
140
141 void NetworkCm02Model::update_actions_state_lazy(double now, double /*delta*/)
142 {
143   while (not get_action_heap().empty() && double_equals(get_action_heap().top_date(), now, sg_surf_precision)) {
144     auto* action = static_cast<NetworkCm02Action*>(get_action_heap().pop());
145     XBT_DEBUG("Something happened to action %p", action);
146
147     // if I am wearing a latency hat
148     if (action->get_type() == ActionHeap::Type::latency) {
149       XBT_DEBUG("Latency paid for action %p. Activating", action);
150       get_maxmin_system()->update_variable_penalty(action->get_variable(), action->sharing_penalty_);
151       get_action_heap().remove(action);
152       action->set_last_update();
153
154       // if I am wearing a max_duration or normal hat
155     } else if (action->get_type() == ActionHeap::Type::max_duration || action->get_type() == ActionHeap::Type::normal) {
156       // no need to communicate anymore
157       // assume that flows that reached max_duration have remaining of 0
158       XBT_DEBUG("Action %p finished", action);
159       action->finish(Action::State::FINISHED);
160       get_action_heap().remove(action);
161     }
162   }
163 }
164
165 void NetworkCm02Model::update_actions_state_full(double /*now*/, double delta)
166 {
167   for (auto it = std::begin(*get_started_action_set()); it != std::end(*get_started_action_set());) {
168     auto& action = static_cast<NetworkCm02Action&>(*it);
169     ++it; // increment iterator here since the following calls to action.finish() may invalidate it
170     XBT_DEBUG("Something happened to action %p", &action);
171     double deltap = delta;
172     if (action.latency_ > 0) {
173       if (action.latency_ > deltap) {
174         double_update(&action.latency_, deltap, sg_surf_precision);
175         deltap = 0.0;
176       } else {
177         double_update(&deltap, action.latency_, sg_surf_precision);
178         action.latency_ = 0.0;
179       }
180       if (action.latency_ <= 0.0 && not action.is_suspended())
181         get_maxmin_system()->update_variable_penalty(action.get_variable(), action.sharing_penalty_);
182     }
183
184     if (not action.get_variable()->get_number_of_constraint()) {
185       /* There is actually no link used, hence an infinite bandwidth. This happens often when using models like
186        * vivaldi. In such case, just make sure that the action completes immediately.
187        */
188       action.update_remains(action.get_remains());
189     }
190     action.update_remains(action.get_variable()->get_value() * delta);
191
192     if (action.get_max_duration() != NO_MAX_DURATION)
193       action.update_max_duration(delta);
194
195     if (((action.get_remains() <= 0) && (action.get_variable()->get_penalty() > 0)) ||
196         ((action.get_max_duration() != NO_MAX_DURATION) && (action.get_max_duration() <= 0))) {
197       action.finish(Action::State::FINISHED);
198     }
199   }
200 }
201
202 Action* NetworkCm02Model::communicate(s4u::Host* src, s4u::Host* dst, double size, double rate)
203 {
204   double latency = 0.0;
205   std::vector<LinkImpl*> back_route;
206   std::vector<LinkImpl*> route;
207   std::unordered_set<kernel::routing::NetZoneImpl*> netzones;
208
209   XBT_IN("(%s,%s,%g,%g)", src->get_cname(), dst->get_cname(), size, rate);
210
211   kernel::routing::NetZoneImpl::get_global_route_with_netzones(src->get_netpoint(), dst->get_netpoint(), route,
212                                                                &latency, netzones);
213
214   xbt_assert(not route.empty() || latency > 0,
215              "You're trying to send data from %s to %s but there is no connecting path between these two hosts.",
216              src->get_cname(), dst->get_cname());
217
218   bool failed = std::any_of(route.begin(), route.end(), [](const LinkImpl* link) { return not link->is_on(); });
219
220   if (cfg_crosstraffic) {
221     dst->route_to(src, back_route, nullptr);
222     if (not failed)
223       failed =
224           std::any_of(back_route.begin(), back_route.end(), [](const LinkImpl* link) { return not link->is_on(); });
225   }
226
227   NetworkWifiLink* src_wifi_link = nullptr;
228   NetworkWifiLink* dst_wifi_link = nullptr;
229   if (not route.empty() && route.front()->get_sharing_policy() == s4u::Link::SharingPolicy::WIFI) {
230     src_wifi_link = static_cast<NetworkWifiLink*>(route.front());
231     xbt_assert(src_wifi_link->get_host_rate(src) != -1,
232                "The route from %s to %s begins with the WIFI link %s, but the host %s does not seem attached to that "
233                "WIFI link. Did you call link->set_host_rate()?",
234                src->get_cname(), dst->get_cname(), src_wifi_link->get_cname(), src->get_cname());
235   }
236   if (route.size() > 1 && route.back()->get_sharing_policy() == s4u::Link::SharingPolicy::WIFI) {
237     dst_wifi_link = static_cast<NetworkWifiLink*>(route.back());
238     xbt_assert(dst_wifi_link->get_host_rate(dst) != -1,
239                "The route from %s to %s ends with the WIFI link %s, but the host %s does not seem attached to that "
240                "WIFI link. Did you call link->set_host_rate()?",
241                src->get_cname(), dst->get_cname(), dst_wifi_link->get_cname(), dst->get_cname());
242   }
243   if (route.size() > 2)
244     for (unsigned i = 1; i < route.size() - 1; i++)
245       xbt_assert(route[i]->get_sharing_policy() != s4u::Link::SharingPolicy::WIFI,
246                  "Link '%s' is a WIFI link. It can only be at the beginning or the end of the route from '%s' to '%s', "
247                  "not in between (it is at position %u out of %zu). "
248                  "Did you declare an access_point in your WIFI zones?",
249                  route[i]->get_cname(), src->get_cname(), dst->get_cname(), i + 1, route.size());
250
251   NetworkCm02Action* action;
252   if (src_wifi_link == nullptr && dst_wifi_link == nullptr)
253     action = new NetworkCm02Action(this, *src, *dst, size, failed);
254   else
255     action = new NetworkWifiAction(this, *src, *dst, size, failed, src_wifi_link, dst_wifi_link);
256   action->sharing_penalty_ = latency;
257   action->latency_         = latency;
258   action->set_user_bound(rate);
259
260   if (is_update_lazy()) {
261     action->set_last_update();
262   }
263
264   if (sg_weight_S_parameter > 0) {
265     action->sharing_penalty_ =
266         std::accumulate(route.begin(), route.end(), action->sharing_penalty_, [](double total, LinkImpl* const& link) {
267           return total + sg_weight_S_parameter / link->get_bandwidth();
268         });
269   }
270
271   double bandwidth_bound = route.empty() ? -1.0 : get_bandwidth_factor(size) * route.front()->get_bandwidth();
272
273   for (auto const& link : route)
274     bandwidth_bound = std::min(bandwidth_bound, get_bandwidth_factor(size) * link->get_bandwidth());
275
276   action->lat_current_ = action->latency_;
277   action->latency_ *= get_latency_factor(size);
278   action->set_user_bound(get_bandwidth_constraint(action->get_user_bound(), bandwidth_bound, size));
279
280   size_t constraints_per_variable = route.size();
281   constraints_per_variable += back_route.size();
282
283   if (action->latency_ > 0) {
284     action->set_variable(get_maxmin_system()->variable_new(action, 0.0, -1.0, constraints_per_variable));
285     if (is_update_lazy()) {
286       // add to the heap the event when the latency is paid
287       double date = action->latency_ + action->get_last_update();
288
289       ActionHeap::Type type = route.empty() ? ActionHeap::Type::normal : ActionHeap::Type::latency;
290
291       XBT_DEBUG("Added action (%p) one latency event at date %f", action, date);
292       get_action_heap().insert(action, date, type);
293     }
294   } else
295     action->set_variable(get_maxmin_system()->variable_new(action, 1.0, -1.0, constraints_per_variable));
296
297   if (action->get_user_bound() < 0) {
298     get_maxmin_system()->update_variable_bound(
299         action->get_variable(), (action->lat_current_ > 0) ? cfg_tcp_gamma / (2.0 * action->lat_current_) : -1.0);
300   } else {
301     get_maxmin_system()->update_variable_bound(
302         action->get_variable(), (action->lat_current_ > 0)
303                                     ? std::min(action->get_user_bound(), cfg_tcp_gamma / (2.0 * action->lat_current_))
304                                     : action->get_user_bound());
305   }
306
307   if (src_wifi_link != nullptr)
308     get_maxmin_system()->expand(src_wifi_link->get_constraint(), action->get_variable(),
309                                 1.0 / src_wifi_link->get_host_rate(src));
310   if (dst_wifi_link != nullptr)
311     get_maxmin_system()->expand(dst_wifi_link->get_constraint(), action->get_variable(),
312                                 1.0 / dst_wifi_link->get_host_rate(dst));
313
314   for (auto const* link : route) {
315     // WIFI links are handled manually just above, so skip them now
316     if (link->get_sharing_policy() == s4u::Link::SharingPolicy::WIFI) {
317       xbt_assert(link == src_wifi_link || link == dst_wifi_link,
318                  "Wifi links can only occur at the beginning of the route (meaning that it's attached to the src) or "
319                  "at its end (meaning that it's attached to the dst");
320     } else {
321       get_maxmin_system()->expand(link->get_constraint(), action->get_variable(), 1.0);
322     }
323   }
324
325   if (cfg_crosstraffic) {
326     XBT_DEBUG("Crosstraffic active: adding backward flow using 5%% of the available bandwidth");
327     if (dst_wifi_link != nullptr)
328       get_maxmin_system()->expand(dst_wifi_link->get_constraint(), action->get_variable(),
329                                   .05 / dst_wifi_link->get_host_rate(dst));
330     if (src_wifi_link != nullptr)
331       get_maxmin_system()->expand(src_wifi_link->get_constraint(), action->get_variable(),
332                                   .05 / src_wifi_link->get_host_rate(src));
333     for (auto const* link : back_route)
334       if (link->get_sharing_policy() != s4u::Link::SharingPolicy::WIFI)
335         get_maxmin_system()->expand(link->get_constraint(), action->get_variable(), .05);
336     // Change concurrency_share here, if you want that cross-traffic is included in the SURF concurrency
337     // (You would also have to change simgrid::kernel::lmm::Element::get_concurrency())
338     // action->getVariable()->set_concurrency_share(2)
339   }
340   XBT_OUT();
341
342   simgrid::s4u::Link::on_communicate(*action);
343   return action;
344 }
345
346 /************
347  * Resource *
348  ************/
349 NetworkCm02Link::NetworkCm02Link(const std::string& name, double bandwidth, kernel::lmm::System* system)
350     : LinkImpl(name)
351 {
352   bandwidth_.scale = 1.0;
353   bandwidth_.peak  = bandwidth;
354   this->set_constraint(system->constraint_new(this, sg_bandwidth_factor * bandwidth));
355 }
356
357 void NetworkCm02Link::apply_event(kernel::profile::Event* triggered, double value)
358 {
359   /* Find out which of my iterators was triggered, and react accordingly */
360   if (triggered == bandwidth_.event) {
361     set_bandwidth(value);
362     tmgr_trace_event_unref(&bandwidth_.event);
363
364   } else if (triggered == latency_.event) {
365     set_latency(value);
366     tmgr_trace_event_unref(&latency_.event);
367
368   } else if (triggered == state_event_) {
369     if (value > 0)
370       turn_on();
371     else
372       turn_off();
373     tmgr_trace_event_unref(&state_event_);
374   } else {
375     xbt_die("Unknown event!\n");
376   }
377
378   XBT_DEBUG("There was a resource state event, need to update actions related to the constraint (%p)",
379             get_constraint());
380 }
381
382 void NetworkCm02Link::set_bandwidth(double value)
383 {
384   bandwidth_.peak = value;
385
386   get_model()->get_maxmin_system()->update_constraint_bound(get_constraint(),
387                                                             sg_bandwidth_factor * (bandwidth_.peak * bandwidth_.scale));
388
389   LinkImpl::on_bandwidth_change();
390
391   if (sg_weight_S_parameter > 0) {
392     double delta = sg_weight_S_parameter / value - sg_weight_S_parameter / (bandwidth_.peak * bandwidth_.scale);
393
394     const kernel::lmm::Element* elem     = nullptr;
395     const kernel::lmm::Element* nextelem = nullptr;
396     int numelem                          = 0;
397     while (const auto* var = get_constraint()->get_variable_safe(&elem, &nextelem, &numelem)) {
398       auto* action = static_cast<NetworkCm02Action*>(var->get_id());
399       action->sharing_penalty_ += delta;
400       if (not action->is_suspended())
401         get_model()->get_maxmin_system()->update_variable_penalty(action->get_variable(), action->sharing_penalty_);
402     }
403   }
404 }
405
406 LinkImpl* NetworkCm02Link::set_latency(double value)
407 {
408   latency_check(value);
409
410   double delta                         = value - latency_.peak;
411   const kernel::lmm::Element* elem     = nullptr;
412   const kernel::lmm::Element* nextelem = nullptr;
413   int numelem                          = 0;
414
415   latency_.scale = 1.0;
416   latency_.peak  = value;
417
418   while (const auto* var = get_constraint()->get_variable_safe(&elem, &nextelem, &numelem)) {
419     auto* action = static_cast<NetworkCm02Action*>(var->get_id());
420     action->lat_current_ += delta;
421     action->sharing_penalty_ += delta;
422     if (action->get_user_bound() < 0)
423       get_model()->get_maxmin_system()->update_variable_bound(action->get_variable(), NetworkModel::cfg_tcp_gamma /
424                                                                                           (2.0 * action->lat_current_));
425     else {
426       get_model()->get_maxmin_system()->update_variable_bound(
427           action->get_variable(),
428           std::min(action->get_user_bound(), NetworkModel::cfg_tcp_gamma / (2.0 * action->lat_current_)));
429
430       if (action->get_user_bound() < NetworkModel::cfg_tcp_gamma / (2.0 * action->lat_current_)) {
431         XBT_INFO("Flow is limited BYBANDWIDTH");
432       } else {
433         XBT_INFO("Flow is limited BYLATENCY, latency of flow is %f", action->lat_current_);
434       }
435     }
436     if (not action->is_suspended())
437       get_model()->get_maxmin_system()->update_variable_penalty(action->get_variable(), action->sharing_penalty_);
438   }
439   return this;
440 }
441
442 /**********
443  * Action *
444  **********/
445
446 void NetworkCm02Action::update_remains_lazy(double now)
447 {
448   if (not is_running())
449     return;
450
451   double delta = now - get_last_update();
452
453   if (get_remains_no_update() > 0) {
454     XBT_DEBUG("Updating action(%p): remains was %f, last_update was: %f", this, get_remains_no_update(),
455               get_last_update());
456     update_remains(get_last_value() * delta);
457
458     XBT_DEBUG("Updating action(%p): remains is now %f", this, get_remains_no_update());
459   }
460
461   update_max_duration(delta);
462
463   if ((get_remains_no_update() <= 0 && (get_variable()->get_penalty() > 0)) ||
464       ((get_max_duration() != NO_MAX_DURATION) && (get_max_duration() <= 0))) {
465     finish(Action::State::FINISHED);
466     get_model()->get_action_heap().remove(this);
467   }
468
469   set_last_update();
470   set_last_value(get_variable()->get_value());
471 }
472
473 } // namespace resource
474 } // namespace kernel
475 } // namespace simgrid