• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright (C) 2014 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #ifndef UPDATE_ENGINE_UPDATE_MANAGER_EVALUATION_CONTEXT_H_
18 #define UPDATE_ENGINE_UPDATE_MANAGER_EVALUATION_CONTEXT_H_
19 
20 #include <map>
21 #include <memory>
22 #include <string>
23 
24 #include <base/bind.h>
25 #include <base/callback.h>
26 #include <base/memory/weak_ptr.h>
27 #include <base/time/time.h>
28 #include <brillo/message_loops/message_loop.h>
29 
30 #include "update_engine/update_manager/boxed_value.h"
31 #include "update_engine/update_manager/variable.h"
32 
33 namespace chromeos_update_manager {
34 
35 // The EvaluationContext class is the interface between a policy implementation
36 // and the state. The EvaluationContext tracks the variables used by a policy
37 // request and caches the returned values, owning those cached values.
38 // The same EvaluationContext should be re-used for all the evaluations of the
39 // same policy request (an AsyncPolicyRequest might involve several
40 // re-evaluations). Each evaluation of the EvaluationContext is run at a given
41 // point in time, which is used as a reference for the evaluation timeout and
42 // the time based queries of the policy, such as
43 // Is{Wallclock,Monotonic}TimeGreaterThan().
44 //
45 // Example:
46 //
47 //   auto ec = std::make_shared<EvaluationContext>(...);
48 //
49 //   ...
50 //   // The following call to ResetEvaluation() is optional. Use it to reset the
51 //   // evaluation time if the EvaluationContext isn't used right after its
52 //   // construction.
53 //   ec->ResetEvaluation();
54 //   EvalStatus status = policy->SomeMethod(ec, state, &result, args...);
55 //
56 //   ...
57 //   // Run a closure when any of the used async variables changes its value or
58 //   // the timeout for re-query the values happens again.
59 //   ec->RunOnValueChangeOrTimeout(closure);
60 //   // If the provided |closure| wants to re-evaluate the policy, it should
61 //   // call ec->ResetEvaluation() to start a new evaluation.
62 //
63 class EvaluationContext : private BaseVariable::ObserverInterface {
64  public:
65   EvaluationContext(
66       base::TimeDelta evaluation_timeout,
67       base::TimeDelta expiration_timeout,
68       std::unique_ptr<base::Callback<void(EvaluationContext*)>> unregister_cb);
EvaluationContext(base::TimeDelta evaluation_timeout)69   explicit EvaluationContext(base::TimeDelta evaluation_timeout)
70       : EvaluationContext(
71             evaluation_timeout,
72             base::TimeDelta::Max(),
73             std::unique_ptr<base::Callback<void(EvaluationContext*)>>()) {}
74   ~EvaluationContext();
75 
76   // Returns a pointer to the value returned by the passed variable |var|. The
77   // EvaluationContext instance keeps the ownership of the returned object. The
78   // returned object is valid during the life of the evaluation, even if the
79   // passed Variable changes it.
80   //
81   // In case of error, a null value is returned.
82   template <typename T>
83   const T* GetValue(Variable<T>* var);
84 
85   // Returns whether the evaluation time has surpassed |timestamp|, on either
86   // the ClockInterface::GetWallclockTime() or
87   // ClockInterface::GetMonotonicTime() scales, respectively.
88   bool IsWallclockTimeGreaterThan(base::Time timestamp);
89   bool IsMonotonicTimeGreaterThan(base::Time timestamp);
90 
91   // Returns whether the evaluation context has expired.
is_expired()92   bool is_expired() const { return is_expired_; }
93 
94   // TODO(deymo): Move the following methods to an interface only visible by the
95   // UpdateManager class and not the policy implementations.
96 
97   // Resets the EvaluationContext to its initial state removing all the
98   // non-const cached variables and re-setting the evaluation time. This should
99   // be called right before any new evaluation starts.
100   void ResetEvaluation();
101 
102   // Clears the expiration status of the EvaluationContext and resets its
103   // expiration timeout based on |expiration_timeout_|. This should be called if
104   // expiration occurred, prior to re-evaluating the policy.
105   void ResetExpiration();
106 
107   // Schedules the passed |callback| closure to be called when a cached
108   // variable changes its value, a polling interval passes, or the context
109   // expiration occurs. If none of these events can happen, for example if
110   // there's no cached variable, this method returns false.
111   //
112   // Right before the passed closure is called the EvaluationContext is
113   // reset, removing all the non-const cached values.
114   bool RunOnValueChangeOrTimeout(base::Closure callback);
115 
116   // Returns a textual representation of the evaluation context,
117   // including the variables and their values. This is intended only
118   // to help with debugging and the format may change in the future.
119   std::string DumpContext() const;
120 
121   // Removes all the Observers callbacks and timeout events scheduled by
122   // RunOnValueChangeOrTimeout(). Also releases and returns the closure
123   // associated with these events. This method is idempotent.
124   std::unique_ptr<base::Closure> RemoveObserversAndTimeout();
125 
126  private:
127   friend class UmEvaluationContextTest;
128 
129   // BaseVariable::ObserverInterface override.
130   void ValueChanged(BaseVariable* var) override;
131 
132   // Called from the main loop when a scheduled timeout has passed.
133   void OnTimeout();
134 
135   // Removes the observers from the used Variables and cancels the timeout,
136   // then executes the scheduled callback.
137   void OnValueChangedOrTimeout();
138 
139   // If |monotonic_deadline| is not Time::Max(), returns the remaining time
140   // until it is reached, or zero if it has passed. Otherwise, returns
141   // TimeDelta::Max().
142   base::TimeDelta RemainingTime(base::Time monotonic_deadline) const;
143 
144   // Returns a monotonic clock timestamp at which |timeout| will have elapsed
145   // since the current time.
146   base::Time MonotonicDeadline(base::TimeDelta timeout);
147 
148   // A map to hold the cached values for every variable.
149   typedef std::map<BaseVariable*, BoxedValue> ValueCacheMap;
150 
151   // The cached values of the called Variables.
152   ValueCacheMap value_cache_;
153 
154   // A callback used for triggering re-evaluation upon a value change or poll
155   // timeout, or notifying about the evaluation context expiration. It is up to
156   // the caller to determine whether or not expiration occurred via
157   // is_expired().
158   std::unique_ptr<base::Closure> callback_;
159 
160   // The TaskId returned by the message loop identifying the timeout callback.
161   // Used for canceling the timeout callback.
162   brillo::MessageLoop::TaskId timeout_event_ = brillo::MessageLoop::kTaskIdNull;
163 
164   // Whether a timeout event firing marks the expiration of the evaluation
165   // context.
166   bool timeout_marks_expiration_;
167 
168   // Whether the evaluation context has indeed expired.
169   bool is_expired_ = false;
170 
171   // The timestamps when the evaluation of this EvaluationContext started,
172   // corresponding to ClockInterface::GetWallclockTime() and
173   // ClockInterface::GetMonotonicTime(), respectively. These values are reset
174   // every time ResetEvaluation() is called.
175   base::Time evaluation_start_wallclock_;
176   base::Time evaluation_start_monotonic_;
177 
178   // The timestamps when a reevaluation should be triggered due to various
179   // expected value changes, corresponding to ClockInterface::GetWallclockTime()
180   // and ClockInterface::GetMonotonicTIme(), respectively. These timestamps are
181   // greater or equal to corresponding |evaluation_start_{wallclock,monotonic}_|
182   // counterparts since they are in the future; however, they may be smaller
183   // than the current corresponding times during the course of evaluation.
184   base::Time reevaluation_time_wallclock_;
185   base::Time reevaluation_time_monotonic_;
186 
187   // The timeout of an evaluation.
188   const base::TimeDelta evaluation_timeout_;
189 
190   // The timestamp in the ClockInterface::GetMonotonicTime() scale at which the
191   // current evaluation should finish.
192   base::Time evaluation_monotonic_deadline_;
193 
194   // The expiration timeout of the evaluation context.
195   const base::TimeDelta expiration_timeout_;
196 
197   // The monotonic clock deadline at which expiration occurs.
198   base::Time expiration_monotonic_deadline_;
199 
200   // A callback for unregistering the context upon destruction.
201   std::unique_ptr<base::Callback<void(EvaluationContext*)>> unregister_cb_;
202 
203   base::WeakPtrFactory<EvaluationContext> weak_ptr_factory_;
204 
205   DISALLOW_COPY_AND_ASSIGN(EvaluationContext);
206 };
207 
208 }  // namespace chromeos_update_manager
209 
210 // Include the implementation of the template methods.
211 #include "update_engine/update_manager/evaluation_context-inl.h"
212 
213 #endif  // UPDATE_ENGINE_UPDATE_MANAGER_EVALUATION_CONTEXT_H_
214