blob: c6f1588f7f3a62c7e81b1b219fd0b57c0eeeb63b [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
Ben Chan9abb7632014-08-07 00:10:53 -07007#include <stdint.h>
8
Alex Vakulenko59e253e2014-02-24 10:40:21 -08009#include <algorithm>
Alex Deymobc91a272014-05-20 16:45:33 -070010#include <memory>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070011#include <set>
Alex Deymobc91a272014-05-20 16:45:33 -070012#include <string>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070013#include <utility>
Alex Deymo44666f92014-07-22 20:29:24 -070014#include <vector>
Darin Petkov9d65b7b2010-07-20 09:13:01 -070015
Jay Srinivasanc1ba09a2012-08-14 14:15:57 -070016#include <base/file_util.h>
David Zeuthen3c55abd2013-10-14 12:48:03 -070017#include <base/logging.h>
Andrew de los Reyes45168102010-11-22 11:13:50 -080018#include <base/rand_util.h>
Daniel Erat65f1da02014-06-27 22:05:38 -070019#include <base/strings/string_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070020#include <base/strings/stringprintf.h>
Daniel Eratc1f07c32013-10-10 10:18:02 -070021#include <chromeos/dbus/service_constants.h>
David Zeuthen3c55abd2013-10-14 12:48:03 -070022
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070023#include <glib.h>
Darin Petkov1023a602010-08-30 13:47:51 -070024#include <metrics/metrics_library.h>
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +020025#include <policy/device_policy.h>
Alex Deymobc91a272014-05-20 16:45:33 -070026#include <policy/libpolicy.h>
Darin Petkov9d65b7b2010-07-20 09:13:01 -070027
Bruno Rocha7f9aea22011-09-12 14:31:24 -070028#include "update_engine/certificate_checker.h"
David Zeuthen985b1122013-10-09 12:13:15 -070029#include "update_engine/clock_interface.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070030#include "update_engine/constants.h"
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070031#include "update_engine/dbus_service.h"
Daniel Erat65f1da02014-06-27 22:05:38 -070032#include "update_engine/dbus_wrapper_interface.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070033#include "update_engine/download_action.h"
34#include "update_engine/filesystem_copier_action.h"
Alex Deymo44666f92014-07-22 20:29:24 -070035#include "update_engine/glib_utils.h"
Alex Deymo42432912013-07-12 20:21:15 -070036#include "update_engine/hardware_interface.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070037#include "update_engine/libcurl_http_fetcher.h"
David Zeuthen33bae492014-02-25 16:16:18 -080038#include "update_engine/metrics.h"
Andrew de los Reyes819fef22010-12-17 11:33:58 -080039#include "update_engine/multi_range_http_fetcher.h"
Darin Petkov6a5b3222010-07-13 14:55:28 -070040#include "update_engine/omaha_request_action.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070041#include "update_engine/omaha_request_params.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070042#include "update_engine/omaha_response_handler_action.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070043#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080044#include "update_engine/payload_state_interface.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070045#include "update_engine/postinstall_runner_action.h"
Darin Petkov36275772010-10-01 11:40:57 -070046#include "update_engine/prefs_interface.h"
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -070047#include "update_engine/subprocess.h"
Jay Srinivasan43488792012-06-19 00:25:31 -070048#include "update_engine/system_state.h"
Darin Petkov1023a602010-08-30 13:47:51 -070049#include "update_engine/update_check_scheduler.h"
J. Richard Barnette30842932013-10-28 15:04:23 -070050#include "update_engine/utils.h"
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070051
Alex Deymobc91a272014-05-20 16:45:33 -070052using base::StringPrintf;
David Zeuthen3c55abd2013-10-14 12:48:03 -070053using base::Time;
Darin Petkovaf183052010-08-23 12:07:13 -070054using base::TimeDelta;
55using base::TimeTicks;
Darin Petkov9b230572010-10-08 10:20:09 -070056using std::make_pair;
Jay Srinivasan43488792012-06-19 00:25:31 -070057using std::set;
Alex Deymobc91a272014-05-20 16:45:33 -070058using std::shared_ptr;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -070059using std::string;
60using std::vector;
61
62namespace chromeos_update_engine {
63
Darin Petkov36275772010-10-01 11:40:57 -070064const int UpdateAttempter::kMaxDeltaUpdateFailures = 3;
65
Andrew de los Reyes45168102010-11-22 11:13:50 -080066namespace {
67const int kMaxConsecutiveObeyProxyRequests = 20;
Gilad Arnold70e476e2013-07-30 16:01:13 -070068
69const char* kUpdateCompletedMarker =
70 "/var/run/update_engine_autoupdate_completed";
Alex Vakulenkod2779df2014-06-16 13:19:00 -070071} // namespace
Andrew de los Reyes45168102010-11-22 11:13:50 -080072
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070073const char* UpdateStatusToString(UpdateStatus status) {
74 switch (status) {
75 case UPDATE_STATUS_IDLE:
Daniel Eratc1f07c32013-10-10 10:18:02 -070076 return update_engine::kUpdateStatusIdle;
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070077 case UPDATE_STATUS_CHECKING_FOR_UPDATE:
Daniel Eratc1f07c32013-10-10 10:18:02 -070078 return update_engine::kUpdateStatusCheckingForUpdate;
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070079 case UPDATE_STATUS_UPDATE_AVAILABLE:
Daniel Eratc1f07c32013-10-10 10:18:02 -070080 return update_engine::kUpdateStatusUpdateAvailable;
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070081 case UPDATE_STATUS_DOWNLOADING:
Daniel Eratc1f07c32013-10-10 10:18:02 -070082 return update_engine::kUpdateStatusDownloading;
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070083 case UPDATE_STATUS_VERIFYING:
Daniel Eratc1f07c32013-10-10 10:18:02 -070084 return update_engine::kUpdateStatusVerifying;
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070085 case UPDATE_STATUS_FINALIZING:
Daniel Eratc1f07c32013-10-10 10:18:02 -070086 return update_engine::kUpdateStatusFinalizing;
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070087 case UPDATE_STATUS_UPDATED_NEED_REBOOT:
Daniel Eratc1f07c32013-10-10 10:18:02 -070088 return update_engine::kUpdateStatusUpdatedNeedReboot;
Darin Petkov09f96c32010-07-20 09:24:57 -070089 case UPDATE_STATUS_REPORTING_ERROR_EVENT:
Daniel Eratc1f07c32013-10-10 10:18:02 -070090 return update_engine::kUpdateStatusReportingErrorEvent;
Chris Sosad317e402013-06-12 13:47:09 -070091 case UPDATE_STATUS_ATTEMPTING_ROLLBACK:
Daniel Eratc1f07c32013-10-10 10:18:02 -070092 return update_engine::kUpdateStatusAttemptingRollback;
Andrew de los Reyes63b96d72010-05-10 13:08:54 -070093 default:
94 return "unknown status";
95 }
96}
97
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -070098// Turns a generic ErrorCode::kError to a generic error code specific
99// to |action| (e.g., ErrorCode::kFilesystemCopierError). If |code| is
100// not ErrorCode::kError, or the action is not matched, returns |code|
Darin Petkov777dbfa2010-07-20 15:03:37 -0700101// unchanged.
David Zeuthena99981f2013-04-29 13:42:47 -0700102ErrorCode GetErrorCodeForAction(AbstractAction* action,
103 ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700104 if (code != ErrorCode::kError)
Darin Petkov777dbfa2010-07-20 15:03:37 -0700105 return code;
106
107 const string type = action->Type();
108 if (type == OmahaRequestAction::StaticType())
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700109 return ErrorCode::kOmahaRequestError;
Darin Petkov777dbfa2010-07-20 15:03:37 -0700110 if (type == OmahaResponseHandlerAction::StaticType())
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700111 return ErrorCode::kOmahaResponseHandlerError;
Darin Petkov777dbfa2010-07-20 15:03:37 -0700112 if (type == FilesystemCopierAction::StaticType())
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700113 return ErrorCode::kFilesystemCopierError;
Darin Petkov777dbfa2010-07-20 15:03:37 -0700114 if (type == PostinstallRunnerAction::StaticType())
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700115 return ErrorCode::kPostinstallRunnerError;
Darin Petkov777dbfa2010-07-20 15:03:37 -0700116
117 return code;
118}
119
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800120UpdateAttempter::UpdateAttempter(SystemState* system_state,
Gilad Arnold1b9d6ae2014-03-03 13:46:07 -0800121 DBusWrapperInterface* dbus_iface)
Gilad Arnold1f847232014-04-07 12:07:49 -0700122 : UpdateAttempter(system_state, dbus_iface, kUpdateCompletedMarker) {}
Gilad Arnold70e476e2013-07-30 16:01:13 -0700123
124UpdateAttempter::UpdateAttempter(SystemState* system_state,
Gilad Arnold1b9d6ae2014-03-03 13:46:07 -0800125 DBusWrapperInterface* dbus_iface,
Gilad Arnold70e476e2013-07-30 16:01:13 -0700126 const std::string& update_completed_marker)
Gilad Arnold1f847232014-04-07 12:07:49 -0700127 : processor_(new ActionProcessor()),
128 system_state_(system_state),
Daniel Erat65f1da02014-06-27 22:05:38 -0700129 dbus_iface_(dbus_iface),
Gilad Arnold1f847232014-04-07 12:07:49 -0700130 chrome_proxy_resolver_(dbus_iface),
131 update_completed_marker_(update_completed_marker) {
Gilad Arnold70e476e2013-07-30 16:01:13 -0700132 if (!update_completed_marker_.empty() &&
Daniel Erat65f1da02014-06-27 22:05:38 -0700133 utils::FileExists(update_completed_marker_.c_str())) {
Darin Petkovc6c135c2010-08-11 13:36:18 -0700134 status_ = UPDATE_STATUS_UPDATED_NEED_REBOOT;
Daniel Erat65f1da02014-06-27 22:05:38 -0700135 } else {
Gilad Arnold70e476e2013-07-30 16:01:13 -0700136 status_ = UPDATE_STATUS_IDLE;
Daniel Erat65f1da02014-06-27 22:05:38 -0700137 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700138}
139
Gilad Arnold1f847232014-04-07 12:07:49 -0700140void UpdateAttempter::Init() {
141 // Pulling from the SystemState can only be done after construction, since
142 // this is an aggregate of various objects (such as the UpdateAttempter),
143 // which requires them all to be constructed prior to it being used.
144 prefs_ = system_state_->prefs();
145 omaha_request_params_ = system_state_->request_params();
146}
147
Darin Petkovc6c135c2010-08-11 13:36:18 -0700148UpdateAttempter::~UpdateAttempter() {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800149 CleanupCpuSharesManagement();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700150}
151
David Zeuthen985b1122013-10-09 12:13:15 -0700152bool UpdateAttempter::CheckAndReportDailyMetrics() {
153 int64_t stored_value;
154 base::Time now = system_state_->clock()->GetWallclockTime();
155 if (system_state_->prefs()->Exists(kPrefsDailyMetricsLastReportedAt) &&
156 system_state_->prefs()->GetInt64(kPrefsDailyMetricsLastReportedAt,
157 &stored_value)) {
158 base::Time last_reported_at = base::Time::FromInternalValue(stored_value);
159 base::TimeDelta time_reported_since = now - last_reported_at;
160 if (time_reported_since.InSeconds() < 0) {
161 LOG(WARNING) << "Last reported daily metrics "
162 << utils::FormatTimeDelta(time_reported_since) << " ago "
163 << "which is negative. Either the system clock is wrong or "
164 << "the kPrefsDailyMetricsLastReportedAt state variable "
165 << "is wrong.";
166 // In this case, report daily metrics to reset.
167 } else {
168 if (time_reported_since.InSeconds() < 24*60*60) {
169 LOG(INFO) << "Last reported daily metrics "
170 << utils::FormatTimeDelta(time_reported_since) << " ago.";
171 return false;
172 }
173 LOG(INFO) << "Last reported daily metrics "
174 << utils::FormatTimeDelta(time_reported_since) << " ago, "
175 << "which is more than 24 hours ago.";
176 }
177 }
178
179 LOG(INFO) << "Reporting daily metrics.";
180 system_state_->prefs()->SetInt64(kPrefsDailyMetricsLastReportedAt,
181 now.ToInternalValue());
182
183 ReportOSAge();
184
185 return true;
186}
187
188void UpdateAttempter::ReportOSAge() {
189 struct stat sb;
190
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700191 if (system_state_ == nullptr)
David Zeuthen985b1122013-10-09 12:13:15 -0700192 return;
193
194 if (stat("/etc/lsb-release", &sb) != 0) {
David Zeuthend9aca3b2014-08-21 13:11:21 -0400195 PLOG(ERROR) << "Error getting file status for /etc/lsb-release "
196 << "(Note: this may happen in some unit tests)";
David Zeuthen985b1122013-10-09 12:13:15 -0700197 return;
198 }
199
200 base::Time lsb_release_timestamp = utils::TimeFromStructTimespec(&sb.st_ctim);
201 base::Time now = system_state_->clock()->GetWallclockTime();
202 base::TimeDelta age = now - lsb_release_timestamp;
203 if (age.InSeconds() < 0) {
204 LOG(ERROR) << "The OS age (" << utils::FormatTimeDelta(age)
David Zeuthend9aca3b2014-08-21 13:11:21 -0400205 << ") is negative. Maybe the clock is wrong? "
206 << "(Note: this may happen in some unit tests.)";
David Zeuthen985b1122013-10-09 12:13:15 -0700207 return;
208 }
209
210 std::string metric = "Installer.OSAgeDays";
211 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(age)
212 << " for metric " << metric;
213 system_state_->metrics_lib()->SendToUMA(
214 metric,
215 static_cast<int>(age.InDays()),
216 0, // min: 0 days
217 6*30, // max: 6 months (approx)
218 kNumDefaultUmaBuckets);
David Zeuthen33bae492014-02-25 16:16:18 -0800219
220 metrics::ReportDailyMetrics(system_state_, age);
David Zeuthen985b1122013-10-09 12:13:15 -0700221}
222
Gilad Arnold28e2f392012-02-09 14:36:46 -0800223void UpdateAttempter::Update(const string& app_version,
224 const string& omaha_url,
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700225 bool obey_proxies,
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700226 bool interactive) {
David Zeuthen985b1122013-10-09 12:13:15 -0700227 // This is called at least every 4 hours (see the constant
228 // UpdateCheckScheduler::kTimeoutMaxBackoffInterval) so it's
229 // appropriate to use as a hook for reporting daily metrics.
230 CheckAndReportDailyMetrics();
231
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700232 // Notify of the new update attempt, clearing prior interactive requests.
233 if (interactive_update_pending_callback_.get())
234 interactive_update_pending_callback_->Run(false);
235
Andrew de los Reyes000d8952011-03-02 15:21:14 -0800236 chrome_proxy_resolver_.Init();
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700237 fake_update_success_ = false;
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700238 if (status_ == UPDATE_STATUS_UPDATED_NEED_REBOOT) {
Thieu Le116fda32011-04-19 11:01:54 -0700239 // Although we have applied an update, we still want to ping Omaha
240 // to ensure the number of active statistics is accurate.
David Zeuthen33bae492014-02-25 16:16:18 -0800241 //
242 // Also convey to the UpdateEngine.Check.Result metric that we're
243 // not performing an update check because of this.
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700244 LOG(INFO) << "Not updating b/c we already updated and we're waiting for "
Thieu Le116fda32011-04-19 11:01:54 -0700245 << "reboot, we'll ping Omaha instead";
David Zeuthen33bae492014-02-25 16:16:18 -0800246 metrics::ReportUpdateCheckMetrics(system_state_,
247 metrics::CheckResult::kRebootPending,
248 metrics::CheckReaction::kUnset,
249 metrics::DownloadErrorCode::kUnset);
Thieu Le116fda32011-04-19 11:01:54 -0700250 PingOmaha();
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700251 return;
252 }
253 if (status_ != UPDATE_STATUS_IDLE) {
254 // Update in progress. Do nothing
255 return;
256 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700257
258 if (!CalculateUpdateParams(app_version,
259 omaha_url,
260 obey_proxies,
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700261 interactive)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700262 return;
263 }
264
265 BuildUpdateActions(interactive);
266
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700267 SetStatusAndNotify(UPDATE_STATUS_CHECKING_FOR_UPDATE);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700268
269 // Just in case we didn't update boot flags yet, make sure they're updated
270 // before any update processing starts.
271 start_action_processor_ = true;
272 UpdateBootFlags();
273}
274
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700275void UpdateAttempter::RefreshDevicePolicy() {
276 // Lazy initialize the policy provider, or reload the latest policy data.
277 if (!policy_provider_.get())
278 policy_provider_.reset(new policy::PolicyProvider());
279 policy_provider_->Reload();
280
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700281 const policy::DevicePolicy* device_policy = nullptr;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700282 if (policy_provider_->device_policy_is_loaded())
283 device_policy = &policy_provider_->GetDevicePolicy();
284
285 if (device_policy)
286 LOG(INFO) << "Device policies/settings present";
287 else
288 LOG(INFO) << "No device policies/settings present.";
289
290 system_state_->set_device_policy(device_policy);
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700291 system_state_->p2p_manager()->SetDevicePolicy(device_policy);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700292}
293
David Zeuthen8f191b22013-08-06 12:27:50 -0700294void UpdateAttempter::CalculateP2PParams(bool interactive) {
295 bool use_p2p_for_downloading = false;
296 bool use_p2p_for_sharing = false;
297
298 // Never use p2p for downloading in interactive checks unless the
299 // developer has opted in for it via a marker file.
300 //
301 // (Why would a developer want to opt in? If he's working on the
302 // update_engine or p2p codebases so he can actually test his
303 // code.).
304
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700305 if (system_state_ != nullptr) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700306 if (!system_state_->p2p_manager()->IsP2PEnabled()) {
307 LOG(INFO) << "p2p is not enabled - disallowing p2p for both"
308 << " downloading and sharing.";
309 } else {
310 // Allow p2p for sharing, even in interactive checks.
311 use_p2p_for_sharing = true;
312 if (!interactive) {
313 LOG(INFO) << "Non-interactive check - allowing p2p for downloading";
314 use_p2p_for_downloading = true;
315 } else {
David Zeuthen052d2902013-09-06 11:41:30 -0700316 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
317 << "since this update attempt is interactive.";
David Zeuthen8f191b22013-08-06 12:27:50 -0700318 }
319 }
320 }
321
322 omaha_request_params_->set_use_p2p_for_downloading(use_p2p_for_downloading);
323 omaha_request_params_->set_use_p2p_for_sharing(use_p2p_for_sharing);
324}
325
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700326bool UpdateAttempter::CalculateUpdateParams(const string& app_version,
327 const string& omaha_url,
328 bool obey_proxies,
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700329 bool interactive) {
Darin Petkov1023a602010-08-30 13:47:51 -0700330 http_response_code_ = 0;
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200331
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700332 RefreshDevicePolicy();
333 const policy::DevicePolicy* device_policy = system_state_->device_policy();
334 if (device_policy) {
Jay Srinivasandc9a8ca2013-03-19 18:12:38 -0700335 bool update_disabled = false;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700336 if (device_policy->GetUpdateDisabled(&update_disabled))
337 omaha_request_params_->set_update_disabled(update_disabled);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700338
339 string target_version_prefix;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700340 if (device_policy->GetTargetVersionPrefix(&target_version_prefix))
341 omaha_request_params_->set_target_version_prefix(target_version_prefix);
Jay Srinivasan43488792012-06-19 00:25:31 -0700342
343 set<string> allowed_types;
344 string allowed_types_str;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700345 if (device_policy->GetAllowedConnectionTypesForUpdate(&allowed_types)) {
Jay Srinivasan43488792012-06-19 00:25:31 -0700346 set<string>::const_iterator iter;
347 for (iter = allowed_types.begin(); iter != allowed_types.end(); ++iter)
348 allowed_types_str += *iter + " ";
349 }
350
351 LOG(INFO) << "Networks over which updates are allowed per policy : "
352 << (allowed_types_str.empty() ? "all" : allowed_types_str);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700353 }
354
Gilad Arnoldb92f0df2013-01-10 16:32:45 -0800355 CalculateScatteringParams(interactive);
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200356
David Zeuthen8f191b22013-08-06 12:27:50 -0700357 CalculateP2PParams(interactive);
358 if (omaha_request_params_->use_p2p_for_downloading() ||
359 omaha_request_params_->use_p2p_for_sharing()) {
360 // OK, p2p is to be used - start it and perform housekeeping.
361 if (!StartP2PAndPerformHousekeeping()) {
362 // If this fails, disable p2p for this attempt
363 LOG(INFO) << "Forcibly disabling use of p2p since starting p2p or "
364 << "performing housekeeping failed.";
365 omaha_request_params_->set_use_p2p_for_downloading(false);
366 omaha_request_params_->set_use_p2p_for_sharing(false);
367 }
368 }
369
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700370 if (!omaha_request_params_->Init(app_version,
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700371 omaha_url,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700372 interactive)) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700373 LOG(ERROR) << "Unable to initialize Omaha request params.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700374 return false;
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700375 }
Darin Petkov3aefa862010-12-07 14:45:00 -0800376
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700377 // Set the target channel iff ReleaseChannelDelegated policy is set to
378 // false and a non-empty ReleaseChannel policy is present. If delegated
379 // is true, we'll ignore ReleaseChannel policy value.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700380 if (device_policy) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700381 bool delegated = false;
Chris Sosad6ab4042013-07-18 10:36:39 -0700382 if (!device_policy->GetReleaseChannelDelegated(&delegated) || delegated) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700383 LOG(INFO) << "Channel settings are delegated to user by policy. "
384 "Ignoring ReleaseChannel policy value";
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700385 } else {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700386 LOG(INFO) << "Channel settings are not delegated to the user by policy";
387 string target_channel;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700388 if (device_policy->GetReleaseChannel(&target_channel) &&
389 !target_channel.empty()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700390 // Pass in false for powerwash_allowed until we add it to the policy
391 // protobuf.
392 LOG(INFO) << "Setting target channel from ReleaseChannel policy value";
393 omaha_request_params_->SetTargetChannel(target_channel, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700394
395 // Since this is the beginning of a new attempt, update the download
396 // channel. The download channel won't be updated until the next
397 // attempt, even if target channel changes meanwhile, so that how we'll
398 // know if we should cancel the current download attempt if there's
399 // such a change in target channel.
400 omaha_request_params_->UpdateDownloadChannel();
401 } else {
402 LOG(INFO) << "No ReleaseChannel specified in policy";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700403 }
404 }
405 }
406
Jay Srinivasan0a708742012-03-20 11:26:12 -0700407 LOG(INFO) << "update_disabled = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700408 << utils::ToString(omaha_request_params_->update_disabled())
Jay Srinivasan0a708742012-03-20 11:26:12 -0700409 << ", target_version_prefix = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700410 << omaha_request_params_->target_version_prefix()
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700411 << ", scatter_factor_in_seconds = "
412 << utils::FormatSecs(scatter_factor_.InSeconds());
413
414 LOG(INFO) << "Wall Clock Based Wait Enabled = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700415 << omaha_request_params_->wall_clock_based_wait_enabled()
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700416 << ", Update Check Count Wait Enabled = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700417 << omaha_request_params_->update_check_count_wait_enabled()
Jay Srinivasan21be0752012-07-25 15:44:56 -0700418 << ", Waiting Period = " << utils::FormatSecs(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700419 omaha_request_params_->waiting_period().InSeconds());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700420
David Zeuthen8f191b22013-08-06 12:27:50 -0700421 LOG(INFO) << "Use p2p For Downloading = "
422 << omaha_request_params_->use_p2p_for_downloading()
423 << ", Use p2p For Sharing = "
424 << omaha_request_params_->use_p2p_for_sharing();
425
Andrew de los Reyes45168102010-11-22 11:13:50 -0800426 obeying_proxies_ = true;
427 if (obey_proxies || proxy_manual_checks_ == 0) {
428 LOG(INFO) << "forced to obey proxies";
429 // If forced to obey proxies, every 20th request will not use proxies
430 proxy_manual_checks_++;
431 LOG(INFO) << "proxy manual checks: " << proxy_manual_checks_;
432 if (proxy_manual_checks_ >= kMaxConsecutiveObeyProxyRequests) {
433 proxy_manual_checks_ = 0;
434 obeying_proxies_ = false;
435 }
436 } else if (base::RandInt(0, 4) == 0) {
437 obeying_proxies_ = false;
438 }
439 LOG_IF(INFO, !obeying_proxies_) << "To help ensure updates work, this update "
440 "check we are ignoring the proxy settings and using "
441 "direct connections.";
442
Darin Petkov36275772010-10-01 11:40:57 -0700443 DisableDeltaUpdateIfNeeded();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700444 return true;
445}
446
Gilad Arnoldb92f0df2013-01-10 16:32:45 -0800447void UpdateAttempter::CalculateScatteringParams(bool interactive) {
Jay Srinivasan21be0752012-07-25 15:44:56 -0700448 // Take a copy of the old scatter value before we update it, as
449 // we need to update the waiting period if this value changes.
450 TimeDelta old_scatter_factor = scatter_factor_;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800451 const policy::DevicePolicy* device_policy = system_state_->device_policy();
Jay Srinivasan21be0752012-07-25 15:44:56 -0700452 if (device_policy) {
Ben Chan9abb7632014-08-07 00:10:53 -0700453 int64_t new_scatter_factor_in_secs = 0;
Jay Srinivasan21be0752012-07-25 15:44:56 -0700454 device_policy->GetScatterFactorInSeconds(&new_scatter_factor_in_secs);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700455 if (new_scatter_factor_in_secs < 0) // sanitize input, just in case.
Jay Srinivasan21be0752012-07-25 15:44:56 -0700456 new_scatter_factor_in_secs = 0;
457 scatter_factor_ = TimeDelta::FromSeconds(new_scatter_factor_in_secs);
458 }
459
460 bool is_scatter_enabled = false;
461 if (scatter_factor_.InSeconds() == 0) {
462 LOG(INFO) << "Scattering disabled since scatter factor is set to 0";
Gilad Arnoldb92f0df2013-01-10 16:32:45 -0800463 } else if (interactive) {
464 LOG(INFO) << "Scattering disabled as this is an interactive update check";
Alex Deymobccbc382014-04-03 13:38:55 -0700465 } else if (!system_state_->hardware()->IsOOBEComplete(nullptr)) {
Jay Srinivasan21be0752012-07-25 15:44:56 -0700466 LOG(INFO) << "Scattering disabled since OOBE is not complete yet";
467 } else {
468 is_scatter_enabled = true;
469 LOG(INFO) << "Scattering is enabled";
470 }
471
472 if (is_scatter_enabled) {
473 // This means the scattering policy is turned on.
474 // Now check if we need to update the waiting period. The two cases
475 // in which we'd need to update the waiting period are:
476 // 1. First time in process or a scheduled check after a user-initiated one.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700477 // (omaha_request_params_->waiting_period will be zero in this case).
Jay Srinivasan21be0752012-07-25 15:44:56 -0700478 // 2. Admin has changed the scattering policy value.
479 // (new scattering value will be different from old one in this case).
Ben Chan9abb7632014-08-07 00:10:53 -0700480 int64_t wait_period_in_secs = 0;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700481 if (omaha_request_params_->waiting_period().InSeconds() == 0) {
Jay Srinivasan21be0752012-07-25 15:44:56 -0700482 // First case. Check if we have a suitable value to set for
483 // the waiting period.
484 if (prefs_->GetInt64(kPrefsWallClockWaitPeriod, &wait_period_in_secs) &&
485 wait_period_in_secs > 0 &&
486 wait_period_in_secs <= scatter_factor_.InSeconds()) {
487 // This means:
488 // 1. There's a persisted value for the waiting period available.
489 // 2. And that persisted value is still valid.
490 // So, in this case, we should reuse the persisted value instead of
491 // generating a new random value to improve the chances of a good
492 // distribution for scattering.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700493 omaha_request_params_->set_waiting_period(
494 TimeDelta::FromSeconds(wait_period_in_secs));
Jay Srinivasan21be0752012-07-25 15:44:56 -0700495 LOG(INFO) << "Using persisted wall-clock waiting period: " <<
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700496 utils::FormatSecs(
497 omaha_request_params_->waiting_period().InSeconds());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700498 } else {
Jay Srinivasan21be0752012-07-25 15:44:56 -0700499 // This means there's no persisted value for the waiting period
500 // available or its value is invalid given the new scatter_factor value.
501 // So, we should go ahead and regenerate a new value for the
502 // waiting period.
503 LOG(INFO) << "Persisted value not present or not valid ("
504 << utils::FormatSecs(wait_period_in_secs)
505 << ") for wall-clock waiting period.";
506 GenerateNewWaitingPeriod();
507 }
508 } else if (scatter_factor_ != old_scatter_factor) {
509 // This means there's already a waiting period value, but we detected
510 // a change in the scattering policy value. So, we should regenerate the
511 // waiting period to make sure it's within the bounds of the new scatter
512 // factor value.
513 GenerateNewWaitingPeriod();
514 } else {
515 // Neither the first time scattering is enabled nor the scattering value
516 // changed. Nothing to do.
517 LOG(INFO) << "Keeping current wall-clock waiting period: " <<
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700518 utils::FormatSecs(
519 omaha_request_params_->waiting_period().InSeconds());
Jay Srinivasan21be0752012-07-25 15:44:56 -0700520 }
521
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700522 // The invariant at this point is that omaha_request_params_->waiting_period
Jay Srinivasan21be0752012-07-25 15:44:56 -0700523 // is non-zero no matter which path we took above.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700524 LOG_IF(ERROR, omaha_request_params_->waiting_period().InSeconds() == 0)
Jay Srinivasan21be0752012-07-25 15:44:56 -0700525 << "Waiting Period should NOT be zero at this point!!!";
526
527 // Since scattering is enabled, wall clock based wait will always be
528 // enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700529 omaha_request_params_->set_wall_clock_based_wait_enabled(true);
Jay Srinivasan21be0752012-07-25 15:44:56 -0700530
531 // If we don't have any issues in accessing the file system to update
532 // the update check count value, we'll turn that on as well.
533 bool decrement_succeeded = DecrementUpdateCheckCount();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700534 omaha_request_params_->set_update_check_count_wait_enabled(
535 decrement_succeeded);
Jay Srinivasan21be0752012-07-25 15:44:56 -0700536 } else {
537 // This means the scattering feature is turned off or disabled for
538 // this particular update check. Make sure to disable
539 // all the knobs and artifacts so that we don't invoke any scattering
540 // related code.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700541 omaha_request_params_->set_wall_clock_based_wait_enabled(false);
542 omaha_request_params_->set_update_check_count_wait_enabled(false);
543 omaha_request_params_->set_waiting_period(TimeDelta::FromSeconds(0));
Jay Srinivasan21be0752012-07-25 15:44:56 -0700544 prefs_->Delete(kPrefsWallClockWaitPeriod);
545 prefs_->Delete(kPrefsUpdateCheckCount);
546 // Don't delete the UpdateFirstSeenAt file as we don't want manual checks
547 // that result in no-updates (e.g. due to server side throttling) to
548 // cause update starvation by having the client generate a new
549 // UpdateFirstSeenAt for each scheduled check that follows a manual check.
550 }
551}
552
553void UpdateAttempter::GenerateNewWaitingPeriod() {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700554 omaha_request_params_->set_waiting_period(TimeDelta::FromSeconds(
555 base::RandInt(1, scatter_factor_.InSeconds())));
Jay Srinivasan21be0752012-07-25 15:44:56 -0700556
557 LOG(INFO) << "Generated new wall-clock waiting period: " << utils::FormatSecs(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700558 omaha_request_params_->waiting_period().InSeconds());
Jay Srinivasan21be0752012-07-25 15:44:56 -0700559
560 // Do a best-effort to persist this in all cases. Even if the persistence
561 // fails, we'll still be able to scatter based on our in-memory value.
562 // The persistence only helps in ensuring a good overall distribution
563 // across multiple devices if they tend to reboot too often.
564 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700565 omaha_request_params_->waiting_period().InSeconds());
Jay Srinivasan21be0752012-07-25 15:44:56 -0700566}
567
Chris Sosad317e402013-06-12 13:47:09 -0700568void UpdateAttempter::BuildPostInstallActions(
569 InstallPlanAction* previous_action) {
570 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
571 new PostinstallRunnerAction());
572 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
573 BondActions(previous_action,
574 postinstall_runner_action.get());
575}
576
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700577void UpdateAttempter::BuildUpdateActions(bool interactive) {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700578 CHECK(!processor_->IsRunning());
579 processor_->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700580
581 // Actions:
Darin Petkova0929552010-11-29 14:19:06 -0800582 LibcurlHttpFetcher* update_check_fetcher =
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700583 new LibcurlHttpFetcher(GetProxyResolver(), system_state_);
Andrew de los Reyesfb2f4612011-06-09 18:21:49 -0700584 // Try harder to connect to the network, esp when not interactive.
585 // See comment in libcurl_http_fetcher.cc.
586 update_check_fetcher->set_no_network_max_retries(interactive ? 1 : 3);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700587 update_check_fetcher->set_check_certificate(CertificateChecker::kUpdate);
Darin Petkov6a5b3222010-07-13 14:55:28 -0700588 shared_ptr<OmahaRequestAction> update_check_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800589 new OmahaRequestAction(system_state_,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700590 nullptr,
Thieu Le116fda32011-04-19 11:01:54 -0700591 update_check_fetcher, // passes ownership
592 false));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700593 shared_ptr<OmahaResponseHandlerAction> response_handler_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800594 new OmahaResponseHandlerAction(system_state_));
Don Garrett83692e42013-11-08 10:11:30 -0800595 // We start with the kernel so it's marked as invalid more quickly.
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700596 shared_ptr<FilesystemCopierAction> kernel_filesystem_copier_action(
Alex Deymo42432912013-07-12 20:21:15 -0700597 new FilesystemCopierAction(system_state_, true, false));
Don Garrett83692e42013-11-08 10:11:30 -0800598 shared_ptr<FilesystemCopierAction> filesystem_copier_action(
599 new FilesystemCopierAction(system_state_, false, false));
600
Darin Petkov8c2980e2010-07-16 15:16:49 -0700601 shared_ptr<OmahaRequestAction> download_started_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800602 new OmahaRequestAction(system_state_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700603 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700604 OmahaEvent::kTypeUpdateDownloadStarted),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700605 new LibcurlHttpFetcher(GetProxyResolver(),
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700606 system_state_),
Thieu Le116fda32011-04-19 11:01:54 -0700607 false));
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700608 LibcurlHttpFetcher* download_fetcher =
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700609 new LibcurlHttpFetcher(GetProxyResolver(), system_state_);
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700610 download_fetcher->set_check_certificate(CertificateChecker::kDownload);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700611 shared_ptr<DownloadAction> download_action(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700612 new DownloadAction(prefs_,
Jay Srinivasanf0572052012-10-23 18:12:56 -0700613 system_state_,
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800614 new MultiRangeHttpFetcher(
Bruno Rocha7f9aea22011-09-12 14:31:24 -0700615 download_fetcher))); // passes ownership
Darin Petkov8c2980e2010-07-16 15:16:49 -0700616 shared_ptr<OmahaRequestAction> download_finished_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800617 new OmahaRequestAction(system_state_,
Darin Petkov8c2980e2010-07-16 15:16:49 -0700618 new OmahaEvent(
Darin Petkove17f86b2010-07-20 09:12:01 -0700619 OmahaEvent::kTypeUpdateDownloadFinished),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700620 new LibcurlHttpFetcher(GetProxyResolver(),
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700621 system_state_),
Thieu Le116fda32011-04-19 11:01:54 -0700622 false));
Darin Petkov3aefa862010-12-07 14:45:00 -0800623 shared_ptr<FilesystemCopierAction> filesystem_verifier_action(
Alex Deymo42432912013-07-12 20:21:15 -0700624 new FilesystemCopierAction(system_state_, false, true));
Darin Petkov3aefa862010-12-07 14:45:00 -0800625 shared_ptr<FilesystemCopierAction> kernel_filesystem_verifier_action(
Alex Deymo42432912013-07-12 20:21:15 -0700626 new FilesystemCopierAction(system_state_, true, true));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700627 shared_ptr<OmahaRequestAction> update_complete_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800628 new OmahaRequestAction(system_state_,
Darin Petkove17f86b2010-07-20 09:12:01 -0700629 new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
Jay Srinivasan08fce042012-06-07 16:31:01 -0700630 new LibcurlHttpFetcher(GetProxyResolver(),
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700631 system_state_),
Thieu Le116fda32011-04-19 11:01:54 -0700632 false));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700633
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700634 download_action->set_delegate(this);
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700635 response_handler_action_ = response_handler_action;
Darin Petkov9b230572010-10-08 10:20:09 -0700636 download_action_ = download_action;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700637
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700638 actions_.push_back(shared_ptr<AbstractAction>(update_check_action));
639 actions_.push_back(shared_ptr<AbstractAction>(response_handler_action));
640 actions_.push_back(shared_ptr<AbstractAction>(filesystem_copier_action));
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700641 actions_.push_back(shared_ptr<AbstractAction>(
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700642 kernel_filesystem_copier_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700643 actions_.push_back(shared_ptr<AbstractAction>(download_started_action));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700644 actions_.push_back(shared_ptr<AbstractAction>(download_action));
Darin Petkov8c2980e2010-07-16 15:16:49 -0700645 actions_.push_back(shared_ptr<AbstractAction>(download_finished_action));
Darin Petkov3aefa862010-12-07 14:45:00 -0800646 actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action));
Chris Sosad317e402013-06-12 13:47:09 -0700647 actions_.push_back(shared_ptr<AbstractAction>(
648 kernel_filesystem_verifier_action));
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700649
650 // Bond them together. We have to use the leaf-types when calling
651 // BondActions().
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700652 BondActions(update_check_action.get(),
653 response_handler_action.get());
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700654 BondActions(response_handler_action.get(),
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700655 filesystem_copier_action.get());
656 BondActions(filesystem_copier_action.get(),
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700657 kernel_filesystem_copier_action.get());
658 BondActions(kernel_filesystem_copier_action.get(),
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700659 download_action.get());
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700660 BondActions(download_action.get(),
Darin Petkov3aefa862010-12-07 14:45:00 -0800661 filesystem_verifier_action.get());
662 BondActions(filesystem_verifier_action.get(),
663 kernel_filesystem_verifier_action.get());
Chris Sosad317e402013-06-12 13:47:09 -0700664
665 BuildPostInstallActions(kernel_filesystem_verifier_action.get());
666
667 actions_.push_back(shared_ptr<AbstractAction>(update_complete_action));
668
669 // Enqueue the actions
670 for (vector<shared_ptr<AbstractAction> >::iterator it = actions_.begin();
671 it != actions_.end(); ++it) {
672 processor_->EnqueueAction(it->get());
673 }
674}
675
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700676bool UpdateAttempter::Rollback(bool powerwash) {
677 if (!CanRollback()) {
678 return false;
679 }
Chris Sosad317e402013-06-12 13:47:09 -0700680
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700681 // Extra check for enterprise-enrolled devices since they don't support
682 // powerwash.
683 if (powerwash) {
684 // Enterprise-enrolled devices have an empty owner in their device policy.
685 string owner;
686 RefreshDevicePolicy();
687 const policy::DevicePolicy* device_policy = system_state_->device_policy();
688 if (device_policy && (!device_policy->GetOwner(&owner) || owner.empty())) {
689 LOG(ERROR) << "Enterprise device detected. "
690 << "Cannot perform a powerwash for enterprise devices.";
691 return false;
692 }
693 }
694
695 processor_->set_delegate(this);
Chris Sosaaa18e162013-06-20 13:20:30 -0700696
Chris Sosa28e479c2013-07-12 11:39:53 -0700697 // Initialize the default request params.
698 if (!omaha_request_params_->Init("", "", true)) {
699 LOG(ERROR) << "Unable to initialize Omaha request params.";
700 return false;
701 }
702
Chris Sosad317e402013-06-12 13:47:09 -0700703 LOG(INFO) << "Setting rollback options.";
704 InstallPlan install_plan;
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700705
706 TEST_AND_RETURN_FALSE(utils::GetInstallDev(
707 system_state_->hardware()->BootDevice(),
708 &install_plan.install_path));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700709
Alex Deymo42432912013-07-12 20:21:15 -0700710 install_plan.kernel_install_path =
J. Richard Barnette30842932013-10-28 15:04:23 -0700711 utils::KernelDeviceOfBootDevice(install_plan.install_path);
Chris Sosad317e402013-06-12 13:47:09 -0700712 install_plan.powerwash_required = powerwash;
713
714 LOG(INFO) << "Using this install plan:";
715 install_plan.Dump();
716
717 shared_ptr<InstallPlanAction> install_plan_action(
718 new InstallPlanAction(install_plan));
719 actions_.push_back(shared_ptr<AbstractAction>(install_plan_action));
720
721 BuildPostInstallActions(install_plan_action.get());
722
723 // Enqueue the actions
724 for (vector<shared_ptr<AbstractAction> >::iterator it = actions_.begin();
725 it != actions_.end(); ++it) {
726 processor_->EnqueueAction(it->get());
727 }
Chris Sosaaa18e162013-06-20 13:20:30 -0700728
729 // Update the payload state for Rollback.
730 system_state_->payload_state()->Rollback();
731
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700732 SetStatusAndNotify(UPDATE_STATUS_ATTEMPTING_ROLLBACK);
Chris Sosad317e402013-06-12 13:47:09 -0700733
734 // Just in case we didn't update boot flags yet, make sure they're updated
735 // before any update processing starts. This also schedules the start of the
736 // actions we just posted.
737 start_action_processor_ = true;
738 UpdateBootFlags();
Chris Sosaaa18e162013-06-20 13:20:30 -0700739 return true;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700740}
741
Alex Vakulenko59e253e2014-02-24 10:40:21 -0800742bool UpdateAttempter::CanRollback() const {
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700743 // We can only rollback if the update_engine isn't busy and we have a valid
744 // rollback partition.
745 return (status_ == UPDATE_STATUS_IDLE && !GetRollbackPartition().empty());
Alex Vakulenko2bddadd2014-03-27 13:23:46 -0700746}
747
748std::string UpdateAttempter::GetRollbackPartition() const {
Alex Vakulenko59e253e2014-02-24 10:40:21 -0800749 std::vector<std::string> kernel_devices =
750 system_state_->hardware()->GetKernelDevices();
751
752 std::string boot_kernel_device =
753 system_state_->hardware()->BootKernelDevice();
754
Alex Vakulenko2bddadd2014-03-27 13:23:46 -0700755 LOG(INFO) << "UpdateAttempter::GetRollbackPartition";
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700756 for (const auto& name : kernel_devices)
Alex Vakulenko2bddadd2014-03-27 13:23:46 -0700757 LOG(INFO) << " Available kernel device = " << name;
758 LOG(INFO) << " Boot kernel device = " << boot_kernel_device;
759
Alex Vakulenko59e253e2014-02-24 10:40:21 -0800760 auto current = std::find(kernel_devices.begin(), kernel_devices.end(),
761 boot_kernel_device);
762
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700763 if (current == kernel_devices.end()) {
Alex Vakulenko59e253e2014-02-24 10:40:21 -0800764 LOG(ERROR) << "Unable to find the boot kernel device in the list of "
765 << "available devices";
Alex Vakulenko2bddadd2014-03-27 13:23:46 -0700766 return std::string();
Alex Vakulenko59e253e2014-02-24 10:40:21 -0800767 }
768
769 for (std::string const& device_name : kernel_devices) {
770 if (device_name != *current) {
771 bool bootable = false;
772 if (system_state_->hardware()->IsKernelBootable(device_name, &bootable) &&
773 bootable) {
Alex Vakulenko2bddadd2014-03-27 13:23:46 -0700774 return device_name;
Alex Vakulenko59e253e2014-02-24 10:40:21 -0800775 }
776 }
777 }
778
Alex Vakulenko2bddadd2014-03-27 13:23:46 -0700779 return std::string();
780}
781
782std::vector<std::pair<std::string, bool>>
783 UpdateAttempter::GetKernelDevices() const {
784 std::vector<std::string> kernel_devices =
785 system_state_->hardware()->GetKernelDevices();
786
787 std::string boot_kernel_device =
788 system_state_->hardware()->BootKernelDevice();
789
790 std::vector<std::pair<std::string, bool>> info_list;
791 info_list.reserve(kernel_devices.size());
792
793 for (std::string device_name : kernel_devices) {
794 bool bootable = false;
795 system_state_->hardware()->IsKernelBootable(device_name, &bootable);
796 // Add '*' to the name of the partition we booted from.
797 if (device_name == boot_kernel_device)
798 device_name += '*';
799 info_list.emplace_back(device_name, bootable);
800 }
801
802 return info_list;
Alex Vakulenko59e253e2014-02-24 10:40:21 -0800803}
804
Gilad Arnold28e2f392012-02-09 14:36:46 -0800805void UpdateAttempter::CheckForUpdate(const string& app_version,
Jay Srinivasane73acab2012-07-10 14:34:03 -0700806 const string& omaha_url,
Gilad Arnoldb92f0df2013-01-10 16:32:45 -0800807 bool interactive) {
Gilad Arnold44dc3bf2014-07-18 23:39:38 -0700808 LOG(INFO) << "Interactive update check requested.";
809 if (interactive_update_pending_callback_.get())
810 interactive_update_pending_callback_->Run(true);
Jay Srinivasan08fce042012-06-07 16:31:01 -0700811
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700812 if (status_ != UPDATE_STATUS_IDLE) {
Jay Srinivasan08fce042012-06-07 16:31:01 -0700813 LOG(INFO) << "Skipping update check because current status is "
814 << UpdateStatusToString(status_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700815 return;
816 }
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800817
Gilad Arnoldb92f0df2013-01-10 16:32:45 -0800818 // Pass through the interactive flag, in case we want to simulate a scheduled
819 // test.
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700820 Update(app_version, omaha_url, true, interactive);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700821}
822
Darin Petkov296889c2010-07-23 16:20:54 -0700823bool UpdateAttempter::RebootIfNeeded() {
824 if (status_ != UPDATE_STATUS_UPDATED_NEED_REBOOT) {
825 LOG(INFO) << "Reboot requested, but status is "
826 << UpdateStatusToString(status_) << ", so not rebooting.";
827 return false;
828 }
Daniel Erat65f1da02014-06-27 22:05:38 -0700829
830 if (USE_POWER_MANAGEMENT && RequestPowerManagerReboot())
831 return true;
832
833 return RebootDirectly();
Darin Petkov296889c2010-07-23 16:20:54 -0700834}
835
David Zeuthen3c55abd2013-10-14 12:48:03 -0700836void UpdateAttempter::WriteUpdateCompletedMarker() {
837 if (update_completed_marker_.empty())
838 return;
839
840 int64_t value = system_state_->clock()->GetBootTime().ToInternalValue();
Alex Vakulenko75039d72014-03-25 12:36:28 -0700841 string contents = base::StringPrintf("%" PRIi64, value);
David Zeuthen3c55abd2013-10-14 12:48:03 -0700842
843 utils::WriteFile(update_completed_marker_.c_str(),
844 contents.c_str(),
845 contents.length());
846}
847
Daniel Erat65f1da02014-06-27 22:05:38 -0700848bool UpdateAttempter::RequestPowerManagerReboot() {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700849 GError* error = nullptr;
Daniel Erat65f1da02014-06-27 22:05:38 -0700850 DBusGConnection* bus = dbus_iface_->BusGet(DBUS_BUS_SYSTEM, &error);
851 if (!bus) {
852 LOG(ERROR) << "Failed to get system bus: "
853 << utils::GetAndFreeGError(&error);
854 return false;
855 }
856
857 LOG(INFO) << "Calling " << power_manager::kPowerManagerInterface << "."
858 << power_manager::kRequestRestartMethod;
859 DBusGProxy* proxy = dbus_iface_->ProxyNewForName(
860 bus,
861 power_manager::kPowerManagerServiceName,
862 power_manager::kPowerManagerServicePath,
863 power_manager::kPowerManagerInterface);
864 const gboolean success = dbus_iface_->ProxyCall_1_0(
865 proxy,
866 power_manager::kRequestRestartMethod,
867 &error,
868 power_manager::REQUEST_RESTART_FOR_UPDATE);
869 dbus_iface_->ProxyUnref(proxy);
870
871 if (!success) {
872 LOG(ERROR) << "Failed to call " << power_manager::kRequestRestartMethod
873 << ": " << utils::GetAndFreeGError(&error);
874 return false;
875 }
876
877 return true;
878}
879
880bool UpdateAttempter::RebootDirectly() {
881 vector<string> command;
882 command.push_back("/sbin/shutdown");
883 command.push_back("-r");
884 command.push_back("now");
885 LOG(INFO) << "Running \"" << JoinString(command, ' ') << "\"";
886 int rc = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700887 Subprocess::SynchronousExec(command, &rc, nullptr);
Daniel Erat65f1da02014-06-27 22:05:38 -0700888 return rc == 0;
889}
890
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700891// Delegate methods:
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700892void UpdateAttempter::ProcessingDone(const ActionProcessor* processor,
David Zeuthena99981f2013-04-29 13:42:47 -0700893 ErrorCode code) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700894 LOG(INFO) << "Processing Done.";
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700895 actions_.clear();
Darin Petkov09f96c32010-07-20 09:24:57 -0700896
Chris Sosa4f8ee272012-11-30 13:01:54 -0800897 // Reset cpu shares back to normal.
898 CleanupCpuSharesManagement();
Darin Petkovc6c135c2010-08-11 13:36:18 -0700899
Darin Petkov09f96c32010-07-20 09:24:57 -0700900 if (status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
901 LOG(INFO) << "Error event sent.";
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800902
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700903 // Inform scheduler of new status;
904 SetStatusAndNotify(UPDATE_STATUS_IDLE);
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800905
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -0700906 if (!fake_update_success_) {
907 return;
908 }
909 LOG(INFO) << "Booted from FW B and tried to install new firmware, "
910 "so requesting reboot from user.";
Darin Petkov09f96c32010-07-20 09:24:57 -0700911 }
912
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700913 if (code == ErrorCode::kSuccess) {
David Zeuthen3c55abd2013-10-14 12:48:03 -0700914 WriteUpdateCompletedMarker();
Darin Petkov36275772010-10-01 11:40:57 -0700915 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700916 prefs_->SetString(kPrefsPreviousVersion,
917 omaha_request_params_->app_version());
Darin Petkov9b230572010-10-08 10:20:09 -0700918 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700919
David Zeuthen9a017f22013-04-11 16:10:26 -0700920 system_state_->payload_state()->UpdateSucceeded();
921
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700922 // Since we're done with scattering fully at this point, this is the
923 // safest point delete the state files, as we're sure that the status is
924 // set to reboot (which means no more updates will be applied until reboot)
925 // This deletion is required for correctness as we want the next update
926 // check to re-create a new random number for the update check count.
927 // Similarly, we also delete the wall-clock-wait period that was persisted
928 // so that we start with a new random value for the next update check
929 // after reboot so that the same device is not favored or punished in any
930 // way.
931 prefs_->Delete(kPrefsUpdateCheckCount);
932 prefs_->Delete(kPrefsWallClockWaitPeriod);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700933 prefs_->Delete(kPrefsUpdateFirstSeenAt);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700934
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700935 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700936 LOG(INFO) << "Update successfully applied, waiting to reboot.";
Darin Petkov9d65b7b2010-07-20 09:13:01 -0700937
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700938 // This pointer is null during rollback operations, and the stats
939 // don't make much sense then anyway.
Don Garrettaf9085e2013-11-06 18:14:29 -0800940 if (response_handler_action_) {
941 const InstallPlan& install_plan =
942 response_handler_action_->install_plan();
Alex Deymo42432912013-07-12 20:21:15 -0700943
Don Garrettaf9085e2013-11-06 18:14:29 -0800944 // Generate an unique payload identifier.
945 const string target_version_uid =
946 install_plan.payload_hash + ":" + install_plan.metadata_signature;
Alex Deymo42432912013-07-12 20:21:15 -0700947
Don Garrettaf9085e2013-11-06 18:14:29 -0800948 // Expect to reboot into the new version to send the proper metric during
949 // next boot.
950 system_state_->payload_state()->ExpectRebootInNewVersion(
951 target_version_uid);
Alex Deymo42432912013-07-12 20:21:15 -0700952
Don Garrettaf9085e2013-11-06 18:14:29 -0800953 // Also report the success code so that the percentiles can be
954 // interpreted properly for the remaining error codes in UMA.
955 utils::SendErrorCodeToUma(system_state_, code);
956 } else {
957 // If we just finished a rollback, then we expect to have no Omaha
958 // response. Otherwise, it's an error.
959 if (system_state_->payload_state()->GetRollbackVersion().empty()) {
960 LOG(ERROR) << "Can't send metrics because expected "
961 "response_handler_action_ missing.";
962 }
963 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700964 return;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -0700965 }
Darin Petkov09f96c32010-07-20 09:24:57 -0700966
Darin Petkov1023a602010-08-30 13:47:51 -0700967 if (ScheduleErrorEventAction()) {
Darin Petkov09f96c32010-07-20 09:24:57 -0700968 return;
Darin Petkov1023a602010-08-30 13:47:51 -0700969 }
970 LOG(INFO) << "No update.";
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700971 SetStatusAndNotify(UPDATE_STATUS_IDLE);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700972}
973
974void UpdateAttempter::ProcessingStopped(const ActionProcessor* processor) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800975 // Reset cpu shares back to normal.
976 CleanupCpuSharesManagement();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700977 download_progress_ = 0.0;
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -0700978 SetStatusAndNotify(UPDATE_STATUS_IDLE);
Andrew de los Reyes6b78e292010-05-10 15:54:39 -0700979 actions_.clear();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700980 error_event_.reset(nullptr);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700981}
982
983// Called whenever an action has finished processing, either successfully
984// or otherwise.
985void UpdateAttempter::ActionCompleted(ActionProcessor* processor,
986 AbstractAction* action,
David Zeuthena99981f2013-04-29 13:42:47 -0700987 ErrorCode code) {
Darin Petkov1023a602010-08-30 13:47:51 -0700988 // Reset download progress regardless of whether or not the download
989 // action succeeded. Also, get the response code from HTTP request
990 // actions (update download as well as the initial update check
991 // actions).
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700992 const string type = action->Type();
Darin Petkov1023a602010-08-30 13:47:51 -0700993 if (type == DownloadAction::StaticType()) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -0700994 download_progress_ = 0.0;
Gilad Arnoldcf175a02014-07-10 16:48:47 -0700995 DownloadAction* download_action = static_cast<DownloadAction*>(action);
Darin Petkov1023a602010-08-30 13:47:51 -0700996 http_response_code_ = download_action->GetHTTPResponseCode();
997 } else if (type == OmahaRequestAction::StaticType()) {
998 OmahaRequestAction* omaha_request_action =
Gilad Arnoldcf175a02014-07-10 16:48:47 -0700999 static_cast<OmahaRequestAction*>(action);
Darin Petkov1023a602010-08-30 13:47:51 -07001000 // If the request is not an event, then it's the update-check.
1001 if (!omaha_request_action->IsEvent()) {
1002 http_response_code_ = omaha_request_action->GetHTTPResponseCode();
Gilad Arnolda6dab942014-04-25 11:46:03 -07001003
1004 // Record the number of consecutive failed update checks.
1005 if (http_response_code_ == kHttpResponseInternalServerError ||
1006 http_response_code_ == kHttpResponseServiceUnavailable) {
1007 consecutive_failed_update_checks_++;
1008 } else {
1009 consecutive_failed_update_checks_ = 0;
1010 }
1011
Gilad Arnolda0258a52014-07-10 16:21:19 -07001012 // Store the server-dictated poll interval, if any.
1013 server_dictated_poll_interval_ =
1014 std::max(0, omaha_request_action->GetOutputObject().poll_interval);
1015 // TODO(garnold) Remove this once we deploy Update Manager.
Darin Petkov85ced132010-09-01 10:20:56 -07001016 if (update_check_scheduler_) {
1017 update_check_scheduler_->set_poll_interval(
Gilad Arnolda0258a52014-07-10 16:21:19 -07001018 server_dictated_poll_interval_);
Darin Petkov85ced132010-09-01 10:20:56 -07001019 }
Darin Petkov1023a602010-08-30 13:47:51 -07001020 }
1021 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001022 if (code != ErrorCode::kSuccess) {
Darin Petkov7ed561b2011-10-04 02:59:03 -07001023 // If the current state is at or past the download phase, count the failure
1024 // in case a switch to full update becomes necessary. Ignore network
1025 // transfer timeouts and failures.
Darin Petkov36275772010-10-01 11:40:57 -07001026 if (status_ >= UPDATE_STATUS_DOWNLOADING &&
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001027 code != ErrorCode::kDownloadTransferError) {
Darin Petkov36275772010-10-01 11:40:57 -07001028 MarkDeltaUpdateFailure();
1029 }
Darin Petkov777dbfa2010-07-20 15:03:37 -07001030 // On failure, schedule an error event to be sent to Omaha.
1031 CreatePendingErrorEvent(action, code);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07001032 return;
Darin Petkov09f96c32010-07-20 09:24:57 -07001033 }
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07001034 // Find out which action completed.
1035 if (type == OmahaResponseHandlerAction::StaticType()) {
Darin Petkov9b230572010-10-08 10:20:09 -07001036 // Note that the status will be updated to DOWNLOADING when some bytes get
1037 // actually downloaded from the server and the BytesReceived callback is
1038 // invoked. This avoids notifying the user that a download has started in
1039 // cases when the server and the client are unable to initiate the download.
1040 CHECK(action == response_handler_action_.get());
1041 const InstallPlan& plan = response_handler_action_->install_plan();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001042 last_checked_time_ = time(nullptr);
Chris Sosafb1020e2013-07-29 17:27:33 -07001043 new_version_ = plan.version;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001044 new_payload_size_ = plan.payload_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001045 SetupDownload();
Chris Sosa4f8ee272012-11-30 13:01:54 -08001046 SetupCpuSharesManagement();
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -07001047 SetStatusAndNotify(UPDATE_STATUS_UPDATE_AVAILABLE);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07001048 } else if (type == DownloadAction::StaticType()) {
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -07001049 SetStatusAndNotify(UPDATE_STATUS_FINALIZING);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07001050 }
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07001051}
1052
1053// Stop updating. An attempt will be made to record status to the disk
1054// so that updates can be resumed later.
1055void UpdateAttempter::Terminate() {
1056 // TODO(adlr): implement this method.
1057 NOTIMPLEMENTED();
1058}
1059
1060// Try to resume from a previously Terminate()d update.
1061void UpdateAttempter::ResumeUpdating() {
1062 // TODO(adlr): implement this method.
1063 NOTIMPLEMENTED();
1064}
1065
Darin Petkov9d911fa2010-08-19 09:36:08 -07001066void UpdateAttempter::SetDownloadStatus(bool active) {
1067 download_active_ = active;
1068 LOG(INFO) << "Download status: " << (active ? "active" : "inactive");
1069}
1070
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07001071void UpdateAttempter::BytesReceived(uint64_t bytes_received, uint64_t total) {
Darin Petkov9d911fa2010-08-19 09:36:08 -07001072 if (!download_active_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07001073 LOG(ERROR) << "BytesReceived called while not downloading.";
1074 return;
1075 }
Darin Petkovaf183052010-08-23 12:07:13 -07001076 double progress = static_cast<double>(bytes_received) /
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07001077 static_cast<double>(total);
Darin Petkovaf183052010-08-23 12:07:13 -07001078 // Self throttle based on progress. Also send notifications if
1079 // progress is too slow.
1080 const double kDeltaPercent = 0.01; // 1%
1081 if (status_ != UPDATE_STATUS_DOWNLOADING ||
1082 bytes_received == total ||
1083 progress - download_progress_ >= kDeltaPercent ||
1084 TimeTicks::Now() - last_notify_time_ >= TimeDelta::FromSeconds(10)) {
1085 download_progress_ = progress;
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -07001086 SetStatusAndNotify(UPDATE_STATUS_DOWNLOADING);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07001087 }
1088}
1089
Jay Srinivasanc1ba09a2012-08-14 14:15:57 -07001090bool UpdateAttempter::ResetStatus() {
1091 LOG(INFO) << "Attempting to reset state from "
1092 << UpdateStatusToString(status_) << " to UPDATE_STATUS_IDLE";
1093
1094 switch (status_) {
1095 case UPDATE_STATUS_IDLE:
1096 // no-op.
1097 return true;
1098
1099 case UPDATE_STATUS_UPDATED_NEED_REBOOT: {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001100 bool ret_value = true;
Jay Srinivasanc1ba09a2012-08-14 14:15:57 -07001101 status_ = UPDATE_STATUS_IDLE;
1102 LOG(INFO) << "Reset Successful";
1103
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001104 // Remove the reboot marker so that if the machine is rebooted
Jay Srinivasanc1ba09a2012-08-14 14:15:57 -07001105 // after resetting to idle state, it doesn't go back to
1106 // UPDATE_STATUS_UPDATED_NEED_REBOOT state.
Gilad Arnold70e476e2013-07-30 16:01:13 -07001107 if (!update_completed_marker_.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -07001108 if (!base::DeleteFile(base::FilePath(update_completed_marker_), false))
Gilad Arnold70e476e2013-07-30 16:01:13 -07001109 ret_value = false;
1110 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001111
Alex Deymo42432912013-07-12 20:21:15 -07001112 // Notify the PayloadState that the successful payload was canceled.
1113 system_state_->payload_state()->ResetUpdateStatus();
1114
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001115 return ret_value;
Jay Srinivasanc1ba09a2012-08-14 14:15:57 -07001116 }
1117
1118 default:
1119 LOG(ERROR) << "Reset not allowed in this state.";
1120 return false;
1121 }
1122}
1123
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07001124bool UpdateAttempter::GetStatus(int64_t* last_checked_time,
1125 double* progress,
Gilad Arnold28e2f392012-02-09 14:36:46 -08001126 string* current_operation,
1127 string* new_version,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001128 int64_t* new_payload_size) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07001129 *last_checked_time = last_checked_time_;
1130 *progress = download_progress_;
1131 *current_operation = UpdateStatusToString(status_);
1132 *new_version = new_version_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001133 *new_payload_size = new_payload_size_;
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07001134 return true;
1135}
1136
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -07001137void UpdateAttempter::UpdateBootFlags() {
Darin Petkov58dd1342011-05-06 12:05:13 -07001138 if (update_boot_flags_running_) {
1139 LOG(INFO) << "Update boot flags running, nothing to do.";
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -07001140 return;
1141 }
Darin Petkov58dd1342011-05-06 12:05:13 -07001142 if (updated_boot_flags_) {
1143 LOG(INFO) << "Already updated boot flags. Skipping.";
1144 if (start_action_processor_) {
1145 ScheduleProcessingStart();
1146 }
1147 return;
1148 }
1149 // This is purely best effort. Failures should be logged by Subprocess. Run
1150 // the script asynchronously to avoid blocking the event loop regardless of
1151 // the script runtime.
1152 update_boot_flags_running_ = true;
1153 LOG(INFO) << "Updating boot flags...";
Alex Deymo3e0b53e2014-08-12 23:12:25 -07001154 vector<string> cmd{set_good_kernel_cmd_};
Darin Petkov58dd1342011-05-06 12:05:13 -07001155 if (!Subprocess::Get().Exec(cmd, StaticCompleteUpdateBootFlags, this)) {
1156 CompleteUpdateBootFlags(1);
1157 }
1158}
1159
1160void UpdateAttempter::CompleteUpdateBootFlags(int return_code) {
1161 update_boot_flags_running_ = false;
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -07001162 updated_boot_flags_ = true;
Darin Petkov58dd1342011-05-06 12:05:13 -07001163 if (start_action_processor_) {
1164 ScheduleProcessingStart();
1165 }
1166}
1167
1168void UpdateAttempter::StaticCompleteUpdateBootFlags(
1169 int return_code,
Gilad Arnold28e2f392012-02-09 14:36:46 -08001170 const string& output,
Darin Petkov58dd1342011-05-06 12:05:13 -07001171 void* p) {
1172 reinterpret_cast<UpdateAttempter*>(p)->CompleteUpdateBootFlags(return_code);
Andrew de los Reyes6dbf30a2011-04-19 10:58:16 -07001173}
1174
Darin Petkov61635a92011-05-18 16:20:36 -07001175void UpdateAttempter::BroadcastStatus() {
1176 if (!dbus_service_) {
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07001177 return;
Darin Petkov61635a92011-05-18 16:20:36 -07001178 }
Darin Petkovaf183052010-08-23 12:07:13 -07001179 last_notify_time_ = TimeTicks::Now();
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07001180 update_engine_service_emit_status_update(
1181 dbus_service_,
1182 last_checked_time_,
1183 download_progress_,
1184 UpdateStatusToString(status_),
1185 new_version_.c_str(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001186 new_payload_size_);
Andrew de los Reyes63b96d72010-05-10 13:08:54 -07001187}
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07001188
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001189uint32_t UpdateAttempter::GetErrorCodeFlags() {
1190 uint32_t flags = 0;
1191
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001192 if (!system_state_->hardware()->IsNormalBootMode())
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001193 flags |= static_cast<uint32_t>(ErrorCode::kDevModeFlag);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001194
1195 if (response_handler_action_.get() &&
1196 response_handler_action_->install_plan().is_resume)
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001197 flags |= static_cast<uint32_t>(ErrorCode::kResumedFlag);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001198
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001199 if (!system_state_->hardware()->IsOfficialBuild())
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001200 flags |= static_cast<uint32_t>(ErrorCode::kTestImageFlag);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001201
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001202 if (omaha_request_params_->update_url() != kProductionOmahaUrl)
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001203 flags |= static_cast<uint32_t>(ErrorCode::kTestOmahaUrlFlag);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001204
1205 return flags;
1206}
1207
David Zeuthena99981f2013-04-29 13:42:47 -07001208bool UpdateAttempter::ShouldCancel(ErrorCode* cancel_reason) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001209 // Check if the channel we're attempting to update to is the same as the
1210 // target channel currently chosen by the user.
1211 OmahaRequestParams* params = system_state_->request_params();
1212 if (params->download_channel() != params->target_channel()) {
1213 LOG(ERROR) << "Aborting download as target channel: "
1214 << params->target_channel()
1215 << " is different from the download channel: "
1216 << params->download_channel();
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001217 *cancel_reason = ErrorCode::kUpdateCanceledByChannelChange;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001218 return true;
1219 }
1220
1221 return false;
1222}
1223
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -07001224void UpdateAttempter::SetStatusAndNotify(UpdateStatus status) {
Darin Petkov61635a92011-05-18 16:20:36 -07001225 status_ = status;
1226 if (update_check_scheduler_) {
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -07001227 update_check_scheduler_->SetUpdateStatus(status_);
Darin Petkov61635a92011-05-18 16:20:36 -07001228 }
1229 BroadcastStatus();
1230}
1231
Darin Petkov777dbfa2010-07-20 15:03:37 -07001232void UpdateAttempter::CreatePendingErrorEvent(AbstractAction* action,
David Zeuthena99981f2013-04-29 13:42:47 -07001233 ErrorCode code) {
Darin Petkov09f96c32010-07-20 09:24:57 -07001234 if (error_event_.get()) {
1235 // This shouldn't really happen.
1236 LOG(WARNING) << "There's already an existing pending error event.";
1237 return;
1238 }
Darin Petkov777dbfa2010-07-20 15:03:37 -07001239
Darin Petkovabc7bc02011-02-23 14:39:43 -08001240 // For now assume that a generic Omaha response action failure means that
1241 // there's no update so don't send an event. Also, double check that the
1242 // failure has not occurred while sending an error event -- in which case
1243 // don't schedule another. This shouldn't really happen but just in case...
1244 if ((action->Type() == OmahaResponseHandlerAction::StaticType() &&
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001245 code == ErrorCode::kError) ||
Darin Petkov777dbfa2010-07-20 15:03:37 -07001246 status_ == UPDATE_STATUS_REPORTING_ERROR_EVENT) {
1247 return;
1248 }
1249
Jay Srinivasan56d5aa42012-03-26 14:27:59 -07001250 // Classify the code to generate the appropriate result so that
1251 // the Borgmon charts show up the results correctly.
1252 // Do this before calling GetErrorCodeForAction which could potentially
1253 // augment the bit representation of code and thus cause no matches for
1254 // the switch cases below.
1255 OmahaEvent::Result event_result;
1256 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001257 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1258 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1259 case ErrorCode::kOmahaUpdateDeferredForBackoff:
Jay Srinivasan56d5aa42012-03-26 14:27:59 -07001260 event_result = OmahaEvent::kResultUpdateDeferred;
1261 break;
1262 default:
1263 event_result = OmahaEvent::kResultError;
1264 break;
1265 }
1266
Darin Petkov777dbfa2010-07-20 15:03:37 -07001267 code = GetErrorCodeForAction(action, code);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001268 fake_update_success_ = code == ErrorCode::kPostinstallBootedFromFirmwareB;
Darin Petkov18c7bce2011-06-16 14:07:00 -07001269
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001270 // Compute the final error code with all the bit flags to be sent to Omaha.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001271 code = static_cast<ErrorCode>(
1272 static_cast<uint32_t>(code) | GetErrorCodeFlags());
Darin Petkov09f96c32010-07-20 09:24:57 -07001273 error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
Jay Srinivasan56d5aa42012-03-26 14:27:59 -07001274 event_result,
Darin Petkov09f96c32010-07-20 09:24:57 -07001275 code));
1276}
1277
1278bool UpdateAttempter::ScheduleErrorEventAction() {
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001279 if (error_event_.get() == nullptr)
Darin Petkov09f96c32010-07-20 09:24:57 -07001280 return false;
1281
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001282 LOG(ERROR) << "Update failed.";
1283 system_state_->payload_state()->UpdateFailed(error_event_->error_code);
1284
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001285 // Send it to Uma.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001286 LOG(INFO) << "Reporting the error event";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001287 utils::SendErrorCodeToUma(system_state_, error_event_->error_code);
1288
1289 // Send it to Omaha.
Darin Petkov09f96c32010-07-20 09:24:57 -07001290 shared_ptr<OmahaRequestAction> error_event_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001291 new OmahaRequestAction(system_state_,
Darin Petkov09f96c32010-07-20 09:24:57 -07001292 error_event_.release(), // Pass ownership.
Jay Srinivasan08fce042012-06-07 16:31:01 -07001293 new LibcurlHttpFetcher(GetProxyResolver(),
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -07001294 system_state_),
Thieu Le116fda32011-04-19 11:01:54 -07001295 false));
Darin Petkov09f96c32010-07-20 09:24:57 -07001296 actions_.push_back(shared_ptr<AbstractAction>(error_event_action));
Darin Petkovf42cc1c2010-09-01 09:03:02 -07001297 processor_->EnqueueAction(error_event_action.get());
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -07001298 SetStatusAndNotify(UPDATE_STATUS_REPORTING_ERROR_EVENT);
Darin Petkovf42cc1c2010-09-01 09:03:02 -07001299 processor_->StartProcessing();
Darin Petkov09f96c32010-07-20 09:24:57 -07001300 return true;
1301}
1302
Chris Sosa4f8ee272012-11-30 13:01:54 -08001303void UpdateAttempter::SetCpuShares(utils::CpuShares shares) {
1304 if (shares_ == shares) {
Darin Petkovc6c135c2010-08-11 13:36:18 -07001305 return;
1306 }
Chris Sosa4f8ee272012-11-30 13:01:54 -08001307 if (utils::SetCpuShares(shares)) {
1308 shares_ = shares;
1309 LOG(INFO) << "CPU shares = " << shares_;
Darin Petkovc6c135c2010-08-11 13:36:18 -07001310 }
1311}
1312
Chris Sosa4f8ee272012-11-30 13:01:54 -08001313void UpdateAttempter::SetupCpuSharesManagement() {
1314 if (manage_shares_source_) {
1315 LOG(ERROR) << "Cpu shares timeout source hasn't been destroyed.";
1316 CleanupCpuSharesManagement();
Darin Petkovc6c135c2010-08-11 13:36:18 -07001317 }
Chris Sosa4f8ee272012-11-30 13:01:54 -08001318 const int kCpuSharesTimeout = 2 * 60 * 60; // 2 hours
1319 manage_shares_source_ = g_timeout_source_new_seconds(kCpuSharesTimeout);
1320 g_source_set_callback(manage_shares_source_,
1321 StaticManageCpuSharesCallback,
Darin Petkovc6c135c2010-08-11 13:36:18 -07001322 this,
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001323 nullptr);
1324 g_source_attach(manage_shares_source_, nullptr);
Chris Sosa4f8ee272012-11-30 13:01:54 -08001325 SetCpuShares(utils::kCpuSharesLow);
Darin Petkovc6c135c2010-08-11 13:36:18 -07001326}
1327
Chris Sosa4f8ee272012-11-30 13:01:54 -08001328void UpdateAttempter::CleanupCpuSharesManagement() {
1329 if (manage_shares_source_) {
1330 g_source_destroy(manage_shares_source_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001331 manage_shares_source_ = nullptr;
Darin Petkovc6c135c2010-08-11 13:36:18 -07001332 }
Chris Sosa4f8ee272012-11-30 13:01:54 -08001333 SetCpuShares(utils::kCpuSharesNormal);
Darin Petkovc6c135c2010-08-11 13:36:18 -07001334}
1335
Chris Sosa4f8ee272012-11-30 13:01:54 -08001336gboolean UpdateAttempter::StaticManageCpuSharesCallback(gpointer data) {
1337 return reinterpret_cast<UpdateAttempter*>(data)->ManageCpuSharesCallback();
Darin Petkovc6c135c2010-08-11 13:36:18 -07001338}
1339
Darin Petkove6ef2f82011-03-07 17:31:11 -08001340gboolean UpdateAttempter::StaticStartProcessing(gpointer data) {
1341 reinterpret_cast<UpdateAttempter*>(data)->processor_->StartProcessing();
1342 return FALSE; // Don't call this callback again.
1343}
1344
Darin Petkov58dd1342011-05-06 12:05:13 -07001345void UpdateAttempter::ScheduleProcessingStart() {
1346 LOG(INFO) << "Scheduling an action processor start.";
1347 start_action_processor_ = false;
1348 g_idle_add(&StaticStartProcessing, this);
1349}
1350
Chris Sosa4f8ee272012-11-30 13:01:54 -08001351bool UpdateAttempter::ManageCpuSharesCallback() {
1352 SetCpuShares(utils::kCpuSharesNormal);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001353 manage_shares_source_ = nullptr;
Darin Petkovf622ef72010-10-26 13:49:24 -07001354 return false; // Destroy the timeout source.
Darin Petkovc6c135c2010-08-11 13:36:18 -07001355}
1356
Darin Petkov36275772010-10-01 11:40:57 -07001357void UpdateAttempter::DisableDeltaUpdateIfNeeded() {
1358 int64_t delta_failures;
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001359 if (omaha_request_params_->delta_okay() &&
Darin Petkov36275772010-10-01 11:40:57 -07001360 prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) &&
1361 delta_failures >= kMaxDeltaUpdateFailures) {
1362 LOG(WARNING) << "Too many delta update failures, forcing full update.";
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001363 omaha_request_params_->set_delta_okay(false);
Darin Petkov36275772010-10-01 11:40:57 -07001364 }
1365}
1366
1367void UpdateAttempter::MarkDeltaUpdateFailure() {
Darin Petkov2dd01092010-10-08 15:43:05 -07001368 // Don't try to resume a failed delta update.
1369 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Darin Petkov36275772010-10-01 11:40:57 -07001370 int64_t delta_failures;
1371 if (!prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) ||
1372 delta_failures < 0) {
1373 delta_failures = 0;
1374 }
1375 prefs_->SetInt64(kPrefsDeltaUpdateFailures, ++delta_failures);
1376}
1377
Darin Petkov9b230572010-10-08 10:20:09 -07001378void UpdateAttempter::SetupDownload() {
Gilad Arnold9bedeb52011-11-17 16:19:57 -08001379 MultiRangeHttpFetcher* fetcher =
Gilad Arnoldcf175a02014-07-10 16:48:47 -07001380 static_cast<MultiRangeHttpFetcher*>(download_action_->http_fetcher());
Andrew de los Reyes819fef22010-12-17 11:33:58 -08001381 fetcher->ClearRanges();
Darin Petkov9b230572010-10-08 10:20:09 -07001382 if (response_handler_action_->install_plan().is_resume) {
Darin Petkovb21ce5d2010-10-21 16:03:05 -07001383 // Resuming an update so fetch the update manifest metadata first.
Darin Petkov9b230572010-10-08 10:20:09 -07001384 int64_t manifest_metadata_size = 0;
1385 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
Andrew de los Reyes819fef22010-12-17 11:33:58 -08001386 fetcher->AddRange(0, manifest_metadata_size);
Darin Petkovb21ce5d2010-10-21 16:03:05 -07001387 // If there're remaining unprocessed data blobs, fetch them. Be careful not
1388 // to request data beyond the end of the payload to avoid 416 HTTP response
1389 // error codes.
Darin Petkov9b230572010-10-08 10:20:09 -07001390 int64_t next_data_offset = 0;
1391 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -07001392 uint64_t resume_offset = manifest_metadata_size + next_data_offset;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001393 if (resume_offset < response_handler_action_->install_plan().payload_size) {
Gilad Arnolde4ad2502011-12-29 17:08:54 -08001394 fetcher->AddRange(resume_offset);
Darin Petkovb21ce5d2010-10-21 16:03:05 -07001395 }
Darin Petkov9b230572010-10-08 10:20:09 -07001396 } else {
Gilad Arnolde4ad2502011-12-29 17:08:54 -08001397 fetcher->AddRange(0);
Darin Petkov9b230572010-10-08 10:20:09 -07001398 }
Darin Petkov9b230572010-10-08 10:20:09 -07001399}
1400
Thieu Le116fda32011-04-19 11:01:54 -07001401void UpdateAttempter::PingOmaha() {
Thieu Led88a8572011-05-26 09:09:19 -07001402 if (!processor_->IsRunning()) {
1403 shared_ptr<OmahaRequestAction> ping_action(
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001404 new OmahaRequestAction(system_state_,
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001405 nullptr,
Jay Srinivasan08fce042012-06-07 16:31:01 -07001406 new LibcurlHttpFetcher(GetProxyResolver(),
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -07001407 system_state_),
Thieu Led88a8572011-05-26 09:09:19 -07001408 true));
1409 actions_.push_back(shared_ptr<OmahaRequestAction>(ping_action));
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001410 processor_->set_delegate(nullptr);
Thieu Led88a8572011-05-26 09:09:19 -07001411 processor_->EnqueueAction(ping_action.get());
1412 // Call StartProcessing() synchronously here to avoid any race conditions
1413 // caused by multiple outstanding ping Omaha requests. If we call
1414 // StartProcessing() asynchronously, the device can be suspended before we
1415 // get a chance to callback to StartProcessing(). When the device resumes
1416 // (assuming the device sleeps longer than the next update check period),
1417 // StartProcessing() is called back and at the same time, the next update
1418 // check is fired which eventually invokes StartProcessing(). A crash
1419 // can occur because StartProcessing() checks to make sure that the
1420 // processor is idle which it isn't due to the two concurrent ping Omaha
1421 // requests.
1422 processor_->StartProcessing();
1423 } else {
Darin Petkov58dd1342011-05-06 12:05:13 -07001424 LOG(WARNING) << "Action processor running, Omaha ping suppressed.";
Darin Petkov58dd1342011-05-06 12:05:13 -07001425 }
Thieu Led88a8572011-05-26 09:09:19 -07001426
1427 // Update the status which will schedule the next update check
Nam T. Nguyen7d623eb2014-05-13 16:06:28 -07001428 SetStatusAndNotify(UPDATE_STATUS_UPDATED_NEED_REBOOT);
Thieu Le116fda32011-04-19 11:01:54 -07001429}
1430
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001431
1432bool UpdateAttempter::DecrementUpdateCheckCount() {
Ben Chan9abb7632014-08-07 00:10:53 -07001433 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001434
1435 if (!prefs_->Exists(kPrefsUpdateCheckCount)) {
1436 // This file does not exist. This means we haven't started our update
1437 // check count down yet, so nothing more to do. This file will be created
1438 // later when we first satisfy the wall-clock-based-wait period.
1439 LOG(INFO) << "No existing update check count. That's normal.";
1440 return true;
1441 }
1442
1443 if (prefs_->GetInt64(kPrefsUpdateCheckCount, &update_check_count_value)) {
1444 // Only if we're able to read a proper integer value, then go ahead
1445 // and decrement and write back the result in the same file, if needed.
1446 LOG(INFO) << "Update check count = " << update_check_count_value;
1447
1448 if (update_check_count_value == 0) {
1449 // It could be 0, if, for some reason, the file didn't get deleted
1450 // when we set our status to waiting for reboot. so we just leave it
1451 // as is so that we can prevent another update_check wait for this client.
1452 LOG(INFO) << "Not decrementing update check count as it's already 0.";
1453 return true;
1454 }
1455
1456 if (update_check_count_value > 0)
1457 update_check_count_value--;
1458 else
1459 update_check_count_value = 0;
1460
1461 // Write out the new value of update_check_count_value.
1462 if (prefs_->SetInt64(kPrefsUpdateCheckCount, update_check_count_value)) {
1463 // We successfully wrote out te new value, so enable the
1464 // update check based wait.
1465 LOG(INFO) << "New update check count = " << update_check_count_value;
1466 return true;
1467 }
1468 }
1469
1470 LOG(INFO) << "Deleting update check count state due to read/write errors.";
1471
1472 // We cannot read/write to the file, so disable the update check based wait
1473 // so that we don't get stuck in this OS version by any chance (which could
1474 // happen if there's some bug that causes to read/write incorrectly).
1475 // Also attempt to delete the file to do our best effort to cleanup.
1476 prefs_->Delete(kPrefsUpdateCheckCount);
1477 return false;
1478}
Chris Sosad317e402013-06-12 13:47:09 -07001479
David Zeuthen8f191b22013-08-06 12:27:50 -07001480
David Zeuthene4c58bf2013-06-18 17:26:50 -07001481void UpdateAttempter::UpdateEngineStarted() {
Alex Vakulenkodea2eac2014-03-14 15:56:59 -07001482 // If we just booted into a new update, keep the previous OS version
1483 // in case we rebooted because of a crash of the old version, so we
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001484 // can do a proper crash report with correct information.
Alex Vakulenkodea2eac2014-03-14 15:56:59 -07001485 // This must be done before calling
1486 // system_state_->payload_state()->UpdateEngineStarted() since it will
1487 // delete SystemUpdated marker file.
1488 if (system_state_->system_rebooted() &&
1489 prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1490 if (!prefs_->GetString(kPrefsPreviousVersion, &prev_version_)) {
1491 // If we fail to get the version string, make sure it stays empty.
1492 prev_version_.clear();
1493 }
1494 }
1495
David Zeuthene4c58bf2013-06-18 17:26:50 -07001496 system_state_->payload_state()->UpdateEngineStarted();
David Zeuthen8f191b22013-08-06 12:27:50 -07001497 StartP2PAtStartup();
1498}
1499
1500bool UpdateAttempter::StartP2PAtStartup() {
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001501 if (system_state_ == nullptr ||
David Zeuthen8f191b22013-08-06 12:27:50 -07001502 !system_state_->p2p_manager()->IsP2PEnabled()) {
1503 LOG(INFO) << "Not starting p2p at startup since it's not enabled.";
1504 return false;
1505 }
1506
1507 if (system_state_->p2p_manager()->CountSharedFiles() < 1) {
1508 LOG(INFO) << "Not starting p2p at startup since our application "
1509 << "is not sharing any files.";
1510 return false;
1511 }
1512
1513 return StartP2PAndPerformHousekeeping();
1514}
1515
1516bool UpdateAttempter::StartP2PAndPerformHousekeeping() {
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001517 if (system_state_ == nullptr)
David Zeuthen8f191b22013-08-06 12:27:50 -07001518 return false;
1519
1520 if (!system_state_->p2p_manager()->IsP2PEnabled()) {
1521 LOG(INFO) << "Not starting p2p since it's not enabled.";
1522 return false;
1523 }
1524
1525 LOG(INFO) << "Ensuring that p2p is running.";
1526 if (!system_state_->p2p_manager()->EnsureP2PRunning()) {
1527 LOG(ERROR) << "Error starting p2p.";
1528 return false;
1529 }
1530
1531 LOG(INFO) << "Performing p2p housekeeping.";
1532 if (!system_state_->p2p_manager()->PerformHousekeeping()) {
1533 LOG(ERROR) << "Error performing housekeeping for p2p.";
1534 return false;
1535 }
1536
1537 LOG(INFO) << "Done performing p2p housekeeping.";
1538 return true;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001539}
1540
David Zeuthen3c55abd2013-10-14 12:48:03 -07001541bool UpdateAttempter::GetBootTimeAtUpdate(base::Time *out_boot_time) {
1542 if (update_completed_marker_.empty())
1543 return false;
1544
1545 string contents;
1546 if (!utils::ReadFile(update_completed_marker_, &contents))
1547 return false;
1548
1549 char *endp;
1550 int64_t stored_value = strtoll(contents.c_str(), &endp, 10);
1551 if (*endp != '\0') {
1552 LOG(ERROR) << "Error parsing file " << update_completed_marker_ << " "
1553 << "with content '" << contents << "'";
1554 return false;
1555 }
1556
1557 *out_boot_time = Time::FromInternalValue(stored_value);
1558 return true;
1559}
1560
Andrew de los Reyes4e9b9f42010-04-26 15:06:43 -07001561} // namespace chromeos_update_engine