blob: ca6643bafaba414e75f03a6620b8f23842f51be9 [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
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07007#include <string>
Darin Petkov9b230572010-10-08 10:20:09 -07008#include <tr1/memory>
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07009#include <vector>
Darin Petkov9d65b7b2010-07-20 09:13:01 -070010
Jay Srinivasanc1ba09a2012-08-14 14:15:57 -070011#include <base/file_util.h>
Andrew de los Reyes45168102010-11-22 11:13:50 -080012#include <base/rand_util.h>
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070013#include <glib.h>
Darin Petkov1023a602010-08-30 13:47:51 -070014#include <metrics/metrics_library.h>
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +020015#include <policy/libpolicy.h>
16#include <policy/device_policy.h>
Darin Petkov9d65b7b2010-07-20 09:13:01 -070017
Bruno Rocha7f9aea22011-09-12 14:31:24 -070018#include "update_engine/certificate_checker.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070019#include "update_engine/constants.h"
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070020#include "update_engine/dbus_service.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070021#include "update_engine/download_action.h"
22#include "update_engine/filesystem_copier_action.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080023#include "update_engine/gpio_handler.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070024#include "update_engine/libcurl_http_fetcher.h"
Andrew de los Reyes819fef22010-12-17 11:33:58 -080025#include "update_engine/multi_range_http_fetcher.h"
Darin Petkov6a5b3222010-07-13 14:55:28 -070026#include "update_engine/omaha_request_action.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070027#include "update_engine/omaha_request_params.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070028#include "update_engine/omaha_response_handler_action.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080029#include "update_engine/payload_state_interface.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070030#include "update_engine/postinstall_runner_action.h"
Darin Petkov36275772010-10-01 11:40:57 -070031#include "update_engine/prefs_interface.h"
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -070032#include "update_engine/subprocess.h"
Jay Srinivasan43488792012-06-19 00:25:31 -070033#include "update_engine/system_state.h"
Darin Petkov1023a602010-08-30 13:47:51 -070034#include "update_engine/update_check_scheduler.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070035
Darin Petkovaf183052010-08-23 12:07:13 -070036using base::TimeDelta;
37using base::TimeTicks;
Andrew de los Reyes21816e12011-04-07 14:18:56 -070038using google::protobuf::NewPermanentCallback;
Darin Petkov9b230572010-10-08 10:20:09 -070039using std::make_pair;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070040using std::tr1::shared_ptr;
Jay Srinivasan43488792012-06-19 00:25:31 -070041using std::set;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070042using std::string;
43using std::vector;
44
45namespace chromeos_update_engine {
46
Darin Petkov36275772010-10-01 11:40:57 -070047const int UpdateAttempter::kMaxDeltaUpdateFailures = 3;
48
Gilad Arnold1ebd8132012-03-05 10:19:29 -080049// Private test server URL w/ custom port number.
Gilad Arnolded747312012-03-15 18:20:41 -070050// TODO(garnold) This is a temporary hack to allow us to test the closed loop
51// automated update testing. To be replaced with an hard-coded local IP address.
52const char* const UpdateAttempter::kTestUpdateUrl(
53 "http://garnold.mtv.corp.google.com:8080/update");
Gilad Arnold28e2f392012-02-09 14:36:46 -080054
Darin Petkovcd1666f2010-09-23 09:53:44 -070055const char* kUpdateCompletedMarker =
56 "/var/run/update_engine_autoupdate_completed";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -070057
Andrew de los Reyes45168102010-11-22 11:13:50 -080058namespace {
59const int kMaxConsecutiveObeyProxyRequests = 20;
60} // namespace {}
61
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070062const char* UpdateStatusToString(UpdateStatus status) {
63 switch (status) {
64 case UPDATE_STATUS_IDLE:
65 return "UPDATE_STATUS_IDLE";
66 case UPDATE_STATUS_CHECKING_FOR_UPDATE:
67 return "UPDATE_STATUS_CHECKING_FOR_UPDATE";
68 case UPDATE_STATUS_UPDATE_AVAILABLE:
69 return "UPDATE_STATUS_UPDATE_AVAILABLE";
70 case UPDATE_STATUS_DOWNLOADING:
71 return "UPDATE_STATUS_DOWNLOADING";
72 case UPDATE_STATUS_VERIFYING:
73 return "UPDATE_STATUS_VERIFYING";
74 case UPDATE_STATUS_FINALIZING:
75 return "UPDATE_STATUS_FINALIZING";
76 case UPDATE_STATUS_UPDATED_NEED_REBOOT:
77 return "UPDATE_STATUS_UPDATED_NEED_REBOOT";
Darin Petkov09f96c32010-07-20 09:24:57 -070078 case UPDATE_STATUS_REPORTING_ERROR_EVENT:
79 return "UPDATE_STATUS_REPORTING_ERROR_EVENT";
Chris Sosad317e402013-06-12 13:47:09 -070080 case UPDATE_STATUS_ATTEMPTING_ROLLBACK:
81 return "UPDATE_STATUS_ATTEMPTING_ROLLBACK";
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070082 default:
83 return "unknown status";
84 }
85}
86
David Zeuthena99981f2013-04-29 13:42:47 -070087// Turns a generic kErrorCodeError to a generic error code specific
88// to |action| (e.g., kErrorCodeFilesystemCopierError). If |code| is
89// not kErrorCodeError, or the action is not matched, returns |code|
Darin Petkov777dbfa2010-07-20 15:03:37 -070090// unchanged.
David Zeuthena99981f2013-04-29 13:42:47 -070091ErrorCode GetErrorCodeForAction(AbstractAction* action,
92 ErrorCode code) {
93 if (code != kErrorCodeError)
Darin Petkov777dbfa2010-07-20 15:03:37 -070094 return code;
95
96 const string type = action->Type();
97 if (type == OmahaRequestAction::StaticType())
David Zeuthena99981f2013-04-29 13:42:47 -070098 return kErrorCodeOmahaRequestError;
Darin Petkov777dbfa2010-07-20 15:03:37 -070099 if (type == OmahaResponseHandlerAction::StaticType())
David Zeuthena99981f2013-04-29 13:42:47 -0700100 return kErrorCodeOmahaResponseHandlerError;
Darin Petkov777dbfa2010-07-20 15:03:37 -0700101 if (type == FilesystemCopierAction::StaticType())
David Zeuthena99981f2013-04-29 13:42:47 -0700102 return kErrorCodeFilesystemCopierError;
Darin Petkov777dbfa2010-07-20 15:03:37 -0700103 if (type == PostinstallRunnerAction::StaticType())
David Zeuthena99981f2013-04-29 13:42:47 -0700104 return kErrorCodePostinstallRunnerError;
Darin Petkov777dbfa2010-07-20 15:03:37 -0700105
106 return code;
107}
108
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800109UpdateAttempter::UpdateAttempter(SystemState* system_state,
Gilad Arnoldbf7919b2013-01-08 13:07:37 -0800110 DbusGlibInterface* dbus_iface)
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700111 : processor_(new ActionProcessor()),
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800112 system_state_(system_state),
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700113 dbus_service_(NULL),
Darin Petkov1023a602010-08-30 13:47:51 -0700114 update_check_scheduler_(NULL),
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700115 fake_update_success_(false),
Darin Petkov1023a602010-08-30 13:47:51 -0700116 http_response_code_(0),
Chris Sosa4f8ee272012-11-30 13:01:54 -0800117 shares_(utils::kCpuSharesNormal),
118 manage_shares_source_(NULL),
Darin Petkov9d911fa2010-08-19 09:36:08 -0700119 download_active_(false),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700120 status_(UPDATE_STATUS_IDLE),
121 download_progress_(0.0),
122 last_checked_time_(0),
123 new_version_("0.0.0.0"),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700124 new_payload_size_(0),
Andrew de los Reyes45168102010-11-22 11:13:50 -0800125 proxy_manual_checks_(0),
126 obeying_proxies_(true),
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700127 chrome_proxy_resolver_(dbus_iface),
Darin Petkov58dd1342011-05-06 12:05:13 -0700128 updated_boot_flags_(false),
129 update_boot_flags_running_(false),
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200130 start_action_processor_(false),
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800131 policy_provider_(NULL),
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700132 is_using_test_url_(false),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700133 is_test_mode_(false),
Gilad Arnoldbf7919b2013-01-08 13:07:37 -0800134 is_test_update_attempted_(false) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800135 prefs_ = system_state->prefs();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700136 omaha_request_params_ = system_state->request_params();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700137 if (utils::FileExists(kUpdateCompletedMarker))
138 status_ = UPDATE_STATUS_UPDATED_NEED_REBOOT;
139}
140
141UpdateAttempter::~UpdateAttempter() {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800142 CleanupCpuSharesManagement();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700143}
144
Gilad Arnold28e2f392012-02-09 14:36:46 -0800145void UpdateAttempter::Update(const string& app_version,
146 const string& omaha_url,
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700147 bool obey_proxies,
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800148 bool interactive,
Gilad Arnoldb92f0df2013-01-10 16:32:45 -0800149 bool is_test_mode) {
Andrew de los Reyes000d8952011-03-02 15:21:14 -0800150 chrome_proxy_resolver_.Init();
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700151 fake_update_success_ = false;
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700152 if (status_ == UPDATE_STATUS_UPDATED_NEED_REBOOT) {
Thieu Le116fda32011-04-19 11:01:54 -0700153 // Although we have applied an update, we still want to ping Omaha
154 // to ensure the number of active statistics is accurate.
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700155 LOG(INFO) << "Not updating b/c we already updated and we're waiting for "
Thieu Le116fda32011-04-19 11:01:54 -0700156 << "reboot, we'll ping Omaha instead";
157 PingOmaha();
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700158 return;
159 }
160 if (status_ != UPDATE_STATUS_IDLE) {
161 // Update in progress. Do nothing
162 return;
163 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700164
165 if (!CalculateUpdateParams(app_version,
166 omaha_url,
167 obey_proxies,
168 interactive,
Gilad Arnoldb92f0df2013-01-10 16:32:45 -0800169 is_test_mode)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700170 return;
171 }
172
173 BuildUpdateActions(interactive);
174
175 SetStatusAndNotify(UPDATE_STATUS_CHECKING_FOR_UPDATE,
176 kUpdateNoticeUnspecified);
177
178 // Just in case we didn't update boot flags yet, make sure they're updated
179 // before any update processing starts.
180 start_action_processor_ = true;
181 UpdateBootFlags();
182}
183
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700184void UpdateAttempter::RefreshDevicePolicy() {
185 // Lazy initialize the policy provider, or reload the latest policy data.
186 if (!policy_provider_.get())
187 policy_provider_.reset(new policy::PolicyProvider());
188 policy_provider_->Reload();
189
190 const policy::DevicePolicy* device_policy = NULL;
191 if (policy_provider_->device_policy_is_loaded())
192 device_policy = &policy_provider_->GetDevicePolicy();
193
194 if (device_policy)
195 LOG(INFO) << "Device policies/settings present";
196 else
197 LOG(INFO) << "No device policies/settings present.";
198
199 system_state_->set_device_policy(device_policy);
200}
201
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700202bool UpdateAttempter::CalculateUpdateParams(const string& app_version,
203 const string& omaha_url,
204 bool obey_proxies,
205 bool interactive,
Gilad Arnoldb92f0df2013-01-10 16:32:45 -0800206 bool is_test_mode) {
Darin Petkov1023a602010-08-30 13:47:51 -0700207 http_response_code_ = 0;
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200208
Gilad Arnold7c04e762012-05-23 10:54:02 -0700209 // Set the test mode flag for the current update attempt.
210 is_test_mode_ = is_test_mode;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700211 RefreshDevicePolicy();
212 const policy::DevicePolicy* device_policy = system_state_->device_policy();
213 if (device_policy) {
Jay Srinivasandc9a8ca2013-03-19 18:12:38 -0700214 bool update_disabled = false;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700215 if (device_policy->GetUpdateDisabled(&update_disabled))
216 omaha_request_params_->set_update_disabled(update_disabled);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700217
218 string target_version_prefix;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700219 if (device_policy->GetTargetVersionPrefix(&target_version_prefix))
220 omaha_request_params_->set_target_version_prefix(target_version_prefix);
Jay Srinivasan43488792012-06-19 00:25:31 -0700221
222 set<string> allowed_types;
223 string allowed_types_str;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700224 if (device_policy->GetAllowedConnectionTypesForUpdate(&allowed_types)) {
Jay Srinivasan43488792012-06-19 00:25:31 -0700225 set<string>::const_iterator iter;
226 for (iter = allowed_types.begin(); iter != allowed_types.end(); ++iter)
227 allowed_types_str += *iter + " ";
228 }
229
230 LOG(INFO) << "Networks over which updates are allowed per policy : "
231 << (allowed_types_str.empty() ? "all" : allowed_types_str);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700232 }
233
Gilad Arnoldb92f0df2013-01-10 16:32:45 -0800234 CalculateScatteringParams(interactive);
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200235
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800236 // Determine whether an alternative test address should be used.
Gilad Arnold28e2f392012-02-09 14:36:46 -0800237 string omaha_url_to_use = omaha_url;
Gilad Arnold7c04e762012-05-23 10:54:02 -0700238 if ((is_using_test_url_ = (omaha_url_to_use.empty() && is_test_mode_))) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800239 omaha_url_to_use = kTestUpdateUrl;
240 LOG(INFO) << "using alternative server address: " << omaha_url_to_use;
Gilad Arnold28e2f392012-02-09 14:36:46 -0800241 }
242
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700243 if (!omaha_request_params_->Init(app_version,
244 omaha_url_to_use,
245 interactive)) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700246 LOG(ERROR) << "Unable to initialize Omaha request params.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700247 return false;
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700248 }
Darin Petkov3aefa862010-12-07 14:45:00 -0800249
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700250 // Set the target channel iff ReleaseChannelDelegated policy is set to
251 // false and a non-empty ReleaseChannel policy is present. If delegated
252 // is true, we'll ignore ReleaseChannel policy value.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700253 if (device_policy) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700254 bool delegated = false;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700255 if (device_policy->GetReleaseChannelDelegated(&delegated) && delegated) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700256 LOG(INFO) << "Channel settings are delegated to user by policy. "
257 "Ignoring ReleaseChannel policy value";
258 }
259 else {
260 LOG(INFO) << "Channel settings are not delegated to the user by policy";
261 string target_channel;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700262 if (device_policy->GetReleaseChannel(&target_channel) &&
263 !target_channel.empty()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700264 // Pass in false for powerwash_allowed until we add it to the policy
265 // protobuf.
266 LOG(INFO) << "Setting target channel from ReleaseChannel policy value";
267 omaha_request_params_->SetTargetChannel(target_channel, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700268
269 // Since this is the beginning of a new attempt, update the download
270 // channel. The download channel won't be updated until the next
271 // attempt, even if target channel changes meanwhile, so that how we'll
272 // know if we should cancel the current download attempt if there's
273 // such a change in target channel.
274 omaha_request_params_->UpdateDownloadChannel();
275 } else {
276 LOG(INFO) << "No ReleaseChannel specified in policy";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700277 }
278 }
279 }
280
Jay Srinivasan0a708742012-03-20 11:26:12 -0700281 LOG(INFO) << "update_disabled = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700282 << utils::ToString(omaha_request_params_->update_disabled())
Jay Srinivasan0a708742012-03-20 11:26:12 -0700283 << ", target_version_prefix = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700284 << omaha_request_params_->target_version_prefix()
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700285 << ", scatter_factor_in_seconds = "
286 << utils::FormatSecs(scatter_factor_.InSeconds());
287
288 LOG(INFO) << "Wall Clock Based Wait Enabled = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700289 << omaha_request_params_->wall_clock_based_wait_enabled()
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700290 << ", Update Check Count Wait Enabled = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700291 << omaha_request_params_->update_check_count_wait_enabled()
Jay Srinivasan21be0752012-07-25 15:44:56 -0700292 << ", Waiting Period = " << utils::FormatSecs(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700293 omaha_request_params_->waiting_period().InSeconds());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700294
Andrew de los Reyes45168102010-11-22 11:13:50 -0800295 obeying_proxies_ = true;
296 if (obey_proxies || proxy_manual_checks_ == 0) {
297 LOG(INFO) << "forced to obey proxies";
298 // If forced to obey proxies, every 20th request will not use proxies
299 proxy_manual_checks_++;
300 LOG(INFO) << "proxy manual checks: " << proxy_manual_checks_;
301 if (proxy_manual_checks_ >= kMaxConsecutiveObeyProxyRequests) {
302 proxy_manual_checks_ = 0;
303 obeying_proxies_ = false;
304 }
305 } else if (base::RandInt(0, 4) == 0) {
306 obeying_proxies_ = false;
307 }
308 LOG_IF(INFO, !obeying_proxies_) << "To help ensure updates work, this update "
309 "check we are ignoring the proxy settings and using "
310 "direct connections.";
311
Darin Petkov36275772010-10-01 11:40:57 -0700312 DisableDeltaUpdateIfNeeded();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700313 return true;
314}
315
Gilad Arnoldb92f0df2013-01-10 16:32:45 -0800316void UpdateAttempter::CalculateScatteringParams(bool interactive) {
Jay Srinivasan21be0752012-07-25 15:44:56 -0700317 // Take a copy of the old scatter value before we update it, as
318 // we need to update the waiting period if this value changes.
319 TimeDelta old_scatter_factor = scatter_factor_;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800320 const policy::DevicePolicy* device_policy = system_state_->device_policy();
Jay Srinivasan21be0752012-07-25 15:44:56 -0700321 if (device_policy) {
322 int64 new_scatter_factor_in_secs = 0;
323 device_policy->GetScatterFactorInSeconds(&new_scatter_factor_in_secs);
324 if (new_scatter_factor_in_secs < 0) // sanitize input, just in case.
325 new_scatter_factor_in_secs = 0;
326 scatter_factor_ = TimeDelta::FromSeconds(new_scatter_factor_in_secs);
327 }
328
329 bool is_scatter_enabled = false;
330 if (scatter_factor_.InSeconds() == 0) {
331 LOG(INFO) << "Scattering disabled since scatter factor is set to 0";
Gilad Arnoldb92f0df2013-01-10 16:32:45 -0800332 } else if (interactive) {
333 LOG(INFO) << "Scattering disabled as this is an interactive update check";
Jay Srinivasan21be0752012-07-25 15:44:56 -0700334 } else if (!system_state_->IsOOBEComplete()) {
335 LOG(INFO) << "Scattering disabled since OOBE is not complete yet";
336 } else {
337 is_scatter_enabled = true;
338 LOG(INFO) << "Scattering is enabled";
339 }
340
341 if (is_scatter_enabled) {
342 // This means the scattering policy is turned on.
343 // Now check if we need to update the waiting period. The two cases
344 // in which we'd need to update the waiting period are:
345 // 1. First time in process or a scheduled check after a user-initiated one.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700346 // (omaha_request_params_->waiting_period will be zero in this case).
Jay Srinivasan21be0752012-07-25 15:44:56 -0700347 // 2. Admin has changed the scattering policy value.
348 // (new scattering value will be different from old one in this case).
349 int64 wait_period_in_secs = 0;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700350 if (omaha_request_params_->waiting_period().InSeconds() == 0) {
Jay Srinivasan21be0752012-07-25 15:44:56 -0700351 // First case. Check if we have a suitable value to set for
352 // the waiting period.
353 if (prefs_->GetInt64(kPrefsWallClockWaitPeriod, &wait_period_in_secs) &&
354 wait_period_in_secs > 0 &&
355 wait_period_in_secs <= scatter_factor_.InSeconds()) {
356 // This means:
357 // 1. There's a persisted value for the waiting period available.
358 // 2. And that persisted value is still valid.
359 // So, in this case, we should reuse the persisted value instead of
360 // generating a new random value to improve the chances of a good
361 // distribution for scattering.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700362 omaha_request_params_->set_waiting_period(
363 TimeDelta::FromSeconds(wait_period_in_secs));
Jay Srinivasan21be0752012-07-25 15:44:56 -0700364 LOG(INFO) << "Using persisted wall-clock waiting period: " <<
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700365 utils::FormatSecs(
366 omaha_request_params_->waiting_period().InSeconds());
Jay Srinivasan21be0752012-07-25 15:44:56 -0700367 }
368 else {
369 // This means there's no persisted value for the waiting period
370 // available or its value is invalid given the new scatter_factor value.
371 // So, we should go ahead and regenerate a new value for the
372 // waiting period.
373 LOG(INFO) << "Persisted value not present or not valid ("
374 << utils::FormatSecs(wait_period_in_secs)
375 << ") for wall-clock waiting period.";
376 GenerateNewWaitingPeriod();
377 }
378 } else if (scatter_factor_ != old_scatter_factor) {
379 // This means there's already a waiting period value, but we detected
380 // a change in the scattering policy value. So, we should regenerate the
381 // waiting period to make sure it's within the bounds of the new scatter
382 // factor value.
383 GenerateNewWaitingPeriod();
384 } else {
385 // Neither the first time scattering is enabled nor the scattering value
386 // changed. Nothing to do.
387 LOG(INFO) << "Keeping current wall-clock waiting period: " <<
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700388 utils::FormatSecs(
389 omaha_request_params_->waiting_period().InSeconds());
Jay Srinivasan21be0752012-07-25 15:44:56 -0700390 }
391
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700392 // The invariant at this point is that omaha_request_params_->waiting_period
Jay Srinivasan21be0752012-07-25 15:44:56 -0700393 // is non-zero no matter which path we took above.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700394 LOG_IF(ERROR, omaha_request_params_->waiting_period().InSeconds() == 0)
Jay Srinivasan21be0752012-07-25 15:44:56 -0700395 << "Waiting Period should NOT be zero at this point!!!";
396
397 // Since scattering is enabled, wall clock based wait will always be
398 // enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700399 omaha_request_params_->set_wall_clock_based_wait_enabled(true);
Jay Srinivasan21be0752012-07-25 15:44:56 -0700400
401 // If we don't have any issues in accessing the file system to update
402 // the update check count value, we'll turn that on as well.
403 bool decrement_succeeded = DecrementUpdateCheckCount();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700404 omaha_request_params_->set_update_check_count_wait_enabled(
405 decrement_succeeded);
Jay Srinivasan21be0752012-07-25 15:44:56 -0700406 } else {
407 // This means the scattering feature is turned off or disabled for
408 // this particular update check. Make sure to disable
409 // all the knobs and artifacts so that we don't invoke any scattering
410 // related code.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700411 omaha_request_params_->set_wall_clock_based_wait_enabled(false);
412 omaha_request_params_->set_update_check_count_wait_enabled(false);
413 omaha_request_params_->set_waiting_period(TimeDelta::FromSeconds(0));
Jay Srinivasan21be0752012-07-25 15:44:56 -0700414 prefs_->Delete(kPrefsWallClockWaitPeriod);
415 prefs_->Delete(kPrefsUpdateCheckCount);
416 // Don't delete the UpdateFirstSeenAt file as we don't want manual checks
417 // that result in no-updates (e.g. due to server side throttling) to
418 // cause update starvation by having the client generate a new
419 // UpdateFirstSeenAt for each scheduled check that follows a manual check.
420 }
421}
422
423void UpdateAttempter::GenerateNewWaitingPeriod() {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700424 omaha_request_params_->set_waiting_period(TimeDelta::FromSeconds(
425 base::RandInt(1, scatter_factor_.InSeconds())));
Jay Srinivasan21be0752012-07-25 15:44:56 -0700426
427 LOG(INFO) << "Generated new wall-clock waiting period: " << utils::FormatSecs(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700428 omaha_request_params_->waiting_period().InSeconds());
Jay Srinivasan21be0752012-07-25 15:44:56 -0700429
430 // Do a best-effort to persist this in all cases. Even if the persistence
431 // fails, we'll still be able to scatter based on our in-memory value.
432 // The persistence only helps in ensuring a good overall distribution
433 // across multiple devices if they tend to reboot too often.
434 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700435 omaha_request_params_->waiting_period().InSeconds());
Jay Srinivasan21be0752012-07-25 15:44:56 -0700436}
437
Chris Sosad317e402013-06-12 13:47:09 -0700438void UpdateAttempter::BuildPostInstallActions(
439 InstallPlanAction* previous_action) {
440 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
441 new PostinstallRunnerAction());
442 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
443 BondActions(previous_action,
444 postinstall_runner_action.get());
445}
446
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700447void UpdateAttempter::BuildUpdateActions(bool interactive) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700448 CHECK(!processor_->IsRunning());
449 processor_->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700450
451 // Actions:
Darin Petkova0929552010-11-29 14:19:06 -0800452 LibcurlHttpFetcher* update_check_fetcher =
Gilad Arnold7c04e762012-05-23 10:54:02 -0700453 new LibcurlHttpFetcher(GetProxyResolver(), system_state_, is_test_mode_);
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700454 // Try harder to connect to the network, esp when not interactive.
455 // See comment in libcurl_http_fetcher.cc.
456 update_check_fetcher->set_no_network_max_retries(interactive ? 1 : 3);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700457 update_check_fetcher->set_check_certificate(CertificateChecker::kUpdate);
Darin Petkov6a5b3222010-07-13 14:55:28 -0700458 shared_ptr<OmahaRequestAction> update_check_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800459 new OmahaRequestAction(system_state_,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700460 NULL,
Thieu Le116fda32011-04-19 11:01:54 -0700461 update_check_fetcher, // passes ownership
462 false));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700463 shared_ptr<OmahaResponseHandlerAction> response_handler_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800464 new OmahaResponseHandlerAction(system_state_));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700465 shared_ptr<FilesystemCopierAction> filesystem_copier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700466 new FilesystemCopierAction(false, false));
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700467 shared_ptr<FilesystemCopierAction> kernel_filesystem_copier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700468 new FilesystemCopierAction(true, false));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700469 shared_ptr<OmahaRequestAction> download_started_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800470 new OmahaRequestAction(system_state_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700471 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700472 OmahaEvent::kTypeUpdateDownloadStarted),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700473 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700474 system_state_,
475 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700476 false));
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700477 LibcurlHttpFetcher* download_fetcher =
Gilad Arnold7c04e762012-05-23 10:54:02 -0700478 new LibcurlHttpFetcher(GetProxyResolver(), system_state_, is_test_mode_);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700479 download_fetcher->set_check_certificate(CertificateChecker::kDownload);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700480 shared_ptr<DownloadAction> download_action(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700481 new DownloadAction(prefs_,
Jay Srinivasanf0572052012-10-23 18:12:56 -0700482 system_state_,
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800483 new MultiRangeHttpFetcher(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700484 download_fetcher))); // passes ownership
Darin Petkov8c2980e2010-07-16 15:16:49 -0700485 shared_ptr<OmahaRequestAction> download_finished_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800486 new OmahaRequestAction(system_state_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700487 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700488 OmahaEvent::kTypeUpdateDownloadFinished),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700489 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700490 system_state_,
491 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700492 false));
Darin Petkov3aefa862010-12-07 14:45:00 -0800493 shared_ptr<FilesystemCopierAction> filesystem_verifier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700494 new FilesystemCopierAction(false, true));
Darin Petkov3aefa862010-12-07 14:45:00 -0800495 shared_ptr<FilesystemCopierAction> kernel_filesystem_verifier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700496 new FilesystemCopierAction(true, true));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700497 shared_ptr<OmahaRequestAction> update_complete_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800498 new OmahaRequestAction(system_state_,
Darin Petkove17f86b2010-07-20 09:12:01 -0700499 new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700500 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700501 system_state_,
502 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700503 false));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700504
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700505 download_action->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700506 response_handler_action_ = response_handler_action;
Darin Petkov9b230572010-10-08 10:20:09 -0700507 download_action_ = download_action;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700508
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700509 actions_.push_back(shared_ptr<AbstractAction>(update_check_action));
510 actions_.push_back(shared_ptr<AbstractAction>(response_handler_action));
511 actions_.push_back(shared_ptr<AbstractAction>(filesystem_copier_action));
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700512 actions_.push_back(shared_ptr<AbstractAction>(
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700513 kernel_filesystem_copier_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700514 actions_.push_back(shared_ptr<AbstractAction>(download_started_action));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700515 actions_.push_back(shared_ptr<AbstractAction>(download_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700516 actions_.push_back(shared_ptr<AbstractAction>(download_finished_action));
Darin Petkov3aefa862010-12-07 14:45:00 -0800517 actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action));
Chris Sosad317e402013-06-12 13:47:09 -0700518 actions_.push_back(shared_ptr<AbstractAction>(
519 kernel_filesystem_verifier_action));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700520
521 // Bond them together. We have to use the leaf-types when calling
522 // BondActions().
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700523 BondActions(update_check_action.get(),
524 response_handler_action.get());
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700525 BondActions(response_handler_action.get(),
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700526 filesystem_copier_action.get());
527 BondActions(filesystem_copier_action.get(),
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700528 kernel_filesystem_copier_action.get());
529 BondActions(kernel_filesystem_copier_action.get(),
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700530 download_action.get());
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700531 BondActions(download_action.get(),
Darin Petkov3aefa862010-12-07 14:45:00 -0800532 filesystem_verifier_action.get());
533 BondActions(filesystem_verifier_action.get(),
534 kernel_filesystem_verifier_action.get());
Chris Sosad317e402013-06-12 13:47:09 -0700535
536 BuildPostInstallActions(kernel_filesystem_verifier_action.get());
537
538 actions_.push_back(shared_ptr<AbstractAction>(update_complete_action));
539
540 // Enqueue the actions
541 for (vector<shared_ptr<AbstractAction> >::iterator it = actions_.begin();
542 it != actions_.end(); ++it) {
543 processor_->EnqueueAction(it->get());
544 }
545}
546
Chris Sosaaa18e162013-06-20 13:20:30 -0700547bool UpdateAttempter::Rollback(bool powerwash) {
Chris Sosad317e402013-06-12 13:47:09 -0700548 CHECK(!processor_->IsRunning());
549 processor_->set_delegate(this);
550
Chris Sosaaa18e162013-06-20 13:20:30 -0700551 // TODO(sosa): crbug.com/252539 -- refactor channel into system_state and
552 // check for != stable-channel here.
553 RefreshDevicePolicy();
554
Chris Sosad317e402013-06-12 13:47:09 -0700555 LOG(INFO) << "Setting rollback options.";
556 InstallPlan install_plan;
Chris Sosaaa18e162013-06-20 13:20:30 -0700557 TEST_AND_RETURN_FALSE(utils::GetInstallDev(utils::BootDevice(),
558 &install_plan.install_path));
Chris Sosad317e402013-06-12 13:47:09 -0700559 install_plan.kernel_install_path = utils::BootKernelDevice(
560 install_plan.install_path);
561 install_plan.powerwash_required = powerwash;
562
563 LOG(INFO) << "Using this install plan:";
564 install_plan.Dump();
565
566 shared_ptr<InstallPlanAction> install_plan_action(
567 new InstallPlanAction(install_plan));
568 actions_.push_back(shared_ptr<AbstractAction>(install_plan_action));
569
Chris Sosaaa18e162013-06-20 13:20:30 -0700570 // Initialize the default request params.
571 if (!omaha_request_params_->Init("", "", true)) {
572 LOG(ERROR) << "Unable to initialize Omaha request params.";
573 return false;
574 }
575
Chris Sosad317e402013-06-12 13:47:09 -0700576 BuildPostInstallActions(install_plan_action.get());
577
578 // Enqueue the actions
579 for (vector<shared_ptr<AbstractAction> >::iterator it = actions_.begin();
580 it != actions_.end(); ++it) {
581 processor_->EnqueueAction(it->get());
582 }
Chris Sosaaa18e162013-06-20 13:20:30 -0700583
584 // Update the payload state for Rollback.
585 system_state_->payload_state()->Rollback();
586
Chris Sosad317e402013-06-12 13:47:09 -0700587 SetStatusAndNotify(UPDATE_STATUS_ATTEMPTING_ROLLBACK,
588 kUpdateNoticeUnspecified);
589
590 // Just in case we didn't update boot flags yet, make sure they're updated
591 // before any update processing starts. This also schedules the start of the
592 // actions we just posted.
593 start_action_processor_ = true;
594 UpdateBootFlags();
Chris Sosaaa18e162013-06-20 13:20:30 -0700595 return true;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700596}
597
Gilad Arnold28e2f392012-02-09 14:36:46 -0800598void UpdateAttempter::CheckForUpdate(const string& app_version,
Jay Srinivasane73acab2012-07-10 14:34:03 -0700599 const string& omaha_url,
Gilad Arnoldb92f0df2013-01-10 16:32:45 -0800600 bool interactive) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700601 LOG(INFO) << "New update check requested";
602
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700603 if (status_ != UPDATE_STATUS_IDLE) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700604 LOG(INFO) << "Skipping update check because current status is "
605 << UpdateStatusToString(status_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700606 return;
607 }
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800608
609 // Read GPIO signals and determine whether this is an automated test scenario.
610 // For safety, we only allow a test update to be performed once; subsequent
611 // update requests will be carried out normally.
Gilad Arnoldbf7919b2013-01-08 13:07:37 -0800612 bool is_test_mode = (!is_test_update_attempted_ &&
613 system_state_->gpio_handler()->IsTestModeSignaled());
Gilad Arnold7c04e762012-05-23 10:54:02 -0700614 if (is_test_mode) {
615 LOG(WARNING) << "this is a test mode update attempt!";
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700616 is_test_update_attempted_ = true;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800617 }
618
Gilad Arnoldb92f0df2013-01-10 16:32:45 -0800619 // Pass through the interactive flag, in case we want to simulate a scheduled
620 // test.
621 Update(app_version, omaha_url, true, interactive, is_test_mode);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700622}
623
Darin Petkov296889c2010-07-23 16:20:54 -0700624bool UpdateAttempter::RebootIfNeeded() {
625 if (status_ != UPDATE_STATUS_UPDATED_NEED_REBOOT) {
626 LOG(INFO) << "Reboot requested, but status is "
627 << UpdateStatusToString(status_) << ", so not rebooting.";
628 return false;
629 }
630 TEST_AND_RETURN_FALSE(utils::Reboot());
631 return true;
632}
633
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700634// Delegate methods:
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700635void UpdateAttempter::ProcessingDone(const ActionProcessor* processor,
David Zeuthena99981f2013-04-29 13:42:47 -0700636 ErrorCode code) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700637 LOG(INFO) << "Processing Done.";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700638 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700639
Chris Sosa4f8ee272012-11-30 13:01:54 -0800640 // Reset cpu shares back to normal.
641 CleanupCpuSharesManagement();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700642
Darin Petkov09f96c32010-07-20 09:24:57 -0700643 if (status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
644 LOG(INFO) << "Error event sent.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800645
646 // Inform scheduler of new status; also specifically inform about a failed
647 // update attempt with a test address.
648 SetStatusAndNotify(UPDATE_STATUS_IDLE,
649 (is_using_test_url_ ? kUpdateNoticeTestAddrFailed :
650 kUpdateNoticeUnspecified));
651
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700652 if (!fake_update_success_) {
653 return;
654 }
655 LOG(INFO) << "Booted from FW B and tried to install new firmware, "
656 "so requesting reboot from user.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700657 }
658
David Zeuthena99981f2013-04-29 13:42:47 -0700659 if (code == kErrorCodeSuccess) {
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700660 utils::WriteFile(kUpdateCompletedMarker, "", 0);
Darin Petkov36275772010-10-01 11:40:57 -0700661 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700662 prefs_->SetString(kPrefsPreviousVersion,
663 omaha_request_params_->app_version());
Darin Petkov9b230572010-10-08 10:20:09 -0700664 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700665
David Zeuthen9a017f22013-04-11 16:10:26 -0700666 system_state_->payload_state()->UpdateSucceeded();
667
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700668 // Since we're done with scattering fully at this point, this is the
669 // safest point delete the state files, as we're sure that the status is
670 // set to reboot (which means no more updates will be applied until reboot)
671 // This deletion is required for correctness as we want the next update
672 // check to re-create a new random number for the update check count.
673 // Similarly, we also delete the wall-clock-wait period that was persisted
674 // so that we start with a new random value for the next update check
675 // after reboot so that the same device is not favored or punished in any
676 // way.
677 prefs_->Delete(kPrefsUpdateCheckCount);
678 prefs_->Delete(kPrefsWallClockWaitPeriod);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700679 prefs_->Delete(kPrefsUpdateFirstSeenAt);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700680
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800681 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
682 kUpdateNoticeUnspecified);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700683 LOG(INFO) << "Update successfully applied, waiting to reboot.";
Darin Petkov9d65b7b2010-07-20 09:13:01 -0700684
Jay Srinivasanf0572052012-10-23 18:12:56 -0700685 // Also report the success code so that the percentiles can be
686 // interpreted properly for the remaining error codes in UMA.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800687 utils::SendErrorCodeToUma(system_state_, code);
Darin Petkov09f96c32010-07-20 09:24:57 -0700688 return;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700689 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700690
Darin Petkov1023a602010-08-30 13:47:51 -0700691 if (ScheduleErrorEventAction()) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700692 return;
Darin Petkov1023a602010-08-30 13:47:51 -0700693 }
694 LOG(INFO) << "No update.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800695 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700696}
697
698void UpdateAttempter::ProcessingStopped(const ActionProcessor* processor) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800699 // Reset cpu shares back to normal.
700 CleanupCpuSharesManagement();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700701 download_progress_ = 0.0;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800702 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700703 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700704 error_event_.reset(NULL);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700705}
706
707// Called whenever an action has finished processing, either successfully
708// or otherwise.
709void UpdateAttempter::ActionCompleted(ActionProcessor* processor,
710 AbstractAction* action,
David Zeuthena99981f2013-04-29 13:42:47 -0700711 ErrorCode code) {
Darin Petkov1023a602010-08-30 13:47:51 -0700712 // Reset download progress regardless of whether or not the download
713 // action succeeded. Also, get the response code from HTTP request
714 // actions (update download as well as the initial update check
715 // actions).
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700716 const string type = action->Type();
Darin Petkov1023a602010-08-30 13:47:51 -0700717 if (type == DownloadAction::StaticType()) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700718 download_progress_ = 0.0;
Darin Petkov1023a602010-08-30 13:47:51 -0700719 DownloadAction* download_action = dynamic_cast<DownloadAction*>(action);
720 http_response_code_ = download_action->GetHTTPResponseCode();
721 } else if (type == OmahaRequestAction::StaticType()) {
722 OmahaRequestAction* omaha_request_action =
723 dynamic_cast<OmahaRequestAction*>(action);
724 // If the request is not an event, then it's the update-check.
725 if (!omaha_request_action->IsEvent()) {
726 http_response_code_ = omaha_request_action->GetHTTPResponseCode();
Darin Petkov85ced132010-09-01 10:20:56 -0700727 // Forward the server-dictated poll interval to the update check
728 // scheduler, if any.
729 if (update_check_scheduler_) {
730 update_check_scheduler_->set_poll_interval(
731 omaha_request_action->GetOutputObject().poll_interval);
732 }
Darin Petkov1023a602010-08-30 13:47:51 -0700733 }
734 }
David Zeuthena99981f2013-04-29 13:42:47 -0700735 if (code != kErrorCodeSuccess) {
Darin Petkov7ed561b2011-10-04 02:59:03 -0700736 // If the current state is at or past the download phase, count the failure
737 // in case a switch to full update becomes necessary. Ignore network
738 // transfer timeouts and failures.
Darin Petkov36275772010-10-01 11:40:57 -0700739 if (status_ >= UPDATE_STATUS_DOWNLOADING &&
David Zeuthena99981f2013-04-29 13:42:47 -0700740 code != kErrorCodeDownloadTransferError) {
Darin Petkov36275772010-10-01 11:40:57 -0700741 MarkDeltaUpdateFailure();
742 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700743 // On failure, schedule an error event to be sent to Omaha.
744 CreatePendingErrorEvent(action, code);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700745 return;
Darin Petkov09f96c32010-07-20 09:24:57 -0700746 }
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700747 // Find out which action completed.
748 if (type == OmahaResponseHandlerAction::StaticType()) {
Darin Petkov9b230572010-10-08 10:20:09 -0700749 // Note that the status will be updated to DOWNLOADING when some bytes get
750 // actually downloaded from the server and the BytesReceived callback is
751 // invoked. This avoids notifying the user that a download has started in
752 // cases when the server and the client are unable to initiate the download.
753 CHECK(action == response_handler_action_.get());
754 const InstallPlan& plan = response_handler_action_->install_plan();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700755 last_checked_time_ = time(NULL);
756 // TODO(adlr): put version in InstallPlan
757 new_version_ = "0.0.0.0";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700758 new_payload_size_ = plan.payload_size;
Darin Petkov9b230572010-10-08 10:20:09 -0700759 SetupDownload();
Chris Sosa4f8ee272012-11-30 13:01:54 -0800760 SetupCpuSharesManagement();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800761 SetStatusAndNotify(UPDATE_STATUS_UPDATE_AVAILABLE,
762 kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700763 } else if (type == DownloadAction::StaticType()) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800764 SetStatusAndNotify(UPDATE_STATUS_FINALIZING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700765 }
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700766}
767
768// Stop updating. An attempt will be made to record status to the disk
769// so that updates can be resumed later.
770void UpdateAttempter::Terminate() {
771 // TODO(adlr): implement this method.
772 NOTIMPLEMENTED();
773}
774
775// Try to resume from a previously Terminate()d update.
776void UpdateAttempter::ResumeUpdating() {
777 // TODO(adlr): implement this method.
778 NOTIMPLEMENTED();
779}
780
Darin Petkov9d911fa2010-08-19 09:36:08 -0700781void UpdateAttempter::SetDownloadStatus(bool active) {
782 download_active_ = active;
783 LOG(INFO) << "Download status: " << (active ? "active" : "inactive");
784}
785
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700786void UpdateAttempter::BytesReceived(uint64_t bytes_received, uint64_t total) {
Darin Petkov9d911fa2010-08-19 09:36:08 -0700787 if (!download_active_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700788 LOG(ERROR) << "BytesReceived called while not downloading.";
789 return;
790 }
Darin Petkovaf183052010-08-23 12:07:13 -0700791 double progress = static_cast<double>(bytes_received) /
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700792 static_cast<double>(total);
Darin Petkovaf183052010-08-23 12:07:13 -0700793 // Self throttle based on progress. Also send notifications if
794 // progress is too slow.
795 const double kDeltaPercent = 0.01; // 1%
796 if (status_ != UPDATE_STATUS_DOWNLOADING ||
797 bytes_received == total ||
798 progress - download_progress_ >= kDeltaPercent ||
799 TimeTicks::Now() - last_notify_time_ >= TimeDelta::FromSeconds(10)) {
800 download_progress_ = progress;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800801 SetStatusAndNotify(UPDATE_STATUS_DOWNLOADING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700802 }
803}
804
Jay Srinivasanc1ba09a2012-08-14 14:15:57 -0700805bool UpdateAttempter::ResetStatus() {
806 LOG(INFO) << "Attempting to reset state from "
807 << UpdateStatusToString(status_) << " to UPDATE_STATUS_IDLE";
808
809 switch (status_) {
810 case UPDATE_STATUS_IDLE:
811 // no-op.
812 return true;
813
814 case UPDATE_STATUS_UPDATED_NEED_REBOOT: {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700815 bool ret_value = true;
Jay Srinivasanc1ba09a2012-08-14 14:15:57 -0700816 status_ = UPDATE_STATUS_IDLE;
817 LOG(INFO) << "Reset Successful";
818
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700819 // Remove the reboot marker so that if the machine is rebooted
Jay Srinivasanc1ba09a2012-08-14 14:15:57 -0700820 // after resetting to idle state, it doesn't go back to
821 // UPDATE_STATUS_UPDATED_NEED_REBOOT state.
822 const FilePath kUpdateCompletedMarkerPath(kUpdateCompletedMarker);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700823 if (!file_util::Delete(kUpdateCompletedMarkerPath, false))
824 ret_value = false;
825
826 return ret_value;
Jay Srinivasanc1ba09a2012-08-14 14:15:57 -0700827 }
828
829 default:
830 LOG(ERROR) << "Reset not allowed in this state.";
831 return false;
832 }
833}
834
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700835bool UpdateAttempter::GetStatus(int64_t* last_checked_time,
836 double* progress,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800837 string* current_operation,
838 string* new_version,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700839 int64_t* new_payload_size) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700840 *last_checked_time = last_checked_time_;
841 *progress = download_progress_;
842 *current_operation = UpdateStatusToString(status_);
843 *new_version = new_version_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700844 *new_payload_size = new_payload_size_;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700845 return true;
846}
847
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700848void UpdateAttempter::UpdateBootFlags() {
Darin Petkov58dd1342011-05-06 12:05:13 -0700849 if (update_boot_flags_running_) {
850 LOG(INFO) << "Update boot flags running, nothing to do.";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700851 return;
852 }
Darin Petkov58dd1342011-05-06 12:05:13 -0700853 if (updated_boot_flags_) {
854 LOG(INFO) << "Already updated boot flags. Skipping.";
855 if (start_action_processor_) {
856 ScheduleProcessingStart();
857 }
858 return;
859 }
860 // This is purely best effort. Failures should be logged by Subprocess. Run
861 // the script asynchronously to avoid blocking the event loop regardless of
862 // the script runtime.
863 update_boot_flags_running_ = true;
864 LOG(INFO) << "Updating boot flags...";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700865 vector<string> cmd(1, "/usr/sbin/chromeos-setgoodkernel");
Darin Petkov58dd1342011-05-06 12:05:13 -0700866 if (!Subprocess::Get().Exec(cmd, StaticCompleteUpdateBootFlags, this)) {
867 CompleteUpdateBootFlags(1);
868 }
869}
870
871void UpdateAttempter::CompleteUpdateBootFlags(int return_code) {
872 update_boot_flags_running_ = false;
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700873 updated_boot_flags_ = true;
Darin Petkov58dd1342011-05-06 12:05:13 -0700874 if (start_action_processor_) {
875 ScheduleProcessingStart();
876 }
877}
878
879void UpdateAttempter::StaticCompleteUpdateBootFlags(
880 int return_code,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800881 const string& output,
Darin Petkov58dd1342011-05-06 12:05:13 -0700882 void* p) {
883 reinterpret_cast<UpdateAttempter*>(p)->CompleteUpdateBootFlags(return_code);
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700884}
885
Darin Petkov61635a92011-05-18 16:20:36 -0700886void UpdateAttempter::BroadcastStatus() {
887 if (!dbus_service_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700888 return;
Darin Petkov61635a92011-05-18 16:20:36 -0700889 }
Darin Petkovaf183052010-08-23 12:07:13 -0700890 last_notify_time_ = TimeTicks::Now();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700891 update_engine_service_emit_status_update(
892 dbus_service_,
893 last_checked_time_,
894 download_progress_,
895 UpdateStatusToString(status_),
896 new_version_.c_str(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700897 new_payload_size_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700898}
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700899
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800900uint32_t UpdateAttempter::GetErrorCodeFlags() {
901 uint32_t flags = 0;
902
903 if (!utils::IsNormalBootMode())
David Zeuthena99981f2013-04-29 13:42:47 -0700904 flags |= kErrorCodeDevModeFlag;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800905
906 if (response_handler_action_.get() &&
907 response_handler_action_->install_plan().is_resume)
David Zeuthena99981f2013-04-29 13:42:47 -0700908 flags |= kErrorCodeResumedFlag;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800909
910 if (!utils::IsOfficialBuild())
David Zeuthena99981f2013-04-29 13:42:47 -0700911 flags |= kErrorCodeTestImageFlag;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800912
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700913 if (omaha_request_params_->update_url() != kProductionOmahaUrl)
David Zeuthena99981f2013-04-29 13:42:47 -0700914 flags |= kErrorCodeTestOmahaUrlFlag;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800915
916 return flags;
917}
918
David Zeuthena99981f2013-04-29 13:42:47 -0700919bool UpdateAttempter::ShouldCancel(ErrorCode* cancel_reason) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700920 // Check if the channel we're attempting to update to is the same as the
921 // target channel currently chosen by the user.
922 OmahaRequestParams* params = system_state_->request_params();
923 if (params->download_channel() != params->target_channel()) {
924 LOG(ERROR) << "Aborting download as target channel: "
925 << params->target_channel()
926 << " is different from the download channel: "
927 << params->download_channel();
David Zeuthena99981f2013-04-29 13:42:47 -0700928 *cancel_reason = kErrorCodeUpdateCanceledByChannelChange;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700929 return true;
930 }
931
932 return false;
933}
934
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800935void UpdateAttempter::SetStatusAndNotify(UpdateStatus status,
936 UpdateNotice notice) {
Darin Petkov61635a92011-05-18 16:20:36 -0700937 status_ = status;
938 if (update_check_scheduler_) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800939 update_check_scheduler_->SetUpdateStatus(status_, notice);
Darin Petkov61635a92011-05-18 16:20:36 -0700940 }
941 BroadcastStatus();
942}
943
Darin Petkov777dbfa2010-07-20 15:03:37 -0700944void UpdateAttempter::CreatePendingErrorEvent(AbstractAction* action,
David Zeuthena99981f2013-04-29 13:42:47 -0700945 ErrorCode code) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700946 if (error_event_.get()) {
947 // This shouldn't really happen.
948 LOG(WARNING) << "There's already an existing pending error event.";
949 return;
950 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700951
Darin Petkovabc7bc02011-02-23 14:39:43 -0800952 // For now assume that a generic Omaha response action failure means that
953 // there's no update so don't send an event. Also, double check that the
954 // failure has not occurred while sending an error event -- in which case
955 // don't schedule another. This shouldn't really happen but just in case...
956 if ((action->Type() == OmahaResponseHandlerAction::StaticType() &&
David Zeuthena99981f2013-04-29 13:42:47 -0700957 code == kErrorCodeError) ||
Darin Petkov777dbfa2010-07-20 15:03:37 -0700958 status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
959 return;
960 }
961
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700962 // Classify the code to generate the appropriate result so that
963 // the Borgmon charts show up the results correctly.
964 // Do this before calling GetErrorCodeForAction which could potentially
965 // augment the bit representation of code and thus cause no matches for
966 // the switch cases below.
967 OmahaEvent::Result event_result;
968 switch (code) {
David Zeuthena99981f2013-04-29 13:42:47 -0700969 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
970 case kErrorCodeOmahaUpdateDeferredPerPolicy:
971 case kErrorCodeOmahaUpdateDeferredForBackoff:
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700972 event_result = OmahaEvent::kResultUpdateDeferred;
973 break;
974 default:
975 event_result = OmahaEvent::kResultError;
976 break;
977 }
978
Darin Petkov777dbfa2010-07-20 15:03:37 -0700979 code = GetErrorCodeForAction(action, code);
David Zeuthena99981f2013-04-29 13:42:47 -0700980 fake_update_success_ = code == kErrorCodePostinstallBootedFromFirmwareB;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700981
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800982 // Compute the final error code with all the bit flags to be sent to Omaha.
David Zeuthena99981f2013-04-29 13:42:47 -0700983 code = static_cast<ErrorCode>(code | GetErrorCodeFlags());
Darin Petkov09f96c32010-07-20 09:24:57 -0700984 error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700985 event_result,
Darin Petkov09f96c32010-07-20 09:24:57 -0700986 code));
987}
988
989bool UpdateAttempter::ScheduleErrorEventAction() {
990 if (error_event_.get() == NULL)
991 return false;
992
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800993 LOG(ERROR) << "Update failed.";
994 system_state_->payload_state()->UpdateFailed(error_event_->error_code);
995
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800996 // Send it to Uma.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800997 LOG(INFO) << "Reporting the error event";
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800998 utils::SendErrorCodeToUma(system_state_, error_event_->error_code);
999
1000 // Send it to Omaha.
Darin Petkov09f96c32010-07-20 09:24:57 -07001001 shared_ptr<OmahaRequestAction> error_event_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001002 new OmahaRequestAction(system_state_,
Darin Petkov09f96c32010-07-20 09:24:57 -07001003 error_event_.release(), // Pass ownership.
Jay Srinivasan08fce042012-06-07 16:31:01 -07001004 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -07001005 system_state_,
1006 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -07001007 false));
Darin Petkov09f96c32010-07-20 09:24:57 -07001008 actions_.push_back(shared_ptr<AbstractAction>(error_event_action));
Darin Petkovf42cc1c2010-09-01 09:03:02 -07001009 processor_->EnqueueAction(error_event_action.get());
Gilad Arnold1ebd8132012-03-05 10:19:29 -08001010 SetStatusAndNotify(UPDATE_STATUS_REPORTING_ERROR_EVENT,
1011 kUpdateNoticeUnspecified);
Darin Petkovf42cc1c2010-09-01 09:03:02 -07001012 processor_->StartProcessing();
Darin Petkov09f96c32010-07-20 09:24:57 -07001013 return true;
1014}
1015
Chris Sosa4f8ee272012-11-30 13:01:54 -08001016void UpdateAttempter::SetCpuShares(utils::CpuShares shares) {
1017 if (shares_ == shares) {
Darin Petkovc6c135c2010-08-11 13:36:18 -07001018 return;
1019 }
Chris Sosa4f8ee272012-11-30 13:01:54 -08001020 if (utils::SetCpuShares(shares)) {
1021 shares_ = shares;
1022 LOG(INFO) << "CPU shares = " << shares_;
Darin Petkovc6c135c2010-08-11 13:36:18 -07001023 }
1024}
1025
Chris Sosa4f8ee272012-11-30 13:01:54 -08001026void UpdateAttempter::SetupCpuSharesManagement() {
1027 if (manage_shares_source_) {
1028 LOG(ERROR) << "Cpu shares timeout source hasn't been destroyed.";
1029 CleanupCpuSharesManagement();
Darin Petkovc6c135c2010-08-11 13:36:18 -07001030 }
Chris Sosa4f8ee272012-11-30 13:01:54 -08001031 const int kCpuSharesTimeout = 2 * 60 * 60; // 2 hours
1032 manage_shares_source_ = g_timeout_source_new_seconds(kCpuSharesTimeout);
1033 g_source_set_callback(manage_shares_source_,
1034 StaticManageCpuSharesCallback,
Darin Petkovc6c135c2010-08-11 13:36:18 -07001035 this,
1036 NULL);
Chris Sosa4f8ee272012-11-30 13:01:54 -08001037 g_source_attach(manage_shares_source_, NULL);
1038 SetCpuShares(utils::kCpuSharesLow);
Darin Petkovc6c135c2010-08-11 13:36:18 -07001039}
1040
Chris Sosa4f8ee272012-11-30 13:01:54 -08001041void UpdateAttempter::CleanupCpuSharesManagement() {
1042 if (manage_shares_source_) {
1043 g_source_destroy(manage_shares_source_);
1044 manage_shares_source_ = NULL;
Darin Petkovc6c135c2010-08-11 13:36:18 -07001045 }
Chris Sosa4f8ee272012-11-30 13:01:54 -08001046 SetCpuShares(utils::kCpuSharesNormal);
Darin Petkovc6c135c2010-08-11 13:36:18 -07001047}
1048
Chris Sosa4f8ee272012-11-30 13:01:54 -08001049gboolean UpdateAttempter::StaticManageCpuSharesCallback(gpointer data) {
1050 return reinterpret_cast<UpdateAttempter*>(data)->ManageCpuSharesCallback();
Darin Petkovc6c135c2010-08-11 13:36:18 -07001051}
1052
Darin Petkove6ef2f82011-03-07 17:31:11 -08001053gboolean UpdateAttempter::StaticStartProcessing(gpointer data) {
1054 reinterpret_cast<UpdateAttempter*>(data)->processor_->StartProcessing();
1055 return FALSE; // Don't call this callback again.
1056}
1057
Darin Petkov58dd1342011-05-06 12:05:13 -07001058void UpdateAttempter::ScheduleProcessingStart() {
1059 LOG(INFO) << "Scheduling an action processor start.";
1060 start_action_processor_ = false;
1061 g_idle_add(&StaticStartProcessing, this);
1062}
1063
Chris Sosa4f8ee272012-11-30 13:01:54 -08001064bool UpdateAttempter::ManageCpuSharesCallback() {
1065 SetCpuShares(utils::kCpuSharesNormal);
1066 manage_shares_source_ = NULL;
Darin Petkovf622ef72010-10-26 13:49:24 -07001067 return false; // Destroy the timeout source.
Darin Petkovc6c135c2010-08-11 13:36:18 -07001068}
1069
Darin Petkov36275772010-10-01 11:40:57 -07001070void UpdateAttempter::DisableDeltaUpdateIfNeeded() {
1071 int64_t delta_failures;
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001072 if (omaha_request_params_->delta_okay() &&
Darin Petkov36275772010-10-01 11:40:57 -07001073 prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) &&
1074 delta_failures >= kMaxDeltaUpdateFailures) {
1075 LOG(WARNING) << "Too many delta update failures, forcing full update.";
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001076 omaha_request_params_->set_delta_okay(false);
Darin Petkov36275772010-10-01 11:40:57 -07001077 }
1078}
1079
1080void UpdateAttempter::MarkDeltaUpdateFailure() {
Darin Petkov2dd01092010-10-08 15:43:05 -07001081 // Don't try to resume a failed delta update.
1082 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Darin Petkov36275772010-10-01 11:40:57 -07001083 int64_t delta_failures;
1084 if (!prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) ||
1085 delta_failures < 0) {
1086 delta_failures = 0;
1087 }
1088 prefs_->SetInt64(kPrefsDeltaUpdateFailures, ++delta_failures);
1089}
1090
Darin Petkov9b230572010-10-08 10:20:09 -07001091void UpdateAttempter::SetupDownload() {
Gilad Arnold9bedeb52011-11-17 16:19:57 -08001092 MultiRangeHttpFetcher* fetcher =
1093 dynamic_cast<MultiRangeHttpFetcher*>(download_action_->http_fetcher());
Andrew de los Reyes819fef22010-12-17 11:33:58 -08001094 fetcher->ClearRanges();
Darin Petkov9b230572010-10-08 10:20:09 -07001095 if (response_handler_action_->install_plan().is_resume) {
Darin Petkovb21ce5d2010-10-21 16:03:05 -07001096 // Resuming an update so fetch the update manifest metadata first.
Darin Petkov9b230572010-10-08 10:20:09 -07001097 int64_t manifest_metadata_size = 0;
1098 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
Andrew de los Reyes819fef22010-12-17 11:33:58 -08001099 fetcher->AddRange(0, manifest_metadata_size);
Darin Petkovb21ce5d2010-10-21 16:03:05 -07001100 // If there're remaining unprocessed data blobs, fetch them. Be careful not
1101 // to request data beyond the end of the payload to avoid 416 HTTP response
1102 // error codes.
Darin Petkov9b230572010-10-08 10:20:09 -07001103 int64_t next_data_offset = 0;
1104 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -07001105 uint64_t resume_offset = manifest_metadata_size + next_data_offset;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001106 if (resume_offset < response_handler_action_->install_plan().payload_size) {
Gilad Arnolde4ad2502011-12-29 17:08:54 -08001107 fetcher->AddRange(resume_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -07001108 }
Darin Petkov9b230572010-10-08 10:20:09 -07001109 } else {
Gilad Arnolde4ad2502011-12-29 17:08:54 -08001110 fetcher->AddRange(0);
Darin Petkov9b230572010-10-08 10:20:09 -07001111 }
Darin Petkov9b230572010-10-08 10:20:09 -07001112}
1113
Thieu Le116fda32011-04-19 11:01:54 -07001114void UpdateAttempter::PingOmaha() {
Thieu Led88a8572011-05-26 09:09:19 -07001115 if (!processor_->IsRunning()) {
1116 shared_ptr<OmahaRequestAction> ping_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001117 new OmahaRequestAction(system_state_,
Thieu Led88a8572011-05-26 09:09:19 -07001118 NULL,
Jay Srinivasan08fce042012-06-07 16:31:01 -07001119 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -07001120 system_state_,
1121 is_test_mode_),
Thieu Led88a8572011-05-26 09:09:19 -07001122 true));
1123 actions_.push_back(shared_ptr<OmahaRequestAction>(ping_action));
1124 processor_->set_delegate(NULL);
1125 processor_->EnqueueAction(ping_action.get());
1126 // Call StartProcessing() synchronously here to avoid any race conditions
1127 // caused by multiple outstanding ping Omaha requests. If we call
1128 // StartProcessing() asynchronously, the device can be suspended before we
1129 // get a chance to callback to StartProcessing(). When the device resumes
1130 // (assuming the device sleeps longer than the next update check period),
1131 // StartProcessing() is called back and at the same time, the next update
1132 // check is fired which eventually invokes StartProcessing(). A crash
1133 // can occur because StartProcessing() checks to make sure that the
1134 // processor is idle which it isn't due to the two concurrent ping Omaha
1135 // requests.
1136 processor_->StartProcessing();
1137 } else {
Darin Petkov58dd1342011-05-06 12:05:13 -07001138 LOG(WARNING) << "Action processor running, Omaha ping suppressed.";
Darin Petkov58dd1342011-05-06 12:05:13 -07001139 }
Thieu Led88a8572011-05-26 09:09:19 -07001140
1141 // Update the status which will schedule the next update check
Gilad Arnold1ebd8132012-03-05 10:19:29 -08001142 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
1143 kUpdateNoticeUnspecified);
Thieu Le116fda32011-04-19 11:01:54 -07001144}
1145
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001146
1147bool UpdateAttempter::DecrementUpdateCheckCount() {
1148 int64 update_check_count_value;
1149
1150 if (!prefs_->Exists(kPrefsUpdateCheckCount)) {
1151 // This file does not exist. This means we haven't started our update
1152 // check count down yet, so nothing more to do. This file will be created
1153 // later when we first satisfy the wall-clock-based-wait period.
1154 LOG(INFO) << "No existing update check count. That's normal.";
1155 return true;
1156 }
1157
1158 if (prefs_->GetInt64(kPrefsUpdateCheckCount, &update_check_count_value)) {
1159 // Only if we're able to read a proper integer value, then go ahead
1160 // and decrement and write back the result in the same file, if needed.
1161 LOG(INFO) << "Update check count = " << update_check_count_value;
1162
1163 if (update_check_count_value == 0) {
1164 // It could be 0, if, for some reason, the file didn't get deleted
1165 // when we set our status to waiting for reboot. so we just leave it
1166 // as is so that we can prevent another update_check wait for this client.
1167 LOG(INFO) << "Not decrementing update check count as it's already 0.";
1168 return true;
1169 }
1170
1171 if (update_check_count_value > 0)
1172 update_check_count_value--;
1173 else
1174 update_check_count_value = 0;
1175
1176 // Write out the new value of update_check_count_value.
1177 if (prefs_->SetInt64(kPrefsUpdateCheckCount, update_check_count_value)) {
1178 // We successfully wrote out te new value, so enable the
1179 // update check based wait.
1180 LOG(INFO) << "New update check count = " << update_check_count_value;
1181 return true;
1182 }
1183 }
1184
1185 LOG(INFO) << "Deleting update check count state due to read/write errors.";
1186
1187 // We cannot read/write to the file, so disable the update check based wait
1188 // so that we don't get stuck in this OS version by any chance (which could
1189 // happen if there's some bug that causes to read/write incorrectly).
1190 // Also attempt to delete the file to do our best effort to cleanup.
1191 prefs_->Delete(kPrefsUpdateCheckCount);
1192 return false;
1193}
Chris Sosad317e402013-06-12 13:47:09 -07001194
David Zeuthene4c58bf2013-06-18 17:26:50 -07001195void UpdateAttempter::UpdateEngineStarted() {
1196 system_state_->payload_state()->UpdateEngineStarted();
1197}
1198
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07001199} // namespace chromeos_update_engine