Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Activity refactoring
[simgrid.git] / include / simgrid / s4u / Activity.hpp
1 /* Copyright (c) 2006-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 #ifndef SIMGRID_S4U_ACTIVITY_HPP
7 #define SIMGRID_S4U_ACTIVITY_HPP
8
9 #include <xbt/asserts.h>
10 #include <algorithm>
11 #include <atomic>
12 #include <set>
13 #include <simgrid/forward.h>
14 #include <stdexcept>
15 #include <string>
16 #include <vector>
17 #include <xbt/signal.hpp>
18 #include <xbt/utility.hpp>
19
20 XBT_LOG_EXTERNAL_CATEGORY(s4u_activity);
21
22 namespace simgrid {
23 namespace s4u {
24
25 /** @brief Activities
26  *
27  * This class is the ancestor of every activities that an actor can undertake.
28  * That is, activities are all the things that do take time to the actor in the simulated world.
29  */
30 class XBT_PUBLIC Activity {
31   friend Comm;
32   friend Exec;
33   friend Io;
34
35 public:
36   // enum class State { ... }
37   XBT_DECLARE_ENUM_CLASS(State, INITED, STARTING, STARTED, FAILED, CANCELED, FINISHED);
38
39   virtual bool is_assigned() const = 0;
40   virtual bool dependencies_solved() const { return dependencies_.empty(); }
41
42 protected:
43   Activity()  = default;
44   virtual ~Activity() = default;
45
46   void release_dependencies()
47   {
48     while (not successors_.empty()) {
49       ActivityPtr b = successors_.back();
50       XBT_CVERB(s4u_activity, "Remove a dependency from '%s' on '%s'", get_cname(), b->get_cname());
51       b->dependencies_.erase(this);
52       if (b->dependencies_solved()) {
53         b->vetoable_start();
54       }
55       successors_.pop_back();
56     }
57   }
58
59   void add_successor(ActivityPtr a)
60   {
61     if(this == a)
62       throw std::invalid_argument("Cannot be its own successor");
63     auto p = std::find_if(successors_.begin(), successors_.end(), [a](ActivityPtr const& i){ return i.get() == a.get(); });
64     if (p != successors_.end())
65       throw std::invalid_argument("Dependency already exists");
66
67     successors_.push_back(a);
68     a->dependencies_.insert({this});
69   }
70
71   void remove_successor(ActivityPtr a)
72   {
73     if(this == a)
74       throw std::invalid_argument("Cannot ask to remove itself from successors list");
75
76     auto p = std::find_if(successors_.begin(), successors_.end(), [a](ActivityPtr const& i){ return i.get() == a.get(); });
77     if (p != successors_.end()){
78       successors_.erase(p);
79       a->dependencies_.erase({this});
80     } else
81       throw std::invalid_argument("Dependency does not exist. Can not be removed.");
82   }
83
84   static std::set<Activity*>* vetoed_activities_;
85
86 public:
87   /*! Signal fired each time that the activity fails to start because of a veto (e.g., unsolved dependency or no
88    * resource assigned) */
89   static xbt::signal<void(Activity&)> on_veto;
90   /*! Signal fired when theactivity completes  (either normally, cancelled or failed) */
91   static xbt::signal<void(Activity&)> on_completion;
92
93   void vetoable_start()
94   {
95     state_ = State::STARTING;
96     if (dependencies_solved() && is_assigned()) {
97       XBT_CVERB(s4u_activity, "'%s' is assigned to a resource and all dependencies are solved. Let's start", get_cname());
98       start();
99     } else {
100       if (vetoed_activities_ != nullptr)
101         vetoed_activities_->insert(this);
102       on_veto(*this);
103     }
104   }
105
106   void complete(Activity::State state)
107   {
108     state_ = state;
109     if (state == State::FINISHED)
110       release_dependencies();
111     on_completion(*this);
112   }
113
114   static std::set<Activity*>* get_vetoed_activities() { return vetoed_activities_; }
115   static void set_vetoed_activities(std::set<Activity*>* whereto) { vetoed_activities_ = whereto; }
116
117 #ifndef DOXYGEN
118   Activity(Activity const&) = delete;
119   Activity& operator=(Activity const&) = delete;
120 #endif
121
122   /** Starts a previously created activity.
123    *
124    * This function is optional: you can call wait() even if you didn't call start()
125    */
126   virtual Activity* start() = 0;
127   /** Blocks the current actor until the activity is terminated */
128   Activity* wait() { return wait_for(-1.0); }
129   /** Blocks the current actor until the activity is terminated, or until the timeout is elapsed\n
130    *  Raises: timeout exception.*/
131   Activity* wait_for(double timeout);
132   /** Blocks the current actor until the activity is terminated, or until the time limit is reached\n
133    * Raises: timeout exception. */
134   void wait_until(double time_limit);
135
136   /** Cancel that activity */
137   Activity* cancel();
138   /** Retrieve the current state of the activity */
139   Activity::State get_state() const { return state_; }
140   /** Return a string representation of the activity's state (one of INITED, STARTING, STARTED, CANCELED, FINISHED) */
141   const char* get_state_str() const;
142   void set_state(Activity::State state) { state_ = state; }
143   /** Tests whether the given activity is terminated yet. */
144   virtual bool test();
145
146   /** Blocks the progression of this activity until it gets resumed */
147   virtual Activity* suspend();
148   /** Unblock the progression of this activity if it was suspended previously */
149   virtual Activity* resume();
150   /** Whether or not the progression of this activity is blocked */
151   bool is_suspended() const { return suspended_; }
152
153   virtual const char* get_cname() const       = 0;
154   virtual const std::string& get_name() const = 0;
155
156   /** Get the remaining amount of work that this Activity entails. When it's 0, it's done. */
157   virtual double get_remaining() const;
158   /** Set the [remaining] amount of work that this Activity will entail
159    *
160    * It is forbidden to change the amount of work once the Activity is started */
161   Activity* set_remaining(double remains);
162
163   /** Returns the internal implementation of this Activity */
164   kernel::activity::ActivityImpl* get_impl() const { return pimpl_.get(); }
165
166 #ifndef DOXYGEN
167   friend void intrusive_ptr_release(Activity* a)
168   {
169     if (a->refcount_.fetch_sub(1, std::memory_order_release) == 1) {
170       std::atomic_thread_fence(std::memory_order_acquire);
171       delete a;
172     }
173   }
174   friend void intrusive_ptr_add_ref(Activity* a) { a->refcount_.fetch_add(1, std::memory_order_relaxed); }
175 #endif
176   Activity* add_ref()
177   {
178     intrusive_ptr_add_ref(this);
179     return this;
180   }
181   void unref() { intrusive_ptr_release(this); }
182
183 private:
184   kernel::activity::ActivityImplPtr pimpl_ = nullptr;
185   Activity::State state_                   = Activity::State::INITED;
186   double remains_                          = 0;
187   bool suspended_                          = false;
188   std::vector<ActivityPtr> successors_;
189   std::set<ActivityPtr> dependencies_;
190   std::atomic_int_fast32_t refcount_{0};
191 };
192
193 template <class AnyActivity> class Activity_T : public Activity {
194   std::string name_             = "unnamed";
195   std::string tracing_category_ = "";
196   void* user_data_              = nullptr;
197
198 public:
199   AnyActivity* add_successor(ActivityPtr a)
200   {
201     Activity::add_successor(a);
202     return static_cast<AnyActivity*>(this);
203   }
204   AnyActivity* remove_successor(ActivityPtr a)
205   {
206     Activity::remove_successor(a);
207     return static_cast<AnyActivity*>(this);
208   }
209   AnyActivity* set_name(const std::string& name)
210   {
211     xbt_assert(get_state() == State::INITED, "Cannot change the name of an activity after its start");
212     name_ = name;
213     return static_cast<AnyActivity*>(this);
214   }
215   const std::string& get_name() const override { return name_; }
216   const char* get_cname() const override { return name_.c_str(); }
217
218   AnyActivity* set_tracing_category(const std::string& category)
219   {
220     xbt_assert(get_state() == State::INITED, "Cannot change the tracing category of an activity after its start");
221     tracing_category_ = category;
222     return static_cast<AnyActivity*>(this);
223   }
224   const std::string& get_tracing_category() const { return tracing_category_; }
225
226   AnyActivity* set_user_data(void* data)
227   {
228     user_data_ = data;
229     return static_cast<AnyActivity*>(this);
230   }
231
232   void* get_user_data() const { return user_data_; }
233
234   AnyActivity* vetoable_start()
235   {
236     Activity::vetoable_start();
237     return static_cast<AnyActivity*>(this);
238   }
239
240   AnyActivity* cancel() { return static_cast<AnyActivity*>(Activity::cancel()); }
241   AnyActivity* wait() { return wait_for(-1.0); }
242   virtual AnyActivity* wait_for(double timeout) { return static_cast<AnyActivity*>(Activity::wait_for(timeout)); }
243
244 #ifndef DOXYGEN
245   /* The refcounting is done in the ancestor class, Activity, but we want each of the classes benefiting of the CRTP
246    * (Exec, Comm, etc) to have smart pointers too, so we define these methods here, that forward the ptr_release and
247    * add_ref to the Activity class. Hopefully, the "inline" helps to not hinder the perf here.
248    */
249   friend void inline intrusive_ptr_release(AnyActivity* a) { intrusive_ptr_release(static_cast<Activity*>(a)); }
250   friend void inline intrusive_ptr_add_ref(AnyActivity* a) { intrusive_ptr_add_ref(static_cast<Activity*>(a)); }
251 #endif
252 };
253
254 } // namespace s4u
255 } // namespace simgrid
256
257 #endif /* SIMGRID_S4U_ACTIVITY_HPP */