blob: 895380306663150232246712eafa51dc31e66575 [file] [log] [blame]
Darin Petkov58dd1342011-05-06 12:05:13 -07001// Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/update_attempter.h"
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07006
7// From 'man clock_gettime': feature test macro: _POSIX_C_SOURCE >= 199309L
8#ifndef _POSIX_C_SOURCE
9#define _POSIX_C_SOURCE 199309L
10#endif // _POSIX_C_SOURCE
11#include <time.h>
12
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070013#include <string>
Darin Petkov9b230572010-10-08 10:20:09 -070014#include <tr1/memory>
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070015#include <vector>
Darin Petkov9d65b7b2010-07-20 09:13:01 -070016
Andrew de los Reyes45168102010-11-22 11:13:50 -080017#include <base/rand_util.h>
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070018#include <glib.h>
Darin Petkov1023a602010-08-30 13:47:51 -070019#include <metrics/metrics_library.h>
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +020020#include <policy/libpolicy.h>
21#include <policy/device_policy.h>
Darin Petkov9d65b7b2010-07-20 09:13:01 -070022
Bruno Rocha7f9aea22011-09-12 14:31:24 -070023#include "update_engine/certificate_checker.h"
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070024#include "update_engine/dbus_service.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070025#include "update_engine/download_action.h"
26#include "update_engine/filesystem_copier_action.h"
27#include "update_engine/libcurl_http_fetcher.h"
Andrew de los Reyes819fef22010-12-17 11:33:58 -080028#include "update_engine/multi_range_http_fetcher.h"
Darin Petkov6a5b3222010-07-13 14:55:28 -070029#include "update_engine/omaha_request_action.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070030#include "update_engine/omaha_request_params.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070031#include "update_engine/omaha_response_handler_action.h"
32#include "update_engine/postinstall_runner_action.h"
Darin Petkov36275772010-10-01 11:40:57 -070033#include "update_engine/prefs_interface.h"
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -070034#include "update_engine/subprocess.h"
Darin Petkov1023a602010-08-30 13:47:51 -070035#include "update_engine/update_check_scheduler.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070036
Darin Petkovaf183052010-08-23 12:07:13 -070037using base::TimeDelta;
38using base::TimeTicks;
Andrew de los Reyes21816e12011-04-07 14:18:56 -070039using google::protobuf::NewPermanentCallback;
Darin Petkov9b230572010-10-08 10:20:09 -070040using std::make_pair;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070041using std::tr1::shared_ptr;
42using std::string;
43using std::vector;
44
45namespace chromeos_update_engine {
46
Darin Petkov36275772010-10-01 11:40:57 -070047const int UpdateAttempter::kMaxDeltaUpdateFailures = 3;
48
Darin Petkovcd1666f2010-09-23 09:53:44 -070049const char* kUpdateCompletedMarker =
50 "/var/run/update_engine_autoupdate_completed";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -070051
Andrew de los Reyes45168102010-11-22 11:13:50 -080052namespace {
53const int kMaxConsecutiveObeyProxyRequests = 20;
54} // namespace {}
55
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070056const char* UpdateStatusToString(UpdateStatus status) {
57 switch (status) {
58 case UPDATE_STATUS_IDLE:
59 return "UPDATE_STATUS_IDLE";
60 case UPDATE_STATUS_CHECKING_FOR_UPDATE:
61 return "UPDATE_STATUS_CHECKING_FOR_UPDATE";
62 case UPDATE_STATUS_UPDATE_AVAILABLE:
63 return "UPDATE_STATUS_UPDATE_AVAILABLE";
64 case UPDATE_STATUS_DOWNLOADING:
65 return "UPDATE_STATUS_DOWNLOADING";
66 case UPDATE_STATUS_VERIFYING:
67 return "UPDATE_STATUS_VERIFYING";
68 case UPDATE_STATUS_FINALIZING:
69 return "UPDATE_STATUS_FINALIZING";
70 case UPDATE_STATUS_UPDATED_NEED_REBOOT:
71 return "UPDATE_STATUS_UPDATED_NEED_REBOOT";
Darin Petkov09f96c32010-07-20 09:24:57 -070072 case UPDATE_STATUS_REPORTING_ERROR_EVENT:
73 return "UPDATE_STATUS_REPORTING_ERROR_EVENT";
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070074 default:
75 return "unknown status";
76 }
77}
78
Darin Petkov777dbfa2010-07-20 15:03:37 -070079// Turns a generic kActionCodeError to a generic error code specific
80// to |action| (e.g., kActionCodeFilesystemCopierError). If |code| is
81// not kActionCodeError, or the action is not matched, returns |code|
82// unchanged.
83ActionExitCode GetErrorCodeForAction(AbstractAction* action,
84 ActionExitCode code) {
85 if (code != kActionCodeError)
86 return code;
87
88 const string type = action->Type();
89 if (type == OmahaRequestAction::StaticType())
90 return kActionCodeOmahaRequestError;
91 if (type == OmahaResponseHandlerAction::StaticType())
92 return kActionCodeOmahaResponseHandlerError;
93 if (type == FilesystemCopierAction::StaticType())
94 return kActionCodeFilesystemCopierError;
95 if (type == PostinstallRunnerAction::StaticType())
96 return kActionCodePostinstallRunnerError;
Darin Petkov777dbfa2010-07-20 15:03:37 -070097
98 return code;
99}
100
Darin Petkovc6c135c2010-08-11 13:36:18 -0700101UpdateAttempter::UpdateAttempter(PrefsInterface* prefs,
Andrew de los Reyes45168102010-11-22 11:13:50 -0800102 MetricsLibraryInterface* metrics_lib,
103 DbusGlibInterface* dbus_iface)
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700104 : processor_(new ActionProcessor()),
105 dbus_service_(NULL),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700106 prefs_(prefs),
107 metrics_lib_(metrics_lib),
Darin Petkov1023a602010-08-30 13:47:51 -0700108 update_check_scheduler_(NULL),
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700109 fake_update_success_(false),
Darin Petkov1023a602010-08-30 13:47:51 -0700110 http_response_code_(0),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700111 priority_(utils::kProcessPriorityNormal),
112 manage_priority_source_(NULL),
Darin Petkov9d911fa2010-08-19 09:36:08 -0700113 download_active_(false),
Darin Petkovc6c135c2010-08-11 13:36:18 -0700114 status_(UPDATE_STATUS_IDLE),
115 download_progress_(0.0),
116 last_checked_time_(0),
117 new_version_("0.0.0.0"),
Darin Petkov36275772010-10-01 11:40:57 -0700118 new_size_(0),
Andrew de los Reyes45168102010-11-22 11:13:50 -0800119 is_full_update_(false),
120 proxy_manual_checks_(0),
121 obeying_proxies_(true),
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700122 chrome_proxy_resolver_(dbus_iface),
Darin Petkov58dd1342011-05-06 12:05:13 -0700123 updated_boot_flags_(false),
124 update_boot_flags_running_(false),
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200125 start_action_processor_(false),
126 policy_provider_(NULL) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700127 if (utils::FileExists(kUpdateCompletedMarker))
128 status_ = UPDATE_STATUS_UPDATED_NEED_REBOOT;
129}
130
131UpdateAttempter::~UpdateAttempter() {
132 CleanupPriorityManagement();
133}
134
Darin Petkov5a7f5652010-07-22 21:40:09 -0700135void UpdateAttempter::Update(const std::string& app_version,
Andrew de los Reyes45168102010-11-22 11:13:50 -0800136 const std::string& omaha_url,
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700137 bool obey_proxies,
138 bool interactive) {
Andrew de los Reyes000d8952011-03-02 15:21:14 -0800139 chrome_proxy_resolver_.Init();
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700140 fake_update_success_ = false;
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700141 if (status_ == UPDATE_STATUS_UPDATED_NEED_REBOOT) {
Thieu Le116fda32011-04-19 11:01:54 -0700142 // Although we have applied an update, we still want to ping Omaha
143 // to ensure the number of active statistics is accurate.
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700144 LOG(INFO) << "Not updating b/c we already updated and we're waiting for "
Thieu Le116fda32011-04-19 11:01:54 -0700145 << "reboot, we'll ping Omaha instead";
146 PingOmaha();
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700147 return;
148 }
149 if (status_ != UPDATE_STATUS_IDLE) {
150 // Update in progress. Do nothing
151 return;
152 }
Darin Petkov1023a602010-08-30 13:47:51 -0700153 http_response_code_ = 0;
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200154
155 // Lazy initialize the policy provider, or reload the latest policy data.
156 if (!policy_provider_.get()) {
157 policy_provider_.reset(new policy::PolicyProvider());
158 } else {
159 policy_provider_->Reload();
160 }
161
162 // If the release_track is specified by policy, that takes precedence.
163 string release_track;
164 if (policy_provider_->device_policy_is_loaded())
165 policy_provider_->GetDevicePolicy().GetReleaseChannel(&release_track);
166
167 if (!omaha_request_params_.Init(app_version, omaha_url, release_track)) {
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700168 LOG(ERROR) << "Unable to initialize Omaha request device params.";
169 return;
170 }
Darin Petkov3aefa862010-12-07 14:45:00 -0800171
Andrew de los Reyes45168102010-11-22 11:13:50 -0800172 obeying_proxies_ = true;
173 if (obey_proxies || proxy_manual_checks_ == 0) {
174 LOG(INFO) << "forced to obey proxies";
175 // If forced to obey proxies, every 20th request will not use proxies
176 proxy_manual_checks_++;
177 LOG(INFO) << "proxy manual checks: " << proxy_manual_checks_;
178 if (proxy_manual_checks_ >= kMaxConsecutiveObeyProxyRequests) {
179 proxy_manual_checks_ = 0;
180 obeying_proxies_ = false;
181 }
182 } else if (base::RandInt(0, 4) == 0) {
183 obeying_proxies_ = false;
184 }
185 LOG_IF(INFO, !obeying_proxies_) << "To help ensure updates work, this update "
186 "check we are ignoring the proxy settings and using "
187 "direct connections.";
188
Darin Petkov36275772010-10-01 11:40:57 -0700189 DisableDeltaUpdateIfNeeded();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700190 CHECK(!processor_->IsRunning());
191 processor_->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700192
193 // Actions:
Darin Petkova0929552010-11-29 14:19:06 -0800194 LibcurlHttpFetcher* update_check_fetcher =
195 new LibcurlHttpFetcher(GetProxyResolver());
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700196 // Try harder to connect to the network, esp when not interactive.
197 // See comment in libcurl_http_fetcher.cc.
198 update_check_fetcher->set_no_network_max_retries(interactive ? 1 : 3);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700199 update_check_fetcher->set_check_certificate(CertificateChecker::kUpdate);
Darin Petkov6a5b3222010-07-13 14:55:28 -0700200 shared_ptr<OmahaRequestAction> update_check_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700201 new OmahaRequestAction(prefs_,
202 omaha_request_params_,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700203 NULL,
Thieu Le116fda32011-04-19 11:01:54 -0700204 update_check_fetcher, // passes ownership
205 false));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700206 shared_ptr<OmahaResponseHandlerAction> response_handler_action(
Darin Petkov73058b42010-10-06 16:32:19 -0700207 new OmahaResponseHandlerAction(prefs_));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700208 shared_ptr<FilesystemCopierAction> filesystem_copier_action(
Darin Petkov3aefa862010-12-07 14:45:00 -0800209 new FilesystemCopierAction(false, false));
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700210 shared_ptr<FilesystemCopierAction> kernel_filesystem_copier_action(
Darin Petkov3aefa862010-12-07 14:45:00 -0800211 new FilesystemCopierAction(true, false));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700212 shared_ptr<OmahaRequestAction> download_started_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700213 new OmahaRequestAction(prefs_,
214 omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700215 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700216 OmahaEvent::kTypeUpdateDownloadStarted),
Thieu Le116fda32011-04-19 11:01:54 -0700217 new LibcurlHttpFetcher(GetProxyResolver()),
218 false));
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700219 LibcurlHttpFetcher* download_fetcher =
220 new LibcurlHttpFetcher(GetProxyResolver());
221 download_fetcher->set_check_certificate(CertificateChecker::kDownload);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700222 shared_ptr<DownloadAction> download_action(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700223 new DownloadAction(prefs_,
224 new MultiRangeHTTPFetcher(
225 download_fetcher))); // passes ownership
Darin Petkov8c2980e2010-07-16 15:16:49 -0700226 shared_ptr<OmahaRequestAction> download_finished_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700227 new OmahaRequestAction(prefs_,
228 omaha_request_params_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700229 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700230 OmahaEvent::kTypeUpdateDownloadFinished),
Thieu Le116fda32011-04-19 11:01:54 -0700231 new LibcurlHttpFetcher(GetProxyResolver()),
232 false));
Darin Petkov3aefa862010-12-07 14:45:00 -0800233 shared_ptr<FilesystemCopierAction> filesystem_verifier_action(
234 new FilesystemCopierAction(false, true));
235 shared_ptr<FilesystemCopierAction> kernel_filesystem_verifier_action(
236 new FilesystemCopierAction(true, true));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800237 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
238 new PostinstallRunnerAction);
Darin Petkov8c2980e2010-07-16 15:16:49 -0700239 shared_ptr<OmahaRequestAction> update_complete_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700240 new OmahaRequestAction(prefs_,
241 omaha_request_params_,
Darin Petkove17f86b2010-07-20 09:12:01 -0700242 new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
Thieu Le116fda32011-04-19 11:01:54 -0700243 new LibcurlHttpFetcher(GetProxyResolver()),
244 false));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700245
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700246 download_action->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700247 response_handler_action_ = response_handler_action;
Darin Petkov9b230572010-10-08 10:20:09 -0700248 download_action_ = download_action;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700249
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700250 actions_.push_back(shared_ptr<AbstractAction>(update_check_action));
251 actions_.push_back(shared_ptr<AbstractAction>(response_handler_action));
252 actions_.push_back(shared_ptr<AbstractAction>(filesystem_copier_action));
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700253 actions_.push_back(shared_ptr<AbstractAction>(
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700254 kernel_filesystem_copier_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700255 actions_.push_back(shared_ptr<AbstractAction>(download_started_action));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700256 actions_.push_back(shared_ptr<AbstractAction>(download_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700257 actions_.push_back(shared_ptr<AbstractAction>(download_finished_action));
Darin Petkov3aefa862010-12-07 14:45:00 -0800258 actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action));
259 actions_.push_back(shared_ptr<AbstractAction>(
260 kernel_filesystem_verifier_action));
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800261 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700262 actions_.push_back(shared_ptr<AbstractAction>(update_complete_action));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700263
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700264 // Enqueue the actions
265 for (vector<shared_ptr<AbstractAction> >::iterator it = actions_.begin();
266 it != actions_.end(); ++it) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700267 processor_->EnqueueAction(it->get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700268 }
269
270 // Bond them together. We have to use the leaf-types when calling
271 // BondActions().
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700272 BondActions(update_check_action.get(),
273 response_handler_action.get());
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700274 BondActions(response_handler_action.get(),
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700275 filesystem_copier_action.get());
276 BondActions(filesystem_copier_action.get(),
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700277 kernel_filesystem_copier_action.get());
278 BondActions(kernel_filesystem_copier_action.get(),
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700279 download_action.get());
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700280 BondActions(download_action.get(),
Darin Petkov3aefa862010-12-07 14:45:00 -0800281 filesystem_verifier_action.get());
282 BondActions(filesystem_verifier_action.get(),
283 kernel_filesystem_verifier_action.get());
284 BondActions(kernel_filesystem_verifier_action.get(),
Darin Petkov6d5dbf62010-11-08 16:09:55 -0800285 postinstall_runner_action.get());
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700286
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700287 SetStatusAndNotify(UPDATE_STATUS_CHECKING_FOR_UPDATE);
Darin Petkove6ef2f82011-03-07 17:31:11 -0800288
Darin Petkov58dd1342011-05-06 12:05:13 -0700289 // Just in case we didn't update boot flags yet, make sure they're updated
290 // before any update processing starts.
291 start_action_processor_ = true;
292 UpdateBootFlags();
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700293}
294
Darin Petkov5a7f5652010-07-22 21:40:09 -0700295void UpdateAttempter::CheckForUpdate(const std::string& app_version,
296 const std::string& omaha_url) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700297 if (status_ != UPDATE_STATUS_IDLE) {
298 LOG(INFO) << "Check for update requested, but status is "
299 << UpdateStatusToString(status_) << ", so not checking.";
300 return;
301 }
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700302 Update(app_version, omaha_url, true, true);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700303}
304
Darin Petkov296889c2010-07-23 16:20:54 -0700305bool UpdateAttempter::RebootIfNeeded() {
306 if (status_ != UPDATE_STATUS_UPDATED_NEED_REBOOT) {
307 LOG(INFO) << "Reboot requested, but status is "
308 << UpdateStatusToString(status_) << ", so not rebooting.";
309 return false;
310 }
311 TEST_AND_RETURN_FALSE(utils::Reboot());
312 return true;
313}
314
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700315// Delegate methods:
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700316void UpdateAttempter::ProcessingDone(const ActionProcessor* processor,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700317 ActionExitCode code) {
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700318 CHECK(response_handler_action_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700319 LOG(INFO) << "Processing Done.";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700320 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700321
Darin Petkovc6c135c2010-08-11 13:36:18 -0700322 // Reset process priority back to normal.
323 CleanupPriorityManagement();
324
Darin Petkov09f96c32010-07-20 09:24:57 -0700325 if (status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
326 LOG(INFO) << "Error event sent.";
327 SetStatusAndNotify(UPDATE_STATUS_IDLE);
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700328 if (!fake_update_success_) {
329 return;
330 }
331 LOG(INFO) << "Booted from FW B and tried to install new firmware, "
332 "so requesting reboot from user.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700333 }
334
Darin Petkovc1a8b422010-07-19 11:34:49 -0700335 if (code == kActionCodeSuccess) {
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700336 utils::WriteFile(kUpdateCompletedMarker, "", 0);
Darin Petkov36275772010-10-01 11:40:57 -0700337 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Darin Petkov95508da2011-01-05 12:42:29 -0800338 prefs_->SetString(kPrefsPreviousVersion, omaha_request_params_.app_version);
Darin Petkov9b230572010-10-08 10:20:09 -0700339 DeltaPerformer::ResetUpdateProgress(prefs_, false);
340 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT);
Darin Petkov9d65b7b2010-07-20 09:13:01 -0700341
342 // Report the time it took to update the system.
343 int64_t update_time = time(NULL) - last_checked_time_;
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700344 if (!fake_update_success_)
345 metrics_lib_->SendToUMA("Installer.UpdateTime",
346 static_cast<int>(update_time), // sample
347 1, // min = 1 second
348 20 * 60, // max = 20 minutes
349 50); // buckets
Darin Petkov09f96c32010-07-20 09:24:57 -0700350 return;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700351 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700352
Darin Petkov1023a602010-08-30 13:47:51 -0700353 if (ScheduleErrorEventAction()) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700354 return;
Darin Petkov1023a602010-08-30 13:47:51 -0700355 }
356 LOG(INFO) << "No update.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700357 SetStatusAndNotify(UPDATE_STATUS_IDLE);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700358}
359
360void UpdateAttempter::ProcessingStopped(const ActionProcessor* processor) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700361 // Reset process priority back to normal.
362 CleanupPriorityManagement();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700363 download_progress_ = 0.0;
364 SetStatusAndNotify(UPDATE_STATUS_IDLE);
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700365 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700366 error_event_.reset(NULL);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700367}
368
369// Called whenever an action has finished processing, either successfully
370// or otherwise.
371void UpdateAttempter::ActionCompleted(ActionProcessor* processor,
372 AbstractAction* action,
Darin Petkovc1a8b422010-07-19 11:34:49 -0700373 ActionExitCode code) {
Darin Petkov1023a602010-08-30 13:47:51 -0700374 // Reset download progress regardless of whether or not the download
375 // action succeeded. Also, get the response code from HTTP request
376 // actions (update download as well as the initial update check
377 // actions).
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700378 const string type = action->Type();
Darin Petkov1023a602010-08-30 13:47:51 -0700379 if (type == DownloadAction::StaticType()) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700380 download_progress_ = 0.0;
Darin Petkov1023a602010-08-30 13:47:51 -0700381 DownloadAction* download_action = dynamic_cast<DownloadAction*>(action);
382 http_response_code_ = download_action->GetHTTPResponseCode();
383 } else if (type == OmahaRequestAction::StaticType()) {
384 OmahaRequestAction* omaha_request_action =
385 dynamic_cast<OmahaRequestAction*>(action);
386 // If the request is not an event, then it's the update-check.
387 if (!omaha_request_action->IsEvent()) {
388 http_response_code_ = omaha_request_action->GetHTTPResponseCode();
Darin Petkov85ced132010-09-01 10:20:56 -0700389 // Forward the server-dictated poll interval to the update check
390 // scheduler, if any.
391 if (update_check_scheduler_) {
392 update_check_scheduler_->set_poll_interval(
393 omaha_request_action->GetOutputObject().poll_interval);
394 }
Darin Petkov1023a602010-08-30 13:47:51 -0700395 }
396 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700397 if (code != kActionCodeSuccess) {
Darin Petkov36275772010-10-01 11:40:57 -0700398 // If this was a delta update attempt and the current state is at or past
399 // the download phase, count the failure in case a switch to full update
400 // becomes necessary. Ignore network transfer timeouts and failures.
401 if (status_ >= UPDATE_STATUS_DOWNLOADING &&
402 !is_full_update_ &&
403 code != kActionCodeDownloadTransferError) {
404 MarkDeltaUpdateFailure();
405 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700406 // On failure, schedule an error event to be sent to Omaha.
407 CreatePendingErrorEvent(action, code);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700408 return;
Darin Petkov09f96c32010-07-20 09:24:57 -0700409 }
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700410 // Find out which action completed.
411 if (type == OmahaResponseHandlerAction::StaticType()) {
Darin Petkov9b230572010-10-08 10:20:09 -0700412 // Note that the status will be updated to DOWNLOADING when some bytes get
413 // actually downloaded from the server and the BytesReceived callback is
414 // invoked. This avoids notifying the user that a download has started in
415 // cases when the server and the client are unable to initiate the download.
416 CHECK(action == response_handler_action_.get());
417 const InstallPlan& plan = response_handler_action_->install_plan();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700418 last_checked_time_ = time(NULL);
419 // TODO(adlr): put version in InstallPlan
420 new_version_ = "0.0.0.0";
421 new_size_ = plan.size;
Darin Petkov36275772010-10-01 11:40:57 -0700422 is_full_update_ = plan.is_full_update;
Darin Petkov9b230572010-10-08 10:20:09 -0700423 SetupDownload();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700424 SetupPriorityManagement();
Darin Petkovb00bccc2010-10-26 14:13:08 -0700425 SetStatusAndNotify(UPDATE_STATUS_UPDATE_AVAILABLE);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700426 } else if (type == DownloadAction::StaticType()) {
427 SetStatusAndNotify(UPDATE_STATUS_FINALIZING);
428 }
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700429}
430
431// Stop updating. An attempt will be made to record status to the disk
432// so that updates can be resumed later.
433void UpdateAttempter::Terminate() {
434 // TODO(adlr): implement this method.
435 NOTIMPLEMENTED();
436}
437
438// Try to resume from a previously Terminate()d update.
439void UpdateAttempter::ResumeUpdating() {
440 // TODO(adlr): implement this method.
441 NOTIMPLEMENTED();
442}
443
Darin Petkov9d911fa2010-08-19 09:36:08 -0700444void UpdateAttempter::SetDownloadStatus(bool active) {
445 download_active_ = active;
446 LOG(INFO) << "Download status: " << (active ? "active" : "inactive");
447}
448
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700449void UpdateAttempter::BytesReceived(uint64_t bytes_received, uint64_t total) {
Darin Petkov9d911fa2010-08-19 09:36:08 -0700450 if (!download_active_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700451 LOG(ERROR) << "BytesReceived called while not downloading.";
452 return;
453 }
Darin Petkovaf183052010-08-23 12:07:13 -0700454 double progress = static_cast<double>(bytes_received) /
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700455 static_cast<double>(total);
Darin Petkovaf183052010-08-23 12:07:13 -0700456 // Self throttle based on progress. Also send notifications if
457 // progress is too slow.
458 const double kDeltaPercent = 0.01; // 1%
459 if (status_ != UPDATE_STATUS_DOWNLOADING ||
460 bytes_received == total ||
461 progress - download_progress_ >= kDeltaPercent ||
462 TimeTicks::Now() - last_notify_time_ >= TimeDelta::FromSeconds(10)) {
463 download_progress_ = progress;
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700464 SetStatusAndNotify(UPDATE_STATUS_DOWNLOADING);
465 }
466}
467
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700468bool UpdateAttempter::GetStatus(int64_t* last_checked_time,
469 double* progress,
470 std::string* current_operation,
471 std::string* new_version,
472 int64_t* new_size) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700473 *last_checked_time = last_checked_time_;
474 *progress = download_progress_;
475 *current_operation = UpdateStatusToString(status_);
476 *new_version = new_version_;
477 *new_size = new_size_;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700478 return true;
479}
480
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700481void UpdateAttempter::UpdateBootFlags() {
Darin Petkov58dd1342011-05-06 12:05:13 -0700482 if (update_boot_flags_running_) {
483 LOG(INFO) << "Update boot flags running, nothing to do.";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700484 return;
485 }
Darin Petkov58dd1342011-05-06 12:05:13 -0700486 if (updated_boot_flags_) {
487 LOG(INFO) << "Already updated boot flags. Skipping.";
488 if (start_action_processor_) {
489 ScheduleProcessingStart();
490 }
491 return;
492 }
493 // This is purely best effort. Failures should be logged by Subprocess. Run
494 // the script asynchronously to avoid blocking the event loop regardless of
495 // the script runtime.
496 update_boot_flags_running_ = true;
497 LOG(INFO) << "Updating boot flags...";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700498 vector<string> cmd(1, "/usr/sbin/chromeos-setgoodkernel");
Darin Petkov58dd1342011-05-06 12:05:13 -0700499 if (!Subprocess::Get().Exec(cmd, StaticCompleteUpdateBootFlags, this)) {
500 CompleteUpdateBootFlags(1);
501 }
502}
503
504void UpdateAttempter::CompleteUpdateBootFlags(int return_code) {
505 update_boot_flags_running_ = false;
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700506 updated_boot_flags_ = true;
Darin Petkov58dd1342011-05-06 12:05:13 -0700507 if (start_action_processor_) {
508 ScheduleProcessingStart();
509 }
510}
511
512void UpdateAttempter::StaticCompleteUpdateBootFlags(
513 int return_code,
514 const std::string& output,
515 void* p) {
516 reinterpret_cast<UpdateAttempter*>(p)->CompleteUpdateBootFlags(return_code);
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -0700517}
518
Darin Petkov61635a92011-05-18 16:20:36 -0700519void UpdateAttempter::BroadcastStatus() {
520 if (!dbus_service_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700521 return;
Darin Petkov61635a92011-05-18 16:20:36 -0700522 }
Darin Petkovaf183052010-08-23 12:07:13 -0700523 last_notify_time_ = TimeTicks::Now();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700524 update_engine_service_emit_status_update(
525 dbus_service_,
526 last_checked_time_,
527 download_progress_,
528 UpdateStatusToString(status_),
529 new_version_.c_str(),
530 new_size_);
531}
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700532
Darin Petkov61635a92011-05-18 16:20:36 -0700533void UpdateAttempter::SetStatusAndNotify(UpdateStatus status) {
534 status_ = status;
535 if (update_check_scheduler_) {
536 update_check_scheduler_->SetUpdateStatus(status_);
537 }
538 BroadcastStatus();
539}
540
Darin Petkov777dbfa2010-07-20 15:03:37 -0700541void UpdateAttempter::CreatePendingErrorEvent(AbstractAction* action,
542 ActionExitCode code) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700543 if (error_event_.get()) {
544 // This shouldn't really happen.
545 LOG(WARNING) << "There's already an existing pending error event.";
546 return;
547 }
Darin Petkov777dbfa2010-07-20 15:03:37 -0700548
Darin Petkovabc7bc02011-02-23 14:39:43 -0800549 // For now assume that a generic Omaha response action failure means that
550 // there's no update so don't send an event. Also, double check that the
551 // failure has not occurred while sending an error event -- in which case
552 // don't schedule another. This shouldn't really happen but just in case...
553 if ((action->Type() == OmahaResponseHandlerAction::StaticType() &&
554 code == kActionCodeError) ||
Darin Petkov777dbfa2010-07-20 15:03:37 -0700555 status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
556 return;
557 }
558
559 code = GetErrorCodeForAction(action, code);
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700560 fake_update_success_ = code == kActionCodePostinstallBootedFromFirmwareB;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700561
562 // Apply the bit modifiers to the error code.
563 if (!utils::IsNormalBootMode()) {
564 code = static_cast<ActionExitCode>(code | kActionCodeBootModeFlag);
565 }
566 if (response_handler_action_.get() &&
567 response_handler_action_->install_plan().is_resume) {
568 code = static_cast<ActionExitCode>(code | kActionCodeResumedFlag);
569 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700570 error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
571 OmahaEvent::kResultError,
572 code));
573}
574
575bool UpdateAttempter::ScheduleErrorEventAction() {
576 if (error_event_.get() == NULL)
577 return false;
578
Darin Petkov1023a602010-08-30 13:47:51 -0700579 LOG(INFO) << "Update failed -- reporting the error event.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700580 shared_ptr<OmahaRequestAction> error_event_action(
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700581 new OmahaRequestAction(prefs_,
582 omaha_request_params_,
Darin Petkov09f96c32010-07-20 09:24:57 -0700583 error_event_.release(), // Pass ownership.
Thieu Le116fda32011-04-19 11:01:54 -0700584 new LibcurlHttpFetcher(GetProxyResolver()),
585 false));
Darin Petkov09f96c32010-07-20 09:24:57 -0700586 actions_.push_back(shared_ptr<AbstractAction>(error_event_action));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700587 processor_->EnqueueAction(error_event_action.get());
Darin Petkov09f96c32010-07-20 09:24:57 -0700588 SetStatusAndNotify(UPDATE_STATUS_REPORTING_ERROR_EVENT);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700589 processor_->StartProcessing();
Darin Petkov09f96c32010-07-20 09:24:57 -0700590 return true;
591}
592
Darin Petkovc6c135c2010-08-11 13:36:18 -0700593void UpdateAttempter::SetPriority(utils::ProcessPriority priority) {
594 if (priority_ == priority) {
595 return;
596 }
597 if (utils::SetProcessPriority(priority)) {
598 priority_ = priority;
599 LOG(INFO) << "Process priority = " << priority_;
600 }
601}
602
603void UpdateAttempter::SetupPriorityManagement() {
604 if (manage_priority_source_) {
605 LOG(ERROR) << "Process priority timeout source hasn't been destroyed.";
606 CleanupPriorityManagement();
607 }
Darin Petkovf622ef72010-10-26 13:49:24 -0700608 const int kPriorityTimeout = 2 * 60 * 60; // 2 hours
Darin Petkovc6c135c2010-08-11 13:36:18 -0700609 manage_priority_source_ = g_timeout_source_new_seconds(kPriorityTimeout);
610 g_source_set_callback(manage_priority_source_,
611 StaticManagePriorityCallback,
612 this,
613 NULL);
614 g_source_attach(manage_priority_source_, NULL);
615 SetPriority(utils::kProcessPriorityLow);
616}
617
618void UpdateAttempter::CleanupPriorityManagement() {
619 if (manage_priority_source_) {
620 g_source_destroy(manage_priority_source_);
621 manage_priority_source_ = NULL;
622 }
623 SetPriority(utils::kProcessPriorityNormal);
624}
625
626gboolean UpdateAttempter::StaticManagePriorityCallback(gpointer data) {
627 return reinterpret_cast<UpdateAttempter*>(data)->ManagePriorityCallback();
628}
629
Darin Petkove6ef2f82011-03-07 17:31:11 -0800630gboolean UpdateAttempter::StaticStartProcessing(gpointer data) {
631 reinterpret_cast<UpdateAttempter*>(data)->processor_->StartProcessing();
632 return FALSE; // Don't call this callback again.
633}
634
Darin Petkov58dd1342011-05-06 12:05:13 -0700635void UpdateAttempter::ScheduleProcessingStart() {
636 LOG(INFO) << "Scheduling an action processor start.";
637 start_action_processor_ = false;
638 g_idle_add(&StaticStartProcessing, this);
639}
640
Darin Petkovc6c135c2010-08-11 13:36:18 -0700641bool UpdateAttempter::ManagePriorityCallback() {
Darin Petkovf622ef72010-10-26 13:49:24 -0700642 SetPriority(utils::kProcessPriorityNormal);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700643 manage_priority_source_ = NULL;
Darin Petkovf622ef72010-10-26 13:49:24 -0700644 return false; // Destroy the timeout source.
Darin Petkovc6c135c2010-08-11 13:36:18 -0700645}
646
Darin Petkov36275772010-10-01 11:40:57 -0700647void UpdateAttempter::DisableDeltaUpdateIfNeeded() {
648 int64_t delta_failures;
649 if (omaha_request_params_.delta_okay &&
650 prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) &&
651 delta_failures >= kMaxDeltaUpdateFailures) {
652 LOG(WARNING) << "Too many delta update failures, forcing full update.";
653 omaha_request_params_.delta_okay = false;
654 }
655}
656
657void UpdateAttempter::MarkDeltaUpdateFailure() {
658 CHECK(!is_full_update_);
Darin Petkov2dd01092010-10-08 15:43:05 -0700659 // Don't try to resume a failed delta update.
660 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Darin Petkov36275772010-10-01 11:40:57 -0700661 int64_t delta_failures;
662 if (!prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) ||
663 delta_failures < 0) {
664 delta_failures = 0;
665 }
666 prefs_->SetInt64(kPrefsDeltaUpdateFailures, ++delta_failures);
667}
668
Darin Petkov9b230572010-10-08 10:20:09 -0700669void UpdateAttempter::SetupDownload() {
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800670 MultiRangeHTTPFetcher* fetcher =
671 dynamic_cast<MultiRangeHTTPFetcher*>(download_action_->http_fetcher());
672 fetcher->ClearRanges();
Darin Petkov9b230572010-10-08 10:20:09 -0700673 if (response_handler_action_->install_plan().is_resume) {
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700674 // Resuming an update so fetch the update manifest metadata first.
Darin Petkov9b230572010-10-08 10:20:09 -0700675 int64_t manifest_metadata_size = 0;
676 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800677 fetcher->AddRange(0, manifest_metadata_size);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700678 // If there're remaining unprocessed data blobs, fetch them. Be careful not
679 // to request data beyond the end of the payload to avoid 416 HTTP response
680 // error codes.
Darin Petkov9b230572010-10-08 10:20:09 -0700681 int64_t next_data_offset = 0;
682 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700683 uint64_t resume_offset = manifest_metadata_size + next_data_offset;
684 if (resume_offset < response_handler_action_->install_plan().size) {
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800685 fetcher->AddRange(resume_offset, -1);
Darin Petkovb21ce5d2010-10-21 16:03:05 -0700686 }
Darin Petkov9b230572010-10-08 10:20:09 -0700687 } else {
Andrew de los Reyes819fef22010-12-17 11:33:58 -0800688 fetcher->AddRange(0, -1);
Darin Petkov9b230572010-10-08 10:20:09 -0700689 }
Darin Petkov9b230572010-10-08 10:20:09 -0700690}
691
Thieu Le116fda32011-04-19 11:01:54 -0700692void UpdateAttempter::PingOmaha() {
Thieu Led88a8572011-05-26 09:09:19 -0700693 if (!processor_->IsRunning()) {
694 shared_ptr<OmahaRequestAction> ping_action(
695 new OmahaRequestAction(prefs_,
696 omaha_request_params_,
697 NULL,
698 new LibcurlHttpFetcher(GetProxyResolver()),
699 true));
700 actions_.push_back(shared_ptr<OmahaRequestAction>(ping_action));
701 processor_->set_delegate(NULL);
702 processor_->EnqueueAction(ping_action.get());
703 // Call StartProcessing() synchronously here to avoid any race conditions
704 // caused by multiple outstanding ping Omaha requests. If we call
705 // StartProcessing() asynchronously, the device can be suspended before we
706 // get a chance to callback to StartProcessing(). When the device resumes
707 // (assuming the device sleeps longer than the next update check period),
708 // StartProcessing() is called back and at the same time, the next update
709 // check is fired which eventually invokes StartProcessing(). A crash
710 // can occur because StartProcessing() checks to make sure that the
711 // processor is idle which it isn't due to the two concurrent ping Omaha
712 // requests.
713 processor_->StartProcessing();
714 } else {
Darin Petkov58dd1342011-05-06 12:05:13 -0700715 LOG(WARNING) << "Action processor running, Omaha ping suppressed.";
Darin Petkov58dd1342011-05-06 12:05:13 -0700716 }
Thieu Led88a8572011-05-26 09:09:19 -0700717
718 // Update the status which will schedule the next update check
Thieu Le116fda32011-04-19 11:01:54 -0700719 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT);
720}
721
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700722} // namespace chromeos_update_engine