blob: da9e7ccb5e5f42f08120ee2f24e47518e388b4d9 [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,
110 GpioHandler* gpio_handler)
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700111 : processor_(new ActionProcessor()),
112 dbus_service_(NULL),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700113 prefs_(prefs),
114 metrics_lib_(metrics_lib),
Darin Petkov1023a602010-08-30 13:47:51 -0700115 update_check_scheduler_(NULL),
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700116 fake_update_success_(false),
Darin Petkov1023a602010-08-30 13:47:51 -0700117 http_response_code_(0),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700118 priority_(utils::kProcessPriorityNormal),
119 manage_priority_source_(NULL),
Darin Petkov9d911fa2010-08-19 09:36:08 -0700120 download_active_(false),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700121 status_(UPDATE_STATUS_IDLE),
122 download_progress_(0.0),
123 last_checked_time_(0),
124 new_version_("0.0.0.0"),
Darin Petkov36275772010-10-01 11:40:57 -0700125 new_size_(0),
Andrew de los Reyes45168102010-11-22 11:13:50 -0800126 proxy_manual_checks_(0),
127 obeying_proxies_(true),
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700128 chrome_proxy_resolver_(dbus_iface),
Darin Petkov58dd1342011-05-06 12:05:13 -0700129 updated_boot_flags_(false),
130 update_boot_flags_running_(false),
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200131 start_action_processor_(false),
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800132 policy_provider_(NULL),
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700133 is_using_test_url_(false),
134 is_test_update_attempted_(false),
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700135 gpio_handler_(gpio_handler),
136 init_waiting_period_from_prefs_(true) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700137 if (utils::FileExists(kUpdateCompletedMarker))
138 status_ = UPDATE_STATUS_UPDATED_NEED_REBOOT;
139}
140
141UpdateAttempter::~UpdateAttempter() {
142 CleanupPriorityManagement();
143}
144
Gilad Arnold28e2f392012-02-09 14:36:46 -0800145void UpdateAttempter::Update(const string& app_version,
146 const string& omaha_url,
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700147 bool obey_proxies,
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800148 bool interactive,
149 bool is_test) {
Andrew de los Reyes000d8952011-03-02 15:21:14 -0800150 chrome_proxy_resolver_.Init();
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700151 fake_update_success_ = false;
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700152 if (status_ == UPDATE_STATUS_UPDATED_NEED_REBOOT) {
Thieu Le116fda32011-04-19 11:01:54 -0700153 // Although we have applied an update, we still want to ping Omaha
154 // to ensure the number of active statistics is accurate.
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700155 LOG(INFO) << "Not updating b/c we already updated and we're waiting for "
Thieu Le116fda32011-04-19 11:01:54 -0700156 << "reboot, we'll ping Omaha instead";
157 PingOmaha();
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700158 return;
159 }
160 if (status_ != UPDATE_STATUS_IDLE) {
161 // Update in progress. Do nothing
162 return;
163 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700164
165 if (!CalculateUpdateParams(app_version,
166 omaha_url,
167 obey_proxies,
168 interactive,
169 is_test)) {
170 return;
171 }
172
173 BuildUpdateActions(interactive);
174
175 SetStatusAndNotify(UPDATE_STATUS_CHECKING_FOR_UPDATE,
176 kUpdateNoticeUnspecified);
177
178 // Just in case we didn't update boot flags yet, make sure they're updated
179 // before any update processing starts.
180 start_action_processor_ = true;
181 UpdateBootFlags();
182}
183
184bool UpdateAttempter::CalculateUpdateParams(const string& app_version,
185 const string& omaha_url,
186 bool obey_proxies,
187 bool interactive,
188 bool is_test) {
Darin Petkov1023a602010-08-30 13:47:51 -0700189 http_response_code_ = 0;
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200190
191 // Lazy initialize the policy provider, or reload the latest policy data.
192 if (!policy_provider_.get()) {
193 policy_provider_.reset(new policy::PolicyProvider());
194 } else {
195 policy_provider_->Reload();
196 }
197
198 // If the release_track is specified by policy, that takes precedence.
199 string release_track;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700200
201 // Take a copy of the old scatter value before we update it.
202 int64 old_scatter_factor_in_secs = scatter_factor_.InSeconds();
Jay Srinivasan0a708742012-03-20 11:26:12 -0700203 if (policy_provider_->device_policy_is_loaded()) {
204 const policy::DevicePolicy& device_policy =
205 policy_provider_->GetDevicePolicy();
206 device_policy.GetReleaseChannel(&release_track);
207 device_policy.GetUpdateDisabled(&omaha_request_params_.update_disabled);
208 device_policy.GetTargetVersionPrefix(
209 &omaha_request_params_.target_version_prefix);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700210 int64 new_scatter_factor_in_secs = 0;
211 device_policy.GetScatterFactorInSeconds(&new_scatter_factor_in_secs);
212 scatter_factor_ = TimeDelta::FromSeconds(new_scatter_factor_in_secs);
213 }
214
215 if (scatter_factor_.InSeconds() != old_scatter_factor_in_secs) {
216 int64 wait_period_in_secs = 0;
217 if (init_waiting_period_from_prefs_ &&
218 prefs_->GetInt64(kPrefsWallClockWaitPeriod, &wait_period_in_secs) &&
219 wait_period_in_secs >= 0 &&
220 wait_period_in_secs <= scatter_factor_.InSeconds()) {
221 // This means:
222 // 1. This is the first update check to come this far in this process.
223 // 2. There's a persisted value for the waiting period available.
224 // 3. And that persisted value is still valid.
225 // So, in this case, we should reuse the persisted value instead of
226 // generating a new random value to improve the chances of a good
227 // distribution for scattering.
228 omaha_request_params_.waiting_period =
229 TimeDelta::FromSeconds(wait_period_in_secs);
230 LOG(INFO) << "Using persisted value for wall clock based waiting period.";
231 } else {
232 // In this case, we should regenerate the waiting period to make sure
233 // it's within the bounds of the new scatter factor value.
234 omaha_request_params_.waiting_period = TimeDelta::FromSeconds(
235 base::RandInt(0, scatter_factor_.InSeconds()));
236
237 LOG(INFO) << "Generated new value of " << utils::FormatSecs(
238 omaha_request_params_.waiting_period.InSeconds())
239 << " for wall clock based waiting period.";
240
241 // Do a best-effort to persist this. We'll work fine even if the
242 // persistence fails.
243 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
244 omaha_request_params_.waiting_period.InSeconds());
245 }
246 }
247
248 // We should reset this value since we're past the first initialization
249 // of the waiting period for this process.
250 init_waiting_period_from_prefs_ = false;
251
252 if (scatter_factor_.InSeconds() == 0) {
253 // This means the scattering feature is turned off. Make sure to disable
254 // all the knobs so that we don't invoke any scattering related code.
255 omaha_request_params_.wall_clock_based_wait_enabled = false;
256 omaha_request_params_.update_check_count_wait_enabled = false;
257 prefs_->Delete(kPrefsWallClockWaitPeriod);
258 prefs_->Delete(kPrefsUpdateCheckCount);
259 } else {
260 // This means the scattering policy is turned on. We'll do wall-clock-
261 // based-wait by default. And if we don't have any issues in accessing
262 // the file system to do update the update check count value, we'll
263 // turn that on as well.
264 omaha_request_params_.wall_clock_based_wait_enabled = true;
265 bool decrement_succeeded = DecrementUpdateCheckCount();
266 omaha_request_params_.update_check_count_wait_enabled = decrement_succeeded;
Jay Srinivasan0a708742012-03-20 11:26:12 -0700267 }
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200268
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800269 // Determine whether an alternative test address should be used.
Gilad Arnold28e2f392012-02-09 14:36:46 -0800270 string omaha_url_to_use = omaha_url;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800271 if ((is_using_test_url_ = (omaha_url_to_use.empty() && is_test))) {
272 omaha_url_to_use = kTestUpdateUrl;
273 LOG(INFO) << "using alternative server address: " << omaha_url_to_use;
Gilad Arnold28e2f392012-02-09 14:36:46 -0800274 }
275
Jay Srinivasan0a708742012-03-20 11:26:12 -0700276 if (!omaha_request_params_.Init(app_version,
277 omaha_url_to_use,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800278 release_track)) {
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700279 LOG(ERROR) << "Unable to initialize Omaha request device params.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700280 return false;
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700281 }
Darin Petkov3aefa862010-12-07 14:45:00 -0800282
Jay Srinivasan0a708742012-03-20 11:26:12 -0700283 LOG(INFO) << "update_disabled = "
284 << (omaha_request_params_.update_disabled ? "true" : "false")
285 << ", target_version_prefix = "
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700286 << omaha_request_params_.target_version_prefix
287 << ", scatter_factor_in_seconds = "
288 << utils::FormatSecs(scatter_factor_.InSeconds());
289
290 LOG(INFO) << "Wall Clock Based Wait Enabled = "
291 << omaha_request_params_.wall_clock_based_wait_enabled
292 << ", Update Check Count Wait Enabled = "
293 << omaha_request_params_.update_check_count_wait_enabled
294 << ", Waiting Period = "
295 << utils::FormatSecs(
296 omaha_request_params_.waiting_period.InSeconds());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700297
Andrew de los Reyes45168102010-11-22 11:13:50 -0800298 obeying_proxies_ = true;
299 if (obey_proxies || proxy_manual_checks_ == 0) {
300 LOG(INFO) << "forced to obey proxies";
301 // If forced to obey proxies, every 20th request will not use proxies
302 proxy_manual_checks_++;
303 LOG(INFO) << "proxy manual checks: " << proxy_manual_checks_;
304 if (proxy_manual_checks_ >= kMaxConsecutiveObeyProxyRequests) {
305 proxy_manual_checks_ = 0;
306 obeying_proxies_ = false;
307 }
308 } else if (base::RandInt(0, 4) == 0) {
309 obeying_proxies_ = false;
310 }
311 LOG_IF(INFO, !obeying_proxies_) << "To help ensure updates work, this update "
312 "check we are ignoring the proxy settings and using "
313 "direct connections.";
314
Darin Petkov36275772010-10-01 11:40:57 -0700315 DisableDeltaUpdateIfNeeded();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700316 return true;
317}
318
319void UpdateAttempter::BuildUpdateActions(bool interactive) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700320 CHECK(!processor_->IsRunning());
321 processor_->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700322
323 // Actions:
Darin Petkova0929552010-11-29 14:19:06 -0800324 LibcurlHttpFetcher* update_check_fetcher =
325 new LibcurlHttpFetcher(GetProxyResolver());
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700326 // Try harder to connect to the network, esp when not interactive.
327 // See comment in libcurl_http_fetcher.cc.
328 update_check_fetcher->set_no_network_max_retries(interactive ? 1 : 3);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700329 update_check_fetcher->set_check_certificate(CertificateChecker::kUpdate);
Darin Petkov6a5b3222010-07-13 14:55:28 -0700330 shared_ptr<OmahaRequestAction> update_check_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700331 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700332 &omaha_request_params_,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700333 NULL,
Thieu Le116fda32011-04-19 11:01:54 -0700334 update_check_fetcher, // passes ownership
335 false));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700336 shared_ptr<OmahaResponseHandlerAction> response_handler_action(
Darin Petkov73058b42010-10-06 16:32:19 -0700337 new OmahaResponseHandlerAction(prefs_));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700338 shared_ptr<FilesystemCopierAction> filesystem_copier_action(
Darin Petkov3aefa862010-12-07 14:45:00 -0800339 new FilesystemCopierAction(false, false));
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700340 shared_ptr<FilesystemCopierAction> kernel_filesystem_copier_action(
Darin Petkov3aefa862010-12-07 14:45:00 -0800341 new FilesystemCopierAction(true, false));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700342 shared_ptr<OmahaRequestAction> download_started_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700343 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700344 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700345 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700346 OmahaEvent::kTypeUpdateDownloadStarted),
Thieu Le116fda32011-04-19 11:01:54 -0700347 new LibcurlHttpFetcher(GetProxyResolver()),
348 false));
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700349 LibcurlHttpFetcher* download_fetcher =
350 new LibcurlHttpFetcher(GetProxyResolver());
351 download_fetcher->set_check_certificate(CertificateChecker::kDownload);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700352 shared_ptr<DownloadAction> download_action(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700353 new DownloadAction(prefs_,
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800354 new MultiRangeHttpFetcher(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700355 download_fetcher))); // passes ownership
Darin Petkov8c2980e2010-07-16 15:16:49 -0700356 shared_ptr<OmahaRequestAction> download_finished_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700357 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700358 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700359 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700360 OmahaEvent::kTypeUpdateDownloadFinished),
Thieu Le116fda32011-04-19 11:01:54 -0700361 new LibcurlHttpFetcher(GetProxyResolver()),
362 false));
Darin Petkov3aefa862010-12-07 14:45:00 -0800363 shared_ptr<FilesystemCopierAction> filesystem_verifier_action(
364 new FilesystemCopierAction(false, true));
365 shared_ptr<FilesystemCopierAction> kernel_filesystem_verifier_action(
366 new FilesystemCopierAction(true, true));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800367 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
368 new PostinstallRunnerAction);
Darin Petkov8c2980e2010-07-16 15:16:49 -0700369 shared_ptr<OmahaRequestAction> update_complete_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700370 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700371 &omaha_request_params_,
Darin Petkove17f86b2010-07-20 09:12:01 -0700372 new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
Thieu Le116fda32011-04-19 11:01:54 -0700373 new LibcurlHttpFetcher(GetProxyResolver()),
374 false));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700375
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700376 download_action->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700377 response_handler_action_ = response_handler_action;
Darin Petkov9b230572010-10-08 10:20:09 -0700378 download_action_ = download_action;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700379
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700380 actions_.push_back(shared_ptr<AbstractAction>(update_check_action));
381 actions_.push_back(shared_ptr<AbstractAction>(response_handler_action));
382 actions_.push_back(shared_ptr<AbstractAction>(filesystem_copier_action));
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700383 actions_.push_back(shared_ptr<AbstractAction>(
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700384 kernel_filesystem_copier_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700385 actions_.push_back(shared_ptr<AbstractAction>(download_started_action));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700386 actions_.push_back(shared_ptr<AbstractAction>(download_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700387 actions_.push_back(shared_ptr<AbstractAction>(download_finished_action));
Darin Petkov3aefa862010-12-07 14:45:00 -0800388 actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action));
389 actions_.push_back(shared_ptr<AbstractAction>(
390 kernel_filesystem_verifier_action));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800391 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700392 actions_.push_back(shared_ptr<AbstractAction>(update_complete_action));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700393
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700394 // Enqueue the actions
395 for (vector<shared_ptr<AbstractAction> >::iterator it = actions_.begin();
396 it != actions_.end(); ++it) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700397 processor_->EnqueueAction(it->get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700398 }
399
400 // Bond them together. We have to use the leaf-types when calling
401 // BondActions().
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700402 BondActions(update_check_action.get(),
403 response_handler_action.get());
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700404 BondActions(response_handler_action.get(),
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700405 filesystem_copier_action.get());
406 BondActions(filesystem_copier_action.get(),
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700407 kernel_filesystem_copier_action.get());
408 BondActions(kernel_filesystem_copier_action.get(),
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700409 download_action.get());
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700410 BondActions(download_action.get(),
Darin Petkov3aefa862010-12-07 14:45:00 -0800411 filesystem_verifier_action.get());
412 BondActions(filesystem_verifier_action.get(),
413 kernel_filesystem_verifier_action.get());
414 BondActions(kernel_filesystem_verifier_action.get(),
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800415 postinstall_runner_action.get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700416}
417
Gilad Arnold28e2f392012-02-09 14:36:46 -0800418void UpdateAttempter::CheckForUpdate(const string& app_version,
419 const string& omaha_url) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700420 if (status_ != UPDATE_STATUS_IDLE) {
421 LOG(INFO) << "Check for update requested, but status is "
422 << UpdateStatusToString(status_) << ", so not checking.";
423 return;
424 }
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800425
426 // Read GPIO signals and determine whether this is an automated test scenario.
427 // For safety, we only allow a test update to be performed once; subsequent
428 // update requests will be carried out normally.
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700429 bool is_test = (!is_test_update_attempted_ && gpio_handler_ &&
430 gpio_handler_->IsTestModeSignaled());
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800431 if (is_test) {
432 LOG(INFO) << "test mode signaled";
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700433 is_test_update_attempted_ = true;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800434 }
435
436 Update(app_version, omaha_url, true, true, is_test);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700437}
438
Darin Petkov296889c2010-07-23 16:20:54 -0700439bool UpdateAttempter::RebootIfNeeded() {
440 if (status_ != UPDATE_STATUS_UPDATED_NEED_REBOOT) {
441 LOG(INFO) << "Reboot requested, but status is "
442 << UpdateStatusToString(status_) << ", so not rebooting.";
443 return false;
444 }
445 TEST_AND_RETURN_FALSE(utils::Reboot());
446 return true;
447}
448
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700449// Delegate methods:
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700450void UpdateAttempter::ProcessingDone(const ActionProcessor* processor,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700451 ActionExitCode code) {
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700452 CHECK(response_handler_action_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700453 LOG(INFO) << "Processing Done.";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700454 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700455
Darin Petkovc6c135c2010-08-11 13:36:18 -0700456 // Reset process priority back to normal.
457 CleanupPriorityManagement();
458
Darin Petkov09f96c32010-07-20 09:24:57 -0700459 if (status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
460 LOG(INFO) << "Error event sent.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800461
462 // Inform scheduler of new status; also specifically inform about a failed
463 // update attempt with a test address.
464 SetStatusAndNotify(UPDATE_STATUS_IDLE,
465 (is_using_test_url_ ? kUpdateNoticeTestAddrFailed :
466 kUpdateNoticeUnspecified));
467
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700468 if (!fake_update_success_) {
469 return;
470 }
471 LOG(INFO) << "Booted from FW B and tried to install new firmware, "
472 "so requesting reboot from user.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700473 }
474
Darin Petkovc1a8b422010-07-19 11:34:49 -0700475 if (code == kActionCodeSuccess) {
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700476 utils::WriteFile(kUpdateCompletedMarker, "", 0);
Darin Petkov36275772010-10-01 11:40:57 -0700477 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Darin Petkov95508da2011-01-05 12:42:29 -0800478 prefs_->SetString(kPrefsPreviousVersion, omaha_request_params_.app_version);
Darin Petkov9b230572010-10-08 10:20:09 -0700479 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700480
481 // Since we're done with scattering fully at this point, this is the
482 // safest point delete the state files, as we're sure that the status is
483 // set to reboot (which means no more updates will be applied until reboot)
484 // This deletion is required for correctness as we want the next update
485 // check to re-create a new random number for the update check count.
486 // Similarly, we also delete the wall-clock-wait period that was persisted
487 // so that we start with a new random value for the next update check
488 // after reboot so that the same device is not favored or punished in any
489 // way.
490 prefs_->Delete(kPrefsUpdateCheckCount);
491 prefs_->Delete(kPrefsWallClockWaitPeriod);
492
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800493 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
494 kUpdateNoticeUnspecified);
Darin Petkov9d65b7b2010-07-20 09:13:01 -0700495
496 // Report the time it took to update the system.
497 int64_t update_time = time(NULL) - last_checked_time_;
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700498 if (!fake_update_success_)
499 metrics_lib_->SendToUMA("Installer.UpdateTime",
500 static_cast<int>(update_time), // sample
501 1, // min = 1 second
502 20 * 60, // max = 20 minutes
503 50); // buckets
Darin Petkov09f96c32010-07-20 09:24:57 -0700504 return;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700505 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700506
Darin Petkov1023a602010-08-30 13:47:51 -0700507 if (ScheduleErrorEventAction()) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700508 return;
Darin Petkov1023a602010-08-30 13:47:51 -0700509 }
510 LOG(INFO) << "No update.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800511 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700512}
513
514void UpdateAttempter::ProcessingStopped(const ActionProcessor* processor) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700515 // Reset process priority back to normal.
516 CleanupPriorityManagement();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700517 download_progress_ = 0.0;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800518 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700519 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700520 error_event_.reset(NULL);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700521}
522
523// Called whenever an action has finished processing, either successfully
524// or otherwise.
525void UpdateAttempter::ActionCompleted(ActionProcessor* processor,
526 AbstractAction* action,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700527 ActionExitCode code) {
Darin Petkov1023a602010-08-30 13:47:51 -0700528 // Reset download progress regardless of whether or not the download
529 // action succeeded. Also, get the response code from HTTP request
530 // actions (update download as well as the initial update check
531 // actions).
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700532 const string type = action->Type();
Darin Petkov1023a602010-08-30 13:47:51 -0700533 if (type == DownloadAction::StaticType()) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700534 download_progress_ = 0.0;
Darin Petkov1023a602010-08-30 13:47:51 -0700535 DownloadAction* download_action = dynamic_cast<DownloadAction*>(action);
536 http_response_code_ = download_action->GetHTTPResponseCode();
537 } else if (type == OmahaRequestAction::StaticType()) {
538 OmahaRequestAction* omaha_request_action =
539 dynamic_cast<OmahaRequestAction*>(action);
540 // If the request is not an event, then it's the update-check.
541 if (!omaha_request_action->IsEvent()) {
542 http_response_code_ = omaha_request_action->GetHTTPResponseCode();
Darin Petkov85ced132010-09-01 10:20:56 -0700543 // Forward the server-dictated poll interval to the update check
544 // scheduler, if any.
545 if (update_check_scheduler_) {
546 update_check_scheduler_->set_poll_interval(
547 omaha_request_action->GetOutputObject().poll_interval);
548 }
Darin Petkov1023a602010-08-30 13:47:51 -0700549 }
550 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700551 if (code != kActionCodeSuccess) {
Darin Petkov7ed561b2011-10-04 02:59:03 -0700552 // If the current state is at or past the download phase, count the failure
553 // in case a switch to full update becomes necessary. Ignore network
554 // transfer timeouts and failures.
Darin Petkov36275772010-10-01 11:40:57 -0700555 if (status_ >= UPDATE_STATUS_DOWNLOADING &&
Darin Petkov36275772010-10-01 11:40:57 -0700556 code != kActionCodeDownloadTransferError) {
557 MarkDeltaUpdateFailure();
558 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700559 // On failure, schedule an error event to be sent to Omaha.
560 CreatePendingErrorEvent(action, code);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700561 return;
Darin Petkov09f96c32010-07-20 09:24:57 -0700562 }
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700563 // Find out which action completed.
564 if (type == OmahaResponseHandlerAction::StaticType()) {
Darin Petkov9b230572010-10-08 10:20:09 -0700565 // Note that the status will be updated to DOWNLOADING when some bytes get
566 // actually downloaded from the server and the BytesReceived callback is
567 // invoked. This avoids notifying the user that a download has started in
568 // cases when the server and the client are unable to initiate the download.
569 CHECK(action == response_handler_action_.get());
570 const InstallPlan& plan = response_handler_action_->install_plan();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700571 last_checked_time_ = time(NULL);
572 // TODO(adlr): put version in InstallPlan
573 new_version_ = "0.0.0.0";
574 new_size_ = plan.size;
Darin Petkov9b230572010-10-08 10:20:09 -0700575 SetupDownload();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700576 SetupPriorityManagement();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800577 SetStatusAndNotify(UPDATE_STATUS_UPDATE_AVAILABLE,
578 kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700579 } else if (type == DownloadAction::StaticType()) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800580 SetStatusAndNotify(UPDATE_STATUS_FINALIZING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700581 }
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700582}
583
584// Stop updating. An attempt will be made to record status to the disk
585// so that updates can be resumed later.
586void UpdateAttempter::Terminate() {
587 // TODO(adlr): implement this method.
588 NOTIMPLEMENTED();
589}
590
591// Try to resume from a previously Terminate()d update.
592void UpdateAttempter::ResumeUpdating() {
593 // TODO(adlr): implement this method.
594 NOTIMPLEMENTED();
595}
596
Darin Petkov9d911fa2010-08-19 09:36:08 -0700597void UpdateAttempter::SetDownloadStatus(bool active) {
598 download_active_ = active;
599 LOG(INFO) << "Download status: " << (active ? "active" : "inactive");
600}
601
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700602void UpdateAttempter::BytesReceived(uint64_t bytes_received, uint64_t total) {
Darin Petkov9d911fa2010-08-19 09:36:08 -0700603 if (!download_active_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700604 LOG(ERROR) << "BytesReceived called while not downloading.";
605 return;
606 }
Darin Petkovaf183052010-08-23 12:07:13 -0700607 double progress = static_cast<double>(bytes_received) /
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700608 static_cast<double>(total);
Darin Petkovaf183052010-08-23 12:07:13 -0700609 // Self throttle based on progress. Also send notifications if
610 // progress is too slow.
611 const double kDeltaPercent = 0.01; // 1%
612 if (status_ != UPDATE_STATUS_DOWNLOADING ||
613 bytes_received == total ||
614 progress - download_progress_ >= kDeltaPercent ||
615 TimeTicks::Now() - last_notify_time_ >= TimeDelta::FromSeconds(10)) {
616 download_progress_ = progress;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800617 SetStatusAndNotify(UPDATE_STATUS_DOWNLOADING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700618 }
619}
620
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700621bool UpdateAttempter::GetStatus(int64_t* last_checked_time,
622 double* progress,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800623 string* current_operation,
624 string* new_version,
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700625 int64_t* new_size) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700626 *last_checked_time = last_checked_time_;
627 *progress = download_progress_;
628 *current_operation = UpdateStatusToString(status_);
629 *new_version = new_version_;
630 *new_size = new_size_;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700631 return true;
632}
633
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700634void UpdateAttempter::UpdateBootFlags() {
Darin Petkov58dd1342011-05-06 12:05:13 -0700635 if (update_boot_flags_running_) {
636 LOG(INFO) << "Update boot flags running, nothing to do.";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700637 return;
638 }
Darin Petkov58dd1342011-05-06 12:05:13 -0700639 if (updated_boot_flags_) {
640 LOG(INFO) << "Already updated boot flags. Skipping.";
641 if (start_action_processor_) {
642 ScheduleProcessingStart();
643 }
644 return;
645 }
646 // This is purely best effort. Failures should be logged by Subprocess. Run
647 // the script asynchronously to avoid blocking the event loop regardless of
648 // the script runtime.
649 update_boot_flags_running_ = true;
650 LOG(INFO) << "Updating boot flags...";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700651 vector<string> cmd(1, "/usr/sbin/chromeos-setgoodkernel");
Darin Petkov58dd1342011-05-06 12:05:13 -0700652 if (!Subprocess::Get().Exec(cmd, StaticCompleteUpdateBootFlags, this)) {
653 CompleteUpdateBootFlags(1);
654 }
655}
656
657void UpdateAttempter::CompleteUpdateBootFlags(int return_code) {
658 update_boot_flags_running_ = false;
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700659 updated_boot_flags_ = true;
Darin Petkov58dd1342011-05-06 12:05:13 -0700660 if (start_action_processor_) {
661 ScheduleProcessingStart();
662 }
663}
664
665void UpdateAttempter::StaticCompleteUpdateBootFlags(
666 int return_code,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800667 const string& output,
Darin Petkov58dd1342011-05-06 12:05:13 -0700668 void* p) {
669 reinterpret_cast<UpdateAttempter*>(p)->CompleteUpdateBootFlags(return_code);
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700670}
671
Darin Petkov61635a92011-05-18 16:20:36 -0700672void UpdateAttempter::BroadcastStatus() {
673 if (!dbus_service_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700674 return;
Darin Petkov61635a92011-05-18 16:20:36 -0700675 }
Darin Petkovaf183052010-08-23 12:07:13 -0700676 last_notify_time_ = TimeTicks::Now();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700677 update_engine_service_emit_status_update(
678 dbus_service_,
679 last_checked_time_,
680 download_progress_,
681 UpdateStatusToString(status_),
682 new_version_.c_str(),
683 new_size_);
684}
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700685
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800686void UpdateAttempter::SetStatusAndNotify(UpdateStatus status,
687 UpdateNotice notice) {
Darin Petkov61635a92011-05-18 16:20:36 -0700688 status_ = status;
689 if (update_check_scheduler_) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800690 update_check_scheduler_->SetUpdateStatus(status_, notice);
Darin Petkov61635a92011-05-18 16:20:36 -0700691 }
692 BroadcastStatus();
693}
694
Darin Petkov777dbfa2010-07-20 15:03:37 -0700695void UpdateAttempter::CreatePendingErrorEvent(AbstractAction* action,
696 ActionExitCode code) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700697 if (error_event_.get()) {
698 // This shouldn't really happen.
699 LOG(WARNING) << "There's already an existing pending error event.";
700 return;
701 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700702
Darin Petkovabc7bc02011-02-23 14:39:43 -0800703 // For now assume that a generic Omaha response action failure means that
704 // there's no update so don't send an event. Also, double check that the
705 // failure has not occurred while sending an error event -- in which case
706 // don't schedule another. This shouldn't really happen but just in case...
707 if ((action->Type() == OmahaResponseHandlerAction::StaticType() &&
708 code == kActionCodeError) ||
Darin Petkov777dbfa2010-07-20 15:03:37 -0700709 status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
710 return;
711 }
712
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700713 // Classify the code to generate the appropriate result so that
714 // the Borgmon charts show up the results correctly.
715 // Do this before calling GetErrorCodeForAction which could potentially
716 // augment the bit representation of code and thus cause no matches for
717 // the switch cases below.
718 OmahaEvent::Result event_result;
719 switch (code) {
720 case kActionCodeOmahaUpdateIgnoredPerPolicy:
721 case kActionCodeOmahaUpdateDeferredPerPolicy:
722 event_result = OmahaEvent::kResultUpdateDeferred;
723 break;
724 default:
725 event_result = OmahaEvent::kResultError;
726 break;
727 }
728
Darin Petkov777dbfa2010-07-20 15:03:37 -0700729 code = GetErrorCodeForAction(action, code);
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700730 fake_update_success_ = code == kActionCodePostinstallBootedFromFirmwareB;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700731
732 // Apply the bit modifiers to the error code.
733 if (!utils::IsNormalBootMode()) {
734 code = static_cast<ActionExitCode>(code | kActionCodeBootModeFlag);
735 }
736 if (response_handler_action_.get() &&
737 response_handler_action_->install_plan().is_resume) {
738 code = static_cast<ActionExitCode>(code | kActionCodeResumedFlag);
739 }
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700740
Darin Petkov09f96c32010-07-20 09:24:57 -0700741 error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700742 event_result,
Darin Petkov09f96c32010-07-20 09:24:57 -0700743 code));
744}
745
746bool UpdateAttempter::ScheduleErrorEventAction() {
747 if (error_event_.get() == NULL)
748 return false;
749
Darin Petkov1023a602010-08-30 13:47:51 -0700750 LOG(INFO) << "Update failed -- reporting the error event.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700751 shared_ptr<OmahaRequestAction> error_event_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700752 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700753 &omaha_request_params_,
Darin Petkov09f96c32010-07-20 09:24:57 -0700754 error_event_.release(), // Pass ownership.
Thieu Le116fda32011-04-19 11:01:54 -0700755 new LibcurlHttpFetcher(GetProxyResolver()),
756 false));
Darin Petkov09f96c32010-07-20 09:24:57 -0700757 actions_.push_back(shared_ptr<AbstractAction>(error_event_action));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700758 processor_->EnqueueAction(error_event_action.get());
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800759 SetStatusAndNotify(UPDATE_STATUS_REPORTING_ERROR_EVENT,
760 kUpdateNoticeUnspecified);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700761 processor_->StartProcessing();
Darin Petkov09f96c32010-07-20 09:24:57 -0700762 return true;
763}
764
Darin Petkovc6c135c2010-08-11 13:36:18 -0700765void UpdateAttempter::SetPriority(utils::ProcessPriority priority) {
766 if (priority_ == priority) {
767 return;
768 }
769 if (utils::SetProcessPriority(priority)) {
770 priority_ = priority;
771 LOG(INFO) << "Process priority = " << priority_;
772 }
773}
774
775void UpdateAttempter::SetupPriorityManagement() {
776 if (manage_priority_source_) {
777 LOG(ERROR) << "Process priority timeout source hasn't been destroyed.";
778 CleanupPriorityManagement();
779 }
Darin Petkovf622ef72010-10-26 13:49:24 -0700780 const int kPriorityTimeout = 2 * 60 * 60; // 2 hours
Darin Petkovc6c135c2010-08-11 13:36:18 -0700781 manage_priority_source_ = g_timeout_source_new_seconds(kPriorityTimeout);
782 g_source_set_callback(manage_priority_source_,
783 StaticManagePriorityCallback,
784 this,
785 NULL);
786 g_source_attach(manage_priority_source_, NULL);
787 SetPriority(utils::kProcessPriorityLow);
788}
789
790void UpdateAttempter::CleanupPriorityManagement() {
791 if (manage_priority_source_) {
792 g_source_destroy(manage_priority_source_);
793 manage_priority_source_ = NULL;
794 }
795 SetPriority(utils::kProcessPriorityNormal);
796}
797
798gboolean UpdateAttempter::StaticManagePriorityCallback(gpointer data) {
799 return reinterpret_cast<UpdateAttempter*>(data)->ManagePriorityCallback();
800}
801
Darin Petkove6ef2f82011-03-07 17:31:11 -0800802gboolean UpdateAttempter::StaticStartProcessing(gpointer data) {
803 reinterpret_cast<UpdateAttempter*>(data)->processor_->StartProcessing();
804 return FALSE; // Don't call this callback again.
805}
806
Darin Petkov58dd1342011-05-06 12:05:13 -0700807void UpdateAttempter::ScheduleProcessingStart() {
808 LOG(INFO) << "Scheduling an action processor start.";
809 start_action_processor_ = false;
810 g_idle_add(&StaticStartProcessing, this);
811}
812
Darin Petkovc6c135c2010-08-11 13:36:18 -0700813bool UpdateAttempter::ManagePriorityCallback() {
Darin Petkovf622ef72010-10-26 13:49:24 -0700814 SetPriority(utils::kProcessPriorityNormal);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700815 manage_priority_source_ = NULL;
Darin Petkovf622ef72010-10-26 13:49:24 -0700816 return false; // Destroy the timeout source.
Darin Petkovc6c135c2010-08-11 13:36:18 -0700817}
818
Darin Petkov36275772010-10-01 11:40:57 -0700819void UpdateAttempter::DisableDeltaUpdateIfNeeded() {
820 int64_t delta_failures;
821 if (omaha_request_params_.delta_okay &&
822 prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) &&
823 delta_failures >= kMaxDeltaUpdateFailures) {
824 LOG(WARNING) << "Too many delta update failures, forcing full update.";
825 omaha_request_params_.delta_okay = false;
826 }
827}
828
829void UpdateAttempter::MarkDeltaUpdateFailure() {
Darin Petkov2dd01092010-10-08 15:43:05 -0700830 // Don't try to resume a failed delta update.
831 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Darin Petkov36275772010-10-01 11:40:57 -0700832 int64_t delta_failures;
833 if (!prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) ||
834 delta_failures < 0) {
835 delta_failures = 0;
836 }
837 prefs_->SetInt64(kPrefsDeltaUpdateFailures, ++delta_failures);
838}
839
Darin Petkov9b230572010-10-08 10:20:09 -0700840void UpdateAttempter::SetupDownload() {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800841 MultiRangeHttpFetcher* fetcher =
842 dynamic_cast<MultiRangeHttpFetcher*>(download_action_->http_fetcher());
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800843 fetcher->ClearRanges();
Darin Petkov9b230572010-10-08 10:20:09 -0700844 if (response_handler_action_->install_plan().is_resume) {
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700845 // Resuming an update so fetch the update manifest metadata first.
Darin Petkov9b230572010-10-08 10:20:09 -0700846 int64_t manifest_metadata_size = 0;
847 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800848 fetcher->AddRange(0, manifest_metadata_size);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700849 // If there're remaining unprocessed data blobs, fetch them. Be careful not
850 // to request data beyond the end of the payload to avoid 416 HTTP response
851 // error codes.
Darin Petkov9b230572010-10-08 10:20:09 -0700852 int64_t next_data_offset = 0;
853 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700854 uint64_t resume_offset = manifest_metadata_size + next_data_offset;
855 if (resume_offset < response_handler_action_->install_plan().size) {
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800856 fetcher->AddRange(resume_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700857 }
Darin Petkov9b230572010-10-08 10:20:09 -0700858 } else {
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800859 fetcher->AddRange(0);
Darin Petkov9b230572010-10-08 10:20:09 -0700860 }
Darin Petkov9b230572010-10-08 10:20:09 -0700861}
862
Thieu Le116fda32011-04-19 11:01:54 -0700863void UpdateAttempter::PingOmaha() {
Thieu Led88a8572011-05-26 09:09:19 -0700864 if (!processor_->IsRunning()) {
865 shared_ptr<OmahaRequestAction> ping_action(
866 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700867 &omaha_request_params_,
Thieu Led88a8572011-05-26 09:09:19 -0700868 NULL,
869 new LibcurlHttpFetcher(GetProxyResolver()),
870 true));
871 actions_.push_back(shared_ptr<OmahaRequestAction>(ping_action));
872 processor_->set_delegate(NULL);
873 processor_->EnqueueAction(ping_action.get());
874 // Call StartProcessing() synchronously here to avoid any race conditions
875 // caused by multiple outstanding ping Omaha requests. If we call
876 // StartProcessing() asynchronously, the device can be suspended before we
877 // get a chance to callback to StartProcessing(). When the device resumes
878 // (assuming the device sleeps longer than the next update check period),
879 // StartProcessing() is called back and at the same time, the next update
880 // check is fired which eventually invokes StartProcessing(). A crash
881 // can occur because StartProcessing() checks to make sure that the
882 // processor is idle which it isn't due to the two concurrent ping Omaha
883 // requests.
884 processor_->StartProcessing();
885 } else {
Darin Petkov58dd1342011-05-06 12:05:13 -0700886 LOG(WARNING) << "Action processor running, Omaha ping suppressed.";
Darin Petkov58dd1342011-05-06 12:05:13 -0700887 }
Thieu Led88a8572011-05-26 09:09:19 -0700888
889 // Update the status which will schedule the next update check
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800890 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
891 kUpdateNoticeUnspecified);
Thieu Le116fda32011-04-19 11:01:54 -0700892}
893
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700894
895bool UpdateAttempter::DecrementUpdateCheckCount() {
896 int64 update_check_count_value;
897
898 if (!prefs_->Exists(kPrefsUpdateCheckCount)) {
899 // This file does not exist. This means we haven't started our update
900 // check count down yet, so nothing more to do. This file will be created
901 // later when we first satisfy the wall-clock-based-wait period.
902 LOG(INFO) << "No existing update check count. That's normal.";
903 return true;
904 }
905
906 if (prefs_->GetInt64(kPrefsUpdateCheckCount, &update_check_count_value)) {
907 // Only if we're able to read a proper integer value, then go ahead
908 // and decrement and write back the result in the same file, if needed.
909 LOG(INFO) << "Update check count = " << update_check_count_value;
910
911 if (update_check_count_value == 0) {
912 // It could be 0, if, for some reason, the file didn't get deleted
913 // when we set our status to waiting for reboot. so we just leave it
914 // as is so that we can prevent another update_check wait for this client.
915 LOG(INFO) << "Not decrementing update check count as it's already 0.";
916 return true;
917 }
918
919 if (update_check_count_value > 0)
920 update_check_count_value--;
921 else
922 update_check_count_value = 0;
923
924 // Write out the new value of update_check_count_value.
925 if (prefs_->SetInt64(kPrefsUpdateCheckCount, update_check_count_value)) {
926 // We successfully wrote out te new value, so enable the
927 // update check based wait.
928 LOG(INFO) << "New update check count = " << update_check_count_value;
929 return true;
930 }
931 }
932
933 LOG(INFO) << "Deleting update check count state due to read/write errors.";
934
935 // We cannot read/write to the file, so disable the update check based wait
936 // so that we don't get stuck in this OS version by any chance (which could
937 // happen if there's some bug that causes to read/write incorrectly).
938 // Also attempt to delete the file to do our best effort to cleanup.
939 prefs_->Delete(kPrefsUpdateCheckCount);
940 return false;
941}
942
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700943} // namespace chromeos_update_engine