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 #include "update_engine/update_manager/update_manager.h"
18 
19 #include <unistd.h>
20 
21 #include <algorithm>
22 #include <memory>
23 #include <string>
24 #include <tuple>
25 #include <utility>
26 #include <vector>
27 
28 #include <base/bind.h>
29 #include <base/test/simple_test_clock.h>
30 #include <base/time/time.h>
31 #include <brillo/message_loops/fake_message_loop.h>
32 #include <brillo/message_loops/message_loop.h>
33 #include <brillo/message_loops/message_loop_utils.h>
34 #include <gmock/gmock.h>
35 #include <gtest/gtest.h>
36 
37 #include "update_engine/common/fake_clock.h"
38 #include "update_engine/update_manager/default_policy.h"
39 #include "update_engine/update_manager/fake_state.h"
40 #include "update_engine/update_manager/mock_policy.h"
41 #include "update_engine/update_manager/umtest_utils.h"
42 
43 using base::Bind;
44 using base::Callback;
45 using base::Time;
46 using base::TimeDelta;
47 using brillo::MessageLoop;
48 using brillo::MessageLoopRunMaxIterations;
49 using chromeos_update_engine::ErrorCode;
50 using chromeos_update_engine::FakeClock;
51 using std::pair;
52 using std::string;
53 using std::tuple;
54 using std::unique_ptr;
55 using std::vector;
56 
57 namespace {
58 
59 // Generates a fixed timestamp for use in faking the current time.
60 Time FixedTime() {
61   Time::Exploded now_exp;
62   now_exp.year = 2014;
63   now_exp.month = 3;
64   now_exp.day_of_week = 2;
65   now_exp.day_of_month = 18;
66   now_exp.hour = 8;
67   now_exp.minute = 5;
68   now_exp.second = 33;
69   now_exp.millisecond = 675;
70   Time time;
71   ignore_result(Time::FromLocalExploded(now_exp, &time));
72   return time;
73 }
74 
75 }  // namespace
76 
77 namespace chromeos_update_manager {
78 
79 class UmUpdateManagerTest : public ::testing::Test {
80  protected:
81   void SetUp() override {
82     loop_.SetAsCurrent();
83     fake_state_ = new FakeState();
84     umut_.reset(new UpdateManager(&fake_clock_,
85                                   TimeDelta::FromSeconds(5),
86                                   TimeDelta::FromSeconds(1),
87                                   fake_state_));
88   }
89 
90   void TearDown() override { EXPECT_FALSE(loop_.PendingTasks()); }
91 
92   base::SimpleTestClock test_clock_;
93   brillo::FakeMessageLoop loop_{&test_clock_};
94   FakeState* fake_state_;  // Owned by the umut_.
95   FakeClock fake_clock_;
96   unique_ptr<UpdateManager> umut_;
97 };
98 
99 // The FailingPolicy implements a single method and make it always fail. This
100 // class extends the DefaultPolicy class to allow extensions of the Policy
101 // class without extending nor changing this test.
102 class FailingPolicy : public DefaultPolicy {
103  public:
104   explicit FailingPolicy(int* num_called_p) : num_called_p_(num_called_p) {}
105   FailingPolicy() : FailingPolicy(nullptr) {}
106   EvalStatus UpdateCheckAllowed(EvaluationContext* ec,
107                                 State* state,
108                                 string* error,
109                                 UpdateCheckParams* result) const override {
110     if (num_called_p_)
111       (*num_called_p_)++;
112     *error = "FailingPolicy failed.";
113     return EvalStatus::kFailed;
114   }
115 
116  protected:
117   string PolicyName() const override { return "FailingPolicy"; }
118 
119  private:
120   int* num_called_p_;
121 };
122 
123 // The LazyPolicy always returns EvalStatus::kAskMeAgainLater.
124 class LazyPolicy : public DefaultPolicy {
125   EvalStatus UpdateCheckAllowed(EvaluationContext* ec,
126                                 State* state,
127                                 string* error,
128                                 UpdateCheckParams* result) const override {
129     return EvalStatus::kAskMeAgainLater;
130   }
131 
132  protected:
133   string PolicyName() const override { return "LazyPolicy"; }
134 };
135 
136 // A policy that sleeps for a predetermined amount of time, then checks for a
137 // wallclock-based time threshold (if given) and returns
138 // EvalStatus::kAskMeAgainLater if not passed; otherwise, returns
139 // EvalStatus::kSucceeded. Increments a counter every time it is being queried,
140 // if a pointer to it is provided.
141 class DelayPolicy : public DefaultPolicy {
142  public:
143   DelayPolicy(int sleep_secs, Time time_threshold, int* num_called_p)
144       : sleep_secs_(sleep_secs),
145         time_threshold_(time_threshold),
146         num_called_p_(num_called_p) {}
147   EvalStatus UpdateCheckAllowed(EvaluationContext* ec,
148                                 State* state,
149                                 string* error,
150                                 UpdateCheckParams* result) const override {
151     if (num_called_p_)
152       (*num_called_p_)++;
153 
154     // Sleep for a predetermined amount of time.
155     if (sleep_secs_ > 0)
156       sleep(sleep_secs_);
157 
158     // Check for a time threshold. This can be used to ensure that the policy
159     // has some non-constant dependency.
160     if (time_threshold_ < Time::Max() &&
161         ec->IsWallclockTimeGreaterThan(time_threshold_))
162       return EvalStatus::kSucceeded;
163 
164     return EvalStatus::kAskMeAgainLater;
165   }
166 
167  protected:
168   string PolicyName() const override { return "DelayPolicy"; }
169 
170  private:
171   int sleep_secs_;
172   Time time_threshold_;
173   int* num_called_p_;
174 };
175 
176 // AccumulateCallsCallback() adds to the passed |acc| accumulator vector pairs
177 // of EvalStatus and T instances. This allows to create a callback that keeps
178 // track of when it is called and the arguments passed to it, to be used with
179 // the UpdateManager::AsyncPolicyRequest().
180 template <typename T>
181 static void AccumulateCallsCallback(vector<pair<EvalStatus, T>>* acc,
182                                     EvalStatus status,
183                                     const T& result) {
184   acc->push_back(std::make_pair(status, result));
185 }
186 
187 // Tests that policy requests are completed successfully. It is important that
188 // this tests cover all policy requests as defined in Policy.
189 TEST_F(UmUpdateManagerTest, PolicyRequestCallUpdateCheckAllowed) {
190   UpdateCheckParams result;
191   EXPECT_EQ(EvalStatus::kSucceeded,
192             umut_->PolicyRequest(&Policy::UpdateCheckAllowed, &result));
193 }
194 
195 TEST_F(UmUpdateManagerTest, PolicyRequestCallUpdateCanStart) {
196   UpdateState update_state = UpdateState();
197   update_state.interactive = true;
198   update_state.is_delta_payload = false;
199   update_state.first_seen = FixedTime();
200   update_state.num_checks = 1;
201   update_state.num_failures = 0;
202   update_state.failures_last_updated = Time();
203   update_state.download_urls = vector<string>{"http://fake/url/"};
204   update_state.download_errors_max = 10;
205   update_state.p2p_downloading_disabled = false;
206   update_state.p2p_sharing_disabled = false;
207   update_state.p2p_num_attempts = 0;
208   update_state.p2p_first_attempted = Time();
209   update_state.last_download_url_idx = -1;
210   update_state.last_download_url_num_errors = 0;
211   update_state.download_errors = vector<tuple<int, ErrorCode, Time>>();
212   update_state.backoff_expiry = Time();
213   update_state.is_backoff_disabled = false;
214   update_state.scatter_wait_period = TimeDelta::FromSeconds(15);
215   update_state.scatter_check_threshold = 4;
216   update_state.scatter_wait_period_max = TimeDelta::FromSeconds(60);
217   update_state.scatter_check_threshold_min = 2;
218   update_state.scatter_check_threshold_max = 8;
219 
220   UpdateDownloadParams result;
221   EXPECT_EQ(
222       EvalStatus::kSucceeded,
223       umut_->PolicyRequest(&Policy::UpdateCanStart, &result, update_state));
224 }
225 
226 TEST_F(UmUpdateManagerTest, PolicyRequestCallsDefaultOnError) {
227   umut_->set_policy(new FailingPolicy());
228 
229   // Tests that the DefaultPolicy instance is called when the method fails,
230   // which will set this as true.
231   UpdateCheckParams result;
232   result.updates_enabled = false;
233   EvalStatus status =
234       umut_->PolicyRequest(&Policy::UpdateCheckAllowed, &result);
235   EXPECT_EQ(EvalStatus::kSucceeded, status);
236   EXPECT_TRUE(result.updates_enabled);
237 }
238 
239 // This test only applies to debug builds where DCHECK is enabled.
240 #if DCHECK_IS_ON
241 TEST_F(UmUpdateManagerTest, PolicyRequestDoesntBlockDeathTest) {
242   // The update manager should die (DCHECK) if a policy called synchronously
243   // returns a kAskMeAgainLater value.
244   UpdateCheckParams result;
245   umut_->set_policy(new LazyPolicy());
246   EXPECT_DEATH(umut_->PolicyRequest(&Policy::UpdateCheckAllowed, &result), "");
247 }
248 #endif  // DCHECK_IS_ON
249 
250 TEST_F(UmUpdateManagerTest, AsyncPolicyRequestDelaysEvaluation) {
251   // To avoid differences in code execution order between an AsyncPolicyRequest
252   // call on a policy that returns AskMeAgainLater the first time and one that
253   // succeeds the first time, we ensure that the passed callback is called from
254   // the main loop in both cases even when we could evaluate it right now.
255   umut_->set_policy(new FailingPolicy());
256 
257   vector<pair<EvalStatus, UpdateCheckParams>> calls;
258   Callback<void(EvalStatus, const UpdateCheckParams&)> callback =
259       Bind(AccumulateCallsCallback<UpdateCheckParams>, &calls);
260 
261   umut_->AsyncPolicyRequest(callback, &Policy::UpdateCheckAllowed);
262   // The callback should wait until we run the main loop for it to be executed.
263   EXPECT_EQ(0U, calls.size());
264   MessageLoopRunMaxIterations(MessageLoop::current(), 100);
265   EXPECT_EQ(1U, calls.size());
266 }
267 
268 TEST_F(UmUpdateManagerTest, AsyncPolicyRequestTimeoutDoesNotFire) {
269   // Set up an async policy call to return immediately, then wait a little and
270   // ensure that the timeout event does not fire.
271   int num_called = 0;
272   umut_->set_policy(new FailingPolicy(&num_called));
273 
274   vector<pair<EvalStatus, UpdateCheckParams>> calls;
275   Callback<void(EvalStatus, const UpdateCheckParams&)> callback =
276       Bind(AccumulateCallsCallback<UpdateCheckParams>, &calls);
277 
278   umut_->AsyncPolicyRequest(callback, &Policy::UpdateCheckAllowed);
279   // Run the main loop, ensure that policy was attempted once before deferring
280   // to the default.
281   MessageLoopRunMaxIterations(MessageLoop::current(), 100);
282   EXPECT_EQ(1, num_called);
283   ASSERT_EQ(1U, calls.size());
284   EXPECT_EQ(EvalStatus::kSucceeded, calls[0].first);
285   // Wait for the timeout to expire, run the main loop again, ensure that
286   // nothing happened.
287   test_clock_.Advance(TimeDelta::FromSeconds(2));
288   MessageLoopRunMaxIterations(MessageLoop::current(), 10);
289   EXPECT_EQ(1, num_called);
290   EXPECT_EQ(1U, calls.size());
291 }
292 
293 TEST_F(UmUpdateManagerTest, AsyncPolicyRequestTimesOut) {
294   // Set up an async policy call to exceed its expiration timeout, make sure
295   // that the default policy was not used (no callback) and that evaluation is
296   // reattempted.
297   int num_called = 0;
298   umut_->set_policy(new DelayPolicy(
299       0,
300       fake_clock_.GetWallclockTime() + TimeDelta::FromSeconds(3),
301       &num_called));
302 
303   vector<pair<EvalStatus, UpdateCheckParams>> calls;
304   Callback<void(EvalStatus, const UpdateCheckParams&)> callback =
305       Bind(AccumulateCallsCallback<UpdateCheckParams>, &calls);
306 
307   umut_->AsyncPolicyRequest(callback, &Policy::UpdateCheckAllowed);
308   // Run the main loop, ensure that policy was attempted once but the callback
309   // was not invoked.
310   MessageLoopRunMaxIterations(MessageLoop::current(), 100);
311   EXPECT_EQ(1, num_called);
312   EXPECT_EQ(0U, calls.size());
313   // Wait for the expiration timeout to expire, run the main loop again,
314   // ensure that reevaluation occurred but callback was not invoked (i.e.
315   // default policy was not consulted).
316   test_clock_.Advance(TimeDelta::FromSeconds(2));
317   fake_clock_.SetWallclockTime(fake_clock_.GetWallclockTime() +
318                                TimeDelta::FromSeconds(2));
319   MessageLoopRunMaxIterations(MessageLoop::current(), 10);
320   EXPECT_EQ(2, num_called);
321   EXPECT_EQ(0U, calls.size());
322   // Wait for reevaluation due to delay to happen, ensure that it occurs and
323   // that the callback is invoked.
324   test_clock_.Advance(TimeDelta::FromSeconds(2));
325   fake_clock_.SetWallclockTime(fake_clock_.GetWallclockTime() +
326                                TimeDelta::FromSeconds(2));
327   MessageLoopRunMaxIterations(MessageLoop::current(), 10);
328   EXPECT_EQ(3, num_called);
329   ASSERT_EQ(1U, calls.size());
330   EXPECT_EQ(EvalStatus::kSucceeded, calls[0].first);
331 }
332 
333 }  // namespace chromeos_update_manager
334