blob: d799c3358204ef05f3cdf45e1a7b5343cd9e8e1d [file] [log] [blame]
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/update_attempter.h"
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07006
7// From 'man clock_gettime': feature test macro: _POSIX_C_SOURCE >= 199309L
8#ifndef _POSIX_C_SOURCE
9#define _POSIX_C_SOURCE 199309L
10#endif // _POSIX_C_SOURCE
11#include <time.h>
12
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070013#include <string>
Darin Petkov9b230572010-10-08 10:20:09 -070014#include <tr1/memory>
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070015#include <vector>
Darin Petkov9d65b7b2010-07-20 09:13:01 -070016
Jay Srinivasanc1ba09a2012-08-14 14:15:57 -070017#include <base/file_util.h>
Andrew de los Reyes45168102010-11-22 11:13:50 -080018#include <base/rand_util.h>
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070019#include <glib.h>
Darin Petkov1023a602010-08-30 13:47:51 -070020#include <metrics/metrics_library.h>
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +020021#include <policy/libpolicy.h>
22#include <policy/device_policy.h>
Darin Petkov9d65b7b2010-07-20 09:13:01 -070023
Bruno Rocha7f9aea22011-09-12 14:31:24 -070024#include "update_engine/certificate_checker.h"
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070025#include "update_engine/dbus_service.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070026#include "update_engine/download_action.h"
27#include "update_engine/filesystem_copier_action.h"
28#include "update_engine/libcurl_http_fetcher.h"
Andrew de los Reyes819fef22010-12-17 11:33:58 -080029#include "update_engine/multi_range_http_fetcher.h"
Darin Petkov6a5b3222010-07-13 14:55:28 -070030#include "update_engine/omaha_request_action.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070031#include "update_engine/omaha_request_params.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070032#include "update_engine/omaha_response_handler_action.h"
33#include "update_engine/postinstall_runner_action.h"
Darin Petkov36275772010-10-01 11:40:57 -070034#include "update_engine/prefs_interface.h"
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -070035#include "update_engine/subprocess.h"
Jay Srinivasan43488792012-06-19 00:25:31 -070036#include "update_engine/system_state.h"
Darin Petkov1023a602010-08-30 13:47:51 -070037#include "update_engine/update_check_scheduler.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070038
Darin Petkovaf183052010-08-23 12:07:13 -070039using base::TimeDelta;
40using base::TimeTicks;
Andrew de los Reyes21816e12011-04-07 14:18:56 -070041using google::protobuf::NewPermanentCallback;
Darin Petkov9b230572010-10-08 10:20:09 -070042using std::make_pair;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070043using std::tr1::shared_ptr;
Jay Srinivasan43488792012-06-19 00:25:31 -070044using std::set;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070045using std::string;
46using std::vector;
47
48namespace chromeos_update_engine {
49
Darin Petkov36275772010-10-01 11:40:57 -070050const int UpdateAttempter::kMaxDeltaUpdateFailures = 3;
51
Gilad Arnold1ebd8132012-03-05 10:19:29 -080052// Private test server URL w/ custom port number.
Gilad Arnolded747312012-03-15 18:20:41 -070053// TODO(garnold) This is a temporary hack to allow us to test the closed loop
54// automated update testing. To be replaced with an hard-coded local IP address.
55const char* const UpdateAttempter::kTestUpdateUrl(
56 "http://garnold.mtv.corp.google.com:8080/update");
Gilad Arnold28e2f392012-02-09 14:36:46 -080057
Darin Petkovcd1666f2010-09-23 09:53:44 -070058const char* kUpdateCompletedMarker =
59 "/var/run/update_engine_autoupdate_completed";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -070060
Andrew de los Reyes45168102010-11-22 11:13:50 -080061namespace {
62const int kMaxConsecutiveObeyProxyRequests = 20;
63} // namespace {}
64
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070065const char* UpdateStatusToString(UpdateStatus status) {
66 switch (status) {
67 case UPDATE_STATUS_IDLE:
68 return "UPDATE_STATUS_IDLE";
69 case UPDATE_STATUS_CHECKING_FOR_UPDATE:
70 return "UPDATE_STATUS_CHECKING_FOR_UPDATE";
71 case UPDATE_STATUS_UPDATE_AVAILABLE:
72 return "UPDATE_STATUS_UPDATE_AVAILABLE";
73 case UPDATE_STATUS_DOWNLOADING:
74 return "UPDATE_STATUS_DOWNLOADING";
75 case UPDATE_STATUS_VERIFYING:
76 return "UPDATE_STATUS_VERIFYING";
77 case UPDATE_STATUS_FINALIZING:
78 return "UPDATE_STATUS_FINALIZING";
79 case UPDATE_STATUS_UPDATED_NEED_REBOOT:
80 return "UPDATE_STATUS_UPDATED_NEED_REBOOT";
Darin Petkov09f96c32010-07-20 09:24:57 -070081 case UPDATE_STATUS_REPORTING_ERROR_EVENT:
82 return "UPDATE_STATUS_REPORTING_ERROR_EVENT";
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070083 default:
84 return "unknown status";
85 }
86}
87
Darin Petkov777dbfa2010-07-20 15:03:37 -070088// Turns a generic kActionCodeError to a generic error code specific
89// to |action| (e.g., kActionCodeFilesystemCopierError). If |code| is
90// not kActionCodeError, or the action is not matched, returns |code|
91// unchanged.
92ActionExitCode GetErrorCodeForAction(AbstractAction* action,
93 ActionExitCode code) {
94 if (code != kActionCodeError)
95 return code;
96
97 const string type = action->Type();
98 if (type == OmahaRequestAction::StaticType())
99 return kActionCodeOmahaRequestError;
100 if (type == OmahaResponseHandlerAction::StaticType())
101 return kActionCodeOmahaResponseHandlerError;
102 if (type == FilesystemCopierAction::StaticType())
103 return kActionCodeFilesystemCopierError;
104 if (type == PostinstallRunnerAction::StaticType())
105 return kActionCodePostinstallRunnerError;
Darin Petkov777dbfa2010-07-20 15:03:37 -0700106
107 return code;
108}
109
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800110UpdateAttempter::UpdateAttempter(SystemState* system_state,
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700111 DbusGlibInterface* dbus_iface,
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800112 GpioHandler* gpio_handler)
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700113 : processor_(new ActionProcessor()),
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800114 system_state_(system_state),
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700115 dbus_service_(NULL),
Darin Petkov1023a602010-08-30 13:47:51 -0700116 update_check_scheduler_(NULL),
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700117 fake_update_success_(false),
Darin Petkov1023a602010-08-30 13:47:51 -0700118 http_response_code_(0),
Chris Sosa4f8ee272012-11-30 13:01:54 -0800119 shares_(utils::kCpuSharesNormal),
120 manage_shares_source_(NULL),
Darin Petkov9d911fa2010-08-19 09:36:08 -0700121 download_active_(false),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700122 status_(UPDATE_STATUS_IDLE),
123 download_progress_(0.0),
124 last_checked_time_(0),
125 new_version_("0.0.0.0"),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700126 new_payload_size_(0),
Andrew de los Reyes45168102010-11-22 11:13:50 -0800127 proxy_manual_checks_(0),
128 obeying_proxies_(true),
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700129 chrome_proxy_resolver_(dbus_iface),
Darin Petkov58dd1342011-05-06 12:05:13 -0700130 updated_boot_flags_(false),
131 update_boot_flags_running_(false),
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200132 start_action_processor_(false),
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800133 policy_provider_(NULL),
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700134 is_using_test_url_(false),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700135 is_test_mode_(false),
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700136 is_test_update_attempted_(false),
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800137 gpio_handler_(gpio_handler) {
138 prefs_ = system_state->prefs();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700139 if (utils::FileExists(kUpdateCompletedMarker))
140 status_ = UPDATE_STATUS_UPDATED_NEED_REBOOT;
141}
142
143UpdateAttempter::~UpdateAttempter() {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800144 CleanupCpuSharesManagement();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700145}
146
Gilad Arnold28e2f392012-02-09 14:36:46 -0800147void UpdateAttempter::Update(const string& app_version,
148 const string& omaha_url,
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700149 bool obey_proxies,
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800150 bool interactive,
Gilad Arnold7c04e762012-05-23 10:54:02 -0700151 bool is_test_mode,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700152 bool is_user_initiated) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800153 LOG(INFO) << "Update called";
Andrew de los Reyes000d8952011-03-02 15:21:14 -0800154 chrome_proxy_resolver_.Init();
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700155 fake_update_success_ = false;
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700156 if (status_ == UPDATE_STATUS_UPDATED_NEED_REBOOT) {
Thieu Le116fda32011-04-19 11:01:54 -0700157 // Although we have applied an update, we still want to ping Omaha
158 // to ensure the number of active statistics is accurate.
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700159 LOG(INFO) << "Not updating b/c we already updated and we're waiting for "
Thieu Le116fda32011-04-19 11:01:54 -0700160 << "reboot, we'll ping Omaha instead";
161 PingOmaha();
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700162 return;
163 }
164 if (status_ != UPDATE_STATUS_IDLE) {
165 // Update in progress. Do nothing
166 return;
167 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700168
169 if (!CalculateUpdateParams(app_version,
170 omaha_url,
171 obey_proxies,
172 interactive,
Gilad Arnold7c04e762012-05-23 10:54:02 -0700173 is_test_mode,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700174 is_user_initiated)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700175 return;
176 }
177
178 BuildUpdateActions(interactive);
179
180 SetStatusAndNotify(UPDATE_STATUS_CHECKING_FOR_UPDATE,
181 kUpdateNoticeUnspecified);
182
183 // Just in case we didn't update boot flags yet, make sure they're updated
184 // before any update processing starts.
185 start_action_processor_ = true;
186 UpdateBootFlags();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800187 LOG(INFO) << "Update finished";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700188}
189
190bool UpdateAttempter::CalculateUpdateParams(const string& app_version,
191 const string& omaha_url,
192 bool obey_proxies,
193 bool interactive,
Gilad Arnold7c04e762012-05-23 10:54:02 -0700194 bool is_test_mode,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700195 bool is_user_initiated) {
Darin Petkov1023a602010-08-30 13:47:51 -0700196 http_response_code_ = 0;
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200197
Gilad Arnold7c04e762012-05-23 10:54:02 -0700198 // Set the test mode flag for the current update attempt.
199 is_test_mode_ = is_test_mode;
200
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200201 // Lazy initialize the policy provider, or reload the latest policy data.
202 if (!policy_provider_.get()) {
203 policy_provider_.reset(new policy::PolicyProvider());
204 } else {
205 policy_provider_->Reload();
206 }
207
208 // If the release_track is specified by policy, that takes precedence.
209 string release_track;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700210
Jay Srinivasan0a708742012-03-20 11:26:12 -0700211 if (policy_provider_->device_policy_is_loaded()) {
212 const policy::DevicePolicy& device_policy =
213 policy_provider_->GetDevicePolicy();
214 device_policy.GetReleaseChannel(&release_track);
215 device_policy.GetUpdateDisabled(&omaha_request_params_.update_disabled);
216 device_policy.GetTargetVersionPrefix(
217 &omaha_request_params_.target_version_prefix);
Jay Srinivasan43488792012-06-19 00:25:31 -0700218
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800219 system_state_->set_device_policy(&device_policy);
Jay Srinivasan43488792012-06-19 00:25:31 -0700220
221 set<string> allowed_types;
222 string allowed_types_str;
223 if (device_policy.GetAllowedConnectionTypesForUpdate(&allowed_types)) {
224 set<string>::const_iterator iter;
225 for (iter = allowed_types.begin(); iter != allowed_types.end(); ++iter)
226 allowed_types_str += *iter + " ";
227 }
228
229 LOG(INFO) << "Networks over which updates are allowed per policy : "
230 << (allowed_types_str.empty() ? "all" : allowed_types_str);
231 } else {
232 LOG(INFO) << "No device policies present.";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800233 system_state_->set_device_policy(NULL);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700234 }
235
Jay Srinivasan21be0752012-07-25 15:44:56 -0700236 CalculateScatteringParams(is_user_initiated);
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200237
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800238 // Determine whether an alternative test address should be used.
Gilad Arnold28e2f392012-02-09 14:36:46 -0800239 string omaha_url_to_use = omaha_url;
Gilad Arnold7c04e762012-05-23 10:54:02 -0700240 if ((is_using_test_url_ = (omaha_url_to_use.empty() && is_test_mode_))) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800241 omaha_url_to_use = kTestUpdateUrl;
242 LOG(INFO) << "using alternative server address: " << omaha_url_to_use;
Gilad Arnold28e2f392012-02-09 14:36:46 -0800243 }
244
Jay Srinivasan0a708742012-03-20 11:26:12 -0700245 if (!omaha_request_params_.Init(app_version,
246 omaha_url_to_use,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800247 release_track)) {
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700248 LOG(ERROR) << "Unable to initialize Omaha request device params.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700249 return false;
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700250 }
Darin Petkov3aefa862010-12-07 14:45:00 -0800251
Jay Srinivasan0a708742012-03-20 11:26:12 -0700252 LOG(INFO) << "update_disabled = "
253 << (omaha_request_params_.update_disabled ? "true" : "false")
254 << ", target_version_prefix = "
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700255 << omaha_request_params_.target_version_prefix
256 << ", scatter_factor_in_seconds = "
257 << utils::FormatSecs(scatter_factor_.InSeconds());
258
259 LOG(INFO) << "Wall Clock Based Wait Enabled = "
260 << omaha_request_params_.wall_clock_based_wait_enabled
261 << ", Update Check Count Wait Enabled = "
262 << omaha_request_params_.update_check_count_wait_enabled
Jay Srinivasan21be0752012-07-25 15:44:56 -0700263 << ", Waiting Period = " << utils::FormatSecs(
264 omaha_request_params_.waiting_period.InSeconds());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700265
Andrew de los Reyes45168102010-11-22 11:13:50 -0800266 obeying_proxies_ = true;
267 if (obey_proxies || proxy_manual_checks_ == 0) {
268 LOG(INFO) << "forced to obey proxies";
269 // If forced to obey proxies, every 20th request will not use proxies
270 proxy_manual_checks_++;
271 LOG(INFO) << "proxy manual checks: " << proxy_manual_checks_;
272 if (proxy_manual_checks_ >= kMaxConsecutiveObeyProxyRequests) {
273 proxy_manual_checks_ = 0;
274 obeying_proxies_ = false;
275 }
276 } else if (base::RandInt(0, 4) == 0) {
277 obeying_proxies_ = false;
278 }
279 LOG_IF(INFO, !obeying_proxies_) << "To help ensure updates work, this update "
280 "check we are ignoring the proxy settings and using "
281 "direct connections.";
282
Darin Petkov36275772010-10-01 11:40:57 -0700283 DisableDeltaUpdateIfNeeded();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700284 return true;
285}
286
Jay Srinivasan21be0752012-07-25 15:44:56 -0700287void UpdateAttempter::CalculateScatteringParams(bool is_user_initiated) {
288 // Take a copy of the old scatter value before we update it, as
289 // we need to update the waiting period if this value changes.
290 TimeDelta old_scatter_factor = scatter_factor_;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800291 const policy::DevicePolicy* device_policy = system_state_->device_policy();
Jay Srinivasan21be0752012-07-25 15:44:56 -0700292 if (device_policy) {
293 int64 new_scatter_factor_in_secs = 0;
294 device_policy->GetScatterFactorInSeconds(&new_scatter_factor_in_secs);
295 if (new_scatter_factor_in_secs < 0) // sanitize input, just in case.
296 new_scatter_factor_in_secs = 0;
297 scatter_factor_ = TimeDelta::FromSeconds(new_scatter_factor_in_secs);
298 }
299
300 bool is_scatter_enabled = false;
301 if (scatter_factor_.InSeconds() == 0) {
302 LOG(INFO) << "Scattering disabled since scatter factor is set to 0";
303 } else if (is_user_initiated) {
304 LOG(INFO) << "Scattering disabled as this update check is user-initiated";
305 } else if (!system_state_->IsOOBEComplete()) {
306 LOG(INFO) << "Scattering disabled since OOBE is not complete yet";
307 } else {
308 is_scatter_enabled = true;
309 LOG(INFO) << "Scattering is enabled";
310 }
311
312 if (is_scatter_enabled) {
313 // This means the scattering policy is turned on.
314 // Now check if we need to update the waiting period. The two cases
315 // in which we'd need to update the waiting period are:
316 // 1. First time in process or a scheduled check after a user-initiated one.
317 // (omaha_request_params_.waiting_period will be zero in this case).
318 // 2. Admin has changed the scattering policy value.
319 // (new scattering value will be different from old one in this case).
320 int64 wait_period_in_secs = 0;
321 if (omaha_request_params_.waiting_period.InSeconds() == 0) {
322 // First case. Check if we have a suitable value to set for
323 // the waiting period.
324 if (prefs_->GetInt64(kPrefsWallClockWaitPeriod, &wait_period_in_secs) &&
325 wait_period_in_secs > 0 &&
326 wait_period_in_secs <= scatter_factor_.InSeconds()) {
327 // This means:
328 // 1. There's a persisted value for the waiting period available.
329 // 2. And that persisted value is still valid.
330 // So, in this case, we should reuse the persisted value instead of
331 // generating a new random value to improve the chances of a good
332 // distribution for scattering.
333 omaha_request_params_.waiting_period =
334 TimeDelta::FromSeconds(wait_period_in_secs);
335 LOG(INFO) << "Using persisted wall-clock waiting period: " <<
336 utils::FormatSecs(omaha_request_params_.waiting_period.InSeconds());
337 }
338 else {
339 // This means there's no persisted value for the waiting period
340 // available or its value is invalid given the new scatter_factor value.
341 // So, we should go ahead and regenerate a new value for the
342 // waiting period.
343 LOG(INFO) << "Persisted value not present or not valid ("
344 << utils::FormatSecs(wait_period_in_secs)
345 << ") for wall-clock waiting period.";
346 GenerateNewWaitingPeriod();
347 }
348 } else if (scatter_factor_ != old_scatter_factor) {
349 // This means there's already a waiting period value, but we detected
350 // a change in the scattering policy value. So, we should regenerate the
351 // waiting period to make sure it's within the bounds of the new scatter
352 // factor value.
353 GenerateNewWaitingPeriod();
354 } else {
355 // Neither the first time scattering is enabled nor the scattering value
356 // changed. Nothing to do.
357 LOG(INFO) << "Keeping current wall-clock waiting period: " <<
358 utils::FormatSecs(omaha_request_params_.waiting_period.InSeconds());
359 }
360
361 // The invariant at this point is that omaha_request_params_.waiting_period
362 // is non-zero no matter which path we took above.
363 LOG_IF(ERROR, omaha_request_params_.waiting_period.InSeconds() == 0)
364 << "Waiting Period should NOT be zero at this point!!!";
365
366 // Since scattering is enabled, wall clock based wait will always be
367 // enabled.
368 omaha_request_params_.wall_clock_based_wait_enabled = true;
369
370 // If we don't have any issues in accessing the file system to update
371 // the update check count value, we'll turn that on as well.
372 bool decrement_succeeded = DecrementUpdateCheckCount();
373 omaha_request_params_.update_check_count_wait_enabled = decrement_succeeded;
374 } else {
375 // This means the scattering feature is turned off or disabled for
376 // this particular update check. Make sure to disable
377 // all the knobs and artifacts so that we don't invoke any scattering
378 // related code.
379 omaha_request_params_.wall_clock_based_wait_enabled = false;
380 omaha_request_params_.update_check_count_wait_enabled = false;
381 omaha_request_params_.waiting_period = TimeDelta::FromSeconds(0);
382 prefs_->Delete(kPrefsWallClockWaitPeriod);
383 prefs_->Delete(kPrefsUpdateCheckCount);
384 // Don't delete the UpdateFirstSeenAt file as we don't want manual checks
385 // that result in no-updates (e.g. due to server side throttling) to
386 // cause update starvation by having the client generate a new
387 // UpdateFirstSeenAt for each scheduled check that follows a manual check.
388 }
389}
390
391void UpdateAttempter::GenerateNewWaitingPeriod() {
392 omaha_request_params_.waiting_period = TimeDelta::FromSeconds(
393 base::RandInt(1, scatter_factor_.InSeconds()));
394
395 LOG(INFO) << "Generated new wall-clock waiting period: " << utils::FormatSecs(
396 omaha_request_params_.waiting_period.InSeconds());
397
398 // Do a best-effort to persist this in all cases. Even if the persistence
399 // fails, we'll still be able to scatter based on our in-memory value.
400 // The persistence only helps in ensuring a good overall distribution
401 // across multiple devices if they tend to reboot too often.
402 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
403 omaha_request_params_.waiting_period.InSeconds());
404}
405
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700406void UpdateAttempter::BuildUpdateActions(bool interactive) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700407 CHECK(!processor_->IsRunning());
408 processor_->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700409
410 // Actions:
Darin Petkova0929552010-11-29 14:19:06 -0800411 LibcurlHttpFetcher* update_check_fetcher =
Gilad Arnold7c04e762012-05-23 10:54:02 -0700412 new LibcurlHttpFetcher(GetProxyResolver(), system_state_, is_test_mode_);
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700413 // Try harder to connect to the network, esp when not interactive.
414 // See comment in libcurl_http_fetcher.cc.
415 update_check_fetcher->set_no_network_max_retries(interactive ? 1 : 3);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700416 update_check_fetcher->set_check_certificate(CertificateChecker::kUpdate);
Darin Petkov6a5b3222010-07-13 14:55:28 -0700417 shared_ptr<OmahaRequestAction> update_check_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800418 new OmahaRequestAction(system_state_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700419 &omaha_request_params_,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700420 NULL,
Thieu Le116fda32011-04-19 11:01:54 -0700421 update_check_fetcher, // passes ownership
422 false));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700423 shared_ptr<OmahaResponseHandlerAction> response_handler_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800424 new OmahaResponseHandlerAction(system_state_));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700425 shared_ptr<FilesystemCopierAction> filesystem_copier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700426 new FilesystemCopierAction(false, false));
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700427 shared_ptr<FilesystemCopierAction> kernel_filesystem_copier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700428 new FilesystemCopierAction(true, false));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700429 shared_ptr<OmahaRequestAction> download_started_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800430 new OmahaRequestAction(system_state_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700431 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700432 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700433 OmahaEvent::kTypeUpdateDownloadStarted),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700434 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700435 system_state_,
436 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700437 false));
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700438 LibcurlHttpFetcher* download_fetcher =
Gilad Arnold7c04e762012-05-23 10:54:02 -0700439 new LibcurlHttpFetcher(GetProxyResolver(), system_state_, is_test_mode_);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700440 download_fetcher->set_check_certificate(CertificateChecker::kDownload);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700441 shared_ptr<DownloadAction> download_action(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700442 new DownloadAction(prefs_,
Jay Srinivasanf0572052012-10-23 18:12:56 -0700443 system_state_,
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800444 new MultiRangeHttpFetcher(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700445 download_fetcher))); // passes ownership
Darin Petkov8c2980e2010-07-16 15:16:49 -0700446 shared_ptr<OmahaRequestAction> download_finished_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800447 new OmahaRequestAction(system_state_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700448 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700449 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700450 OmahaEvent::kTypeUpdateDownloadFinished),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700451 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700452 system_state_,
453 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700454 false));
Darin Petkov3aefa862010-12-07 14:45:00 -0800455 shared_ptr<FilesystemCopierAction> filesystem_verifier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700456 new FilesystemCopierAction(false, true));
Darin Petkov3aefa862010-12-07 14:45:00 -0800457 shared_ptr<FilesystemCopierAction> kernel_filesystem_verifier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700458 new FilesystemCopierAction(true, true));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800459 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
460 new PostinstallRunnerAction);
Darin Petkov8c2980e2010-07-16 15:16:49 -0700461 shared_ptr<OmahaRequestAction> update_complete_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800462 new OmahaRequestAction(system_state_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700463 &omaha_request_params_,
Darin Petkove17f86b2010-07-20 09:12:01 -0700464 new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700465 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700466 system_state_,
467 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700468 false));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700469
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700470 download_action->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700471 response_handler_action_ = response_handler_action;
Darin Petkov9b230572010-10-08 10:20:09 -0700472 download_action_ = download_action;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700473
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700474 actions_.push_back(shared_ptr<AbstractAction>(update_check_action));
475 actions_.push_back(shared_ptr<AbstractAction>(response_handler_action));
476 actions_.push_back(shared_ptr<AbstractAction>(filesystem_copier_action));
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700477 actions_.push_back(shared_ptr<AbstractAction>(
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700478 kernel_filesystem_copier_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700479 actions_.push_back(shared_ptr<AbstractAction>(download_started_action));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700480 actions_.push_back(shared_ptr<AbstractAction>(download_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700481 actions_.push_back(shared_ptr<AbstractAction>(download_finished_action));
Darin Petkov3aefa862010-12-07 14:45:00 -0800482 actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action));
483 actions_.push_back(shared_ptr<AbstractAction>(
484 kernel_filesystem_verifier_action));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800485 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700486 actions_.push_back(shared_ptr<AbstractAction>(update_complete_action));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700487
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700488 // Enqueue the actions
489 for (vector<shared_ptr<AbstractAction> >::iterator it = actions_.begin();
490 it != actions_.end(); ++it) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700491 processor_->EnqueueAction(it->get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700492 }
493
494 // Bond them together. We have to use the leaf-types when calling
495 // BondActions().
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700496 BondActions(update_check_action.get(),
497 response_handler_action.get());
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700498 BondActions(response_handler_action.get(),
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700499 filesystem_copier_action.get());
500 BondActions(filesystem_copier_action.get(),
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700501 kernel_filesystem_copier_action.get());
502 BondActions(kernel_filesystem_copier_action.get(),
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700503 download_action.get());
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700504 BondActions(download_action.get(),
Darin Petkov3aefa862010-12-07 14:45:00 -0800505 filesystem_verifier_action.get());
506 BondActions(filesystem_verifier_action.get(),
507 kernel_filesystem_verifier_action.get());
508 BondActions(kernel_filesystem_verifier_action.get(),
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800509 postinstall_runner_action.get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700510}
511
Gilad Arnold28e2f392012-02-09 14:36:46 -0800512void UpdateAttempter::CheckForUpdate(const string& app_version,
Jay Srinivasane73acab2012-07-10 14:34:03 -0700513 const string& omaha_url,
514 bool is_user_initiated) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700515 LOG(INFO) << "New update check requested";
516
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700517 if (status_ != UPDATE_STATUS_IDLE) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700518 LOG(INFO) << "Skipping update check because current status is "
519 << UpdateStatusToString(status_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700520 return;
521 }
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800522
523 // Read GPIO signals and determine whether this is an automated test scenario.
524 // For safety, we only allow a test update to be performed once; subsequent
525 // update requests will be carried out normally.
Gilad Arnold7c04e762012-05-23 10:54:02 -0700526 bool is_test_mode = (!is_test_update_attempted_ && gpio_handler_ &&
527 gpio_handler_->IsTestModeSignaled());
528 if (is_test_mode) {
529 LOG(WARNING) << "this is a test mode update attempt!";
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700530 is_test_update_attempted_ = true;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800531 }
532
Jay Srinivasan08fce042012-06-07 16:31:01 -0700533 // Passing true for is_user_initiated to indicate that this
534 // is not a scheduled update check.
Gilad Arnold7c04e762012-05-23 10:54:02 -0700535 Update(app_version, omaha_url, true, true, is_test_mode, is_user_initiated);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700536}
537
Darin Petkov296889c2010-07-23 16:20:54 -0700538bool UpdateAttempter::RebootIfNeeded() {
539 if (status_ != UPDATE_STATUS_UPDATED_NEED_REBOOT) {
540 LOG(INFO) << "Reboot requested, but status is "
541 << UpdateStatusToString(status_) << ", so not rebooting.";
542 return false;
543 }
544 TEST_AND_RETURN_FALSE(utils::Reboot());
545 return true;
546}
547
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700548// Delegate methods:
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700549void UpdateAttempter::ProcessingDone(const ActionProcessor* processor,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700550 ActionExitCode code) {
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700551 CHECK(response_handler_action_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700552 LOG(INFO) << "Processing Done.";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700553 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700554
Chris Sosa4f8ee272012-11-30 13:01:54 -0800555 // Reset cpu shares back to normal.
556 CleanupCpuSharesManagement();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700557
Darin Petkov09f96c32010-07-20 09:24:57 -0700558 if (status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
559 LOG(INFO) << "Error event sent.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800560
561 // Inform scheduler of new status; also specifically inform about a failed
562 // update attempt with a test address.
563 SetStatusAndNotify(UPDATE_STATUS_IDLE,
564 (is_using_test_url_ ? kUpdateNoticeTestAddrFailed :
565 kUpdateNoticeUnspecified));
566
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700567 if (!fake_update_success_) {
568 return;
569 }
570 LOG(INFO) << "Booted from FW B and tried to install new firmware, "
571 "so requesting reboot from user.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700572 }
573
Darin Petkovc1a8b422010-07-19 11:34:49 -0700574 if (code == kActionCodeSuccess) {
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700575 utils::WriteFile(kUpdateCompletedMarker, "", 0);
Darin Petkov36275772010-10-01 11:40:57 -0700576 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Darin Petkov95508da2011-01-05 12:42:29 -0800577 prefs_->SetString(kPrefsPreviousVersion, omaha_request_params_.app_version);
Darin Petkov9b230572010-10-08 10:20:09 -0700578 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700579
580 // Since we're done with scattering fully at this point, this is the
581 // safest point delete the state files, as we're sure that the status is
582 // set to reboot (which means no more updates will be applied until reboot)
583 // This deletion is required for correctness as we want the next update
584 // check to re-create a new random number for the update check count.
585 // Similarly, we also delete the wall-clock-wait period that was persisted
586 // so that we start with a new random value for the next update check
587 // after reboot so that the same device is not favored or punished in any
588 // way.
589 prefs_->Delete(kPrefsUpdateCheckCount);
590 prefs_->Delete(kPrefsWallClockWaitPeriod);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700591 prefs_->Delete(kPrefsUpdateFirstSeenAt);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700592 LOG(INFO) << "Update successfully applied, waiting to reboot.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700593
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800594 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
595 kUpdateNoticeUnspecified);
Darin Petkov9d65b7b2010-07-20 09:13:01 -0700596
597 // Report the time it took to update the system.
598 int64_t update_time = time(NULL) - last_checked_time_;
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700599 if (!fake_update_success_)
Jay Srinivasanf0572052012-10-23 18:12:56 -0700600 system_state_->metrics_lib()->SendToUMA(
601 "Installer.UpdateTime",
602 static_cast<int>(update_time), // sample
603 1, // min = 1 second
604 20 * 60, // max = 20 minutes
605 50); // buckets
606
607 // Also report the success code so that the percentiles can be
608 // interpreted properly for the remaining error codes in UMA.
Jay Srinivasanedce2832012-10-24 18:57:47 -0700609 utils::SendErrorCodeToUma(system_state_->metrics_lib(), code);
Darin Petkov09f96c32010-07-20 09:24:57 -0700610 return;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700611 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700612
Darin Petkov1023a602010-08-30 13:47:51 -0700613 if (ScheduleErrorEventAction()) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700614 return;
Darin Petkov1023a602010-08-30 13:47:51 -0700615 }
616 LOG(INFO) << "No update.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800617 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700618}
619
620void UpdateAttempter::ProcessingStopped(const ActionProcessor* processor) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800621 // Reset cpu shares back to normal.
622 CleanupCpuSharesManagement();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700623 download_progress_ = 0.0;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800624 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700625 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700626 error_event_.reset(NULL);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700627}
628
629// Called whenever an action has finished processing, either successfully
630// or otherwise.
631void UpdateAttempter::ActionCompleted(ActionProcessor* processor,
632 AbstractAction* action,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700633 ActionExitCode code) {
Darin Petkov1023a602010-08-30 13:47:51 -0700634 // Reset download progress regardless of whether or not the download
635 // action succeeded. Also, get the response code from HTTP request
636 // actions (update download as well as the initial update check
637 // actions).
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700638 const string type = action->Type();
Darin Petkov1023a602010-08-30 13:47:51 -0700639 if (type == DownloadAction::StaticType()) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700640 download_progress_ = 0.0;
Darin Petkov1023a602010-08-30 13:47:51 -0700641 DownloadAction* download_action = dynamic_cast<DownloadAction*>(action);
642 http_response_code_ = download_action->GetHTTPResponseCode();
643 } else if (type == OmahaRequestAction::StaticType()) {
644 OmahaRequestAction* omaha_request_action =
645 dynamic_cast<OmahaRequestAction*>(action);
646 // If the request is not an event, then it's the update-check.
647 if (!omaha_request_action->IsEvent()) {
648 http_response_code_ = omaha_request_action->GetHTTPResponseCode();
Darin Petkov85ced132010-09-01 10:20:56 -0700649 // Forward the server-dictated poll interval to the update check
650 // scheduler, if any.
651 if (update_check_scheduler_) {
652 update_check_scheduler_->set_poll_interval(
653 omaha_request_action->GetOutputObject().poll_interval);
654 }
Darin Petkov1023a602010-08-30 13:47:51 -0700655 }
656 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700657 if (code != kActionCodeSuccess) {
Darin Petkov7ed561b2011-10-04 02:59:03 -0700658 // If the current state is at or past the download phase, count the failure
659 // in case a switch to full update becomes necessary. Ignore network
660 // transfer timeouts and failures.
Darin Petkov36275772010-10-01 11:40:57 -0700661 if (status_ >= UPDATE_STATUS_DOWNLOADING &&
Darin Petkov36275772010-10-01 11:40:57 -0700662 code != kActionCodeDownloadTransferError) {
663 MarkDeltaUpdateFailure();
664 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700665 // On failure, schedule an error event to be sent to Omaha.
666 CreatePendingErrorEvent(action, code);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700667 return;
Darin Petkov09f96c32010-07-20 09:24:57 -0700668 }
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700669 // Find out which action completed.
670 if (type == OmahaResponseHandlerAction::StaticType()) {
Darin Petkov9b230572010-10-08 10:20:09 -0700671 // Note that the status will be updated to DOWNLOADING when some bytes get
672 // actually downloaded from the server and the BytesReceived callback is
673 // invoked. This avoids notifying the user that a download has started in
674 // cases when the server and the client are unable to initiate the download.
675 CHECK(action == response_handler_action_.get());
676 const InstallPlan& plan = response_handler_action_->install_plan();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700677 last_checked_time_ = time(NULL);
678 // TODO(adlr): put version in InstallPlan
679 new_version_ = "0.0.0.0";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700680 new_payload_size_ = plan.payload_size;
Darin Petkov9b230572010-10-08 10:20:09 -0700681 SetupDownload();
Chris Sosa4f8ee272012-11-30 13:01:54 -0800682 SetupCpuSharesManagement();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800683 SetStatusAndNotify(UPDATE_STATUS_UPDATE_AVAILABLE,
684 kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700685 } else if (type == DownloadAction::StaticType()) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800686 SetStatusAndNotify(UPDATE_STATUS_FINALIZING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700687 }
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700688}
689
690// Stop updating. An attempt will be made to record status to the disk
691// so that updates can be resumed later.
692void UpdateAttempter::Terminate() {
693 // TODO(adlr): implement this method.
694 NOTIMPLEMENTED();
695}
696
697// Try to resume from a previously Terminate()d update.
698void UpdateAttempter::ResumeUpdating() {
699 // TODO(adlr): implement this method.
700 NOTIMPLEMENTED();
701}
702
Darin Petkov9d911fa2010-08-19 09:36:08 -0700703void UpdateAttempter::SetDownloadStatus(bool active) {
704 download_active_ = active;
705 LOG(INFO) << "Download status: " << (active ? "active" : "inactive");
706}
707
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700708void UpdateAttempter::BytesReceived(uint64_t bytes_received, uint64_t total) {
Darin Petkov9d911fa2010-08-19 09:36:08 -0700709 if (!download_active_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700710 LOG(ERROR) << "BytesReceived called while not downloading.";
711 return;
712 }
Darin Petkovaf183052010-08-23 12:07:13 -0700713 double progress = static_cast<double>(bytes_received) /
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700714 static_cast<double>(total);
Darin Petkovaf183052010-08-23 12:07:13 -0700715 // Self throttle based on progress. Also send notifications if
716 // progress is too slow.
717 const double kDeltaPercent = 0.01; // 1%
718 if (status_ != UPDATE_STATUS_DOWNLOADING ||
719 bytes_received == total ||
720 progress - download_progress_ >= kDeltaPercent ||
721 TimeTicks::Now() - last_notify_time_ >= TimeDelta::FromSeconds(10)) {
722 download_progress_ = progress;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800723 SetStatusAndNotify(UPDATE_STATUS_DOWNLOADING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700724 }
725}
726
Jay Srinivasanc1ba09a2012-08-14 14:15:57 -0700727bool UpdateAttempter::ResetStatus() {
728 LOG(INFO) << "Attempting to reset state from "
729 << UpdateStatusToString(status_) << " to UPDATE_STATUS_IDLE";
730
731 switch (status_) {
732 case UPDATE_STATUS_IDLE:
733 // no-op.
734 return true;
735
736 case UPDATE_STATUS_UPDATED_NEED_REBOOT: {
737 status_ = UPDATE_STATUS_IDLE;
738 LOG(INFO) << "Reset Successful";
739
740 // also remove the reboot marker so that if the machine is rebooted
741 // after resetting to idle state, it doesn't go back to
742 // UPDATE_STATUS_UPDATED_NEED_REBOOT state.
743 const FilePath kUpdateCompletedMarkerPath(kUpdateCompletedMarker);
744 return file_util::Delete(kUpdateCompletedMarkerPath, false);
745 }
746
747 default:
748 LOG(ERROR) << "Reset not allowed in this state.";
749 return false;
750 }
751}
752
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700753bool UpdateAttempter::GetStatus(int64_t* last_checked_time,
754 double* progress,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800755 string* current_operation,
756 string* new_version,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700757 int64_t* new_payload_size) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700758 *last_checked_time = last_checked_time_;
759 *progress = download_progress_;
760 *current_operation = UpdateStatusToString(status_);
761 *new_version = new_version_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700762 *new_payload_size = new_payload_size_;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700763 return true;
764}
765
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700766void UpdateAttempter::UpdateBootFlags() {
Darin Petkov58dd1342011-05-06 12:05:13 -0700767 if (update_boot_flags_running_) {
768 LOG(INFO) << "Update boot flags running, nothing to do.";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700769 return;
770 }
Darin Petkov58dd1342011-05-06 12:05:13 -0700771 if (updated_boot_flags_) {
772 LOG(INFO) << "Already updated boot flags. Skipping.";
773 if (start_action_processor_) {
774 ScheduleProcessingStart();
775 }
776 return;
777 }
778 // This is purely best effort. Failures should be logged by Subprocess. Run
779 // the script asynchronously to avoid blocking the event loop regardless of
780 // the script runtime.
781 update_boot_flags_running_ = true;
782 LOG(INFO) << "Updating boot flags...";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700783 vector<string> cmd(1, "/usr/sbin/chromeos-setgoodkernel");
Darin Petkov58dd1342011-05-06 12:05:13 -0700784 if (!Subprocess::Get().Exec(cmd, StaticCompleteUpdateBootFlags, this)) {
785 CompleteUpdateBootFlags(1);
786 }
787}
788
789void UpdateAttempter::CompleteUpdateBootFlags(int return_code) {
790 update_boot_flags_running_ = false;
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700791 updated_boot_flags_ = true;
Darin Petkov58dd1342011-05-06 12:05:13 -0700792 if (start_action_processor_) {
793 ScheduleProcessingStart();
794 }
795}
796
797void UpdateAttempter::StaticCompleteUpdateBootFlags(
798 int return_code,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800799 const string& output,
Darin Petkov58dd1342011-05-06 12:05:13 -0700800 void* p) {
801 reinterpret_cast<UpdateAttempter*>(p)->CompleteUpdateBootFlags(return_code);
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700802}
803
Darin Petkov61635a92011-05-18 16:20:36 -0700804void UpdateAttempter::BroadcastStatus() {
805 if (!dbus_service_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700806 return;
Darin Petkov61635a92011-05-18 16:20:36 -0700807 }
Darin Petkovaf183052010-08-23 12:07:13 -0700808 last_notify_time_ = TimeTicks::Now();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700809 update_engine_service_emit_status_update(
810 dbus_service_,
811 last_checked_time_,
812 download_progress_,
813 UpdateStatusToString(status_),
814 new_version_.c_str(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700815 new_payload_size_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700816}
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700817
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800818void UpdateAttempter::SetStatusAndNotify(UpdateStatus status,
819 UpdateNotice notice) {
Darin Petkov61635a92011-05-18 16:20:36 -0700820 status_ = status;
821 if (update_check_scheduler_) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800822 update_check_scheduler_->SetUpdateStatus(status_, notice);
Darin Petkov61635a92011-05-18 16:20:36 -0700823 }
824 BroadcastStatus();
825}
826
Darin Petkov777dbfa2010-07-20 15:03:37 -0700827void UpdateAttempter::CreatePendingErrorEvent(AbstractAction* action,
828 ActionExitCode code) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700829 if (error_event_.get()) {
830 // This shouldn't really happen.
831 LOG(WARNING) << "There's already an existing pending error event.";
832 return;
833 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700834
Darin Petkovabc7bc02011-02-23 14:39:43 -0800835 // For now assume that a generic Omaha response action failure means that
836 // there's no update so don't send an event. Also, double check that the
837 // failure has not occurred while sending an error event -- in which case
838 // don't schedule another. This shouldn't really happen but just in case...
839 if ((action->Type() == OmahaResponseHandlerAction::StaticType() &&
840 code == kActionCodeError) ||
Darin Petkov777dbfa2010-07-20 15:03:37 -0700841 status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
842 return;
843 }
844
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700845 // Classify the code to generate the appropriate result so that
846 // the Borgmon charts show up the results correctly.
847 // Do this before calling GetErrorCodeForAction which could potentially
848 // augment the bit representation of code and thus cause no matches for
849 // the switch cases below.
850 OmahaEvent::Result event_result;
851 switch (code) {
852 case kActionCodeOmahaUpdateIgnoredPerPolicy:
853 case kActionCodeOmahaUpdateDeferredPerPolicy:
854 event_result = OmahaEvent::kResultUpdateDeferred;
855 break;
856 default:
857 event_result = OmahaEvent::kResultError;
858 break;
859 }
860
Darin Petkov777dbfa2010-07-20 15:03:37 -0700861 code = GetErrorCodeForAction(action, code);
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700862 fake_update_success_ = code == kActionCodePostinstallBootedFromFirmwareB;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700863
864 // Apply the bit modifiers to the error code.
865 if (!utils::IsNormalBootMode()) {
866 code = static_cast<ActionExitCode>(code | kActionCodeBootModeFlag);
867 }
868 if (response_handler_action_.get() &&
869 response_handler_action_->install_plan().is_resume) {
870 code = static_cast<ActionExitCode>(code | kActionCodeResumedFlag);
871 }
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700872
Darin Petkov09f96c32010-07-20 09:24:57 -0700873 error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700874 event_result,
Darin Petkov09f96c32010-07-20 09:24:57 -0700875 code));
876}
877
878bool UpdateAttempter::ScheduleErrorEventAction() {
879 if (error_event_.get() == NULL)
880 return false;
881
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800882 LOG(ERROR) << "Update failed.";
883 system_state_->payload_state()->UpdateFailed(error_event_->error_code);
884
885 LOG(INFO) << "Reporting the error event";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700886 utils::SendErrorCodeToUma(system_state_->metrics_lib(),
Jay Srinivasanf0572052012-10-23 18:12:56 -0700887 error_event_->error_code);
Darin Petkov09f96c32010-07-20 09:24:57 -0700888 shared_ptr<OmahaRequestAction> error_event_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800889 new OmahaRequestAction(system_state_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700890 &omaha_request_params_,
Darin Petkov09f96c32010-07-20 09:24:57 -0700891 error_event_.release(), // Pass ownership.
Jay Srinivasan08fce042012-06-07 16:31:01 -0700892 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700893 system_state_,
894 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700895 false));
Darin Petkov09f96c32010-07-20 09:24:57 -0700896 actions_.push_back(shared_ptr<AbstractAction>(error_event_action));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700897 processor_->EnqueueAction(error_event_action.get());
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800898 SetStatusAndNotify(UPDATE_STATUS_REPORTING_ERROR_EVENT,
899 kUpdateNoticeUnspecified);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700900 processor_->StartProcessing();
Darin Petkov09f96c32010-07-20 09:24:57 -0700901 return true;
902}
903
Chris Sosa4f8ee272012-11-30 13:01:54 -0800904void UpdateAttempter::SetCpuShares(utils::CpuShares shares) {
905 if (shares_ == shares) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700906 return;
907 }
Chris Sosa4f8ee272012-11-30 13:01:54 -0800908 if (utils::SetCpuShares(shares)) {
909 shares_ = shares;
910 LOG(INFO) << "CPU shares = " << shares_;
Darin Petkovc6c135c2010-08-11 13:36:18 -0700911 }
912}
913
Chris Sosa4f8ee272012-11-30 13:01:54 -0800914void UpdateAttempter::SetupCpuSharesManagement() {
915 if (manage_shares_source_) {
916 LOG(ERROR) << "Cpu shares timeout source hasn't been destroyed.";
917 CleanupCpuSharesManagement();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700918 }
Chris Sosa4f8ee272012-11-30 13:01:54 -0800919 const int kCpuSharesTimeout = 2 * 60 * 60; // 2 hours
920 manage_shares_source_ = g_timeout_source_new_seconds(kCpuSharesTimeout);
921 g_source_set_callback(manage_shares_source_,
922 StaticManageCpuSharesCallback,
Darin Petkovc6c135c2010-08-11 13:36:18 -0700923 this,
924 NULL);
Chris Sosa4f8ee272012-11-30 13:01:54 -0800925 g_source_attach(manage_shares_source_, NULL);
926 SetCpuShares(utils::kCpuSharesLow);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700927}
928
Chris Sosa4f8ee272012-11-30 13:01:54 -0800929void UpdateAttempter::CleanupCpuSharesManagement() {
930 if (manage_shares_source_) {
931 g_source_destroy(manage_shares_source_);
932 manage_shares_source_ = NULL;
Darin Petkovc6c135c2010-08-11 13:36:18 -0700933 }
Chris Sosa4f8ee272012-11-30 13:01:54 -0800934 SetCpuShares(utils::kCpuSharesNormal);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700935}
936
Chris Sosa4f8ee272012-11-30 13:01:54 -0800937gboolean UpdateAttempter::StaticManageCpuSharesCallback(gpointer data) {
938 return reinterpret_cast<UpdateAttempter*>(data)->ManageCpuSharesCallback();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700939}
940
Darin Petkove6ef2f82011-03-07 17:31:11 -0800941gboolean UpdateAttempter::StaticStartProcessing(gpointer data) {
942 reinterpret_cast<UpdateAttempter*>(data)->processor_->StartProcessing();
943 return FALSE; // Don't call this callback again.
944}
945
Darin Petkov58dd1342011-05-06 12:05:13 -0700946void UpdateAttempter::ScheduleProcessingStart() {
947 LOG(INFO) << "Scheduling an action processor start.";
948 start_action_processor_ = false;
949 g_idle_add(&StaticStartProcessing, this);
950}
951
Chris Sosa4f8ee272012-11-30 13:01:54 -0800952bool UpdateAttempter::ManageCpuSharesCallback() {
953 SetCpuShares(utils::kCpuSharesNormal);
954 manage_shares_source_ = NULL;
Darin Petkovf622ef72010-10-26 13:49:24 -0700955 return false; // Destroy the timeout source.
Darin Petkovc6c135c2010-08-11 13:36:18 -0700956}
957
Darin Petkov36275772010-10-01 11:40:57 -0700958void UpdateAttempter::DisableDeltaUpdateIfNeeded() {
959 int64_t delta_failures;
960 if (omaha_request_params_.delta_okay &&
961 prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) &&
962 delta_failures >= kMaxDeltaUpdateFailures) {
963 LOG(WARNING) << "Too many delta update failures, forcing full update.";
964 omaha_request_params_.delta_okay = false;
965 }
966}
967
968void UpdateAttempter::MarkDeltaUpdateFailure() {
Darin Petkov2dd01092010-10-08 15:43:05 -0700969 // Don't try to resume a failed delta update.
970 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Darin Petkov36275772010-10-01 11:40:57 -0700971 int64_t delta_failures;
972 if (!prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) ||
973 delta_failures < 0) {
974 delta_failures = 0;
975 }
976 prefs_->SetInt64(kPrefsDeltaUpdateFailures, ++delta_failures);
977}
978
Darin Petkov9b230572010-10-08 10:20:09 -0700979void UpdateAttempter::SetupDownload() {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800980 MultiRangeHttpFetcher* fetcher =
981 dynamic_cast<MultiRangeHttpFetcher*>(download_action_->http_fetcher());
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800982 fetcher->ClearRanges();
Darin Petkov9b230572010-10-08 10:20:09 -0700983 if (response_handler_action_->install_plan().is_resume) {
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700984 // Resuming an update so fetch the update manifest metadata first.
Darin Petkov9b230572010-10-08 10:20:09 -0700985 int64_t manifest_metadata_size = 0;
986 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800987 fetcher->AddRange(0, manifest_metadata_size);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700988 // If there're remaining unprocessed data blobs, fetch them. Be careful not
989 // to request data beyond the end of the payload to avoid 416 HTTP response
990 // error codes.
Darin Petkov9b230572010-10-08 10:20:09 -0700991 int64_t next_data_offset = 0;
992 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700993 uint64_t resume_offset = manifest_metadata_size + next_data_offset;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700994 if (resume_offset < response_handler_action_->install_plan().payload_size) {
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800995 fetcher->AddRange(resume_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700996 }
Darin Petkov9b230572010-10-08 10:20:09 -0700997 } else {
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800998 fetcher->AddRange(0);
Darin Petkov9b230572010-10-08 10:20:09 -0700999 }
Darin Petkov9b230572010-10-08 10:20:09 -07001000}
1001
Thieu Le116fda32011-04-19 11:01:54 -07001002void UpdateAttempter::PingOmaha() {
Thieu Led88a8572011-05-26 09:09:19 -07001003 if (!processor_->IsRunning()) {
1004 shared_ptr<OmahaRequestAction> ping_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001005 new OmahaRequestAction(system_state_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001006 &omaha_request_params_,
Thieu Led88a8572011-05-26 09:09:19 -07001007 NULL,
Jay Srinivasan08fce042012-06-07 16:31:01 -07001008 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -07001009 system_state_,
1010 is_test_mode_),
Thieu Led88a8572011-05-26 09:09:19 -07001011 true));
1012 actions_.push_back(shared_ptr<OmahaRequestAction>(ping_action));
1013 processor_->set_delegate(NULL);
1014 processor_->EnqueueAction(ping_action.get());
1015 // Call StartProcessing() synchronously here to avoid any race conditions
1016 // caused by multiple outstanding ping Omaha requests. If we call
1017 // StartProcessing() asynchronously, the device can be suspended before we
1018 // get a chance to callback to StartProcessing(). When the device resumes
1019 // (assuming the device sleeps longer than the next update check period),
1020 // StartProcessing() is called back and at the same time, the next update
1021 // check is fired which eventually invokes StartProcessing(). A crash
1022 // can occur because StartProcessing() checks to make sure that the
1023 // processor is idle which it isn't due to the two concurrent ping Omaha
1024 // requests.
1025 processor_->StartProcessing();
1026 } else {
Darin Petkov58dd1342011-05-06 12:05:13 -07001027 LOG(WARNING) << "Action processor running, Omaha ping suppressed.";
Darin Petkov58dd1342011-05-06 12:05:13 -07001028 }
Thieu Led88a8572011-05-26 09:09:19 -07001029
1030 // Update the status which will schedule the next update check
Gilad Arnold1ebd8132012-03-05 10:19:29 -08001031 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
1032 kUpdateNoticeUnspecified);
Thieu Le116fda32011-04-19 11:01:54 -07001033}
1034
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001035
1036bool UpdateAttempter::DecrementUpdateCheckCount() {
1037 int64 update_check_count_value;
1038
1039 if (!prefs_->Exists(kPrefsUpdateCheckCount)) {
1040 // This file does not exist. This means we haven't started our update
1041 // check count down yet, so nothing more to do. This file will be created
1042 // later when we first satisfy the wall-clock-based-wait period.
1043 LOG(INFO) << "No existing update check count. That's normal.";
1044 return true;
1045 }
1046
1047 if (prefs_->GetInt64(kPrefsUpdateCheckCount, &update_check_count_value)) {
1048 // Only if we're able to read a proper integer value, then go ahead
1049 // and decrement and write back the result in the same file, if needed.
1050 LOG(INFO) << "Update check count = " << update_check_count_value;
1051
1052 if (update_check_count_value == 0) {
1053 // It could be 0, if, for some reason, the file didn't get deleted
1054 // when we set our status to waiting for reboot. so we just leave it
1055 // as is so that we can prevent another update_check wait for this client.
1056 LOG(INFO) << "Not decrementing update check count as it's already 0.";
1057 return true;
1058 }
1059
1060 if (update_check_count_value > 0)
1061 update_check_count_value--;
1062 else
1063 update_check_count_value = 0;
1064
1065 // Write out the new value of update_check_count_value.
1066 if (prefs_->SetInt64(kPrefsUpdateCheckCount, update_check_count_value)) {
1067 // We successfully wrote out te new value, so enable the
1068 // update check based wait.
1069 LOG(INFO) << "New update check count = " << update_check_count_value;
1070 return true;
1071 }
1072 }
1073
1074 LOG(INFO) << "Deleting update check count state due to read/write errors.";
1075
1076 // We cannot read/write to the file, so disable the update check based wait
1077 // so that we don't get stuck in this OS version by any chance (which could
1078 // happen if there's some bug that causes to read/write incorrectly).
1079 // Also attempt to delete the file to do our best effort to cleanup.
1080 prefs_->Delete(kPrefsUpdateCheckCount);
1081 return false;
1082}
1083
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07001084} // namespace chromeos_update_engine