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