blob: b2cbe4cb27d76c9f0b651bc4b666a7d702b01b67 [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"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080028#include "update_engine/gpio_handler.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070029#include "update_engine/libcurl_http_fetcher.h"
Andrew de los Reyes819fef22010-12-17 11:33:58 -080030#include "update_engine/multi_range_http_fetcher.h"
Darin Petkov6a5b3222010-07-13 14:55:28 -070031#include "update_engine/omaha_request_action.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070032#include "update_engine/omaha_request_params.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070033#include "update_engine/omaha_response_handler_action.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080034#include "update_engine/payload_state_interface.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070035#include "update_engine/postinstall_runner_action.h"
Darin Petkov36275772010-10-01 11:40:57 -070036#include "update_engine/prefs_interface.h"
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -070037#include "update_engine/subprocess.h"
Jay Srinivasan43488792012-06-19 00:25:31 -070038#include "update_engine/system_state.h"
Darin Petkov1023a602010-08-30 13:47:51 -070039#include "update_engine/update_check_scheduler.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070040
Darin Petkovaf183052010-08-23 12:07:13 -070041using base::TimeDelta;
42using base::TimeTicks;
Andrew de los Reyes21816e12011-04-07 14:18:56 -070043using google::protobuf::NewPermanentCallback;
Darin Petkov9b230572010-10-08 10:20:09 -070044using std::make_pair;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070045using std::tr1::shared_ptr;
Jay Srinivasan43488792012-06-19 00:25:31 -070046using std::set;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070047using std::string;
48using std::vector;
49
50namespace chromeos_update_engine {
51
Darin Petkov36275772010-10-01 11:40:57 -070052const int UpdateAttempter::kMaxDeltaUpdateFailures = 3;
53
Gilad Arnold1ebd8132012-03-05 10:19:29 -080054// Private test server URL w/ custom port number.
Gilad Arnolded747312012-03-15 18:20:41 -070055// TODO(garnold) This is a temporary hack to allow us to test the closed loop
56// automated update testing. To be replaced with an hard-coded local IP address.
57const char* const UpdateAttempter::kTestUpdateUrl(
58 "http://garnold.mtv.corp.google.com:8080/update");
Gilad Arnold28e2f392012-02-09 14:36:46 -080059
Darin Petkovcd1666f2010-09-23 09:53:44 -070060const char* kUpdateCompletedMarker =
61 "/var/run/update_engine_autoupdate_completed";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -070062
Andrew de los Reyes45168102010-11-22 11:13:50 -080063namespace {
64const int kMaxConsecutiveObeyProxyRequests = 20;
65} // namespace {}
66
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070067const char* UpdateStatusToString(UpdateStatus status) {
68 switch (status) {
69 case UPDATE_STATUS_IDLE:
70 return "UPDATE_STATUS_IDLE";
71 case UPDATE_STATUS_CHECKING_FOR_UPDATE:
72 return "UPDATE_STATUS_CHECKING_FOR_UPDATE";
73 case UPDATE_STATUS_UPDATE_AVAILABLE:
74 return "UPDATE_STATUS_UPDATE_AVAILABLE";
75 case UPDATE_STATUS_DOWNLOADING:
76 return "UPDATE_STATUS_DOWNLOADING";
77 case UPDATE_STATUS_VERIFYING:
78 return "UPDATE_STATUS_VERIFYING";
79 case UPDATE_STATUS_FINALIZING:
80 return "UPDATE_STATUS_FINALIZING";
81 case UPDATE_STATUS_UPDATED_NEED_REBOOT:
82 return "UPDATE_STATUS_UPDATED_NEED_REBOOT";
Darin Petkov09f96c32010-07-20 09:24:57 -070083 case UPDATE_STATUS_REPORTING_ERROR_EVENT:
84 return "UPDATE_STATUS_REPORTING_ERROR_EVENT";
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070085 default:
86 return "unknown status";
87 }
88}
89
Darin Petkov777dbfa2010-07-20 15:03:37 -070090// Turns a generic kActionCodeError to a generic error code specific
91// to |action| (e.g., kActionCodeFilesystemCopierError). If |code| is
92// not kActionCodeError, or the action is not matched, returns |code|
93// unchanged.
94ActionExitCode GetErrorCodeForAction(AbstractAction* action,
95 ActionExitCode code) {
96 if (code != kActionCodeError)
97 return code;
98
99 const string type = action->Type();
100 if (type == OmahaRequestAction::StaticType())
101 return kActionCodeOmahaRequestError;
102 if (type == OmahaResponseHandlerAction::StaticType())
103 return kActionCodeOmahaResponseHandlerError;
104 if (type == FilesystemCopierAction::StaticType())
105 return kActionCodeFilesystemCopierError;
106 if (type == PostinstallRunnerAction::StaticType())
107 return kActionCodePostinstallRunnerError;
Darin Petkov777dbfa2010-07-20 15:03:37 -0700108
109 return code;
110}
111
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800112UpdateAttempter::UpdateAttempter(SystemState* system_state,
Gilad Arnoldbf7919b2013-01-08 13:07:37 -0800113 DbusGlibInterface* dbus_iface)
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700114 : processor_(new ActionProcessor()),
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800115 system_state_(system_state),
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700116 dbus_service_(NULL),
Darin Petkov1023a602010-08-30 13:47:51 -0700117 update_check_scheduler_(NULL),
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700118 fake_update_success_(false),
Darin Petkov1023a602010-08-30 13:47:51 -0700119 http_response_code_(0),
Chris Sosa4f8ee272012-11-30 13:01:54 -0800120 shares_(utils::kCpuSharesNormal),
121 manage_shares_source_(NULL),
Darin Petkov9d911fa2010-08-19 09:36:08 -0700122 download_active_(false),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700123 status_(UPDATE_STATUS_IDLE),
124 download_progress_(0.0),
125 last_checked_time_(0),
126 new_version_("0.0.0.0"),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700127 new_payload_size_(0),
Andrew de los Reyes45168102010-11-22 11:13:50 -0800128 proxy_manual_checks_(0),
129 obeying_proxies_(true),
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700130 chrome_proxy_resolver_(dbus_iface),
Darin Petkov58dd1342011-05-06 12:05:13 -0700131 updated_boot_flags_(false),
132 update_boot_flags_running_(false),
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200133 start_action_processor_(false),
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800134 policy_provider_(NULL),
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700135 is_using_test_url_(false),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700136 is_test_mode_(false),
Gilad Arnoldbf7919b2013-01-08 13:07:37 -0800137 is_test_update_attempted_(false) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800138 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) {
Andrew de los Reyes000d8952011-03-02 15:21:14 -0800153 chrome_proxy_resolver_.Init();
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700154 fake_update_success_ = false;
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700155 if (status_ == UPDATE_STATUS_UPDATED_NEED_REBOOT) {
Thieu Le116fda32011-04-19 11:01:54 -0700156 // Although we have applied an update, we still want to ping Omaha
157 // to ensure the number of active statistics is accurate.
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700158 LOG(INFO) << "Not updating b/c we already updated and we're waiting for "
Thieu Le116fda32011-04-19 11:01:54 -0700159 << "reboot, we'll ping Omaha instead";
160 PingOmaha();
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700161 return;
162 }
163 if (status_ != UPDATE_STATUS_IDLE) {
164 // Update in progress. Do nothing
165 return;
166 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700167
168 if (!CalculateUpdateParams(app_version,
169 omaha_url,
170 obey_proxies,
171 interactive,
Gilad Arnold7c04e762012-05-23 10:54:02 -0700172 is_test_mode,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700173 is_user_initiated)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700174 return;
175 }
176
177 BuildUpdateActions(interactive);
178
179 SetStatusAndNotify(UPDATE_STATUS_CHECKING_FOR_UPDATE,
180 kUpdateNoticeUnspecified);
181
182 // Just in case we didn't update boot flags yet, make sure they're updated
183 // before any update processing starts.
184 start_action_processor_ = true;
185 UpdateBootFlags();
186}
187
188bool UpdateAttempter::CalculateUpdateParams(const string& app_version,
189 const string& omaha_url,
190 bool obey_proxies,
191 bool interactive,
Gilad Arnold7c04e762012-05-23 10:54:02 -0700192 bool is_test_mode,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700193 bool is_user_initiated) {
Darin Petkov1023a602010-08-30 13:47:51 -0700194 http_response_code_ = 0;
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200195
Gilad Arnold7c04e762012-05-23 10:54:02 -0700196 // Set the test mode flag for the current update attempt.
197 is_test_mode_ = is_test_mode;
198
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200199 // Lazy initialize the policy provider, or reload the latest policy data.
200 if (!policy_provider_.get()) {
201 policy_provider_.reset(new policy::PolicyProvider());
202 } else {
203 policy_provider_->Reload();
204 }
205
206 // If the release_track is specified by policy, that takes precedence.
207 string release_track;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700208
Jay Srinivasan0a708742012-03-20 11:26:12 -0700209 if (policy_provider_->device_policy_is_loaded()) {
210 const policy::DevicePolicy& device_policy =
211 policy_provider_->GetDevicePolicy();
212 device_policy.GetReleaseChannel(&release_track);
213 device_policy.GetUpdateDisabled(&omaha_request_params_.update_disabled);
214 device_policy.GetTargetVersionPrefix(
215 &omaha_request_params_.target_version_prefix);
Jay Srinivasan43488792012-06-19 00:25:31 -0700216
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800217 system_state_->set_device_policy(&device_policy);
Jay Srinivasan43488792012-06-19 00:25:31 -0700218
219 set<string> allowed_types;
220 string allowed_types_str;
221 if (device_policy.GetAllowedConnectionTypesForUpdate(&allowed_types)) {
222 set<string>::const_iterator iter;
223 for (iter = allowed_types.begin(); iter != allowed_types.end(); ++iter)
224 allowed_types_str += *iter + " ";
225 }
226
227 LOG(INFO) << "Networks over which updates are allowed per policy : "
228 << (allowed_types_str.empty() ? "all" : allowed_types_str);
229 } else {
230 LOG(INFO) << "No device policies present.";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800231 system_state_->set_device_policy(NULL);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700232 }
233
Jay Srinivasan21be0752012-07-25 15:44:56 -0700234 CalculateScatteringParams(is_user_initiated);
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200235
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800236 // Determine whether an alternative test address should be used.
Gilad Arnold28e2f392012-02-09 14:36:46 -0800237 string omaha_url_to_use = omaha_url;
Gilad Arnold7c04e762012-05-23 10:54:02 -0700238 if ((is_using_test_url_ = (omaha_url_to_use.empty() && is_test_mode_))) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800239 omaha_url_to_use = kTestUpdateUrl;
240 LOG(INFO) << "using alternative server address: " << omaha_url_to_use;
Gilad Arnold28e2f392012-02-09 14:36:46 -0800241 }
242
Jay Srinivasan0a708742012-03-20 11:26:12 -0700243 if (!omaha_request_params_.Init(app_version,
244 omaha_url_to_use,
Gilad Arnoldbbdd4902013-01-10 16:06:30 -0800245 release_track,
246 interactive)) {
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700247 LOG(ERROR) << "Unable to initialize Omaha request device params.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700248 return false;
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700249 }
Darin Petkov3aefa862010-12-07 14:45:00 -0800250
Jay Srinivasan0a708742012-03-20 11:26:12 -0700251 LOG(INFO) << "update_disabled = "
252 << (omaha_request_params_.update_disabled ? "true" : "false")
253 << ", target_version_prefix = "
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700254 << omaha_request_params_.target_version_prefix
255 << ", scatter_factor_in_seconds = "
256 << utils::FormatSecs(scatter_factor_.InSeconds());
257
258 LOG(INFO) << "Wall Clock Based Wait Enabled = "
259 << omaha_request_params_.wall_clock_based_wait_enabled
260 << ", Update Check Count Wait Enabled = "
261 << omaha_request_params_.update_check_count_wait_enabled
Jay Srinivasan21be0752012-07-25 15:44:56 -0700262 << ", Waiting Period = " << utils::FormatSecs(
263 omaha_request_params_.waiting_period.InSeconds());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700264
Andrew de los Reyes45168102010-11-22 11:13:50 -0800265 obeying_proxies_ = true;
266 if (obey_proxies || proxy_manual_checks_ == 0) {
267 LOG(INFO) << "forced to obey proxies";
268 // If forced to obey proxies, every 20th request will not use proxies
269 proxy_manual_checks_++;
270 LOG(INFO) << "proxy manual checks: " << proxy_manual_checks_;
271 if (proxy_manual_checks_ >= kMaxConsecutiveObeyProxyRequests) {
272 proxy_manual_checks_ = 0;
273 obeying_proxies_ = false;
274 }
275 } else if (base::RandInt(0, 4) == 0) {
276 obeying_proxies_ = false;
277 }
278 LOG_IF(INFO, !obeying_proxies_) << "To help ensure updates work, this update "
279 "check we are ignoring the proxy settings and using "
280 "direct connections.";
281
Darin Petkov36275772010-10-01 11:40:57 -0700282 DisableDeltaUpdateIfNeeded();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700283 return true;
284}
285
Jay Srinivasan21be0752012-07-25 15:44:56 -0700286void UpdateAttempter::CalculateScatteringParams(bool is_user_initiated) {
287 // Take a copy of the old scatter value before we update it, as
288 // we need to update the waiting period if this value changes.
289 TimeDelta old_scatter_factor = scatter_factor_;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800290 const policy::DevicePolicy* device_policy = system_state_->device_policy();
Jay Srinivasan21be0752012-07-25 15:44:56 -0700291 if (device_policy) {
292 int64 new_scatter_factor_in_secs = 0;
293 device_policy->GetScatterFactorInSeconds(&new_scatter_factor_in_secs);
294 if (new_scatter_factor_in_secs < 0) // sanitize input, just in case.
295 new_scatter_factor_in_secs = 0;
296 scatter_factor_ = TimeDelta::FromSeconds(new_scatter_factor_in_secs);
297 }
298
299 bool is_scatter_enabled = false;
300 if (scatter_factor_.InSeconds() == 0) {
301 LOG(INFO) << "Scattering disabled since scatter factor is set to 0";
302 } else if (is_user_initiated) {
303 LOG(INFO) << "Scattering disabled as this update check is user-initiated";
304 } else if (!system_state_->IsOOBEComplete()) {
305 LOG(INFO) << "Scattering disabled since OOBE is not complete yet";
306 } else {
307 is_scatter_enabled = true;
308 LOG(INFO) << "Scattering is enabled";
309 }
310
311 if (is_scatter_enabled) {
312 // This means the scattering policy is turned on.
313 // Now check if we need to update the waiting period. The two cases
314 // in which we'd need to update the waiting period are:
315 // 1. First time in process or a scheduled check after a user-initiated one.
316 // (omaha_request_params_.waiting_period will be zero in this case).
317 // 2. Admin has changed the scattering policy value.
318 // (new scattering value will be different from old one in this case).
319 int64 wait_period_in_secs = 0;
320 if (omaha_request_params_.waiting_period.InSeconds() == 0) {
321 // First case. Check if we have a suitable value to set for
322 // the waiting period.
323 if (prefs_->GetInt64(kPrefsWallClockWaitPeriod, &wait_period_in_secs) &&
324 wait_period_in_secs > 0 &&
325 wait_period_in_secs <= scatter_factor_.InSeconds()) {
326 // This means:
327 // 1. There's a persisted value for the waiting period available.
328 // 2. And that persisted value is still valid.
329 // So, in this case, we should reuse the persisted value instead of
330 // generating a new random value to improve the chances of a good
331 // distribution for scattering.
332 omaha_request_params_.waiting_period =
333 TimeDelta::FromSeconds(wait_period_in_secs);
334 LOG(INFO) << "Using persisted wall-clock waiting period: " <<
335 utils::FormatSecs(omaha_request_params_.waiting_period.InSeconds());
336 }
337 else {
338 // This means there's no persisted value for the waiting period
339 // available or its value is invalid given the new scatter_factor value.
340 // So, we should go ahead and regenerate a new value for the
341 // waiting period.
342 LOG(INFO) << "Persisted value not present or not valid ("
343 << utils::FormatSecs(wait_period_in_secs)
344 << ") for wall-clock waiting period.";
345 GenerateNewWaitingPeriod();
346 }
347 } else if (scatter_factor_ != old_scatter_factor) {
348 // This means there's already a waiting period value, but we detected
349 // a change in the scattering policy value. So, we should regenerate the
350 // waiting period to make sure it's within the bounds of the new scatter
351 // factor value.
352 GenerateNewWaitingPeriod();
353 } else {
354 // Neither the first time scattering is enabled nor the scattering value
355 // changed. Nothing to do.
356 LOG(INFO) << "Keeping current wall-clock waiting period: " <<
357 utils::FormatSecs(omaha_request_params_.waiting_period.InSeconds());
358 }
359
360 // The invariant at this point is that omaha_request_params_.waiting_period
361 // is non-zero no matter which path we took above.
362 LOG_IF(ERROR, omaha_request_params_.waiting_period.InSeconds() == 0)
363 << "Waiting Period should NOT be zero at this point!!!";
364
365 // Since scattering is enabled, wall clock based wait will always be
366 // enabled.
367 omaha_request_params_.wall_clock_based_wait_enabled = true;
368
369 // If we don't have any issues in accessing the file system to update
370 // the update check count value, we'll turn that on as well.
371 bool decrement_succeeded = DecrementUpdateCheckCount();
372 omaha_request_params_.update_check_count_wait_enabled = decrement_succeeded;
373 } else {
374 // This means the scattering feature is turned off or disabled for
375 // this particular update check. Make sure to disable
376 // all the knobs and artifacts so that we don't invoke any scattering
377 // related code.
378 omaha_request_params_.wall_clock_based_wait_enabled = false;
379 omaha_request_params_.update_check_count_wait_enabled = false;
380 omaha_request_params_.waiting_period = TimeDelta::FromSeconds(0);
381 prefs_->Delete(kPrefsWallClockWaitPeriod);
382 prefs_->Delete(kPrefsUpdateCheckCount);
383 // Don't delete the UpdateFirstSeenAt file as we don't want manual checks
384 // that result in no-updates (e.g. due to server side throttling) to
385 // cause update starvation by having the client generate a new
386 // UpdateFirstSeenAt for each scheduled check that follows a manual check.
387 }
388}
389
390void UpdateAttempter::GenerateNewWaitingPeriod() {
391 omaha_request_params_.waiting_period = TimeDelta::FromSeconds(
392 base::RandInt(1, scatter_factor_.InSeconds()));
393
394 LOG(INFO) << "Generated new wall-clock waiting period: " << utils::FormatSecs(
395 omaha_request_params_.waiting_period.InSeconds());
396
397 // Do a best-effort to persist this in all cases. Even if the persistence
398 // fails, we'll still be able to scatter based on our in-memory value.
399 // The persistence only helps in ensuring a good overall distribution
400 // across multiple devices if they tend to reboot too often.
401 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
402 omaha_request_params_.waiting_period.InSeconds());
403}
404
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700405void UpdateAttempter::BuildUpdateActions(bool interactive) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700406 CHECK(!processor_->IsRunning());
407 processor_->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700408
409 // Actions:
Darin Petkova0929552010-11-29 14:19:06 -0800410 LibcurlHttpFetcher* update_check_fetcher =
Gilad Arnold7c04e762012-05-23 10:54:02 -0700411 new LibcurlHttpFetcher(GetProxyResolver(), system_state_, is_test_mode_);
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700412 // Try harder to connect to the network, esp when not interactive.
413 // See comment in libcurl_http_fetcher.cc.
414 update_check_fetcher->set_no_network_max_retries(interactive ? 1 : 3);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700415 update_check_fetcher->set_check_certificate(CertificateChecker::kUpdate);
Darin Petkov6a5b3222010-07-13 14:55:28 -0700416 shared_ptr<OmahaRequestAction> update_check_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800417 new OmahaRequestAction(system_state_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700418 &omaha_request_params_,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700419 NULL,
Thieu Le116fda32011-04-19 11:01:54 -0700420 update_check_fetcher, // passes ownership
421 false));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700422 shared_ptr<OmahaResponseHandlerAction> response_handler_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800423 new OmahaResponseHandlerAction(system_state_));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700424 shared_ptr<FilesystemCopierAction> filesystem_copier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700425 new FilesystemCopierAction(false, false));
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700426 shared_ptr<FilesystemCopierAction> kernel_filesystem_copier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700427 new FilesystemCopierAction(true, false));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700428 shared_ptr<OmahaRequestAction> download_started_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800429 new OmahaRequestAction(system_state_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700430 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700431 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700432 OmahaEvent::kTypeUpdateDownloadStarted),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700433 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700434 system_state_,
435 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700436 false));
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700437 LibcurlHttpFetcher* download_fetcher =
Gilad Arnold7c04e762012-05-23 10:54:02 -0700438 new LibcurlHttpFetcher(GetProxyResolver(), system_state_, is_test_mode_);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700439 download_fetcher->set_check_certificate(CertificateChecker::kDownload);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700440 shared_ptr<DownloadAction> download_action(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700441 new DownloadAction(prefs_,
Jay Srinivasanf0572052012-10-23 18:12:56 -0700442 system_state_,
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800443 new MultiRangeHttpFetcher(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700444 download_fetcher))); // passes ownership
Darin Petkov8c2980e2010-07-16 15:16:49 -0700445 shared_ptr<OmahaRequestAction> download_finished_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800446 new OmahaRequestAction(system_state_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700447 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700448 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700449 OmahaEvent::kTypeUpdateDownloadFinished),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700450 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700451 system_state_,
452 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700453 false));
Darin Petkov3aefa862010-12-07 14:45:00 -0800454 shared_ptr<FilesystemCopierAction> filesystem_verifier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700455 new FilesystemCopierAction(false, true));
Darin Petkov3aefa862010-12-07 14:45:00 -0800456 shared_ptr<FilesystemCopierAction> kernel_filesystem_verifier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700457 new FilesystemCopierAction(true, true));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800458 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
459 new PostinstallRunnerAction);
Darin Petkov8c2980e2010-07-16 15:16:49 -0700460 shared_ptr<OmahaRequestAction> update_complete_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800461 new OmahaRequestAction(system_state_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700462 &omaha_request_params_,
Darin Petkove17f86b2010-07-20 09:12:01 -0700463 new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700464 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700465 system_state_,
466 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700467 false));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700468
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700469 download_action->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700470 response_handler_action_ = response_handler_action;
Darin Petkov9b230572010-10-08 10:20:09 -0700471 download_action_ = download_action;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700472
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700473 actions_.push_back(shared_ptr<AbstractAction>(update_check_action));
474 actions_.push_back(shared_ptr<AbstractAction>(response_handler_action));
475 actions_.push_back(shared_ptr<AbstractAction>(filesystem_copier_action));
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700476 actions_.push_back(shared_ptr<AbstractAction>(
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700477 kernel_filesystem_copier_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700478 actions_.push_back(shared_ptr<AbstractAction>(download_started_action));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700479 actions_.push_back(shared_ptr<AbstractAction>(download_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700480 actions_.push_back(shared_ptr<AbstractAction>(download_finished_action));
Darin Petkov3aefa862010-12-07 14:45:00 -0800481 actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action));
482 actions_.push_back(shared_ptr<AbstractAction>(
483 kernel_filesystem_verifier_action));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800484 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700485 actions_.push_back(shared_ptr<AbstractAction>(update_complete_action));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700486
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700487 // Enqueue the actions
488 for (vector<shared_ptr<AbstractAction> >::iterator it = actions_.begin();
489 it != actions_.end(); ++it) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700490 processor_->EnqueueAction(it->get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700491 }
492
493 // Bond them together. We have to use the leaf-types when calling
494 // BondActions().
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700495 BondActions(update_check_action.get(),
496 response_handler_action.get());
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700497 BondActions(response_handler_action.get(),
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700498 filesystem_copier_action.get());
499 BondActions(filesystem_copier_action.get(),
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700500 kernel_filesystem_copier_action.get());
501 BondActions(kernel_filesystem_copier_action.get(),
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700502 download_action.get());
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700503 BondActions(download_action.get(),
Darin Petkov3aefa862010-12-07 14:45:00 -0800504 filesystem_verifier_action.get());
505 BondActions(filesystem_verifier_action.get(),
506 kernel_filesystem_verifier_action.get());
507 BondActions(kernel_filesystem_verifier_action.get(),
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800508 postinstall_runner_action.get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700509}
510
Gilad Arnold28e2f392012-02-09 14:36:46 -0800511void UpdateAttempter::CheckForUpdate(const string& app_version,
Jay Srinivasane73acab2012-07-10 14:34:03 -0700512 const string& omaha_url,
513 bool is_user_initiated) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700514 LOG(INFO) << "New update check requested";
515
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700516 if (status_ != UPDATE_STATUS_IDLE) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700517 LOG(INFO) << "Skipping update check because current status is "
518 << UpdateStatusToString(status_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700519 return;
520 }
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800521
522 // Read GPIO signals and determine whether this is an automated test scenario.
523 // For safety, we only allow a test update to be performed once; subsequent
524 // update requests will be carried out normally.
Gilad Arnoldbf7919b2013-01-08 13:07:37 -0800525 bool is_test_mode = (!is_test_update_attempted_ &&
526 system_state_->gpio_handler()->IsTestModeSignaled());
Gilad Arnold7c04e762012-05-23 10:54:02 -0700527 if (is_test_mode) {
528 LOG(WARNING) << "this is a test mode update attempt!";
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700529 is_test_update_attempted_ = true;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800530 }
531
Jay Srinivasan08fce042012-06-07 16:31:01 -0700532 // Passing true for is_user_initiated to indicate that this
533 // is not a scheduled update check.
Gilad Arnold7c04e762012-05-23 10:54:02 -0700534 Update(app_version, omaha_url, true, true, is_test_mode, is_user_initiated);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700535}
536
Darin Petkov296889c2010-07-23 16:20:54 -0700537bool UpdateAttempter::RebootIfNeeded() {
538 if (status_ != UPDATE_STATUS_UPDATED_NEED_REBOOT) {
539 LOG(INFO) << "Reboot requested, but status is "
540 << UpdateStatusToString(status_) << ", so not rebooting.";
541 return false;
542 }
543 TEST_AND_RETURN_FALSE(utils::Reboot());
544 return true;
545}
546
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700547// Delegate methods:
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700548void UpdateAttempter::ProcessingDone(const ActionProcessor* processor,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700549 ActionExitCode code) {
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700550 CHECK(response_handler_action_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700551 LOG(INFO) << "Processing Done.";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700552 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700553
Chris Sosa4f8ee272012-11-30 13:01:54 -0800554 // Reset cpu shares back to normal.
555 CleanupCpuSharesManagement();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700556
Darin Petkov09f96c32010-07-20 09:24:57 -0700557 if (status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
558 LOG(INFO) << "Error event sent.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800559
560 // Inform scheduler of new status; also specifically inform about a failed
561 // update attempt with a test address.
562 SetStatusAndNotify(UPDATE_STATUS_IDLE,
563 (is_using_test_url_ ? kUpdateNoticeTestAddrFailed :
564 kUpdateNoticeUnspecified));
565
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700566 if (!fake_update_success_) {
567 return;
568 }
569 LOG(INFO) << "Booted from FW B and tried to install new firmware, "
570 "so requesting reboot from user.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700571 }
572
Darin Petkovc1a8b422010-07-19 11:34:49 -0700573 if (code == kActionCodeSuccess) {
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700574 utils::WriteFile(kUpdateCompletedMarker, "", 0);
Darin Petkov36275772010-10-01 11:40:57 -0700575 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Darin Petkov95508da2011-01-05 12:42:29 -0800576 prefs_->SetString(kPrefsPreviousVersion, omaha_request_params_.app_version);
Darin Petkov9b230572010-10-08 10:20:09 -0700577 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700578
579 // Since we're done with scattering fully at this point, this is the
580 // safest point delete the state files, as we're sure that the status is
581 // set to reboot (which means no more updates will be applied until reboot)
582 // This deletion is required for correctness as we want the next update
583 // check to re-create a new random number for the update check count.
584 // Similarly, we also delete the wall-clock-wait period that was persisted
585 // so that we start with a new random value for the next update check
586 // after reboot so that the same device is not favored or punished in any
587 // way.
588 prefs_->Delete(kPrefsUpdateCheckCount);
589 prefs_->Delete(kPrefsWallClockWaitPeriod);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700590 prefs_->Delete(kPrefsUpdateFirstSeenAt);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700591 LOG(INFO) << "Update successfully applied, waiting to reboot.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700592
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800593 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
594 kUpdateNoticeUnspecified);
Darin Petkov9d65b7b2010-07-20 09:13:01 -0700595
596 // Report the time it took to update the system.
597 int64_t update_time = time(NULL) - last_checked_time_;
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700598 if (!fake_update_success_)
Jay Srinivasanf0572052012-10-23 18:12:56 -0700599 system_state_->metrics_lib()->SendToUMA(
600 "Installer.UpdateTime",
601 static_cast<int>(update_time), // sample
602 1, // min = 1 second
603 20 * 60, // max = 20 minutes
604 50); // buckets
605
606 // Also report the success code so that the percentiles can be
607 // interpreted properly for the remaining error codes in UMA.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800608 utils::SendErrorCodeToUma(system_state_, code);
Darin Petkov09f96c32010-07-20 09:24:57 -0700609 return;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700610 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700611
Darin Petkov1023a602010-08-30 13:47:51 -0700612 if (ScheduleErrorEventAction()) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700613 return;
Darin Petkov1023a602010-08-30 13:47:51 -0700614 }
615 LOG(INFO) << "No update.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800616 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700617}
618
619void UpdateAttempter::ProcessingStopped(const ActionProcessor* processor) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800620 // Reset cpu shares back to normal.
621 CleanupCpuSharesManagement();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700622 download_progress_ = 0.0;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800623 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700624 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700625 error_event_.reset(NULL);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700626}
627
628// Called whenever an action has finished processing, either successfully
629// or otherwise.
630void UpdateAttempter::ActionCompleted(ActionProcessor* processor,
631 AbstractAction* action,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700632 ActionExitCode code) {
Darin Petkov1023a602010-08-30 13:47:51 -0700633 // Reset download progress regardless of whether or not the download
634 // action succeeded. Also, get the response code from HTTP request
635 // actions (update download as well as the initial update check
636 // actions).
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700637 const string type = action->Type();
Darin Petkov1023a602010-08-30 13:47:51 -0700638 if (type == DownloadAction::StaticType()) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700639 download_progress_ = 0.0;
Darin Petkov1023a602010-08-30 13:47:51 -0700640 DownloadAction* download_action = dynamic_cast<DownloadAction*>(action);
641 http_response_code_ = download_action->GetHTTPResponseCode();
642 } else if (type == OmahaRequestAction::StaticType()) {
643 OmahaRequestAction* omaha_request_action =
644 dynamic_cast<OmahaRequestAction*>(action);
645 // If the request is not an event, then it's the update-check.
646 if (!omaha_request_action->IsEvent()) {
647 http_response_code_ = omaha_request_action->GetHTTPResponseCode();
Darin Petkov85ced132010-09-01 10:20:56 -0700648 // Forward the server-dictated poll interval to the update check
649 // scheduler, if any.
650 if (update_check_scheduler_) {
651 update_check_scheduler_->set_poll_interval(
652 omaha_request_action->GetOutputObject().poll_interval);
653 }
Darin Petkov1023a602010-08-30 13:47:51 -0700654 }
655 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700656 if (code != kActionCodeSuccess) {
Darin Petkov7ed561b2011-10-04 02:59:03 -0700657 // If the current state is at or past the download phase, count the failure
658 // in case a switch to full update becomes necessary. Ignore network
659 // transfer timeouts and failures.
Darin Petkov36275772010-10-01 11:40:57 -0700660 if (status_ >= UPDATE_STATUS_DOWNLOADING &&
Darin Petkov36275772010-10-01 11:40:57 -0700661 code != kActionCodeDownloadTransferError) {
662 MarkDeltaUpdateFailure();
663 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700664 // On failure, schedule an error event to be sent to Omaha.
665 CreatePendingErrorEvent(action, code);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700666 return;
Darin Petkov09f96c32010-07-20 09:24:57 -0700667 }
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700668 // Find out which action completed.
669 if (type == OmahaResponseHandlerAction::StaticType()) {
Darin Petkov9b230572010-10-08 10:20:09 -0700670 // Note that the status will be updated to DOWNLOADING when some bytes get
671 // actually downloaded from the server and the BytesReceived callback is
672 // invoked. This avoids notifying the user that a download has started in
673 // cases when the server and the client are unable to initiate the download.
674 CHECK(action == response_handler_action_.get());
675 const InstallPlan& plan = response_handler_action_->install_plan();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700676 last_checked_time_ = time(NULL);
677 // TODO(adlr): put version in InstallPlan
678 new_version_ = "0.0.0.0";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700679 new_payload_size_ = plan.payload_size;
Darin Petkov9b230572010-10-08 10:20:09 -0700680 SetupDownload();
Chris Sosa4f8ee272012-11-30 13:01:54 -0800681 SetupCpuSharesManagement();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800682 SetStatusAndNotify(UPDATE_STATUS_UPDATE_AVAILABLE,
683 kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700684 } else if (type == DownloadAction::StaticType()) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800685 SetStatusAndNotify(UPDATE_STATUS_FINALIZING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700686 }
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700687}
688
689// Stop updating. An attempt will be made to record status to the disk
690// so that updates can be resumed later.
691void UpdateAttempter::Terminate() {
692 // TODO(adlr): implement this method.
693 NOTIMPLEMENTED();
694}
695
696// Try to resume from a previously Terminate()d update.
697void UpdateAttempter::ResumeUpdating() {
698 // TODO(adlr): implement this method.
699 NOTIMPLEMENTED();
700}
701
Darin Petkov9d911fa2010-08-19 09:36:08 -0700702void UpdateAttempter::SetDownloadStatus(bool active) {
703 download_active_ = active;
704 LOG(INFO) << "Download status: " << (active ? "active" : "inactive");
705}
706
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700707void UpdateAttempter::BytesReceived(uint64_t bytes_received, uint64_t total) {
Darin Petkov9d911fa2010-08-19 09:36:08 -0700708 if (!download_active_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700709 LOG(ERROR) << "BytesReceived called while not downloading.";
710 return;
711 }
Darin Petkovaf183052010-08-23 12:07:13 -0700712 double progress = static_cast<double>(bytes_received) /
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700713 static_cast<double>(total);
Darin Petkovaf183052010-08-23 12:07:13 -0700714 // Self throttle based on progress. Also send notifications if
715 // progress is too slow.
716 const double kDeltaPercent = 0.01; // 1%
717 if (status_ != UPDATE_STATUS_DOWNLOADING ||
718 bytes_received == total ||
719 progress - download_progress_ >= kDeltaPercent ||
720 TimeTicks::Now() - last_notify_time_ >= TimeDelta::FromSeconds(10)) {
721 download_progress_ = progress;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800722 SetStatusAndNotify(UPDATE_STATUS_DOWNLOADING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700723 }
724}
725
Jay Srinivasanc1ba09a2012-08-14 14:15:57 -0700726bool UpdateAttempter::ResetStatus() {
727 LOG(INFO) << "Attempting to reset state from "
728 << UpdateStatusToString(status_) << " to UPDATE_STATUS_IDLE";
729
730 switch (status_) {
731 case UPDATE_STATUS_IDLE:
732 // no-op.
733 return true;
734
735 case UPDATE_STATUS_UPDATED_NEED_REBOOT: {
736 status_ = UPDATE_STATUS_IDLE;
737 LOG(INFO) << "Reset Successful";
738
739 // also remove the reboot marker so that if the machine is rebooted
740 // after resetting to idle state, it doesn't go back to
741 // UPDATE_STATUS_UPDATED_NEED_REBOOT state.
742 const FilePath kUpdateCompletedMarkerPath(kUpdateCompletedMarker);
743 return file_util::Delete(kUpdateCompletedMarkerPath, false);
744 }
745
746 default:
747 LOG(ERROR) << "Reset not allowed in this state.";
748 return false;
749 }
750}
751
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700752bool UpdateAttempter::GetStatus(int64_t* last_checked_time,
753 double* progress,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800754 string* current_operation,
755 string* new_version,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700756 int64_t* new_payload_size) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700757 *last_checked_time = last_checked_time_;
758 *progress = download_progress_;
759 *current_operation = UpdateStatusToString(status_);
760 *new_version = new_version_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700761 *new_payload_size = new_payload_size_;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700762 return true;
763}
764
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700765void UpdateAttempter::UpdateBootFlags() {
Darin Petkov58dd1342011-05-06 12:05:13 -0700766 if (update_boot_flags_running_) {
767 LOG(INFO) << "Update boot flags running, nothing to do.";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700768 return;
769 }
Darin Petkov58dd1342011-05-06 12:05:13 -0700770 if (updated_boot_flags_) {
771 LOG(INFO) << "Already updated boot flags. Skipping.";
772 if (start_action_processor_) {
773 ScheduleProcessingStart();
774 }
775 return;
776 }
777 // This is purely best effort. Failures should be logged by Subprocess. Run
778 // the script asynchronously to avoid blocking the event loop regardless of
779 // the script runtime.
780 update_boot_flags_running_ = true;
781 LOG(INFO) << "Updating boot flags...";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700782 vector<string> cmd(1, "/usr/sbin/chromeos-setgoodkernel");
Darin Petkov58dd1342011-05-06 12:05:13 -0700783 if (!Subprocess::Get().Exec(cmd, StaticCompleteUpdateBootFlags, this)) {
784 CompleteUpdateBootFlags(1);
785 }
786}
787
788void UpdateAttempter::CompleteUpdateBootFlags(int return_code) {
789 update_boot_flags_running_ = false;
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700790 updated_boot_flags_ = true;
Darin Petkov58dd1342011-05-06 12:05:13 -0700791 if (start_action_processor_) {
792 ScheduleProcessingStart();
793 }
794}
795
796void UpdateAttempter::StaticCompleteUpdateBootFlags(
797 int return_code,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800798 const string& output,
Darin Petkov58dd1342011-05-06 12:05:13 -0700799 void* p) {
800 reinterpret_cast<UpdateAttempter*>(p)->CompleteUpdateBootFlags(return_code);
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700801}
802
Darin Petkov61635a92011-05-18 16:20:36 -0700803void UpdateAttempter::BroadcastStatus() {
804 if (!dbus_service_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700805 return;
Darin Petkov61635a92011-05-18 16:20:36 -0700806 }
Darin Petkovaf183052010-08-23 12:07:13 -0700807 last_notify_time_ = TimeTicks::Now();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700808 update_engine_service_emit_status_update(
809 dbus_service_,
810 last_checked_time_,
811 download_progress_,
812 UpdateStatusToString(status_),
813 new_version_.c_str(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700814 new_payload_size_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700815}
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700816
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800817uint32_t UpdateAttempter::GetErrorCodeFlags() {
818 uint32_t flags = 0;
819
820 if (!utils::IsNormalBootMode())
821 flags |= kActionCodeDevModeFlag;
822
823 if (response_handler_action_.get() &&
824 response_handler_action_->install_plan().is_resume)
825 flags |= kActionCodeResumedFlag;
826
827 if (!utils::IsOfficialBuild())
828 flags |= kActionCodeTestImageFlag;
829
830 if (omaha_request_params_.update_url != kProductionOmahaUrl)
831 flags |= kActionCodeTestOmahaUrlFlag;
832
833 return flags;
834}
835
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800836void UpdateAttempter::SetStatusAndNotify(UpdateStatus status,
837 UpdateNotice notice) {
Darin Petkov61635a92011-05-18 16:20:36 -0700838 status_ = status;
839 if (update_check_scheduler_) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800840 update_check_scheduler_->SetUpdateStatus(status_, notice);
Darin Petkov61635a92011-05-18 16:20:36 -0700841 }
842 BroadcastStatus();
843}
844
Darin Petkov777dbfa2010-07-20 15:03:37 -0700845void UpdateAttempter::CreatePendingErrorEvent(AbstractAction* action,
846 ActionExitCode code) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700847 if (error_event_.get()) {
848 // This shouldn't really happen.
849 LOG(WARNING) << "There's already an existing pending error event.";
850 return;
851 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700852
Darin Petkovabc7bc02011-02-23 14:39:43 -0800853 // For now assume that a generic Omaha response action failure means that
854 // there's no update so don't send an event. Also, double check that the
855 // failure has not occurred while sending an error event -- in which case
856 // don't schedule another. This shouldn't really happen but just in case...
857 if ((action->Type() == OmahaResponseHandlerAction::StaticType() &&
858 code == kActionCodeError) ||
Darin Petkov777dbfa2010-07-20 15:03:37 -0700859 status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
860 return;
861 }
862
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700863 // Classify the code to generate the appropriate result so that
864 // the Borgmon charts show up the results correctly.
865 // Do this before calling GetErrorCodeForAction which could potentially
866 // augment the bit representation of code and thus cause no matches for
867 // the switch cases below.
868 OmahaEvent::Result event_result;
869 switch (code) {
870 case kActionCodeOmahaUpdateIgnoredPerPolicy:
871 case kActionCodeOmahaUpdateDeferredPerPolicy:
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800872 case kActionCodeOmahaUpdateDeferredForBackoff:
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700873 event_result = OmahaEvent::kResultUpdateDeferred;
874 break;
875 default:
876 event_result = OmahaEvent::kResultError;
877 break;
878 }
879
Darin Petkov777dbfa2010-07-20 15:03:37 -0700880 code = GetErrorCodeForAction(action, code);
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700881 fake_update_success_ = code == kActionCodePostinstallBootedFromFirmwareB;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700882
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800883 // Compute the final error code with all the bit flags to be sent to Omaha.
884 code = static_cast<ActionExitCode>(code | GetErrorCodeFlags());
Darin Petkov09f96c32010-07-20 09:24:57 -0700885 error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700886 event_result,
Darin Petkov09f96c32010-07-20 09:24:57 -0700887 code));
888}
889
890bool UpdateAttempter::ScheduleErrorEventAction() {
891 if (error_event_.get() == NULL)
892 return false;
893
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800894 LOG(ERROR) << "Update failed.";
895 system_state_->payload_state()->UpdateFailed(error_event_->error_code);
896
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800897 // Send it to Uma.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800898 LOG(INFO) << "Reporting the error event";
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800899 utils::SendErrorCodeToUma(system_state_, error_event_->error_code);
900
901 // Send it to Omaha.
Darin Petkov09f96c32010-07-20 09:24:57 -0700902 shared_ptr<OmahaRequestAction> error_event_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800903 new OmahaRequestAction(system_state_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700904 &omaha_request_params_,
Darin Petkov09f96c32010-07-20 09:24:57 -0700905 error_event_.release(), // Pass ownership.
Jay Srinivasan08fce042012-06-07 16:31:01 -0700906 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700907 system_state_,
908 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700909 false));
Darin Petkov09f96c32010-07-20 09:24:57 -0700910 actions_.push_back(shared_ptr<AbstractAction>(error_event_action));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700911 processor_->EnqueueAction(error_event_action.get());
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800912 SetStatusAndNotify(UPDATE_STATUS_REPORTING_ERROR_EVENT,
913 kUpdateNoticeUnspecified);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700914 processor_->StartProcessing();
Darin Petkov09f96c32010-07-20 09:24:57 -0700915 return true;
916}
917
Chris Sosa4f8ee272012-11-30 13:01:54 -0800918void UpdateAttempter::SetCpuShares(utils::CpuShares shares) {
919 if (shares_ == shares) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700920 return;
921 }
Chris Sosa4f8ee272012-11-30 13:01:54 -0800922 if (utils::SetCpuShares(shares)) {
923 shares_ = shares;
924 LOG(INFO) << "CPU shares = " << shares_;
Darin Petkovc6c135c2010-08-11 13:36:18 -0700925 }
926}
927
Chris Sosa4f8ee272012-11-30 13:01:54 -0800928void UpdateAttempter::SetupCpuSharesManagement() {
929 if (manage_shares_source_) {
930 LOG(ERROR) << "Cpu shares timeout source hasn't been destroyed.";
931 CleanupCpuSharesManagement();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700932 }
Chris Sosa4f8ee272012-11-30 13:01:54 -0800933 const int kCpuSharesTimeout = 2 * 60 * 60; // 2 hours
934 manage_shares_source_ = g_timeout_source_new_seconds(kCpuSharesTimeout);
935 g_source_set_callback(manage_shares_source_,
936 StaticManageCpuSharesCallback,
Darin Petkovc6c135c2010-08-11 13:36:18 -0700937 this,
938 NULL);
Chris Sosa4f8ee272012-11-30 13:01:54 -0800939 g_source_attach(manage_shares_source_, NULL);
940 SetCpuShares(utils::kCpuSharesLow);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700941}
942
Chris Sosa4f8ee272012-11-30 13:01:54 -0800943void UpdateAttempter::CleanupCpuSharesManagement() {
944 if (manage_shares_source_) {
945 g_source_destroy(manage_shares_source_);
946 manage_shares_source_ = NULL;
Darin Petkovc6c135c2010-08-11 13:36:18 -0700947 }
Chris Sosa4f8ee272012-11-30 13:01:54 -0800948 SetCpuShares(utils::kCpuSharesNormal);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700949}
950
Chris Sosa4f8ee272012-11-30 13:01:54 -0800951gboolean UpdateAttempter::StaticManageCpuSharesCallback(gpointer data) {
952 return reinterpret_cast<UpdateAttempter*>(data)->ManageCpuSharesCallback();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700953}
954
Darin Petkove6ef2f82011-03-07 17:31:11 -0800955gboolean UpdateAttempter::StaticStartProcessing(gpointer data) {
956 reinterpret_cast<UpdateAttempter*>(data)->processor_->StartProcessing();
957 return FALSE; // Don't call this callback again.
958}
959
Darin Petkov58dd1342011-05-06 12:05:13 -0700960void UpdateAttempter::ScheduleProcessingStart() {
961 LOG(INFO) << "Scheduling an action processor start.";
962 start_action_processor_ = false;
963 g_idle_add(&StaticStartProcessing, this);
964}
965
Chris Sosa4f8ee272012-11-30 13:01:54 -0800966bool UpdateAttempter::ManageCpuSharesCallback() {
967 SetCpuShares(utils::kCpuSharesNormal);
968 manage_shares_source_ = NULL;
Darin Petkovf622ef72010-10-26 13:49:24 -0700969 return false; // Destroy the timeout source.
Darin Petkovc6c135c2010-08-11 13:36:18 -0700970}
971
Darin Petkov36275772010-10-01 11:40:57 -0700972void UpdateAttempter::DisableDeltaUpdateIfNeeded() {
973 int64_t delta_failures;
974 if (omaha_request_params_.delta_okay &&
975 prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) &&
976 delta_failures >= kMaxDeltaUpdateFailures) {
977 LOG(WARNING) << "Too many delta update failures, forcing full update.";
978 omaha_request_params_.delta_okay = false;
979 }
980}
981
982void UpdateAttempter::MarkDeltaUpdateFailure() {
Darin Petkov2dd01092010-10-08 15:43:05 -0700983 // Don't try to resume a failed delta update.
984 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Darin Petkov36275772010-10-01 11:40:57 -0700985 int64_t delta_failures;
986 if (!prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) ||
987 delta_failures < 0) {
988 delta_failures = 0;
989 }
990 prefs_->SetInt64(kPrefsDeltaUpdateFailures, ++delta_failures);
991}
992
Darin Petkov9b230572010-10-08 10:20:09 -0700993void UpdateAttempter::SetupDownload() {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800994 MultiRangeHttpFetcher* fetcher =
995 dynamic_cast<MultiRangeHttpFetcher*>(download_action_->http_fetcher());
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800996 fetcher->ClearRanges();
Darin Petkov9b230572010-10-08 10:20:09 -0700997 if (response_handler_action_->install_plan().is_resume) {
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700998 // Resuming an update so fetch the update manifest metadata first.
Darin Petkov9b230572010-10-08 10:20:09 -0700999 int64_t manifest_metadata_size = 0;
1000 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
Andrew de los Reyes819fef22010-12-17 11:33:58 -08001001 fetcher->AddRange(0, manifest_metadata_size);
Darin Petkovb21ce5d2010-10-21 16:03:05 -07001002 // If there're remaining unprocessed data blobs, fetch them. Be careful not
1003 // to request data beyond the end of the payload to avoid 416 HTTP response
1004 // error codes.
Darin Petkov9b230572010-10-08 10:20:09 -07001005 int64_t next_data_offset = 0;
1006 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -07001007 uint64_t resume_offset = manifest_metadata_size + next_data_offset;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001008 if (resume_offset < response_handler_action_->install_plan().payload_size) {
Gilad Arnolde4ad2502011-12-29 17:08:54 -08001009 fetcher->AddRange(resume_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -07001010 }
Darin Petkov9b230572010-10-08 10:20:09 -07001011 } else {
Gilad Arnolde4ad2502011-12-29 17:08:54 -08001012 fetcher->AddRange(0);
Darin Petkov9b230572010-10-08 10:20:09 -07001013 }
Darin Petkov9b230572010-10-08 10:20:09 -07001014}
1015
Thieu Le116fda32011-04-19 11:01:54 -07001016void UpdateAttempter::PingOmaha() {
Thieu Led88a8572011-05-26 09:09:19 -07001017 if (!processor_->IsRunning()) {
1018 shared_ptr<OmahaRequestAction> ping_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001019 new OmahaRequestAction(system_state_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001020 &omaha_request_params_,
Thieu Led88a8572011-05-26 09:09:19 -07001021 NULL,
Jay Srinivasan08fce042012-06-07 16:31:01 -07001022 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -07001023 system_state_,
1024 is_test_mode_),
Thieu Led88a8572011-05-26 09:09:19 -07001025 true));
1026 actions_.push_back(shared_ptr<OmahaRequestAction>(ping_action));
1027 processor_->set_delegate(NULL);
1028 processor_->EnqueueAction(ping_action.get());
1029 // Call StartProcessing() synchronously here to avoid any race conditions
1030 // caused by multiple outstanding ping Omaha requests. If we call
1031 // StartProcessing() asynchronously, the device can be suspended before we
1032 // get a chance to callback to StartProcessing(). When the device resumes
1033 // (assuming the device sleeps longer than the next update check period),
1034 // StartProcessing() is called back and at the same time, the next update
1035 // check is fired which eventually invokes StartProcessing(). A crash
1036 // can occur because StartProcessing() checks to make sure that the
1037 // processor is idle which it isn't due to the two concurrent ping Omaha
1038 // requests.
1039 processor_->StartProcessing();
1040 } else {
Darin Petkov58dd1342011-05-06 12:05:13 -07001041 LOG(WARNING) << "Action processor running, Omaha ping suppressed.";
Darin Petkov58dd1342011-05-06 12:05:13 -07001042 }
Thieu Led88a8572011-05-26 09:09:19 -07001043
1044 // Update the status which will schedule the next update check
Gilad Arnold1ebd8132012-03-05 10:19:29 -08001045 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
1046 kUpdateNoticeUnspecified);
Thieu Le116fda32011-04-19 11:01:54 -07001047}
1048
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001049
1050bool UpdateAttempter::DecrementUpdateCheckCount() {
1051 int64 update_check_count_value;
1052
1053 if (!prefs_->Exists(kPrefsUpdateCheckCount)) {
1054 // This file does not exist. This means we haven't started our update
1055 // check count down yet, so nothing more to do. This file will be created
1056 // later when we first satisfy the wall-clock-based-wait period.
1057 LOG(INFO) << "No existing update check count. That's normal.";
1058 return true;
1059 }
1060
1061 if (prefs_->GetInt64(kPrefsUpdateCheckCount, &update_check_count_value)) {
1062 // Only if we're able to read a proper integer value, then go ahead
1063 // and decrement and write back the result in the same file, if needed.
1064 LOG(INFO) << "Update check count = " << update_check_count_value;
1065
1066 if (update_check_count_value == 0) {
1067 // It could be 0, if, for some reason, the file didn't get deleted
1068 // when we set our status to waiting for reboot. so we just leave it
1069 // as is so that we can prevent another update_check wait for this client.
1070 LOG(INFO) << "Not decrementing update check count as it's already 0.";
1071 return true;
1072 }
1073
1074 if (update_check_count_value > 0)
1075 update_check_count_value--;
1076 else
1077 update_check_count_value = 0;
1078
1079 // Write out the new value of update_check_count_value.
1080 if (prefs_->SetInt64(kPrefsUpdateCheckCount, update_check_count_value)) {
1081 // We successfully wrote out te new value, so enable the
1082 // update check based wait.
1083 LOG(INFO) << "New update check count = " << update_check_count_value;
1084 return true;
1085 }
1086 }
1087
1088 LOG(INFO) << "Deleting update check count state due to read/write errors.";
1089
1090 // We cannot read/write to the file, so disable the update check based wait
1091 // so that we don't get stuck in this OS version by any chance (which could
1092 // happen if there's some bug that causes to read/write incorrectly).
1093 // Also attempt to delete the file to do our best effort to cleanup.
1094 prefs_->Delete(kPrefsUpdateCheckCount);
1095 return false;
1096}
1097
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07001098} // namespace chromeos_update_engine