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/cros/fake_system_state.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 chromeos_update_engine::FakeSystemState;
52 using std::pair;
53 using std::string;
54 using std::tuple;
55 using std::unique_ptr;
56 using std::vector;
57
58 namespace {
59
60 // Generates a fixed timestamp for use in faking the current time.
FixedTime()61 Time FixedTime() {
62 Time::Exploded now_exp;
63 now_exp.year = 2014;
64 now_exp.month = 3;
65 now_exp.day_of_week = 2;
66 now_exp.day_of_month = 18;
67 now_exp.hour = 8;
68 now_exp.minute = 5;
69 now_exp.second = 33;
70 now_exp.millisecond = 675;
71 Time time;
72 ignore_result(Time::FromLocalExploded(now_exp, &time));
73 return time;
74 }
75
76 } // namespace
77
78 namespace chromeos_update_manager {
79
80 class UmUpdateManagerTest : public ::testing::Test {
81 protected:
SetUp()82 void SetUp() override {
83 loop_.SetAsCurrent();
84 FakeSystemState::CreateInstance();
85 fake_state_ = new FakeState();
86 umut_.reset(new UpdateManager(
87 TimeDelta::FromSeconds(5), TimeDelta::FromSeconds(1), fake_state_));
88 }
89
TearDown()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 unique_ptr<UpdateManager> umut_;
96 };
97
98 // The FailingPolicy implements a single method and make it always fail. This
99 // class extends the DefaultPolicy class to allow extensions of the Policy
100 // class without extending nor changing this test.
101 class FailingPolicy : public DefaultPolicy {
102 public:
FailingPolicy(int * num_called_p)103 explicit FailingPolicy(int* num_called_p) : num_called_p_(num_called_p) {}
FailingPolicy()104 FailingPolicy() : FailingPolicy(nullptr) {}
UpdateCheckAllowed(EvaluationContext * ec,State * state,string * error,UpdateCheckParams * result) const105 EvalStatus UpdateCheckAllowed(EvaluationContext* ec,
106 State* state,
107 string* error,
108 UpdateCheckParams* result) const override {
109 if (num_called_p_)
110 (*num_called_p_)++;
111 *error = "FailingPolicy failed.";
112 return EvalStatus::kFailed;
113 }
114
115 protected:
PolicyName() const116 string PolicyName() const override { return "FailingPolicy"; }
117
118 private:
119 int* num_called_p_;
120 };
121
122 // The LazyPolicy always returns EvalStatus::kAskMeAgainLater.
123 class LazyPolicy : public DefaultPolicy {
UpdateCheckAllowed(EvaluationContext * ec,State * state,string * error,UpdateCheckParams * result) const124 EvalStatus UpdateCheckAllowed(EvaluationContext* ec,
125 State* state,
126 string* error,
127 UpdateCheckParams* result) const override {
128 return EvalStatus::kAskMeAgainLater;
129 }
130
131 protected:
PolicyName() const132 string PolicyName() const override { return "LazyPolicy"; }
133 };
134
135 // A policy that sleeps for a predetermined amount of time, then checks for a
136 // wallclock-based time threshold (if given) and returns
137 // EvalStatus::kAskMeAgainLater if not passed; otherwise, returns
138 // EvalStatus::kSucceeded. Increments a counter every time it is being queried,
139 // if a pointer to it is provided.
140 class DelayPolicy : public DefaultPolicy {
141 public:
DelayPolicy(int sleep_secs,Time time_threshold,int * num_called_p)142 DelayPolicy(int sleep_secs, Time time_threshold, int* num_called_p)
143 : sleep_secs_(sleep_secs),
144 time_threshold_(time_threshold),
145 num_called_p_(num_called_p) {}
UpdateCheckAllowed(EvaluationContext * ec,State * state,string * error,UpdateCheckParams * result) const146 EvalStatus UpdateCheckAllowed(EvaluationContext* ec,
147 State* state,
148 string* error,
149 UpdateCheckParams* result) const override {
150 if (num_called_p_)
151 (*num_called_p_)++;
152
153 // Sleep for a predetermined amount of time.
154 if (sleep_secs_ > 0)
155 sleep(sleep_secs_);
156
157 // Check for a time threshold. This can be used to ensure that the policy
158 // has some non-constant dependency.
159 if (time_threshold_ < Time::Max() &&
160 ec->IsWallclockTimeGreaterThan(time_threshold_))
161 return EvalStatus::kSucceeded;
162
163 return EvalStatus::kAskMeAgainLater;
164 }
165
166 protected:
PolicyName() const167 string PolicyName() const override { return "DelayPolicy"; }
168
169 private:
170 int sleep_secs_;
171 Time time_threshold_;
172 int* num_called_p_;
173 };
174
175 // AccumulateCallsCallback() adds to the passed |acc| accumulator vector pairs
176 // of EvalStatus and T instances. This allows to create a callback that keeps
177 // track of when it is called and the arguments passed to it, to be used with
178 // the UpdateManager::AsyncPolicyRequest().
179 template <typename T>
AccumulateCallsCallback(vector<pair<EvalStatus,T>> * acc,EvalStatus status,const T & result)180 static void AccumulateCallsCallback(vector<pair<EvalStatus, T>>* acc,
181 EvalStatus status,
182 const T& result) {
183 acc->push_back(std::make_pair(status, result));
184 }
185
186 // Tests that policy requests are completed successfully. It is important that
187 // this tests cover all policy requests as defined in Policy.
TEST_F(UmUpdateManagerTest,PolicyRequestCallUpdateCheckAllowed)188 TEST_F(UmUpdateManagerTest, PolicyRequestCallUpdateCheckAllowed) {
189 UpdateCheckParams result;
190 EXPECT_EQ(EvalStatus::kSucceeded,
191 umut_->PolicyRequest(&Policy::UpdateCheckAllowed, &result));
192 }
193
TEST_F(UmUpdateManagerTest,PolicyRequestCallUpdateCanStart)194 TEST_F(UmUpdateManagerTest, PolicyRequestCallUpdateCanStart) {
195 UpdateState update_state = UpdateState();
196 update_state.interactive = true;
197 update_state.is_delta_payload = false;
198 update_state.first_seen = FixedTime();
199 update_state.num_checks = 1;
200 update_state.num_failures = 0;
201 update_state.failures_last_updated = Time();
202 update_state.download_urls = vector<string>{"http://fake/url/"};
203 update_state.download_errors_max = 10;
204 update_state.p2p_downloading_disabled = false;
205 update_state.p2p_sharing_disabled = false;
206 update_state.p2p_num_attempts = 0;
207 update_state.p2p_first_attempted = Time();
208 update_state.last_download_url_idx = -1;
209 update_state.last_download_url_num_errors = 0;
210 update_state.download_errors = vector<tuple<int, ErrorCode, Time>>();
211 update_state.backoff_expiry = Time();
212 update_state.is_backoff_disabled = false;
213 update_state.scatter_wait_period = TimeDelta::FromSeconds(15);
214 update_state.scatter_check_threshold = 4;
215 update_state.scatter_wait_period_max = TimeDelta::FromSeconds(60);
216 update_state.scatter_check_threshold_min = 2;
217 update_state.scatter_check_threshold_max = 8;
218
219 UpdateDownloadParams result;
220 EXPECT_EQ(
221 EvalStatus::kSucceeded,
222 umut_->PolicyRequest(&Policy::UpdateCanStart, &result, update_state));
223 }
224
TEST_F(UmUpdateManagerTest,PolicyRequestCallsDefaultOnError)225 TEST_F(UmUpdateManagerTest, PolicyRequestCallsDefaultOnError) {
226 umut_->set_policy(new FailingPolicy());
227
228 // Tests that the DefaultPolicy instance is called when the method fails,
229 // which will set this as true.
230 UpdateCheckParams result;
231 result.updates_enabled = false;
232 EvalStatus status =
233 umut_->PolicyRequest(&Policy::UpdateCheckAllowed, &result);
234 EXPECT_EQ(EvalStatus::kSucceeded, status);
235 EXPECT_TRUE(result.updates_enabled);
236 }
237
238 // This test only applies to debug builds where DCHECK is enabled.
239 #if DCHECK_IS_ON
TEST_F(UmUpdateManagerTest,PolicyRequestDoesntBlockDeathTest)240 TEST_F(UmUpdateManagerTest, PolicyRequestDoesntBlockDeathTest) {
241 // The update manager should die (DCHECK) if a policy called synchronously
242 // returns a kAskMeAgainLater value.
243 UpdateCheckParams result;
244 umut_->set_policy(new LazyPolicy());
245 EXPECT_DEATH(umut_->PolicyRequest(&Policy::UpdateCheckAllowed, &result), "");
246 }
247 #endif // DCHECK_IS_ON
248
TEST_F(UmUpdateManagerTest,AsyncPolicyRequestDelaysEvaluation)249 TEST_F(UmUpdateManagerTest, AsyncPolicyRequestDelaysEvaluation) {
250 // To avoid differences in code execution order between an AsyncPolicyRequest
251 // call on a policy that returns AskMeAgainLater the first time and one that
252 // succeeds the first time, we ensure that the passed callback is called from
253 // the main loop in both cases even when we could evaluate it right now.
254 umut_->set_policy(new FailingPolicy());
255
256 vector<pair<EvalStatus, UpdateCheckParams>> calls;
257 Callback<void(EvalStatus, const UpdateCheckParams&)> callback =
258 Bind(AccumulateCallsCallback<UpdateCheckParams>, &calls);
259
260 umut_->AsyncPolicyRequest(callback, &Policy::UpdateCheckAllowed);
261 // The callback should wait until we run the main loop for it to be executed.
262 EXPECT_EQ(0U, calls.size());
263 MessageLoopRunMaxIterations(MessageLoop::current(), 100);
264 EXPECT_EQ(1U, calls.size());
265 }
266
TEST_F(UmUpdateManagerTest,AsyncPolicyRequestTimeoutDoesNotFire)267 TEST_F(UmUpdateManagerTest, AsyncPolicyRequestTimeoutDoesNotFire) {
268 // Set up an async policy call to return immediately, then wait a little and
269 // ensure that the timeout event does not fire.
270 int num_called = 0;
271 umut_->set_policy(new FailingPolicy(&num_called));
272
273 vector<pair<EvalStatus, UpdateCheckParams>> calls;
274 Callback<void(EvalStatus, const UpdateCheckParams&)> callback =
275 Bind(AccumulateCallsCallback<UpdateCheckParams>, &calls);
276
277 umut_->AsyncPolicyRequest(callback, &Policy::UpdateCheckAllowed);
278 // Run the main loop, ensure that policy was attempted once before deferring
279 // to the default.
280 MessageLoopRunMaxIterations(MessageLoop::current(), 100);
281 EXPECT_EQ(1, num_called);
282 ASSERT_EQ(1U, calls.size());
283 EXPECT_EQ(EvalStatus::kSucceeded, calls[0].first);
284 // Wait for the timeout to expire, run the main loop again, ensure that
285 // nothing happened.
286 test_clock_.Advance(TimeDelta::FromSeconds(2));
287 MessageLoopRunMaxIterations(MessageLoop::current(), 10);
288 EXPECT_EQ(1, num_called);
289 EXPECT_EQ(1U, calls.size());
290 }
291
TEST_F(UmUpdateManagerTest,AsyncPolicyRequestTimesOut)292 TEST_F(UmUpdateManagerTest, AsyncPolicyRequestTimesOut) {
293 auto* fake_clock = FakeSystemState::Get()->fake_clock();
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