blob: ba61f255a2c7b993480d259aac2655dadd26f661 [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;
Alex Deymo5e3ea272016-01-28 13:42:23 -080067using std::string;
68using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070069using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080070
71namespace chromeos_update_engine {
72
73namespace {
74
Alex Deymo0d298542016-03-30 18:31:49 -070075// Minimum threshold to broadcast an status update in progress and time.
76const double kBroadcastThresholdProgress = 0.01; // 1%
77const int kBroadcastThresholdSeconds = 10;
78
Alex Deymo5e3ea272016-01-28 13:42:23 -080079const char* const kErrorDomain = "update_engine";
80// TODO(deymo): Convert the different errors to a numeric value to report them
81// back on the service error.
82const char* const kGenericError = "generic_error";
83
84// Log and set the error on the passed ErrorPtr.
85bool LogAndSetError(brillo::ErrorPtr* error,
Jakub Pawlowski7e1dcf72018-07-26 00:29:42 -070086 const base::Location& location,
Alex Deymo5e3ea272016-01-28 13:42:23 -080087 const string& reason) {
88 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
89 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
90 << reason;
91 return false;
92}
93
Sen Jiangfe522822017-10-31 15:14:11 -070094bool GetHeaderAsBool(const string& header, bool default_value) {
95 int value = 0;
96 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
97 return value == 1;
98 return default_value;
99}
100
Yifan Hongbd47d622019-12-13 14:59:58 -0800101bool ParseKeyValuePairHeaders(const vector<string>& key_value_pair_headers,
102 std::map<string, string>* headers,
103 brillo::ErrorPtr* error) {
104 for (const string& key_value_pair : key_value_pair_headers) {
105 string key;
106 string value;
107 if (!brillo::string_utils::SplitAtFirst(
108 key_value_pair, "=", &key, &value, false)) {
109 return LogAndSetError(
110 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
111 }
112 if (!headers->emplace(key, value).second)
113 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
114 }
115 return true;
116}
117
118// Unique identifier for the payload. An empty string means that the payload
119// can't be resumed.
120string GetPayloadId(const std::map<string, string>& headers) {
121 return (headers.count(kPayloadPropertyFileHash)
122 ? headers.at(kPayloadPropertyFileHash)
123 : "") +
124 (headers.count(kPayloadPropertyMetadataHash)
125 ? headers.at(kPayloadPropertyMetadataHash)
126 : "");
127}
128
Alex Deymo5e3ea272016-01-28 13:42:23 -0800129} // namespace
130
131UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700132 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800133 PrefsInterface* prefs,
134 BootControlInterface* boot_control,
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000135 HardwareInterface* hardware,
136 std::unique_ptr<ApexHandlerInterface> apex_handler)
Alex Deymo5e3ea272016-01-28 13:42:23 -0800137 : daemon_state_(daemon_state),
138 prefs_(prefs),
139 boot_control_(boot_control),
140 hardware_(hardware),
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000141 apex_handler_android_(std::move(apex_handler)),
Tianjie Xu1b661142017-09-28 14:03:42 -0700142 processor_(new ActionProcessor()),
Tianjie Xud4c5deb2017-10-24 11:17:03 -0700143 clock_(new Clock()) {
Yifan Hongc514f662021-02-04 11:18:43 -0800144 metrics_reporter_ = metrics::CreateMetricsReporter(
Kelvin Zhang9a5e3682021-03-29 12:58:48 -0400145 boot_control_->GetDynamicPartitionControl(), &install_plan_);
Alex Deymo87792ea2016-07-25 15:40:36 -0700146 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800147}
148
149UpdateAttempterAndroid::~UpdateAttempterAndroid() {
150 // Release ourselves as the ActionProcessor's delegate to prevent
151 // re-scheduling the updates due to the processing stopped.
152 processor_->set_delegate(nullptr);
153}
154
155void UpdateAttempterAndroid::Init() {
156 // In case of update_engine restart without a reboot we need to restore the
157 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700158 if (UpdateCompletedOnThisBoot()) {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800159 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700160 } else {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800161 SetStatusAndNotify(UpdateStatus::IDLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700162 UpdatePrefsAndReportUpdateMetricsOnReboot();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700163#ifdef _UE_SIDELOAD
164 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
165 << "ApplyPayload will call it later.";
166#else
Yifan Hong90965502020-02-19 15:22:47 -0800167 ScheduleCleanupPreviousUpdate();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700168#endif
Tianjie Xu90aaa102017-10-10 17:39:03 -0700169 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800170}
171
172bool UpdateAttempterAndroid::ApplyPayload(
173 const string& payload_url,
174 int64_t payload_offset,
175 int64_t payload_size,
176 const vector<string>& key_value_pair_headers,
177 brillo::ErrorPtr* error) {
178 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
179 return LogAndSetError(
180 error, FROM_HERE, "An update already applied, waiting for reboot");
181 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700182 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800183 return LogAndSetError(
184 error, FROM_HERE, "Already processing an update, cancel it first.");
185 }
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100186 DCHECK_EQ(status_, UpdateStatus::IDLE);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800187
Alex Deymo218397f2016-02-04 23:55:10 -0800188 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800189 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
190 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800191 }
192
Yifan Hongbd47d622019-12-13 14:59:58 -0800193 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800194
195 // Setup the InstallPlan based on the request.
196 install_plan_ = InstallPlan();
197
198 install_plan_.download_url = payload_url;
199 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800200 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800201 InstallPlan::Payload payload;
202 payload.size = payload_size;
203 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800204 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800205 &payload.size)) {
206 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800207 }
208 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700209 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800210 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700211 LOG(WARNING) << "Unable to decode base64 file hash: "
212 << headers[kPayloadPropertyFileHash];
213 }
Alex Deymo218397f2016-02-04 23:55:10 -0800214 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800215 &payload.metadata_size)) {
216 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800217 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700218 // The |payload.type| is not used anymore since minor_version 3.
219 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800220 install_plan_.payloads.push_back(payload);
221
Alex Deymo5e3ea272016-01-28 13:42:23 -0800222 // The |public_key_rsa| key would override the public key stored on disk.
223 install_plan_.public_key_rsa = "";
224
225 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
226 install_plan_.is_resume = !payload_id.empty() &&
227 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
228 if (!install_plan_.is_resume) {
Yifan Hong55c2bfe2020-01-13 17:01:19 -0800229 // No need to reset dynamic_partititon_metadata_updated. If previous calls
230 // to AllocateSpaceForPayload uses the same payload_id, reuse preallocated
231 // space. Otherwise, DeltaPerformer re-allocates space when the payload is
232 // applied.
233 if (!DeltaPerformer::ResetUpdateProgress(
234 prefs_,
235 false /* quick */,
236 true /* skip_dynamic_partititon_metadata_updated */)) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800237 LOG(WARNING) << "Unable to reset the update progress.";
238 }
239 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
240 LOG(WARNING) << "Unable to save the update check response hash.";
241 }
242 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800243 install_plan_.source_slot = GetCurrentSlot();
244 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700245
Alex Deymofb905d92016-06-03 19:26:58 -0700246 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700247 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
248
249 install_plan_.switch_slot_on_reboot =
250 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
251
Tianjie Xu087de9d2019-11-01 17:11:22 -0700252 install_plan_.run_post_install =
253 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800254
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700255 // Skip writing verity if we're resuming and verity has already been written.
256 install_plan_.write_verity = true;
257 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
258 bool verity_written = false;
259 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
260 verity_written) {
261 install_plan_.write_verity = false;
262 }
263 }
264
Alex Deymo87792ea2016-07-25 15:40:36 -0700265 NetworkId network_id = kDefaultNetworkId;
266 if (!headers[kPayloadPropertyNetworkId].empty()) {
267 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
268 &network_id)) {
269 return LogAndSetError(
270 error,
271 FROM_HERE,
272 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
273 }
274 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700275 return LogAndSetError(
276 error,
277 FROM_HERE,
278 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700279 }
280 }
281
Alex Deymo5e3ea272016-01-28 13:42:23 -0800282 LOG(INFO) << "Using this install plan:";
283 install_plan_.Dump();
284
Amin Hassani667cf7b2018-07-25 14:32:00 -0700285 HttpFetcher* fetcher = nullptr;
286 if (FileFetcher::SupportedUrl(payload_url)) {
287 DLOG(INFO) << "Using FileFetcher for file URL.";
288 fetcher = new FileFetcher();
289 } else {
290#ifdef _UE_SIDELOAD
291 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
292#else
293 LibcurlHttpFetcher* libcurl_fetcher =
294 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
295 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
296 fetcher = libcurl_fetcher;
297#endif // _UE_SIDELOAD
298 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800299 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800300 if (!headers[kPayloadPropertyAuthorization].empty())
301 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
302 if (!headers[kPayloadPropertyUserAgent].empty())
303 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
304
Amin Hassani667cf7b2018-07-25 14:32:00 -0700305 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800306
Alex Deymo5e3ea272016-01-28 13:42:23 -0800307 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700308
309 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
310 // TODO(xunchang) report the metrics for unresumable updates
311
Amin Hassani667cf7b2018-07-25 14:32:00 -0700312 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800313 return true;
314}
315
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900316bool UpdateAttempterAndroid::ApplyPayload(
317 int fd,
318 int64_t payload_offset,
319 int64_t payload_size,
320 const vector<string>& key_value_pair_headers,
321 brillo::ErrorPtr* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100322 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000323 // already running update will be terminated (existing file descriptor will be
324 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100325 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
326 return LogAndSetError(
327 error, FROM_HERE, "An update already applied, waiting for reboot");
328 }
329 if (processor_->IsRunning()) {
330 return LogAndSetError(
331 error, FROM_HERE, "Already processing an update, cancel it first.");
332 }
333 DCHECK_EQ(status_, UpdateStatus::IDLE);
334
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900335 payload_fd_.reset(dup(fd));
336 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
337
338 return ApplyPayload(
339 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
340}
341
Alex Deymo5e3ea272016-01-28 13:42:23 -0800342bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700343 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800344 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
345 processor_->SuspendProcessing();
346 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800347}
348
349bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700350 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800351 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
352 processor_->ResumeProcessing();
353 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800354}
355
356bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700357 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800358 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800359 processor_->StopProcessing();
360 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800361}
362
Alex Deymo3b678db2016-02-09 11:50:06 -0800363bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
364 LOG(INFO) << "Attempting to reset state from "
365 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
366
367 switch (status_) {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700368 case UpdateStatus::IDLE: {
369 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
370 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
371 << "space might not be freed.";
372 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800373 return true;
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700374 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800375
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800376 case UpdateStatus::UPDATED_NEED_REBOOT: {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700377 bool ret_value = true;
Alex Deymo3b678db2016-02-09 11:50:06 -0800378
379 // Update the boot flags so the current slot has higher priority.
Yifan Hongbd47d622019-12-13 14:59:58 -0800380 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot()))
Alex Deymo3b678db2016-02-09 11:50:06 -0800381 ret_value = false;
382
Alex Deymo52590332016-11-29 18:29:13 -0800383 // Mark the current slot as successful again, since marking it as active
384 // may reset the successful bit. We ignore the result of whether marking
385 // the current slot as successful worked.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800386 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {})))
Alex Deymo52590332016-11-29 18:29:13 -0800387 ret_value = false;
388
Tianjie Xud6aa91f2019-11-14 11:55:10 -0800389 // Resets the warm reset property since we won't switch the slot.
390 hardware_->SetWarmReset(false);
391
Tianjie838793d2021-01-14 22:05:13 -0800392 // Resets the vbmeta digest.
393 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
394
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700395 // Remove update progress for DeltaPerformer and remove snapshots.
396 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_))
397 ret_value = false;
398
399 // Remove the reboot marker so that if the machine is rebooted
400 // after resetting to idle state, it doesn't go back to
401 // UpdateStatus::UPDATED_NEED_REBOOT state.
402 if (!prefs_->Delete(kPrefsUpdateCompletedOnBootId))
403 ret_value = false;
404 ClearMetricsPrefs();
405
Alex Deymo3b678db2016-02-09 11:50:06 -0800406 if (!ret_value) {
407 return LogAndSetError(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800408 error, FROM_HERE, "Failed to reset the status to ");
Alex Deymo3b678db2016-02-09 11:50:06 -0800409 }
410
411 SetStatusAndNotify(UpdateStatus::IDLE);
412 LOG(INFO) << "Reset status successful";
413 return true;
414 }
415
416 default:
417 return LogAndSetError(
418 error,
419 FROM_HERE,
420 "Reset not allowed in this state. Cancel the ongoing update first");
421 }
422}
423
Yifan Hongbd47d622019-12-13 14:59:58 -0800424bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
425 const std::string& metadata_filename,
426 DeltaArchiveManifest* manifest,
427 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800428 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
429 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
430 return LogAndSetError(
431 error, FROM_HERE, "Failed to open " + metadata_filename);
432 }
433 brillo::Blob metadata(kMaxPayloadHeaderSize);
434 if (!fd->Read(metadata.data(), metadata.size())) {
435 return LogAndSetError(
436 error,
437 FROM_HERE,
438 "Failed to read payload header from " + metadata_filename);
439 }
440 ErrorCode errorcode;
441 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700442 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800443 MetadataParseResult::kSuccess) {
444 return LogAndSetError(error,
445 FROM_HERE,
446 "Failed to parse payload header: " +
447 utils::ErrorCodeToString(errorcode));
448 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700449 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
450 payload_metadata.GetMetadataSignatureSize();
451 if (metadata_size < kMaxPayloadHeaderSize ||
452 metadata_size >
453 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800454 return LogAndSetError(
455 error,
456 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700457 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800458 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700459 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800460 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
461 metadata.size() - kMaxPayloadHeaderSize)) {
462 return LogAndSetError(
463 error,
464 FROM_HERE,
465 "Failed to read metadata and signature from " + metadata_filename);
466 }
467 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800468
Tianjie Xu7a78d632019-10-08 16:32:39 -0700469 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
470 constants::kUpdateCertificatesPath);
471 if (!payload_verifier) {
472 return LogAndSetError(error,
473 FROM_HERE,
474 "Failed to create the payload verifier from " +
475 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800476 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700477 errorcode = payload_metadata.ValidateMetadataSignature(
478 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800479 if (errorcode != ErrorCode::kSuccess) {
480 return LogAndSetError(error,
481 FROM_HERE,
482 "Failed to validate metadata signature: " +
483 utils::ErrorCodeToString(errorcode));
484 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800485 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800486 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
487 }
488
Yifan Hongbd47d622019-12-13 14:59:58 -0800489 return true;
490}
491
492bool UpdateAttempterAndroid::VerifyPayloadApplicable(
493 const std::string& metadata_filename, brillo::ErrorPtr* error) {
494 DeltaArchiveManifest manifest;
495 TEST_AND_RETURN_FALSE(
496 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
497
498 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
499 ErrorCode errorcode;
500
501 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800502 for (const PartitionUpdate& partition : manifest.partitions()) {
503 if (!partition.has_old_partition_info())
504 continue;
505 string partition_path;
506 if (!boot_control_->GetPartitionDevice(
507 partition.partition_name(), current_slot, &partition_path)) {
508 return LogAndSetError(
509 error,
510 FROM_HERE,
511 "Failed to get partition device for " + partition.partition_name());
512 }
513 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
514 return LogAndSetError(
515 error, FROM_HERE, "Failed to open " + partition_path);
516 }
517 for (const InstallOperation& operation : partition.operations()) {
518 if (!operation.has_src_sha256_hash())
519 continue;
520 brillo::Blob source_hash;
521 if (!fd_utils::ReadAndHashExtents(fd,
522 operation.src_extents(),
523 manifest.block_size(),
524 &source_hash)) {
525 return LogAndSetError(
526 error, FROM_HERE, "Failed to hash " + partition_path);
527 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400528 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800529 source_hash, operation, fd, &errorcode)) {
530 return false;
531 }
532 }
533 fd->Close();
534 }
535 return true;
536}
537
Alex Deymo5e3ea272016-01-28 13:42:23 -0800538void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
539 ErrorCode code) {
540 LOG(INFO) << "Processing Done.";
541
Yifan Hong90965502020-02-19 15:22:47 -0800542 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
543 TerminateUpdateAndNotify(code);
544 return;
545 }
546
Alex Deymo5990bf32016-07-19 17:01:41 -0700547 switch (code) {
548 case ErrorCode::kSuccess:
549 // Update succeeded.
550 WriteUpdateCompletedMarker();
551 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800552
Alex Deymo5990bf32016-07-19 17:01:41 -0700553 LOG(INFO) << "Update successfully applied, waiting to reboot.";
554 break;
555
556 case ErrorCode::kFilesystemCopierError:
557 case ErrorCode::kNewRootfsVerificationError:
558 case ErrorCode::kNewKernelVerificationError:
559 case ErrorCode::kFilesystemVerifierError:
560 case ErrorCode::kDownloadStateInitializationError:
561 // Reset the ongoing update for these errors so it starts from the
562 // beginning next time.
563 DeltaPerformer::ResetUpdateProgress(prefs_, false);
564 LOG(INFO) << "Resetting update progress.";
565 break;
566
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700567 case ErrorCode::kPayloadTimestampError:
568 // SafetyNet logging, b/36232423
569 android_errorWriteLog(0x534e4554, "36232423");
570 break;
571
Alex Deymo5990bf32016-07-19 17:01:41 -0700572 default:
573 // Ignore all other error codes.
574 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700575 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800576
577 TerminateUpdateAndNotify(code);
578}
579
580void UpdateAttempterAndroid::ProcessingStopped(
581 const ActionProcessor* processor) {
582 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
583}
584
585void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
586 AbstractAction* action,
587 ErrorCode code) {
588 // Reset download progress regardless of whether or not the download
589 // action succeeded.
590 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800591 if (type == CleanupPreviousUpdateAction::StaticType() ||
592 (type == NoOpAction::StaticType() &&
593 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
594 cleanup_previous_update_code_ = code;
595 NotifyCleanupPreviousUpdateCallbacksAndClear();
596 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000597 // download_progress_ is actually used by other actions, such as
598 // filesystem_verify_action. Therefore we always clear it.
599 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700600 if (type == PostinstallRunnerAction::StaticType()) {
601 bool succeeded =
602 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
603 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
604 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800605 if (code != ErrorCode::kSuccess) {
606 // If an action failed, the ActionProcessor will cancel the whole thing.
607 return;
608 }
Yifan Hong83517502020-02-19 15:34:13 -0800609 if (type == UpdateBootFlagsAction::StaticType()) {
610 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
611 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800612 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400613 auto download_action = static_cast<DownloadAction*>(action);
614 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000615 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700616 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000617 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700618 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800619 }
620}
621
622void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
623 uint64_t bytes_received,
624 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700625 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800626 if (total)
627 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700628 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800629 download_progress_ = progress;
630 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700631 } else {
632 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800633 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700634
635 // Update the bytes downloaded in prefs.
636 int64_t current_bytes_downloaded =
637 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
638 int64_t total_bytes_downloaded =
639 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
640 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
641 current_bytes_downloaded + bytes_progressed);
642 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
643 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800644}
645
646bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
647 // TODO(deymo): Notify the DownloadAction that it should cancel the update
648 // download.
649 return false;
650}
651
652void UpdateAttempterAndroid::DownloadComplete() {
653 // Nothing needs to be done when the download completes.
654}
655
Alex Deymo0d298542016-03-30 18:31:49 -0700656void UpdateAttempterAndroid::ProgressUpdate(double progress) {
657 // Self throttle based on progress. Also send notifications if progress is
658 // too slow.
659 if (progress == 1.0 ||
660 progress - download_progress_ >= kBroadcastThresholdProgress ||
661 TimeTicks::Now() - last_notify_time_ >=
662 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
663 download_progress_ = progress;
664 SetStatusAndNotify(status_);
665 }
666}
667
Kelvin Zhang70eef232020-06-12 20:32:40 +0000668void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
669 assert(status_ == UpdateStatus::VERIFYING);
670 ProgressUpdate(progress);
671}
672
Alex Deymo5e3ea272016-01-28 13:42:23 -0800673void UpdateAttempterAndroid::ScheduleProcessingStart() {
674 LOG(INFO) << "Scheduling an action processor start.";
675 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700676 FROM_HERE,
677 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
678 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800679}
680
681void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
682 if (status_ == UpdateStatus::IDLE) {
683 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
684 return;
685 }
686
Yifan Hong90965502020-02-19 15:22:47 -0800687 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
688 LOG(INFO) << "Terminating cleanup previous update.";
689 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700690 for (auto observer : daemon_state_->service_observers())
691 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800692 return;
693 }
694
Yifan Hong9194ce82019-11-07 11:03:42 -0800695 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700696
Alex Deymo0d298542016-03-30 18:31:49 -0700697 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800698 UpdateStatus new_status =
699 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
700 : UpdateStatus::IDLE);
701 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900702 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800703
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700704 // The network id is only applicable to one download attempt and once it's
705 // done the network id should not be re-used anymore.
706 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
707 LOG(WARNING) << "Unable to unbind network.";
708 }
709
Alex Deymo5e3ea272016-01-28 13:42:23 -0800710 for (auto observer : daemon_state_->service_observers())
711 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700712
Tianjie Xu90aaa102017-10-10 17:39:03 -0700713 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
714 ClearMetricsPrefs();
715 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800716 // We should only reset the PayloadAttemptNumber if the update succeeds, or
717 // we switch to a different payload.
718 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700719 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700720 // Clear the total bytes downloaded if and only if the update succeeds.
721 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700722 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800723}
724
725void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
726 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700727 size_t payload_size =
728 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700729 UpdateEngineStatus status_to_send = {.status = status_,
730 .progress = download_progress_,
731 .new_size_bytes = payload_size};
732
Alex Deymo5e3ea272016-01-28 13:42:23 -0800733 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700734 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800735 }
736 last_notify_time_ = TimeTicks::Now();
737}
738
Amin Hassani667cf7b2018-07-25 14:32:00 -0700739void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800740 CHECK(!processor_->IsRunning());
741 processor_->set_delegate(this);
742
743 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700744 auto update_boot_flags_action =
745 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800746 auto cleanup_previous_update_action =
747 boot_control_->GetDynamicPartitionControl()
748 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700749 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
750 auto download_action =
751 std::make_unique<DownloadAction>(prefs_,
752 boot_control_,
753 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700754 fetcher, // passes ownership
755 true /* interactive */);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800756 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700757 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700758 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
759 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700760 auto postinstall_runner_action =
761 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000762 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700763 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800764
Alex Deymo5e3ea272016-01-28 13:42:23 -0800765 // Bond them together. We have to use the leaf-types when calling
766 // BondActions().
767 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700768 BondActions(download_action.get(), filesystem_verifier_action.get());
769 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800770 postinstall_runner_action.get());
771
Amin Hassani667cf7b2018-07-25 14:32:00 -0700772 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800773 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700774 processor_->EnqueueAction(std::move(install_plan_action));
775 processor_->EnqueueAction(std::move(download_action));
776 processor_->EnqueueAction(std::move(filesystem_verifier_action));
777 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800778}
779
Alex Deymo5e3ea272016-01-28 13:42:23 -0800780bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
781 string boot_id;
782 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
783 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
784 return true;
785}
786
787bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
788 // In case of an update_engine restart without a reboot, we stored the boot_id
789 // when the update was completed by setting a pref, so we can check whether
790 // the last update was on this boot or a previous one.
791 string boot_id;
792 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
793
794 string update_completed_on_boot_id;
795 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
796 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
797 &update_completed_on_boot_id) &&
798 update_completed_on_boot_id == boot_id);
799}
800
Tianjie Xu90aaa102017-10-10 17:39:03 -0700801// Collect and report the android metrics when we terminate the update.
802void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
803 ErrorCode error_code) {
804 int64_t attempt_number =
805 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
806 PayloadType payload_type = kPayloadTypeFull;
807 int64_t payload_size = 0;
808 for (const auto& p : install_plan_.payloads) {
809 if (p.type == InstallPayloadType::kDelta)
810 payload_type = kPayloadTypeDelta;
811 payload_size += p.size;
812 }
813
814 metrics::AttemptResult attempt_result =
815 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700816 Time boot_time_start = Time::FromInternalValue(
817 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
818 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700819 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700820 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
821 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700822
823 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700824 static_cast<int>(attempt_number),
825 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700826 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700827 duration_uptime,
828 payload_size,
829 attempt_result,
830 error_code);
831
Tianjie Xud4777a12017-10-24 14:54:18 -0700832 int64_t current_bytes_downloaded =
833 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
834 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
835 current_bytes_downloaded,
836 0,
837 DownloadSource::kNumDownloadSources,
838 metrics::DownloadErrorCode::kUnset,
839 metrics::ConnectionType::kUnset);
840
Tianjie Xu90aaa102017-10-10 17:39:03 -0700841 if (error_code == ErrorCode::kSuccess) {
842 int64_t reboot_count =
843 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
844 string build_version;
845 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700846
847 // For android metrics, we only care about the total bytes downloaded
848 // for all sources; for now we assume the only download source is
849 // HttpsServer.
850 int64_t total_bytes_downloaded =
851 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
852 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
853 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
854 total_bytes_downloaded;
855
856 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700857 if (total_bytes_downloaded >= payload_size) {
858 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700859 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700860 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
861 } else {
862 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
863 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700864 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700865
Tianjie Xu90aaa102017-10-10 17:39:03 -0700866 metrics_reporter_->ReportSuccessfulUpdateMetrics(
867 static_cast<int>(attempt_number),
868 0, // update abandoned count
869 payload_type,
870 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700871 num_bytes_downloaded,
872 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700873 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700874 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700875 static_cast<int>(reboot_count),
876 0); // url_switch_count
877 }
878}
879
880void UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
881 string current_boot_id;
882 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
883 // Example: [ro.build.version.incremental]: [4292972]
884 string current_version =
885 android::base::GetProperty("ro.build.version.incremental", "");
886 TEST_AND_RETURN(!current_version.empty());
887
888 // If there's no record of previous version (e.g. due to a data wipe), we
889 // save the info of current boot and skip the metrics report.
890 if (!prefs_->Exists(kPrefsPreviousVersion)) {
891 prefs_->SetString(kPrefsBootId, current_boot_id);
892 prefs_->SetString(kPrefsPreviousVersion, current_version);
893 ClearMetricsPrefs();
894 return;
895 }
896 string previous_version;
897 // update_engine restarted under the same build.
898 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
899 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
900 previous_version == current_version) {
901 string last_boot_id;
902 bool is_reboot = prefs_->Exists(kPrefsBootId) &&
903 (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
904 last_boot_id != current_boot_id);
905 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
906 // set when we start a new update.
907 if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
908 prefs_->SetString(kPrefsBootId, current_boot_id);
909 int64_t reboot_count =
910 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
911 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
912 }
913 return;
914 }
915
916 // Now that the build version changes, report the update metrics.
917 // TODO(xunchang) check the build version is larger than the previous one.
918 prefs_->SetString(kPrefsBootId, current_boot_id);
919 prefs_->SetString(kPrefsPreviousVersion, current_version);
920
921 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
922 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
923 if (previous_attempt_exists) {
924 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
925 }
926
927 metrics_utils::LoadAndReportTimeToReboot(
928 metrics_reporter_.get(), prefs_, clock_.get());
929 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -0800930
931 // Also reset the update progress if the build version has changed.
932 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
933 LOG(WARNING) << "Unable to reset the update progress.";
934 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700935}
936
937// Save the update start time. Reset the reboot count and attempt number if the
938// update isn't a resume; otherwise increment the attempt number.
939void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
940 if (!is_resume) {
941 metrics_utils::SetNumReboots(0, prefs_);
942 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
943 } else {
944 int64_t attempt_number =
945 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
946 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
947 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700948 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
949 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700950}
951
952void UpdateAttempterAndroid::ClearMetricsPrefs() {
953 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700954 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700955 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700956 prefs_->Delete(kPrefsSystemUpdatedMarker);
957 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700958 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700959}
960
Yifan Hongbd47d622019-12-13 14:59:58 -0800961BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
962 return boot_control_->GetCurrentSlot();
963}
964
965BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
966 return GetCurrentSlot() == 0 ? 1 : 0;
967}
968
Yifan Hong6f7e29f2019-12-13 14:41:06 -0800969uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
970 const std::string& metadata_filename,
971 const vector<string>& key_value_pair_headers,
972 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -0800973 DeltaArchiveManifest manifest;
974 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
975 return 0;
976 }
977 std::map<string, string> headers;
978 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
979 return 0;
980 }
981
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000982 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
983 manifest.apex_info().end());
984 uint64_t apex_size_required = 0;
985 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000986 auto result = apex_handler_android_->CalculateSize(apex_infos);
987 if (!result.ok()) {
988 LogAndSetError(error,
989 FROM_HERE,
990 "Failed to calculate size required for compressed APEX");
991 return 0;
992 }
993 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000994 }
995
Yifan Hong65613032020-01-09 17:52:13 -0800996 string payload_id = GetPayloadId(headers);
997 uint64_t required_size = 0;
998 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
999 boot_control_,
1000 GetTargetSlot(),
1001 manifest,
1002 payload_id,
1003 &required_size)) {
1004 if (required_size == 0) {
1005 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
1006 return 0;
1007 } else {
1008 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001009 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001010 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001011 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001012 }
1013 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001014
1015 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001016 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001017 LOG(ERROR) << "Insufficient space for apex decompression: "
1018 << apex_size_required << " bytes";
1019 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001020 }
Yifan Hong65613032020-01-09 17:52:13 -08001021
1022 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001023 return 0;
1024}
1025
Yifan Hong40bb0d02020-02-24 17:33:14 -08001026void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1027 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Yifan Hong2236ea02019-12-13 16:11:22 -08001028 brillo::ErrorPtr* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001029 if (cleanup_previous_update_code_.has_value()) {
1030 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1031 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1032 if (callback) {
1033 callback->OnCleanupComplete(
1034 static_cast<int32_t>(*cleanup_previous_update_code_));
1035 }
1036 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001037 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001038 if (callback) {
1039 auto callback_ptr = callback.get();
1040 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1041 callback_ptr->RegisterForDeathNotifications(
1042 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1043 base::Unretained(this),
1044 base::Unretained(callback_ptr)));
1045 }
1046 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001047}
1048
Yifan Hong90965502020-02-19 15:22:47 -08001049void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1050 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1051 // is in progress, skip enqueueing the action.
1052 if (processor_->IsRunning()) {
1053 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1054 << "be done when the current update finishes.";
1055 return;
1056 }
1057 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1058 auto action =
1059 boot_control_->GetDynamicPartitionControl()
1060 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1061 processor_->EnqueueAction(std::move(action));
1062 processor_->set_delegate(this);
1063 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1064 processor_->StartProcessing();
1065}
1066
Yifan Hong40bb0d02020-02-24 17:33:14 -08001067void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1068 for (auto&& callback : cleanup_previous_update_callbacks_) {
1069 callback->OnCleanupProgressUpdate(progress);
1070 }
1071}
1072
1073void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1074 CHECK(cleanup_previous_update_code_.has_value());
1075 for (auto&& callback : cleanup_previous_update_callbacks_) {
1076 callback->OnCleanupComplete(
1077 static_cast<int32_t>(*cleanup_previous_update_code_));
1078 }
1079 cleanup_previous_update_callbacks_.clear();
1080}
1081
1082void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1083 CleanupSuccessfulUpdateCallbackInterface* callback) {
1084 auto end_it =
1085 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1086 cleanup_previous_update_callbacks_.end(),
1087 [&](const auto& e) { return e.get() == callback; });
1088 cleanup_previous_update_callbacks_.erase(
1089 end_it, cleanup_previous_update_callbacks_.end());
1090}
Yifan Hong90965502020-02-19 15:22:47 -08001091
Alex Deymo5e3ea272016-01-28 13:42:23 -08001092} // namespace chromeos_update_engine