Logo AND Algorithmique Numérique Distribuée

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