Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use the right version for the deprecate macro
[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   virtual void fire_this_completion() const = 0;
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     auto p = std::find_if(successors_.begin(), successors_.end(), [a](ActivityPtr const& i){ return i.get() == a.get(); });
79     if (p != successors_.end())
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 = std::find_if(successors_.begin(), successors_.end(), [a](ActivityPtr const& i){ return i.get() == a.get(); });
92     if (p != successors_.end()){
93       successors_.erase(p);
94       a->dependencies_.erase({this});
95     } else
96       throw std::invalid_argument("Dependency does not exist. Can not be removed.");
97   }
98
99   static std::set<Activity*>* vetoed_activities_;
100
101   /** Set the [remaining] amount of work that this Activity will entail
102    *
103    * It is forbidden to change the amount of work once the Activity is started */
104   Activity* set_remaining(double remains);
105
106 private:
107   static xbt::signal<void(Activity&)> on_veto;
108   static xbt::signal<void(Activity const&)> on_suspend;
109   static xbt::signal<void(Activity const&)> on_resume;
110
111 public:
112   /*! Add a callback fired each time that the activity fails to start because of a veto (e.g., unsolved dependency or no
113    * resource assigned) */
114   static void on_veto_cb(const std::function<void(Activity&)>& cb) { on_veto.connect(cb); }
115   /*! Add a callback fired when the activity is suspended */
116   static void on_suspend_cb(const std::function<void(Activity const&)>& cb)
117   {
118     on_suspend.connect(cb);
119   }
120   /*! Add a callback fired when the activity is resumed after being suspended */
121   static void on_resume_cb(const std::function<void(Activity const&)>& cb)
122   {
123     on_resume.connect(cb);
124   }
125
126   XBT_ATTRIB_DEPRECATED_v337("Please use on_suspend_cb() instead") static void on_suspended_cb(
127       const std::function<void(Activity const&)>& cb)
128   {
129     on_suspend.connect(cb);
130   }
131   XBT_ATTRIB_DEPRECATED_v337("Please use on_resume_cb() instead") static void on_resumed_cb(
132       const std::function<void(Activity const&)>& cb)
133   {
134     on_resume.connect(cb);
135   }
136
137   XBT_ATTRIB_DEPRECATED_v334("All start() are vetoable now. Please use start() ") void vetoable_start()
138   {
139     start();
140   }
141   void start()
142   {
143     state_ = State::STARTING;
144     if (dependencies_solved() && is_assigned()) {
145       XBT_CVERB(s4u_activity, "'%s' is assigned to a resource and all dependencies are solved. Let's start", get_cname());
146       do_start();
147     } else {
148       if (vetoed_activities_ != nullptr)
149         vetoed_activities_->insert(this);
150       on_veto(*this);
151     }
152   }
153
154   void complete(Activity::State state)
155   {
156     // Ensure that the current activity remains alive until the end of the function, even if its last reference is
157     // released by the on_completion() callbacks.
158     ActivityPtr keepalive(this);
159     state_ = state;
160     fire_this_completion();
161     if (state == State::FINISHED)
162       release_dependencies();
163   }
164
165   static std::set<Activity*>* get_vetoed_activities() { return vetoed_activities_; }
166   static void set_vetoed_activities(std::set<Activity*>* whereto) { vetoed_activities_ = whereto; }
167
168 #ifndef DOXYGEN
169   Activity(Activity const&) = delete;
170   Activity& operator=(Activity const&) = delete;
171 #endif
172
173   /** Starts a previously created activity.
174    *
175    * This function is optional: you can call wait() even if you didn't call start()
176    */
177   virtual Activity* do_start() = 0;
178   /** Tests whether the given activity is terminated yet. */
179   virtual bool test();
180   /*! take a vector s4u::ActivityPtr and return the rank of the first finished one (or -1 if none is done). */
181   static ssize_t test_any(const std::vector<ActivityPtr>& activities);
182
183   /** Blocks the current actor until the activity is terminated */
184   Activity* wait() { return wait_for(-1.0); }
185   /** Blocks the current actor until the activity is terminated, or until the timeout is elapsed\n
186    *  Raises: timeout exception.*/
187   Activity* wait_for(double timeout);
188   /** Blocks the current actor until the activity is terminated, or until the time limit is reached\n
189    * Raises: timeout exception. */
190   void wait_until(double time_limit);
191   /*! take a vector of s4u::ActivityPtr and return when one of them is finished.
192    * The return value is the rank of the first finished ActivityPtr. */
193   static ssize_t wait_any(const std::vector<ActivityPtr>& activities) { return wait_any_for(activities, -1); }
194   /*! Same as wait_any, but with a timeout. If the timeout occurs, parameter last is returned.*/
195   static ssize_t wait_any_for(const std::vector<ActivityPtr>& activities, double timeout);
196
197   /** Cancel that activity */
198   Activity* cancel();
199   /** Retrieve the current state of the activity */
200   Activity::State get_state() const { return state_; }
201   /** Return a string representation of the activity's state (one of INITED, STARTING, STARTED, CANCELED, FINISHED) */
202   const char* get_state_str() const;
203   void set_state(Activity::State state) { state_ = state; }
204
205   /** Blocks the progression of this activity until it gets resumed */
206   virtual Activity* suspend();
207   /** Unblock the progression of this activity if it was suspended previously */
208   virtual Activity* resume();
209   /** Whether or not the progression of this activity is blocked */
210   bool is_suspended() const { return suspended_; }
211
212   virtual const char* get_cname() const       = 0;
213   virtual const std::string& get_name() const = 0;
214
215   /** Get the remaining amount of work that this Activity entails. When it's 0, it's done. */
216   virtual double get_remaining() const;
217
218   double get_start_time() const;
219   double get_finish_time() const;
220   void mark() { marked_ = true; }
221   bool is_marked() const { return marked_; }
222
223   /** Returns the internal implementation of this Activity */
224   kernel::activity::ActivityImpl* get_impl() const { return pimpl_.get(); }
225
226 #ifndef DOXYGEN
227   friend void intrusive_ptr_release(Activity* a)
228   {
229     if (a->refcount_.fetch_sub(1, std::memory_order_release) == 1) {
230       std::atomic_thread_fence(std::memory_order_acquire);
231       delete a;
232     }
233   }
234   friend void intrusive_ptr_add_ref(Activity* a) { a->refcount_.fetch_add(1, std::memory_order_relaxed); }
235 #endif
236   Activity* add_ref()
237   {
238     intrusive_ptr_add_ref(this);
239     return this;
240   }
241   void unref() { intrusive_ptr_release(this); }
242
243 private:
244   kernel::activity::ActivityImplPtr pimpl_ = nullptr;
245   Activity::State state_                   = Activity::State::INITED;
246   double remains_                          = 0;
247   bool suspended_                          = false;
248   bool marked_                             = false;
249   std::vector<ActivityPtr> successors_;
250   std::set<ActivityPtr> dependencies_;
251   std::atomic_int_fast32_t refcount_{0};
252 };
253
254 template <class AnyActivity> class Activity_T : public Activity {
255   std::string name_             = "unnamed";
256   std::string tracing_category_ = "";
257
258 public:
259   inline static xbt::signal<void(AnyActivity const&)> on_completion;
260   /*! Add a callback fired when the activity completes (either normally, cancelled or failed) */
261   static void on_completion_cb(const std::function<void(AnyActivity const&)>& cb) { on_completion.connect(cb); }
262
263   AnyActivity* add_successor(ActivityPtr a)
264   {
265     Activity::add_successor(a);
266     return static_cast<AnyActivity*>(this);
267   }
268   AnyActivity* remove_successor(ActivityPtr a)
269   {
270     Activity::remove_successor(a);
271     return static_cast<AnyActivity*>(this);
272   }
273   AnyActivity* set_name(const std::string& name)
274   {
275     name_ = name;
276     return static_cast<AnyActivity*>(this);
277   }
278   const std::string& get_name() const override { return name_; }
279   const char* get_cname() const override { return name_.c_str(); }
280
281   AnyActivity* set_tracing_category(const std::string& category)
282   {
283     xbt_assert(get_state() == State::INITED || get_state() == State::STARTING,
284                "Cannot change the tracing category of an activity after its start");
285     tracing_category_ = category;
286     return static_cast<AnyActivity*>(this);
287   }
288   const std::string& get_tracing_category() const { return tracing_category_; }
289
290   XBT_ATTRIB_DEPRECATED_v334("Please use Activity::set_data()") AnyActivity* set_user_data(void* data)
291   {
292     set_data(data);
293     return static_cast<AnyActivity*>(this);
294   }
295
296   XBT_ATTRIB_DEPRECATED_v334("Please use Activity::get_data<>()") void* get_user_data() const
297   {
298     return get_data<void>();
299   }
300   XBT_ATTRIB_DEPRECATED_v334("All start() are vetoable now. Please use start() ") AnyActivity* vetoable_start()
301   {
302     return start();
303   }
304   AnyActivity* start()
305   {
306     Activity::start();
307     return static_cast<AnyActivity*>(this);
308   }
309
310   AnyActivity* cancel() { return static_cast<AnyActivity*>(Activity::cancel()); }
311   AnyActivity* wait() { return wait_for(-1.0); }
312   virtual AnyActivity* wait_for(double timeout) {
313     return static_cast<AnyActivity*>(Activity::wait_for(timeout));
314   }
315
316 #ifndef DOXYGEN
317   /* The refcounting is done in the ancestor class, Activity, but we want each of the classes benefiting of the CRTP
318    * (Exec, Comm, etc) to have smart pointers too, so we define these methods here, that forward the ptr_release and
319    * add_ref to the Activity class. Hopefully, the "inline" helps to not hinder the perf here.
320    */
321   friend void inline intrusive_ptr_release(AnyActivity* a) { intrusive_ptr_release(static_cast<Activity*>(a)); }
322   friend void inline intrusive_ptr_add_ref(AnyActivity* a) { intrusive_ptr_add_ref(static_cast<Activity*>(a)); }
323 #endif
324 };
325
326 } // namespace s4u
327 } // namespace simgrid
328
329 #endif /* SIMGRID_S4U_ACTIVITY_HPP */