Logo AND Algorithmique Numérique Distribuée

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