blob: ca93a9a7a352e080bc1f895083fc0c132b233be0 [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
Jay Srinivasanc1ba09a2012-08-14 14:15:57 -070017#include <base/file_util.h>
Andrew de los Reyes45168102010-11-22 11:13:50 -080018#include <base/rand_util.h>
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070019#include <glib.h>
Darin Petkov1023a602010-08-30 13:47:51 -070020#include <metrics/metrics_library.h>
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +020021#include <policy/libpolicy.h>
22#include <policy/device_policy.h>
Darin Petkov9d65b7b2010-07-20 09:13:01 -070023
Bruno Rocha7f9aea22011-09-12 14:31:24 -070024#include "update_engine/certificate_checker.h"
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070025#include "update_engine/dbus_service.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070026#include "update_engine/download_action.h"
27#include "update_engine/filesystem_copier_action.h"
28#include "update_engine/libcurl_http_fetcher.h"
Andrew de los Reyes819fef22010-12-17 11:33:58 -080029#include "update_engine/multi_range_http_fetcher.h"
Darin Petkov6a5b3222010-07-13 14:55:28 -070030#include "update_engine/omaha_request_action.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070031#include "update_engine/omaha_request_params.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070032#include "update_engine/omaha_response_handler_action.h"
33#include "update_engine/postinstall_runner_action.h"
Darin Petkov36275772010-10-01 11:40:57 -070034#include "update_engine/prefs_interface.h"
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -070035#include "update_engine/subprocess.h"
Jay Srinivasan43488792012-06-19 00:25:31 -070036#include "update_engine/system_state.h"
Darin Petkov1023a602010-08-30 13:47:51 -070037#include "update_engine/update_check_scheduler.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070038
Darin Petkovaf183052010-08-23 12:07:13 -070039using base::TimeDelta;
40using base::TimeTicks;
Andrew de los Reyes21816e12011-04-07 14:18:56 -070041using google::protobuf::NewPermanentCallback;
Darin Petkov9b230572010-10-08 10:20:09 -070042using std::make_pair;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070043using std::tr1::shared_ptr;
Jay Srinivasan43488792012-06-19 00:25:31 -070044using std::set;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070045using std::string;
46using std::vector;
47
48namespace chromeos_update_engine {
49
Darin Petkov36275772010-10-01 11:40:57 -070050const int UpdateAttempter::kMaxDeltaUpdateFailures = 3;
51
Gilad Arnold1ebd8132012-03-05 10:19:29 -080052// Private test server URL w/ custom port number.
Gilad Arnolded747312012-03-15 18:20:41 -070053// TODO(garnold) This is a temporary hack to allow us to test the closed loop
54// automated update testing. To be replaced with an hard-coded local IP address.
55const char* const UpdateAttempter::kTestUpdateUrl(
56 "http://garnold.mtv.corp.google.com:8080/update");
Gilad Arnold28e2f392012-02-09 14:36:46 -080057
Darin Petkovcd1666f2010-09-23 09:53:44 -070058const char* kUpdateCompletedMarker =
59 "/var/run/update_engine_autoupdate_completed";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -070060
Andrew de los Reyes45168102010-11-22 11:13:50 -080061namespace {
62const int kMaxConsecutiveObeyProxyRequests = 20;
63} // namespace {}
64
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070065const char* UpdateStatusToString(UpdateStatus status) {
66 switch (status) {
67 case UPDATE_STATUS_IDLE:
68 return "UPDATE_STATUS_IDLE";
69 case UPDATE_STATUS_CHECKING_FOR_UPDATE:
70 return "UPDATE_STATUS_CHECKING_FOR_UPDATE";
71 case UPDATE_STATUS_UPDATE_AVAILABLE:
72 return "UPDATE_STATUS_UPDATE_AVAILABLE";
73 case UPDATE_STATUS_DOWNLOADING:
74 return "UPDATE_STATUS_DOWNLOADING";
75 case UPDATE_STATUS_VERIFYING:
76 return "UPDATE_STATUS_VERIFYING";
77 case UPDATE_STATUS_FINALIZING:
78 return "UPDATE_STATUS_FINALIZING";
79 case UPDATE_STATUS_UPDATED_NEED_REBOOT:
80 return "UPDATE_STATUS_UPDATED_NEED_REBOOT";
Darin Petkov09f96c32010-07-20 09:24:57 -070081 case UPDATE_STATUS_REPORTING_ERROR_EVENT:
82 return "UPDATE_STATUS_REPORTING_ERROR_EVENT";
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070083 default:
84 return "unknown status";
85 }
86}
87
Darin Petkov777dbfa2010-07-20 15:03:37 -070088// Turns a generic kActionCodeError to a generic error code specific
89// to |action| (e.g., kActionCodeFilesystemCopierError). If |code| is
90// not kActionCodeError, or the action is not matched, returns |code|
91// unchanged.
92ActionExitCode GetErrorCodeForAction(AbstractAction* action,
93 ActionExitCode code) {
94 if (code != kActionCodeError)
95 return code;
96
97 const string type = action->Type();
98 if (type == OmahaRequestAction::StaticType())
99 return kActionCodeOmahaRequestError;
100 if (type == OmahaResponseHandlerAction::StaticType())
101 return kActionCodeOmahaResponseHandlerError;
102 if (type == FilesystemCopierAction::StaticType())
103 return kActionCodeFilesystemCopierError;
104 if (type == PostinstallRunnerAction::StaticType())
105 return kActionCodePostinstallRunnerError;
Darin Petkov777dbfa2010-07-20 15:03:37 -0700106
107 return code;
108}
109
Darin Petkovc6c135c2010-08-11 13:36:18 -0700110UpdateAttempter::UpdateAttempter(PrefsInterface* prefs,
Andrew de los Reyes45168102010-11-22 11:13:50 -0800111 MetricsLibraryInterface* metrics_lib,
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700112 DbusGlibInterface* dbus_iface,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700113 GpioHandler* gpio_handler,
114 SystemState* system_state)
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700115 : processor_(new ActionProcessor()),
116 dbus_service_(NULL),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700117 prefs_(prefs),
118 metrics_lib_(metrics_lib),
Darin Petkov1023a602010-08-30 13:47:51 -0700119 update_check_scheduler_(NULL),
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700120 fake_update_success_(false),
Darin Petkov1023a602010-08-30 13:47:51 -0700121 http_response_code_(0),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700122 priority_(utils::kProcessPriorityNormal),
123 manage_priority_source_(NULL),
Darin Petkov9d911fa2010-08-19 09:36:08 -0700124 download_active_(false),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700125 status_(UPDATE_STATUS_IDLE),
126 download_progress_(0.0),
127 last_checked_time_(0),
128 new_version_("0.0.0.0"),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700129 new_payload_size_(0),
Andrew de los Reyes45168102010-11-22 11:13:50 -0800130 proxy_manual_checks_(0),
131 obeying_proxies_(true),
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700132 chrome_proxy_resolver_(dbus_iface),
Darin Petkov58dd1342011-05-06 12:05:13 -0700133 updated_boot_flags_(false),
134 update_boot_flags_running_(false),
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200135 start_action_processor_(false),
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800136 policy_provider_(NULL),
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700137 is_using_test_url_(false),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700138 is_test_mode_(false),
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700139 is_test_update_attempted_(false),
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700140 gpio_handler_(gpio_handler),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700141 system_state_(system_state) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700142 if (utils::FileExists(kUpdateCompletedMarker))
143 status_ = UPDATE_STATUS_UPDATED_NEED_REBOOT;
144}
145
146UpdateAttempter::~UpdateAttempter() {
147 CleanupPriorityManagement();
148}
149
Gilad Arnold28e2f392012-02-09 14:36:46 -0800150void UpdateAttempter::Update(const string& app_version,
151 const string& omaha_url,
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700152 bool obey_proxies,
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800153 bool interactive,
Gilad Arnold7c04e762012-05-23 10:54:02 -0700154 bool is_test_mode,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700155 bool is_user_initiated) {
Andrew de los Reyes000d8952011-03-02 15:21:14 -0800156 chrome_proxy_resolver_.Init();
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700157 fake_update_success_ = false;
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700158 if (status_ == UPDATE_STATUS_UPDATED_NEED_REBOOT) {
Thieu Le116fda32011-04-19 11:01:54 -0700159 // Although we have applied an update, we still want to ping Omaha
160 // to ensure the number of active statistics is accurate.
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700161 LOG(INFO) << "Not updating b/c we already updated and we're waiting for "
Thieu Le116fda32011-04-19 11:01:54 -0700162 << "reboot, we'll ping Omaha instead";
163 PingOmaha();
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700164 return;
165 }
166 if (status_ != UPDATE_STATUS_IDLE) {
167 // Update in progress. Do nothing
168 return;
169 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700170
171 if (!CalculateUpdateParams(app_version,
172 omaha_url,
173 obey_proxies,
174 interactive,
Gilad Arnold7c04e762012-05-23 10:54:02 -0700175 is_test_mode,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700176 is_user_initiated)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700177 return;
178 }
179
180 BuildUpdateActions(interactive);
181
182 SetStatusAndNotify(UPDATE_STATUS_CHECKING_FOR_UPDATE,
183 kUpdateNoticeUnspecified);
184
185 // Just in case we didn't update boot flags yet, make sure they're updated
186 // before any update processing starts.
187 start_action_processor_ = true;
188 UpdateBootFlags();
189}
190
191bool UpdateAttempter::CalculateUpdateParams(const string& app_version,
192 const string& omaha_url,
193 bool obey_proxies,
194 bool interactive,
Gilad Arnold7c04e762012-05-23 10:54:02 -0700195 bool is_test_mode,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700196 bool is_user_initiated) {
Darin Petkov1023a602010-08-30 13:47:51 -0700197 http_response_code_ = 0;
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200198
Gilad Arnold7c04e762012-05-23 10:54:02 -0700199 // Set the test mode flag for the current update attempt.
200 is_test_mode_ = is_test_mode;
201
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200202 // Lazy initialize the policy provider, or reload the latest policy data.
203 if (!policy_provider_.get()) {
204 policy_provider_.reset(new policy::PolicyProvider());
205 } else {
206 policy_provider_->Reload();
207 }
208
209 // If the release_track is specified by policy, that takes precedence.
210 string release_track;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700211
Jay Srinivasan0a708742012-03-20 11:26:12 -0700212 if (policy_provider_->device_policy_is_loaded()) {
213 const policy::DevicePolicy& device_policy =
214 policy_provider_->GetDevicePolicy();
215 device_policy.GetReleaseChannel(&release_track);
216 device_policy.GetUpdateDisabled(&omaha_request_params_.update_disabled);
217 device_policy.GetTargetVersionPrefix(
218 &omaha_request_params_.target_version_prefix);
Jay Srinivasan43488792012-06-19 00:25:31 -0700219
220 system_state_->SetDevicePolicy(&device_policy);
221
222 set<string> allowed_types;
223 string allowed_types_str;
224 if (device_policy.GetAllowedConnectionTypesForUpdate(&allowed_types)) {
225 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);
232 } else {
233 LOG(INFO) << "No device policies present.";
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700234 system_state_->SetDevicePolicy(NULL);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700235 }
236
Jay Srinivasan21be0752012-07-25 15:44:56 -0700237 CalculateScatteringParams(is_user_initiated);
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200238
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800239 // Determine whether an alternative test address should be used.
Gilad Arnold28e2f392012-02-09 14:36:46 -0800240 string omaha_url_to_use = omaha_url;
Gilad Arnold7c04e762012-05-23 10:54:02 -0700241 if ((is_using_test_url_ = (omaha_url_to_use.empty() && is_test_mode_))) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800242 omaha_url_to_use = kTestUpdateUrl;
243 LOG(INFO) << "using alternative server address: " << omaha_url_to_use;
Gilad Arnold28e2f392012-02-09 14:36:46 -0800244 }
245
Jay Srinivasan0a708742012-03-20 11:26:12 -0700246 if (!omaha_request_params_.Init(app_version,
247 omaha_url_to_use,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800248 release_track)) {
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700249 LOG(ERROR) << "Unable to initialize Omaha request device params.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700250 return false;
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700251 }
Darin Petkov3aefa862010-12-07 14:45:00 -0800252
Jay Srinivasan0a708742012-03-20 11:26:12 -0700253 LOG(INFO) << "update_disabled = "
254 << (omaha_request_params_.update_disabled ? "true" : "false")
255 << ", target_version_prefix = "
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700256 << omaha_request_params_.target_version_prefix
257 << ", scatter_factor_in_seconds = "
258 << utils::FormatSecs(scatter_factor_.InSeconds());
259
260 LOG(INFO) << "Wall Clock Based Wait Enabled = "
261 << omaha_request_params_.wall_clock_based_wait_enabled
262 << ", Update Check Count Wait Enabled = "
263 << omaha_request_params_.update_check_count_wait_enabled
Jay Srinivasan21be0752012-07-25 15:44:56 -0700264 << ", Waiting Period = " << utils::FormatSecs(
265 omaha_request_params_.waiting_period.InSeconds());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700266
Andrew de los Reyes45168102010-11-22 11:13:50 -0800267 obeying_proxies_ = true;
268 if (obey_proxies || proxy_manual_checks_ == 0) {
269 LOG(INFO) << "forced to obey proxies";
270 // If forced to obey proxies, every 20th request will not use proxies
271 proxy_manual_checks_++;
272 LOG(INFO) << "proxy manual checks: " << proxy_manual_checks_;
273 if (proxy_manual_checks_ >= kMaxConsecutiveObeyProxyRequests) {
274 proxy_manual_checks_ = 0;
275 obeying_proxies_ = false;
276 }
277 } else if (base::RandInt(0, 4) == 0) {
278 obeying_proxies_ = false;
279 }
280 LOG_IF(INFO, !obeying_proxies_) << "To help ensure updates work, this update "
281 "check we are ignoring the proxy settings and using "
282 "direct connections.";
283
Darin Petkov36275772010-10-01 11:40:57 -0700284 DisableDeltaUpdateIfNeeded();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700285 return true;
286}
287
Jay Srinivasan21be0752012-07-25 15:44:56 -0700288void UpdateAttempter::CalculateScatteringParams(bool is_user_initiated) {
289 // Take a copy of the old scatter value before we update it, as
290 // we need to update the waiting period if this value changes.
291 TimeDelta old_scatter_factor = scatter_factor_;
292 const policy::DevicePolicy* device_policy = system_state_->GetDevicePolicy();
293 if (device_policy) {
294 int64 new_scatter_factor_in_secs = 0;
295 device_policy->GetScatterFactorInSeconds(&new_scatter_factor_in_secs);
296 if (new_scatter_factor_in_secs < 0) // sanitize input, just in case.
297 new_scatter_factor_in_secs = 0;
298 scatter_factor_ = TimeDelta::FromSeconds(new_scatter_factor_in_secs);
299 }
300
301 bool is_scatter_enabled = false;
302 if (scatter_factor_.InSeconds() == 0) {
303 LOG(INFO) << "Scattering disabled since scatter factor is set to 0";
304 } else if (is_user_initiated) {
305 LOG(INFO) << "Scattering disabled as this update check is user-initiated";
306 } else if (!system_state_->IsOOBEComplete()) {
307 LOG(INFO) << "Scattering disabled since OOBE is not complete yet";
308 } else {
309 is_scatter_enabled = true;
310 LOG(INFO) << "Scattering is enabled";
311 }
312
313 if (is_scatter_enabled) {
314 // This means the scattering policy is turned on.
315 // Now check if we need to update the waiting period. The two cases
316 // in which we'd need to update the waiting period are:
317 // 1. First time in process or a scheduled check after a user-initiated one.
318 // (omaha_request_params_.waiting_period will be zero in this case).
319 // 2. Admin has changed the scattering policy value.
320 // (new scattering value will be different from old one in this case).
321 int64 wait_period_in_secs = 0;
322 if (omaha_request_params_.waiting_period.InSeconds() == 0) {
323 // First case. Check if we have a suitable value to set for
324 // the waiting period.
325 if (prefs_->GetInt64(kPrefsWallClockWaitPeriod, &wait_period_in_secs) &&
326 wait_period_in_secs > 0 &&
327 wait_period_in_secs <= scatter_factor_.InSeconds()) {
328 // This means:
329 // 1. There's a persisted value for the waiting period available.
330 // 2. And that persisted value is still valid.
331 // So, in this case, we should reuse the persisted value instead of
332 // generating a new random value to improve the chances of a good
333 // distribution for scattering.
334 omaha_request_params_.waiting_period =
335 TimeDelta::FromSeconds(wait_period_in_secs);
336 LOG(INFO) << "Using persisted wall-clock waiting period: " <<
337 utils::FormatSecs(omaha_request_params_.waiting_period.InSeconds());
338 }
339 else {
340 // This means there's no persisted value for the waiting period
341 // available or its value is invalid given the new scatter_factor value.
342 // So, we should go ahead and regenerate a new value for the
343 // waiting period.
344 LOG(INFO) << "Persisted value not present or not valid ("
345 << utils::FormatSecs(wait_period_in_secs)
346 << ") for wall-clock waiting period.";
347 GenerateNewWaitingPeriod();
348 }
349 } else if (scatter_factor_ != old_scatter_factor) {
350 // This means there's already a waiting period value, but we detected
351 // a change in the scattering policy value. So, we should regenerate the
352 // waiting period to make sure it's within the bounds of the new scatter
353 // factor value.
354 GenerateNewWaitingPeriod();
355 } else {
356 // Neither the first time scattering is enabled nor the scattering value
357 // changed. Nothing to do.
358 LOG(INFO) << "Keeping current wall-clock waiting period: " <<
359 utils::FormatSecs(omaha_request_params_.waiting_period.InSeconds());
360 }
361
362 // The invariant at this point is that omaha_request_params_.waiting_period
363 // is non-zero no matter which path we took above.
364 LOG_IF(ERROR, omaha_request_params_.waiting_period.InSeconds() == 0)
365 << "Waiting Period should NOT be zero at this point!!!";
366
367 // Since scattering is enabled, wall clock based wait will always be
368 // enabled.
369 omaha_request_params_.wall_clock_based_wait_enabled = true;
370
371 // If we don't have any issues in accessing the file system to update
372 // the update check count value, we'll turn that on as well.
373 bool decrement_succeeded = DecrementUpdateCheckCount();
374 omaha_request_params_.update_check_count_wait_enabled = decrement_succeeded;
375 } else {
376 // This means the scattering feature is turned off or disabled for
377 // this particular update check. Make sure to disable
378 // all the knobs and artifacts so that we don't invoke any scattering
379 // related code.
380 omaha_request_params_.wall_clock_based_wait_enabled = false;
381 omaha_request_params_.update_check_count_wait_enabled = false;
382 omaha_request_params_.waiting_period = TimeDelta::FromSeconds(0);
383 prefs_->Delete(kPrefsWallClockWaitPeriod);
384 prefs_->Delete(kPrefsUpdateCheckCount);
385 // Don't delete the UpdateFirstSeenAt file as we don't want manual checks
386 // that result in no-updates (e.g. due to server side throttling) to
387 // cause update starvation by having the client generate a new
388 // UpdateFirstSeenAt for each scheduled check that follows a manual check.
389 }
390}
391
392void UpdateAttempter::GenerateNewWaitingPeriod() {
393 omaha_request_params_.waiting_period = TimeDelta::FromSeconds(
394 base::RandInt(1, scatter_factor_.InSeconds()));
395
396 LOG(INFO) << "Generated new wall-clock waiting period: " << utils::FormatSecs(
397 omaha_request_params_.waiting_period.InSeconds());
398
399 // Do a best-effort to persist this in all cases. Even if the persistence
400 // fails, we'll still be able to scatter based on our in-memory value.
401 // The persistence only helps in ensuring a good overall distribution
402 // across multiple devices if they tend to reboot too often.
403 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
404 omaha_request_params_.waiting_period.InSeconds());
405}
406
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700407void UpdateAttempter::BuildUpdateActions(bool interactive) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700408 CHECK(!processor_->IsRunning());
409 processor_->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700410
411 // Actions:
Darin Petkova0929552010-11-29 14:19:06 -0800412 LibcurlHttpFetcher* update_check_fetcher =
Gilad Arnold7c04e762012-05-23 10:54:02 -0700413 new LibcurlHttpFetcher(GetProxyResolver(), system_state_, is_test_mode_);
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700414 // Try harder to connect to the network, esp when not interactive.
415 // See comment in libcurl_http_fetcher.cc.
416 update_check_fetcher->set_no_network_max_retries(interactive ? 1 : 3);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700417 update_check_fetcher->set_check_certificate(CertificateChecker::kUpdate);
Darin Petkov6a5b3222010-07-13 14:55:28 -0700418 shared_ptr<OmahaRequestAction> update_check_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700419 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700420 &omaha_request_params_,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700421 NULL,
Thieu Le116fda32011-04-19 11:01:54 -0700422 update_check_fetcher, // passes ownership
423 false));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700424 shared_ptr<OmahaResponseHandlerAction> response_handler_action(
Darin Petkov73058b42010-10-06 16:32:19 -0700425 new OmahaResponseHandlerAction(prefs_));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700426 shared_ptr<FilesystemCopierAction> filesystem_copier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700427 new FilesystemCopierAction(false, false));
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700428 shared_ptr<FilesystemCopierAction> kernel_filesystem_copier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700429 new FilesystemCopierAction(true, false));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700430 shared_ptr<OmahaRequestAction> download_started_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700431 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700432 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700433 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700434 OmahaEvent::kTypeUpdateDownloadStarted),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700435 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700436 system_state_,
437 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700438 false));
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700439 LibcurlHttpFetcher* download_fetcher =
Gilad Arnold7c04e762012-05-23 10:54:02 -0700440 new LibcurlHttpFetcher(GetProxyResolver(), system_state_, is_test_mode_);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700441 download_fetcher->set_check_certificate(CertificateChecker::kDownload);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700442 shared_ptr<DownloadAction> download_action(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700443 new DownloadAction(prefs_,
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800444 new MultiRangeHttpFetcher(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700445 download_fetcher))); // passes ownership
Darin Petkov8c2980e2010-07-16 15:16:49 -0700446 shared_ptr<OmahaRequestAction> download_finished_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700447 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700448 &omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700449 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700450 OmahaEvent::kTypeUpdateDownloadFinished),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700451 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700452 system_state_,
453 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700454 false));
Darin Petkov3aefa862010-12-07 14:45:00 -0800455 shared_ptr<FilesystemCopierAction> filesystem_verifier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700456 new FilesystemCopierAction(false, true));
Darin Petkov3aefa862010-12-07 14:45:00 -0800457 shared_ptr<FilesystemCopierAction> kernel_filesystem_verifier_action(
Gilad Arnold581c2ea2012-07-19 12:33:49 -0700458 new FilesystemCopierAction(true, true));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800459 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
460 new PostinstallRunnerAction);
Darin Petkov8c2980e2010-07-16 15:16:49 -0700461 shared_ptr<OmahaRequestAction> update_complete_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700462 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700463 &omaha_request_params_,
Darin Petkove17f86b2010-07-20 09:12:01 -0700464 new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700465 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700466 system_state_,
467 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700468 false));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700469
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700470 download_action->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700471 response_handler_action_ = response_handler_action;
Darin Petkov9b230572010-10-08 10:20:09 -0700472 download_action_ = download_action;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700473
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700474 actions_.push_back(shared_ptr<AbstractAction>(update_check_action));
475 actions_.push_back(shared_ptr<AbstractAction>(response_handler_action));
476 actions_.push_back(shared_ptr<AbstractAction>(filesystem_copier_action));
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700477 actions_.push_back(shared_ptr<AbstractAction>(
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700478 kernel_filesystem_copier_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700479 actions_.push_back(shared_ptr<AbstractAction>(download_started_action));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700480 actions_.push_back(shared_ptr<AbstractAction>(download_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700481 actions_.push_back(shared_ptr<AbstractAction>(download_finished_action));
Darin Petkov3aefa862010-12-07 14:45:00 -0800482 actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action));
483 actions_.push_back(shared_ptr<AbstractAction>(
484 kernel_filesystem_verifier_action));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800485 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700486 actions_.push_back(shared_ptr<AbstractAction>(update_complete_action));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700487
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700488 // Enqueue the actions
489 for (vector<shared_ptr<AbstractAction> >::iterator it = actions_.begin();
490 it != actions_.end(); ++it) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700491 processor_->EnqueueAction(it->get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700492 }
493
494 // Bond them together. We have to use the leaf-types when calling
495 // BondActions().
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700496 BondActions(update_check_action.get(),
497 response_handler_action.get());
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700498 BondActions(response_handler_action.get(),
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700499 filesystem_copier_action.get());
500 BondActions(filesystem_copier_action.get(),
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700501 kernel_filesystem_copier_action.get());
502 BondActions(kernel_filesystem_copier_action.get(),
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700503 download_action.get());
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700504 BondActions(download_action.get(),
Darin Petkov3aefa862010-12-07 14:45:00 -0800505 filesystem_verifier_action.get());
506 BondActions(filesystem_verifier_action.get(),
507 kernel_filesystem_verifier_action.get());
508 BondActions(kernel_filesystem_verifier_action.get(),
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800509 postinstall_runner_action.get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700510}
511
Gilad Arnold28e2f392012-02-09 14:36:46 -0800512void UpdateAttempter::CheckForUpdate(const string& app_version,
Jay Srinivasane73acab2012-07-10 14:34:03 -0700513 const string& omaha_url,
514 bool is_user_initiated) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700515 LOG(INFO) << "New update check requested";
516
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700517 if (status_ != UPDATE_STATUS_IDLE) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700518 LOG(INFO) << "Skipping update check because current status is "
519 << UpdateStatusToString(status_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700520 return;
521 }
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800522
523 // Read GPIO signals and determine whether this is an automated test scenario.
524 // For safety, we only allow a test update to be performed once; subsequent
525 // update requests will be carried out normally.
Gilad Arnold7c04e762012-05-23 10:54:02 -0700526 bool is_test_mode = (!is_test_update_attempted_ && gpio_handler_ &&
527 gpio_handler_->IsTestModeSignaled());
528 if (is_test_mode) {
529 LOG(WARNING) << "this is a test mode update attempt!";
Gilad Arnold4d740eb2012-05-15 08:48:13 -0700530 is_test_update_attempted_ = true;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800531 }
532
Jay Srinivasan08fce042012-06-07 16:31:01 -0700533 // Passing true for is_user_initiated to indicate that this
534 // is not a scheduled update check.
Gilad Arnold7c04e762012-05-23 10:54:02 -0700535 Update(app_version, omaha_url, true, true, is_test_mode, is_user_initiated);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700536}
537
Darin Petkov296889c2010-07-23 16:20:54 -0700538bool UpdateAttempter::RebootIfNeeded() {
539 if (status_ != UPDATE_STATUS_UPDATED_NEED_REBOOT) {
540 LOG(INFO) << "Reboot requested, but status is "
541 << UpdateStatusToString(status_) << ", so not rebooting.";
542 return false;
543 }
544 TEST_AND_RETURN_FALSE(utils::Reboot());
545 return true;
546}
547
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700548// Delegate methods:
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700549void UpdateAttempter::ProcessingDone(const ActionProcessor* processor,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700550 ActionExitCode code) {
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700551 CHECK(response_handler_action_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700552 LOG(INFO) << "Processing Done.";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700553 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700554
Darin Petkovc6c135c2010-08-11 13:36:18 -0700555 // Reset process priority back to normal.
556 CleanupPriorityManagement();
557
Darin Petkov09f96c32010-07-20 09:24:57 -0700558 if (status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
559 LOG(INFO) << "Error event sent.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800560
561 // Inform scheduler of new status; also specifically inform about a failed
562 // update attempt with a test address.
563 SetStatusAndNotify(UPDATE_STATUS_IDLE,
564 (is_using_test_url_ ? kUpdateNoticeTestAddrFailed :
565 kUpdateNoticeUnspecified));
566
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700567 if (!fake_update_success_) {
568 return;
569 }
570 LOG(INFO) << "Booted from FW B and tried to install new firmware, "
571 "so requesting reboot from user.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700572 }
573
Darin Petkovc1a8b422010-07-19 11:34:49 -0700574 if (code == kActionCodeSuccess) {
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700575 utils::WriteFile(kUpdateCompletedMarker, "", 0);
Darin Petkov36275772010-10-01 11:40:57 -0700576 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Darin Petkov95508da2011-01-05 12:42:29 -0800577 prefs_->SetString(kPrefsPreviousVersion, omaha_request_params_.app_version);
Darin Petkov9b230572010-10-08 10:20:09 -0700578 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700579
580 // Since we're done with scattering fully at this point, this is the
581 // safest point delete the state files, as we're sure that the status is
582 // set to reboot (which means no more updates will be applied until reboot)
583 // This deletion is required for correctness as we want the next update
584 // check to re-create a new random number for the update check count.
585 // Similarly, we also delete the wall-clock-wait period that was persisted
586 // so that we start with a new random value for the next update check
587 // after reboot so that the same device is not favored or punished in any
588 // way.
589 prefs_->Delete(kPrefsUpdateCheckCount);
590 prefs_->Delete(kPrefsWallClockWaitPeriod);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700591 prefs_->Delete(kPrefsUpdateFirstSeenAt);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700592
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800593 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
594 kUpdateNoticeUnspecified);
Darin Petkov9d65b7b2010-07-20 09:13:01 -0700595
596 // Report the time it took to update the system.
597 int64_t update_time = time(NULL) - last_checked_time_;
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700598 if (!fake_update_success_)
599 metrics_lib_->SendToUMA("Installer.UpdateTime",
600 static_cast<int>(update_time), // sample
601 1, // min = 1 second
602 20 * 60, // max = 20 minutes
603 50); // buckets
Darin Petkov09f96c32010-07-20 09:24:57 -0700604 return;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700605 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700606
Darin Petkov1023a602010-08-30 13:47:51 -0700607 if (ScheduleErrorEventAction()) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700608 return;
Darin Petkov1023a602010-08-30 13:47:51 -0700609 }
610 LOG(INFO) << "No update.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800611 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700612}
613
614void UpdateAttempter::ProcessingStopped(const ActionProcessor* processor) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700615 // Reset process priority back to normal.
616 CleanupPriorityManagement();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700617 download_progress_ = 0.0;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800618 SetStatusAndNotify(UPDATE_STATUS_IDLE, kUpdateNoticeUnspecified);
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700619 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700620 error_event_.reset(NULL);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700621}
622
623// Called whenever an action has finished processing, either successfully
624// or otherwise.
625void UpdateAttempter::ActionCompleted(ActionProcessor* processor,
626 AbstractAction* action,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700627 ActionExitCode code) {
Darin Petkov1023a602010-08-30 13:47:51 -0700628 // Reset download progress regardless of whether or not the download
629 // action succeeded. Also, get the response code from HTTP request
630 // actions (update download as well as the initial update check
631 // actions).
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700632 const string type = action->Type();
Darin Petkov1023a602010-08-30 13:47:51 -0700633 if (type == DownloadAction::StaticType()) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700634 download_progress_ = 0.0;
Darin Petkov1023a602010-08-30 13:47:51 -0700635 DownloadAction* download_action = dynamic_cast<DownloadAction*>(action);
636 http_response_code_ = download_action->GetHTTPResponseCode();
637 } else if (type == OmahaRequestAction::StaticType()) {
638 OmahaRequestAction* omaha_request_action =
639 dynamic_cast<OmahaRequestAction*>(action);
640 // If the request is not an event, then it's the update-check.
641 if (!omaha_request_action->IsEvent()) {
642 http_response_code_ = omaha_request_action->GetHTTPResponseCode();
Darin Petkov85ced132010-09-01 10:20:56 -0700643 // Forward the server-dictated poll interval to the update check
644 // scheduler, if any.
645 if (update_check_scheduler_) {
646 update_check_scheduler_->set_poll_interval(
647 omaha_request_action->GetOutputObject().poll_interval);
648 }
Darin Petkov1023a602010-08-30 13:47:51 -0700649 }
650 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700651 if (code != kActionCodeSuccess) {
Darin Petkov7ed561b2011-10-04 02:59:03 -0700652 // If the current state is at or past the download phase, count the failure
653 // in case a switch to full update becomes necessary. Ignore network
654 // transfer timeouts and failures.
Darin Petkov36275772010-10-01 11:40:57 -0700655 if (status_ >= UPDATE_STATUS_DOWNLOADING &&
Darin Petkov36275772010-10-01 11:40:57 -0700656 code != kActionCodeDownloadTransferError) {
657 MarkDeltaUpdateFailure();
658 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700659 // On failure, schedule an error event to be sent to Omaha.
660 CreatePendingErrorEvent(action, code);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700661 return;
Darin Petkov09f96c32010-07-20 09:24:57 -0700662 }
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700663 // Find out which action completed.
664 if (type == OmahaResponseHandlerAction::StaticType()) {
Darin Petkov9b230572010-10-08 10:20:09 -0700665 // Note that the status will be updated to DOWNLOADING when some bytes get
666 // actually downloaded from the server and the BytesReceived callback is
667 // invoked. This avoids notifying the user that a download has started in
668 // cases when the server and the client are unable to initiate the download.
669 CHECK(action == response_handler_action_.get());
670 const InstallPlan& plan = response_handler_action_->install_plan();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700671 last_checked_time_ = time(NULL);
672 // TODO(adlr): put version in InstallPlan
673 new_version_ = "0.0.0.0";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700674 new_payload_size_ = plan.payload_size;
Darin Petkov9b230572010-10-08 10:20:09 -0700675 SetupDownload();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700676 SetupPriorityManagement();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800677 SetStatusAndNotify(UPDATE_STATUS_UPDATE_AVAILABLE,
678 kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700679 } else if (type == DownloadAction::StaticType()) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800680 SetStatusAndNotify(UPDATE_STATUS_FINALIZING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700681 }
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700682}
683
684// Stop updating. An attempt will be made to record status to the disk
685// so that updates can be resumed later.
686void UpdateAttempter::Terminate() {
687 // TODO(adlr): implement this method.
688 NOTIMPLEMENTED();
689}
690
691// Try to resume from a previously Terminate()d update.
692void UpdateAttempter::ResumeUpdating() {
693 // TODO(adlr): implement this method.
694 NOTIMPLEMENTED();
695}
696
Darin Petkov9d911fa2010-08-19 09:36:08 -0700697void UpdateAttempter::SetDownloadStatus(bool active) {
698 download_active_ = active;
699 LOG(INFO) << "Download status: " << (active ? "active" : "inactive");
700}
701
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700702void UpdateAttempter::BytesReceived(uint64_t bytes_received, uint64_t total) {
Darin Petkov9d911fa2010-08-19 09:36:08 -0700703 if (!download_active_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700704 LOG(ERROR) << "BytesReceived called while not downloading.";
705 return;
706 }
Darin Petkovaf183052010-08-23 12:07:13 -0700707 double progress = static_cast<double>(bytes_received) /
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700708 static_cast<double>(total);
Darin Petkovaf183052010-08-23 12:07:13 -0700709 // Self throttle based on progress. Also send notifications if
710 // progress is too slow.
711 const double kDeltaPercent = 0.01; // 1%
712 if (status_ != UPDATE_STATUS_DOWNLOADING ||
713 bytes_received == total ||
714 progress - download_progress_ >= kDeltaPercent ||
715 TimeTicks::Now() - last_notify_time_ >= TimeDelta::FromSeconds(10)) {
716 download_progress_ = progress;
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800717 SetStatusAndNotify(UPDATE_STATUS_DOWNLOADING, kUpdateNoticeUnspecified);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700718 }
719}
720
Jay Srinivasanc1ba09a2012-08-14 14:15:57 -0700721bool UpdateAttempter::ResetStatus() {
722 LOG(INFO) << "Attempting to reset state from "
723 << UpdateStatusToString(status_) << " to UPDATE_STATUS_IDLE";
724
725 switch (status_) {
726 case UPDATE_STATUS_IDLE:
727 // no-op.
728 return true;
729
730 case UPDATE_STATUS_UPDATED_NEED_REBOOT: {
731 status_ = UPDATE_STATUS_IDLE;
732 LOG(INFO) << "Reset Successful";
733
734 // also remove the reboot marker so that if the machine is rebooted
735 // after resetting to idle state, it doesn't go back to
736 // UPDATE_STATUS_UPDATED_NEED_REBOOT state.
737 const FilePath kUpdateCompletedMarkerPath(kUpdateCompletedMarker);
738 return file_util::Delete(kUpdateCompletedMarkerPath, false);
739 }
740
741 default:
742 LOG(ERROR) << "Reset not allowed in this state.";
743 return false;
744 }
745}
746
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700747bool UpdateAttempter::GetStatus(int64_t* last_checked_time,
748 double* progress,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800749 string* current_operation,
750 string* new_version,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700751 int64_t* new_payload_size) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700752 *last_checked_time = last_checked_time_;
753 *progress = download_progress_;
754 *current_operation = UpdateStatusToString(status_);
755 *new_version = new_version_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700756 *new_payload_size = new_payload_size_;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700757 return true;
758}
759
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700760void UpdateAttempter::UpdateBootFlags() {
Darin Petkov58dd1342011-05-06 12:05:13 -0700761 if (update_boot_flags_running_) {
762 LOG(INFO) << "Update boot flags running, nothing to do.";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700763 return;
764 }
Darin Petkov58dd1342011-05-06 12:05:13 -0700765 if (updated_boot_flags_) {
766 LOG(INFO) << "Already updated boot flags. Skipping.";
767 if (start_action_processor_) {
768 ScheduleProcessingStart();
769 }
770 return;
771 }
772 // This is purely best effort. Failures should be logged by Subprocess. Run
773 // the script asynchronously to avoid blocking the event loop regardless of
774 // the script runtime.
775 update_boot_flags_running_ = true;
776 LOG(INFO) << "Updating boot flags...";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700777 vector<string> cmd(1, "/usr/sbin/chromeos-setgoodkernel");
Darin Petkov58dd1342011-05-06 12:05:13 -0700778 if (!Subprocess::Get().Exec(cmd, StaticCompleteUpdateBootFlags, this)) {
779 CompleteUpdateBootFlags(1);
780 }
781}
782
783void UpdateAttempter::CompleteUpdateBootFlags(int return_code) {
784 update_boot_flags_running_ = false;
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700785 updated_boot_flags_ = true;
Darin Petkov58dd1342011-05-06 12:05:13 -0700786 if (start_action_processor_) {
787 ScheduleProcessingStart();
788 }
789}
790
791void UpdateAttempter::StaticCompleteUpdateBootFlags(
792 int return_code,
Gilad Arnold28e2f392012-02-09 14:36:46 -0800793 const string& output,
Darin Petkov58dd1342011-05-06 12:05:13 -0700794 void* p) {
795 reinterpret_cast<UpdateAttempter*>(p)->CompleteUpdateBootFlags(return_code);
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700796}
797
Darin Petkov61635a92011-05-18 16:20:36 -0700798void UpdateAttempter::BroadcastStatus() {
799 if (!dbus_service_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700800 return;
Darin Petkov61635a92011-05-18 16:20:36 -0700801 }
Darin Petkovaf183052010-08-23 12:07:13 -0700802 last_notify_time_ = TimeTicks::Now();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700803 update_engine_service_emit_status_update(
804 dbus_service_,
805 last_checked_time_,
806 download_progress_,
807 UpdateStatusToString(status_),
808 new_version_.c_str(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700809 new_payload_size_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700810}
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700811
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800812void UpdateAttempter::SetStatusAndNotify(UpdateStatus status,
813 UpdateNotice notice) {
Darin Petkov61635a92011-05-18 16:20:36 -0700814 status_ = status;
815 if (update_check_scheduler_) {
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800816 update_check_scheduler_->SetUpdateStatus(status_, notice);
Darin Petkov61635a92011-05-18 16:20:36 -0700817 }
818 BroadcastStatus();
819}
820
Darin Petkov777dbfa2010-07-20 15:03:37 -0700821void UpdateAttempter::CreatePendingErrorEvent(AbstractAction* action,
822 ActionExitCode code) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700823 if (error_event_.get()) {
824 // This shouldn't really happen.
825 LOG(WARNING) << "There's already an existing pending error event.";
826 return;
827 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700828
Darin Petkovabc7bc02011-02-23 14:39:43 -0800829 // For now assume that a generic Omaha response action failure means that
830 // there's no update so don't send an event. Also, double check that the
831 // failure has not occurred while sending an error event -- in which case
832 // don't schedule another. This shouldn't really happen but just in case...
833 if ((action->Type() == OmahaResponseHandlerAction::StaticType() &&
834 code == kActionCodeError) ||
Darin Petkov777dbfa2010-07-20 15:03:37 -0700835 status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
836 return;
837 }
838
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700839 // Classify the code to generate the appropriate result so that
840 // the Borgmon charts show up the results correctly.
841 // Do this before calling GetErrorCodeForAction which could potentially
842 // augment the bit representation of code and thus cause no matches for
843 // the switch cases below.
844 OmahaEvent::Result event_result;
845 switch (code) {
846 case kActionCodeOmahaUpdateIgnoredPerPolicy:
847 case kActionCodeOmahaUpdateDeferredPerPolicy:
848 event_result = OmahaEvent::kResultUpdateDeferred;
849 break;
850 default:
851 event_result = OmahaEvent::kResultError;
852 break;
853 }
854
Darin Petkov777dbfa2010-07-20 15:03:37 -0700855 code = GetErrorCodeForAction(action, code);
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700856 fake_update_success_ = code == kActionCodePostinstallBootedFromFirmwareB;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700857
858 // Apply the bit modifiers to the error code.
859 if (!utils::IsNormalBootMode()) {
860 code = static_cast<ActionExitCode>(code | kActionCodeBootModeFlag);
861 }
862 if (response_handler_action_.get() &&
863 response_handler_action_->install_plan().is_resume) {
864 code = static_cast<ActionExitCode>(code | kActionCodeResumedFlag);
865 }
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700866
Darin Petkov09f96c32010-07-20 09:24:57 -0700867 error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700868 event_result,
Darin Petkov09f96c32010-07-20 09:24:57 -0700869 code));
870}
871
872bool UpdateAttempter::ScheduleErrorEventAction() {
873 if (error_event_.get() == NULL)
874 return false;
875
Darin Petkov1023a602010-08-30 13:47:51 -0700876 LOG(INFO) << "Update failed -- reporting the error event.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700877 shared_ptr<OmahaRequestAction> error_event_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700878 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700879 &omaha_request_params_,
Darin Petkov09f96c32010-07-20 09:24:57 -0700880 error_event_.release(), // Pass ownership.
Jay Srinivasan08fce042012-06-07 16:31:01 -0700881 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700882 system_state_,
883 is_test_mode_),
Thieu Le116fda32011-04-19 11:01:54 -0700884 false));
Darin Petkov09f96c32010-07-20 09:24:57 -0700885 actions_.push_back(shared_ptr<AbstractAction>(error_event_action));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700886 processor_->EnqueueAction(error_event_action.get());
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800887 SetStatusAndNotify(UPDATE_STATUS_REPORTING_ERROR_EVENT,
888 kUpdateNoticeUnspecified);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700889 processor_->StartProcessing();
Darin Petkov09f96c32010-07-20 09:24:57 -0700890 return true;
891}
892
Darin Petkovc6c135c2010-08-11 13:36:18 -0700893void UpdateAttempter::SetPriority(utils::ProcessPriority priority) {
894 if (priority_ == priority) {
895 return;
896 }
897 if (utils::SetProcessPriority(priority)) {
898 priority_ = priority;
899 LOG(INFO) << "Process priority = " << priority_;
900 }
901}
902
903void UpdateAttempter::SetupPriorityManagement() {
904 if (manage_priority_source_) {
905 LOG(ERROR) << "Process priority timeout source hasn't been destroyed.";
906 CleanupPriorityManagement();
907 }
Darin Petkovf622ef72010-10-26 13:49:24 -0700908 const int kPriorityTimeout = 2 * 60 * 60; // 2 hours
Darin Petkovc6c135c2010-08-11 13:36:18 -0700909 manage_priority_source_ = g_timeout_source_new_seconds(kPriorityTimeout);
910 g_source_set_callback(manage_priority_source_,
911 StaticManagePriorityCallback,
912 this,
913 NULL);
914 g_source_attach(manage_priority_source_, NULL);
915 SetPriority(utils::kProcessPriorityLow);
916}
917
918void UpdateAttempter::CleanupPriorityManagement() {
919 if (manage_priority_source_) {
920 g_source_destroy(manage_priority_source_);
921 manage_priority_source_ = NULL;
922 }
923 SetPriority(utils::kProcessPriorityNormal);
924}
925
926gboolean UpdateAttempter::StaticManagePriorityCallback(gpointer data) {
927 return reinterpret_cast<UpdateAttempter*>(data)->ManagePriorityCallback();
928}
929
Darin Petkove6ef2f82011-03-07 17:31:11 -0800930gboolean UpdateAttempter::StaticStartProcessing(gpointer data) {
931 reinterpret_cast<UpdateAttempter*>(data)->processor_->StartProcessing();
932 return FALSE; // Don't call this callback again.
933}
934
Darin Petkov58dd1342011-05-06 12:05:13 -0700935void UpdateAttempter::ScheduleProcessingStart() {
936 LOG(INFO) << "Scheduling an action processor start.";
937 start_action_processor_ = false;
938 g_idle_add(&StaticStartProcessing, this);
939}
940
Darin Petkovc6c135c2010-08-11 13:36:18 -0700941bool UpdateAttempter::ManagePriorityCallback() {
Darin Petkovf622ef72010-10-26 13:49:24 -0700942 SetPriority(utils::kProcessPriorityNormal);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700943 manage_priority_source_ = NULL;
Darin Petkovf622ef72010-10-26 13:49:24 -0700944 return false; // Destroy the timeout source.
Darin Petkovc6c135c2010-08-11 13:36:18 -0700945}
946
Darin Petkov36275772010-10-01 11:40:57 -0700947void UpdateAttempter::DisableDeltaUpdateIfNeeded() {
948 int64_t delta_failures;
949 if (omaha_request_params_.delta_okay &&
950 prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) &&
951 delta_failures >= kMaxDeltaUpdateFailures) {
952 LOG(WARNING) << "Too many delta update failures, forcing full update.";
953 omaha_request_params_.delta_okay = false;
954 }
955}
956
957void UpdateAttempter::MarkDeltaUpdateFailure() {
Darin Petkov2dd01092010-10-08 15:43:05 -0700958 // Don't try to resume a failed delta update.
959 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Darin Petkov36275772010-10-01 11:40:57 -0700960 int64_t delta_failures;
961 if (!prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) ||
962 delta_failures < 0) {
963 delta_failures = 0;
964 }
965 prefs_->SetInt64(kPrefsDeltaUpdateFailures, ++delta_failures);
966}
967
Darin Petkov9b230572010-10-08 10:20:09 -0700968void UpdateAttempter::SetupDownload() {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800969 MultiRangeHttpFetcher* fetcher =
970 dynamic_cast<MultiRangeHttpFetcher*>(download_action_->http_fetcher());
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800971 fetcher->ClearRanges();
Darin Petkov9b230572010-10-08 10:20:09 -0700972 if (response_handler_action_->install_plan().is_resume) {
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700973 // Resuming an update so fetch the update manifest metadata first.
Darin Petkov9b230572010-10-08 10:20:09 -0700974 int64_t manifest_metadata_size = 0;
975 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800976 fetcher->AddRange(0, manifest_metadata_size);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700977 // If there're remaining unprocessed data blobs, fetch them. Be careful not
978 // to request data beyond the end of the payload to avoid 416 HTTP response
979 // error codes.
Darin Petkov9b230572010-10-08 10:20:09 -0700980 int64_t next_data_offset = 0;
981 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700982 uint64_t resume_offset = manifest_metadata_size + next_data_offset;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700983 if (resume_offset < response_handler_action_->install_plan().payload_size) {
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800984 fetcher->AddRange(resume_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700985 }
Darin Petkov9b230572010-10-08 10:20:09 -0700986 } else {
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800987 fetcher->AddRange(0);
Darin Petkov9b230572010-10-08 10:20:09 -0700988 }
Darin Petkov9b230572010-10-08 10:20:09 -0700989}
990
Thieu Le116fda32011-04-19 11:01:54 -0700991void UpdateAttempter::PingOmaha() {
Thieu Led88a8572011-05-26 09:09:19 -0700992 if (!processor_->IsRunning()) {
993 shared_ptr<OmahaRequestAction> ping_action(
994 new OmahaRequestAction(prefs_,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700995 &omaha_request_params_,
Thieu Led88a8572011-05-26 09:09:19 -0700996 NULL,
Jay Srinivasan08fce042012-06-07 16:31:01 -0700997 new LibcurlHttpFetcher(GetProxyResolver(),
Gilad Arnold7c04e762012-05-23 10:54:02 -0700998 system_state_,
999 is_test_mode_),
Thieu Led88a8572011-05-26 09:09:19 -07001000 true));
1001 actions_.push_back(shared_ptr<OmahaRequestAction>(ping_action));
1002 processor_->set_delegate(NULL);
1003 processor_->EnqueueAction(ping_action.get());
1004 // Call StartProcessing() synchronously here to avoid any race conditions
1005 // caused by multiple outstanding ping Omaha requests. If we call
1006 // StartProcessing() asynchronously, the device can be suspended before we
1007 // get a chance to callback to StartProcessing(). When the device resumes
1008 // (assuming the device sleeps longer than the next update check period),
1009 // StartProcessing() is called back and at the same time, the next update
1010 // check is fired which eventually invokes StartProcessing(). A crash
1011 // can occur because StartProcessing() checks to make sure that the
1012 // processor is idle which it isn't due to the two concurrent ping Omaha
1013 // requests.
1014 processor_->StartProcessing();
1015 } else {
Darin Petkov58dd1342011-05-06 12:05:13 -07001016 LOG(WARNING) << "Action processor running, Omaha ping suppressed.";
Darin Petkov58dd1342011-05-06 12:05:13 -07001017 }
Thieu Led88a8572011-05-26 09:09:19 -07001018
1019 // Update the status which will schedule the next update check
Gilad Arnold1ebd8132012-03-05 10:19:29 -08001020 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT,
1021 kUpdateNoticeUnspecified);
Thieu Le116fda32011-04-19 11:01:54 -07001022}
1023
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001024
1025bool UpdateAttempter::DecrementUpdateCheckCount() {
1026 int64 update_check_count_value;
1027
1028 if (!prefs_->Exists(kPrefsUpdateCheckCount)) {
1029 // This file does not exist. This means we haven't started our update
1030 // check count down yet, so nothing more to do. This file will be created
1031 // later when we first satisfy the wall-clock-based-wait period.
1032 LOG(INFO) << "No existing update check count. That's normal.";
1033 return true;
1034 }
1035
1036 if (prefs_->GetInt64(kPrefsUpdateCheckCount, &update_check_count_value)) {
1037 // Only if we're able to read a proper integer value, then go ahead
1038 // and decrement and write back the result in the same file, if needed.
1039 LOG(INFO) << "Update check count = " << update_check_count_value;
1040
1041 if (update_check_count_value == 0) {
1042 // It could be 0, if, for some reason, the file didn't get deleted
1043 // when we set our status to waiting for reboot. so we just leave it
1044 // as is so that we can prevent another update_check wait for this client.
1045 LOG(INFO) << "Not decrementing update check count as it's already 0.";
1046 return true;
1047 }
1048
1049 if (update_check_count_value > 0)
1050 update_check_count_value--;
1051 else
1052 update_check_count_value = 0;
1053
1054 // Write out the new value of update_check_count_value.
1055 if (prefs_->SetInt64(kPrefsUpdateCheckCount, update_check_count_value)) {
1056 // We successfully wrote out te new value, so enable the
1057 // update check based wait.
1058 LOG(INFO) << "New update check count = " << update_check_count_value;
1059 return true;
1060 }
1061 }
1062
1063 LOG(INFO) << "Deleting update check count state due to read/write errors.";
1064
1065 // We cannot read/write to the file, so disable the update check based wait
1066 // so that we don't get stuck in this OS version by any chance (which could
1067 // happen if there's some bug that causes to read/write incorrectly).
1068 // Also attempt to delete the file to do our best effort to cleanup.
1069 prefs_->Delete(kPrefsUpdateCheckCount);
1070 return false;
1071}
1072
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07001073} // namespace chromeos_update_engine