Logo AND Algorithmique Numérique Distribuée

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