blob: 4d21de6a36341d91d056eb64ee5a555bd0168eac [file] [log] [blame]
Alex Deymo5e3ea272016-01-28 13:42:23 -08001//
2// Copyright (C) 2016 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
17#include "update_engine/update_attempter_android.h"
18
19#include <algorithm>
Alex Deymo218397f2016-02-04 23:55:10 -080020#include <map>
Tianjie Xu90aaa102017-10-10 17:39:03 -070021#include <memory>
Alex Deymo5e3ea272016-01-28 13:42:23 -080022#include <utility>
23
Tianjie Xu90aaa102017-10-10 17:39:03 -070024#include <android-base/properties.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080025#include <base/bind.h>
26#include <base/logging.h>
Alex Deymo218397f2016-02-04 23:55:10 -080027#include <base/strings/string_number_conversions.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080028#include <brillo/bind_lambda.h>
Sen Jiang2703ef42017-03-16 13:36:21 -070029#include <brillo/data_encoding.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080030#include <brillo/message_loops/message_loop.h>
Alex Deymo218397f2016-02-04 23:55:10 -080031#include <brillo/strings/string_utils.h>
Sen Jiangacbdd1c2017-10-19 13:30:19 -070032#include <log/log_safetynet.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080033
34#include "update_engine/common/constants.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080035#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070036#include "update_engine/common/file_fetcher.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080037#include "update_engine/common/utils.h"
Alex Deymo03a4de72016-07-20 16:08:23 -070038#include "update_engine/daemon_state_interface.h"
Tianjie Xud4c5deb2017-10-24 11:17:03 -070039#include "update_engine/metrics_reporter_interface.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070040#include "update_engine/metrics_utils.h"
Alex Deymo87792ea2016-07-25 15:40:36 -070041#include "update_engine/network_selector.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080042#include "update_engine/payload_consumer/delta_performer.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080043#include "update_engine/payload_consumer/download_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080044#include "update_engine/payload_consumer/file_descriptor.h"
45#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080046#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080047#include "update_engine/payload_consumer/payload_constants.h"
48#include "update_engine/payload_consumer/payload_metadata.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080049#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070050#include "update_engine/update_boot_flags_action.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080051#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080052
Alex Deymo14c0da82016-07-20 16:45:45 -070053#ifndef _UE_SIDELOAD
54// Do not include support for external HTTP(s) urls when building
55// update_engine_sideload.
56#include "update_engine/libcurl_http_fetcher.h"
57#endif
58
Alex Deymo5e3ea272016-01-28 13:42:23 -080059using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070060using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080061using base::TimeDelta;
62using base::TimeTicks;
63using std::shared_ptr;
64using std::string;
65using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070066using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080067
68namespace chromeos_update_engine {
69
70namespace {
71
Alex Deymo0d298542016-03-30 18:31:49 -070072// Minimum threshold to broadcast an status update in progress and time.
73const double kBroadcastThresholdProgress = 0.01; // 1%
74const int kBroadcastThresholdSeconds = 10;
75
Alex Deymo5e3ea272016-01-28 13:42:23 -080076const char* const kErrorDomain = "update_engine";
77// TODO(deymo): Convert the different errors to a numeric value to report them
78// back on the service error.
79const char* const kGenericError = "generic_error";
80
81// Log and set the error on the passed ErrorPtr.
82bool LogAndSetError(brillo::ErrorPtr* error,
83 const tracked_objects::Location& location,
84 const string& reason) {
85 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
86 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
87 << reason;
88 return false;
89}
90
Sen Jiangfe522822017-10-31 15:14:11 -070091bool GetHeaderAsBool(const string& header, bool default_value) {
92 int value = 0;
93 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
94 return value == 1;
95 return default_value;
96}
97
Alex Deymo5e3ea272016-01-28 13:42:23 -080098} // namespace
99
100UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700101 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800102 PrefsInterface* prefs,
103 BootControlInterface* boot_control,
104 HardwareInterface* hardware)
105 : daemon_state_(daemon_state),
106 prefs_(prefs),
107 boot_control_(boot_control),
108 hardware_(hardware),
Tianjie Xu1b661142017-09-28 14:03:42 -0700109 processor_(new ActionProcessor()),
Tianjie Xud4c5deb2017-10-24 11:17:03 -0700110 clock_(new Clock()) {
111 metrics_reporter_ = metrics::CreateMetricsReporter();
Alex Deymo87792ea2016-07-25 15:40:36 -0700112 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800113}
114
115UpdateAttempterAndroid::~UpdateAttempterAndroid() {
116 // Release ourselves as the ActionProcessor's delegate to prevent
117 // re-scheduling the updates due to the processing stopped.
118 processor_->set_delegate(nullptr);
119}
120
121void UpdateAttempterAndroid::Init() {
122 // In case of update_engine restart without a reboot we need to restore the
123 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700124 if (UpdateCompletedOnThisBoot()) {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800125 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700126 } else {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800127 SetStatusAndNotify(UpdateStatus::IDLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700128 UpdatePrefsAndReportUpdateMetricsOnReboot();
129 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800130}
131
132bool UpdateAttempterAndroid::ApplyPayload(
133 const string& payload_url,
134 int64_t payload_offset,
135 int64_t payload_size,
136 const vector<string>& key_value_pair_headers,
137 brillo::ErrorPtr* error) {
138 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
139 return LogAndSetError(
140 error, FROM_HERE, "An update already applied, waiting for reboot");
141 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700142 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800143 return LogAndSetError(
144 error, FROM_HERE, "Already processing an update, cancel it first.");
145 }
146 DCHECK(status_ == UpdateStatus::IDLE);
147
Alex Deymo218397f2016-02-04 23:55:10 -0800148 std::map<string, string> headers;
149 for (const string& key_value_pair : key_value_pair_headers) {
150 string key;
151 string value;
152 if (!brillo::string_utils::SplitAtFirst(
153 key_value_pair, "=", &key, &value, false)) {
154 return LogAndSetError(
155 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
156 }
157 if (!headers.emplace(key, value).second)
158 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
159 }
160
161 // Unique identifier for the payload. An empty string means that the payload
162 // can't be resumed.
163 string payload_id = (headers[kPayloadPropertyFileHash] +
164 headers[kPayloadPropertyMetadataHash]);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800165
166 // Setup the InstallPlan based on the request.
167 install_plan_ = InstallPlan();
168
169 install_plan_.download_url = payload_url;
170 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800171 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800172 InstallPlan::Payload payload;
173 payload.size = payload_size;
174 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800175 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800176 &payload.size)) {
177 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800178 }
179 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700180 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800181 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700182 LOG(WARNING) << "Unable to decode base64 file hash: "
183 << headers[kPayloadPropertyFileHash];
184 }
Alex Deymo218397f2016-02-04 23:55:10 -0800185 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800186 &payload.metadata_size)) {
187 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800188 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700189 // The |payload.type| is not used anymore since minor_version 3.
190 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800191 install_plan_.payloads.push_back(payload);
192
Alex Deymo5e3ea272016-01-28 13:42:23 -0800193 // The |public_key_rsa| key would override the public key stored on disk.
194 install_plan_.public_key_rsa = "";
195
196 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
197 install_plan_.is_resume = !payload_id.empty() &&
198 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
199 if (!install_plan_.is_resume) {
200 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
201 LOG(WARNING) << "Unable to reset the update progress.";
202 }
203 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
204 LOG(WARNING) << "Unable to save the update check response hash.";
205 }
206 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800207 install_plan_.source_slot = boot_control_->GetCurrentSlot();
208 install_plan_.target_slot = install_plan_.source_slot == 0 ? 1 : 0;
Alex Deymofb905d92016-06-03 19:26:58 -0700209
Alex Deymofb905d92016-06-03 19:26:58 -0700210 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700211 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
212
213 install_plan_.switch_slot_on_reboot =
214 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
215
216 install_plan_.run_post_install = true;
217 // Optionally skip post install if and only if:
218 // a) we're resuming
219 // b) post install has already succeeded before
220 // c) RUN_POST_INSTALL is set to 0.
221 if (install_plan_.is_resume && prefs_->Exists(kPrefsPostInstallSucceeded)) {
222 bool post_install_succeeded = false;
223 prefs_->GetBoolean(kPrefsPostInstallSucceeded, &post_install_succeeded);
224 if (post_install_succeeded) {
225 install_plan_.run_post_install =
226 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
227 }
228 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800229
Alex Deymo87792ea2016-07-25 15:40:36 -0700230 NetworkId network_id = kDefaultNetworkId;
231 if (!headers[kPayloadPropertyNetworkId].empty()) {
232 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
233 &network_id)) {
234 return LogAndSetError(
235 error,
236 FROM_HERE,
237 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
238 }
239 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700240 return LogAndSetError(
241 error,
242 FROM_HERE,
243 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700244 }
245 }
246
Alex Deymo5e3ea272016-01-28 13:42:23 -0800247 LOG(INFO) << "Using this install plan:";
248 install_plan_.Dump();
249
Amin Hassani667cf7b2018-07-25 14:32:00 -0700250 HttpFetcher* fetcher = nullptr;
251 if (FileFetcher::SupportedUrl(payload_url)) {
252 DLOG(INFO) << "Using FileFetcher for file URL.";
253 fetcher = new FileFetcher();
254 } else {
255#ifdef _UE_SIDELOAD
256 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
257#else
258 LibcurlHttpFetcher* libcurl_fetcher =
259 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
260 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
261 fetcher = libcurl_fetcher;
262#endif // _UE_SIDELOAD
263 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800264 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800265 if (!headers[kPayloadPropertyAuthorization].empty())
266 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
267 if (!headers[kPayloadPropertyUserAgent].empty())
268 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
269
Amin Hassani667cf7b2018-07-25 14:32:00 -0700270 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800271
Alex Deymo5e3ea272016-01-28 13:42:23 -0800272 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700273
274 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
275 // TODO(xunchang) report the metrics for unresumable updates
276
Amin Hassani667cf7b2018-07-25 14:32:00 -0700277 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800278 return true;
279}
280
281bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700282 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800283 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
284 processor_->SuspendProcessing();
285 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800286}
287
288bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700289 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800290 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
291 processor_->ResumeProcessing();
292 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800293}
294
295bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700296 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800297 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800298 processor_->StopProcessing();
299 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800300}
301
Alex Deymo3b678db2016-02-09 11:50:06 -0800302bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
303 LOG(INFO) << "Attempting to reset state from "
304 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
305
306 switch (status_) {
307 case UpdateStatus::IDLE:
308 return true;
309
310 case UpdateStatus::UPDATED_NEED_REBOOT: {
311 // Remove the reboot marker so that if the machine is rebooted
312 // after resetting to idle state, it doesn't go back to
313 // UpdateStatus::UPDATED_NEED_REBOOT state.
314 bool ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700315 ClearMetricsPrefs();
Alex Deymo3b678db2016-02-09 11:50:06 -0800316
317 // Update the boot flags so the current slot has higher priority.
318 if (!boot_control_->SetActiveBootSlot(boot_control_->GetCurrentSlot()))
319 ret_value = false;
320
Alex Deymo52590332016-11-29 18:29:13 -0800321 // Mark the current slot as successful again, since marking it as active
322 // may reset the successful bit. We ignore the result of whether marking
323 // the current slot as successful worked.
324 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful){})))
325 ret_value = false;
326
Alex Deymo3b678db2016-02-09 11:50:06 -0800327 if (!ret_value) {
328 return LogAndSetError(
329 error,
330 FROM_HERE,
331 "Failed to reset the status to ");
332 }
333
334 SetStatusAndNotify(UpdateStatus::IDLE);
335 LOG(INFO) << "Reset status successful";
336 return true;
337 }
338
339 default:
340 return LogAndSetError(
341 error,
342 FROM_HERE,
343 "Reset not allowed in this state. Cancel the ongoing update first");
344 }
345}
346
Sen Jiang8371c1c2018-02-01 13:46:39 -0800347bool UpdateAttempterAndroid::VerifyPayloadApplicable(
348 const std::string& metadata_filename, brillo::ErrorPtr* error) {
349 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
350 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
351 return LogAndSetError(
352 error, FROM_HERE, "Failed to open " + metadata_filename);
353 }
354 brillo::Blob metadata(kMaxPayloadHeaderSize);
355 if (!fd->Read(metadata.data(), metadata.size())) {
356 return LogAndSetError(
357 error,
358 FROM_HERE,
359 "Failed to read payload header from " + metadata_filename);
360 }
361 ErrorCode errorcode;
362 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700363 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800364 MetadataParseResult::kSuccess) {
365 return LogAndSetError(error,
366 FROM_HERE,
367 "Failed to parse payload header: " +
368 utils::ErrorCodeToString(errorcode));
369 }
370 metadata.resize(payload_metadata.GetMetadataSize() +
371 payload_metadata.GetMetadataSignatureSize());
372 if (metadata.size() < kMaxPayloadHeaderSize) {
373 return LogAndSetError(
374 error,
375 FROM_HERE,
376 "Metadata size too small: " + std::to_string(metadata.size()));
377 }
378 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
379 metadata.size() - kMaxPayloadHeaderSize)) {
380 return LogAndSetError(
381 error,
382 FROM_HERE,
383 "Failed to read metadata and signature from " + metadata_filename);
384 }
385 fd->Close();
386 errorcode = payload_metadata.ValidateMetadataSignature(
387 metadata, "", base::FilePath(constants::kUpdatePayloadPublicKeyPath));
388 if (errorcode != ErrorCode::kSuccess) {
389 return LogAndSetError(error,
390 FROM_HERE,
391 "Failed to validate metadata signature: " +
392 utils::ErrorCodeToString(errorcode));
393 }
394 DeltaArchiveManifest manifest;
395 if (!payload_metadata.GetManifest(metadata, &manifest)) {
396 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
397 }
398
399 BootControlInterface::Slot current_slot = boot_control_->GetCurrentSlot();
400 for (const PartitionUpdate& partition : manifest.partitions()) {
401 if (!partition.has_old_partition_info())
402 continue;
403 string partition_path;
404 if (!boot_control_->GetPartitionDevice(
405 partition.partition_name(), current_slot, &partition_path)) {
406 return LogAndSetError(
407 error,
408 FROM_HERE,
409 "Failed to get partition device for " + partition.partition_name());
410 }
411 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
412 return LogAndSetError(
413 error, FROM_HERE, "Failed to open " + partition_path);
414 }
415 for (const InstallOperation& operation : partition.operations()) {
416 if (!operation.has_src_sha256_hash())
417 continue;
418 brillo::Blob source_hash;
419 if (!fd_utils::ReadAndHashExtents(fd,
420 operation.src_extents(),
421 manifest.block_size(),
422 &source_hash)) {
423 return LogAndSetError(
424 error, FROM_HERE, "Failed to hash " + partition_path);
425 }
426 if (!DeltaPerformer::ValidateSourceHash(
427 source_hash, operation, fd, &errorcode)) {
428 return false;
429 }
430 }
431 fd->Close();
432 }
433 return true;
434}
435
Alex Deymo5e3ea272016-01-28 13:42:23 -0800436void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
437 ErrorCode code) {
438 LOG(INFO) << "Processing Done.";
439
Alex Deymo5990bf32016-07-19 17:01:41 -0700440 switch (code) {
441 case ErrorCode::kSuccess:
442 // Update succeeded.
443 WriteUpdateCompletedMarker();
444 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800445
Alex Deymo5990bf32016-07-19 17:01:41 -0700446 LOG(INFO) << "Update successfully applied, waiting to reboot.";
447 break;
448
449 case ErrorCode::kFilesystemCopierError:
450 case ErrorCode::kNewRootfsVerificationError:
451 case ErrorCode::kNewKernelVerificationError:
452 case ErrorCode::kFilesystemVerifierError:
453 case ErrorCode::kDownloadStateInitializationError:
454 // Reset the ongoing update for these errors so it starts from the
455 // beginning next time.
456 DeltaPerformer::ResetUpdateProgress(prefs_, false);
457 LOG(INFO) << "Resetting update progress.";
458 break;
459
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700460 case ErrorCode::kPayloadTimestampError:
461 // SafetyNet logging, b/36232423
462 android_errorWriteLog(0x534e4554, "36232423");
463 break;
464
Alex Deymo5990bf32016-07-19 17:01:41 -0700465 default:
466 // Ignore all other error codes.
467 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700468 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800469
470 TerminateUpdateAndNotify(code);
471}
472
473void UpdateAttempterAndroid::ProcessingStopped(
474 const ActionProcessor* processor) {
475 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
476}
477
478void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
479 AbstractAction* action,
480 ErrorCode code) {
481 // Reset download progress regardless of whether or not the download
482 // action succeeded.
483 const string type = action->Type();
484 if (type == DownloadAction::StaticType()) {
Alex Deymo0d298542016-03-30 18:31:49 -0700485 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800486 }
Sen Jiangfe522822017-10-31 15:14:11 -0700487 if (type == PostinstallRunnerAction::StaticType()) {
488 bool succeeded =
489 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
490 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
491 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800492 if (code != ErrorCode::kSuccess) {
493 // If an action failed, the ActionProcessor will cancel the whole thing.
494 return;
495 }
496 if (type == DownloadAction::StaticType()) {
497 SetStatusAndNotify(UpdateStatus::FINALIZING);
498 }
499}
500
501void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
502 uint64_t bytes_received,
503 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700504 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800505 if (total)
506 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700507 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800508 download_progress_ = progress;
509 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700510 } else {
511 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800512 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700513
514 // Update the bytes downloaded in prefs.
515 int64_t current_bytes_downloaded =
516 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
517 int64_t total_bytes_downloaded =
518 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
519 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
520 current_bytes_downloaded + bytes_progressed);
521 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
522 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800523}
524
525bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
526 // TODO(deymo): Notify the DownloadAction that it should cancel the update
527 // download.
528 return false;
529}
530
531void UpdateAttempterAndroid::DownloadComplete() {
532 // Nothing needs to be done when the download completes.
533}
534
Alex Deymo0d298542016-03-30 18:31:49 -0700535void UpdateAttempterAndroid::ProgressUpdate(double progress) {
536 // Self throttle based on progress. Also send notifications if progress is
537 // too slow.
538 if (progress == 1.0 ||
539 progress - download_progress_ >= kBroadcastThresholdProgress ||
540 TimeTicks::Now() - last_notify_time_ >=
541 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
542 download_progress_ = progress;
543 SetStatusAndNotify(status_);
544 }
545}
546
Alex Deymo5e3ea272016-01-28 13:42:23 -0800547void UpdateAttempterAndroid::ScheduleProcessingStart() {
548 LOG(INFO) << "Scheduling an action processor start.";
549 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700550 FROM_HERE,
551 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
552 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800553}
554
555void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
556 if (status_ == UpdateStatus::IDLE) {
557 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
558 return;
559 }
560
Alex Deymo0d298542016-03-30 18:31:49 -0700561 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800562 UpdateStatus new_status =
563 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
564 : UpdateStatus::IDLE);
565 SetStatusAndNotify(new_status);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800566
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700567 // The network id is only applicable to one download attempt and once it's
568 // done the network id should not be re-used anymore.
569 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
570 LOG(WARNING) << "Unable to unbind network.";
571 }
572
Alex Deymo5e3ea272016-01-28 13:42:23 -0800573 for (auto observer : daemon_state_->service_observers())
574 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700575
Tianjie Xu90aaa102017-10-10 17:39:03 -0700576 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
577 ClearMetricsPrefs();
578 if (error_code == ErrorCode::kSuccess) {
579 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700580 // Clear the total bytes downloaded if and only if the update succeeds.
581 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700582 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800583}
584
585void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
586 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700587 size_t payload_size =
588 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700589 UpdateEngineStatus status_to_send = {.status = status_,
590 .progress = download_progress_,
591 .new_size_bytes = payload_size};
592
Alex Deymo5e3ea272016-01-28 13:42:23 -0800593 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700594 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800595 }
596 last_notify_time_ = TimeTicks::Now();
597}
598
Amin Hassani667cf7b2018-07-25 14:32:00 -0700599void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800600 CHECK(!processor_->IsRunning());
601 processor_->set_delegate(this);
602
603 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700604 auto update_boot_flags_action =
605 std::make_unique<UpdateBootFlagsAction>(boot_control_);
606 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
607 auto download_action =
608 std::make_unique<DownloadAction>(prefs_,
609 boot_control_,
610 hardware_,
611 nullptr, // system_state, not used.
612 fetcher, // passes ownership
613 true /* interactive */);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800614 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700615 download_action->set_base_offset(base_offset_);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700616 auto filesystem_verifier_action =
617 std::make_unique<FilesystemVerifierAction>();
618 auto postinstall_runner_action =
619 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Alex Deymob6eef732016-06-10 12:58:11 -0700620 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800621
Alex Deymo5e3ea272016-01-28 13:42:23 -0800622 // Bond them together. We have to use the leaf-types when calling
623 // BondActions().
624 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700625 BondActions(download_action.get(), filesystem_verifier_action.get());
626 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800627 postinstall_runner_action.get());
628
Amin Hassani667cf7b2018-07-25 14:32:00 -0700629 processor_->EnqueueAction(std::move(update_boot_flags_action));
630 processor_->EnqueueAction(std::move(install_plan_action));
631 processor_->EnqueueAction(std::move(download_action));
632 processor_->EnqueueAction(std::move(filesystem_verifier_action));
633 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800634}
635
Alex Deymo5e3ea272016-01-28 13:42:23 -0800636bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
637 string boot_id;
638 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
639 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
640 return true;
641}
642
643bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
644 // In case of an update_engine restart without a reboot, we stored the boot_id
645 // when the update was completed by setting a pref, so we can check whether
646 // the last update was on this boot or a previous one.
647 string boot_id;
648 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
649
650 string update_completed_on_boot_id;
651 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
652 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
653 &update_completed_on_boot_id) &&
654 update_completed_on_boot_id == boot_id);
655}
656
Tianjie Xu90aaa102017-10-10 17:39:03 -0700657// Collect and report the android metrics when we terminate the update.
658void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
659 ErrorCode error_code) {
660 int64_t attempt_number =
661 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
662 PayloadType payload_type = kPayloadTypeFull;
663 int64_t payload_size = 0;
664 for (const auto& p : install_plan_.payloads) {
665 if (p.type == InstallPayloadType::kDelta)
666 payload_type = kPayloadTypeDelta;
667 payload_size += p.size;
668 }
669
670 metrics::AttemptResult attempt_result =
671 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700672 Time boot_time_start = Time::FromInternalValue(
673 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
674 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700675 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700676 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
677 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700678
679 metrics_reporter_->ReportUpdateAttemptMetrics(
680 nullptr, // system_state
681 static_cast<int>(attempt_number),
682 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700683 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700684 duration_uptime,
685 payload_size,
686 attempt_result,
687 error_code);
688
Tianjie Xud4777a12017-10-24 14:54:18 -0700689 int64_t current_bytes_downloaded =
690 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
691 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
692 current_bytes_downloaded,
693 0,
694 DownloadSource::kNumDownloadSources,
695 metrics::DownloadErrorCode::kUnset,
696 metrics::ConnectionType::kUnset);
697
Tianjie Xu90aaa102017-10-10 17:39:03 -0700698 if (error_code == ErrorCode::kSuccess) {
699 int64_t reboot_count =
700 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
701 string build_version;
702 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700703
704 // For android metrics, we only care about the total bytes downloaded
705 // for all sources; for now we assume the only download source is
706 // HttpsServer.
707 int64_t total_bytes_downloaded =
708 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
709 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
710 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
711 total_bytes_downloaded;
712
713 int download_overhead_percentage = 0;
714 if (current_bytes_downloaded > 0) {
715 download_overhead_percentage =
716 (total_bytes_downloaded - current_bytes_downloaded) * 100ull /
717 current_bytes_downloaded;
718 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700719 metrics_reporter_->ReportSuccessfulUpdateMetrics(
720 static_cast<int>(attempt_number),
721 0, // update abandoned count
722 payload_type,
723 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700724 num_bytes_downloaded,
725 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700726 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700727 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700728 static_cast<int>(reboot_count),
729 0); // url_switch_count
730 }
731}
732
733void UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
734 string current_boot_id;
735 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
736 // Example: [ro.build.version.incremental]: [4292972]
737 string current_version =
738 android::base::GetProperty("ro.build.version.incremental", "");
739 TEST_AND_RETURN(!current_version.empty());
740
741 // If there's no record of previous version (e.g. due to a data wipe), we
742 // save the info of current boot and skip the metrics report.
743 if (!prefs_->Exists(kPrefsPreviousVersion)) {
744 prefs_->SetString(kPrefsBootId, current_boot_id);
745 prefs_->SetString(kPrefsPreviousVersion, current_version);
746 ClearMetricsPrefs();
747 return;
748 }
749 string previous_version;
750 // update_engine restarted under the same build.
751 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
752 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
753 previous_version == current_version) {
754 string last_boot_id;
755 bool is_reboot = prefs_->Exists(kPrefsBootId) &&
756 (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
757 last_boot_id != current_boot_id);
758 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
759 // set when we start a new update.
760 if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
761 prefs_->SetString(kPrefsBootId, current_boot_id);
762 int64_t reboot_count =
763 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
764 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
765 }
766 return;
767 }
768
769 // Now that the build version changes, report the update metrics.
770 // TODO(xunchang) check the build version is larger than the previous one.
771 prefs_->SetString(kPrefsBootId, current_boot_id);
772 prefs_->SetString(kPrefsPreviousVersion, current_version);
773
774 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
775 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
776 if (previous_attempt_exists) {
777 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
778 }
779
780 metrics_utils::LoadAndReportTimeToReboot(
781 metrics_reporter_.get(), prefs_, clock_.get());
782 ClearMetricsPrefs();
783}
784
785// Save the update start time. Reset the reboot count and attempt number if the
786// update isn't a resume; otherwise increment the attempt number.
787void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
788 if (!is_resume) {
789 metrics_utils::SetNumReboots(0, prefs_);
790 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
791 } else {
792 int64_t attempt_number =
793 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
794 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
795 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700796 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
797 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700798}
799
800void UpdateAttempterAndroid::ClearMetricsPrefs() {
801 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700802 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700803 prefs_->Delete(kPrefsNumReboots);
804 prefs_->Delete(kPrefsPayloadAttemptNumber);
805 prefs_->Delete(kPrefsSystemUpdatedMarker);
806 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700807 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700808}
809
Alex Deymo5e3ea272016-01-28 13:42:23 -0800810} // namespace chromeos_update_engine