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_, TimeDelta::FromSeconds(5), 85 TimeDelta::FromSeconds(1), fake_state_)); 86 } 87 88 void TearDown() override { 89 EXPECT_FALSE(loop_.PendingTasks()); 90 } 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, 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: 116 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 { 124 EvalStatus UpdateCheckAllowed(EvaluationContext* ec, State* state, 125 string* error, 126 UpdateCheckParams* result) const override { 127 return EvalStatus::kAskMeAgainLater; 128 } 129 130 protected: 131 string PolicyName() const override { return "LazyPolicy"; } 132 }; 133 134 // A policy that sleeps for a predetermined amount of time, then checks for a 135 // wallclock-based time threshold (if given) and returns 136 // EvalStatus::kAskMeAgainLater if not passed; otherwise, returns 137 // EvalStatus::kSucceeded. Increments a counter every time it is being queried, 138 // if a pointer to it is provided. 139 class DelayPolicy : public DefaultPolicy { 140 public: 141 DelayPolicy(int sleep_secs, Time time_threshold, int* num_called_p) 142 : sleep_secs_(sleep_secs), time_threshold_(time_threshold), 143 num_called_p_(num_called_p) {} 144 EvalStatus UpdateCheckAllowed(EvaluationContext* ec, State* state, 145 string* error, 146 UpdateCheckParams* result) const override { 147 if (num_called_p_) 148 (*num_called_p_)++; 149 150 // Sleep for a predetermined amount of time. 151 if (sleep_secs_ > 0) 152 sleep(sleep_secs_); 153 154 // Check for a time threshold. This can be used to ensure that the policy 155 // has some non-constant dependency. 156 if (time_threshold_ < Time::Max() && 157 ec->IsWallclockTimeGreaterThan(time_threshold_)) 158 return EvalStatus::kSucceeded; 159 160 return EvalStatus::kAskMeAgainLater; 161 } 162 163 protected: 164 string PolicyName() const override { return "DelayPolicy"; } 165 166 private: 167 int sleep_secs_; 168 Time time_threshold_; 169 int* num_called_p_; 170 }; 171 172 // AccumulateCallsCallback() adds to the passed |acc| accumulator vector pairs 173 // of EvalStatus and T instances. This allows to create a callback that keeps 174 // track of when it is called and the arguments passed to it, to be used with 175 // the UpdateManager::AsyncPolicyRequest(). 176 template<typename T> 177 static void AccumulateCallsCallback(vector<pair<EvalStatus, T>>* acc, 178 EvalStatus status, const T& result) { 179 acc->push_back(std::make_pair(status, result)); 180 } 181 182 // Tests that policy requests are completed successfully. It is important that 183 // this tests cover all policy requests as defined in Policy. 184 TEST_F(UmUpdateManagerTest, PolicyRequestCallUpdateCheckAllowed) { 185 UpdateCheckParams result; 186 EXPECT_EQ(EvalStatus::kSucceeded, umut_->PolicyRequest( 187 &Policy::UpdateCheckAllowed, &result)); 188 } 189 190 TEST_F(UmUpdateManagerTest, PolicyRequestCallUpdateCanStart) { 191 UpdateState update_state = UpdateState(); 192 update_state.is_interactive = true; 193 update_state.is_delta_payload = false; 194 update_state.first_seen = FixedTime(); 195 update_state.num_checks = 1; 196 update_state.num_failures = 0; 197 update_state.failures_last_updated = Time(); 198 update_state.download_urls = vector<string>{"http://fake/url/"}; 199 update_state.download_errors_max = 10; 200 update_state.p2p_downloading_disabled = false; 201 update_state.p2p_sharing_disabled = false; 202 update_state.p2p_num_attempts = 0; 203 update_state.p2p_first_attempted = Time(); 204 update_state.last_download_url_idx = -1; 205 update_state.last_download_url_num_errors = 0; 206 update_state.download_errors = vector<tuple<int, ErrorCode, Time>>(); 207 update_state.backoff_expiry = Time(); 208 update_state.is_backoff_disabled = false; 209 update_state.scatter_wait_period = TimeDelta::FromSeconds(15); 210 update_state.scatter_check_threshold = 4; 211 update_state.scatter_wait_period_max = TimeDelta::FromSeconds(60); 212 update_state.scatter_check_threshold_min = 2; 213 update_state.scatter_check_threshold_max = 8; 214 215 UpdateDownloadParams result; 216 EXPECT_EQ(EvalStatus::kSucceeded, 217 umut_->PolicyRequest(&Policy::UpdateCanStart, &result, 218 update_state)); 219 } 220 221 TEST_F(UmUpdateManagerTest, PolicyRequestCallsDefaultOnError) { 222 umut_->set_policy(new FailingPolicy()); 223 224 // Tests that the DefaultPolicy instance is called when the method fails, 225 // which will set this as true. 226 UpdateCheckParams result; 227 result.updates_enabled = false; 228 EvalStatus status = umut_->PolicyRequest( 229 &Policy::UpdateCheckAllowed, &result); 230 EXPECT_EQ(EvalStatus::kSucceeded, status); 231 EXPECT_TRUE(result.updates_enabled); 232 } 233 234 // This test only applies to debug builds where DCHECK is enabled. 235 #if DCHECK_IS_ON 236 TEST_F(UmUpdateManagerTest, PolicyRequestDoesntBlockDeathTest) { 237 // The update manager should die (DCHECK) if a policy called synchronously 238 // returns a kAskMeAgainLater value. 239 UpdateCheckParams result; 240 umut_->set_policy(new LazyPolicy()); 241 EXPECT_DEATH(umut_->PolicyRequest(&Policy::UpdateCheckAllowed, &result), ""); 242 } 243 #endif // DCHECK_IS_ON 244 245 TEST_F(UmUpdateManagerTest, AsyncPolicyRequestDelaysEvaluation) { 246 // To avoid differences in code execution order between an AsyncPolicyRequest 247 // call on a policy that returns AskMeAgainLater the first time and one that 248 // succeeds the first time, we ensure that the passed callback is called from 249 // the main loop in both cases even when we could evaluate it right now. 250 umut_->set_policy(new FailingPolicy()); 251 252 vector<pair<EvalStatus, UpdateCheckParams>> calls; 253 Callback<void(EvalStatus, const UpdateCheckParams&)> callback = Bind( 254 AccumulateCallsCallback<UpdateCheckParams>, &calls); 255 256 umut_->AsyncPolicyRequest(callback, &Policy::UpdateCheckAllowed); 257 // The callback should wait until we run the main loop for it to be executed. 258 EXPECT_EQ(0U, calls.size()); 259 MessageLoopRunMaxIterations(MessageLoop::current(), 100); 260 EXPECT_EQ(1U, calls.size()); 261 } 262 263 TEST_F(UmUpdateManagerTest, AsyncPolicyRequestTimeoutDoesNotFire) { 264 // Set up an async policy call to return immediately, then wait a little and 265 // ensure that the timeout event does not fire. 266 int num_called = 0; 267 umut_->set_policy(new FailingPolicy(&num_called)); 268 269 vector<pair<EvalStatus, UpdateCheckParams>> calls; 270 Callback<void(EvalStatus, const UpdateCheckParams&)> callback = 271 Bind(AccumulateCallsCallback<UpdateCheckParams>, &calls); 272 273 umut_->AsyncPolicyRequest(callback, &Policy::UpdateCheckAllowed); 274 // Run the main loop, ensure that policy was attempted once before deferring 275 // to the default. 276 MessageLoopRunMaxIterations(MessageLoop::current(), 100); 277 EXPECT_EQ(1, num_called); 278 ASSERT_EQ(1U, calls.size()); 279 EXPECT_EQ(EvalStatus::kSucceeded, calls[0].first); 280 // Wait for the timeout to expire, run the main loop again, ensure that 281 // nothing happened. 282 test_clock_.Advance(TimeDelta::FromSeconds(2)); 283 MessageLoopRunMaxIterations(MessageLoop::current(), 10); 284 EXPECT_EQ(1, num_called); 285 EXPECT_EQ(1U, calls.size()); 286 } 287 288 TEST_F(UmUpdateManagerTest, AsyncPolicyRequestTimesOut) { 289 // Set up an async policy call to exceed its expiration timeout, make sure 290 // that the default policy was not used (no callback) and that evaluation is 291 // reattempted. 292 int num_called = 0; 293 umut_->set_policy(new DelayPolicy( 294 0, fake_clock_.GetWallclockTime() + TimeDelta::FromSeconds(3), 295 &num_called)); 296 297 vector<pair<EvalStatus, UpdateCheckParams>> calls; 298 Callback<void(EvalStatus, const UpdateCheckParams&)> callback = 299 Bind(AccumulateCallsCallback<UpdateCheckParams>, &calls); 300 301 umut_->AsyncPolicyRequest(callback, &Policy::UpdateCheckAllowed); 302 // Run the main loop, ensure that policy was attempted once but the callback 303 // was not invoked. 304 MessageLoopRunMaxIterations(MessageLoop::current(), 100); 305 EXPECT_EQ(1, num_called); 306 EXPECT_EQ(0U, calls.size()); 307 // Wait for the expiration timeout to expire, run the main loop again, 308 // ensure that reevaluation occurred but callback was not invoked (i.e. 309 // default policy was not consulted). 310 test_clock_.Advance(TimeDelta::FromSeconds(2)); 311 fake_clock_.SetWallclockTime(fake_clock_.GetWallclockTime() + 312 TimeDelta::FromSeconds(2)); 313 MessageLoopRunMaxIterations(MessageLoop::current(), 10); 314 EXPECT_EQ(2, num_called); 315 EXPECT_EQ(0U, calls.size()); 316 // Wait for reevaluation due to delay to happen, ensure that it occurs and 317 // that the callback is invoked. 318 test_clock_.Advance(TimeDelta::FromSeconds(2)); 319 fake_clock_.SetWallclockTime(fake_clock_.GetWallclockTime() + 320 TimeDelta::FromSeconds(2)); 321 MessageLoopRunMaxIterations(MessageLoop::current(), 10); 322 EXPECT_EQ(3, num_called); 323 ASSERT_EQ(1U, calls.size()); 324 EXPECT_EQ(EvalStatus::kSucceeded, calls[0].first); 325 } 326 327 } // namespace chromeos_update_manager 328