Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
use an enum class for surf::Action type
[simgrid.git] / src / surf / surf_interface.hpp
1 /* Copyright (c) 2004-2017. 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 #ifndef SURF_MODEL_H_
7 #define SURF_MODEL_H_
8
9 #include "xbt/signal.hpp"
10 #include "xbt/utility.hpp"
11
12 #include "src/surf/surf_private.hpp"
13 #include "surf/surf.hpp"
14 #include "xbt/str.h"
15
16 #include <boost/heap/pairing_heap.hpp>
17 #include <boost/intrusive/list.hpp>
18 #include <boost/optional.hpp>
19 #include <cmath>
20 #include <set>
21 #include <string>
22 #include <unordered_map>
23
24 #define NO_MAX_DURATION -1.0
25
26 /*********
27  * Utils *
28  *********/
29
30 /* user-visible parameters */
31 XBT_PUBLIC_DATA(double) sg_maxmin_precision;
32 XBT_PUBLIC_DATA(double) sg_surf_precision;
33 XBT_PUBLIC_DATA(int) sg_concurrency_limit;
34
35 extern XBT_PRIVATE double sg_tcp_gamma;
36 extern XBT_PRIVATE double sg_latency_factor;
37 extern XBT_PRIVATE double sg_bandwidth_factor;
38 extern XBT_PRIVATE double sg_weight_S_parameter;
39 extern XBT_PRIVATE int sg_network_crosstraffic;
40 extern XBT_PRIVATE std::vector<std::string> surf_path;
41 extern XBT_PRIVATE std::unordered_map<std::string, tmgr_trace_t> traces_set_list;
42 extern XBT_PRIVATE std::set<std::string> watched_hosts;
43
44 static inline void double_update(double* variable, double value, double precision)
45 {
46   // printf("Updating %g -= %g +- %g\n",*variable,value,precision);
47   // xbt_assert(value==0  || value>precision);
48   // Check that precision is higher than the machine-dependent size of the mantissa. If not, brutal rounding  may
49   // happen, and the precision mechanism is not active...
50   // xbt_assert(*variable< (2<<DBL_MANT_DIG)*precision && FLT_RADIX==2);
51   *variable -= value;
52   if (*variable < precision)
53     *variable = 0.0;
54 }
55
56 static inline int double_positive(double value, double precision)
57 {
58   return (value > precision);
59 }
60
61 static inline int double_equals(double value1, double value2, double precision)
62 {
63   return (fabs(value1 - value2) < precision);
64 }
65
66 extern "C" {
67 XBT_PUBLIC(double) surf_get_clock();
68 }
69 /** \ingroup SURF_simulation
70  *  \brief List of hosts that have just restarted and whose autorestart process should be restarted.
71  */
72 XBT_PUBLIC_DATA(std::vector<sg_host_t>) host_that_restart;
73
74 namespace simgrid {
75 namespace surf {
76
77 extern XBT_PRIVATE simgrid::xbt::signal<void()> surfExitCallbacks;
78 }
79 }
80
81 int XBT_PRIVATE __surf_is_absolute_file_path(const char *file_path);
82
83 /**********
84  * Action *
85  **********/
86
87 /** \ingroup SURF_models
88  *  \brief List of initialized models
89  */
90 XBT_PUBLIC_DATA(std::vector<surf_model_t>*) all_existing_models;
91
92 namespace simgrid {
93 namespace surf {
94
95 typedef std::pair<double, simgrid::surf::Action*> heap_element_type;
96 typedef boost::heap::pairing_heap<heap_element_type, boost::heap::constant_time_size<false>, boost::heap::stable<true>,
97                                   boost::heap::compare<simgrid::xbt::HeapComparator<heap_element_type>>>
98     heap_type;
99
100 /** @ingroup SURF_interface
101  * @brief SURF action interface class
102  * @details An action is an event generated by a resource (e.g.: a communication for the network)
103  */
104 XBT_PUBLIC_CLASS Action {
105 public:
106   boost::intrusive::list_member_hook<> action_hook;
107   boost::intrusive::list_member_hook<> action_lmm_hook;
108   typedef boost::intrusive::member_hook<
109     Action, boost::intrusive::list_member_hook<>, &Action::action_hook> ActionOptions;
110   typedef boost::intrusive::list<Action, ActionOptions> ActionList;
111
112   enum class State {
113     ready = 0,        /**< Ready        */
114     running,          /**< Running      */
115     failed,           /**< Task Failure */
116     done,             /**< Completed    */
117     to_free,          /**< Action to free in next cleanup */
118     not_in_the_system /**< Not in the system anymore. Why did you ask ? */
119   };
120
121   enum class SuspendStates {
122     not_suspended = 0, /**< Action currently not suspended **/
123     suspended,
124     sleeping
125   };
126
127   enum class Type { LATENCY = 100, MAX_DURATION, NORMAL, NOTSET };
128
129   /**
130    * @brief Action constructor
131    *
132    * @param model The Model associated to this Action
133    * @param cost The cost of the Action
134    * @param failed If the action is impossible (e.g.: execute something on a switched off host)
135    */
136   Action(simgrid::surf::Model* model, double cost, bool failed);
137
138   /**
139    * @brief Action constructor
140    *
141    * @param model The Model associated to this Action
142    * @param cost The cost of the Action
143    * @param failed If the action is impossible (e.g.: execute something on a switched off host)
144    * @param var The lmm variable associated to this Action if it is part of a LMM component
145    */
146   Action(simgrid::surf::Model* model, double cost, bool failed, lmm_variable_t var);
147
148   /** @brief Destructor */
149   virtual ~Action();
150
151   /**
152    * @brief Mark that the action is now finished
153    *
154    * @param state the new [state](\ref simgrid::surf::Action::State) of the current Action
155    */
156   void finish(Action::State state);
157
158   /** @brief Get the [state](\ref simgrid::surf::Action::State) of the current Action */
159   Action::State getState() const; /**< get the state*/
160   /** @brief Set the [state](\ref simgrid::surf::Action::State) of the current Action */
161   virtual void setState(Action::State state);
162
163   /** @brief Get the bound of the current Action */
164   double getBound() const;
165   /** @brief Set the bound of the current Action */
166   void setBound(double bound);
167
168   /** @brief Get the start time of the current action */
169   double getStartTime() const { return start_; }
170   /** @brief Get the finish time of the current action */
171   double getFinishTime() const { return finishTime_; }
172
173   /** @brief Get the user data associated to the current action */
174   void* getData() const { return data_; }
175   /** @brief Set the user data associated to the current action */
176   void setData(void* data) { data_ = data; }
177
178   /** @brief Get the cost of the current action */
179   double getCost() const { return cost_; }
180   /** @brief Set the cost of the current action */
181   void setCost(double cost) {cost_ = cost;}
182
183   /** @brief Update the maximum duration of the current action
184    *  @param delta Amount to remove from the MaxDuration */
185   void updateMaxDuration(double delta) {double_update(&maxDuration_, delta,sg_surf_precision);}
186
187   /** @brief Update the remaining time of the current action
188    *  @param delta Amount to remove from the remaining time */
189   void updateRemains(double delta) {double_update(&remains_, delta, sg_maxmin_precision*sg_surf_precision);}
190
191   /** @brief Set the remaining time of the current action */
192   void setRemains(double value) {remains_ = value;}
193   /** @brief Get the remaining time of the current action after updating the resource */
194   virtual double getRemains();
195   /** @brief Get the remaining time of the current action without updating the resource */
196   double getRemainsNoUpdate() const { return remains_; }
197
198   /** @brief Set the finish time of the current action */
199   void setFinishTime(double value) {finishTime_ = value;}
200
201   /**@brief Add a reference to the current action (refcounting) */
202   void ref();
203   /** @brief Unref that action (and destroy it if refcount reaches 0)
204    *  @return true if the action was destroyed and false if someone still has references on it
205    */
206   virtual int unref();
207
208   /** @brief Cancel the current Action if running */
209   virtual void cancel();
210
211   /** @brief Suspend the current Action */
212   virtual void suspend();
213
214   /** @brief Resume the current Action */
215   virtual void resume();
216
217   /** @brief Returns true if the current action is running */
218   virtual bool isSuspended();
219
220   /** @brief Get the maximum duration of the current action */
221   double getMaxDuration() const { return maxDuration_; }
222   /** @brief Set the maximum duration of the current Action */
223   virtual void setMaxDuration(double duration);
224
225   /** @brief Get the tracing category associated to the current action */
226   char* getCategory() const { return category_; }
227   /** @brief Set the tracing category of the current Action */
228   void setCategory(const char *category);
229
230   /** @brief Get the priority of the current Action */
231   double getPriority() const { return sharingWeight_; };
232   /** @brief Set the priority of the current Action */
233   virtual void setSharingWeight(double priority);
234   void setSharingWeightNoUpdate(double weight) { sharingWeight_ = weight; }
235
236   /** @brief Get the state set in which the action is */
237   ActionList* getStateSet() const { return stateSet_; };
238
239   simgrid::surf::Model* getModel() const { return model_; }
240
241 protected:
242   ActionList* stateSet_;
243   int    refcount_ = 1;
244
245 private:
246   double sharingWeight_ = 1.0;             /**< priority (1.0 by default) */
247   double maxDuration_ = NO_MAX_DURATION; /*< max_duration (may fluctuate until the task is completed) */
248   double remains_;                       /**< How much of that cost remains to be done in the currently running task */
249   double start_; /**< start time  */
250   char *category_ = nullptr;            /**< tracing category for categorized resource utilization monitoring */
251   double finishTime_ =
252       -1; /**< finish time : this is modified during the run and fluctuates until the task is completed */
253
254   double    cost_;
255   simgrid::surf::Model *model_;
256   void *data_ = nullptr; /**< for your convenience */
257
258   /* LMM */
259   double lastUpdate_                                  = 0;
260   double lastValue_                                   = 0;
261   lmm_variable_t variable_                            = nullptr;
262   Action::Type hat_                                   = Action::Type::NOTSET;
263   boost::optional<heap_type::handle_type> heapHandle_ = boost::none;
264
265 public:
266   virtual void updateRemainingLazy(double now) { THROW_IMPOSSIBLE; };
267   void heapInsert(heap_type & heap, double key, Action::Type hat);
268   void heapRemove(heap_type& heap);
269   void heapUpdate(heap_type & heap, double key, Action::Type hat);
270   void clearHeapHandle() { heapHandle_ = boost::none; }
271   lmm_variable_t getVariable() const { return variable_; }
272   void setVariable(lmm_variable_t var) { variable_ = var; }
273   double getLastUpdate() const { return lastUpdate_; }
274   void refreshLastUpdate() {lastUpdate_ = surf_get_clock();}
275   double getLastValue() const { return lastValue_; }
276   void setLastValue(double val) { lastValue_ = val; }
277   Action::Type getHat() const { return hat_; }
278   bool is_linked() const { return action_lmm_hook.is_linked(); }
279 protected:
280   Action::SuspendStates suspended_ = Action::SuspendStates::not_suspended;
281 };
282
283 typedef Action::ActionList ActionList;
284
285 typedef boost::intrusive::member_hook<
286   Action, boost::intrusive::list_member_hook<>, &Action::action_lmm_hook> ActionLmmOptions;
287 typedef boost::intrusive::list<Action, ActionLmmOptions> ActionLmmList;
288 typedef ActionLmmList* ActionLmmListPtr;
289
290 /*********
291  * Model *
292  *********/
293
294 /** @ingroup SURF_interface
295  * @brief SURF model interface class
296  * @details A model is an object which handle the interactions between its Resources and its Actions
297  */
298 XBT_PUBLIC_CLASS Model {
299 public:
300   Model();
301   virtual ~Model();
302
303   /** @brief Get the set of [actions](@ref Action) in *ready* state */
304   virtual ActionList* getReadyActionSet() const { return readyActionSet_; }
305
306   /** @brief Get the set of [actions](@ref Action) in *running* state */
307   virtual ActionList* getRunningActionSet() const { return runningActionSet_; }
308
309   /** @brief Get the set of [actions](@ref Action) in *failed* state */
310   virtual ActionList* getFailedActionSet() const { return failedActionSet_; }
311
312   /** @brief Get the set of [actions](@ref Action) in *done* state */
313   virtual ActionList* getDoneActionSet() const { return doneActionSet_; }
314
315   /** @brief Get the set of modified [actions](@ref Action) */
316   virtual ActionLmmListPtr getModifiedSet() const { return modifiedSet_; }
317
318   /** @brief Get the maxmin system of the current Model */
319   lmm_system_t getMaxminSystem() const { return maxminSystem_; }
320
321   /**
322    * @brief Get the update mechanism of the current Model
323    * @see e_UM_t
324    */
325   e_UM_t getUpdateMechanism() const { return updateMechanism_; }
326   void setUpdateMechanism(e_UM_t mechanism) { updateMechanism_ = mechanism; }
327
328   /** @brief Get Action heap */
329   heap_type& getActionHeap() { return actionHeap_; }
330
331   double actionHeapTopDate() const { return actionHeap_.top().first; }
332   Action* actionHeapPop();
333   bool actionHeapIsEmpty() const { return actionHeap_.empty(); }
334
335   /**
336    * @brief Share the resources between the actions
337    *
338    * @param now The current time of the simulation
339    * @return The delta of time till the next action will finish
340    */
341   virtual double nextOccuringEvent(double now);
342   virtual double nextOccuringEventLazy(double now);
343   virtual double nextOccuringEventFull(double now);
344
345   /**
346    * @brief Update action to the current time
347    *
348    * @param now The current time of the simulation
349    * @param delta The delta of time since the last update
350    */
351   virtual void updateActionsState(double now, double delta);
352   virtual void updateActionsStateLazy(double now, double delta);
353   virtual void updateActionsStateFull(double now, double delta);
354
355   /** @brief Returns whether this model have an idempotent shareResource()
356    *
357    * The only model that is not is NS3: computing the next timestamp moves the model up to that point,
358    * so we need to call it only when the next timestamp of other sources is computed.
359    */
360   virtual bool nextOccuringEventIsIdempotent() { return true;}
361
362 protected:
363   ActionLmmListPtr modifiedSet_;
364   lmm_system_t maxminSystem_ = nullptr;
365   bool selectiveUpdate_;
366
367 private:
368   e_UM_t updateMechanism_ = UM_UNDEFINED;
369   ActionList* readyActionSet_; /**< Actions in state SURF_ACTION_READY */
370   ActionList* runningActionSet_; /**< Actions in state SURF_ACTION_RUNNING */
371   ActionList* failedActionSet_; /**< Actions in state SURF_ACTION_FAILED */
372   ActionList* doneActionSet_; /**< Actions in state SURF_ACTION_DONE */
373   heap_type actionHeap_;
374 };
375
376 }
377 }
378
379 /************
380  * Resource *
381  ************/
382
383 /** @ingroup SURF_interface
384  * @brief Resource which have a metric handled by a maxmin system
385  */
386 struct s_surf_metric_t {
387   double peak;              /**< The peak of the metric, ie its max value */
388   double scale;             /**< Current availability of the metric according to the traces, in [0,1] */
389   tmgr_trace_event_t event; /**< The associated trace event associated to the metric */
390 };
391
392 namespace simgrid {
393 namespace surf {
394
395 /** @ingroup SURF_interface
396  * @brief SURF resource interface class
397  * @details This is the ancestor class of every resources in SimGrid, such as links, CPU or storage
398  */
399 XBT_PUBLIC_CLASS Resource {
400 public:
401   /**
402    * @brief Constructor of LMM Resources
403    *
404    * @param model Model associated to this Resource
405    * @param name The name of the Resource
406    * @param constraint The lmm constraint associated to this Resource if it is part of a LMM component
407    */
408   Resource(Model * model, const std::string& name, lmm_constraint_t constraint);
409
410   virtual ~Resource();
411
412   /** @brief Get the Model of the current Resource */
413   Model* model() const;
414
415   /** @brief Get the name of the current Resource */
416   const std::string& getName() const;
417   /** @brief Get the name of the current Resource */
418   const char* getCname() const;
419
420   bool operator==(const Resource &other) const;
421
422   /**
423    * @brief Apply an event of external load event to that resource
424    *
425    * @param event What happened
426    * @param value [TODO]
427    */
428   virtual void apply_event(tmgr_trace_event_t event, double value) = 0;
429
430   /** @brief Check if the current Resource is used (if it currently serves an action) */
431   virtual bool isUsed()=0;
432
433   /** @brief returns the current load (in flops per second, byte per second or similar) */
434   virtual double getLoad();
435
436   /** @brief Check if the current Resource is active */
437   virtual bool isOn() const;
438   /** @brief Check if the current Resource is shut down */
439   virtual bool isOff() const;
440   /** @brief Turn on the current Resource */
441   virtual void turnOn();
442   /** @brief Turn off the current Resource */
443   virtual void turnOff();
444
445 private:
446   std::string name_;
447   Model *model_;
448   bool isOn_ = true;
449
450 public: /* LMM */
451   /** @brief Get the lmm constraint associated to this Resource if it is part of a LMM component (or null if none) */
452   lmm_constraint_t constraint() const;
453
454 protected:
455   const lmm_constraint_t constraint_ = nullptr;
456 };
457
458 }
459 }
460
461 namespace std {
462 template <> class hash<simgrid::surf::Resource> {
463 public:
464   std::size_t operator()(const simgrid::surf::Resource& r) const { return (std::size_t)xbt_str_hash(r.getCname()); }
465 };
466 }
467
468 #endif /* SURF_MODEL_H_ */