Logo AND Algorithmique Numérique Distribuée

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