Logo AND Algorithmique Numérique Distribuée

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