blob: 4e609d4e1134b7fb3e5bbc073ed429c9935d6a82 [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>
Kelvin Zhanga43d6e82021-05-26 10:14:42 -040022#include <ostream>
Alex Deymo5e3ea272016-01-28 13:42:23 -080023#include <utility>
24
Tianjie Xu90aaa102017-10-10 17:39:03 -070025#include <android-base/properties.h>
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090026#include <android-base/unique_fd.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080027#include <base/bind.h>
28#include <base/logging.h>
Alex Deymo218397f2016-02-04 23:55:10 -080029#include <base/strings/string_number_conversions.h>
Sen Jiang2703ef42017-03-16 13:36:21 -070030#include <brillo/data_encoding.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080031#include <brillo/message_loops/message_loop.h>
Alex Deymo218397f2016-02-04 23:55:10 -080032#include <brillo/strings/string_utils.h>
Sen Jiangacbdd1c2017-10-19 13:30:19 -070033#include <log/log_safetynet.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080034
Amin Hassaniec7bc112020-10-29 16:47:58 -070035#include "update_engine/aosp/cleanup_previous_update_action.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080036#include "update_engine/common/constants.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070037#include "update_engine/common/daemon_state_interface.h"
38#include "update_engine/common/download_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080039#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070040#include "update_engine/common/file_fetcher.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070041#include "update_engine/common/metrics_reporter_interface.h"
42#include "update_engine/common/network_selector.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080043#include "update_engine/common/utils.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070044#include "update_engine/metrics_utils.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070045#include "update_engine/payload_consumer/certificate_parser_interface.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080046#include "update_engine/payload_consumer/delta_performer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080047#include "update_engine/payload_consumer/file_descriptor.h"
48#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080049#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080050#include "update_engine/payload_consumer/payload_constants.h"
51#include "update_engine/payload_consumer/payload_metadata.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070052#include "update_engine/payload_consumer/payload_verifier.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080053#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070054#include "update_engine/update_boot_flags_action.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080055#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080056
Alex Deymo14c0da82016-07-20 16:45:45 -070057#ifndef _UE_SIDELOAD
58// Do not include support for external HTTP(s) urls when building
59// update_engine_sideload.
60#include "update_engine/libcurl_http_fetcher.h"
61#endif
62
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090063using android::base::unique_fd;
Alex Deymo5e3ea272016-01-28 13:42:23 -080064using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070065using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080066using base::TimeDelta;
67using base::TimeTicks;
Alex Deymo5e3ea272016-01-28 13:42:23 -080068using 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(
Kelvin Zhang9a5e3682021-03-29 12:58:48 -0400146 boot_control_->GetDynamicPartitionControl(), &install_plan_);
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
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400156[[nodiscard]] static bool DidSystemReboot(PrefsInterface* prefs) {
157 string boot_id;
158 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
159 string old_boot_id;
160 // If no previous boot id found, treat as a reboot and write boot ID.
161 if (!prefs->GetString(kPrefsBootId, &old_boot_id)) {
162 return true;
163 }
164 return old_boot_id != boot_id;
165}
166
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400167std::ostream& operator<<(std::ostream& out, OTAResult result) {
168 switch (result) {
169 case OTAResult::NOT_ATTEMPTED:
170 out << "OTAResult::NOT_ATTEMPTED";
171 break;
172 case OTAResult::ROLLED_BACK:
173 out << "OTAResult::ROLLED_BACK";
174 break;
175 case OTAResult::UPDATED_NEED_REBOOT:
176 out << "OTAResult::UPDATED_NEED_REBOOT";
177 break;
178 case OTAResult::OTA_SUCCESSFUL:
179 out << "OTAResult::OTA_SUCCESSFUL";
180 break;
181 }
182 return out;
183}
184
Alex Deymo5e3ea272016-01-28 13:42:23 -0800185void UpdateAttempterAndroid::Init() {
186 // In case of update_engine restart without a reboot we need to restore the
187 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700188 if (UpdateCompletedOnThisBoot()) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400189 LOG(INFO) << "Updated installed but update_engine is restarted without "
190 "device reboot. Resuming old state.";
Alex Deymo0e061ae2016-02-09 17:49:03 -0800191 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700192 } else {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400193 const auto result = GetOTAUpdateResult();
194 LOG(INFO) << result;
Alex Deymo0e061ae2016-02-09 17:49:03 -0800195 SetStatusAndNotify(UpdateStatus::IDLE);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400196 if (DidSystemReboot(prefs_)) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400197 UpdateStateAfterReboot(result);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400198 }
199
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700200#ifdef _UE_SIDELOAD
201 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
202 << "ApplyPayload will call it later.";
203#else
Yifan Hong90965502020-02-19 15:22:47 -0800204 ScheduleCleanupPreviousUpdate();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700205#endif
Tianjie Xu90aaa102017-10-10 17:39:03 -0700206 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800207}
208
209bool UpdateAttempterAndroid::ApplyPayload(
210 const string& payload_url,
211 int64_t payload_offset,
212 int64_t payload_size,
213 const vector<string>& key_value_pair_headers,
214 brillo::ErrorPtr* error) {
215 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
216 return LogAndSetError(
217 error, FROM_HERE, "An update already applied, waiting for reboot");
218 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700219 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800220 return LogAndSetError(
221 error, FROM_HERE, "Already processing an update, cancel it first.");
222 }
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100223 DCHECK_EQ(status_, UpdateStatus::IDLE);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800224
Alex Deymo218397f2016-02-04 23:55:10 -0800225 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800226 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
227 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800228 }
229
Yifan Hongbd47d622019-12-13 14:59:58 -0800230 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800231
232 // Setup the InstallPlan based on the request.
233 install_plan_ = InstallPlan();
234
235 install_plan_.download_url = payload_url;
236 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800237 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800238 InstallPlan::Payload payload;
239 payload.size = payload_size;
240 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800241 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800242 &payload.size)) {
243 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800244 }
245 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700246 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800247 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700248 LOG(WARNING) << "Unable to decode base64 file hash: "
249 << headers[kPayloadPropertyFileHash];
250 }
Alex Deymo218397f2016-02-04 23:55:10 -0800251 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800252 &payload.metadata_size)) {
253 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800254 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700255 // The |payload.type| is not used anymore since minor_version 3.
256 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800257 install_plan_.payloads.push_back(payload);
258
Alex Deymo5e3ea272016-01-28 13:42:23 -0800259 // The |public_key_rsa| key would override the public key stored on disk.
260 install_plan_.public_key_rsa = "";
261
262 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
263 install_plan_.is_resume = !payload_id.empty() &&
264 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
265 if (!install_plan_.is_resume) {
Yifan Hong55c2bfe2020-01-13 17:01:19 -0800266 // No need to reset dynamic_partititon_metadata_updated. If previous calls
267 // to AllocateSpaceForPayload uses the same payload_id, reuse preallocated
268 // space. Otherwise, DeltaPerformer re-allocates space when the payload is
269 // applied.
270 if (!DeltaPerformer::ResetUpdateProgress(
271 prefs_,
272 false /* quick */,
273 true /* skip_dynamic_partititon_metadata_updated */)) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800274 LOG(WARNING) << "Unable to reset the update progress.";
275 }
276 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
277 LOG(WARNING) << "Unable to save the update check response hash.";
278 }
279 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800280 install_plan_.source_slot = GetCurrentSlot();
281 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700282
Alex Deymofb905d92016-06-03 19:26:58 -0700283 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700284 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
285
286 install_plan_.switch_slot_on_reboot =
287 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
288
Tianjie Xu087de9d2019-11-01 17:11:22 -0700289 install_plan_.run_post_install =
290 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800291
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700292 // Skip writing verity if we're resuming and verity has already been written.
293 install_plan_.write_verity = true;
294 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
295 bool verity_written = false;
296 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
297 verity_written) {
298 install_plan_.write_verity = false;
299 }
300 }
301
Alex Deymo87792ea2016-07-25 15:40:36 -0700302 NetworkId network_id = kDefaultNetworkId;
303 if (!headers[kPayloadPropertyNetworkId].empty()) {
304 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
305 &network_id)) {
306 return LogAndSetError(
307 error,
308 FROM_HERE,
309 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
310 }
311 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700312 return LogAndSetError(
313 error,
314 FROM_HERE,
315 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700316 }
317 }
318
Alex Deymo5e3ea272016-01-28 13:42:23 -0800319 LOG(INFO) << "Using this install plan:";
320 install_plan_.Dump();
321
Amin Hassani667cf7b2018-07-25 14:32:00 -0700322 HttpFetcher* fetcher = nullptr;
323 if (FileFetcher::SupportedUrl(payload_url)) {
324 DLOG(INFO) << "Using FileFetcher for file URL.";
325 fetcher = new FileFetcher();
326 } else {
327#ifdef _UE_SIDELOAD
328 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
329#else
330 LibcurlHttpFetcher* libcurl_fetcher =
331 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
332 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
333 fetcher = libcurl_fetcher;
334#endif // _UE_SIDELOAD
335 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800336 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800337 if (!headers[kPayloadPropertyAuthorization].empty())
338 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
339 if (!headers[kPayloadPropertyUserAgent].empty())
340 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
341
Amin Hassani667cf7b2018-07-25 14:32:00 -0700342 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800343
Alex Deymo5e3ea272016-01-28 13:42:23 -0800344 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700345
346 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
347 // TODO(xunchang) report the metrics for unresumable updates
348
Amin Hassani667cf7b2018-07-25 14:32:00 -0700349 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800350 return true;
351}
352
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900353bool UpdateAttempterAndroid::ApplyPayload(
354 int fd,
355 int64_t payload_offset,
356 int64_t payload_size,
357 const vector<string>& key_value_pair_headers,
358 brillo::ErrorPtr* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100359 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000360 // already running update will be terminated (existing file descriptor will be
361 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100362 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
363 return LogAndSetError(
364 error, FROM_HERE, "An update already applied, waiting for reboot");
365 }
366 if (processor_->IsRunning()) {
367 return LogAndSetError(
368 error, FROM_HERE, "Already processing an update, cancel it first.");
369 }
370 DCHECK_EQ(status_, UpdateStatus::IDLE);
371
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900372 payload_fd_.reset(dup(fd));
373 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
374
375 return ApplyPayload(
376 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
377}
378
Alex Deymo5e3ea272016-01-28 13:42:23 -0800379bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700380 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800381 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
382 processor_->SuspendProcessing();
383 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800384}
385
386bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700387 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800388 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
389 processor_->ResumeProcessing();
390 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800391}
392
393bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700394 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800395 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800396 processor_->StopProcessing();
397 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800398}
399
Alex Deymo3b678db2016-02-09 11:50:06 -0800400bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
401 LOG(INFO) << "Attempting to reset state from "
402 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
403
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000404 if (apex_handler_android_ != nullptr) {
405 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
406 std::vector<ApexInfo> apex_infos_blank;
407 apex_handler_android_->AllocateSpace(apex_infos_blank);
408 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400409 // Remove the reboot marker so that if the machine is rebooted
410 // after resetting to idle state, it doesn't go back to
411 // UpdateStatus::UPDATED_NEED_REBOOT state.
412 if (!ClearUpdateCompletedMarker()) {
413 return LogAndSetError(error,
414 FROM_HERE,
415 "Failed to reset the status because "
416 "ClearUpdateCompletedMarker() failed");
417 }
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000418
Alex Deymo3b678db2016-02-09 11:50:06 -0800419 switch (status_) {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700420 case UpdateStatus::IDLE: {
421 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
422 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
423 << "space might not be freed.";
424 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800425 return true;
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700426 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800427
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800428 case UpdateStatus::UPDATED_NEED_REBOOT: {
Kelvin Zhang20982a52021-08-13 12:31:16 -0700429 const bool ret_value = resetShouldSwitchSlotOnReboot(error);
430 if (ret_value) {
431 LOG(INFO) << "Reset status successful";
Alex Deymo3b678db2016-02-09 11:50:06 -0800432 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700433 return ret_value;
Alex Deymo3b678db2016-02-09 11:50:06 -0800434 }
435
436 default:
437 return LogAndSetError(
438 error,
439 FROM_HERE,
440 "Reset not allowed in this state. Cancel the ongoing update first");
441 }
442}
443
Yifan Hongbd47d622019-12-13 14:59:58 -0800444bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
445 const std::string& metadata_filename,
446 DeltaArchiveManifest* manifest,
447 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800448 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
449 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
450 return LogAndSetError(
451 error, FROM_HERE, "Failed to open " + metadata_filename);
452 }
453 brillo::Blob metadata(kMaxPayloadHeaderSize);
454 if (!fd->Read(metadata.data(), metadata.size())) {
455 return LogAndSetError(
456 error,
457 FROM_HERE,
458 "Failed to read payload header from " + metadata_filename);
459 }
460 ErrorCode errorcode;
461 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700462 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800463 MetadataParseResult::kSuccess) {
464 return LogAndSetError(error,
465 FROM_HERE,
466 "Failed to parse payload header: " +
467 utils::ErrorCodeToString(errorcode));
468 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700469 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
470 payload_metadata.GetMetadataSignatureSize();
471 if (metadata_size < kMaxPayloadHeaderSize ||
472 metadata_size >
473 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800474 return LogAndSetError(
475 error,
476 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700477 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800478 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700479 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800480 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
481 metadata.size() - kMaxPayloadHeaderSize)) {
482 return LogAndSetError(
483 error,
484 FROM_HERE,
485 "Failed to read metadata and signature from " + metadata_filename);
486 }
487 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800488
Tianjie Xu7a78d632019-10-08 16:32:39 -0700489 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
490 constants::kUpdateCertificatesPath);
491 if (!payload_verifier) {
492 return LogAndSetError(error,
493 FROM_HERE,
494 "Failed to create the payload verifier from " +
495 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800496 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700497 errorcode = payload_metadata.ValidateMetadataSignature(
498 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800499 if (errorcode != ErrorCode::kSuccess) {
500 return LogAndSetError(error,
501 FROM_HERE,
502 "Failed to validate metadata signature: " +
503 utils::ErrorCodeToString(errorcode));
504 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800505 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800506 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
507 }
508
Yifan Hongbd47d622019-12-13 14:59:58 -0800509 return true;
510}
511
512bool UpdateAttempterAndroid::VerifyPayloadApplicable(
513 const std::string& metadata_filename, brillo::ErrorPtr* error) {
514 DeltaArchiveManifest manifest;
515 TEST_AND_RETURN_FALSE(
516 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
517
518 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
519 ErrorCode errorcode;
520
521 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800522 for (const PartitionUpdate& partition : manifest.partitions()) {
523 if (!partition.has_old_partition_info())
524 continue;
525 string partition_path;
526 if (!boot_control_->GetPartitionDevice(
527 partition.partition_name(), current_slot, &partition_path)) {
528 return LogAndSetError(
529 error,
530 FROM_HERE,
531 "Failed to get partition device for " + partition.partition_name());
532 }
533 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
534 return LogAndSetError(
535 error, FROM_HERE, "Failed to open " + partition_path);
536 }
537 for (const InstallOperation& operation : partition.operations()) {
538 if (!operation.has_src_sha256_hash())
539 continue;
540 brillo::Blob source_hash;
541 if (!fd_utils::ReadAndHashExtents(fd,
542 operation.src_extents(),
543 manifest.block_size(),
544 &source_hash)) {
545 return LogAndSetError(
546 error, FROM_HERE, "Failed to hash " + partition_path);
547 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400548 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800549 source_hash, operation, fd, &errorcode)) {
550 return false;
551 }
552 }
553 fd->Close();
554 }
555 return true;
556}
557
Alex Deymo5e3ea272016-01-28 13:42:23 -0800558void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
559 ErrorCode code) {
560 LOG(INFO) << "Processing Done.";
561
Yifan Hong90965502020-02-19 15:22:47 -0800562 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
563 TerminateUpdateAndNotify(code);
564 return;
565 }
566
Alex Deymo5990bf32016-07-19 17:01:41 -0700567 switch (code) {
568 case ErrorCode::kSuccess:
569 // Update succeeded.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400570 if (!WriteUpdateCompletedMarker()) {
571 LOG(ERROR) << "Failed to write update completion marker";
572 }
Alex Deymo5990bf32016-07-19 17:01:41 -0700573 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800574
Alex Deymo5990bf32016-07-19 17:01:41 -0700575 LOG(INFO) << "Update successfully applied, waiting to reboot.";
576 break;
577
578 case ErrorCode::kFilesystemCopierError:
579 case ErrorCode::kNewRootfsVerificationError:
580 case ErrorCode::kNewKernelVerificationError:
581 case ErrorCode::kFilesystemVerifierError:
582 case ErrorCode::kDownloadStateInitializationError:
583 // Reset the ongoing update for these errors so it starts from the
584 // beginning next time.
585 DeltaPerformer::ResetUpdateProgress(prefs_, false);
586 LOG(INFO) << "Resetting update progress.";
587 break;
588
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700589 case ErrorCode::kPayloadTimestampError:
590 // SafetyNet logging, b/36232423
591 android_errorWriteLog(0x534e4554, "36232423");
592 break;
593
Alex Deymo5990bf32016-07-19 17:01:41 -0700594 default:
595 // Ignore all other error codes.
596 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700597 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800598
599 TerminateUpdateAndNotify(code);
600}
601
602void UpdateAttempterAndroid::ProcessingStopped(
603 const ActionProcessor* processor) {
604 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
605}
606
607void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
608 AbstractAction* action,
609 ErrorCode code) {
610 // Reset download progress regardless of whether or not the download
611 // action succeeded.
612 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800613 if (type == CleanupPreviousUpdateAction::StaticType() ||
614 (type == NoOpAction::StaticType() &&
615 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
616 cleanup_previous_update_code_ = code;
617 NotifyCleanupPreviousUpdateCallbacksAndClear();
618 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000619 // download_progress_ is actually used by other actions, such as
620 // filesystem_verify_action. Therefore we always clear it.
621 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700622 if (type == PostinstallRunnerAction::StaticType()) {
623 bool succeeded =
624 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
625 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
626 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800627 if (code != ErrorCode::kSuccess) {
628 // If an action failed, the ActionProcessor will cancel the whole thing.
629 return;
630 }
Yifan Hong83517502020-02-19 15:34:13 -0800631 if (type == UpdateBootFlagsAction::StaticType()) {
632 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
633 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800634 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400635 auto download_action = static_cast<DownloadAction*>(action);
636 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000637 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700638 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000639 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700640 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800641 }
642}
643
644void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
645 uint64_t bytes_received,
646 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700647 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800648 if (total)
649 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700650 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800651 download_progress_ = progress;
652 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700653 } else {
654 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800655 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700656
657 // Update the bytes downloaded in prefs.
658 int64_t current_bytes_downloaded =
659 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
660 int64_t total_bytes_downloaded =
661 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
662 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
663 current_bytes_downloaded + bytes_progressed);
664 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
665 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800666}
667
668bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
669 // TODO(deymo): Notify the DownloadAction that it should cancel the update
670 // download.
671 return false;
672}
673
674void UpdateAttempterAndroid::DownloadComplete() {
675 // Nothing needs to be done when the download completes.
676}
677
Alex Deymo0d298542016-03-30 18:31:49 -0700678void UpdateAttempterAndroid::ProgressUpdate(double progress) {
679 // Self throttle based on progress. Also send notifications if progress is
680 // too slow.
681 if (progress == 1.0 ||
682 progress - download_progress_ >= kBroadcastThresholdProgress ||
683 TimeTicks::Now() - last_notify_time_ >=
684 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
685 download_progress_ = progress;
686 SetStatusAndNotify(status_);
687 }
688}
689
Kelvin Zhang70eef232020-06-12 20:32:40 +0000690void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
691 assert(status_ == UpdateStatus::VERIFYING);
692 ProgressUpdate(progress);
693}
694
Alex Deymo5e3ea272016-01-28 13:42:23 -0800695void UpdateAttempterAndroid::ScheduleProcessingStart() {
696 LOG(INFO) << "Scheduling an action processor start.";
Kelvin Zhang20982a52021-08-13 12:31:16 -0700697 processor_->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800698 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700699 FROM_HERE,
700 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
701 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800702}
703
704void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
705 if (status_ == UpdateStatus::IDLE) {
706 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
707 return;
708 }
709
Yifan Hong90965502020-02-19 15:22:47 -0800710 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400711 ClearUpdateCompletedMarker();
Yifan Hong90965502020-02-19 15:22:47 -0800712 LOG(INFO) << "Terminating cleanup previous update.";
713 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700714 for (auto observer : daemon_state_->service_observers())
715 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800716 return;
717 }
718
Yifan Hong9194ce82019-11-07 11:03:42 -0800719 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700720
Alex Deymo0d298542016-03-30 18:31:49 -0700721 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800722 UpdateStatus new_status =
723 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
724 : UpdateStatus::IDLE);
725 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900726 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800727
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700728 // The network id is only applicable to one download attempt and once it's
729 // done the network id should not be re-used anymore.
730 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
731 LOG(WARNING) << "Unable to unbind network.";
732 }
733
Alex Deymo5e3ea272016-01-28 13:42:23 -0800734 for (auto observer : daemon_state_->service_observers())
735 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700736
Tianjie Xu90aaa102017-10-10 17:39:03 -0700737 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
738 ClearMetricsPrefs();
739 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800740 // We should only reset the PayloadAttemptNumber if the update succeeds, or
741 // we switch to a different payload.
742 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700743 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700744 // Clear the total bytes downloaded if and only if the update succeeds.
745 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700746 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800747}
748
749void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
750 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700751 size_t payload_size =
752 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700753 UpdateEngineStatus status_to_send = {.status = status_,
754 .progress = download_progress_,
755 .new_size_bytes = payload_size};
756
Alex Deymo5e3ea272016-01-28 13:42:23 -0800757 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700758 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800759 }
760 last_notify_time_ = TimeTicks::Now();
761}
762
Amin Hassani667cf7b2018-07-25 14:32:00 -0700763void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800764 CHECK(!processor_->IsRunning());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800765
766 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700767 auto update_boot_flags_action =
768 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800769 auto cleanup_previous_update_action =
770 boot_control_->GetDynamicPartitionControl()
771 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700772 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
773 auto download_action =
774 std::make_unique<DownloadAction>(prefs_,
775 boot_control_,
776 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700777 fetcher, // passes ownership
Kelvin Zhang1304fe72021-10-06 19:12:12 -0700778 true /* interactive */,
779 update_certificates_path_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800780 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700781 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700782 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
783 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700784 auto postinstall_runner_action =
785 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000786 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700787 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800788
Alex Deymo5e3ea272016-01-28 13:42:23 -0800789 // Bond them together. We have to use the leaf-types when calling
790 // BondActions().
791 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700792 BondActions(download_action.get(), filesystem_verifier_action.get());
793 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800794 postinstall_runner_action.get());
795
Amin Hassani667cf7b2018-07-25 14:32:00 -0700796 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800797 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700798 processor_->EnqueueAction(std::move(install_plan_action));
799 processor_->EnqueueAction(std::move(download_action));
800 processor_->EnqueueAction(std::move(filesystem_verifier_action));
801 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800802}
803
Alex Deymo5e3ea272016-01-28 13:42:23 -0800804bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400805 LOG(INFO) << "Writing update complete marker.";
Alex Deymo5e3ea272016-01-28 13:42:23 -0800806 string boot_id;
807 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400808 TEST_AND_RETURN_FALSE(
809 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id));
810 TEST_AND_RETURN_FALSE(
811 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot()));
812 return true;
813}
814
815bool UpdateAttempterAndroid::ClearUpdateCompletedMarker() {
816 LOG(INFO) << "Clearing update complete marker.";
817 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsUpdateCompletedOnBootId));
818 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsPreviousSlot));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800819 return true;
820}
821
822bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
823 // In case of an update_engine restart without a reboot, we stored the boot_id
824 // when the update was completed by setting a pref, so we can check whether
825 // the last update was on this boot or a previous one.
826 string boot_id;
827 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
828
829 string update_completed_on_boot_id;
830 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
831 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
832 &update_completed_on_boot_id) &&
833 update_completed_on_boot_id == boot_id);
834}
835
Tianjie Xu90aaa102017-10-10 17:39:03 -0700836// Collect and report the android metrics when we terminate the update.
837void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
838 ErrorCode error_code) {
839 int64_t attempt_number =
840 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
841 PayloadType payload_type = kPayloadTypeFull;
842 int64_t payload_size = 0;
843 for (const auto& p : install_plan_.payloads) {
844 if (p.type == InstallPayloadType::kDelta)
845 payload_type = kPayloadTypeDelta;
846 payload_size += p.size;
847 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700848 // In some cases, e.g. after calling |setShouldSwitchSlotOnReboot()|, this
849 // function will be triggered, but payload_size in this case might be 0, if so
850 // skip reporting any metrics.
851 if (payload_size == 0) {
852 return;
853 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700854
855 metrics::AttemptResult attempt_result =
856 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700857 Time boot_time_start = Time::FromInternalValue(
858 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
859 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700860 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700861 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
862 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700863
864 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700865 static_cast<int>(attempt_number),
866 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700867 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700868 duration_uptime,
869 payload_size,
870 attempt_result,
871 error_code);
872
Tianjie Xud4777a12017-10-24 14:54:18 -0700873 int64_t current_bytes_downloaded =
874 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
875 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
876 current_bytes_downloaded,
877 0,
878 DownloadSource::kNumDownloadSources,
879 metrics::DownloadErrorCode::kUnset,
880 metrics::ConnectionType::kUnset);
881
Tianjie Xu90aaa102017-10-10 17:39:03 -0700882 if (error_code == ErrorCode::kSuccess) {
883 int64_t reboot_count =
884 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
885 string build_version;
886 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700887
888 // For android metrics, we only care about the total bytes downloaded
889 // for all sources; for now we assume the only download source is
890 // HttpsServer.
891 int64_t total_bytes_downloaded =
892 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
893 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
894 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
895 total_bytes_downloaded;
896
897 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700898 if (total_bytes_downloaded >= payload_size) {
899 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700900 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700901 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
902 } else {
903 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
904 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700905 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700906
Tianjie Xu90aaa102017-10-10 17:39:03 -0700907 metrics_reporter_->ReportSuccessfulUpdateMetrics(
908 static_cast<int>(attempt_number),
909 0, // update abandoned count
910 payload_type,
911 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700912 num_bytes_downloaded,
913 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700914 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700915 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700916 static_cast<int>(reboot_count),
917 0); // url_switch_count
918 }
919}
920
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400921bool UpdateAttempterAndroid::OTARebootSucceeded() const {
922 const auto current_slot = boot_control_->GetCurrentSlot();
923 const string current_version =
924 android::base::GetProperty("ro.build.version.incremental", "");
925 int64_t previous_slot = -1;
926 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot));
927 string previous_version;
928 TEST_AND_RETURN_FALSE(
929 prefs_->GetString(kPrefsPreviousVersion, &previous_version));
930 if (previous_slot != current_slot) {
931 LOG(INFO) << "Detected a slot switch, OTA succeeded, device updated from "
932 << previous_version << " to " << current_version;
933 if (previous_version == current_version) {
934 LOG(INFO) << "Previous version is the same as current version, this is "
935 "possibly a self-OTA.";
936 }
937 return true;
938 } else {
939 LOG(INFO) << "Slot didn't switch, either the OTA is rolled back, or slot "
940 "switch never happened, or system not rebooted at all.";
941 if (previous_version != current_version) {
942 LOG(INFO) << "Slot didn't change, but version changed from "
943 << previous_version << " to " << current_version
944 << " device could be flashed.";
945 }
946 return false;
947 }
948}
949
950OTAResult UpdateAttempterAndroid::GetOTAUpdateResult() const {
951 // We only set |kPrefsSystemUpdatedMarker| if slot is actually switched, so
952 // existence of this pref is sufficient indicator. Given that we have to
953 // delete this pref after checking it. This is done in
954 // |DeltaPerformer::ResetUpdateProgress|
955 auto slot_switch_attempted = prefs_->Exists(kPrefsUpdateCompletedOnBootId);
956 auto system_rebooted = DidSystemReboot(prefs_);
957 auto ota_successful = OTARebootSucceeded();
958 if (ota_successful) {
959 return OTAResult::OTA_SUCCESSFUL;
960 }
961 if (slot_switch_attempted) {
962 if (system_rebooted) {
963 // If we attempted slot switch, but still end up on the same slot, we
964 // probably rolled back.
965 return OTAResult::ROLLED_BACK;
966 } else {
967 return OTAResult::UPDATED_NEED_REBOOT;
968 }
969 }
970 return OTAResult::NOT_ATTEMPTED;
971}
972
973void UpdateAttempterAndroid::UpdateStateAfterReboot(const OTAResult result) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700974 // Example: [ro.build.version.incremental]: [4292972]
975 string current_version =
976 android::base::GetProperty("ro.build.version.incremental", "");
977 TEST_AND_RETURN(!current_version.empty());
978
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400979 // |UpdateStateAfterReboot()| is only called after system reboot, so record
980 // boot id unconditionally
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400981 string current_boot_id;
982 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
983 prefs_->SetString(kPrefsBootId, current_boot_id);
984
Tianjie Xu90aaa102017-10-10 17:39:03 -0700985 // If there's no record of previous version (e.g. due to a data wipe), we
986 // save the info of current boot and skip the metrics report.
987 if (!prefs_->Exists(kPrefsPreviousVersion)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700988 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400989 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -0700990 ClearMetricsPrefs();
991 return;
992 }
Kelvin Zhang86603472021-05-11 12:16:27 -0400993 // update_engine restarted under the same build and same slot.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400994 if (result != OTAResult::OTA_SUCCESSFUL) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700995 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
996 // set when we start a new update.
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400997 if (prefs_->Exists(kPrefsNumReboots)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700998 int64_t reboot_count =
999 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1000 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
1001 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001002
1003 if (result == OTAResult::ROLLED_BACK) {
1004 // This will release all space previously allocated for apex
1005 // decompression. If we detect a rollback, we should release space and
1006 // return the space to user. Any subsequent attempt to install OTA will
1007 // allocate space again anyway.
1008 LOG(INFO) << "Detected a rollback, releasing space allocated for apex "
1009 "deompression.";
1010 apex_handler_android_->AllocateSpace({});
1011 DeltaPerformer::ResetUpdateProgress(prefs_, false);
1012 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001013 return;
1014 }
1015
1016 // Now that the build version changes, report the update metrics.
1017 // TODO(xunchang) check the build version is larger than the previous one.
Tianjie Xu90aaa102017-10-10 17:39:03 -07001018 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001019 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001020
1021 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
1022 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
1023 if (previous_attempt_exists) {
1024 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
1025 }
1026
1027 metrics_utils::LoadAndReportTimeToReboot(
1028 metrics_reporter_.get(), prefs_, clock_.get());
1029 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -08001030
1031 // Also reset the update progress if the build version has changed.
1032 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1033 LOG(WARNING) << "Unable to reset the update progress.";
1034 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001035}
1036
1037// Save the update start time. Reset the reboot count and attempt number if the
1038// update isn't a resume; otherwise increment the attempt number.
1039void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
1040 if (!is_resume) {
1041 metrics_utils::SetNumReboots(0, prefs_);
1042 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
1043 } else {
1044 int64_t attempt_number =
1045 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1046 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
1047 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001048 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
1049 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001050 ClearUpdateCompletedMarker();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001051}
1052
1053void UpdateAttempterAndroid::ClearMetricsPrefs() {
1054 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -07001055 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001056 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001057 prefs_->Delete(kPrefsSystemUpdatedMarker);
1058 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001059 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001060}
1061
Yifan Hongbd47d622019-12-13 14:59:58 -08001062BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
1063 return boot_control_->GetCurrentSlot();
1064}
1065
1066BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
1067 return GetCurrentSlot() == 0 ? 1 : 0;
1068}
1069
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001070uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
1071 const std::string& metadata_filename,
1072 const vector<string>& key_value_pair_headers,
1073 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -08001074 DeltaArchiveManifest manifest;
1075 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
1076 return 0;
1077 }
1078 std::map<string, string> headers;
1079 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1080 return 0;
1081 }
1082
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001083 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1084 manifest.apex_info().end());
1085 uint64_t apex_size_required = 0;
1086 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001087 auto result = apex_handler_android_->CalculateSize(apex_infos);
1088 if (!result.ok()) {
1089 LogAndSetError(error,
1090 FROM_HERE,
1091 "Failed to calculate size required for compressed APEX");
1092 return 0;
1093 }
1094 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001095 }
1096
Yifan Hong65613032020-01-09 17:52:13 -08001097 string payload_id = GetPayloadId(headers);
1098 uint64_t required_size = 0;
1099 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1100 boot_control_,
1101 GetTargetSlot(),
1102 manifest,
1103 payload_id,
1104 &required_size)) {
1105 if (required_size == 0) {
1106 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
1107 return 0;
1108 } else {
1109 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001110 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001111 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001112 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001113 }
1114 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001115
1116 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001117 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001118 LOG(ERROR) << "Insufficient space for apex decompression: "
1119 << apex_size_required << " bytes";
1120 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001121 }
Yifan Hong65613032020-01-09 17:52:13 -08001122
1123 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001124 return 0;
1125}
1126
Yifan Hong40bb0d02020-02-24 17:33:14 -08001127void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1128 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Yifan Hong2236ea02019-12-13 16:11:22 -08001129 brillo::ErrorPtr* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001130 if (cleanup_previous_update_code_.has_value()) {
1131 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1132 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1133 if (callback) {
1134 callback->OnCleanupComplete(
1135 static_cast<int32_t>(*cleanup_previous_update_code_));
1136 }
1137 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001138 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001139 if (callback) {
1140 auto callback_ptr = callback.get();
1141 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1142 callback_ptr->RegisterForDeathNotifications(
1143 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1144 base::Unretained(this),
1145 base::Unretained(callback_ptr)));
1146 }
1147 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001148}
1149
Tianjie7f8f2ab2021-07-23 17:08:50 -07001150bool UpdateAttempterAndroid::setShouldSwitchSlotOnReboot(
1151 const std::string& metadata_filename, brillo::ErrorPtr* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -07001152 LOG(INFO) << "setShouldSwitchSlotOnReboot(" << metadata_filename << ")";
Tianjie7f8f2ab2021-07-23 17:08:50 -07001153 if (processor_->IsRunning()) {
1154 return LogAndSetError(
1155 error, FROM_HERE, "Already processing an update, cancel it first.");
1156 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001157 DeltaArchiveManifest manifest;
1158 TEST_AND_RETURN_FALSE(
1159 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
1160
1161 if (!boot_control_->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
1162 GetCurrentSlot(),
1163 GetTargetSlot(),
1164 manifest,
1165 false /* should update */,
1166 nullptr)) {
1167 return LogAndSetError(
1168 error, FROM_HERE, "Failed to PreparePartitionsForUpdate");
1169 }
1170 InstallPlan install_plan_;
1171 install_plan_.source_slot = GetCurrentSlot();
1172 install_plan_.target_slot = GetTargetSlot();
1173 // Don't do verity computation, just hash the partitions
1174 install_plan_.write_verity = false;
1175 // Don't run postinstall, we just need PostinstallAction to switch the slots.
1176 install_plan_.run_post_install = false;
1177 install_plan_.is_resume = true;
1178
1179 CHECK_NE(install_plan_.source_slot, UINT32_MAX);
1180 CHECK_NE(install_plan_.target_slot, UINT32_MAX);
1181
1182 ErrorCode error_code;
1183 if (!install_plan_.ParsePartitions(manifest.partitions(),
1184 boot_control_,
1185 manifest.block_size(),
1186 &error_code)) {
1187 return LogAndSetError(error,
1188 FROM_HERE,
1189 "Failed to LoadPartitionsFromSlots " +
1190 utils::ErrorCodeToString(error_code));
1191 }
1192
1193 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
1194 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
1195 boot_control_->GetDynamicPartitionControl());
1196 auto postinstall_runner_action =
1197 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
1198 SetStatusAndNotify(UpdateStatus::VERIFYING);
1199 filesystem_verifier_action->set_delegate(this);
1200 postinstall_runner_action->set_delegate(this);
1201
1202 // Bond them together. We have to use the leaf-types when calling
1203 // BondActions().
1204 BondActions(install_plan_action.get(), filesystem_verifier_action.get());
1205 BondActions(filesystem_verifier_action.get(),
1206 postinstall_runner_action.get());
1207
1208 processor_->EnqueueAction(std::move(install_plan_action));
1209 processor_->EnqueueAction(std::move(filesystem_verifier_action));
1210 processor_->EnqueueAction(std::move(postinstall_runner_action));
1211 ScheduleProcessingStart();
1212 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001213}
1214
1215bool UpdateAttempterAndroid::resetShouldSwitchSlotOnReboot(
1216 brillo::ErrorPtr* error) {
1217 if (processor_->IsRunning()) {
1218 return LogAndSetError(
1219 error, FROM_HERE, "Already processing an update, cancel it first.");
1220 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001221 // Update the boot flags so the current slot has higher priority.
1222 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot())) {
1223 return LogAndSetError(error, FROM_HERE, "Failed to SetActiveBootSlot");
1224 }
1225
1226 // Mark the current slot as successful again, since marking it as active
1227 // may reset the successful bit. We ignore the result of whether marking
1228 // the current slot as successful worked.
1229 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {}))) {
1230 return LogAndSetError(
1231 error, FROM_HERE, "Failed to MarkBootSuccessfulAsync");
1232 }
1233
1234 // Resets the warm reset property since we won't switch the slot.
1235 hardware_->SetWarmReset(false);
1236
1237 // Resets the vbmeta digest.
1238 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
1239 LOG(INFO) << "Slot switch cancelled.";
1240 SetStatusAndNotify(UpdateStatus::IDLE);
1241 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001242}
1243
Yifan Hong90965502020-02-19 15:22:47 -08001244void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1245 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1246 // is in progress, skip enqueueing the action.
1247 if (processor_->IsRunning()) {
1248 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1249 << "be done when the current update finishes.";
1250 return;
1251 }
1252 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1253 auto action =
1254 boot_control_->GetDynamicPartitionControl()
1255 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1256 processor_->EnqueueAction(std::move(action));
1257 processor_->set_delegate(this);
1258 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1259 processor_->StartProcessing();
1260}
1261
Yifan Hong40bb0d02020-02-24 17:33:14 -08001262void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1263 for (auto&& callback : cleanup_previous_update_callbacks_) {
1264 callback->OnCleanupProgressUpdate(progress);
1265 }
1266}
1267
1268void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1269 CHECK(cleanup_previous_update_code_.has_value());
1270 for (auto&& callback : cleanup_previous_update_callbacks_) {
1271 callback->OnCleanupComplete(
1272 static_cast<int32_t>(*cleanup_previous_update_code_));
1273 }
1274 cleanup_previous_update_callbacks_.clear();
1275}
1276
1277void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1278 CleanupSuccessfulUpdateCallbackInterface* callback) {
1279 auto end_it =
1280 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1281 cleanup_previous_update_callbacks_.end(),
1282 [&](const auto& e) { return e.get() == callback; });
1283 cleanup_previous_update_callbacks_.erase(
1284 end_it, cleanup_previous_update_callbacks_.end());
1285}
Yifan Hong90965502020-02-19 15:22:47 -08001286
Alex Deymo5e3ea272016-01-28 13:42:23 -08001287} // namespace chromeos_update_engine