Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'add_missing_comm_python_bindings' into 'master'
[simgrid.git] / include / simgrid / s4u / Activity.hpp
1 /* Copyright (c) 2006-2022. 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 #endif
43
44 public:
45   // enum class State { ... }
46   XBT_DECLARE_ENUM_CLASS(State, INITED, STARTING, STARTED, FAILED, CANCELED, FINISHED);
47
48   virtual bool is_assigned() const = 0;
49   bool dependencies_solved() const { return dependencies_.empty(); }
50   bool has_no_successor() const { return successors_.empty(); }
51   const std::set<ActivityPtr>& get_dependencies() const { return dependencies_; }
52   const std::vector<ActivityPtr>& get_successors() const { return successors_; }
53
54 protected:
55   Activity()  = default;
56   virtual ~Activity() = default;
57   void destroy();
58
59   void release_dependencies()
60   {
61     while (not successors_.empty()) {
62       ActivityPtr b = successors_.back();
63       XBT_CVERB(s4u_activity, "Remove a dependency from '%s' on '%s'", get_cname(), b->get_cname());
64       b->dependencies_.erase(this);
65       if (b->dependencies_solved()) {
66         b->vetoable_start();
67       }
68       successors_.pop_back();
69     }
70   }
71
72   void add_successor(ActivityPtr a)
73   {
74     if(this == a)
75       throw std::invalid_argument("Cannot be its own successor");
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       throw std::invalid_argument("Dependency already exists");
79
80     successors_.push_back(a);
81     a->dependencies_.insert({this});
82   }
83
84   void remove_successor(ActivityPtr a)
85   {
86     if(this == a)
87       throw std::invalid_argument("Cannot ask to remove itself from successors list");
88
89     auto p = std::find_if(successors_.begin(), successors_.end(), [a](ActivityPtr const& i){ return i.get() == a.get(); });
90     if (p != successors_.end()){
91       successors_.erase(p);
92       a->dependencies_.erase({this});
93     } else
94       throw std::invalid_argument("Dependency does not exist. Can not be removed.");
95   }
96
97   static std::set<Activity*>* vetoed_activities_;
98
99 private:
100   static xbt::signal<void(Activity&)> on_veto;
101   static xbt::signal<void(Activity const&)> on_completion;
102   static xbt::signal<void(Activity const&)> on_suspended;
103   static xbt::signal<void(Activity const&)> on_resumed;
104
105 public:
106   /*! Add a callback fired each time that the activity fails to start because of a veto (e.g., unsolved dependency or no
107    * resource assigned) */
108   static void on_veto_cb(const std::function<void(Activity&)>& cb) { on_veto.connect(cb); }
109   /*! Add a callback fired when the activity completes (either normally, cancelled or failed) */
110   static void on_completion_cb(const std::function<void(Activity const&)>& cb) { on_completion.connect(cb); }
111   /*! Add a callback fired when the activity is suspended */
112   static void on_suspended_cb(const std::function<void(Activity const&)>& cb) { on_suspended.connect(cb); }
113   /*! Add a callback fired when the activity is resumed after being suspended */
114   static void on_resumed_cb(const std::function<void(Activity const&)>& cb) { on_resumed.connect(cb); }
115
116   void vetoable_start()
117   {
118     state_ = State::STARTING;
119     if (dependencies_solved() && is_assigned()) {
120       XBT_CVERB(s4u_activity, "'%s' is assigned to a resource and all dependencies are solved. Let's start", get_cname());
121       start();
122     } else {
123       if (vetoed_activities_ != nullptr)
124         vetoed_activities_->insert(this);
125       on_veto(*this);
126     }
127   }
128
129   void complete(Activity::State state)
130   {
131     state_ = state;
132     on_completion(*this);
133     if (state == State::FINISHED)
134       release_dependencies();
135   }
136
137   static std::set<Activity*>* get_vetoed_activities() { return vetoed_activities_; }
138   static void set_vetoed_activities(std::set<Activity*>* whereto) { vetoed_activities_ = whereto; }
139
140 #ifndef DOXYGEN
141   Activity(Activity const&) = delete;
142   Activity& operator=(Activity const&) = delete;
143 #endif
144
145   /** Starts a previously created activity.
146    *
147    * This function is optional: you can call wait() even if you didn't call start()
148    */
149   virtual Activity* start() = 0;
150   /** Tests whether the given activity is terminated yet. */
151   virtual bool test();
152   /*! take a vector s4u::ActivityPtr and return the rank of the first finished one (or -1 if none is done). */
153   static ssize_t test_any(const std::vector<ActivityPtr>& activities);
154
155   /** Blocks the current actor until the activity is terminated */
156   Activity* wait() { return wait_for(-1.0); }
157   /** Blocks the current actor until the activity is terminated, or until the timeout is elapsed\n
158    *  Raises: timeout exception.*/
159   Activity* wait_for(double timeout);
160   /** Blocks the current actor until the activity is terminated, or until the time limit is reached\n
161    * Raises: timeout exception. */
162   void wait_until(double time_limit);
163   /*! take a vector of s4u::ActivityPtr and return when one of them is finished.
164    * The return value is the rank of the first finished ActivityPtr. */
165   static ssize_t wait_any(const std::vector<ActivityPtr>& activities) { return wait_any_for(activities, -1); }
166   /*! Same as wait_any, but with a timeout. If the timeout occurs, parameter last is returned.*/
167   static ssize_t wait_any_for(const std::vector<ActivityPtr>& activities, double timeout);
168
169   /** Cancel that activity */
170   Activity* cancel();
171   /** Retrieve the current state of the activity */
172   Activity::State get_state() const { return state_; }
173   /** Return a string representation of the activity's state (one of INITED, STARTING, STARTED, CANCELED, FINISHED) */
174   const char* get_state_str() const;
175   void set_state(Activity::State state) { state_ = state; }
176
177   /** Blocks the progression of this activity until it gets resumed */
178   virtual Activity* suspend();
179   /** Unblock the progression of this activity if it was suspended previously */
180   virtual Activity* resume();
181   /** Whether or not the progression of this activity is blocked */
182   bool is_suspended() const { return suspended_; }
183
184   virtual const char* get_cname() const       = 0;
185   virtual const std::string& get_name() const = 0;
186
187   /** Get the remaining amount of work that this Activity entails. When it's 0, it's done. */
188   virtual double get_remaining() const;
189   /** Set the [remaining] amount of work that this Activity will entail
190    *
191    * It is forbidden to change the amount of work once the Activity is started */
192   Activity* set_remaining(double remains);
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 public:
235   AnyActivity* add_successor(ActivityPtr a)
236   {
237     Activity::add_successor(a);
238     return static_cast<AnyActivity*>(this);
239   }
240   AnyActivity* remove_successor(ActivityPtr a)
241   {
242     Activity::remove_successor(a);
243     return static_cast<AnyActivity*>(this);
244   }
245   AnyActivity* set_name(const std::string& name)
246   {
247     name_ = name;
248     return static_cast<AnyActivity*>(this);
249   }
250   const std::string& get_name() const override { return name_; }
251   const char* get_cname() const override { return name_.c_str(); }
252
253   AnyActivity* set_tracing_category(const std::string& category)
254   {
255     xbt_assert(get_state() == State::INITED, "Cannot change the tracing category of an activity after its start");
256     tracing_category_ = category;
257     return static_cast<AnyActivity*>(this);
258   }
259   const std::string& get_tracing_category() const { return tracing_category_; }
260
261   XBT_ATTRIB_DEPRECATED_v334("Please use Activity::set_data()") AnyActivity* set_user_data(void* data)
262   {
263     set_data(data);
264     return static_cast<AnyActivity*>(this);
265   }
266
267   XBT_ATTRIB_DEPRECATED_v334("Please use Activity::get_data<>()") void* get_user_data() const
268   {
269     return get_data<void>();
270   }
271
272   AnyActivity* vetoable_start()
273   {
274     Activity::vetoable_start();
275     return static_cast<AnyActivity*>(this);
276   }
277
278   AnyActivity* cancel() { return static_cast<AnyActivity*>(Activity::cancel()); }
279   AnyActivity* wait() { return wait_for(-1.0); }
280   virtual AnyActivity* wait_for(double timeout) { return static_cast<AnyActivity*>(Activity::wait_for(timeout)); }
281
282 #ifndef DOXYGEN
283   /* The refcounting is done in the ancestor class, Activity, but we want each of the classes benefiting of the CRTP
284    * (Exec, Comm, etc) to have smart pointers too, so we define these methods here, that forward the ptr_release and
285    * add_ref to the Activity class. Hopefully, the "inline" helps to not hinder the perf here.
286    */
287   friend void inline intrusive_ptr_release(AnyActivity* a) { intrusive_ptr_release(static_cast<Activity*>(a)); }
288   friend void inline intrusive_ptr_add_ref(AnyActivity* a) { intrusive_ptr_add_ref(static_cast<Activity*>(a)); }
289 #endif
290 };
291
292 } // namespace s4u
293 } // namespace simgrid
294
295 #endif /* SIMGRID_S4U_ACTIVITY_HPP */