blob: 68c141774af995bc98497face449ddf5d661f513 [file] [log] [blame]
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/update_attempter.h"
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07006
7// From 'man clock_gettime': feature test macro: _POSIX_C_SOURCE >= 199309L
8#ifndef _POSIX_C_SOURCE
9#define _POSIX_C_SOURCE 199309L
10#endif // _POSIX_C_SOURCE
11#include <time.h>
12
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070013#include <string>
Darin Petkov9b230572010-10-08 10:20:09 -070014#include <tr1/memory>
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070015#include <vector>
Darin Petkov9d65b7b2010-07-20 09:13:01 -070016
Andrew de los Reyes45168102010-11-22 11:13:50 -080017#include <base/rand_util.h>
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070018#include <glib.h>
Darin Petkov1023a602010-08-30 13:47:51 -070019#include <metrics/metrics_library.h>
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +020020#include <policy/libpolicy.h>
21#include <policy/device_policy.h>
Darin Petkov9d65b7b2010-07-20 09:13:01 -070022
Bruno Rocha7f9aea22011-09-12 14:31:24 -070023#include "update_engine/certificate_checker.h"
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070024#include "update_engine/dbus_service.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070025#include "update_engine/download_action.h"
26#include "update_engine/filesystem_copier_action.h"
27#include "update_engine/libcurl_http_fetcher.h"
Andrew de los Reyes819fef22010-12-17 11:33:58 -080028#include "update_engine/multi_range_http_fetcher.h"
Darin Petkov6a5b3222010-07-13 14:55:28 -070029#include "update_engine/omaha_request_action.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070030#include "update_engine/omaha_request_params.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070031#include "update_engine/omaha_response_handler_action.h"
32#include "update_engine/postinstall_runner_action.h"
Darin Petkov36275772010-10-01 11:40:57 -070033#include "update_engine/prefs_interface.h"
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -070034#include "update_engine/subprocess.h"
Jay Srinivasan43488792012-06-19 00:25:31 -070035#include "update_engine/system_state.h"
Darin Petkov1023a602010-08-30 13:47:51 -070036#include "update_engine/update_check_scheduler.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070037
Darin Petkovaf183052010-08-23 12:07:13 -070038using base::TimeDelta;
39using base::TimeTicks;
Andrew de los Reyes21816e12011-04-07 14:18:56 -070040using google::protobuf::NewPermanentCallback;
Darin Petkov9b230572010-10-08 10:20:09 -070041using std::make_pair;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070042using std::tr1::shared_ptr;
Jay Srinivasan43488792012-06-19 00:25:31 -070043using std::set;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070044using std::string;
45using std::vector;
46
47namespace chromeos_update_engine {
48
Darin Petkov36275772010-10-01 11:40:57 -070049const int UpdateAttempter::kMaxDeltaUpdateFailures = 3;
50
Gilad Arnold1ebd8132012-03-05 10:19:29 -080051// Private test server URL w/ custom port number.
Gilad Arnolded747312012-03-15 18:20:41 -070052// TODO(garnold) This is a temporary hack to allow us to test the closed loop
53// automated update testing. To be replaced with an hard-coded local IP address.
54const char* const UpdateAttempter::kTestUpdateUrl(
55 "http://garnold.mtv.corp.google.com:8080/update");
Gilad Arnold28e2f392012-02-09 14:36:46 -080056
Darin Petkovcd1666f2010-09-23 09:53:44 -070057const char* kUpdateCompletedMarker =
58 "/var/run/update_engine_autoupdate_completed";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -070059
Andrew de los Reyes45168102010-11-22 11:13:50 -080060namespace {
61const int kMaxConsecutiveObeyProxyRequests = 20;
62} // namespace {}
63
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070064const char* UpdateStatusToString(UpdateStatus status) {
65 switch (status) {
66 case UPDATE_STATUS_IDLE:
67 return "UPDATE_STATUS_IDLE";
68 case UPDATE_STATUS_CHECKING_FOR_UPDATE:
69 return "UPDATE_STATUS_CHECKING_FOR_UPDATE";
70 case UPDATE_STATUS_UPDATE_AVAILABLE:
71 return "UPDATE_STATUS_UPDATE_AVAILABLE";
72 case UPDATE_STATUS_DOWNLOADING:
73 return "UPDATE_STATUS_DOWNLOADING";
74 case UPDATE_STATUS_VERIFYING:
75 return "UPDATE_STATUS_VERIFYING";
76 case UPDATE_STATUS_FINALIZING:
77 return "UPDATE_STATUS_FINALIZING";
78 case UPDATE_STATUS_UPDATED_NEED_REBOOT:
79 return "UPDATE_STATUS_UPDATED_NEED_REBOOT";
Darin Petkov09f96c32010-07-20 09:24:57 -070080 case UPDATE_STATUS_REPORTING_ERROR_EVENT:
81 return "UPDATE_STATUS_REPORTING_ERROR_EVENT";
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070082 default:
83 return "unknown status";
84 }
85}
86
Darin Petkov777dbfa2010-07-20 15:03:37 -070087// Turns a generic kActionCodeError to a generic error code specific
88// to |action| (e.g., kActionCodeFilesystemCopierError). If |code| is
89// not kActionCodeError, or the action is not matched, returns |code|
90// unchanged.
91ActionExitCode GetErrorCodeForAction(AbstractAction* action,
92 ActionExitCode code) {
93 if (code != kActionCodeError)
94 return code;
95
96 const string type = action->Type();
97 if (type == OmahaRequestAction::StaticType())
98 return kActionCodeOmahaRequestError;
99 if (type == OmahaResponseHandlerAction::StaticType())
100 return kActionCodeOmahaResponseHandlerError;
101 if (type == FilesystemCopierAction::StaticType())
102 return kActionCodeFilesystemCopierError;
103 if (type == PostinstallRunnerAction::StaticType())
104 return kActionCodePostinstallRunnerError;
Darin Petkov777dbfa2010-07-20 15:03:37 -0700105
106 return code;
107}
108
Darin Petkovc6c135c2010-08-11 13:36:18 -0700109UpdateAttempter::UpdateAttempter(PrefsInterface* prefs,
Andrew de los Reyes45168102010-11-22 11:13:50 -0800110 MetricsLibraryInterface* metrics_lib,
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700111 DbusGlibInterface* dbus_iface,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700112 GpioHandler* gpio_handler,
113 SystemState* system_state)
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700114 : processor_(new ActionProcessor()),
115 dbus_service_(NULL),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700116 prefs_(prefs),
117 metrics_lib_(metrics_lib),
Darin Petkov1023a602010-08-30 13:47:51 -0700118 update_check_scheduler_(NULL),
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700119 fake_update_success_(false),
Darin Petkov1023a602010-08-30 13:47:51 -0700120 http_response_code_(0),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700121 priority_(utils::kProcessPriorityNormal),
122 manage_priority_source_(NULL),
Darin Petkov9d911fa2010-08-19 09:36:08 -0700123 download_active_(false),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700124 status_(UPDATE_STATUS_IDLE),
125 download_progress_(0.0),
126 last_checked_time_(0),
127 new_version_("0.0.0.0"),
Darin Petkov36275772010-10-01 11:40:57 -0700128 new_size_(0),
Andrew de los Reyes45168102010-11-22 11:13:50 -0800129 proxy_manual_checks_(0),
130 obeying_proxies_(true),
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700131 chrome_proxy_resolver_(dbus_iface),
Darin Petkov58dd1342011-05-06 12:05:13 -0700132 updated_boot_flags_(false),
133 update_boot_flags_running_(false),
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200134 start_action_processor_(false),
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800135 policy_provider_(NULL),
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700136 is_using_test_url_(false),
137 is_test_update_attempted_(false),
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700138 gpio_handler_(gpio_handler),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700139 init_waiting_period_from_prefs_(true),
140 system_state_(system_state) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700141 if (utils::FileExists(kUpdateCompletedMarker))
142 status_ = UPDATE_STATUS_UPDATED_NEED_REBOOT;
143}
144
145UpdateAttempter::~UpdateAttempter() {
146 CleanupPriorityManagement();
147}
148
Gilad Arnold28e2f392012-02-09 14:36:46 -0800149void UpdateAttempter::Update(const string& app_version,
150 const string& omaha_url,
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700151 bool obey_proxies,
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800152 bool interactive,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700153 bool is_test,
154 bool is_user_initiated) {
Andrew de los Reyes000d8952011-03-02 15:21:14 -0800155 chrome_proxy_resolver_.Init();
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700156 fake_update_success_ = false;
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700157 if (status_ == UPDATE_STATUS_UPDATED_NEED_REBOOT) {
Thieu Le116fda32011-04-19 11:01:54 -0700158 // Although we have applied an update, we still want to ping Omaha
159 // to ensure the number of active statistics is accurate.
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700160 LOG(INFO) << "Not updating b/c we already updated and we're waiting for "
Thieu Le116fda32011-04-19 11:01:54 -0700161 << "reboot, we'll ping Omaha instead";
162 PingOmaha();
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700163 return;
164 }
165 if (status_ != UPDATE_STATUS_IDLE) {
166 // Update in progress. Do nothing
167 return;
168 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700169
170 if (!CalculateUpdateParams(app_version,
171 omaha_url,
172 obey_proxies,
173 interactive,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700174 is_test,
175 is_user_initiated)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700176 return;
177 }
178
179 BuildUpdateActions(interactive);
180
181 SetStatusAndNotify(UPDATE_STATUS_CHECKING_FOR_UPDATE,
182 kUpdateNoticeUnspecified);
183
184 // Just in case we didn't update boot flags yet, make sure they're updated
185 // before any update processing starts.
186 start_action_processor_ = true;
187 UpdateBootFlags();
188}
189
190bool UpdateAttempter::CalculateUpdateParams(const string& app_version,
191 const string& omaha_url,
192 bool obey_proxies,
193 bool interactive,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700194 bool is_test,
195 bool is_user_initiated) {
Darin Petkov1023a602010-08-30 13:47:51 -0700196 http_response_code_ = 0;
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200197
198 // Lazy initialize the policy provider, or reload the latest policy data.
199 if (!policy_provider_.get()) {
200 policy_provider_.reset(new policy::PolicyProvider());
201 } else {
202 policy_provider_->Reload();
203 }
204
205 // If the release_track is specified by policy, that takes precedence.
206 string release_track;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700207
208 // Take a copy of the old scatter value before we update it.
209 int64 old_scatter_factor_in_secs = scatter_factor_.InSeconds();
Jay Srinivasan0a708742012-03-20 11:26:12 -0700210 if (policy_provider_->device_policy_is_loaded()) {
211 const policy::DevicePolicy& device_policy =
212 policy_provider_->GetDevicePolicy();
213 device_policy.GetReleaseChannel(&release_track);
214 device_policy.GetUpdateDisabled(&omaha_request_params_.update_disabled);
215 device_policy.GetTargetVersionPrefix(
216 &omaha_request_params_.target_version_prefix);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700217 int64 new_scatter_factor_in_secs = 0;
218 device_policy.GetScatterFactorInSeconds(&new_scatter_factor_in_secs);
Jay Srinivasan08fce042012-06-07 16:31:01 -0700219 if (new_scatter_factor_in_secs < 0) // sanitize input, just in case.
220 new_scatter_factor_in_secs = 0;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700221 scatter_factor_ = TimeDelta::FromSeconds(new_scatter_factor_in_secs);
Jay Srinivasan43488792012-06-19 00:25:31 -0700222
223 system_state_->SetDevicePolicy(&device_policy);
224
225 set<string> allowed_types;
226 string allowed_types_str;
227 if (device_policy.GetAllowedConnectionTypesForUpdate(&allowed_types)) {
228 set<string>::const_iterator iter;
229 for (iter = allowed_types.begin(); iter != allowed_types.end(); ++iter)
230 allowed_types_str += *iter + " ";
231 }
232
233 LOG(INFO) << "Networks over which updates are allowed per policy : "
234 << (allowed_types_str.empty() ? "all" : allowed_types_str);
235 } else {
236 LOG(INFO) << "No device policies present.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700237 }
238
Jay Srinivasan08fce042012-06-07 16:31:01 -0700239 bool is_scatter_enabled = false;
240 if (scatter_factor_.InSeconds() == 0) {
241 LOG(INFO) << "Scattering disabled since scatter factor is set to 0";
242 } else if (is_user_initiated) {
243 LOG(INFO) << "Scattering disabled as this update check is user-initiated";
244 } else if (!system_state_->IsOOBEComplete()) {
245 LOG(INFO) << "Scattering disabled since OOBE is not complete yet";
246 } else {
247 is_scatter_enabled = true;
248 LOG(INFO) << "Scattering is enabled";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700249 }
250
Jay Srinivasan08fce042012-06-07 16:31:01 -0700251 if (is_scatter_enabled) {
252 // This means the scattering policy is turned on.
253 if (scatter_factor_.InSeconds() != old_scatter_factor_in_secs) {
254 int64 wait_period_in_secs = 0;
255 if (init_waiting_period_from_prefs_ &&
256 prefs_->GetInt64(kPrefsWallClockWaitPeriod, &wait_period_in_secs) &&
257 wait_period_in_secs >= 0 &&
258 wait_period_in_secs <= scatter_factor_.InSeconds()) {
259 // This means:
260 // 1. This is the first update check to come this far in this process.
261 // 2. There's a persisted value for the waiting period available.
262 // 3. And that persisted value is still valid.
263 // So, in this case, we should reuse the persisted value instead of
264 // generating a new random value to improve the chances of a good
265 // distribution for scattering.
266 omaha_request_params_.waiting_period =
267 TimeDelta::FromSeconds(wait_period_in_secs);
268 LOG(INFO) << "Using persisted value for wall clock based waiting period.";
269 } else {
270 // In this case, we should regenerate the waiting period to make sure
271 // it's within the bounds of the new scatter factor value.
272 omaha_request_params_.waiting_period = TimeDelta::FromSeconds(
273 base::RandInt(0, scatter_factor_.InSeconds()));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700274
Jay Srinivasan08fce042012-06-07 16:31:01 -0700275 LOG(INFO) << "Generated new value of " << utils::FormatSecs(
276 omaha_request_params_.waiting_period.InSeconds())
277 << " for wall clock based waiting period.";
278
279 // Do a best-effort to persist this. We'll work fine even if the
280 // persistence fails.
281 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
282 omaha_request_params_.waiting_period.InSeconds());
283 }
284 }
285
286 // We should reset this value since we're past the first initialization
287 // of the waiting period for this process.
288 init_waiting_period_from_prefs_ = false;
289
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700290 // This means the scattering policy is turned on. We'll do wall-clock-
291 // based-wait by default. And if we don't have any issues in accessing
292 // the file system to do update the update check count value, we'll
293 // turn that on as well.
294 omaha_request_params_.wall_clock_based_wait_enabled = true;
295 bool decrement_succeeded = DecrementUpdateCheckCount();
296 omaha_request_params_.update_check_count_wait_enabled = decrement_succeeded;
Jay Srinivasan08fce042012-06-07 16:31:01 -0700297 } else {
298 // This means the scattering feature is turned off. Make sure to disable
299 // all the knobs so that we don't invoke any scattering related code.
300 omaha_request_params_.wall_clock_based_wait_enabled = false;
301 omaha_request_params_.update_check_count_wait_enabled = false;
302 prefs_->Delete(kPrefsWallClockWaitPeriod);
303 prefs_->Delete(kPrefsUpdateCheckCount);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700304 }
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200305
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800306 // Determine whether an alternative test address should be used.
Gilad Arnold28e2f392012-02-09 14:36:46 -0800307 string omaha_url_to_use = omaha_url;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800308 if ((is_using_test_url_ = (omaha_url_to_use.empty() && is_test))) {
309 omaha_url_to_use = kTestUpdateUrl;
310 LOG(INFO) << "using alternative server address: " << omaha_url_to_use;
Gilad Arnold28e2f392012-02-09 14:36:46 -0800311 }
312
Jay Srinivasan0a708742012-03-20 11:26:12 -0700313 if (!omaha_request_params_.Init(app_version,
314 omaha_url_to_use,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800315 release_track)) {
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700316 LOG(ERROR) << "Unable to initialize Omaha request device params.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700317 return false;
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700318 }
Darin Petkov3aefa862010-12-07 14:45:00 -0800319
Jay Srinivasan0a708742012-03-20 11:26:12 -0700320 LOG(INFO) << "update_disabled = "
321 << (omaha_request_params_.update_disabled ? "true" : "false")
322 << ", target_version_prefix = "
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700323 << omaha_request_params_.target_version_prefix
324 << ", scatter_factor_in_seconds = "
325 << utils::FormatSecs(scatter_factor_.InSeconds());
326
327 LOG(INFO) << "Wall Clock Based Wait Enabled = "
328 << omaha_request_params_.wall_clock_based_wait_enabled
329 << ", Update Check Count Wait Enabled = "
330 << omaha_request_params_.update_check_count_wait_enabled
331 << ", Waiting Period = "
332 << utils::FormatSecs(
333 omaha_request_params_.waiting_period.InSeconds());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700334
Andrew de los Reyes45168102010-11-22 11:13:50 -0800335 obeying_proxies_ = true;
336 if (obey_proxies || proxy_manual_checks_ == 0) {
337 LOG(INFO) << "forced to obey proxies";
338 // If forced to obey proxies, every 20th request will not use proxies
339 proxy_manual_checks_++;
340 LOG(INFO) << "proxy manual checks: " << proxy_manual_checks_;
341 if (proxy_manual_checks_ >= kMaxConsecutiveObeyProxyRequests) {
342 proxy_manual_checks_ = 0;
343 obeying_proxies_ = false;
344 }
345 } else if (base::RandInt(0, 4) == 0) {
346 obeying_proxies_ = false;
347 }
348 LOG_IF(INFO, !obeying_proxies_) << "To help ensure updates work, this update "
349 "check we are ignoring the proxy settings and using "
350 "direct connections.";
351
Darin Petkov36275772010-10-01 11:40:57 -0700352 DisableDeltaUpdateIfNeeded();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700353 return true;
354}
355
356void UpdateAttempter::BuildUpdateActions(bool interactive) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700357 CHECK(!processor_->IsRunning());
358 processor_->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700359
360 // Actions:
Darin Petkova0929552010-11-29 14:19:06 -0800361 LibcurlHttpFetcher* update_check_fetcher =
Jay Srinivasan08fce042012-06-07 16:31:01 -0700362 new LibcurlHttpFetcher(GetProxyResolver(), system_state_);
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700363 // Try harder to connect to the network, esp when not interactive.
364 // See comment in libcurl_http_fetcher.cc.
365 update_check_fetcher->set_no_network_max_retries(interactive ? 1 : 3);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700366 update_check_fetcher->set_check_certificate(CertificateChecker::kUpdate);
Darin Petkov6a5b3222010-07-13 14:55:28 -0700367 shared_ptr<OmahaRequestAction> update_check_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700368 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700369 &omaha_request_params_,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700370 NULL,
Thieu Le116fda32011-04-19 11:01:54 -0700371 update_check_fetcher, // passes ownership
372 false));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700373 shared_ptr<OmahaResponseHandlerAction> response_handler_action(
Darin Petkov73058b42010-10-06 16:32:19 -0700374 new OmahaResponseHandlerAction(prefs_));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700375 shared_ptr<FilesystemCopierAction> filesystem_copier_action(
Darin Petkov3aefa862010-12-07 14:45:00 -0800376 new FilesystemCopierAction(false, false));
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700377 shared_ptr<FilesystemCopierAction> kernel_filesystem_copier_action(
Darin Petkov3aefa862010-12-07 14:45:00 -0800378 new FilesystemCopierAction(true, false));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700379 shared_ptr<OmahaRequestAction> download_started_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700380 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700381 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700382 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700383 OmahaEvent::kTypeUpdateDownloadStarted),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700384 new LibcurlHttpFetcher(GetProxyResolver(),
385 system_state_),
Thieu Le116fda32011-04-19 11:01:54 -0700386 false));
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700387 LibcurlHttpFetcher* download_fetcher =
Jay Srinivasan08fce042012-06-07 16:31:01 -0700388 new LibcurlHttpFetcher(GetProxyResolver(), system_state_);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700389 download_fetcher->set_check_certificate(CertificateChecker::kDownload);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700390 shared_ptr<DownloadAction> download_action(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700391 new DownloadAction(prefs_,
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800392 new MultiRangeHttpFetcher(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700393 download_fetcher))); // passes ownership
Darin Petkov8c2980e2010-07-16 15:16:49 -0700394 shared_ptr<OmahaRequestAction> download_finished_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700395 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700396 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700397 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700398 OmahaEvent::kTypeUpdateDownloadFinished),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700399 new LibcurlHttpFetcher(GetProxyResolver(),
400 system_state_),
Thieu Le116fda32011-04-19 11:01:54 -0700401 false));
Darin Petkov3aefa862010-12-07 14:45:00 -0800402 shared_ptr<FilesystemCopierAction> filesystem_verifier_action(
403 new FilesystemCopierAction(false, true));
404 shared_ptr<FilesystemCopierAction> kernel_filesystem_verifier_action(
405 new FilesystemCopierAction(true, true));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800406 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
407 new PostinstallRunnerAction);
Darin Petkov8c2980e2010-07-16 15:16:49 -0700408 shared_ptr<OmahaRequestAction> update_complete_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700409 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700410 &omaha_request_params_,
Darin Petkove17f86b2010-07-20 09:12:01 -0700411 new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700412 new LibcurlHttpFetcher(GetProxyResolver(),
413 system_state_),
Thieu Le116fda32011-04-19 11:01:54 -0700414 false));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700415
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700416 download_action->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700417 response_handler_action_ = response_handler_action;
Darin Petkov9b230572010-10-08 10:20:09 -0700418 download_action_ = download_action;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700419
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700420 actions_.push_back(shared_ptr<AbstractAction>(update_check_action));
421 actions_.push_back(shared_ptr<AbstractAction>(response_handler_action));
422 actions_.push_back(shared_ptr<AbstractAction>(filesystem_copier_action));
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700423 actions_.push_back(shared_ptr<AbstractAction>(
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700424 kernel_filesystem_copier_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700425 actions_.push_back(shared_ptr<AbstractAction>(download_started_action));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700426 actions_.push_back(shared_ptr<AbstractAction>(download_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700427 actions_.push_back(shared_ptr<AbstractAction>(download_finished_action));
Darin Petkov3aefa862010-12-07 14:45:00 -0800428 actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action));
429 actions_.push_back(shared_ptr<AbstractAction>(
430 kernel_filesystem_verifier_action));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800431 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700432 actions_.push_back(shared_ptr<AbstractAction>(update_complete_action));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700433
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700434 // Enqueue the actions
435 for (vector<shared_ptr<AbstractAction> >::iterator it = actions_.begin();
436 it != actions_.end(); ++it) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700437 processor_->EnqueueAction(it->get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700438 }
439
440 // Bond them together. We have to use the leaf-types when calling
441 // BondActions().
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700442 BondActions(update_check_action.get(),
443 response_handler_action.get());
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700444 BondActions(response_handler_action.get(),
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700445 filesystem_copier_action.get());
446 BondActions(filesystem_copier_action.get(),
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700447 kernel_filesystem_copier_action.get());
448 BondActions(kernel_filesystem_copier_action.get(),
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700449 download_action.get());
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700450 BondActions(download_action.get(),
Darin Petkov3aefa862010-12-07 14:45:00 -0800451 filesystem_verifier_action.get());
452 BondActions(filesystem_verifier_action.get(),
453 kernel_filesystem_verifier_action.get());
454 BondActions(kernel_filesystem_verifier_action.get(),
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800455 postinstall_runner_action.get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700456}
457
Gilad Arnold28e2f392012-02-09 14:36:46 -0800458void UpdateAttempter::CheckForUpdate(const string& app_version,
459 const string& omaha_url) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700460 LOG(INFO) << "New update check requested";
461
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700462 if (status_ != UPDATE_STATUS_IDLE) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700463 LOG(INFO) << "Skipping update check because current status is "
464 << UpdateStatusToString(status_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700465 return;
466 }
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800467
468 // Read GPIO signals and determine whether this is an automated test scenario.
469 // For safety, we only allow a test update to be performed once; subsequent
470 // update requests will be carried out normally.
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700471 bool is_test = (!is_test_update_attempted_ && gpio_handler_ &&
472 gpio_handler_->IsTestModeSignaled());
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800473 if (is_test) {
474 LOG(INFO) << "test mode signaled";
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700475 is_test_update_attempted_ = true;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800476 }
477
Jay Srinivasan08fce042012-06-07 16:31:01 -0700478 // Passing true for is_user_initiated to indicate that this
479 // is not a scheduled update check.
480 Update(app_version, omaha_url, true, true, is_test, true);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700481}
482
Darin Petkov296889c2010-07-23 16:20:54 -0700483bool UpdateAttempter::RebootIfNeeded() {
484 if (status_ != UPDATE_STATUS_UPDATED_NEED_REBOOT) {
485 LOG(INFO) << "Reboot requested, but status is "
486 << UpdateStatusToString(status_) << ", so not rebooting.";
487 return false;
488 }
489 TEST_AND_RETURN_FALSE(utils::Reboot());
490 return true;
491}
492
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700493// Delegate methods:
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700494void UpdateAttempter::ProcessingDone(const ActionProcessor* processor,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700495 ActionExitCode code) {
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700496 CHECK(response_handler_action_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700497 LOG(INFO) << "Processing Done.";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700498 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700499
Darin Petkovc6c135c2010-08-11 13:36:18 -0700500 // Reset process priority back to normal.
501 CleanupPriorityManagement();
502
Darin Petkov09f96c32010-07-20 09:24:57 -0700503 if (status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
504 LOG(INFO) << "Error event sent.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800505
506 // Inform scheduler of new status; also specifically inform about a failed
507 // update attempt with a test address.
508 SetStatusAndNotify(UPDATE_STATUS_IDLE,
509 (is_using_test_url_ ? kUpdateNoticeTestAddrFailed :
510 kUpdateNoticeUnspecified));
511
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700512 if (!fake_update_success_) {
513 return;
514 }
515 LOG(INFO) << "Booted from FW B and tried to install new firmware, "
516 "so requesting reboot from user.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700517 }
518
Darin Petkovc1a8b422010-07-19 11:34:49 -0700519 if (code == kActionCodeSuccess) {
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700520 utils::WriteFile(kUpdateCompletedMarker, "", 0);
Darin Petkov36275772010-10-01 11:40:57 -0700521 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Darin Petkov95508da2011-01-05 12:42:29 -0800522 prefs_->SetString(kPrefsPreviousVersion, omaha_request_params_.app_version);
Darin Petkov9b230572010-10-08 10:20:09 -0700523 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700524
525 // Since we're done with scattering fully at this point, this is the
526 // safest point delete the state files, as we're sure that the status is
527 // set to reboot (which means no more updates will be applied until reboot)
528 // This deletion is required for correctness as we want the next update
529 // check to re-create a new random number for the update check count.
530 // Similarly, we also delete the wall-clock-wait period that was persisted
531 // so that we start with a new random value for the next update check
532 // after reboot so that the same device is not favored or punished in any
533 // way.
534 prefs_->Delete(kPrefsUpdateCheckCount);
535 prefs_->Delete(kPrefsWallClockWaitPeriod);
536
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800537 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
538 kUpdateNoticeUnspecified);
Darin Petkov9d65b7b2010-07-20 09:13:01 -0700539
540 // Report the time it took to update the system.
541 int64_t update_time = time(NULL) - last_checked_time_;
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700542 if (!fake_update_success_)
543 metrics_lib_->SendToUMA("Installer.UpdateTime",
544 static_cast<int>(update_time), // sample
545 1, // min = 1 second
546 20 * 60, // max = 20 minutes
547 50); // buckets
Darin Petkov09f96c32010-07-20 09:24:57 -0700548 return;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700549 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700550
Darin Petkov1023a602010-08-30 13:47:51 -0700551 if (ScheduleErrorEventAction()) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700552 return;
Darin Petkov1023a602010-08-30 13:47:51 -0700553 }
554 LOG(INFO) << "No update.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800555 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700556}
557
558void UpdateAttempter::ProcessingStopped(const ActionProcessor* processor) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700559 // Reset process priority back to normal.
560 CleanupPriorityManagement();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700561 download_progress_ = 0.0;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800562 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700563 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700564 error_event_.reset(NULL);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700565}
566
567// Called whenever an action has finished processing, either successfully
568// or otherwise.
569void UpdateAttempter::ActionCompleted(ActionProcessor* processor,
570 AbstractAction* action,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700571 ActionExitCode code) {
Darin Petkov1023a602010-08-30 13:47:51 -0700572 // Reset download progress regardless of whether or not the download
573 // action succeeded. Also, get the response code from HTTP request
574 // actions (update download as well as the initial update check
575 // actions).
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700576 const string type = action->Type();
Darin Petkov1023a602010-08-30 13:47:51 -0700577 if (type == DownloadAction::StaticType()) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700578 download_progress_ = 0.0;
Darin Petkov1023a602010-08-30 13:47:51 -0700579 DownloadAction* download_action = dynamic_cast<DownloadAction*>(action);
580 http_response_code_ = download_action->GetHTTPResponseCode();
581 } else if (type == OmahaRequestAction::StaticType()) {
582 OmahaRequestAction* omaha_request_action =
583 dynamic_cast<OmahaRequestAction*>(action);
584 // If the request is not an event, then it's the update-check.
585 if (!omaha_request_action->IsEvent()) {
586 http_response_code_ = omaha_request_action->GetHTTPResponseCode();
Darin Petkov85ced132010-09-01 10:20:56 -0700587 // Forward the server-dictated poll interval to the update check
588 // scheduler, if any.
589 if (update_check_scheduler_) {
590 update_check_scheduler_->set_poll_interval(
591 omaha_request_action->GetOutputObject().poll_interval);
592 }
Darin Petkov1023a602010-08-30 13:47:51 -0700593 }
594 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700595 if (code != kActionCodeSuccess) {
Darin Petkov7ed561b2011-10-04 02:59:03 -0700596 // If the current state is at or past the download phase, count the failure
597 // in case a switch to full update becomes necessary. Ignore network
598 // transfer timeouts and failures.
Darin Petkov36275772010-10-01 11:40:57 -0700599 if (status_ >= UPDATE_STATUS_DOWNLOADING &&
Darin Petkov36275772010-10-01 11:40:57 -0700600 code != kActionCodeDownloadTransferError) {
601 MarkDeltaUpdateFailure();
602 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700603 // On failure, schedule an error event to be sent to Omaha.
604 CreatePendingErrorEvent(action, code);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700605 return;
Darin Petkov09f96c32010-07-20 09:24:57 -0700606 }
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700607 // Find out which action completed.
608 if (type == OmahaResponseHandlerAction::StaticType()) {
Darin Petkov9b230572010-10-08 10:20:09 -0700609 // Note that the status will be updated to DOWNLOADING when some bytes get
610 // actually downloaded from the server and the BytesReceived callback is
611 // invoked. This avoids notifying the user that a download has started in
612 // cases when the server and the client are unable to initiate the download.
613 CHECK(action == response_handler_action_.get());
614 const InstallPlan& plan = response_handler_action_->install_plan();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700615 last_checked_time_ = time(NULL);
616 // TODO(adlr): put version in InstallPlan
617 new_version_ = "0.0.0.0";
618 new_size_ = plan.size;
Darin Petkov9b230572010-10-08 10:20:09 -0700619 SetupDownload();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700620 SetupPriorityManagement();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800621 SetStatusAndNotify(UPDATE_STATUS_UPDATE_AVAILABLE,
622 kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700623 } else if (type == DownloadAction::StaticType()) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800624 SetStatusAndNotify(UPDATE_STATUS_FINALIZING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700625 }
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700626}
627
628// Stop updating. An attempt will be made to record status to the disk
629// so that updates can be resumed later.
630void UpdateAttempter::Terminate() {
631 // TODO(adlr): implement this method.
632 NOTIMPLEMENTED();
633}
634
635// Try to resume from a previously Terminate()d update.
636void UpdateAttempter::ResumeUpdating() {
637 // TODO(adlr): implement this method.
638 NOTIMPLEMENTED();
639}
640
Darin Petkov9d911fa2010-08-19 09:36:08 -0700641void UpdateAttempter::SetDownloadStatus(bool active) {
642 download_active_ = active;
643 LOG(INFO) << "Download status: " << (active ? "active" : "inactive");
644}
645
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700646void UpdateAttempter::BytesReceived(uint64_t bytes_received, uint64_t total) {
Darin Petkov9d911fa2010-08-19 09:36:08 -0700647 if (!download_active_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700648 LOG(ERROR) << "BytesReceived called while not downloading.";
649 return;
650 }
Darin Petkovaf183052010-08-23 12:07:13 -0700651 double progress = static_cast<double>(bytes_received) /
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700652 static_cast<double>(total);
Darin Petkovaf183052010-08-23 12:07:13 -0700653 // Self throttle based on progress. Also send notifications if
654 // progress is too slow.
655 const double kDeltaPercent = 0.01; // 1%
656 if (status_ != UPDATE_STATUS_DOWNLOADING ||
657 bytes_received == total ||
658 progress - download_progress_ >= kDeltaPercent ||
659 TimeTicks::Now() - last_notify_time_ >= TimeDelta::FromSeconds(10)) {
660 download_progress_ = progress;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800661 SetStatusAndNotify(UPDATE_STATUS_DOWNLOADING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700662 }
663}
664
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700665bool UpdateAttempter::GetStatus(int64_t* last_checked_time,
666 double* progress,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800667 string* current_operation,
668 string* new_version,
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700669 int64_t* new_size) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700670 *last_checked_time = last_checked_time_;
671 *progress = download_progress_;
672 *current_operation = UpdateStatusToString(status_);
673 *new_version = new_version_;
674 *new_size = new_size_;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700675 return true;
676}
677
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700678void UpdateAttempter::UpdateBootFlags() {
Darin Petkov58dd1342011-05-06 12:05:13 -0700679 if (update_boot_flags_running_) {
680 LOG(INFO) << "Update boot flags running, nothing to do.";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700681 return;
682 }
Darin Petkov58dd1342011-05-06 12:05:13 -0700683 if (updated_boot_flags_) {
684 LOG(INFO) << "Already updated boot flags. Skipping.";
685 if (start_action_processor_) {
686 ScheduleProcessingStart();
687 }
688 return;
689 }
690 // This is purely best effort. Failures should be logged by Subprocess. Run
691 // the script asynchronously to avoid blocking the event loop regardless of
692 // the script runtime.
693 update_boot_flags_running_ = true;
694 LOG(INFO) << "Updating boot flags...";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700695 vector<string> cmd(1, "/usr/sbin/chromeos-setgoodkernel");
Darin Petkov58dd1342011-05-06 12:05:13 -0700696 if (!Subprocess::Get().Exec(cmd, StaticCompleteUpdateBootFlags, this)) {
697 CompleteUpdateBootFlags(1);
698 }
699}
700
701void UpdateAttempter::CompleteUpdateBootFlags(int return_code) {
702 update_boot_flags_running_ = false;
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700703 updated_boot_flags_ = true;
Darin Petkov58dd1342011-05-06 12:05:13 -0700704 if (start_action_processor_) {
705 ScheduleProcessingStart();
706 }
707}
708
709void UpdateAttempter::StaticCompleteUpdateBootFlags(
710 int return_code,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800711 const string& output,
Darin Petkov58dd1342011-05-06 12:05:13 -0700712 void* p) {
713 reinterpret_cast<UpdateAttempter*>(p)->CompleteUpdateBootFlags(return_code);
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700714}
715
Darin Petkov61635a92011-05-18 16:20:36 -0700716void UpdateAttempter::BroadcastStatus() {
717 if (!dbus_service_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700718 return;
Darin Petkov61635a92011-05-18 16:20:36 -0700719 }
Darin Petkovaf183052010-08-23 12:07:13 -0700720 last_notify_time_ = TimeTicks::Now();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700721 update_engine_service_emit_status_update(
722 dbus_service_,
723 last_checked_time_,
724 download_progress_,
725 UpdateStatusToString(status_),
726 new_version_.c_str(),
727 new_size_);
728}
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700729
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800730void UpdateAttempter::SetStatusAndNotify(UpdateStatus status,
731 UpdateNotice notice) {
Darin Petkov61635a92011-05-18 16:20:36 -0700732 status_ = status;
733 if (update_check_scheduler_) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800734 update_check_scheduler_->SetUpdateStatus(status_, notice);
Darin Petkov61635a92011-05-18 16:20:36 -0700735 }
736 BroadcastStatus();
737}
738
Darin Petkov777dbfa2010-07-20 15:03:37 -0700739void UpdateAttempter::CreatePendingErrorEvent(AbstractAction* action,
740 ActionExitCode code) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700741 if (error_event_.get()) {
742 // This shouldn't really happen.
743 LOG(WARNING) << "There's already an existing pending error event.";
744 return;
745 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700746
Darin Petkovabc7bc02011-02-23 14:39:43 -0800747 // For now assume that a generic Omaha response action failure means that
748 // there's no update so don't send an event. Also, double check that the
749 // failure has not occurred while sending an error event -- in which case
750 // don't schedule another. This shouldn't really happen but just in case...
751 if ((action->Type() == OmahaResponseHandlerAction::StaticType() &&
752 code == kActionCodeError) ||
Darin Petkov777dbfa2010-07-20 15:03:37 -0700753 status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
754 return;
755 }
756
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700757 // Classify the code to generate the appropriate result so that
758 // the Borgmon charts show up the results correctly.
759 // Do this before calling GetErrorCodeForAction which could potentially
760 // augment the bit representation of code and thus cause no matches for
761 // the switch cases below.
762 OmahaEvent::Result event_result;
763 switch (code) {
764 case kActionCodeOmahaUpdateIgnoredPerPolicy:
765 case kActionCodeOmahaUpdateDeferredPerPolicy:
766 event_result = OmahaEvent::kResultUpdateDeferred;
767 break;
768 default:
769 event_result = OmahaEvent::kResultError;
770 break;
771 }
772
Darin Petkov777dbfa2010-07-20 15:03:37 -0700773 code = GetErrorCodeForAction(action, code);
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700774 fake_update_success_ = code == kActionCodePostinstallBootedFromFirmwareB;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700775
776 // Apply the bit modifiers to the error code.
777 if (!utils::IsNormalBootMode()) {
778 code = static_cast<ActionExitCode>(code | kActionCodeBootModeFlag);
779 }
780 if (response_handler_action_.get() &&
781 response_handler_action_->install_plan().is_resume) {
782 code = static_cast<ActionExitCode>(code | kActionCodeResumedFlag);
783 }
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700784
Darin Petkov09f96c32010-07-20 09:24:57 -0700785 error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700786 event_result,
Darin Petkov09f96c32010-07-20 09:24:57 -0700787 code));
788}
789
790bool UpdateAttempter::ScheduleErrorEventAction() {
791 if (error_event_.get() == NULL)
792 return false;
793
Darin Petkov1023a602010-08-30 13:47:51 -0700794 LOG(INFO) << "Update failed -- reporting the error event.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700795 shared_ptr<OmahaRequestAction> error_event_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700796 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700797 &omaha_request_params_,
Darin Petkov09f96c32010-07-20 09:24:57 -0700798 error_event_.release(), // Pass ownership.
Jay Srinivasan08fce042012-06-07 16:31:01 -0700799 new LibcurlHttpFetcher(GetProxyResolver(),
800 system_state_),
Thieu Le116fda32011-04-19 11:01:54 -0700801 false));
Darin Petkov09f96c32010-07-20 09:24:57 -0700802 actions_.push_back(shared_ptr<AbstractAction>(error_event_action));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700803 processor_->EnqueueAction(error_event_action.get());
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800804 SetStatusAndNotify(UPDATE_STATUS_REPORTING_ERROR_EVENT,
805 kUpdateNoticeUnspecified);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700806 processor_->StartProcessing();
Darin Petkov09f96c32010-07-20 09:24:57 -0700807 return true;
808}
809
Darin Petkovc6c135c2010-08-11 13:36:18 -0700810void UpdateAttempter::SetPriority(utils::ProcessPriority priority) {
811 if (priority_ == priority) {
812 return;
813 }
814 if (utils::SetProcessPriority(priority)) {
815 priority_ = priority;
816 LOG(INFO) << "Process priority = " << priority_;
817 }
818}
819
820void UpdateAttempter::SetupPriorityManagement() {
821 if (manage_priority_source_) {
822 LOG(ERROR) << "Process priority timeout source hasn't been destroyed.";
823 CleanupPriorityManagement();
824 }
Darin Petkovf622ef72010-10-26 13:49:24 -0700825 const int kPriorityTimeout = 2 * 60 * 60; // 2 hours
Darin Petkovc6c135c2010-08-11 13:36:18 -0700826 manage_priority_source_ = g_timeout_source_new_seconds(kPriorityTimeout);
827 g_source_set_callback(manage_priority_source_,
828 StaticManagePriorityCallback,
829 this,
830 NULL);
831 g_source_attach(manage_priority_source_, NULL);
832 SetPriority(utils::kProcessPriorityLow);
833}
834
835void UpdateAttempter::CleanupPriorityManagement() {
836 if (manage_priority_source_) {
837 g_source_destroy(manage_priority_source_);
838 manage_priority_source_ = NULL;
839 }
840 SetPriority(utils::kProcessPriorityNormal);
841}
842
843gboolean UpdateAttempter::StaticManagePriorityCallback(gpointer data) {
844 return reinterpret_cast<UpdateAttempter*>(data)->ManagePriorityCallback();
845}
846
Darin Petkove6ef2f82011-03-07 17:31:11 -0800847gboolean UpdateAttempter::StaticStartProcessing(gpointer data) {
848 reinterpret_cast<UpdateAttempter*>(data)->processor_->StartProcessing();
849 return FALSE; // Don't call this callback again.
850}
851
Darin Petkov58dd1342011-05-06 12:05:13 -0700852void UpdateAttempter::ScheduleProcessingStart() {
853 LOG(INFO) << "Scheduling an action processor start.";
854 start_action_processor_ = false;
855 g_idle_add(&StaticStartProcessing, this);
856}
857
Darin Petkovc6c135c2010-08-11 13:36:18 -0700858bool UpdateAttempter::ManagePriorityCallback() {
Darin Petkovf622ef72010-10-26 13:49:24 -0700859 SetPriority(utils::kProcessPriorityNormal);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700860 manage_priority_source_ = NULL;
Darin Petkovf622ef72010-10-26 13:49:24 -0700861 return false; // Destroy the timeout source.
Darin Petkovc6c135c2010-08-11 13:36:18 -0700862}
863
Darin Petkov36275772010-10-01 11:40:57 -0700864void UpdateAttempter::DisableDeltaUpdateIfNeeded() {
865 int64_t delta_failures;
866 if (omaha_request_params_.delta_okay &&
867 prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) &&
868 delta_failures >= kMaxDeltaUpdateFailures) {
869 LOG(WARNING) << "Too many delta update failures, forcing full update.";
870 omaha_request_params_.delta_okay = false;
871 }
872}
873
874void UpdateAttempter::MarkDeltaUpdateFailure() {
Darin Petkov2dd01092010-10-08 15:43:05 -0700875 // Don't try to resume a failed delta update.
876 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Darin Petkov36275772010-10-01 11:40:57 -0700877 int64_t delta_failures;
878 if (!prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) ||
879 delta_failures < 0) {
880 delta_failures = 0;
881 }
882 prefs_->SetInt64(kPrefsDeltaUpdateFailures, ++delta_failures);
883}
884
Darin Petkov9b230572010-10-08 10:20:09 -0700885void UpdateAttempter::SetupDownload() {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800886 MultiRangeHttpFetcher* fetcher =
887 dynamic_cast<MultiRangeHttpFetcher*>(download_action_->http_fetcher());
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800888 fetcher->ClearRanges();
Darin Petkov9b230572010-10-08 10:20:09 -0700889 if (response_handler_action_->install_plan().is_resume) {
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700890 // Resuming an update so fetch the update manifest metadata first.
Darin Petkov9b230572010-10-08 10:20:09 -0700891 int64_t manifest_metadata_size = 0;
892 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800893 fetcher->AddRange(0, manifest_metadata_size);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700894 // If there're remaining unprocessed data blobs, fetch them. Be careful not
895 // to request data beyond the end of the payload to avoid 416 HTTP response
896 // error codes.
Darin Petkov9b230572010-10-08 10:20:09 -0700897 int64_t next_data_offset = 0;
898 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700899 uint64_t resume_offset = manifest_metadata_size + next_data_offset;
900 if (resume_offset < response_handler_action_->install_plan().size) {
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800901 fetcher->AddRange(resume_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700902 }
Darin Petkov9b230572010-10-08 10:20:09 -0700903 } else {
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800904 fetcher->AddRange(0);
Darin Petkov9b230572010-10-08 10:20:09 -0700905 }
Darin Petkov9b230572010-10-08 10:20:09 -0700906}
907
Thieu Le116fda32011-04-19 11:01:54 -0700908void UpdateAttempter::PingOmaha() {
Thieu Led88a8572011-05-26 09:09:19 -0700909 if (!processor_->IsRunning()) {
910 shared_ptr<OmahaRequestAction> ping_action(
911 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700912 &omaha_request_params_,
Thieu Led88a8572011-05-26 09:09:19 -0700913 NULL,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700914 new LibcurlHttpFetcher(GetProxyResolver(),
915 system_state_),
Thieu Led88a8572011-05-26 09:09:19 -0700916 true));
917 actions_.push_back(shared_ptr<OmahaRequestAction>(ping_action));
918 processor_->set_delegate(NULL);
919 processor_->EnqueueAction(ping_action.get());
920 // Call StartProcessing() synchronously here to avoid any race conditions
921 // caused by multiple outstanding ping Omaha requests. If we call
922 // StartProcessing() asynchronously, the device can be suspended before we
923 // get a chance to callback to StartProcessing(). When the device resumes
924 // (assuming the device sleeps longer than the next update check period),
925 // StartProcessing() is called back and at the same time, the next update
926 // check is fired which eventually invokes StartProcessing(). A crash
927 // can occur because StartProcessing() checks to make sure that the
928 // processor is idle which it isn't due to the two concurrent ping Omaha
929 // requests.
930 processor_->StartProcessing();
931 } else {
Darin Petkov58dd1342011-05-06 12:05:13 -0700932 LOG(WARNING) << "Action processor running, Omaha ping suppressed.";
Darin Petkov58dd1342011-05-06 12:05:13 -0700933 }
Thieu Led88a8572011-05-26 09:09:19 -0700934
935 // Update the status which will schedule the next update check
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800936 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
937 kUpdateNoticeUnspecified);
Thieu Le116fda32011-04-19 11:01:54 -0700938}
939
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700940
941bool UpdateAttempter::DecrementUpdateCheckCount() {
942 int64 update_check_count_value;
943
944 if (!prefs_->Exists(kPrefsUpdateCheckCount)) {
945 // This file does not exist. This means we haven't started our update
946 // check count down yet, so nothing more to do. This file will be created
947 // later when we first satisfy the wall-clock-based-wait period.
948 LOG(INFO) << "No existing update check count. That's normal.";
949 return true;
950 }
951
952 if (prefs_->GetInt64(kPrefsUpdateCheckCount, &update_check_count_value)) {
953 // Only if we're able to read a proper integer value, then go ahead
954 // and decrement and write back the result in the same file, if needed.
955 LOG(INFO) << "Update check count = " << update_check_count_value;
956
957 if (update_check_count_value == 0) {
958 // It could be 0, if, for some reason, the file didn't get deleted
959 // when we set our status to waiting for reboot. so we just leave it
960 // as is so that we can prevent another update_check wait for this client.
961 LOG(INFO) << "Not decrementing update check count as it's already 0.";
962 return true;
963 }
964
965 if (update_check_count_value > 0)
966 update_check_count_value--;
967 else
968 update_check_count_value = 0;
969
970 // Write out the new value of update_check_count_value.
971 if (prefs_->SetInt64(kPrefsUpdateCheckCount, update_check_count_value)) {
972 // We successfully wrote out te new value, so enable the
973 // update check based wait.
974 LOG(INFO) << "New update check count = " << update_check_count_value;
975 return true;
976 }
977 }
978
979 LOG(INFO) << "Deleting update check count state due to read/write errors.";
980
981 // We cannot read/write to the file, so disable the update check based wait
982 // so that we don't get stuck in this OS version by any chance (which could
983 // happen if there's some bug that causes to read/write incorrectly).
984 // Also attempt to delete the file to do our best effort to cleanup.
985 prefs_->Delete(kPrefsUpdateCheckCount);
986 return false;
987}
988
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700989} // namespace chromeos_update_engine