blob: 52d6e4c2e97986cdfc7dc136868e00c40c867ee7 [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"
Darin Petkov1023a602010-08-30 13:47:51 -070035#include "update_engine/update_check_scheduler.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070036
Darin Petkovaf183052010-08-23 12:07:13 -070037using base::TimeDelta;
38using base::TimeTicks;
Andrew de los Reyes21816e12011-04-07 14:18:56 -070039using google::protobuf::NewPermanentCallback;
Darin Petkov9b230572010-10-08 10:20:09 -070040using std::make_pair;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070041using std::tr1::shared_ptr;
42using std::string;
43using std::vector;
44
45namespace chromeos_update_engine {
46
Darin Petkov36275772010-10-01 11:40:57 -070047const int UpdateAttempter::kMaxDeltaUpdateFailures = 3;
48
Gilad Arnold1ebd8132012-03-05 10:19:29 -080049// Private test server URL w/ custom port number.
Gilad Arnolded747312012-03-15 18:20:41 -070050// TODO(garnold) This is a temporary hack to allow us to test the closed loop
51// automated update testing. To be replaced with an hard-coded local IP address.
52const char* const UpdateAttempter::kTestUpdateUrl(
53 "http://garnold.mtv.corp.google.com:8080/update");
Gilad Arnold28e2f392012-02-09 14:36:46 -080054
Darin Petkovcd1666f2010-09-23 09:53:44 -070055const char* kUpdateCompletedMarker =
56 "/var/run/update_engine_autoupdate_completed";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -070057
Andrew de los Reyes45168102010-11-22 11:13:50 -080058namespace {
59const int kMaxConsecutiveObeyProxyRequests = 20;
60} // namespace {}
61
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070062const char* UpdateStatusToString(UpdateStatus status) {
63 switch (status) {
64 case UPDATE_STATUS_IDLE:
65 return "UPDATE_STATUS_IDLE";
66 case UPDATE_STATUS_CHECKING_FOR_UPDATE:
67 return "UPDATE_STATUS_CHECKING_FOR_UPDATE";
68 case UPDATE_STATUS_UPDATE_AVAILABLE:
69 return "UPDATE_STATUS_UPDATE_AVAILABLE";
70 case UPDATE_STATUS_DOWNLOADING:
71 return "UPDATE_STATUS_DOWNLOADING";
72 case UPDATE_STATUS_VERIFYING:
73 return "UPDATE_STATUS_VERIFYING";
74 case UPDATE_STATUS_FINALIZING:
75 return "UPDATE_STATUS_FINALIZING";
76 case UPDATE_STATUS_UPDATED_NEED_REBOOT:
77 return "UPDATE_STATUS_UPDATED_NEED_REBOOT";
Darin Petkov09f96c32010-07-20 09:24:57 -070078 case UPDATE_STATUS_REPORTING_ERROR_EVENT:
79 return "UPDATE_STATUS_REPORTING_ERROR_EVENT";
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070080 default:
81 return "unknown status";
82 }
83}
84
Darin Petkov777dbfa2010-07-20 15:03:37 -070085// Turns a generic kActionCodeError to a generic error code specific
86// to |action| (e.g., kActionCodeFilesystemCopierError). If |code| is
87// not kActionCodeError, or the action is not matched, returns |code|
88// unchanged.
89ActionExitCode GetErrorCodeForAction(AbstractAction* action,
90 ActionExitCode code) {
91 if (code != kActionCodeError)
92 return code;
93
94 const string type = action->Type();
95 if (type == OmahaRequestAction::StaticType())
96 return kActionCodeOmahaRequestError;
97 if (type == OmahaResponseHandlerAction::StaticType())
98 return kActionCodeOmahaResponseHandlerError;
99 if (type == FilesystemCopierAction::StaticType())
100 return kActionCodeFilesystemCopierError;
101 if (type == PostinstallRunnerAction::StaticType())
102 return kActionCodePostinstallRunnerError;
Darin Petkov777dbfa2010-07-20 15:03:37 -0700103
104 return code;
105}
106
Darin Petkovc6c135c2010-08-11 13:36:18 -0700107UpdateAttempter::UpdateAttempter(PrefsInterface* prefs,
Andrew de los Reyes45168102010-11-22 11:13:50 -0800108 MetricsLibraryInterface* metrics_lib,
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700109 DbusGlibInterface* dbus_iface,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700110 GpioHandler* gpio_handler,
111 SystemState* system_state)
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700112 : processor_(new ActionProcessor()),
113 dbus_service_(NULL),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700114 prefs_(prefs),
115 metrics_lib_(metrics_lib),
Darin Petkov1023a602010-08-30 13:47:51 -0700116 update_check_scheduler_(NULL),
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700117 fake_update_success_(false),
Darin Petkov1023a602010-08-30 13:47:51 -0700118 http_response_code_(0),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700119 priority_(utils::kProcessPriorityNormal),
120 manage_priority_source_(NULL),
Darin Petkov9d911fa2010-08-19 09:36:08 -0700121 download_active_(false),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700122 status_(UPDATE_STATUS_IDLE),
123 download_progress_(0.0),
124 last_checked_time_(0),
125 new_version_("0.0.0.0"),
Darin Petkov36275772010-10-01 11:40:57 -0700126 new_size_(0),
Andrew de los Reyes45168102010-11-22 11:13:50 -0800127 proxy_manual_checks_(0),
128 obeying_proxies_(true),
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700129 chrome_proxy_resolver_(dbus_iface),
Darin Petkov58dd1342011-05-06 12:05:13 -0700130 updated_boot_flags_(false),
131 update_boot_flags_running_(false),
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200132 start_action_processor_(false),
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800133 policy_provider_(NULL),
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700134 is_using_test_url_(false),
135 is_test_update_attempted_(false),
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700136 gpio_handler_(gpio_handler),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700137 init_waiting_period_from_prefs_(true),
138 system_state_(system_state) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700139 if (utils::FileExists(kUpdateCompletedMarker))
140 status_ = UPDATE_STATUS_UPDATED_NEED_REBOOT;
141}
142
143UpdateAttempter::~UpdateAttempter() {
144 CleanupPriorityManagement();
145}
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,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700151 bool is_test,
152 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,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700172 is_test,
173 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,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700192 bool is_test,
193 bool is_user_initiated) {
Darin Petkov1023a602010-08-30 13:47:51 -0700194 http_response_code_ = 0;
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200195
196 // Lazy initialize the policy provider, or reload the latest policy data.
197 if (!policy_provider_.get()) {
198 policy_provider_.reset(new policy::PolicyProvider());
199 } else {
200 policy_provider_->Reload();
201 }
202
203 // If the release_track is specified by policy, that takes precedence.
204 string release_track;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700205
206 // Take a copy of the old scatter value before we update it.
207 int64 old_scatter_factor_in_secs = scatter_factor_.InSeconds();
Jay Srinivasan0a708742012-03-20 11:26:12 -0700208 if (policy_provider_->device_policy_is_loaded()) {
209 const policy::DevicePolicy& device_policy =
210 policy_provider_->GetDevicePolicy();
211 device_policy.GetReleaseChannel(&release_track);
212 device_policy.GetUpdateDisabled(&omaha_request_params_.update_disabled);
213 device_policy.GetTargetVersionPrefix(
214 &omaha_request_params_.target_version_prefix);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700215 int64 new_scatter_factor_in_secs = 0;
216 device_policy.GetScatterFactorInSeconds(&new_scatter_factor_in_secs);
Jay Srinivasan08fce042012-06-07 16:31:01 -0700217 if (new_scatter_factor_in_secs < 0) // sanitize input, just in case.
218 new_scatter_factor_in_secs = 0;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700219 scatter_factor_ = TimeDelta::FromSeconds(new_scatter_factor_in_secs);
220 }
221
Jay Srinivasan08fce042012-06-07 16:31:01 -0700222 bool is_scatter_enabled = false;
223 if (scatter_factor_.InSeconds() == 0) {
224 LOG(INFO) << "Scattering disabled since scatter factor is set to 0";
225 } else if (is_user_initiated) {
226 LOG(INFO) << "Scattering disabled as this update check is user-initiated";
227 } else if (!system_state_->IsOOBEComplete()) {
228 LOG(INFO) << "Scattering disabled since OOBE is not complete yet";
229 } else {
230 is_scatter_enabled = true;
231 LOG(INFO) << "Scattering is enabled";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700232 }
233
Jay Srinivasan08fce042012-06-07 16:31:01 -0700234 if (is_scatter_enabled) {
235 // This means the scattering policy is turned on.
236 if (scatter_factor_.InSeconds() != old_scatter_factor_in_secs) {
237 int64 wait_period_in_secs = 0;
238 if (init_waiting_period_from_prefs_ &&
239 prefs_->GetInt64(kPrefsWallClockWaitPeriod, &wait_period_in_secs) &&
240 wait_period_in_secs >= 0 &&
241 wait_period_in_secs <= scatter_factor_.InSeconds()) {
242 // This means:
243 // 1. This is the first update check to come this far in this process.
244 // 2. There's a persisted value for the waiting period available.
245 // 3. And that persisted value is still valid.
246 // So, in this case, we should reuse the persisted value instead of
247 // generating a new random value to improve the chances of a good
248 // distribution for scattering.
249 omaha_request_params_.waiting_period =
250 TimeDelta::FromSeconds(wait_period_in_secs);
251 LOG(INFO) << "Using persisted value for wall clock based waiting period.";
252 } else {
253 // In this case, we should regenerate the waiting period to make sure
254 // it's within the bounds of the new scatter factor value.
255 omaha_request_params_.waiting_period = TimeDelta::FromSeconds(
256 base::RandInt(0, scatter_factor_.InSeconds()));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700257
Jay Srinivasan08fce042012-06-07 16:31:01 -0700258 LOG(INFO) << "Generated new value of " << utils::FormatSecs(
259 omaha_request_params_.waiting_period.InSeconds())
260 << " for wall clock based waiting period.";
261
262 // Do a best-effort to persist this. We'll work fine even if the
263 // persistence fails.
264 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
265 omaha_request_params_.waiting_period.InSeconds());
266 }
267 }
268
269 // We should reset this value since we're past the first initialization
270 // of the waiting period for this process.
271 init_waiting_period_from_prefs_ = false;
272
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700273 // This means the scattering policy is turned on. We'll do wall-clock-
274 // based-wait by default. And if we don't have any issues in accessing
275 // the file system to do update the update check count value, we'll
276 // turn that on as well.
277 omaha_request_params_.wall_clock_based_wait_enabled = true;
278 bool decrement_succeeded = DecrementUpdateCheckCount();
279 omaha_request_params_.update_check_count_wait_enabled = decrement_succeeded;
Jay Srinivasan08fce042012-06-07 16:31:01 -0700280 } else {
281 // This means the scattering feature is turned off. Make sure to disable
282 // all the knobs so that we don't invoke any scattering related code.
283 omaha_request_params_.wall_clock_based_wait_enabled = false;
284 omaha_request_params_.update_check_count_wait_enabled = false;
285 prefs_->Delete(kPrefsWallClockWaitPeriod);
286 prefs_->Delete(kPrefsUpdateCheckCount);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700287 }
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200288
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800289 // Determine whether an alternative test address should be used.
Gilad Arnold28e2f392012-02-09 14:36:46 -0800290 string omaha_url_to_use = omaha_url;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800291 if ((is_using_test_url_ = (omaha_url_to_use.empty() && is_test))) {
292 omaha_url_to_use = kTestUpdateUrl;
293 LOG(INFO) << "using alternative server address: " << omaha_url_to_use;
Gilad Arnold28e2f392012-02-09 14:36:46 -0800294 }
295
Jay Srinivasan0a708742012-03-20 11:26:12 -0700296 if (!omaha_request_params_.Init(app_version,
297 omaha_url_to_use,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800298 release_track)) {
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700299 LOG(ERROR) << "Unable to initialize Omaha request device params.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700300 return false;
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700301 }
Darin Petkov3aefa862010-12-07 14:45:00 -0800302
Jay Srinivasan0a708742012-03-20 11:26:12 -0700303 LOG(INFO) << "update_disabled = "
304 << (omaha_request_params_.update_disabled ? "true" : "false")
305 << ", target_version_prefix = "
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700306 << omaha_request_params_.target_version_prefix
307 << ", scatter_factor_in_seconds = "
308 << utils::FormatSecs(scatter_factor_.InSeconds());
309
310 LOG(INFO) << "Wall Clock Based Wait Enabled = "
311 << omaha_request_params_.wall_clock_based_wait_enabled
312 << ", Update Check Count Wait Enabled = "
313 << omaha_request_params_.update_check_count_wait_enabled
314 << ", Waiting Period = "
315 << utils::FormatSecs(
316 omaha_request_params_.waiting_period.InSeconds());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700317
Andrew de los Reyes45168102010-11-22 11:13:50 -0800318 obeying_proxies_ = true;
319 if (obey_proxies || proxy_manual_checks_ == 0) {
320 LOG(INFO) << "forced to obey proxies";
321 // If forced to obey proxies, every 20th request will not use proxies
322 proxy_manual_checks_++;
323 LOG(INFO) << "proxy manual checks: " << proxy_manual_checks_;
324 if (proxy_manual_checks_ >= kMaxConsecutiveObeyProxyRequests) {
325 proxy_manual_checks_ = 0;
326 obeying_proxies_ = false;
327 }
328 } else if (base::RandInt(0, 4) == 0) {
329 obeying_proxies_ = false;
330 }
331 LOG_IF(INFO, !obeying_proxies_) << "To help ensure updates work, this update "
332 "check we are ignoring the proxy settings and using "
333 "direct connections.";
334
Darin Petkov36275772010-10-01 11:40:57 -0700335 DisableDeltaUpdateIfNeeded();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700336 return true;
337}
338
339void UpdateAttempter::BuildUpdateActions(bool interactive) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700340 CHECK(!processor_->IsRunning());
341 processor_->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700342
343 // Actions:
Darin Petkova0929552010-11-29 14:19:06 -0800344 LibcurlHttpFetcher* update_check_fetcher =
Jay Srinivasan08fce042012-06-07 16:31:01 -0700345 new LibcurlHttpFetcher(GetProxyResolver(), system_state_);
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700346 // Try harder to connect to the network, esp when not interactive.
347 // See comment in libcurl_http_fetcher.cc.
348 update_check_fetcher->set_no_network_max_retries(interactive ? 1 : 3);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700349 update_check_fetcher->set_check_certificate(CertificateChecker::kUpdate);
Darin Petkov6a5b3222010-07-13 14:55:28 -0700350 shared_ptr<OmahaRequestAction> update_check_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700351 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700352 &omaha_request_params_,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700353 NULL,
Thieu Le116fda32011-04-19 11:01:54 -0700354 update_check_fetcher, // passes ownership
355 false));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700356 shared_ptr<OmahaResponseHandlerAction> response_handler_action(
Darin Petkov73058b42010-10-06 16:32:19 -0700357 new OmahaResponseHandlerAction(prefs_));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700358 shared_ptr<FilesystemCopierAction> filesystem_copier_action(
Darin Petkov3aefa862010-12-07 14:45:00 -0800359 new FilesystemCopierAction(false, false));
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700360 shared_ptr<FilesystemCopierAction> kernel_filesystem_copier_action(
Darin Petkov3aefa862010-12-07 14:45:00 -0800361 new FilesystemCopierAction(true, false));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700362 shared_ptr<OmahaRequestAction> download_started_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700363 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700364 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700365 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700366 OmahaEvent::kTypeUpdateDownloadStarted),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700367 new LibcurlHttpFetcher(GetProxyResolver(),
368 system_state_),
Thieu Le116fda32011-04-19 11:01:54 -0700369 false));
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700370 LibcurlHttpFetcher* download_fetcher =
Jay Srinivasan08fce042012-06-07 16:31:01 -0700371 new LibcurlHttpFetcher(GetProxyResolver(), system_state_);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700372 download_fetcher->set_check_certificate(CertificateChecker::kDownload);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700373 shared_ptr<DownloadAction> download_action(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700374 new DownloadAction(prefs_,
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800375 new MultiRangeHttpFetcher(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700376 download_fetcher))); // passes ownership
Darin Petkov8c2980e2010-07-16 15:16:49 -0700377 shared_ptr<OmahaRequestAction> download_finished_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700378 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700379 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700380 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700381 OmahaEvent::kTypeUpdateDownloadFinished),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700382 new LibcurlHttpFetcher(GetProxyResolver(),
383 system_state_),
Thieu Le116fda32011-04-19 11:01:54 -0700384 false));
Darin Petkov3aefa862010-12-07 14:45:00 -0800385 shared_ptr<FilesystemCopierAction> filesystem_verifier_action(
386 new FilesystemCopierAction(false, true));
387 shared_ptr<FilesystemCopierAction> kernel_filesystem_verifier_action(
388 new FilesystemCopierAction(true, true));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800389 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
390 new PostinstallRunnerAction);
Darin Petkov8c2980e2010-07-16 15:16:49 -0700391 shared_ptr<OmahaRequestAction> update_complete_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700392 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700393 &omaha_request_params_,
Darin Petkove17f86b2010-07-20 09:12:01 -0700394 new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700395 new LibcurlHttpFetcher(GetProxyResolver(),
396 system_state_),
Thieu Le116fda32011-04-19 11:01:54 -0700397 false));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700398
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700399 download_action->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700400 response_handler_action_ = response_handler_action;
Darin Petkov9b230572010-10-08 10:20:09 -0700401 download_action_ = download_action;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700402
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700403 actions_.push_back(shared_ptr<AbstractAction>(update_check_action));
404 actions_.push_back(shared_ptr<AbstractAction>(response_handler_action));
405 actions_.push_back(shared_ptr<AbstractAction>(filesystem_copier_action));
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700406 actions_.push_back(shared_ptr<AbstractAction>(
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700407 kernel_filesystem_copier_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700408 actions_.push_back(shared_ptr<AbstractAction>(download_started_action));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700409 actions_.push_back(shared_ptr<AbstractAction>(download_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700410 actions_.push_back(shared_ptr<AbstractAction>(download_finished_action));
Darin Petkov3aefa862010-12-07 14:45:00 -0800411 actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action));
412 actions_.push_back(shared_ptr<AbstractAction>(
413 kernel_filesystem_verifier_action));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800414 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700415 actions_.push_back(shared_ptr<AbstractAction>(update_complete_action));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700416
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700417 // Enqueue the actions
418 for (vector<shared_ptr<AbstractAction> >::iterator it = actions_.begin();
419 it != actions_.end(); ++it) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700420 processor_->EnqueueAction(it->get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700421 }
422
423 // Bond them together. We have to use the leaf-types when calling
424 // BondActions().
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700425 BondActions(update_check_action.get(),
426 response_handler_action.get());
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700427 BondActions(response_handler_action.get(),
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700428 filesystem_copier_action.get());
429 BondActions(filesystem_copier_action.get(),
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700430 kernel_filesystem_copier_action.get());
431 BondActions(kernel_filesystem_copier_action.get(),
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700432 download_action.get());
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700433 BondActions(download_action.get(),
Darin Petkov3aefa862010-12-07 14:45:00 -0800434 filesystem_verifier_action.get());
435 BondActions(filesystem_verifier_action.get(),
436 kernel_filesystem_verifier_action.get());
437 BondActions(kernel_filesystem_verifier_action.get(),
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800438 postinstall_runner_action.get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700439}
440
Gilad Arnold28e2f392012-02-09 14:36:46 -0800441void UpdateAttempter::CheckForUpdate(const string& app_version,
442 const string& omaha_url) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700443 LOG(INFO) << "New update check requested";
444
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700445 if (status_ != UPDATE_STATUS_IDLE) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700446 LOG(INFO) << "Skipping update check because current status is "
447 << UpdateStatusToString(status_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700448 return;
449 }
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800450
451 // Read GPIO signals and determine whether this is an automated test scenario.
452 // For safety, we only allow a test update to be performed once; subsequent
453 // update requests will be carried out normally.
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700454 bool is_test = (!is_test_update_attempted_ && gpio_handler_ &&
455 gpio_handler_->IsTestModeSignaled());
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800456 if (is_test) {
457 LOG(INFO) << "test mode signaled";
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700458 is_test_update_attempted_ = true;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800459 }
460
Jay Srinivasan08fce042012-06-07 16:31:01 -0700461 // Passing true for is_user_initiated to indicate that this
462 // is not a scheduled update check.
463 Update(app_version, omaha_url, true, true, is_test, true);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700464}
465
Darin Petkov296889c2010-07-23 16:20:54 -0700466bool UpdateAttempter::RebootIfNeeded() {
467 if (status_ != UPDATE_STATUS_UPDATED_NEED_REBOOT) {
468 LOG(INFO) << "Reboot requested, but status is "
469 << UpdateStatusToString(status_) << ", so not rebooting.";
470 return false;
471 }
472 TEST_AND_RETURN_FALSE(utils::Reboot());
473 return true;
474}
475
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700476// Delegate methods:
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700477void UpdateAttempter::ProcessingDone(const ActionProcessor* processor,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700478 ActionExitCode code) {
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700479 CHECK(response_handler_action_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700480 LOG(INFO) << "Processing Done.";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700481 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700482
Darin Petkovc6c135c2010-08-11 13:36:18 -0700483 // Reset process priority back to normal.
484 CleanupPriorityManagement();
485
Darin Petkov09f96c32010-07-20 09:24:57 -0700486 if (status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
487 LOG(INFO) << "Error event sent.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800488
489 // Inform scheduler of new status; also specifically inform about a failed
490 // update attempt with a test address.
491 SetStatusAndNotify(UPDATE_STATUS_IDLE,
492 (is_using_test_url_ ? kUpdateNoticeTestAddrFailed :
493 kUpdateNoticeUnspecified));
494
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700495 if (!fake_update_success_) {
496 return;
497 }
498 LOG(INFO) << "Booted from FW B and tried to install new firmware, "
499 "so requesting reboot from user.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700500 }
501
Darin Petkovc1a8b422010-07-19 11:34:49 -0700502 if (code == kActionCodeSuccess) {
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700503 utils::WriteFile(kUpdateCompletedMarker, "", 0);
Darin Petkov36275772010-10-01 11:40:57 -0700504 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Darin Petkov95508da2011-01-05 12:42:29 -0800505 prefs_->SetString(kPrefsPreviousVersion, omaha_request_params_.app_version);
Darin Petkov9b230572010-10-08 10:20:09 -0700506 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700507
508 // Since we're done with scattering fully at this point, this is the
509 // safest point delete the state files, as we're sure that the status is
510 // set to reboot (which means no more updates will be applied until reboot)
511 // This deletion is required for correctness as we want the next update
512 // check to re-create a new random number for the update check count.
513 // Similarly, we also delete the wall-clock-wait period that was persisted
514 // so that we start with a new random value for the next update check
515 // after reboot so that the same device is not favored or punished in any
516 // way.
517 prefs_->Delete(kPrefsUpdateCheckCount);
518 prefs_->Delete(kPrefsWallClockWaitPeriod);
519
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800520 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
521 kUpdateNoticeUnspecified);
Darin Petkov9d65b7b2010-07-20 09:13:01 -0700522
523 // Report the time it took to update the system.
524 int64_t update_time = time(NULL) - last_checked_time_;
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700525 if (!fake_update_success_)
526 metrics_lib_->SendToUMA("Installer.UpdateTime",
527 static_cast<int>(update_time), // sample
528 1, // min = 1 second
529 20 * 60, // max = 20 minutes
530 50); // buckets
Darin Petkov09f96c32010-07-20 09:24:57 -0700531 return;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700532 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700533
Darin Petkov1023a602010-08-30 13:47:51 -0700534 if (ScheduleErrorEventAction()) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700535 return;
Darin Petkov1023a602010-08-30 13:47:51 -0700536 }
537 LOG(INFO) << "No update.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800538 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700539}
540
541void UpdateAttempter::ProcessingStopped(const ActionProcessor* processor) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700542 // Reset process priority back to normal.
543 CleanupPriorityManagement();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700544 download_progress_ = 0.0;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800545 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700546 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700547 error_event_.reset(NULL);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700548}
549
550// Called whenever an action has finished processing, either successfully
551// or otherwise.
552void UpdateAttempter::ActionCompleted(ActionProcessor* processor,
553 AbstractAction* action,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700554 ActionExitCode code) {
Darin Petkov1023a602010-08-30 13:47:51 -0700555 // Reset download progress regardless of whether or not the download
556 // action succeeded. Also, get the response code from HTTP request
557 // actions (update download as well as the initial update check
558 // actions).
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700559 const string type = action->Type();
Darin Petkov1023a602010-08-30 13:47:51 -0700560 if (type == DownloadAction::StaticType()) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700561 download_progress_ = 0.0;
Darin Petkov1023a602010-08-30 13:47:51 -0700562 DownloadAction* download_action = dynamic_cast<DownloadAction*>(action);
563 http_response_code_ = download_action->GetHTTPResponseCode();
564 } else if (type == OmahaRequestAction::StaticType()) {
565 OmahaRequestAction* omaha_request_action =
566 dynamic_cast<OmahaRequestAction*>(action);
567 // If the request is not an event, then it's the update-check.
568 if (!omaha_request_action->IsEvent()) {
569 http_response_code_ = omaha_request_action->GetHTTPResponseCode();
Darin Petkov85ced132010-09-01 10:20:56 -0700570 // Forward the server-dictated poll interval to the update check
571 // scheduler, if any.
572 if (update_check_scheduler_) {
573 update_check_scheduler_->set_poll_interval(
574 omaha_request_action->GetOutputObject().poll_interval);
575 }
Darin Petkov1023a602010-08-30 13:47:51 -0700576 }
577 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700578 if (code != kActionCodeSuccess) {
Darin Petkov7ed561b2011-10-04 02:59:03 -0700579 // If the current state is at or past the download phase, count the failure
580 // in case a switch to full update becomes necessary. Ignore network
581 // transfer timeouts and failures.
Darin Petkov36275772010-10-01 11:40:57 -0700582 if (status_ >= UPDATE_STATUS_DOWNLOADING &&
Darin Petkov36275772010-10-01 11:40:57 -0700583 code != kActionCodeDownloadTransferError) {
584 MarkDeltaUpdateFailure();
585 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700586 // On failure, schedule an error event to be sent to Omaha.
587 CreatePendingErrorEvent(action, code);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700588 return;
Darin Petkov09f96c32010-07-20 09:24:57 -0700589 }
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700590 // Find out which action completed.
591 if (type == OmahaResponseHandlerAction::StaticType()) {
Darin Petkov9b230572010-10-08 10:20:09 -0700592 // Note that the status will be updated to DOWNLOADING when some bytes get
593 // actually downloaded from the server and the BytesReceived callback is
594 // invoked. This avoids notifying the user that a download has started in
595 // cases when the server and the client are unable to initiate the download.
596 CHECK(action == response_handler_action_.get());
597 const InstallPlan& plan = response_handler_action_->install_plan();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700598 last_checked_time_ = time(NULL);
599 // TODO(adlr): put version in InstallPlan
600 new_version_ = "0.0.0.0";
601 new_size_ = plan.size;
Darin Petkov9b230572010-10-08 10:20:09 -0700602 SetupDownload();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700603 SetupPriorityManagement();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800604 SetStatusAndNotify(UPDATE_STATUS_UPDATE_AVAILABLE,
605 kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700606 } else if (type == DownloadAction::StaticType()) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800607 SetStatusAndNotify(UPDATE_STATUS_FINALIZING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700608 }
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700609}
610
611// Stop updating. An attempt will be made to record status to the disk
612// so that updates can be resumed later.
613void UpdateAttempter::Terminate() {
614 // TODO(adlr): implement this method.
615 NOTIMPLEMENTED();
616}
617
618// Try to resume from a previously Terminate()d update.
619void UpdateAttempter::ResumeUpdating() {
620 // TODO(adlr): implement this method.
621 NOTIMPLEMENTED();
622}
623
Darin Petkov9d911fa2010-08-19 09:36:08 -0700624void UpdateAttempter::SetDownloadStatus(bool active) {
625 download_active_ = active;
626 LOG(INFO) << "Download status: " << (active ? "active" : "inactive");
627}
628
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700629void UpdateAttempter::BytesReceived(uint64_t bytes_received, uint64_t total) {
Darin Petkov9d911fa2010-08-19 09:36:08 -0700630 if (!download_active_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700631 LOG(ERROR) << "BytesReceived called while not downloading.";
632 return;
633 }
Darin Petkovaf183052010-08-23 12:07:13 -0700634 double progress = static_cast<double>(bytes_received) /
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700635 static_cast<double>(total);
Darin Petkovaf183052010-08-23 12:07:13 -0700636 // Self throttle based on progress. Also send notifications if
637 // progress is too slow.
638 const double kDeltaPercent = 0.01; // 1%
639 if (status_ != UPDATE_STATUS_DOWNLOADING ||
640 bytes_received == total ||
641 progress - download_progress_ >= kDeltaPercent ||
642 TimeTicks::Now() - last_notify_time_ >= TimeDelta::FromSeconds(10)) {
643 download_progress_ = progress;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800644 SetStatusAndNotify(UPDATE_STATUS_DOWNLOADING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700645 }
646}
647
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700648bool UpdateAttempter::GetStatus(int64_t* last_checked_time,
649 double* progress,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800650 string* current_operation,
651 string* new_version,
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700652 int64_t* new_size) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700653 *last_checked_time = last_checked_time_;
654 *progress = download_progress_;
655 *current_operation = UpdateStatusToString(status_);
656 *new_version = new_version_;
657 *new_size = new_size_;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700658 return true;
659}
660
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700661void UpdateAttempter::UpdateBootFlags() {
Darin Petkov58dd1342011-05-06 12:05:13 -0700662 if (update_boot_flags_running_) {
663 LOG(INFO) << "Update boot flags running, nothing to do.";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700664 return;
665 }
Darin Petkov58dd1342011-05-06 12:05:13 -0700666 if (updated_boot_flags_) {
667 LOG(INFO) << "Already updated boot flags. Skipping.";
668 if (start_action_processor_) {
669 ScheduleProcessingStart();
670 }
671 return;
672 }
673 // This is purely best effort. Failures should be logged by Subprocess. Run
674 // the script asynchronously to avoid blocking the event loop regardless of
675 // the script runtime.
676 update_boot_flags_running_ = true;
677 LOG(INFO) << "Updating boot flags...";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700678 vector<string> cmd(1, "/usr/sbin/chromeos-setgoodkernel");
Darin Petkov58dd1342011-05-06 12:05:13 -0700679 if (!Subprocess::Get().Exec(cmd, StaticCompleteUpdateBootFlags, this)) {
680 CompleteUpdateBootFlags(1);
681 }
682}
683
684void UpdateAttempter::CompleteUpdateBootFlags(int return_code) {
685 update_boot_flags_running_ = false;
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700686 updated_boot_flags_ = true;
Darin Petkov58dd1342011-05-06 12:05:13 -0700687 if (start_action_processor_) {
688 ScheduleProcessingStart();
689 }
690}
691
692void UpdateAttempter::StaticCompleteUpdateBootFlags(
693 int return_code,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800694 const string& output,
Darin Petkov58dd1342011-05-06 12:05:13 -0700695 void* p) {
696 reinterpret_cast<UpdateAttempter*>(p)->CompleteUpdateBootFlags(return_code);
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700697}
698
Darin Petkov61635a92011-05-18 16:20:36 -0700699void UpdateAttempter::BroadcastStatus() {
700 if (!dbus_service_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700701 return;
Darin Petkov61635a92011-05-18 16:20:36 -0700702 }
Darin Petkovaf183052010-08-23 12:07:13 -0700703 last_notify_time_ = TimeTicks::Now();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700704 update_engine_service_emit_status_update(
705 dbus_service_,
706 last_checked_time_,
707 download_progress_,
708 UpdateStatusToString(status_),
709 new_version_.c_str(),
710 new_size_);
711}
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700712
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800713void UpdateAttempter::SetStatusAndNotify(UpdateStatus status,
714 UpdateNotice notice) {
Darin Petkov61635a92011-05-18 16:20:36 -0700715 status_ = status;
716 if (update_check_scheduler_) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800717 update_check_scheduler_->SetUpdateStatus(status_, notice);
Darin Petkov61635a92011-05-18 16:20:36 -0700718 }
719 BroadcastStatus();
720}
721
Darin Petkov777dbfa2010-07-20 15:03:37 -0700722void UpdateAttempter::CreatePendingErrorEvent(AbstractAction* action,
723 ActionExitCode code) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700724 if (error_event_.get()) {
725 // This shouldn't really happen.
726 LOG(WARNING) << "There's already an existing pending error event.";
727 return;
728 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700729
Darin Petkovabc7bc02011-02-23 14:39:43 -0800730 // For now assume that a generic Omaha response action failure means that
731 // there's no update so don't send an event. Also, double check that the
732 // failure has not occurred while sending an error event -- in which case
733 // don't schedule another. This shouldn't really happen but just in case...
734 if ((action->Type() == OmahaResponseHandlerAction::StaticType() &&
735 code == kActionCodeError) ||
Darin Petkov777dbfa2010-07-20 15:03:37 -0700736 status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
737 return;
738 }
739
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700740 // Classify the code to generate the appropriate result so that
741 // the Borgmon charts show up the results correctly.
742 // Do this before calling GetErrorCodeForAction which could potentially
743 // augment the bit representation of code and thus cause no matches for
744 // the switch cases below.
745 OmahaEvent::Result event_result;
746 switch (code) {
747 case kActionCodeOmahaUpdateIgnoredPerPolicy:
748 case kActionCodeOmahaUpdateDeferredPerPolicy:
749 event_result = OmahaEvent::kResultUpdateDeferred;
750 break;
751 default:
752 event_result = OmahaEvent::kResultError;
753 break;
754 }
755
Darin Petkov777dbfa2010-07-20 15:03:37 -0700756 code = GetErrorCodeForAction(action, code);
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700757 fake_update_success_ = code == kActionCodePostinstallBootedFromFirmwareB;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700758
759 // Apply the bit modifiers to the error code.
760 if (!utils::IsNormalBootMode()) {
761 code = static_cast<ActionExitCode>(code | kActionCodeBootModeFlag);
762 }
763 if (response_handler_action_.get() &&
764 response_handler_action_->install_plan().is_resume) {
765 code = static_cast<ActionExitCode>(code | kActionCodeResumedFlag);
766 }
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700767
Darin Petkov09f96c32010-07-20 09:24:57 -0700768 error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700769 event_result,
Darin Petkov09f96c32010-07-20 09:24:57 -0700770 code));
771}
772
773bool UpdateAttempter::ScheduleErrorEventAction() {
774 if (error_event_.get() == NULL)
775 return false;
776
Darin Petkov1023a602010-08-30 13:47:51 -0700777 LOG(INFO) << "Update failed -- reporting the error event.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700778 shared_ptr<OmahaRequestAction> error_event_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700779 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700780 &omaha_request_params_,
Darin Petkov09f96c32010-07-20 09:24:57 -0700781 error_event_.release(), // Pass ownership.
Jay Srinivasan08fce042012-06-07 16:31:01 -0700782 new LibcurlHttpFetcher(GetProxyResolver(),
783 system_state_),
Thieu Le116fda32011-04-19 11:01:54 -0700784 false));
Darin Petkov09f96c32010-07-20 09:24:57 -0700785 actions_.push_back(shared_ptr<AbstractAction>(error_event_action));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700786 processor_->EnqueueAction(error_event_action.get());
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800787 SetStatusAndNotify(UPDATE_STATUS_REPORTING_ERROR_EVENT,
788 kUpdateNoticeUnspecified);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700789 processor_->StartProcessing();
Darin Petkov09f96c32010-07-20 09:24:57 -0700790 return true;
791}
792
Darin Petkovc6c135c2010-08-11 13:36:18 -0700793void UpdateAttempter::SetPriority(utils::ProcessPriority priority) {
794 if (priority_ == priority) {
795 return;
796 }
797 if (utils::SetProcessPriority(priority)) {
798 priority_ = priority;
799 LOG(INFO) << "Process priority = " << priority_;
800 }
801}
802
803void UpdateAttempter::SetupPriorityManagement() {
804 if (manage_priority_source_) {
805 LOG(ERROR) << "Process priority timeout source hasn't been destroyed.";
806 CleanupPriorityManagement();
807 }
Darin Petkovf622ef72010-10-26 13:49:24 -0700808 const int kPriorityTimeout = 2 * 60 * 60; // 2 hours
Darin Petkovc6c135c2010-08-11 13:36:18 -0700809 manage_priority_source_ = g_timeout_source_new_seconds(kPriorityTimeout);
810 g_source_set_callback(manage_priority_source_,
811 StaticManagePriorityCallback,
812 this,
813 NULL);
814 g_source_attach(manage_priority_source_, NULL);
815 SetPriority(utils::kProcessPriorityLow);
816}
817
818void UpdateAttempter::CleanupPriorityManagement() {
819 if (manage_priority_source_) {
820 g_source_destroy(manage_priority_source_);
821 manage_priority_source_ = NULL;
822 }
823 SetPriority(utils::kProcessPriorityNormal);
824}
825
826gboolean UpdateAttempter::StaticManagePriorityCallback(gpointer data) {
827 return reinterpret_cast<UpdateAttempter*>(data)->ManagePriorityCallback();
828}
829
Darin Petkove6ef2f82011-03-07 17:31:11 -0800830gboolean UpdateAttempter::StaticStartProcessing(gpointer data) {
831 reinterpret_cast<UpdateAttempter*>(data)->processor_->StartProcessing();
832 return FALSE; // Don't call this callback again.
833}
834
Darin Petkov58dd1342011-05-06 12:05:13 -0700835void UpdateAttempter::ScheduleProcessingStart() {
836 LOG(INFO) << "Scheduling an action processor start.";
837 start_action_processor_ = false;
838 g_idle_add(&StaticStartProcessing, this);
839}
840
Darin Petkovc6c135c2010-08-11 13:36:18 -0700841bool UpdateAttempter::ManagePriorityCallback() {
Darin Petkovf622ef72010-10-26 13:49:24 -0700842 SetPriority(utils::kProcessPriorityNormal);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700843 manage_priority_source_ = NULL;
Darin Petkovf622ef72010-10-26 13:49:24 -0700844 return false; // Destroy the timeout source.
Darin Petkovc6c135c2010-08-11 13:36:18 -0700845}
846
Darin Petkov36275772010-10-01 11:40:57 -0700847void UpdateAttempter::DisableDeltaUpdateIfNeeded() {
848 int64_t delta_failures;
849 if (omaha_request_params_.delta_okay &&
850 prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) &&
851 delta_failures >= kMaxDeltaUpdateFailures) {
852 LOG(WARNING) << "Too many delta update failures, forcing full update.";
853 omaha_request_params_.delta_okay = false;
854 }
855}
856
857void UpdateAttempter::MarkDeltaUpdateFailure() {
Darin Petkov2dd01092010-10-08 15:43:05 -0700858 // Don't try to resume a failed delta update.
859 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Darin Petkov36275772010-10-01 11:40:57 -0700860 int64_t delta_failures;
861 if (!prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) ||
862 delta_failures < 0) {
863 delta_failures = 0;
864 }
865 prefs_->SetInt64(kPrefsDeltaUpdateFailures, ++delta_failures);
866}
867
Darin Petkov9b230572010-10-08 10:20:09 -0700868void UpdateAttempter::SetupDownload() {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800869 MultiRangeHttpFetcher* fetcher =
870 dynamic_cast<MultiRangeHttpFetcher*>(download_action_->http_fetcher());
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800871 fetcher->ClearRanges();
Darin Petkov9b230572010-10-08 10:20:09 -0700872 if (response_handler_action_->install_plan().is_resume) {
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700873 // Resuming an update so fetch the update manifest metadata first.
Darin Petkov9b230572010-10-08 10:20:09 -0700874 int64_t manifest_metadata_size = 0;
875 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800876 fetcher->AddRange(0, manifest_metadata_size);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700877 // If there're remaining unprocessed data blobs, fetch them. Be careful not
878 // to request data beyond the end of the payload to avoid 416 HTTP response
879 // error codes.
Darin Petkov9b230572010-10-08 10:20:09 -0700880 int64_t next_data_offset = 0;
881 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700882 uint64_t resume_offset = manifest_metadata_size + next_data_offset;
883 if (resume_offset < response_handler_action_->install_plan().size) {
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800884 fetcher->AddRange(resume_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700885 }
Darin Petkov9b230572010-10-08 10:20:09 -0700886 } else {
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800887 fetcher->AddRange(0);
Darin Petkov9b230572010-10-08 10:20:09 -0700888 }
Darin Petkov9b230572010-10-08 10:20:09 -0700889}
890
Thieu Le116fda32011-04-19 11:01:54 -0700891void UpdateAttempter::PingOmaha() {
Thieu Led88a8572011-05-26 09:09:19 -0700892 if (!processor_->IsRunning()) {
893 shared_ptr<OmahaRequestAction> ping_action(
894 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700895 &omaha_request_params_,
Thieu Led88a8572011-05-26 09:09:19 -0700896 NULL,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700897 new LibcurlHttpFetcher(GetProxyResolver(),
898 system_state_),
Thieu Led88a8572011-05-26 09:09:19 -0700899 true));
900 actions_.push_back(shared_ptr<OmahaRequestAction>(ping_action));
901 processor_->set_delegate(NULL);
902 processor_->EnqueueAction(ping_action.get());
903 // Call StartProcessing() synchronously here to avoid any race conditions
904 // caused by multiple outstanding ping Omaha requests. If we call
905 // StartProcessing() asynchronously, the device can be suspended before we
906 // get a chance to callback to StartProcessing(). When the device resumes
907 // (assuming the device sleeps longer than the next update check period),
908 // StartProcessing() is called back and at the same time, the next update
909 // check is fired which eventually invokes StartProcessing(). A crash
910 // can occur because StartProcessing() checks to make sure that the
911 // processor is idle which it isn't due to the two concurrent ping Omaha
912 // requests.
913 processor_->StartProcessing();
914 } else {
Darin Petkov58dd1342011-05-06 12:05:13 -0700915 LOG(WARNING) << "Action processor running, Omaha ping suppressed.";
Darin Petkov58dd1342011-05-06 12:05:13 -0700916 }
Thieu Led88a8572011-05-26 09:09:19 -0700917
918 // Update the status which will schedule the next update check
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800919 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
920 kUpdateNoticeUnspecified);
Thieu Le116fda32011-04-19 11:01:54 -0700921}
922
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700923
924bool UpdateAttempter::DecrementUpdateCheckCount() {
925 int64 update_check_count_value;
926
927 if (!prefs_->Exists(kPrefsUpdateCheckCount)) {
928 // This file does not exist. This means we haven't started our update
929 // check count down yet, so nothing more to do. This file will be created
930 // later when we first satisfy the wall-clock-based-wait period.
931 LOG(INFO) << "No existing update check count. That's normal.";
932 return true;
933 }
934
935 if (prefs_->GetInt64(kPrefsUpdateCheckCount, &update_check_count_value)) {
936 // Only if we're able to read a proper integer value, then go ahead
937 // and decrement and write back the result in the same file, if needed.
938 LOG(INFO) << "Update check count = " << update_check_count_value;
939
940 if (update_check_count_value == 0) {
941 // It could be 0, if, for some reason, the file didn't get deleted
942 // when we set our status to waiting for reboot. so we just leave it
943 // as is so that we can prevent another update_check wait for this client.
944 LOG(INFO) << "Not decrementing update check count as it's already 0.";
945 return true;
946 }
947
948 if (update_check_count_value > 0)
949 update_check_count_value--;
950 else
951 update_check_count_value = 0;
952
953 // Write out the new value of update_check_count_value.
954 if (prefs_->SetInt64(kPrefsUpdateCheckCount, update_check_count_value)) {
955 // We successfully wrote out te new value, so enable the
956 // update check based wait.
957 LOG(INFO) << "New update check count = " << update_check_count_value;
958 return true;
959 }
960 }
961
962 LOG(INFO) << "Deleting update check count state due to read/write errors.";
963
964 // We cannot read/write to the file, so disable the update check based wait
965 // so that we don't get stuck in this OS version by any chance (which could
966 // happen if there's some bug that causes to read/write incorrectly).
967 // Also attempt to delete the file to do our best effort to cleanup.
968 prefs_->Delete(kPrefsUpdateCheckCount);
969 return false;
970}
971
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700972} // namespace chromeos_update_engine