blob: 4422e4c0c909b8dd1a7215894aff9a399cab5a58 [file] [log] [blame]
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/update_attempter.h"
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07006
7// From 'man clock_gettime': feature test macro: _POSIX_C_SOURCE >= 199309L
8#ifndef _POSIX_C_SOURCE
9#define _POSIX_C_SOURCE 199309L
10#endif // _POSIX_C_SOURCE
11#include <time.h>
12
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070013#include <string>
Darin Petkov9b230572010-10-08 10:20:09 -070014#include <tr1/memory>
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070015#include <vector>
Darin Petkov9d65b7b2010-07-20 09:13:01 -070016
Andrew de los Reyes45168102010-11-22 11:13:50 -080017#include <base/rand_util.h>
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070018#include <glib.h>
Darin Petkov1023a602010-08-30 13:47:51 -070019#include <metrics/metrics_library.h>
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +020020#include <policy/libpolicy.h>
21#include <policy/device_policy.h>
Darin Petkov9d65b7b2010-07-20 09:13:01 -070022
Bruno Rocha7f9aea22011-09-12 14:31:24 -070023#include "update_engine/certificate_checker.h"
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070024#include "update_engine/dbus_service.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070025#include "update_engine/download_action.h"
26#include "update_engine/filesystem_copier_action.h"
27#include "update_engine/libcurl_http_fetcher.h"
Andrew de los Reyes819fef22010-12-17 11:33:58 -080028#include "update_engine/multi_range_http_fetcher.h"
Darin Petkov6a5b3222010-07-13 14:55:28 -070029#include "update_engine/omaha_request_action.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070030#include "update_engine/omaha_request_params.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070031#include "update_engine/omaha_response_handler_action.h"
32#include "update_engine/postinstall_runner_action.h"
Darin Petkov36275772010-10-01 11:40:57 -070033#include "update_engine/prefs_interface.h"
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -070034#include "update_engine/subprocess.h"
Jay Srinivasan43488792012-06-19 00:25:31 -070035#include "update_engine/system_state.h"
Darin Petkov1023a602010-08-30 13:47:51 -070036#include "update_engine/update_check_scheduler.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070037
Darin Petkovaf183052010-08-23 12:07:13 -070038using base::TimeDelta;
39using base::TimeTicks;
Andrew de los Reyes21816e12011-04-07 14:18:56 -070040using google::protobuf::NewPermanentCallback;
Darin Petkov9b230572010-10-08 10:20:09 -070041using std::make_pair;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070042using std::tr1::shared_ptr;
Jay Srinivasan43488792012-06-19 00:25:31 -070043using std::set;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070044using std::string;
45using std::vector;
46
47namespace chromeos_update_engine {
48
Darin Petkov36275772010-10-01 11:40:57 -070049const int UpdateAttempter::kMaxDeltaUpdateFailures = 3;
50
Gilad Arnold1ebd8132012-03-05 10:19:29 -080051// Private test server URL w/ custom port number.
Gilad Arnolded747312012-03-15 18:20:41 -070052// TODO(garnold) This is a temporary hack to allow us to test the closed loop
53// automated update testing. To be replaced with an hard-coded local IP address.
54const char* const UpdateAttempter::kTestUpdateUrl(
55 "http://garnold.mtv.corp.google.com:8080/update");
Gilad Arnold28e2f392012-02-09 14:36:46 -080056
Darin Petkovcd1666f2010-09-23 09:53:44 -070057const char* kUpdateCompletedMarker =
58 "/var/run/update_engine_autoupdate_completed";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -070059
Andrew de los Reyes45168102010-11-22 11:13:50 -080060namespace {
61const int kMaxConsecutiveObeyProxyRequests = 20;
62} // namespace {}
63
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070064const char* UpdateStatusToString(UpdateStatus status) {
65 switch (status) {
66 case UPDATE_STATUS_IDLE:
67 return "UPDATE_STATUS_IDLE";
68 case UPDATE_STATUS_CHECKING_FOR_UPDATE:
69 return "UPDATE_STATUS_CHECKING_FOR_UPDATE";
70 case UPDATE_STATUS_UPDATE_AVAILABLE:
71 return "UPDATE_STATUS_UPDATE_AVAILABLE";
72 case UPDATE_STATUS_DOWNLOADING:
73 return "UPDATE_STATUS_DOWNLOADING";
74 case UPDATE_STATUS_VERIFYING:
75 return "UPDATE_STATUS_VERIFYING";
76 case UPDATE_STATUS_FINALIZING:
77 return "UPDATE_STATUS_FINALIZING";
78 case UPDATE_STATUS_UPDATED_NEED_REBOOT:
79 return "UPDATE_STATUS_UPDATED_NEED_REBOOT";
Darin Petkov09f96c32010-07-20 09:24:57 -070080 case UPDATE_STATUS_REPORTING_ERROR_EVENT:
81 return "UPDATE_STATUS_REPORTING_ERROR_EVENT";
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070082 default:
83 return "unknown status";
84 }
85}
86
Darin Petkov777dbfa2010-07-20 15:03:37 -070087// Turns a generic kActionCodeError to a generic error code specific
88// to |action| (e.g., kActionCodeFilesystemCopierError). If |code| is
89// not kActionCodeError, or the action is not matched, returns |code|
90// unchanged.
91ActionExitCode GetErrorCodeForAction(AbstractAction* action,
92 ActionExitCode code) {
93 if (code != kActionCodeError)
94 return code;
95
96 const string type = action->Type();
97 if (type == OmahaRequestAction::StaticType())
98 return kActionCodeOmahaRequestError;
99 if (type == OmahaResponseHandlerAction::StaticType())
100 return kActionCodeOmahaResponseHandlerError;
101 if (type == FilesystemCopierAction::StaticType())
102 return kActionCodeFilesystemCopierError;
103 if (type == PostinstallRunnerAction::StaticType())
104 return kActionCodePostinstallRunnerError;
Darin Petkov777dbfa2010-07-20 15:03:37 -0700105
106 return code;
107}
108
Darin Petkovc6c135c2010-08-11 13:36:18 -0700109UpdateAttempter::UpdateAttempter(PrefsInterface* prefs,
Andrew de los Reyes45168102010-11-22 11:13:50 -0800110 MetricsLibraryInterface* metrics_lib,
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700111 DbusGlibInterface* dbus_iface,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700112 GpioHandler* gpio_handler,
113 SystemState* system_state)
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700114 : processor_(new ActionProcessor()),
115 dbus_service_(NULL),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700116 prefs_(prefs),
117 metrics_lib_(metrics_lib),
Darin Petkov1023a602010-08-30 13:47:51 -0700118 update_check_scheduler_(NULL),
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700119 fake_update_success_(false),
Darin Petkov1023a602010-08-30 13:47:51 -0700120 http_response_code_(0),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700121 priority_(utils::kProcessPriorityNormal),
122 manage_priority_source_(NULL),
Darin Petkov9d911fa2010-08-19 09:36:08 -0700123 download_active_(false),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700124 status_(UPDATE_STATUS_IDLE),
125 download_progress_(0.0),
126 last_checked_time_(0),
127 new_version_("0.0.0.0"),
Darin Petkov36275772010-10-01 11:40:57 -0700128 new_size_(0),
Andrew de los Reyes45168102010-11-22 11:13:50 -0800129 proxy_manual_checks_(0),
130 obeying_proxies_(true),
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700131 chrome_proxy_resolver_(dbus_iface),
Darin Petkov58dd1342011-05-06 12:05:13 -0700132 updated_boot_flags_(false),
133 update_boot_flags_running_(false),
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200134 start_action_processor_(false),
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800135 policy_provider_(NULL),
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700136 is_using_test_url_(false),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700137 is_test_mode_(false),
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700138 is_test_update_attempted_(false),
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700139 gpio_handler_(gpio_handler),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700140 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,
Gilad Arnold7c04e762012-05-23 10:54:02 -0700153 bool is_test_mode,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700154 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,
Gilad Arnold7c04e762012-05-23 10:54:02 -0700174 is_test_mode,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700175 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,
Gilad Arnold7c04e762012-05-23 10:54:02 -0700194 bool is_test_mode,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700195 bool is_user_initiated) {
Darin Petkov1023a602010-08-30 13:47:51 -0700196 http_response_code_ = 0;
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200197
Gilad Arnold7c04e762012-05-23 10:54:02 -0700198 // Set the test mode flag for the current update attempt.
199 is_test_mode_ = is_test_mode;
200
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200201 // Lazy initialize the policy provider, or reload the latest policy data.
202 if (!policy_provider_.get()) {
203 policy_provider_.reset(new policy::PolicyProvider());
204 } else {
205 policy_provider_->Reload();
206 }
207
208 // If the release_track is specified by policy, that takes precedence.
209 string release_track;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700210
Jay Srinivasan0a708742012-03-20 11:26:12 -0700211 if (policy_provider_->device_policy_is_loaded()) {
212 const policy::DevicePolicy& device_policy =
213 policy_provider_->GetDevicePolicy();
214 device_policy.GetReleaseChannel(&release_track);
215 device_policy.GetUpdateDisabled(&omaha_request_params_.update_disabled);
216 device_policy.GetTargetVersionPrefix(
217 &omaha_request_params_.target_version_prefix);
Jay Srinivasan43488792012-06-19 00:25:31 -0700218
219 system_state_->SetDevicePolicy(&device_policy);
220
221 set<string> allowed_types;
222 string allowed_types_str;
223 if (device_policy.GetAllowedConnectionTypesForUpdate(&allowed_types)) {
224 set<string>::const_iterator iter;
225 for (iter = allowed_types.begin(); iter != allowed_types.end(); ++iter)
226 allowed_types_str += *iter + " ";
227 }
228
229 LOG(INFO) << "Networks over which updates are allowed per policy : "
230 << (allowed_types_str.empty() ? "all" : allowed_types_str);
231 } else {
232 LOG(INFO) << "No device policies present.";
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700233 system_state_->SetDevicePolicy(NULL);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700234 }
235
Jay Srinivasan21be0752012-07-25 15:44:56 -0700236 CalculateScatteringParams(is_user_initiated);
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200237
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800238 // Determine whether an alternative test address should be used.
Gilad Arnold28e2f392012-02-09 14:36:46 -0800239 string omaha_url_to_use = omaha_url;
Gilad Arnold7c04e762012-05-23 10:54:02 -0700240 if ((is_using_test_url_ = (omaha_url_to_use.empty() && is_test_mode_))) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800241 omaha_url_to_use = kTestUpdateUrl;
242 LOG(INFO) << "using alternative server address: " << omaha_url_to_use;
Gilad Arnold28e2f392012-02-09 14:36:46 -0800243 }
244
Jay Srinivasan0a708742012-03-20 11:26:12 -0700245 if (!omaha_request_params_.Init(app_version,
246 omaha_url_to_use,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800247 release_track)) {
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700248 LOG(ERROR) << "Unable to initialize Omaha request device params.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700249 return false;
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700250 }
Darin Petkov3aefa862010-12-07 14:45:00 -0800251
Jay Srinivasan0a708742012-03-20 11:26:12 -0700252 LOG(INFO) << "update_disabled = "
253 << (omaha_request_params_.update_disabled ? "true" : "false")
254 << ", target_version_prefix = "
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700255 << omaha_request_params_.target_version_prefix
256 << ", scatter_factor_in_seconds = "
257 << utils::FormatSecs(scatter_factor_.InSeconds());
258
259 LOG(INFO) << "Wall Clock Based Wait Enabled = "
260 << omaha_request_params_.wall_clock_based_wait_enabled
261 << ", Update Check Count Wait Enabled = "
262 << omaha_request_params_.update_check_count_wait_enabled
Jay Srinivasan21be0752012-07-25 15:44:56 -0700263 << ", Waiting Period = " << utils::FormatSecs(
264 omaha_request_params_.waiting_period.InSeconds());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700265
Andrew de los Reyes45168102010-11-22 11:13:50 -0800266 obeying_proxies_ = true;
267 if (obey_proxies || proxy_manual_checks_ == 0) {
268 LOG(INFO) << "forced to obey proxies";
269 // If forced to obey proxies, every 20th request will not use proxies
270 proxy_manual_checks_++;
271 LOG(INFO) << "proxy manual checks: " << proxy_manual_checks_;
272 if (proxy_manual_checks_ >= kMaxConsecutiveObeyProxyRequests) {
273 proxy_manual_checks_ = 0;
274 obeying_proxies_ = false;
275 }
276 } else if (base::RandInt(0, 4) == 0) {
277 obeying_proxies_ = false;
278 }
279 LOG_IF(INFO, !obeying_proxies_) << "To help ensure updates work, this update "
280 "check we are ignoring the proxy settings and using "
281 "direct connections.";
282
Darin Petkov36275772010-10-01 11:40:57 -0700283 DisableDeltaUpdateIfNeeded();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700284 return true;
285}
286
Jay Srinivasan21be0752012-07-25 15:44:56 -0700287void UpdateAttempter::CalculateScatteringParams(bool is_user_initiated) {
288 // Take a copy of the old scatter value before we update it, as
289 // we need to update the waiting period if this value changes.
290 TimeDelta old_scatter_factor = scatter_factor_;
291 const policy::DevicePolicy* device_policy = system_state_->GetDevicePolicy();
292 if (device_policy) {
293 int64 new_scatter_factor_in_secs = 0;
294 device_policy->GetScatterFactorInSeconds(&new_scatter_factor_in_secs);
295 if (new_scatter_factor_in_secs < 0) // sanitize input, just in case.
296 new_scatter_factor_in_secs = 0;
297 scatter_factor_ = TimeDelta::FromSeconds(new_scatter_factor_in_secs);
298 }
299
300 bool is_scatter_enabled = false;
301 if (scatter_factor_.InSeconds() == 0) {
302 LOG(INFO) << "Scattering disabled since scatter factor is set to 0";
303 } else if (is_user_initiated) {
304 LOG(INFO) << "Scattering disabled as this update check is user-initiated";
305 } else if (!system_state_->IsOOBEComplete()) {
306 LOG(INFO) << "Scattering disabled since OOBE is not complete yet";
307 } else {
308 is_scatter_enabled = true;
309 LOG(INFO) << "Scattering is enabled";
310 }
311
312 if (is_scatter_enabled) {
313 // This means the scattering policy is turned on.
314 // Now check if we need to update the waiting period. The two cases
315 // in which we'd need to update the waiting period are:
316 // 1. First time in process or a scheduled check after a user-initiated one.
317 // (omaha_request_params_.waiting_period will be zero in this case).
318 // 2. Admin has changed the scattering policy value.
319 // (new scattering value will be different from old one in this case).
320 int64 wait_period_in_secs = 0;
321 if (omaha_request_params_.waiting_period.InSeconds() == 0) {
322 // First case. Check if we have a suitable value to set for
323 // the waiting period.
324 if (prefs_->GetInt64(kPrefsWallClockWaitPeriod, &wait_period_in_secs) &&
325 wait_period_in_secs > 0 &&
326 wait_period_in_secs <= scatter_factor_.InSeconds()) {
327 // This means:
328 // 1. There's a persisted value for the waiting period available.
329 // 2. And that persisted value is still valid.
330 // So, in this case, we should reuse the persisted value instead of
331 // generating a new random value to improve the chances of a good
332 // distribution for scattering.
333 omaha_request_params_.waiting_period =
334 TimeDelta::FromSeconds(wait_period_in_secs);
335 LOG(INFO) << "Using persisted wall-clock waiting period: " <<
336 utils::FormatSecs(omaha_request_params_.waiting_period.InSeconds());
337 }
338 else {
339 // This means there's no persisted value for the waiting period
340 // available or its value is invalid given the new scatter_factor value.
341 // So, we should go ahead and regenerate a new value for the
342 // waiting period.
343 LOG(INFO) << "Persisted value not present or not valid ("
344 << utils::FormatSecs(wait_period_in_secs)
345 << ") for wall-clock waiting period.";
346 GenerateNewWaitingPeriod();
347 }
348 } else if (scatter_factor_ != old_scatter_factor) {
349 // This means there's already a waiting period value, but we detected
350 // a change in the scattering policy value. So, we should regenerate the
351 // waiting period to make sure it's within the bounds of the new scatter
352 // factor value.
353 GenerateNewWaitingPeriod();
354 } else {
355 // Neither the first time scattering is enabled nor the scattering value
356 // changed. Nothing to do.
357 LOG(INFO) << "Keeping current wall-clock waiting period: " <<
358 utils::FormatSecs(omaha_request_params_.waiting_period.InSeconds());
359 }
360
361 // The invariant at this point is that omaha_request_params_.waiting_period
362 // is non-zero no matter which path we took above.
363 LOG_IF(ERROR, omaha_request_params_.waiting_period.InSeconds() == 0)
364 << "Waiting Period should NOT be zero at this point!!!";
365
366 // Since scattering is enabled, wall clock based wait will always be
367 // enabled.
368 omaha_request_params_.wall_clock_based_wait_enabled = true;
369
370 // If we don't have any issues in accessing the file system to update
371 // the update check count value, we'll turn that on as well.
372 bool decrement_succeeded = DecrementUpdateCheckCount();
373 omaha_request_params_.update_check_count_wait_enabled = decrement_succeeded;
374 } else {
375 // This means the scattering feature is turned off or disabled for
376 // this particular update check. Make sure to disable
377 // all the knobs and artifacts so that we don't invoke any scattering
378 // related code.
379 omaha_request_params_.wall_clock_based_wait_enabled = false;
380 omaha_request_params_.update_check_count_wait_enabled = false;
381 omaha_request_params_.waiting_period = TimeDelta::FromSeconds(0);
382 prefs_->Delete(kPrefsWallClockWaitPeriod);
383 prefs_->Delete(kPrefsUpdateCheckCount);
384 // Don't delete the UpdateFirstSeenAt file as we don't want manual checks
385 // that result in no-updates (e.g. due to server side throttling) to
386 // cause update starvation by having the client generate a new
387 // UpdateFirstSeenAt for each scheduled check that follows a manual check.
388 }
389}
390
391void UpdateAttempter::GenerateNewWaitingPeriod() {
392 omaha_request_params_.waiting_period = TimeDelta::FromSeconds(
393 base::RandInt(1, scatter_factor_.InSeconds()));
394
395 LOG(INFO) << "Generated new wall-clock waiting period: " << utils::FormatSecs(
396 omaha_request_params_.waiting_period.InSeconds());
397
398 // Do a best-effort to persist this in all cases. Even if the persistence
399 // fails, we'll still be able to scatter based on our in-memory value.
400 // The persistence only helps in ensuring a good overall distribution
401 // across multiple devices if they tend to reboot too often.
402 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
403 omaha_request_params_.waiting_period.InSeconds());
404}
405
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700406void UpdateAttempter::BuildUpdateActions(bool interactive) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700407 CHECK(!processor_->IsRunning());
408 processor_->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700409
410 // Actions:
Darin Petkova0929552010-11-29 14:19:06 -0800411 LibcurlHttpFetcher* update_check_fetcher =
Gilad Arnold7c04e762012-05-23 10:54:02 -0700412 new LibcurlHttpFetcher(GetProxyResolver(), system_state_, is_test_mode_);
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700413 // Try harder to connect to the network, esp when not interactive.
414 // See comment in libcurl_http_fetcher.cc.
415 update_check_fetcher->set_no_network_max_retries(interactive ? 1 : 3);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700416 update_check_fetcher->set_check_certificate(CertificateChecker::kUpdate);
Darin Petkov6a5b3222010-07-13 14:55:28 -0700417 shared_ptr<OmahaRequestAction> update_check_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700418 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700419 &omaha_request_params_,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700420 NULL,
Thieu Le116fda32011-04-19 11:01:54 -0700421 update_check_fetcher, // passes ownership
422 false));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700423 shared_ptr<OmahaResponseHandlerAction> response_handler_action(
Darin Petkov73058b42010-10-06 16:32:19 -0700424 new OmahaResponseHandlerAction(prefs_));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700425 shared_ptr<FilesystemCopierAction> filesystem_copier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700426 new FilesystemCopierAction(false, false));
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700427 shared_ptr<FilesystemCopierAction> kernel_filesystem_copier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700428 new FilesystemCopierAction(true, false));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700429 shared_ptr<OmahaRequestAction> download_started_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700430 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700431 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700432 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700433 OmahaEvent::kTypeUpdateDownloadStarted),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700434 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700435 system_state_,
436 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700437 false));
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700438 LibcurlHttpFetcher* download_fetcher =
Gilad Arnold7c04e762012-05-23 10:54:02 -0700439 new LibcurlHttpFetcher(GetProxyResolver(), system_state_, is_test_mode_);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700440 download_fetcher->set_check_certificate(CertificateChecker::kDownload);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700441 shared_ptr<DownloadAction> download_action(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700442 new DownloadAction(prefs_,
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800443 new MultiRangeHttpFetcher(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700444 download_fetcher))); // passes ownership
Darin Petkov8c2980e2010-07-16 15:16:49 -0700445 shared_ptr<OmahaRequestAction> download_finished_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700446 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700447 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700448 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700449 OmahaEvent::kTypeUpdateDownloadFinished),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700450 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700451 system_state_,
452 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700453 false));
Darin Petkov3aefa862010-12-07 14:45:00 -0800454 shared_ptr<FilesystemCopierAction> filesystem_verifier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700455 new FilesystemCopierAction(false, true));
Darin Petkov3aefa862010-12-07 14:45:00 -0800456 shared_ptr<FilesystemCopierAction> kernel_filesystem_verifier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700457 new FilesystemCopierAction(true, true));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800458 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
459 new PostinstallRunnerAction);
Darin Petkov8c2980e2010-07-16 15:16:49 -0700460 shared_ptr<OmahaRequestAction> update_complete_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700461 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700462 &omaha_request_params_,
Darin Petkove17f86b2010-07-20 09:12:01 -0700463 new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700464 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700465 system_state_,
466 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700467 false));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700468
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700469 download_action->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700470 response_handler_action_ = response_handler_action;
Darin Petkov9b230572010-10-08 10:20:09 -0700471 download_action_ = download_action;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700472
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700473 actions_.push_back(shared_ptr<AbstractAction>(update_check_action));
474 actions_.push_back(shared_ptr<AbstractAction>(response_handler_action));
475 actions_.push_back(shared_ptr<AbstractAction>(filesystem_copier_action));
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700476 actions_.push_back(shared_ptr<AbstractAction>(
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700477 kernel_filesystem_copier_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700478 actions_.push_back(shared_ptr<AbstractAction>(download_started_action));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700479 actions_.push_back(shared_ptr<AbstractAction>(download_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700480 actions_.push_back(shared_ptr<AbstractAction>(download_finished_action));
Darin Petkov3aefa862010-12-07 14:45:00 -0800481 actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action));
482 actions_.push_back(shared_ptr<AbstractAction>(
483 kernel_filesystem_verifier_action));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800484 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700485 actions_.push_back(shared_ptr<AbstractAction>(update_complete_action));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700486
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700487 // Enqueue the actions
488 for (vector<shared_ptr<AbstractAction> >::iterator it = actions_.begin();
489 it != actions_.end(); ++it) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700490 processor_->EnqueueAction(it->get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700491 }
492
493 // Bond them together. We have to use the leaf-types when calling
494 // BondActions().
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700495 BondActions(update_check_action.get(),
496 response_handler_action.get());
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700497 BondActions(response_handler_action.get(),
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700498 filesystem_copier_action.get());
499 BondActions(filesystem_copier_action.get(),
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700500 kernel_filesystem_copier_action.get());
501 BondActions(kernel_filesystem_copier_action.get(),
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700502 download_action.get());
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700503 BondActions(download_action.get(),
Darin Petkov3aefa862010-12-07 14:45:00 -0800504 filesystem_verifier_action.get());
505 BondActions(filesystem_verifier_action.get(),
506 kernel_filesystem_verifier_action.get());
507 BondActions(kernel_filesystem_verifier_action.get(),
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800508 postinstall_runner_action.get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700509}
510
Gilad Arnold28e2f392012-02-09 14:36:46 -0800511void UpdateAttempter::CheckForUpdate(const string& app_version,
Jay Srinivasane73acab2012-07-10 14:34:03 -0700512 const string& omaha_url,
513 bool is_user_initiated) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700514 LOG(INFO) << "New update check requested";
515
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700516 if (status_ != UPDATE_STATUS_IDLE) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700517 LOG(INFO) << "Skipping update check because current status is "
518 << UpdateStatusToString(status_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700519 return;
520 }
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800521
522 // Read GPIO signals and determine whether this is an automated test scenario.
523 // For safety, we only allow a test update to be performed once; subsequent
524 // update requests will be carried out normally.
Gilad Arnold7c04e762012-05-23 10:54:02 -0700525 bool is_test_mode = (!is_test_update_attempted_ && gpio_handler_ &&
526 gpio_handler_->IsTestModeSignaled());
527 if (is_test_mode) {
528 LOG(WARNING) << "this is a test mode update attempt!";
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700529 is_test_update_attempted_ = true;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800530 }
531
Jay Srinivasan08fce042012-06-07 16:31:01 -0700532 // Passing true for is_user_initiated to indicate that this
533 // is not a scheduled update check.
Gilad Arnold7c04e762012-05-23 10:54:02 -0700534 Update(app_version, omaha_url, true, true, is_test_mode, is_user_initiated);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700535}
536
Darin Petkov296889c2010-07-23 16:20:54 -0700537bool UpdateAttempter::RebootIfNeeded() {
538 if (status_ != UPDATE_STATUS_UPDATED_NEED_REBOOT) {
539 LOG(INFO) << "Reboot requested, but status is "
540 << UpdateStatusToString(status_) << ", so not rebooting.";
541 return false;
542 }
543 TEST_AND_RETURN_FALSE(utils::Reboot());
544 return true;
545}
546
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700547// Delegate methods:
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700548void UpdateAttempter::ProcessingDone(const ActionProcessor* processor,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700549 ActionExitCode code) {
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700550 CHECK(response_handler_action_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700551 LOG(INFO) << "Processing Done.";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700552 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700553
Darin Petkovc6c135c2010-08-11 13:36:18 -0700554 // Reset process priority back to normal.
555 CleanupPriorityManagement();
556
Darin Petkov09f96c32010-07-20 09:24:57 -0700557 if (status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
558 LOG(INFO) << "Error event sent.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800559
560 // Inform scheduler of new status; also specifically inform about a failed
561 // update attempt with a test address.
562 SetStatusAndNotify(UPDATE_STATUS_IDLE,
563 (is_using_test_url_ ? kUpdateNoticeTestAddrFailed :
564 kUpdateNoticeUnspecified));
565
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700566 if (!fake_update_success_) {
567 return;
568 }
569 LOG(INFO) << "Booted from FW B and tried to install new firmware, "
570 "so requesting reboot from user.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700571 }
572
Darin Petkovc1a8b422010-07-19 11:34:49 -0700573 if (code == kActionCodeSuccess) {
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700574 utils::WriteFile(kUpdateCompletedMarker, "", 0);
Darin Petkov36275772010-10-01 11:40:57 -0700575 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Darin Petkov95508da2011-01-05 12:42:29 -0800576 prefs_->SetString(kPrefsPreviousVersion, omaha_request_params_.app_version);
Darin Petkov9b230572010-10-08 10:20:09 -0700577 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700578
579 // Since we're done with scattering fully at this point, this is the
580 // safest point delete the state files, as we're sure that the status is
581 // set to reboot (which means no more updates will be applied until reboot)
582 // This deletion is required for correctness as we want the next update
583 // check to re-create a new random number for the update check count.
584 // Similarly, we also delete the wall-clock-wait period that was persisted
585 // so that we start with a new random value for the next update check
586 // after reboot so that the same device is not favored or punished in any
587 // way.
588 prefs_->Delete(kPrefsUpdateCheckCount);
589 prefs_->Delete(kPrefsWallClockWaitPeriod);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700590 prefs_->Delete(kPrefsUpdateFirstSeenAt);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700591
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800592 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
593 kUpdateNoticeUnspecified);
Darin Petkov9d65b7b2010-07-20 09:13:01 -0700594
595 // Report the time it took to update the system.
596 int64_t update_time = time(NULL) - last_checked_time_;
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700597 if (!fake_update_success_)
598 metrics_lib_->SendToUMA("Installer.UpdateTime",
599 static_cast<int>(update_time), // sample
600 1, // min = 1 second
601 20 * 60, // max = 20 minutes
602 50); // buckets
Darin Petkov09f96c32010-07-20 09:24:57 -0700603 return;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700604 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700605
Darin Petkov1023a602010-08-30 13:47:51 -0700606 if (ScheduleErrorEventAction()) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700607 return;
Darin Petkov1023a602010-08-30 13:47:51 -0700608 }
609 LOG(INFO) << "No update.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800610 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700611}
612
613void UpdateAttempter::ProcessingStopped(const ActionProcessor* processor) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700614 // Reset process priority back to normal.
615 CleanupPriorityManagement();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700616 download_progress_ = 0.0;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800617 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700618 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700619 error_event_.reset(NULL);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700620}
621
622// Called whenever an action has finished processing, either successfully
623// or otherwise.
624void UpdateAttempter::ActionCompleted(ActionProcessor* processor,
625 AbstractAction* action,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700626 ActionExitCode code) {
Darin Petkov1023a602010-08-30 13:47:51 -0700627 // Reset download progress regardless of whether or not the download
628 // action succeeded. Also, get the response code from HTTP request
629 // actions (update download as well as the initial update check
630 // actions).
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700631 const string type = action->Type();
Darin Petkov1023a602010-08-30 13:47:51 -0700632 if (type == DownloadAction::StaticType()) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700633 download_progress_ = 0.0;
Darin Petkov1023a602010-08-30 13:47:51 -0700634 DownloadAction* download_action = dynamic_cast<DownloadAction*>(action);
635 http_response_code_ = download_action->GetHTTPResponseCode();
636 } else if (type == OmahaRequestAction::StaticType()) {
637 OmahaRequestAction* omaha_request_action =
638 dynamic_cast<OmahaRequestAction*>(action);
639 // If the request is not an event, then it's the update-check.
640 if (!omaha_request_action->IsEvent()) {
641 http_response_code_ = omaha_request_action->GetHTTPResponseCode();
Darin Petkov85ced132010-09-01 10:20:56 -0700642 // Forward the server-dictated poll interval to the update check
643 // scheduler, if any.
644 if (update_check_scheduler_) {
645 update_check_scheduler_->set_poll_interval(
646 omaha_request_action->GetOutputObject().poll_interval);
647 }
Darin Petkov1023a602010-08-30 13:47:51 -0700648 }
649 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700650 if (code != kActionCodeSuccess) {
Darin Petkov7ed561b2011-10-04 02:59:03 -0700651 // If the current state is at or past the download phase, count the failure
652 // in case a switch to full update becomes necessary. Ignore network
653 // transfer timeouts and failures.
Darin Petkov36275772010-10-01 11:40:57 -0700654 if (status_ >= UPDATE_STATUS_DOWNLOADING &&
Darin Petkov36275772010-10-01 11:40:57 -0700655 code != kActionCodeDownloadTransferError) {
656 MarkDeltaUpdateFailure();
657 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700658 // On failure, schedule an error event to be sent to Omaha.
659 CreatePendingErrorEvent(action, code);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700660 return;
Darin Petkov09f96c32010-07-20 09:24:57 -0700661 }
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700662 // Find out which action completed.
663 if (type == OmahaResponseHandlerAction::StaticType()) {
Darin Petkov9b230572010-10-08 10:20:09 -0700664 // Note that the status will be updated to DOWNLOADING when some bytes get
665 // actually downloaded from the server and the BytesReceived callback is
666 // invoked. This avoids notifying the user that a download has started in
667 // cases when the server and the client are unable to initiate the download.
668 CHECK(action == response_handler_action_.get());
669 const InstallPlan& plan = response_handler_action_->install_plan();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700670 last_checked_time_ = time(NULL);
671 // TODO(adlr): put version in InstallPlan
672 new_version_ = "0.0.0.0";
673 new_size_ = plan.size;
Darin Petkov9b230572010-10-08 10:20:09 -0700674 SetupDownload();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700675 SetupPriorityManagement();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800676 SetStatusAndNotify(UPDATE_STATUS_UPDATE_AVAILABLE,
677 kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700678 } else if (type == DownloadAction::StaticType()) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800679 SetStatusAndNotify(UPDATE_STATUS_FINALIZING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700680 }
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700681}
682
683// Stop updating. An attempt will be made to record status to the disk
684// so that updates can be resumed later.
685void UpdateAttempter::Terminate() {
686 // TODO(adlr): implement this method.
687 NOTIMPLEMENTED();
688}
689
690// Try to resume from a previously Terminate()d update.
691void UpdateAttempter::ResumeUpdating() {
692 // TODO(adlr): implement this method.
693 NOTIMPLEMENTED();
694}
695
Darin Petkov9d911fa2010-08-19 09:36:08 -0700696void UpdateAttempter::SetDownloadStatus(bool active) {
697 download_active_ = active;
698 LOG(INFO) << "Download status: " << (active ? "active" : "inactive");
699}
700
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700701void UpdateAttempter::BytesReceived(uint64_t bytes_received, uint64_t total) {
Darin Petkov9d911fa2010-08-19 09:36:08 -0700702 if (!download_active_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700703 LOG(ERROR) << "BytesReceived called while not downloading.";
704 return;
705 }
Darin Petkovaf183052010-08-23 12:07:13 -0700706 double progress = static_cast<double>(bytes_received) /
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700707 static_cast<double>(total);
Darin Petkovaf183052010-08-23 12:07:13 -0700708 // Self throttle based on progress. Also send notifications if
709 // progress is too slow.
710 const double kDeltaPercent = 0.01; // 1%
711 if (status_ != UPDATE_STATUS_DOWNLOADING ||
712 bytes_received == total ||
713 progress - download_progress_ >= kDeltaPercent ||
714 TimeTicks::Now() - last_notify_time_ >= TimeDelta::FromSeconds(10)) {
715 download_progress_ = progress;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800716 SetStatusAndNotify(UPDATE_STATUS_DOWNLOADING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700717 }
718}
719
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700720bool UpdateAttempter::GetStatus(int64_t* last_checked_time,
721 double* progress,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800722 string* current_operation,
723 string* new_version,
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700724 int64_t* new_size) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700725 *last_checked_time = last_checked_time_;
726 *progress = download_progress_;
727 *current_operation = UpdateStatusToString(status_);
728 *new_version = new_version_;
729 *new_size = new_size_;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700730 return true;
731}
732
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700733void UpdateAttempter::UpdateBootFlags() {
Darin Petkov58dd1342011-05-06 12:05:13 -0700734 if (update_boot_flags_running_) {
735 LOG(INFO) << "Update boot flags running, nothing to do.";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700736 return;
737 }
Darin Petkov58dd1342011-05-06 12:05:13 -0700738 if (updated_boot_flags_) {
739 LOG(INFO) << "Already updated boot flags. Skipping.";
740 if (start_action_processor_) {
741 ScheduleProcessingStart();
742 }
743 return;
744 }
745 // This is purely best effort. Failures should be logged by Subprocess. Run
746 // the script asynchronously to avoid blocking the event loop regardless of
747 // the script runtime.
748 update_boot_flags_running_ = true;
749 LOG(INFO) << "Updating boot flags...";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700750 vector<string> cmd(1, "/usr/sbin/chromeos-setgoodkernel");
Darin Petkov58dd1342011-05-06 12:05:13 -0700751 if (!Subprocess::Get().Exec(cmd, StaticCompleteUpdateBootFlags, this)) {
752 CompleteUpdateBootFlags(1);
753 }
754}
755
756void UpdateAttempter::CompleteUpdateBootFlags(int return_code) {
757 update_boot_flags_running_ = false;
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700758 updated_boot_flags_ = true;
Darin Petkov58dd1342011-05-06 12:05:13 -0700759 if (start_action_processor_) {
760 ScheduleProcessingStart();
761 }
762}
763
764void UpdateAttempter::StaticCompleteUpdateBootFlags(
765 int return_code,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800766 const string& output,
Darin Petkov58dd1342011-05-06 12:05:13 -0700767 void* p) {
768 reinterpret_cast<UpdateAttempter*>(p)->CompleteUpdateBootFlags(return_code);
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700769}
770
Darin Petkov61635a92011-05-18 16:20:36 -0700771void UpdateAttempter::BroadcastStatus() {
772 if (!dbus_service_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700773 return;
Darin Petkov61635a92011-05-18 16:20:36 -0700774 }
Darin Petkovaf183052010-08-23 12:07:13 -0700775 last_notify_time_ = TimeTicks::Now();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700776 update_engine_service_emit_status_update(
777 dbus_service_,
778 last_checked_time_,
779 download_progress_,
780 UpdateStatusToString(status_),
781 new_version_.c_str(),
782 new_size_);
783}
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700784
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800785void UpdateAttempter::SetStatusAndNotify(UpdateStatus status,
786 UpdateNotice notice) {
Darin Petkov61635a92011-05-18 16:20:36 -0700787 status_ = status;
788 if (update_check_scheduler_) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800789 update_check_scheduler_->SetUpdateStatus(status_, notice);
Darin Petkov61635a92011-05-18 16:20:36 -0700790 }
791 BroadcastStatus();
792}
793
Darin Petkov777dbfa2010-07-20 15:03:37 -0700794void UpdateAttempter::CreatePendingErrorEvent(AbstractAction* action,
795 ActionExitCode code) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700796 if (error_event_.get()) {
797 // This shouldn't really happen.
798 LOG(WARNING) << "There's already an existing pending error event.";
799 return;
800 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700801
Darin Petkovabc7bc02011-02-23 14:39:43 -0800802 // For now assume that a generic Omaha response action failure means that
803 // there's no update so don't send an event. Also, double check that the
804 // failure has not occurred while sending an error event -- in which case
805 // don't schedule another. This shouldn't really happen but just in case...
806 if ((action->Type() == OmahaResponseHandlerAction::StaticType() &&
807 code == kActionCodeError) ||
Darin Petkov777dbfa2010-07-20 15:03:37 -0700808 status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
809 return;
810 }
811
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700812 // Classify the code to generate the appropriate result so that
813 // the Borgmon charts show up the results correctly.
814 // Do this before calling GetErrorCodeForAction which could potentially
815 // augment the bit representation of code and thus cause no matches for
816 // the switch cases below.
817 OmahaEvent::Result event_result;
818 switch (code) {
819 case kActionCodeOmahaUpdateIgnoredPerPolicy:
820 case kActionCodeOmahaUpdateDeferredPerPolicy:
821 event_result = OmahaEvent::kResultUpdateDeferred;
822 break;
823 default:
824 event_result = OmahaEvent::kResultError;
825 break;
826 }
827
Darin Petkov777dbfa2010-07-20 15:03:37 -0700828 code = GetErrorCodeForAction(action, code);
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700829 fake_update_success_ = code == kActionCodePostinstallBootedFromFirmwareB;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700830
831 // Apply the bit modifiers to the error code.
832 if (!utils::IsNormalBootMode()) {
833 code = static_cast<ActionExitCode>(code | kActionCodeBootModeFlag);
834 }
835 if (response_handler_action_.get() &&
836 response_handler_action_->install_plan().is_resume) {
837 code = static_cast<ActionExitCode>(code | kActionCodeResumedFlag);
838 }
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700839
Darin Petkov09f96c32010-07-20 09:24:57 -0700840 error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700841 event_result,
Darin Petkov09f96c32010-07-20 09:24:57 -0700842 code));
843}
844
845bool UpdateAttempter::ScheduleErrorEventAction() {
846 if (error_event_.get() == NULL)
847 return false;
848
Darin Petkov1023a602010-08-30 13:47:51 -0700849 LOG(INFO) << "Update failed -- reporting the error event.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700850 shared_ptr<OmahaRequestAction> error_event_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700851 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700852 &omaha_request_params_,
Darin Petkov09f96c32010-07-20 09:24:57 -0700853 error_event_.release(), // Pass ownership.
Jay Srinivasan08fce042012-06-07 16:31:01 -0700854 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700855 system_state_,
856 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700857 false));
Darin Petkov09f96c32010-07-20 09:24:57 -0700858 actions_.push_back(shared_ptr<AbstractAction>(error_event_action));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700859 processor_->EnqueueAction(error_event_action.get());
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800860 SetStatusAndNotify(UPDATE_STATUS_REPORTING_ERROR_EVENT,
861 kUpdateNoticeUnspecified);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700862 processor_->StartProcessing();
Darin Petkov09f96c32010-07-20 09:24:57 -0700863 return true;
864}
865
Darin Petkovc6c135c2010-08-11 13:36:18 -0700866void UpdateAttempter::SetPriority(utils::ProcessPriority priority) {
867 if (priority_ == priority) {
868 return;
869 }
870 if (utils::SetProcessPriority(priority)) {
871 priority_ = priority;
872 LOG(INFO) << "Process priority = " << priority_;
873 }
874}
875
876void UpdateAttempter::SetupPriorityManagement() {
877 if (manage_priority_source_) {
878 LOG(ERROR) << "Process priority timeout source hasn't been destroyed.";
879 CleanupPriorityManagement();
880 }
Darin Petkovf622ef72010-10-26 13:49:24 -0700881 const int kPriorityTimeout = 2 * 60 * 60; // 2 hours
Darin Petkovc6c135c2010-08-11 13:36:18 -0700882 manage_priority_source_ = g_timeout_source_new_seconds(kPriorityTimeout);
883 g_source_set_callback(manage_priority_source_,
884 StaticManagePriorityCallback,
885 this,
886 NULL);
887 g_source_attach(manage_priority_source_, NULL);
888 SetPriority(utils::kProcessPriorityLow);
889}
890
891void UpdateAttempter::CleanupPriorityManagement() {
892 if (manage_priority_source_) {
893 g_source_destroy(manage_priority_source_);
894 manage_priority_source_ = NULL;
895 }
896 SetPriority(utils::kProcessPriorityNormal);
897}
898
899gboolean UpdateAttempter::StaticManagePriorityCallback(gpointer data) {
900 return reinterpret_cast<UpdateAttempter*>(data)->ManagePriorityCallback();
901}
902
Darin Petkove6ef2f82011-03-07 17:31:11 -0800903gboolean UpdateAttempter::StaticStartProcessing(gpointer data) {
904 reinterpret_cast<UpdateAttempter*>(data)->processor_->StartProcessing();
905 return FALSE; // Don't call this callback again.
906}
907
Darin Petkov58dd1342011-05-06 12:05:13 -0700908void UpdateAttempter::ScheduleProcessingStart() {
909 LOG(INFO) << "Scheduling an action processor start.";
910 start_action_processor_ = false;
911 g_idle_add(&StaticStartProcessing, this);
912}
913
Darin Petkovc6c135c2010-08-11 13:36:18 -0700914bool UpdateAttempter::ManagePriorityCallback() {
Darin Petkovf622ef72010-10-26 13:49:24 -0700915 SetPriority(utils::kProcessPriorityNormal);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700916 manage_priority_source_ = NULL;
Darin Petkovf622ef72010-10-26 13:49:24 -0700917 return false; // Destroy the timeout source.
Darin Petkovc6c135c2010-08-11 13:36:18 -0700918}
919
Darin Petkov36275772010-10-01 11:40:57 -0700920void UpdateAttempter::DisableDeltaUpdateIfNeeded() {
921 int64_t delta_failures;
922 if (omaha_request_params_.delta_okay &&
923 prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) &&
924 delta_failures >= kMaxDeltaUpdateFailures) {
925 LOG(WARNING) << "Too many delta update failures, forcing full update.";
926 omaha_request_params_.delta_okay = false;
927 }
928}
929
930void UpdateAttempter::MarkDeltaUpdateFailure() {
Darin Petkov2dd01092010-10-08 15:43:05 -0700931 // Don't try to resume a failed delta update.
932 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Darin Petkov36275772010-10-01 11:40:57 -0700933 int64_t delta_failures;
934 if (!prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) ||
935 delta_failures < 0) {
936 delta_failures = 0;
937 }
938 prefs_->SetInt64(kPrefsDeltaUpdateFailures, ++delta_failures);
939}
940
Darin Petkov9b230572010-10-08 10:20:09 -0700941void UpdateAttempter::SetupDownload() {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800942 MultiRangeHttpFetcher* fetcher =
943 dynamic_cast<MultiRangeHttpFetcher*>(download_action_->http_fetcher());
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800944 fetcher->ClearRanges();
Darin Petkov9b230572010-10-08 10:20:09 -0700945 if (response_handler_action_->install_plan().is_resume) {
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700946 // Resuming an update so fetch the update manifest metadata first.
Darin Petkov9b230572010-10-08 10:20:09 -0700947 int64_t manifest_metadata_size = 0;
948 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800949 fetcher->AddRange(0, manifest_metadata_size);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700950 // If there're remaining unprocessed data blobs, fetch them. Be careful not
951 // to request data beyond the end of the payload to avoid 416 HTTP response
952 // error codes.
Darin Petkov9b230572010-10-08 10:20:09 -0700953 int64_t next_data_offset = 0;
954 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700955 uint64_t resume_offset = manifest_metadata_size + next_data_offset;
956 if (resume_offset < response_handler_action_->install_plan().size) {
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800957 fetcher->AddRange(resume_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700958 }
Darin Petkov9b230572010-10-08 10:20:09 -0700959 } else {
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800960 fetcher->AddRange(0);
Darin Petkov9b230572010-10-08 10:20:09 -0700961 }
Darin Petkov9b230572010-10-08 10:20:09 -0700962}
963
Thieu Le116fda32011-04-19 11:01:54 -0700964void UpdateAttempter::PingOmaha() {
Thieu Led88a8572011-05-26 09:09:19 -0700965 if (!processor_->IsRunning()) {
966 shared_ptr<OmahaRequestAction> ping_action(
967 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700968 &omaha_request_params_,
Thieu Led88a8572011-05-26 09:09:19 -0700969 NULL,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700970 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700971 system_state_,
972 is_test_mode_),
Thieu Led88a8572011-05-26 09:09:19 -0700973 true));
974 actions_.push_back(shared_ptr<OmahaRequestAction>(ping_action));
975 processor_->set_delegate(NULL);
976 processor_->EnqueueAction(ping_action.get());
977 // Call StartProcessing() synchronously here to avoid any race conditions
978 // caused by multiple outstanding ping Omaha requests. If we call
979 // StartProcessing() asynchronously, the device can be suspended before we
980 // get a chance to callback to StartProcessing(). When the device resumes
981 // (assuming the device sleeps longer than the next update check period),
982 // StartProcessing() is called back and at the same time, the next update
983 // check is fired which eventually invokes StartProcessing(). A crash
984 // can occur because StartProcessing() checks to make sure that the
985 // processor is idle which it isn't due to the two concurrent ping Omaha
986 // requests.
987 processor_->StartProcessing();
988 } else {
Darin Petkov58dd1342011-05-06 12:05:13 -0700989 LOG(WARNING) << "Action processor running, Omaha ping suppressed.";
Darin Petkov58dd1342011-05-06 12:05:13 -0700990 }
Thieu Led88a8572011-05-26 09:09:19 -0700991
992 // Update the status which will schedule the next update check
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800993 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
994 kUpdateNoticeUnspecified);
Thieu Le116fda32011-04-19 11:01:54 -0700995}
996
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700997
998bool UpdateAttempter::DecrementUpdateCheckCount() {
999 int64 update_check_count_value;
1000
1001 if (!prefs_->Exists(kPrefsUpdateCheckCount)) {
1002 // This file does not exist. This means we haven't started our update
1003 // check count down yet, so nothing more to do. This file will be created
1004 // later when we first satisfy the wall-clock-based-wait period.
1005 LOG(INFO) << "No existing update check count. That's normal.";
1006 return true;
1007 }
1008
1009 if (prefs_->GetInt64(kPrefsUpdateCheckCount, &update_check_count_value)) {
1010 // Only if we're able to read a proper integer value, then go ahead
1011 // and decrement and write back the result in the same file, if needed.
1012 LOG(INFO) << "Update check count = " << update_check_count_value;
1013
1014 if (update_check_count_value == 0) {
1015 // It could be 0, if, for some reason, the file didn't get deleted
1016 // when we set our status to waiting for reboot. so we just leave it
1017 // as is so that we can prevent another update_check wait for this client.
1018 LOG(INFO) << "Not decrementing update check count as it's already 0.";
1019 return true;
1020 }
1021
1022 if (update_check_count_value > 0)
1023 update_check_count_value--;
1024 else
1025 update_check_count_value = 0;
1026
1027 // Write out the new value of update_check_count_value.
1028 if (prefs_->SetInt64(kPrefsUpdateCheckCount, update_check_count_value)) {
1029 // We successfully wrote out te new value, so enable the
1030 // update check based wait.
1031 LOG(INFO) << "New update check count = " << update_check_count_value;
1032 return true;
1033 }
1034 }
1035
1036 LOG(INFO) << "Deleting update check count state due to read/write errors.";
1037
1038 // We cannot read/write to the file, so disable the update check based wait
1039 // so that we don't get stuck in this OS version by any chance (which could
1040 // happen if there's some bug that causes to read/write incorrectly).
1041 // Also attempt to delete the file to do our best effort to cleanup.
1042 prefs_->Delete(kPrefsUpdateCheckCount);
1043 return false;
1044}
1045
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07001046} // namespace chromeos_update_engine