blob: 1080acbaf144d6b4a4b21cab422c21ba7ad7c3a9 [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
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/aosp/update_attempter_android.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080018
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>
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090025#include <android-base/unique_fd.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080026#include <base/bind.h>
27#include <base/logging.h>
Alex Deymo218397f2016-02-04 23:55:10 -080028#include <base/strings/string_number_conversions.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
Amin Hassaniec7bc112020-10-29 16:47:58 -070034#include "update_engine/aosp/cleanup_previous_update_action.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080035#include "update_engine/common/constants.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070036#include "update_engine/common/daemon_state_interface.h"
37#include "update_engine/common/download_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080038#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070039#include "update_engine/common/file_fetcher.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070040#include "update_engine/common/metrics_reporter_interface.h"
41#include "update_engine/common/network_selector.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080042#include "update_engine/common/utils.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070043#include "update_engine/metrics_utils.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070044#include "update_engine/payload_consumer/certificate_parser_interface.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080045#include "update_engine/payload_consumer/delta_performer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080046#include "update_engine/payload_consumer/file_descriptor.h"
47#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080048#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080049#include "update_engine/payload_consumer/payload_constants.h"
50#include "update_engine/payload_consumer/payload_metadata.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070051#include "update_engine/payload_consumer/payload_verifier.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080052#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070053#include "update_engine/update_boot_flags_action.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080054#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080055
Alex Deymo14c0da82016-07-20 16:45:45 -070056#ifndef _UE_SIDELOAD
57// Do not include support for external HTTP(s) urls when building
58// update_engine_sideload.
59#include "update_engine/libcurl_http_fetcher.h"
60#endif
61
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090062using android::base::unique_fd;
Alex Deymo5e3ea272016-01-28 13:42:23 -080063using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070064using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080065using base::TimeDelta;
66using base::TimeTicks;
67using std::shared_ptr;
68using std::string;
69using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070070using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080071
72namespace chromeos_update_engine {
73
74namespace {
75
Alex Deymo0d298542016-03-30 18:31:49 -070076// Minimum threshold to broadcast an status update in progress and time.
77const double kBroadcastThresholdProgress = 0.01; // 1%
78const int kBroadcastThresholdSeconds = 10;
79
Alex Deymo5e3ea272016-01-28 13:42:23 -080080const char* const kErrorDomain = "update_engine";
81// TODO(deymo): Convert the different errors to a numeric value to report them
82// back on the service error.
83const char* const kGenericError = "generic_error";
84
85// Log and set the error on the passed ErrorPtr.
86bool LogAndSetError(brillo::ErrorPtr* error,
Jakub Pawlowski7e1dcf72018-07-26 00:29:42 -070087 const base::Location& location,
Alex Deymo5e3ea272016-01-28 13:42:23 -080088 const string& reason) {
89 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
90 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
91 << reason;
92 return false;
93}
94
Sen Jiangfe522822017-10-31 15:14:11 -070095bool GetHeaderAsBool(const string& header, bool default_value) {
96 int value = 0;
97 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
98 return value == 1;
99 return default_value;
100}
101
Yifan Hongbd47d622019-12-13 14:59:58 -0800102bool ParseKeyValuePairHeaders(const vector<string>& key_value_pair_headers,
103 std::map<string, string>* headers,
104 brillo::ErrorPtr* error) {
105 for (const string& key_value_pair : key_value_pair_headers) {
106 string key;
107 string value;
108 if (!brillo::string_utils::SplitAtFirst(
109 key_value_pair, "=", &key, &value, false)) {
110 return LogAndSetError(
111 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
112 }
113 if (!headers->emplace(key, value).second)
114 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
115 }
116 return true;
117}
118
119// Unique identifier for the payload. An empty string means that the payload
120// can't be resumed.
121string GetPayloadId(const std::map<string, string>& headers) {
122 return (headers.count(kPayloadPropertyFileHash)
123 ? headers.at(kPayloadPropertyFileHash)
124 : "") +
125 (headers.count(kPayloadPropertyMetadataHash)
126 ? headers.at(kPayloadPropertyMetadataHash)
127 : "");
128}
129
Alex Deymo5e3ea272016-01-28 13:42:23 -0800130} // namespace
131
132UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700133 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800134 PrefsInterface* prefs,
135 BootControlInterface* boot_control,
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000136 HardwareInterface* hardware,
137 std::unique_ptr<ApexHandlerInterface> apex_handler)
Alex Deymo5e3ea272016-01-28 13:42:23 -0800138 : daemon_state_(daemon_state),
139 prefs_(prefs),
140 boot_control_(boot_control),
141 hardware_(hardware),
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000142 apex_handler_android_(std::move(apex_handler)),
Tianjie Xu1b661142017-09-28 14:03:42 -0700143 processor_(new ActionProcessor()),
Tianjie Xud4c5deb2017-10-24 11:17:03 -0700144 clock_(new Clock()) {
Yifan Hongc514f662021-02-04 11:18:43 -0800145 metrics_reporter_ = metrics::CreateMetricsReporter(
146 boot_control_->GetDynamicPartitionControl());
Alex Deymo87792ea2016-07-25 15:40:36 -0700147 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800148}
149
150UpdateAttempterAndroid::~UpdateAttempterAndroid() {
151 // Release ourselves as the ActionProcessor's delegate to prevent
152 // re-scheduling the updates due to the processing stopped.
153 processor_->set_delegate(nullptr);
154}
155
156void UpdateAttempterAndroid::Init() {
157 // In case of update_engine restart without a reboot we need to restore the
158 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700159 if (UpdateCompletedOnThisBoot()) {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800160 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700161 } else {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800162 SetStatusAndNotify(UpdateStatus::IDLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700163 UpdatePrefsAndReportUpdateMetricsOnReboot();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700164#ifdef _UE_SIDELOAD
165 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
166 << "ApplyPayload will call it later.";
167#else
Yifan Hong90965502020-02-19 15:22:47 -0800168 ScheduleCleanupPreviousUpdate();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700169#endif
Tianjie Xu90aaa102017-10-10 17:39:03 -0700170 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800171}
172
173bool UpdateAttempterAndroid::ApplyPayload(
174 const string& payload_url,
175 int64_t payload_offset,
176 int64_t payload_size,
177 const vector<string>& key_value_pair_headers,
178 brillo::ErrorPtr* error) {
179 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
180 return LogAndSetError(
181 error, FROM_HERE, "An update already applied, waiting for reboot");
182 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700183 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800184 return LogAndSetError(
185 error, FROM_HERE, "Already processing an update, cancel it first.");
186 }
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100187 DCHECK_EQ(status_, UpdateStatus::IDLE);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800188
Alex Deymo218397f2016-02-04 23:55:10 -0800189 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800190 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
191 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800192 }
193
Yifan Hongbd47d622019-12-13 14:59:58 -0800194 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800195
196 // Setup the InstallPlan based on the request.
197 install_plan_ = InstallPlan();
198
199 install_plan_.download_url = payload_url;
200 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800201 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800202 InstallPlan::Payload payload;
203 payload.size = payload_size;
204 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800205 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800206 &payload.size)) {
207 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800208 }
209 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700210 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800211 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700212 LOG(WARNING) << "Unable to decode base64 file hash: "
213 << headers[kPayloadPropertyFileHash];
214 }
Alex Deymo218397f2016-02-04 23:55:10 -0800215 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800216 &payload.metadata_size)) {
217 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800218 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700219 // The |payload.type| is not used anymore since minor_version 3.
220 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800221 install_plan_.payloads.push_back(payload);
222
Alex Deymo5e3ea272016-01-28 13:42:23 -0800223 // The |public_key_rsa| key would override the public key stored on disk.
224 install_plan_.public_key_rsa = "";
225
226 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
227 install_plan_.is_resume = !payload_id.empty() &&
228 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
229 if (!install_plan_.is_resume) {
Yifan Hong55c2bfe2020-01-13 17:01:19 -0800230 // No need to reset dynamic_partititon_metadata_updated. If previous calls
231 // to AllocateSpaceForPayload uses the same payload_id, reuse preallocated
232 // space. Otherwise, DeltaPerformer re-allocates space when the payload is
233 // applied.
234 if (!DeltaPerformer::ResetUpdateProgress(
235 prefs_,
236 false /* quick */,
237 true /* skip_dynamic_partititon_metadata_updated */)) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800238 LOG(WARNING) << "Unable to reset the update progress.";
239 }
240 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
241 LOG(WARNING) << "Unable to save the update check response hash.";
242 }
243 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800244 install_plan_.source_slot = GetCurrentSlot();
245 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700246
Alex Deymofb905d92016-06-03 19:26:58 -0700247 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700248 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
249
250 install_plan_.switch_slot_on_reboot =
251 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
252
Tianjie Xu087de9d2019-11-01 17:11:22 -0700253 install_plan_.run_post_install =
254 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800255
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700256 // Skip writing verity if we're resuming and verity has already been written.
257 install_plan_.write_verity = true;
258 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
259 bool verity_written = false;
260 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
261 verity_written) {
262 install_plan_.write_verity = false;
263 }
264 }
265
Alex Deymo87792ea2016-07-25 15:40:36 -0700266 NetworkId network_id = kDefaultNetworkId;
267 if (!headers[kPayloadPropertyNetworkId].empty()) {
268 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
269 &network_id)) {
270 return LogAndSetError(
271 error,
272 FROM_HERE,
273 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
274 }
275 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700276 return LogAndSetError(
277 error,
278 FROM_HERE,
279 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700280 }
281 }
282
Alex Deymo5e3ea272016-01-28 13:42:23 -0800283 LOG(INFO) << "Using this install plan:";
284 install_plan_.Dump();
285
Amin Hassani667cf7b2018-07-25 14:32:00 -0700286 HttpFetcher* fetcher = nullptr;
287 if (FileFetcher::SupportedUrl(payload_url)) {
288 DLOG(INFO) << "Using FileFetcher for file URL.";
289 fetcher = new FileFetcher();
290 } else {
291#ifdef _UE_SIDELOAD
292 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
293#else
294 LibcurlHttpFetcher* libcurl_fetcher =
295 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
296 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
297 fetcher = libcurl_fetcher;
298#endif // _UE_SIDELOAD
299 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800300 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800301 if (!headers[kPayloadPropertyAuthorization].empty())
302 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
303 if (!headers[kPayloadPropertyUserAgent].empty())
304 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
305
Amin Hassani667cf7b2018-07-25 14:32:00 -0700306 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800307
Alex Deymo5e3ea272016-01-28 13:42:23 -0800308 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700309
310 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
311 // TODO(xunchang) report the metrics for unresumable updates
312
Amin Hassani667cf7b2018-07-25 14:32:00 -0700313 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800314 return true;
315}
316
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900317bool UpdateAttempterAndroid::ApplyPayload(
318 int fd,
319 int64_t payload_offset,
320 int64_t payload_size,
321 const vector<string>& key_value_pair_headers,
322 brillo::ErrorPtr* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100323 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000324 // already running update will be terminated (existing file descriptor will be
325 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100326 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
327 return LogAndSetError(
328 error, FROM_HERE, "An update already applied, waiting for reboot");
329 }
330 if (processor_->IsRunning()) {
331 return LogAndSetError(
332 error, FROM_HERE, "Already processing an update, cancel it first.");
333 }
334 DCHECK_EQ(status_, UpdateStatus::IDLE);
335
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900336 payload_fd_.reset(dup(fd));
337 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
338
339 return ApplyPayload(
340 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
341}
342
Alex Deymo5e3ea272016-01-28 13:42:23 -0800343bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700344 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800345 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
346 processor_->SuspendProcessing();
347 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800348}
349
350bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700351 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800352 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
353 processor_->ResumeProcessing();
354 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800355}
356
357bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700358 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800359 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800360 processor_->StopProcessing();
361 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800362}
363
Alex Deymo3b678db2016-02-09 11:50:06 -0800364bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
365 LOG(INFO) << "Attempting to reset state from "
366 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
367
368 switch (status_) {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700369 case UpdateStatus::IDLE: {
370 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
371 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
372 << "space might not be freed.";
373 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800374 return true;
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700375 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800376
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800377 case UpdateStatus::UPDATED_NEED_REBOOT: {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700378 bool ret_value = true;
Alex Deymo3b678db2016-02-09 11:50:06 -0800379
380 // Update the boot flags so the current slot has higher priority.
Yifan Hongbd47d622019-12-13 14:59:58 -0800381 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot()))
Alex Deymo3b678db2016-02-09 11:50:06 -0800382 ret_value = false;
383
Alex Deymo52590332016-11-29 18:29:13 -0800384 // Mark the current slot as successful again, since marking it as active
385 // may reset the successful bit. We ignore the result of whether marking
386 // the current slot as successful worked.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800387 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {})))
Alex Deymo52590332016-11-29 18:29:13 -0800388 ret_value = false;
389
Tianjie Xud6aa91f2019-11-14 11:55:10 -0800390 // Resets the warm reset property since we won't switch the slot.
391 hardware_->SetWarmReset(false);
392
Tianjie838793d2021-01-14 22:05:13 -0800393 // Resets the vbmeta digest.
394 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
395
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700396 // Remove update progress for DeltaPerformer and remove snapshots.
397 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_))
398 ret_value = false;
399
400 // Remove the reboot marker so that if the machine is rebooted
401 // after resetting to idle state, it doesn't go back to
402 // UpdateStatus::UPDATED_NEED_REBOOT state.
403 if (!prefs_->Delete(kPrefsUpdateCompletedOnBootId))
404 ret_value = false;
405 ClearMetricsPrefs();
406
Alex Deymo3b678db2016-02-09 11:50:06 -0800407 if (!ret_value) {
408 return LogAndSetError(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800409 error, FROM_HERE, "Failed to reset the status to ");
Alex Deymo3b678db2016-02-09 11:50:06 -0800410 }
411
412 SetStatusAndNotify(UpdateStatus::IDLE);
413 LOG(INFO) << "Reset status successful";
414 return true;
415 }
416
417 default:
418 return LogAndSetError(
419 error,
420 FROM_HERE,
421 "Reset not allowed in this state. Cancel the ongoing update first");
422 }
423}
424
Yifan Hongbd47d622019-12-13 14:59:58 -0800425bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
426 const std::string& metadata_filename,
427 DeltaArchiveManifest* manifest,
428 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800429 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
430 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
431 return LogAndSetError(
432 error, FROM_HERE, "Failed to open " + metadata_filename);
433 }
434 brillo::Blob metadata(kMaxPayloadHeaderSize);
435 if (!fd->Read(metadata.data(), metadata.size())) {
436 return LogAndSetError(
437 error,
438 FROM_HERE,
439 "Failed to read payload header from " + metadata_filename);
440 }
441 ErrorCode errorcode;
442 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700443 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800444 MetadataParseResult::kSuccess) {
445 return LogAndSetError(error,
446 FROM_HERE,
447 "Failed to parse payload header: " +
448 utils::ErrorCodeToString(errorcode));
449 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700450 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
451 payload_metadata.GetMetadataSignatureSize();
452 if (metadata_size < kMaxPayloadHeaderSize ||
453 metadata_size >
454 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800455 return LogAndSetError(
456 error,
457 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700458 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800459 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700460 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800461 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
462 metadata.size() - kMaxPayloadHeaderSize)) {
463 return LogAndSetError(
464 error,
465 FROM_HERE,
466 "Failed to read metadata and signature from " + metadata_filename);
467 }
468 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800469
Tianjie Xu7a78d632019-10-08 16:32:39 -0700470 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
471 constants::kUpdateCertificatesPath);
472 if (!payload_verifier) {
473 return LogAndSetError(error,
474 FROM_HERE,
475 "Failed to create the payload verifier from " +
476 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800477 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700478 errorcode = payload_metadata.ValidateMetadataSignature(
479 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800480 if (errorcode != ErrorCode::kSuccess) {
481 return LogAndSetError(error,
482 FROM_HERE,
483 "Failed to validate metadata signature: " +
484 utils::ErrorCodeToString(errorcode));
485 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800486 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800487 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
488 }
489
Yifan Hongbd47d622019-12-13 14:59:58 -0800490 return true;
491}
492
493bool UpdateAttempterAndroid::VerifyPayloadApplicable(
494 const std::string& metadata_filename, brillo::ErrorPtr* error) {
495 DeltaArchiveManifest manifest;
496 TEST_AND_RETURN_FALSE(
497 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
498
499 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
500 ErrorCode errorcode;
501
502 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800503 for (const PartitionUpdate& partition : manifest.partitions()) {
504 if (!partition.has_old_partition_info())
505 continue;
506 string partition_path;
507 if (!boot_control_->GetPartitionDevice(
508 partition.partition_name(), current_slot, &partition_path)) {
509 return LogAndSetError(
510 error,
511 FROM_HERE,
512 "Failed to get partition device for " + partition.partition_name());
513 }
514 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
515 return LogAndSetError(
516 error, FROM_HERE, "Failed to open " + partition_path);
517 }
518 for (const InstallOperation& operation : partition.operations()) {
519 if (!operation.has_src_sha256_hash())
520 continue;
521 brillo::Blob source_hash;
522 if (!fd_utils::ReadAndHashExtents(fd,
523 operation.src_extents(),
524 manifest.block_size(),
525 &source_hash)) {
526 return LogAndSetError(
527 error, FROM_HERE, "Failed to hash " + partition_path);
528 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400529 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800530 source_hash, operation, fd, &errorcode)) {
531 return false;
532 }
533 }
534 fd->Close();
535 }
536 return true;
537}
538
Alex Deymo5e3ea272016-01-28 13:42:23 -0800539void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
540 ErrorCode code) {
541 LOG(INFO) << "Processing Done.";
542
Yifan Hong90965502020-02-19 15:22:47 -0800543 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
544 TerminateUpdateAndNotify(code);
545 return;
546 }
547
Alex Deymo5990bf32016-07-19 17:01:41 -0700548 switch (code) {
549 case ErrorCode::kSuccess:
550 // Update succeeded.
551 WriteUpdateCompletedMarker();
552 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800553
Alex Deymo5990bf32016-07-19 17:01:41 -0700554 LOG(INFO) << "Update successfully applied, waiting to reboot.";
555 break;
556
557 case ErrorCode::kFilesystemCopierError:
558 case ErrorCode::kNewRootfsVerificationError:
559 case ErrorCode::kNewKernelVerificationError:
560 case ErrorCode::kFilesystemVerifierError:
561 case ErrorCode::kDownloadStateInitializationError:
562 // Reset the ongoing update for these errors so it starts from the
563 // beginning next time.
564 DeltaPerformer::ResetUpdateProgress(prefs_, false);
565 LOG(INFO) << "Resetting update progress.";
566 break;
567
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700568 case ErrorCode::kPayloadTimestampError:
569 // SafetyNet logging, b/36232423
570 android_errorWriteLog(0x534e4554, "36232423");
571 break;
572
Alex Deymo5990bf32016-07-19 17:01:41 -0700573 default:
574 // Ignore all other error codes.
575 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700576 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800577
578 TerminateUpdateAndNotify(code);
579}
580
581void UpdateAttempterAndroid::ProcessingStopped(
582 const ActionProcessor* processor) {
583 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
584}
585
586void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
587 AbstractAction* action,
588 ErrorCode code) {
589 // Reset download progress regardless of whether or not the download
590 // action succeeded.
591 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800592 if (type == CleanupPreviousUpdateAction::StaticType() ||
593 (type == NoOpAction::StaticType() &&
594 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
595 cleanup_previous_update_code_ = code;
596 NotifyCleanupPreviousUpdateCallbacksAndClear();
597 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000598 // download_progress_ is actually used by other actions, such as
599 // filesystem_verify_action. Therefore we always clear it.
600 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700601 if (type == PostinstallRunnerAction::StaticType()) {
602 bool succeeded =
603 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
604 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
605 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800606 if (code != ErrorCode::kSuccess) {
607 // If an action failed, the ActionProcessor will cancel the whole thing.
608 return;
609 }
Yifan Hong83517502020-02-19 15:34:13 -0800610 if (type == UpdateBootFlagsAction::StaticType()) {
611 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
612 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800613 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400614 auto download_action = static_cast<DownloadAction*>(action);
615 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000616 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700617 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000618 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700619 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800620 }
621}
622
623void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
624 uint64_t bytes_received,
625 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700626 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800627 if (total)
628 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700629 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800630 download_progress_ = progress;
631 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700632 } else {
633 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800634 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700635
636 // Update the bytes downloaded in prefs.
637 int64_t current_bytes_downloaded =
638 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
639 int64_t total_bytes_downloaded =
640 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
641 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
642 current_bytes_downloaded + bytes_progressed);
643 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
644 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800645}
646
647bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
648 // TODO(deymo): Notify the DownloadAction that it should cancel the update
649 // download.
650 return false;
651}
652
653void UpdateAttempterAndroid::DownloadComplete() {
654 // Nothing needs to be done when the download completes.
655}
656
Alex Deymo0d298542016-03-30 18:31:49 -0700657void UpdateAttempterAndroid::ProgressUpdate(double progress) {
658 // Self throttle based on progress. Also send notifications if progress is
659 // too slow.
660 if (progress == 1.0 ||
661 progress - download_progress_ >= kBroadcastThresholdProgress ||
662 TimeTicks::Now() - last_notify_time_ >=
663 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
664 download_progress_ = progress;
665 SetStatusAndNotify(status_);
666 }
667}
668
Kelvin Zhang70eef232020-06-12 20:32:40 +0000669void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
670 assert(status_ == UpdateStatus::VERIFYING);
671 ProgressUpdate(progress);
672}
673
Alex Deymo5e3ea272016-01-28 13:42:23 -0800674void UpdateAttempterAndroid::ScheduleProcessingStart() {
675 LOG(INFO) << "Scheduling an action processor start.";
676 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700677 FROM_HERE,
678 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
679 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800680}
681
682void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
683 if (status_ == UpdateStatus::IDLE) {
684 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
685 return;
686 }
687
Yifan Hong90965502020-02-19 15:22:47 -0800688 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
689 LOG(INFO) << "Terminating cleanup previous update.";
690 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700691 for (auto observer : daemon_state_->service_observers())
692 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800693 return;
694 }
695
Yifan Hong9194ce82019-11-07 11:03:42 -0800696 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700697
Alex Deymo0d298542016-03-30 18:31:49 -0700698 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800699 UpdateStatus new_status =
700 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
701 : UpdateStatus::IDLE);
702 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900703 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800704
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700705 // The network id is only applicable to one download attempt and once it's
706 // done the network id should not be re-used anymore.
707 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
708 LOG(WARNING) << "Unable to unbind network.";
709 }
710
Alex Deymo5e3ea272016-01-28 13:42:23 -0800711 for (auto observer : daemon_state_->service_observers())
712 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700713
Tianjie Xu90aaa102017-10-10 17:39:03 -0700714 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
715 ClearMetricsPrefs();
716 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800717 // We should only reset the PayloadAttemptNumber if the update succeeds, or
718 // we switch to a different payload.
719 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700720 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700721 // Clear the total bytes downloaded if and only if the update succeeds.
722 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700723 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800724}
725
726void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
727 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700728 size_t payload_size =
729 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700730 UpdateEngineStatus status_to_send = {.status = status_,
731 .progress = download_progress_,
732 .new_size_bytes = payload_size};
733
Alex Deymo5e3ea272016-01-28 13:42:23 -0800734 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700735 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800736 }
737 last_notify_time_ = TimeTicks::Now();
738}
739
Amin Hassani667cf7b2018-07-25 14:32:00 -0700740void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800741 CHECK(!processor_->IsRunning());
742 processor_->set_delegate(this);
743
744 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700745 auto update_boot_flags_action =
746 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800747 auto cleanup_previous_update_action =
748 boot_control_->GetDynamicPartitionControl()
749 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700750 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
751 auto download_action =
752 std::make_unique<DownloadAction>(prefs_,
753 boot_control_,
754 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700755 fetcher, // passes ownership
756 true /* interactive */);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800757 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700758 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700759 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
760 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700761 auto postinstall_runner_action =
762 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000763 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700764 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800765
Alex Deymo5e3ea272016-01-28 13:42:23 -0800766 // Bond them together. We have to use the leaf-types when calling
767 // BondActions().
768 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700769 BondActions(download_action.get(), filesystem_verifier_action.get());
770 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800771 postinstall_runner_action.get());
772
Amin Hassani667cf7b2018-07-25 14:32:00 -0700773 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800774 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700775 processor_->EnqueueAction(std::move(install_plan_action));
776 processor_->EnqueueAction(std::move(download_action));
777 processor_->EnqueueAction(std::move(filesystem_verifier_action));
778 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800779}
780
Alex Deymo5e3ea272016-01-28 13:42:23 -0800781bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
782 string boot_id;
783 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
784 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
785 return true;
786}
787
788bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
789 // In case of an update_engine restart without a reboot, we stored the boot_id
790 // when the update was completed by setting a pref, so we can check whether
791 // the last update was on this boot or a previous one.
792 string boot_id;
793 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
794
795 string update_completed_on_boot_id;
796 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
797 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
798 &update_completed_on_boot_id) &&
799 update_completed_on_boot_id == boot_id);
800}
801
Tianjie Xu90aaa102017-10-10 17:39:03 -0700802// Collect and report the android metrics when we terminate the update.
803void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
804 ErrorCode error_code) {
805 int64_t attempt_number =
806 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
807 PayloadType payload_type = kPayloadTypeFull;
808 int64_t payload_size = 0;
809 for (const auto& p : install_plan_.payloads) {
810 if (p.type == InstallPayloadType::kDelta)
811 payload_type = kPayloadTypeDelta;
812 payload_size += p.size;
813 }
814
815 metrics::AttemptResult attempt_result =
816 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700817 Time boot_time_start = Time::FromInternalValue(
818 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
819 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700820 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700821 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
822 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700823
824 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700825 static_cast<int>(attempt_number),
826 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700827 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700828 duration_uptime,
829 payload_size,
830 attempt_result,
831 error_code);
832
Tianjie Xud4777a12017-10-24 14:54:18 -0700833 int64_t current_bytes_downloaded =
834 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
835 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
836 current_bytes_downloaded,
837 0,
838 DownloadSource::kNumDownloadSources,
839 metrics::DownloadErrorCode::kUnset,
840 metrics::ConnectionType::kUnset);
841
Tianjie Xu90aaa102017-10-10 17:39:03 -0700842 if (error_code == ErrorCode::kSuccess) {
843 int64_t reboot_count =
844 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
845 string build_version;
846 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700847
848 // For android metrics, we only care about the total bytes downloaded
849 // for all sources; for now we assume the only download source is
850 // HttpsServer.
851 int64_t total_bytes_downloaded =
852 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
853 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
854 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
855 total_bytes_downloaded;
856
857 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700858 if (total_bytes_downloaded >= payload_size) {
859 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700860 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700861 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
862 } else {
863 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
864 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700865 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700866
Tianjie Xu90aaa102017-10-10 17:39:03 -0700867 metrics_reporter_->ReportSuccessfulUpdateMetrics(
868 static_cast<int>(attempt_number),
869 0, // update abandoned count
870 payload_type,
871 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700872 num_bytes_downloaded,
873 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700874 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700875 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700876 static_cast<int>(reboot_count),
877 0); // url_switch_count
878 }
879}
880
881void UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
882 string current_boot_id;
883 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
884 // Example: [ro.build.version.incremental]: [4292972]
885 string current_version =
886 android::base::GetProperty("ro.build.version.incremental", "");
887 TEST_AND_RETURN(!current_version.empty());
888
889 // If there's no record of previous version (e.g. due to a data wipe), we
890 // save the info of current boot and skip the metrics report.
891 if (!prefs_->Exists(kPrefsPreviousVersion)) {
892 prefs_->SetString(kPrefsBootId, current_boot_id);
893 prefs_->SetString(kPrefsPreviousVersion, current_version);
894 ClearMetricsPrefs();
895 return;
896 }
897 string previous_version;
898 // update_engine restarted under the same build.
899 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
900 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
901 previous_version == current_version) {
902 string last_boot_id;
903 bool is_reboot = prefs_->Exists(kPrefsBootId) &&
904 (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
905 last_boot_id != current_boot_id);
906 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
907 // set when we start a new update.
908 if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
909 prefs_->SetString(kPrefsBootId, current_boot_id);
910 int64_t reboot_count =
911 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
912 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
913 }
914 return;
915 }
916
917 // Now that the build version changes, report the update metrics.
918 // TODO(xunchang) check the build version is larger than the previous one.
919 prefs_->SetString(kPrefsBootId, current_boot_id);
920 prefs_->SetString(kPrefsPreviousVersion, current_version);
921
922 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
923 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
924 if (previous_attempt_exists) {
925 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
926 }
927
928 metrics_utils::LoadAndReportTimeToReboot(
929 metrics_reporter_.get(), prefs_, clock_.get());
930 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -0800931
932 // Also reset the update progress if the build version has changed.
933 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
934 LOG(WARNING) << "Unable to reset the update progress.";
935 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700936}
937
938// Save the update start time. Reset the reboot count and attempt number if the
939// update isn't a resume; otherwise increment the attempt number.
940void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
941 if (!is_resume) {
942 metrics_utils::SetNumReboots(0, prefs_);
943 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
944 } else {
945 int64_t attempt_number =
946 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
947 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
948 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700949 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
950 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700951}
952
953void UpdateAttempterAndroid::ClearMetricsPrefs() {
954 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700955 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700956 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700957 prefs_->Delete(kPrefsSystemUpdatedMarker);
958 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700959 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700960}
961
Yifan Hongbd47d622019-12-13 14:59:58 -0800962BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
963 return boot_control_->GetCurrentSlot();
964}
965
966BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
967 return GetCurrentSlot() == 0 ? 1 : 0;
968}
969
Yifan Hong6f7e29f2019-12-13 14:41:06 -0800970uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
971 const std::string& metadata_filename,
972 const vector<string>& key_value_pair_headers,
973 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -0800974 DeltaArchiveManifest manifest;
975 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
976 return 0;
977 }
978 std::map<string, string> headers;
979 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
980 return 0;
981 }
982
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000983 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
984 manifest.apex_info().end());
985 uint64_t apex_size_required = 0;
986 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000987 auto result = apex_handler_android_->CalculateSize(apex_infos);
988 if (!result.ok()) {
989 LogAndSetError(error,
990 FROM_HERE,
991 "Failed to calculate size required for compressed APEX");
992 return 0;
993 }
994 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000995 }
996
Yifan Hong65613032020-01-09 17:52:13 -0800997 string payload_id = GetPayloadId(headers);
998 uint64_t required_size = 0;
999 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1000 boot_control_,
1001 GetTargetSlot(),
1002 manifest,
1003 payload_id,
1004 &required_size)) {
1005 if (required_size == 0) {
1006 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
1007 return 0;
1008 } else {
1009 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001010 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001011 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001012 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001013 }
1014 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001015
1016 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001017 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001018 LOG(ERROR) << "Insufficient space for apex decompression: "
1019 << apex_size_required << " bytes";
1020 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001021 }
Yifan Hong65613032020-01-09 17:52:13 -08001022
1023 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001024 return 0;
1025}
1026
Yifan Hong40bb0d02020-02-24 17:33:14 -08001027void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1028 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Yifan Hong2236ea02019-12-13 16:11:22 -08001029 brillo::ErrorPtr* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001030 if (cleanup_previous_update_code_.has_value()) {
1031 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1032 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1033 if (callback) {
1034 callback->OnCleanupComplete(
1035 static_cast<int32_t>(*cleanup_previous_update_code_));
1036 }
1037 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001038 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001039 if (callback) {
1040 auto callback_ptr = callback.get();
1041 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1042 callback_ptr->RegisterForDeathNotifications(
1043 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1044 base::Unretained(this),
1045 base::Unretained(callback_ptr)));
1046 }
1047 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001048}
1049
Yifan Hong90965502020-02-19 15:22:47 -08001050void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1051 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1052 // is in progress, skip enqueueing the action.
1053 if (processor_->IsRunning()) {
1054 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1055 << "be done when the current update finishes.";
1056 return;
1057 }
1058 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1059 auto action =
1060 boot_control_->GetDynamicPartitionControl()
1061 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1062 processor_->EnqueueAction(std::move(action));
1063 processor_->set_delegate(this);
1064 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1065 processor_->StartProcessing();
1066}
1067
Yifan Hong40bb0d02020-02-24 17:33:14 -08001068void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1069 for (auto&& callback : cleanup_previous_update_callbacks_) {
1070 callback->OnCleanupProgressUpdate(progress);
1071 }
1072}
1073
1074void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1075 CHECK(cleanup_previous_update_code_.has_value());
1076 for (auto&& callback : cleanup_previous_update_callbacks_) {
1077 callback->OnCleanupComplete(
1078 static_cast<int32_t>(*cleanup_previous_update_code_));
1079 }
1080 cleanup_previous_update_callbacks_.clear();
1081}
1082
1083void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1084 CleanupSuccessfulUpdateCallbackInterface* callback) {
1085 auto end_it =
1086 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1087 cleanup_previous_update_callbacks_.end(),
1088 [&](const auto& e) { return e.get() == callback; });
1089 cleanup_previous_update_callbacks_.erase(
1090 end_it, cleanup_previous_update_callbacks_.end());
1091}
Yifan Hong90965502020-02-19 15:22:47 -08001092
Alex Deymo5e3ea272016-01-28 13:42:23 -08001093} // namespace chromeos_update_engine