blob: 8dd4622c28f9cdc8d505870735a14986fdae1cfb [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
Andrew de los Reyes45168102010-11-22 11:13:50 -080017#include <base/rand_util.h>
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070018#include <glib.h>
Darin Petkov1023a602010-08-30 13:47:51 -070019#include <metrics/metrics_library.h>
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +020020#include <policy/libpolicy.h>
21#include <policy/device_policy.h>
Darin Petkov9d65b7b2010-07-20 09:13:01 -070022
Bruno Rocha7f9aea22011-09-12 14:31:24 -070023#include "update_engine/certificate_checker.h"
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070024#include "update_engine/dbus_service.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070025#include "update_engine/download_action.h"
26#include "update_engine/filesystem_copier_action.h"
27#include "update_engine/libcurl_http_fetcher.h"
Andrew de los Reyes819fef22010-12-17 11:33:58 -080028#include "update_engine/multi_range_http_fetcher.h"
Darin Petkov6a5b3222010-07-13 14:55:28 -070029#include "update_engine/omaha_request_action.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070030#include "update_engine/omaha_request_params.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070031#include "update_engine/omaha_response_handler_action.h"
32#include "update_engine/postinstall_runner_action.h"
Darin Petkov36275772010-10-01 11:40:57 -070033#include "update_engine/prefs_interface.h"
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -070034#include "update_engine/subprocess.h"
Jay Srinivasan43488792012-06-19 00:25:31 -070035#include "update_engine/system_state.h"
Darin Petkov1023a602010-08-30 13:47:51 -070036#include "update_engine/update_check_scheduler.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070037
Darin Petkovaf183052010-08-23 12:07:13 -070038using base::TimeDelta;
39using base::TimeTicks;
Andrew de los Reyes21816e12011-04-07 14:18:56 -070040using google::protobuf::NewPermanentCallback;
Darin Petkov9b230572010-10-08 10:20:09 -070041using std::make_pair;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070042using std::tr1::shared_ptr;
Jay Srinivasan43488792012-06-19 00:25:31 -070043using std::set;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070044using std::string;
45using std::vector;
46
47namespace chromeos_update_engine {
48
Darin Petkov36275772010-10-01 11:40:57 -070049const int UpdateAttempter::kMaxDeltaUpdateFailures = 3;
50
Gilad Arnold1ebd8132012-03-05 10:19:29 -080051// Private test server URL w/ custom port number.
Gilad Arnolded747312012-03-15 18:20:41 -070052// TODO(garnold) This is a temporary hack to allow us to test the closed loop
53// automated update testing. To be replaced with an hard-coded local IP address.
54const char* const UpdateAttempter::kTestUpdateUrl(
55 "http://garnold.mtv.corp.google.com:8080/update");
Gilad Arnold28e2f392012-02-09 14:36:46 -080056
Darin Petkovcd1666f2010-09-23 09:53:44 -070057const char* kUpdateCompletedMarker =
58 "/var/run/update_engine_autoupdate_completed";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -070059
Andrew de los Reyes45168102010-11-22 11:13:50 -080060namespace {
61const int kMaxConsecutiveObeyProxyRequests = 20;
62} // namespace {}
63
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070064const char* UpdateStatusToString(UpdateStatus status) {
65 switch (status) {
66 case UPDATE_STATUS_IDLE:
67 return "UPDATE_STATUS_IDLE";
68 case UPDATE_STATUS_CHECKING_FOR_UPDATE:
69 return "UPDATE_STATUS_CHECKING_FOR_UPDATE";
70 case UPDATE_STATUS_UPDATE_AVAILABLE:
71 return "UPDATE_STATUS_UPDATE_AVAILABLE";
72 case UPDATE_STATUS_DOWNLOADING:
73 return "UPDATE_STATUS_DOWNLOADING";
74 case UPDATE_STATUS_VERIFYING:
75 return "UPDATE_STATUS_VERIFYING";
76 case UPDATE_STATUS_FINALIZING:
77 return "UPDATE_STATUS_FINALIZING";
78 case UPDATE_STATUS_UPDATED_NEED_REBOOT:
79 return "UPDATE_STATUS_UPDATED_NEED_REBOOT";
Darin Petkov09f96c32010-07-20 09:24:57 -070080 case UPDATE_STATUS_REPORTING_ERROR_EVENT:
81 return "UPDATE_STATUS_REPORTING_ERROR_EVENT";
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070082 default:
83 return "unknown status";
84 }
85}
86
Darin Petkov777dbfa2010-07-20 15:03:37 -070087// Turns a generic kActionCodeError to a generic error code specific
88// to |action| (e.g., kActionCodeFilesystemCopierError). If |code| is
89// not kActionCodeError, or the action is not matched, returns |code|
90// unchanged.
91ActionExitCode GetErrorCodeForAction(AbstractAction* action,
92 ActionExitCode code) {
93 if (code != kActionCodeError)
94 return code;
95
96 const string type = action->Type();
97 if (type == OmahaRequestAction::StaticType())
98 return kActionCodeOmahaRequestError;
99 if (type == OmahaResponseHandlerAction::StaticType())
100 return kActionCodeOmahaResponseHandlerError;
101 if (type == FilesystemCopierAction::StaticType())
102 return kActionCodeFilesystemCopierError;
103 if (type == PostinstallRunnerAction::StaticType())
104 return kActionCodePostinstallRunnerError;
Darin Petkov777dbfa2010-07-20 15:03:37 -0700105
106 return code;
107}
108
Darin Petkovc6c135c2010-08-11 13:36:18 -0700109UpdateAttempter::UpdateAttempter(PrefsInterface* prefs,
Andrew de los Reyes45168102010-11-22 11:13:50 -0800110 MetricsLibraryInterface* metrics_lib,
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700111 DbusGlibInterface* dbus_iface,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700112 GpioHandler* gpio_handler,
113 SystemState* system_state)
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700114 : processor_(new ActionProcessor()),
115 dbus_service_(NULL),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700116 prefs_(prefs),
117 metrics_lib_(metrics_lib),
Darin Petkov1023a602010-08-30 13:47:51 -0700118 update_check_scheduler_(NULL),
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700119 fake_update_success_(false),
Darin Petkov1023a602010-08-30 13:47:51 -0700120 http_response_code_(0),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700121 priority_(utils::kProcessPriorityNormal),
122 manage_priority_source_(NULL),
Darin Petkov9d911fa2010-08-19 09:36:08 -0700123 download_active_(false),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700124 status_(UPDATE_STATUS_IDLE),
125 download_progress_(0.0),
126 last_checked_time_(0),
127 new_version_("0.0.0.0"),
Darin Petkov36275772010-10-01 11:40:57 -0700128 new_size_(0),
Andrew de los Reyes45168102010-11-22 11:13:50 -0800129 proxy_manual_checks_(0),
130 obeying_proxies_(true),
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700131 chrome_proxy_resolver_(dbus_iface),
Darin Petkov58dd1342011-05-06 12:05:13 -0700132 updated_boot_flags_(false),
133 update_boot_flags_running_(false),
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200134 start_action_processor_(false),
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800135 policy_provider_(NULL),
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700136 is_using_test_url_(false),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700137 is_test_mode_(false),
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700138 is_test_update_attempted_(false),
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700139 gpio_handler_(gpio_handler),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700140 init_waiting_period_from_prefs_(true),
141 system_state_(system_state) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700142 if (utils::FileExists(kUpdateCompletedMarker))
143 status_ = UPDATE_STATUS_UPDATED_NEED_REBOOT;
144}
145
146UpdateAttempter::~UpdateAttempter() {
147 CleanupPriorityManagement();
148}
149
Gilad Arnold28e2f392012-02-09 14:36:46 -0800150void UpdateAttempter::Update(const string& app_version,
151 const string& omaha_url,
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700152 bool obey_proxies,
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800153 bool interactive,
Gilad Arnold7c04e762012-05-23 10:54:02 -0700154 bool is_test_mode,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700155 bool is_user_initiated) {
Andrew de los Reyes000d8952011-03-02 15:21:14 -0800156 chrome_proxy_resolver_.Init();
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700157 fake_update_success_ = false;
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700158 if (status_ == UPDATE_STATUS_UPDATED_NEED_REBOOT) {
Thieu Le116fda32011-04-19 11:01:54 -0700159 // Although we have applied an update, we still want to ping Omaha
160 // to ensure the number of active statistics is accurate.
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700161 LOG(INFO) << "Not updating b/c we already updated and we're waiting for "
Thieu Le116fda32011-04-19 11:01:54 -0700162 << "reboot, we'll ping Omaha instead";
163 PingOmaha();
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700164 return;
165 }
166 if (status_ != UPDATE_STATUS_IDLE) {
167 // Update in progress. Do nothing
168 return;
169 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700170
171 if (!CalculateUpdateParams(app_version,
172 omaha_url,
173 obey_proxies,
174 interactive,
Gilad Arnold7c04e762012-05-23 10:54:02 -0700175 is_test_mode,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700176 is_user_initiated)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700177 return;
178 }
179
180 BuildUpdateActions(interactive);
181
182 SetStatusAndNotify(UPDATE_STATUS_CHECKING_FOR_UPDATE,
183 kUpdateNoticeUnspecified);
184
185 // Just in case we didn't update boot flags yet, make sure they're updated
186 // before any update processing starts.
187 start_action_processor_ = true;
188 UpdateBootFlags();
189}
190
191bool UpdateAttempter::CalculateUpdateParams(const string& app_version,
192 const string& omaha_url,
193 bool obey_proxies,
194 bool interactive,
Gilad Arnold7c04e762012-05-23 10:54:02 -0700195 bool is_test_mode,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700196 bool is_user_initiated) {
Darin Petkov1023a602010-08-30 13:47:51 -0700197 http_response_code_ = 0;
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200198
Gilad Arnold7c04e762012-05-23 10:54:02 -0700199 // Set the test mode flag for the current update attempt.
200 is_test_mode_ = is_test_mode;
201
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200202 // Lazy initialize the policy provider, or reload the latest policy data.
203 if (!policy_provider_.get()) {
204 policy_provider_.reset(new policy::PolicyProvider());
205 } else {
206 policy_provider_->Reload();
207 }
208
209 // If the release_track is specified by policy, that takes precedence.
210 string release_track;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700211
212 // Take a copy of the old scatter value before we update it.
213 int64 old_scatter_factor_in_secs = scatter_factor_.InSeconds();
Jay Srinivasan0a708742012-03-20 11:26:12 -0700214 if (policy_provider_->device_policy_is_loaded()) {
215 const policy::DevicePolicy& device_policy =
216 policy_provider_->GetDevicePolicy();
217 device_policy.GetReleaseChannel(&release_track);
218 device_policy.GetUpdateDisabled(&omaha_request_params_.update_disabled);
219 device_policy.GetTargetVersionPrefix(
220 &omaha_request_params_.target_version_prefix);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700221 int64 new_scatter_factor_in_secs = 0;
222 device_policy.GetScatterFactorInSeconds(&new_scatter_factor_in_secs);
Jay Srinivasan08fce042012-06-07 16:31:01 -0700223 if (new_scatter_factor_in_secs < 0) // sanitize input, just in case.
224 new_scatter_factor_in_secs = 0;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700225 scatter_factor_ = TimeDelta::FromSeconds(new_scatter_factor_in_secs);
Jay Srinivasan43488792012-06-19 00:25:31 -0700226
227 system_state_->SetDevicePolicy(&device_policy);
228
229 set<string> allowed_types;
230 string allowed_types_str;
231 if (device_policy.GetAllowedConnectionTypesForUpdate(&allowed_types)) {
232 set<string>::const_iterator iter;
233 for (iter = allowed_types.begin(); iter != allowed_types.end(); ++iter)
234 allowed_types_str += *iter + " ";
235 }
236
237 LOG(INFO) << "Networks over which updates are allowed per policy : "
238 << (allowed_types_str.empty() ? "all" : allowed_types_str);
239 } else {
240 LOG(INFO) << "No device policies present.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700241 }
242
Jay Srinivasan08fce042012-06-07 16:31:01 -0700243 bool is_scatter_enabled = false;
244 if (scatter_factor_.InSeconds() == 0) {
245 LOG(INFO) << "Scattering disabled since scatter factor is set to 0";
246 } else if (is_user_initiated) {
247 LOG(INFO) << "Scattering disabled as this update check is user-initiated";
248 } else if (!system_state_->IsOOBEComplete()) {
249 LOG(INFO) << "Scattering disabled since OOBE is not complete yet";
250 } else {
251 is_scatter_enabled = true;
252 LOG(INFO) << "Scattering is enabled";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700253 }
254
Jay Srinivasan08fce042012-06-07 16:31:01 -0700255 if (is_scatter_enabled) {
256 // This means the scattering policy is turned on.
257 if (scatter_factor_.InSeconds() != old_scatter_factor_in_secs) {
258 int64 wait_period_in_secs = 0;
259 if (init_waiting_period_from_prefs_ &&
260 prefs_->GetInt64(kPrefsWallClockWaitPeriod, &wait_period_in_secs) &&
261 wait_period_in_secs >= 0 &&
262 wait_period_in_secs <= scatter_factor_.InSeconds()) {
263 // This means:
264 // 1. This is the first update check to come this far in this process.
265 // 2. There's a persisted value for the waiting period available.
266 // 3. And that persisted value is still valid.
267 // So, in this case, we should reuse the persisted value instead of
268 // generating a new random value to improve the chances of a good
269 // distribution for scattering.
270 omaha_request_params_.waiting_period =
271 TimeDelta::FromSeconds(wait_period_in_secs);
272 LOG(INFO) << "Using persisted value for wall clock based waiting period.";
273 } else {
274 // In this case, we should regenerate the waiting period to make sure
275 // it's within the bounds of the new scatter factor value.
276 omaha_request_params_.waiting_period = TimeDelta::FromSeconds(
277 base::RandInt(0, scatter_factor_.InSeconds()));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700278
Jay Srinivasan08fce042012-06-07 16:31:01 -0700279 LOG(INFO) << "Generated new value of " << utils::FormatSecs(
280 omaha_request_params_.waiting_period.InSeconds())
281 << " for wall clock based waiting period.";
282
283 // Do a best-effort to persist this. We'll work fine even if the
284 // persistence fails.
285 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
286 omaha_request_params_.waiting_period.InSeconds());
287 }
288 }
289
290 // We should reset this value since we're past the first initialization
291 // of the waiting period for this process.
292 init_waiting_period_from_prefs_ = false;
293
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700294 // This means the scattering policy is turned on. We'll do wall-clock-
295 // based-wait by default. And if we don't have any issues in accessing
296 // the file system to do update the update check count value, we'll
297 // turn that on as well.
298 omaha_request_params_.wall_clock_based_wait_enabled = true;
299 bool decrement_succeeded = DecrementUpdateCheckCount();
300 omaha_request_params_.update_check_count_wait_enabled = decrement_succeeded;
Jay Srinivasan08fce042012-06-07 16:31:01 -0700301 } else {
302 // This means the scattering feature is turned off. Make sure to disable
303 // all the knobs so that we don't invoke any scattering related code.
304 omaha_request_params_.wall_clock_based_wait_enabled = false;
305 omaha_request_params_.update_check_count_wait_enabled = false;
306 prefs_->Delete(kPrefsWallClockWaitPeriod);
307 prefs_->Delete(kPrefsUpdateCheckCount);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700308 }
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200309
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800310 // Determine whether an alternative test address should be used.
Gilad Arnold28e2f392012-02-09 14:36:46 -0800311 string omaha_url_to_use = omaha_url;
Gilad Arnold7c04e762012-05-23 10:54:02 -0700312 if ((is_using_test_url_ = (omaha_url_to_use.empty() && is_test_mode_))) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800313 omaha_url_to_use = kTestUpdateUrl;
314 LOG(INFO) << "using alternative server address: " << omaha_url_to_use;
Gilad Arnold28e2f392012-02-09 14:36:46 -0800315 }
316
Jay Srinivasan0a708742012-03-20 11:26:12 -0700317 if (!omaha_request_params_.Init(app_version,
318 omaha_url_to_use,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800319 release_track)) {
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700320 LOG(ERROR) << "Unable to initialize Omaha request device params.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700321 return false;
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700322 }
Darin Petkov3aefa862010-12-07 14:45:00 -0800323
Jay Srinivasan0a708742012-03-20 11:26:12 -0700324 LOG(INFO) << "update_disabled = "
325 << (omaha_request_params_.update_disabled ? "true" : "false")
326 << ", target_version_prefix = "
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700327 << omaha_request_params_.target_version_prefix
328 << ", scatter_factor_in_seconds = "
329 << utils::FormatSecs(scatter_factor_.InSeconds());
330
331 LOG(INFO) << "Wall Clock Based Wait Enabled = "
332 << omaha_request_params_.wall_clock_based_wait_enabled
333 << ", Update Check Count Wait Enabled = "
334 << omaha_request_params_.update_check_count_wait_enabled
335 << ", Waiting Period = "
336 << utils::FormatSecs(
337 omaha_request_params_.waiting_period.InSeconds());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700338
Andrew de los Reyes45168102010-11-22 11:13:50 -0800339 obeying_proxies_ = true;
340 if (obey_proxies || proxy_manual_checks_ == 0) {
341 LOG(INFO) << "forced to obey proxies";
342 // If forced to obey proxies, every 20th request will not use proxies
343 proxy_manual_checks_++;
344 LOG(INFO) << "proxy manual checks: " << proxy_manual_checks_;
345 if (proxy_manual_checks_ >= kMaxConsecutiveObeyProxyRequests) {
346 proxy_manual_checks_ = 0;
347 obeying_proxies_ = false;
348 }
349 } else if (base::RandInt(0, 4) == 0) {
350 obeying_proxies_ = false;
351 }
352 LOG_IF(INFO, !obeying_proxies_) << "To help ensure updates work, this update "
353 "check we are ignoring the proxy settings and using "
354 "direct connections.";
355
Darin Petkov36275772010-10-01 11:40:57 -0700356 DisableDeltaUpdateIfNeeded();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700357 return true;
358}
359
360void UpdateAttempter::BuildUpdateActions(bool interactive) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700361 CHECK(!processor_->IsRunning());
362 processor_->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700363
364 // Actions:
Darin Petkova0929552010-11-29 14:19:06 -0800365 LibcurlHttpFetcher* update_check_fetcher =
Gilad Arnold7c04e762012-05-23 10:54:02 -0700366 new LibcurlHttpFetcher(GetProxyResolver(), system_state_, is_test_mode_);
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700367 // Try harder to connect to the network, esp when not interactive.
368 // See comment in libcurl_http_fetcher.cc.
369 update_check_fetcher->set_no_network_max_retries(interactive ? 1 : 3);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700370 update_check_fetcher->set_check_certificate(CertificateChecker::kUpdate);
Darin Petkov6a5b3222010-07-13 14:55:28 -0700371 shared_ptr<OmahaRequestAction> update_check_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700372 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700373 &omaha_request_params_,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700374 NULL,
Thieu Le116fda32011-04-19 11:01:54 -0700375 update_check_fetcher, // passes ownership
376 false));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700377 shared_ptr<OmahaResponseHandlerAction> response_handler_action(
Darin Petkov73058b42010-10-06 16:32:19 -0700378 new OmahaResponseHandlerAction(prefs_));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700379 shared_ptr<FilesystemCopierAction> filesystem_copier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700380 new FilesystemCopierAction(false, false));
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700381 shared_ptr<FilesystemCopierAction> kernel_filesystem_copier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700382 new FilesystemCopierAction(true, false));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700383 shared_ptr<OmahaRequestAction> download_started_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700384 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700385 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700386 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700387 OmahaEvent::kTypeUpdateDownloadStarted),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700388 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700389 system_state_,
390 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700391 false));
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700392 LibcurlHttpFetcher* download_fetcher =
Gilad Arnold7c04e762012-05-23 10:54:02 -0700393 new LibcurlHttpFetcher(GetProxyResolver(), system_state_, is_test_mode_);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700394 download_fetcher->set_check_certificate(CertificateChecker::kDownload);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700395 shared_ptr<DownloadAction> download_action(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700396 new DownloadAction(prefs_,
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800397 new MultiRangeHttpFetcher(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700398 download_fetcher))); // passes ownership
Darin Petkov8c2980e2010-07-16 15:16:49 -0700399 shared_ptr<OmahaRequestAction> download_finished_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700400 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700401 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700402 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700403 OmahaEvent::kTypeUpdateDownloadFinished),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700404 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700405 system_state_,
406 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700407 false));
Darin Petkov3aefa862010-12-07 14:45:00 -0800408 shared_ptr<FilesystemCopierAction> filesystem_verifier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700409 new FilesystemCopierAction(false, true));
Darin Petkov3aefa862010-12-07 14:45:00 -0800410 shared_ptr<FilesystemCopierAction> kernel_filesystem_verifier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700411 new FilesystemCopierAction(true, true));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800412 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
413 new PostinstallRunnerAction);
Darin Petkov8c2980e2010-07-16 15:16:49 -0700414 shared_ptr<OmahaRequestAction> update_complete_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700415 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700416 &omaha_request_params_,
Darin Petkove17f86b2010-07-20 09:12:01 -0700417 new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700418 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700419 system_state_,
420 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700421 false));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700422
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700423 download_action->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700424 response_handler_action_ = response_handler_action;
Darin Petkov9b230572010-10-08 10:20:09 -0700425 download_action_ = download_action;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700426
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700427 actions_.push_back(shared_ptr<AbstractAction>(update_check_action));
428 actions_.push_back(shared_ptr<AbstractAction>(response_handler_action));
429 actions_.push_back(shared_ptr<AbstractAction>(filesystem_copier_action));
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700430 actions_.push_back(shared_ptr<AbstractAction>(
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700431 kernel_filesystem_copier_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700432 actions_.push_back(shared_ptr<AbstractAction>(download_started_action));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700433 actions_.push_back(shared_ptr<AbstractAction>(download_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700434 actions_.push_back(shared_ptr<AbstractAction>(download_finished_action));
Darin Petkov3aefa862010-12-07 14:45:00 -0800435 actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action));
436 actions_.push_back(shared_ptr<AbstractAction>(
437 kernel_filesystem_verifier_action));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800438 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700439 actions_.push_back(shared_ptr<AbstractAction>(update_complete_action));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700440
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700441 // Enqueue the actions
442 for (vector<shared_ptr<AbstractAction> >::iterator it = actions_.begin();
443 it != actions_.end(); ++it) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700444 processor_->EnqueueAction(it->get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700445 }
446
447 // Bond them together. We have to use the leaf-types when calling
448 // BondActions().
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700449 BondActions(update_check_action.get(),
450 response_handler_action.get());
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700451 BondActions(response_handler_action.get(),
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700452 filesystem_copier_action.get());
453 BondActions(filesystem_copier_action.get(),
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700454 kernel_filesystem_copier_action.get());
455 BondActions(kernel_filesystem_copier_action.get(),
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700456 download_action.get());
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700457 BondActions(download_action.get(),
Darin Petkov3aefa862010-12-07 14:45:00 -0800458 filesystem_verifier_action.get());
459 BondActions(filesystem_verifier_action.get(),
460 kernel_filesystem_verifier_action.get());
461 BondActions(kernel_filesystem_verifier_action.get(),
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800462 postinstall_runner_action.get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700463}
464
Gilad Arnold28e2f392012-02-09 14:36:46 -0800465void UpdateAttempter::CheckForUpdate(const string& app_version,
Jay Srinivasane73acab2012-07-10 14:34:03 -0700466 const string& omaha_url,
467 bool is_user_initiated) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700468 LOG(INFO) << "New update check requested";
469
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700470 if (status_ != UPDATE_STATUS_IDLE) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700471 LOG(INFO) << "Skipping update check because current status is "
472 << UpdateStatusToString(status_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700473 return;
474 }
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800475
476 // Read GPIO signals and determine whether this is an automated test scenario.
477 // For safety, we only allow a test update to be performed once; subsequent
478 // update requests will be carried out normally.
Gilad Arnold7c04e762012-05-23 10:54:02 -0700479 bool is_test_mode = (!is_test_update_attempted_ && gpio_handler_ &&
480 gpio_handler_->IsTestModeSignaled());
481 if (is_test_mode) {
482 LOG(WARNING) << "this is a test mode update attempt!";
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700483 is_test_update_attempted_ = true;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800484 }
485
Jay Srinivasan08fce042012-06-07 16:31:01 -0700486 // Passing true for is_user_initiated to indicate that this
487 // is not a scheduled update check.
Gilad Arnold7c04e762012-05-23 10:54:02 -0700488 Update(app_version, omaha_url, true, true, is_test_mode, is_user_initiated);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700489}
490
Darin Petkov296889c2010-07-23 16:20:54 -0700491bool UpdateAttempter::RebootIfNeeded() {
492 if (status_ != UPDATE_STATUS_UPDATED_NEED_REBOOT) {
493 LOG(INFO) << "Reboot requested, but status is "
494 << UpdateStatusToString(status_) << ", so not rebooting.";
495 return false;
496 }
497 TEST_AND_RETURN_FALSE(utils::Reboot());
498 return true;
499}
500
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700501// Delegate methods:
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700502void UpdateAttempter::ProcessingDone(const ActionProcessor* processor,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700503 ActionExitCode code) {
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700504 CHECK(response_handler_action_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700505 LOG(INFO) << "Processing Done.";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700506 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700507
Darin Petkovc6c135c2010-08-11 13:36:18 -0700508 // Reset process priority back to normal.
509 CleanupPriorityManagement();
510
Darin Petkov09f96c32010-07-20 09:24:57 -0700511 if (status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
512 LOG(INFO) << "Error event sent.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800513
514 // Inform scheduler of new status; also specifically inform about a failed
515 // update attempt with a test address.
516 SetStatusAndNotify(UPDATE_STATUS_IDLE,
517 (is_using_test_url_ ? kUpdateNoticeTestAddrFailed :
518 kUpdateNoticeUnspecified));
519
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700520 if (!fake_update_success_) {
521 return;
522 }
523 LOG(INFO) << "Booted from FW B and tried to install new firmware, "
524 "so requesting reboot from user.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700525 }
526
Darin Petkovc1a8b422010-07-19 11:34:49 -0700527 if (code == kActionCodeSuccess) {
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700528 utils::WriteFile(kUpdateCompletedMarker, "", 0);
Darin Petkov36275772010-10-01 11:40:57 -0700529 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Darin Petkov95508da2011-01-05 12:42:29 -0800530 prefs_->SetString(kPrefsPreviousVersion, omaha_request_params_.app_version);
Darin Petkov9b230572010-10-08 10:20:09 -0700531 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700532
533 // Since we're done with scattering fully at this point, this is the
534 // safest point delete the state files, as we're sure that the status is
535 // set to reboot (which means no more updates will be applied until reboot)
536 // This deletion is required for correctness as we want the next update
537 // check to re-create a new random number for the update check count.
538 // Similarly, we also delete the wall-clock-wait period that was persisted
539 // so that we start with a new random value for the next update check
540 // after reboot so that the same device is not favored or punished in any
541 // way.
542 prefs_->Delete(kPrefsUpdateCheckCount);
543 prefs_->Delete(kPrefsWallClockWaitPeriod);
544
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800545 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
546 kUpdateNoticeUnspecified);
Darin Petkov9d65b7b2010-07-20 09:13:01 -0700547
548 // Report the time it took to update the system.
549 int64_t update_time = time(NULL) - last_checked_time_;
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700550 if (!fake_update_success_)
551 metrics_lib_->SendToUMA("Installer.UpdateTime",
552 static_cast<int>(update_time), // sample
553 1, // min = 1 second
554 20 * 60, // max = 20 minutes
555 50); // buckets
Darin Petkov09f96c32010-07-20 09:24:57 -0700556 return;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700557 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700558
Darin Petkov1023a602010-08-30 13:47:51 -0700559 if (ScheduleErrorEventAction()) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700560 return;
Darin Petkov1023a602010-08-30 13:47:51 -0700561 }
562 LOG(INFO) << "No update.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800563 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700564}
565
566void UpdateAttempter::ProcessingStopped(const ActionProcessor* processor) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700567 // Reset process priority back to normal.
568 CleanupPriorityManagement();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700569 download_progress_ = 0.0;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800570 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700571 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700572 error_event_.reset(NULL);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700573}
574
575// Called whenever an action has finished processing, either successfully
576// or otherwise.
577void UpdateAttempter::ActionCompleted(ActionProcessor* processor,
578 AbstractAction* action,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700579 ActionExitCode code) {
Darin Petkov1023a602010-08-30 13:47:51 -0700580 // Reset download progress regardless of whether or not the download
581 // action succeeded. Also, get the response code from HTTP request
582 // actions (update download as well as the initial update check
583 // actions).
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700584 const string type = action->Type();
Darin Petkov1023a602010-08-30 13:47:51 -0700585 if (type == DownloadAction::StaticType()) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700586 download_progress_ = 0.0;
Darin Petkov1023a602010-08-30 13:47:51 -0700587 DownloadAction* download_action = dynamic_cast<DownloadAction*>(action);
588 http_response_code_ = download_action->GetHTTPResponseCode();
589 } else if (type == OmahaRequestAction::StaticType()) {
590 OmahaRequestAction* omaha_request_action =
591 dynamic_cast<OmahaRequestAction*>(action);
592 // If the request is not an event, then it's the update-check.
593 if (!omaha_request_action->IsEvent()) {
594 http_response_code_ = omaha_request_action->GetHTTPResponseCode();
Darin Petkov85ced132010-09-01 10:20:56 -0700595 // Forward the server-dictated poll interval to the update check
596 // scheduler, if any.
597 if (update_check_scheduler_) {
598 update_check_scheduler_->set_poll_interval(
599 omaha_request_action->GetOutputObject().poll_interval);
600 }
Darin Petkov1023a602010-08-30 13:47:51 -0700601 }
602 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700603 if (code != kActionCodeSuccess) {
Darin Petkov7ed561b2011-10-04 02:59:03 -0700604 // If the current state is at or past the download phase, count the failure
605 // in case a switch to full update becomes necessary. Ignore network
606 // transfer timeouts and failures.
Darin Petkov36275772010-10-01 11:40:57 -0700607 if (status_ >= UPDATE_STATUS_DOWNLOADING &&
Darin Petkov36275772010-10-01 11:40:57 -0700608 code != kActionCodeDownloadTransferError) {
609 MarkDeltaUpdateFailure();
610 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700611 // On failure, schedule an error event to be sent to Omaha.
612 CreatePendingErrorEvent(action, code);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700613 return;
Darin Petkov09f96c32010-07-20 09:24:57 -0700614 }
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700615 // Find out which action completed.
616 if (type == OmahaResponseHandlerAction::StaticType()) {
Darin Petkov9b230572010-10-08 10:20:09 -0700617 // Note that the status will be updated to DOWNLOADING when some bytes get
618 // actually downloaded from the server and the BytesReceived callback is
619 // invoked. This avoids notifying the user that a download has started in
620 // cases when the server and the client are unable to initiate the download.
621 CHECK(action == response_handler_action_.get());
622 const InstallPlan& plan = response_handler_action_->install_plan();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700623 last_checked_time_ = time(NULL);
624 // TODO(adlr): put version in InstallPlan
625 new_version_ = "0.0.0.0";
626 new_size_ = plan.size;
Darin Petkov9b230572010-10-08 10:20:09 -0700627 SetupDownload();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700628 SetupPriorityManagement();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800629 SetStatusAndNotify(UPDATE_STATUS_UPDATE_AVAILABLE,
630 kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700631 } else if (type == DownloadAction::StaticType()) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800632 SetStatusAndNotify(UPDATE_STATUS_FINALIZING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700633 }
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700634}
635
636// Stop updating. An attempt will be made to record status to the disk
637// so that updates can be resumed later.
638void UpdateAttempter::Terminate() {
639 // TODO(adlr): implement this method.
640 NOTIMPLEMENTED();
641}
642
643// Try to resume from a previously Terminate()d update.
644void UpdateAttempter::ResumeUpdating() {
645 // TODO(adlr): implement this method.
646 NOTIMPLEMENTED();
647}
648
Darin Petkov9d911fa2010-08-19 09:36:08 -0700649void UpdateAttempter::SetDownloadStatus(bool active) {
650 download_active_ = active;
651 LOG(INFO) << "Download status: " << (active ? "active" : "inactive");
652}
653
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700654void UpdateAttempter::BytesReceived(uint64_t bytes_received, uint64_t total) {
Darin Petkov9d911fa2010-08-19 09:36:08 -0700655 if (!download_active_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700656 LOG(ERROR) << "BytesReceived called while not downloading.";
657 return;
658 }
Darin Petkovaf183052010-08-23 12:07:13 -0700659 double progress = static_cast<double>(bytes_received) /
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700660 static_cast<double>(total);
Darin Petkovaf183052010-08-23 12:07:13 -0700661 // Self throttle based on progress. Also send notifications if
662 // progress is too slow.
663 const double kDeltaPercent = 0.01; // 1%
664 if (status_ != UPDATE_STATUS_DOWNLOADING ||
665 bytes_received == total ||
666 progress - download_progress_ >= kDeltaPercent ||
667 TimeTicks::Now() - last_notify_time_ >= TimeDelta::FromSeconds(10)) {
668 download_progress_ = progress;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800669 SetStatusAndNotify(UPDATE_STATUS_DOWNLOADING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700670 }
671}
672
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700673bool UpdateAttempter::GetStatus(int64_t* last_checked_time,
674 double* progress,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800675 string* current_operation,
676 string* new_version,
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700677 int64_t* new_size) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700678 *last_checked_time = last_checked_time_;
679 *progress = download_progress_;
680 *current_operation = UpdateStatusToString(status_);
681 *new_version = new_version_;
682 *new_size = new_size_;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700683 return true;
684}
685
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700686void UpdateAttempter::UpdateBootFlags() {
Darin Petkov58dd1342011-05-06 12:05:13 -0700687 if (update_boot_flags_running_) {
688 LOG(INFO) << "Update boot flags running, nothing to do.";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700689 return;
690 }
Darin Petkov58dd1342011-05-06 12:05:13 -0700691 if (updated_boot_flags_) {
692 LOG(INFO) << "Already updated boot flags. Skipping.";
693 if (start_action_processor_) {
694 ScheduleProcessingStart();
695 }
696 return;
697 }
698 // This is purely best effort. Failures should be logged by Subprocess. Run
699 // the script asynchronously to avoid blocking the event loop regardless of
700 // the script runtime.
701 update_boot_flags_running_ = true;
702 LOG(INFO) << "Updating boot flags...";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700703 vector<string> cmd(1, "/usr/sbin/chromeos-setgoodkernel");
Darin Petkov58dd1342011-05-06 12:05:13 -0700704 if (!Subprocess::Get().Exec(cmd, StaticCompleteUpdateBootFlags, this)) {
705 CompleteUpdateBootFlags(1);
706 }
707}
708
709void UpdateAttempter::CompleteUpdateBootFlags(int return_code) {
710 update_boot_flags_running_ = false;
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700711 updated_boot_flags_ = true;
Darin Petkov58dd1342011-05-06 12:05:13 -0700712 if (start_action_processor_) {
713 ScheduleProcessingStart();
714 }
715}
716
717void UpdateAttempter::StaticCompleteUpdateBootFlags(
718 int return_code,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800719 const string& output,
Darin Petkov58dd1342011-05-06 12:05:13 -0700720 void* p) {
721 reinterpret_cast<UpdateAttempter*>(p)->CompleteUpdateBootFlags(return_code);
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700722}
723
Darin Petkov61635a92011-05-18 16:20:36 -0700724void UpdateAttempter::BroadcastStatus() {
725 if (!dbus_service_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700726 return;
Darin Petkov61635a92011-05-18 16:20:36 -0700727 }
Darin Petkovaf183052010-08-23 12:07:13 -0700728 last_notify_time_ = TimeTicks::Now();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700729 update_engine_service_emit_status_update(
730 dbus_service_,
731 last_checked_time_,
732 download_progress_,
733 UpdateStatusToString(status_),
734 new_version_.c_str(),
735 new_size_);
736}
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700737
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800738void UpdateAttempter::SetStatusAndNotify(UpdateStatus status,
739 UpdateNotice notice) {
Darin Petkov61635a92011-05-18 16:20:36 -0700740 status_ = status;
741 if (update_check_scheduler_) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800742 update_check_scheduler_->SetUpdateStatus(status_, notice);
Darin Petkov61635a92011-05-18 16:20:36 -0700743 }
744 BroadcastStatus();
745}
746
Darin Petkov777dbfa2010-07-20 15:03:37 -0700747void UpdateAttempter::CreatePendingErrorEvent(AbstractAction* action,
748 ActionExitCode code) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700749 if (error_event_.get()) {
750 // This shouldn't really happen.
751 LOG(WARNING) << "There's already an existing pending error event.";
752 return;
753 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700754
Darin Petkovabc7bc02011-02-23 14:39:43 -0800755 // For now assume that a generic Omaha response action failure means that
756 // there's no update so don't send an event. Also, double check that the
757 // failure has not occurred while sending an error event -- in which case
758 // don't schedule another. This shouldn't really happen but just in case...
759 if ((action->Type() == OmahaResponseHandlerAction::StaticType() &&
760 code == kActionCodeError) ||
Darin Petkov777dbfa2010-07-20 15:03:37 -0700761 status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
762 return;
763 }
764
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700765 // Classify the code to generate the appropriate result so that
766 // the Borgmon charts show up the results correctly.
767 // Do this before calling GetErrorCodeForAction which could potentially
768 // augment the bit representation of code and thus cause no matches for
769 // the switch cases below.
770 OmahaEvent::Result event_result;
771 switch (code) {
772 case kActionCodeOmahaUpdateIgnoredPerPolicy:
773 case kActionCodeOmahaUpdateDeferredPerPolicy:
774 event_result = OmahaEvent::kResultUpdateDeferred;
775 break;
776 default:
777 event_result = OmahaEvent::kResultError;
778 break;
779 }
780
Darin Petkov777dbfa2010-07-20 15:03:37 -0700781 code = GetErrorCodeForAction(action, code);
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700782 fake_update_success_ = code == kActionCodePostinstallBootedFromFirmwareB;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700783
784 // Apply the bit modifiers to the error code.
785 if (!utils::IsNormalBootMode()) {
786 code = static_cast<ActionExitCode>(code | kActionCodeBootModeFlag);
787 }
788 if (response_handler_action_.get() &&
789 response_handler_action_->install_plan().is_resume) {
790 code = static_cast<ActionExitCode>(code | kActionCodeResumedFlag);
791 }
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700792
Darin Petkov09f96c32010-07-20 09:24:57 -0700793 error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700794 event_result,
Darin Petkov09f96c32010-07-20 09:24:57 -0700795 code));
796}
797
798bool UpdateAttempter::ScheduleErrorEventAction() {
799 if (error_event_.get() == NULL)
800 return false;
801
Darin Petkov1023a602010-08-30 13:47:51 -0700802 LOG(INFO) << "Update failed -- reporting the error event.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700803 shared_ptr<OmahaRequestAction> error_event_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700804 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700805 &omaha_request_params_,
Darin Petkov09f96c32010-07-20 09:24:57 -0700806 error_event_.release(), // Pass ownership.
Jay Srinivasan08fce042012-06-07 16:31:01 -0700807 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700808 system_state_,
809 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700810 false));
Darin Petkov09f96c32010-07-20 09:24:57 -0700811 actions_.push_back(shared_ptr<AbstractAction>(error_event_action));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700812 processor_->EnqueueAction(error_event_action.get());
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800813 SetStatusAndNotify(UPDATE_STATUS_REPORTING_ERROR_EVENT,
814 kUpdateNoticeUnspecified);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700815 processor_->StartProcessing();
Darin Petkov09f96c32010-07-20 09:24:57 -0700816 return true;
817}
818
Darin Petkovc6c135c2010-08-11 13:36:18 -0700819void UpdateAttempter::SetPriority(utils::ProcessPriority priority) {
820 if (priority_ == priority) {
821 return;
822 }
823 if (utils::SetProcessPriority(priority)) {
824 priority_ = priority;
825 LOG(INFO) << "Process priority = " << priority_;
826 }
827}
828
829void UpdateAttempter::SetupPriorityManagement() {
830 if (manage_priority_source_) {
831 LOG(ERROR) << "Process priority timeout source hasn't been destroyed.";
832 CleanupPriorityManagement();
833 }
Darin Petkovf622ef72010-10-26 13:49:24 -0700834 const int kPriorityTimeout = 2 * 60 * 60; // 2 hours
Darin Petkovc6c135c2010-08-11 13:36:18 -0700835 manage_priority_source_ = g_timeout_source_new_seconds(kPriorityTimeout);
836 g_source_set_callback(manage_priority_source_,
837 StaticManagePriorityCallback,
838 this,
839 NULL);
840 g_source_attach(manage_priority_source_, NULL);
841 SetPriority(utils::kProcessPriorityLow);
842}
843
844void UpdateAttempter::CleanupPriorityManagement() {
845 if (manage_priority_source_) {
846 g_source_destroy(manage_priority_source_);
847 manage_priority_source_ = NULL;
848 }
849 SetPriority(utils::kProcessPriorityNormal);
850}
851
852gboolean UpdateAttempter::StaticManagePriorityCallback(gpointer data) {
853 return reinterpret_cast<UpdateAttempter*>(data)->ManagePriorityCallback();
854}
855
Darin Petkove6ef2f82011-03-07 17:31:11 -0800856gboolean UpdateAttempter::StaticStartProcessing(gpointer data) {
857 reinterpret_cast<UpdateAttempter*>(data)->processor_->StartProcessing();
858 return FALSE; // Don't call this callback again.
859}
860
Darin Petkov58dd1342011-05-06 12:05:13 -0700861void UpdateAttempter::ScheduleProcessingStart() {
862 LOG(INFO) << "Scheduling an action processor start.";
863 start_action_processor_ = false;
864 g_idle_add(&StaticStartProcessing, this);
865}
866
Darin Petkovc6c135c2010-08-11 13:36:18 -0700867bool UpdateAttempter::ManagePriorityCallback() {
Darin Petkovf622ef72010-10-26 13:49:24 -0700868 SetPriority(utils::kProcessPriorityNormal);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700869 manage_priority_source_ = NULL;
Darin Petkovf622ef72010-10-26 13:49:24 -0700870 return false; // Destroy the timeout source.
Darin Petkovc6c135c2010-08-11 13:36:18 -0700871}
872
Darin Petkov36275772010-10-01 11:40:57 -0700873void UpdateAttempter::DisableDeltaUpdateIfNeeded() {
874 int64_t delta_failures;
875 if (omaha_request_params_.delta_okay &&
876 prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) &&
877 delta_failures >= kMaxDeltaUpdateFailures) {
878 LOG(WARNING) << "Too many delta update failures, forcing full update.";
879 omaha_request_params_.delta_okay = false;
880 }
881}
882
883void UpdateAttempter::MarkDeltaUpdateFailure() {
Darin Petkov2dd01092010-10-08 15:43:05 -0700884 // Don't try to resume a failed delta update.
885 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Darin Petkov36275772010-10-01 11:40:57 -0700886 int64_t delta_failures;
887 if (!prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) ||
888 delta_failures < 0) {
889 delta_failures = 0;
890 }
891 prefs_->SetInt64(kPrefsDeltaUpdateFailures, ++delta_failures);
892}
893
Darin Petkov9b230572010-10-08 10:20:09 -0700894void UpdateAttempter::SetupDownload() {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800895 MultiRangeHttpFetcher* fetcher =
896 dynamic_cast<MultiRangeHttpFetcher*>(download_action_->http_fetcher());
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800897 fetcher->ClearRanges();
Darin Petkov9b230572010-10-08 10:20:09 -0700898 if (response_handler_action_->install_plan().is_resume) {
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700899 // Resuming an update so fetch the update manifest metadata first.
Darin Petkov9b230572010-10-08 10:20:09 -0700900 int64_t manifest_metadata_size = 0;
901 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800902 fetcher->AddRange(0, manifest_metadata_size);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700903 // If there're remaining unprocessed data blobs, fetch them. Be careful not
904 // to request data beyond the end of the payload to avoid 416 HTTP response
905 // error codes.
Darin Petkov9b230572010-10-08 10:20:09 -0700906 int64_t next_data_offset = 0;
907 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700908 uint64_t resume_offset = manifest_metadata_size + next_data_offset;
909 if (resume_offset < response_handler_action_->install_plan().size) {
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800910 fetcher->AddRange(resume_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700911 }
Darin Petkov9b230572010-10-08 10:20:09 -0700912 } else {
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800913 fetcher->AddRange(0);
Darin Petkov9b230572010-10-08 10:20:09 -0700914 }
Darin Petkov9b230572010-10-08 10:20:09 -0700915}
916
Thieu Le116fda32011-04-19 11:01:54 -0700917void UpdateAttempter::PingOmaha() {
Thieu Led88a8572011-05-26 09:09:19 -0700918 if (!processor_->IsRunning()) {
919 shared_ptr<OmahaRequestAction> ping_action(
920 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700921 &omaha_request_params_,
Thieu Led88a8572011-05-26 09:09:19 -0700922 NULL,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700923 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700924 system_state_,
925 is_test_mode_),
Thieu Led88a8572011-05-26 09:09:19 -0700926 true));
927 actions_.push_back(shared_ptr<OmahaRequestAction>(ping_action));
928 processor_->set_delegate(NULL);
929 processor_->EnqueueAction(ping_action.get());
930 // Call StartProcessing() synchronously here to avoid any race conditions
931 // caused by multiple outstanding ping Omaha requests. If we call
932 // StartProcessing() asynchronously, the device can be suspended before we
933 // get a chance to callback to StartProcessing(). When the device resumes
934 // (assuming the device sleeps longer than the next update check period),
935 // StartProcessing() is called back and at the same time, the next update
936 // check is fired which eventually invokes StartProcessing(). A crash
937 // can occur because StartProcessing() checks to make sure that the
938 // processor is idle which it isn't due to the two concurrent ping Omaha
939 // requests.
940 processor_->StartProcessing();
941 } else {
Darin Petkov58dd1342011-05-06 12:05:13 -0700942 LOG(WARNING) << "Action processor running, Omaha ping suppressed.";
Darin Petkov58dd1342011-05-06 12:05:13 -0700943 }
Thieu Led88a8572011-05-26 09:09:19 -0700944
945 // Update the status which will schedule the next update check
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800946 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
947 kUpdateNoticeUnspecified);
Thieu Le116fda32011-04-19 11:01:54 -0700948}
949
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700950
951bool UpdateAttempter::DecrementUpdateCheckCount() {
952 int64 update_check_count_value;
953
954 if (!prefs_->Exists(kPrefsUpdateCheckCount)) {
955 // This file does not exist. This means we haven't started our update
956 // check count down yet, so nothing more to do. This file will be created
957 // later when we first satisfy the wall-clock-based-wait period.
958 LOG(INFO) << "No existing update check count. That's normal.";
959 return true;
960 }
961
962 if (prefs_->GetInt64(kPrefsUpdateCheckCount, &update_check_count_value)) {
963 // Only if we're able to read a proper integer value, then go ahead
964 // and decrement and write back the result in the same file, if needed.
965 LOG(INFO) << "Update check count = " << update_check_count_value;
966
967 if (update_check_count_value == 0) {
968 // It could be 0, if, for some reason, the file didn't get deleted
969 // when we set our status to waiting for reboot. so we just leave it
970 // as is so that we can prevent another update_check wait for this client.
971 LOG(INFO) << "Not decrementing update check count as it's already 0.";
972 return true;
973 }
974
975 if (update_check_count_value > 0)
976 update_check_count_value--;
977 else
978 update_check_count_value = 0;
979
980 // Write out the new value of update_check_count_value.
981 if (prefs_->SetInt64(kPrefsUpdateCheckCount, update_check_count_value)) {
982 // We successfully wrote out te new value, so enable the
983 // update check based wait.
984 LOG(INFO) << "New update check count = " << update_check_count_value;
985 return true;
986 }
987 }
988
989 LOG(INFO) << "Deleting update check count state due to read/write errors.";
990
991 // We cannot read/write to the file, so disable the update check based wait
992 // so that we don't get stuck in this OS version by any chance (which could
993 // happen if there's some bug that causes to read/write incorrectly).
994 // Also attempt to delete the file to do our best effort to cleanup.
995 prefs_->Delete(kPrefsUpdateCheckCount);
996 return false;
997}
998
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700999} // namespace chromeos_update_engine