Logo AND Algorithmique Numérique Distribuée

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