blob: 9b90030f8e39e22603c4bb42c11d7452d38dfd16 [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>
Daniel Zhengda4f7292022-09-02 22:59:32 +000024#include <vector>
Alex Deymo5e3ea272016-01-28 13:42:23 -080025
Tianjie Xu90aaa102017-10-10 17:39:03 -070026#include <android-base/properties.h>
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090027#include <android-base/unique_fd.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080028#include <base/bind.h>
29#include <base/logging.h>
Alex Deymo218397f2016-02-04 23:55:10 -080030#include <base/strings/string_number_conversions.h>
Sen Jiang2703ef42017-03-16 13:36:21 -070031#include <brillo/data_encoding.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080032#include <brillo/message_loops/message_loop.h>
Alex Deymo218397f2016-02-04 23:55:10 -080033#include <brillo/strings/string_utils.h>
Sen Jiangacbdd1c2017-10-19 13:30:19 -070034#include <log/log_safetynet.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080035
Amin Hassaniec7bc112020-10-29 16:47:58 -070036#include "update_engine/aosp/cleanup_previous_update_action.h"
Daniel Zhengda4f7292022-09-02 22:59:32 +000037#include "update_engine/common/clock.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080038#include "update_engine/common/constants.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070039#include "update_engine/common/daemon_state_interface.h"
40#include "update_engine/common/download_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080041#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070042#include "update_engine/common/file_fetcher.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070043#include "update_engine/common/metrics_reporter_interface.h"
44#include "update_engine/common/network_selector.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080045#include "update_engine/common/utils.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070046#include "update_engine/metrics_utils.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080047#include "update_engine/payload_consumer/delta_performer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080048#include "update_engine/payload_consumer/file_descriptor.h"
49#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080050#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Kelvin Zhangcfc531f2022-08-24 17:58:53 +000051#include "update_engine/payload_consumer/partition_writer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080052#include "update_engine/payload_consumer/payload_constants.h"
53#include "update_engine/payload_consumer/payload_metadata.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070054#include "update_engine/payload_consumer/payload_verifier.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080055#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070056#include "update_engine/update_boot_flags_action.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080057#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080058
Alex Deymo14c0da82016-07-20 16:45:45 -070059#ifndef _UE_SIDELOAD
60// Do not include support for external HTTP(s) urls when building
61// update_engine_sideload.
62#include "update_engine/libcurl_http_fetcher.h"
63#endif
64
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090065using android::base::unique_fd;
Alex Deymo5e3ea272016-01-28 13:42:23 -080066using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070067using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080068using base::TimeDelta;
69using base::TimeTicks;
Alex Deymo5e3ea272016-01-28 13:42:23 -080070using std::string;
71using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070072using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080073
74namespace chromeos_update_engine {
75
76namespace {
77
Alex Deymo0d298542016-03-30 18:31:49 -070078// Minimum threshold to broadcast an status update in progress and time.
79const double kBroadcastThresholdProgress = 0.01; // 1%
80const int kBroadcastThresholdSeconds = 10;
81
Alex Deymo5e3ea272016-01-28 13:42:23 -080082const char* const kErrorDomain = "update_engine";
83// TODO(deymo): Convert the different errors to a numeric value to report them
84// back on the service error.
85const char* const kGenericError = "generic_error";
86
87// Log and set the error on the passed ErrorPtr.
88bool LogAndSetError(brillo::ErrorPtr* error,
Jakub Pawlowski7e1dcf72018-07-26 00:29:42 -070089 const base::Location& location,
Alex Deymo5e3ea272016-01-28 13:42:23 -080090 const string& reason) {
91 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
92 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
93 << reason;
94 return false;
95}
96
Sen Jiangfe522822017-10-31 15:14:11 -070097bool GetHeaderAsBool(const string& header, bool default_value) {
98 int value = 0;
99 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
100 return value == 1;
101 return default_value;
102}
103
Yifan Hongbd47d622019-12-13 14:59:58 -0800104bool ParseKeyValuePairHeaders(const vector<string>& key_value_pair_headers,
105 std::map<string, string>* headers,
106 brillo::ErrorPtr* error) {
107 for (const string& key_value_pair : key_value_pair_headers) {
108 string key;
109 string value;
110 if (!brillo::string_utils::SplitAtFirst(
111 key_value_pair, "=", &key, &value, false)) {
112 return LogAndSetError(
113 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
114 }
115 if (!headers->emplace(key, value).second)
116 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
117 }
118 return true;
119}
120
121// Unique identifier for the payload. An empty string means that the payload
122// can't be resumed.
123string GetPayloadId(const std::map<string, string>& headers) {
124 return (headers.count(kPayloadPropertyFileHash)
125 ? headers.at(kPayloadPropertyFileHash)
126 : "") +
127 (headers.count(kPayloadPropertyMetadataHash)
128 ? headers.at(kPayloadPropertyMetadataHash)
129 : "");
130}
131
Alex Deymo5e3ea272016-01-28 13:42:23 -0800132} // namespace
133
134UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700135 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800136 PrefsInterface* prefs,
137 BootControlInterface* boot_control,
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000138 HardwareInterface* hardware,
139 std::unique_ptr<ApexHandlerInterface> apex_handler)
Alex Deymo5e3ea272016-01-28 13:42:23 -0800140 : daemon_state_(daemon_state),
141 prefs_(prefs),
142 boot_control_(boot_control),
143 hardware_(hardware),
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000144 apex_handler_android_(std::move(apex_handler)),
Tianjie Xu1b661142017-09-28 14:03:42 -0700145 processor_(new ActionProcessor()),
Tianjie Xud4c5deb2017-10-24 11:17:03 -0700146 clock_(new Clock()) {
Yifan Hongc514f662021-02-04 11:18:43 -0800147 metrics_reporter_ = metrics::CreateMetricsReporter(
Kelvin Zhang9a5e3682021-03-29 12:58:48 -0400148 boot_control_->GetDynamicPartitionControl(), &install_plan_);
Alex Deymo87792ea2016-07-25 15:40:36 -0700149 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800150}
151
152UpdateAttempterAndroid::~UpdateAttempterAndroid() {
153 // Release ourselves as the ActionProcessor's delegate to prevent
154 // re-scheduling the updates due to the processing stopped.
155 processor_->set_delegate(nullptr);
156}
157
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400158[[nodiscard]] static bool DidSystemReboot(PrefsInterface* prefs) {
159 string boot_id;
160 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
161 string old_boot_id;
162 // If no previous boot id found, treat as a reboot and write boot ID.
163 if (!prefs->GetString(kPrefsBootId, &old_boot_id)) {
164 return true;
165 }
166 return old_boot_id != boot_id;
167}
168
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400169std::ostream& operator<<(std::ostream& out, OTAResult result) {
170 switch (result) {
171 case OTAResult::NOT_ATTEMPTED:
172 out << "OTAResult::NOT_ATTEMPTED";
173 break;
174 case OTAResult::ROLLED_BACK:
175 out << "OTAResult::ROLLED_BACK";
176 break;
177 case OTAResult::UPDATED_NEED_REBOOT:
178 out << "OTAResult::UPDATED_NEED_REBOOT";
179 break;
180 case OTAResult::OTA_SUCCESSFUL:
181 out << "OTAResult::OTA_SUCCESSFUL";
182 break;
183 }
184 return out;
185}
186
Alex Deymo5e3ea272016-01-28 13:42:23 -0800187void UpdateAttempterAndroid::Init() {
188 // In case of update_engine restart without a reboot we need to restore the
189 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700190 if (UpdateCompletedOnThisBoot()) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400191 LOG(INFO) << "Updated installed but update_engine is restarted without "
192 "device reboot. Resuming old state.";
Alex Deymo0e061ae2016-02-09 17:49:03 -0800193 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700194 } else {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400195 const auto result = GetOTAUpdateResult();
196 LOG(INFO) << result;
Alex Deymo0e061ae2016-02-09 17:49:03 -0800197 SetStatusAndNotify(UpdateStatus::IDLE);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400198 if (DidSystemReboot(prefs_)) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400199 UpdateStateAfterReboot(result);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400200 }
201
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700202#ifdef _UE_SIDELOAD
203 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
204 << "ApplyPayload will call it later.";
205#else
Yifan Hong90965502020-02-19 15:22:47 -0800206 ScheduleCleanupPreviousUpdate();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700207#endif
Tianjie Xu90aaa102017-10-10 17:39:03 -0700208 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800209}
210
211bool UpdateAttempterAndroid::ApplyPayload(
212 const string& payload_url,
213 int64_t payload_offset,
214 int64_t payload_size,
215 const vector<string>& key_value_pair_headers,
216 brillo::ErrorPtr* error) {
217 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
218 return LogAndSetError(
219 error, FROM_HERE, "An update already applied, waiting for reboot");
220 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700221 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800222 return LogAndSetError(
223 error, FROM_HERE, "Already processing an update, cancel it first.");
224 }
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100225 DCHECK_EQ(status_, UpdateStatus::IDLE);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800226
Alex Deymo218397f2016-02-04 23:55:10 -0800227 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800228 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
229 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800230 }
231
Yifan Hongbd47d622019-12-13 14:59:58 -0800232 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800233
234 // Setup the InstallPlan based on the request.
235 install_plan_ = InstallPlan();
236
237 install_plan_.download_url = payload_url;
238 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800239 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800240 InstallPlan::Payload payload;
241 payload.size = payload_size;
242 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800243 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800244 &payload.size)) {
245 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800246 }
247 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700248 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800249 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700250 LOG(WARNING) << "Unable to decode base64 file hash: "
251 << headers[kPayloadPropertyFileHash];
252 }
Alex Deymo218397f2016-02-04 23:55:10 -0800253 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800254 &payload.metadata_size)) {
255 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800256 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700257 // The |payload.type| is not used anymore since minor_version 3.
258 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800259 install_plan_.payloads.push_back(payload);
260
Alex Deymo5e3ea272016-01-28 13:42:23 -0800261 // The |public_key_rsa| key would override the public key stored on disk.
262 install_plan_.public_key_rsa = "";
263
264 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
265 install_plan_.is_resume = !payload_id.empty() &&
266 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
267 if (!install_plan_.is_resume) {
Kelvin Zhang42c2d552022-07-25 11:04:00 -0700268 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong55c2bfe2020-01-13 17:01:19 -0800269 // No need to reset dynamic_partititon_metadata_updated. If previous calls
270 // to AllocateSpaceForPayload uses the same payload_id, reuse preallocated
271 // space. Otherwise, DeltaPerformer re-allocates space when the payload is
272 // applied.
273 if (!DeltaPerformer::ResetUpdateProgress(
274 prefs_,
275 false /* quick */,
276 true /* skip_dynamic_partititon_metadata_updated */)) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800277 LOG(WARNING) << "Unable to reset the update progress.";
278 }
279 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
280 LOG(WARNING) << "Unable to save the update check response hash.";
281 }
282 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800283 install_plan_.source_slot = GetCurrentSlot();
284 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700285
Alex Deymofb905d92016-06-03 19:26:58 -0700286 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700287 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
288
289 install_plan_.switch_slot_on_reboot =
290 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
291
Tianjie Xu087de9d2019-11-01 17:11:22 -0700292 install_plan_.run_post_install =
293 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800294
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700295 // Skip writing verity if we're resuming and verity has already been written.
296 install_plan_.write_verity = true;
297 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
298 bool verity_written = false;
299 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
300 verity_written) {
301 install_plan_.write_verity = false;
302 }
303 }
304
Alex Deymo87792ea2016-07-25 15:40:36 -0700305 NetworkId network_id = kDefaultNetworkId;
306 if (!headers[kPayloadPropertyNetworkId].empty()) {
307 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
308 &network_id)) {
309 return LogAndSetError(
310 error,
311 FROM_HERE,
312 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
313 }
314 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700315 return LogAndSetError(
316 error,
317 FROM_HERE,
318 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700319 }
320 }
321
Alex Deymo5e3ea272016-01-28 13:42:23 -0800322 LOG(INFO) << "Using this install plan:";
323 install_plan_.Dump();
324
Amin Hassani667cf7b2018-07-25 14:32:00 -0700325 HttpFetcher* fetcher = nullptr;
326 if (FileFetcher::SupportedUrl(payload_url)) {
327 DLOG(INFO) << "Using FileFetcher for file URL.";
328 fetcher = new FileFetcher();
329 } else {
330#ifdef _UE_SIDELOAD
331 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
332#else
Kelvin Zhangc7a1d1f2022-07-29 13:36:29 -0700333 LibcurlHttpFetcher* libcurl_fetcher = new LibcurlHttpFetcher(hardware_);
Kelvin Zhang3cc4fa32022-09-27 16:15:10 -0700334 if (!headers[kPayloadDownloadRetry].empty()) {
335 libcurl_fetcher->set_max_retry_count(
336 atoi(headers[kPayloadDownloadRetry].c_str()));
337 }
Amin Hassani667cf7b2018-07-25 14:32:00 -0700338 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
339 fetcher = libcurl_fetcher;
340#endif // _UE_SIDELOAD
341 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800342 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800343 if (!headers[kPayloadPropertyAuthorization].empty())
344 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
345 if (!headers[kPayloadPropertyUserAgent].empty())
346 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
347
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700348 if (!headers[kPayloadPropertyNetworkProxy].empty()) {
349 LOG(INFO) << "Using proxy url from payload headers: "
350 << headers[kPayloadPropertyNetworkProxy];
351 fetcher->SetProxies({headers[kPayloadPropertyNetworkProxy]});
352 }
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000353 if (!headers[kPayloadDisableVABC].empty()) {
354 install_plan_.disable_vabc = true;
355 }
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700356
Amin Hassani667cf7b2018-07-25 14:32:00 -0700357 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800358
Alex Deymo5e3ea272016-01-28 13:42:23 -0800359 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700360
361 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
362 // TODO(xunchang) report the metrics for unresumable updates
363
Amin Hassani667cf7b2018-07-25 14:32:00 -0700364 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800365 return true;
366}
367
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900368bool UpdateAttempterAndroid::ApplyPayload(
369 int fd,
370 int64_t payload_offset,
371 int64_t payload_size,
372 const vector<string>& key_value_pair_headers,
373 brillo::ErrorPtr* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100374 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000375 // already running update will be terminated (existing file descriptor will be
376 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100377 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
378 return LogAndSetError(
379 error, FROM_HERE, "An update already applied, waiting for reboot");
380 }
381 if (processor_->IsRunning()) {
382 return LogAndSetError(
383 error, FROM_HERE, "Already processing an update, cancel it first.");
384 }
385 DCHECK_EQ(status_, UpdateStatus::IDLE);
386
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900387 payload_fd_.reset(dup(fd));
388 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
389
390 return ApplyPayload(
391 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
392}
393
Alex Deymo5e3ea272016-01-28 13:42:23 -0800394bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700395 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800396 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
397 processor_->SuspendProcessing();
398 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800399}
400
401bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700402 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800403 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
404 processor_->ResumeProcessing();
405 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800406}
407
408bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700409 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800410 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800411 processor_->StopProcessing();
412 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800413}
414
Alex Deymo3b678db2016-02-09 11:50:06 -0800415bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
416 LOG(INFO) << "Attempting to reset state from "
417 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700418 if (processor_->IsRunning()) {
419 return LogAndSetError(
420 error, FROM_HERE, "Already processing an update, cancel it first.");
421 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800422
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000423 if (apex_handler_android_ != nullptr) {
424 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
425 std::vector<ApexInfo> apex_infos_blank;
426 apex_handler_android_->AllocateSpace(apex_infos_blank);
427 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400428 // Remove the reboot marker so that if the machine is rebooted
429 // after resetting to idle state, it doesn't go back to
430 // UpdateStatus::UPDATED_NEED_REBOOT state.
431 if (!ClearUpdateCompletedMarker()) {
432 return LogAndSetError(error,
433 FROM_HERE,
434 "Failed to reset the status because "
435 "ClearUpdateCompletedMarker() failed");
436 }
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000437
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700438 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
439 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000440 << "space might not be freed.";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700441 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800442 switch (status_) {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700443 case UpdateStatus::IDLE: {
Alex Deymo3b678db2016-02-09 11:50:06 -0800444 return true;
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700445 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800446
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800447 case UpdateStatus::UPDATED_NEED_REBOOT: {
Kelvin Zhang20982a52021-08-13 12:31:16 -0700448 const bool ret_value = resetShouldSwitchSlotOnReboot(error);
449 if (ret_value) {
450 LOG(INFO) << "Reset status successful";
Alex Deymo3b678db2016-02-09 11:50:06 -0800451 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700452 return ret_value;
Alex Deymo3b678db2016-02-09 11:50:06 -0800453 }
454
455 default:
456 return LogAndSetError(
457 error,
458 FROM_HERE,
459 "Reset not allowed in this state. Cancel the ongoing update first");
460 }
461}
462
Yifan Hongbd47d622019-12-13 14:59:58 -0800463bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
464 const std::string& metadata_filename,
465 DeltaArchiveManifest* manifest,
466 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800467 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
468 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
469 return LogAndSetError(
470 error, FROM_HERE, "Failed to open " + metadata_filename);
471 }
472 brillo::Blob metadata(kMaxPayloadHeaderSize);
473 if (!fd->Read(metadata.data(), metadata.size())) {
474 return LogAndSetError(
475 error,
476 FROM_HERE,
477 "Failed to read payload header from " + metadata_filename);
478 }
Daniel Zhengda4f7292022-09-02 22:59:32 +0000479 ErrorCode errorcode{};
Sen Jiang8371c1c2018-02-01 13:46:39 -0800480 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700481 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800482 MetadataParseResult::kSuccess) {
483 return LogAndSetError(error,
484 FROM_HERE,
485 "Failed to parse payload header: " +
486 utils::ErrorCodeToString(errorcode));
487 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700488 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
489 payload_metadata.GetMetadataSignatureSize();
490 if (metadata_size < kMaxPayloadHeaderSize ||
491 metadata_size >
492 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800493 return LogAndSetError(
494 error,
495 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700496 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800497 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700498 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800499 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
500 metadata.size() - kMaxPayloadHeaderSize)) {
501 return LogAndSetError(
502 error,
503 FROM_HERE,
504 "Failed to read metadata and signature from " + metadata_filename);
505 }
506 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800507
Tianjie Xu7a78d632019-10-08 16:32:39 -0700508 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
509 constants::kUpdateCertificatesPath);
510 if (!payload_verifier) {
511 return LogAndSetError(error,
512 FROM_HERE,
513 "Failed to create the payload verifier from " +
514 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800515 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700516 errorcode = payload_metadata.ValidateMetadataSignature(
517 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800518 if (errorcode != ErrorCode::kSuccess) {
519 return LogAndSetError(error,
520 FROM_HERE,
521 "Failed to validate metadata signature: " +
522 utils::ErrorCodeToString(errorcode));
523 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800524 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800525 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
526 }
527
Yifan Hongbd47d622019-12-13 14:59:58 -0800528 return true;
529}
530
531bool UpdateAttempterAndroid::VerifyPayloadApplicable(
532 const std::string& metadata_filename, brillo::ErrorPtr* error) {
533 DeltaArchiveManifest manifest;
534 TEST_AND_RETURN_FALSE(
535 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
536
537 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
Daniel Zhengda4f7292022-09-02 22:59:32 +0000538 ErrorCode errorcode{};
Yifan Hongbd47d622019-12-13 14:59:58 -0800539
540 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800541 for (const PartitionUpdate& partition : manifest.partitions()) {
542 if (!partition.has_old_partition_info())
543 continue;
544 string partition_path;
545 if (!boot_control_->GetPartitionDevice(
546 partition.partition_name(), current_slot, &partition_path)) {
547 return LogAndSetError(
548 error,
549 FROM_HERE,
550 "Failed to get partition device for " + partition.partition_name());
551 }
552 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
553 return LogAndSetError(
554 error, FROM_HERE, "Failed to open " + partition_path);
555 }
556 for (const InstallOperation& operation : partition.operations()) {
557 if (!operation.has_src_sha256_hash())
558 continue;
559 brillo::Blob source_hash;
560 if (!fd_utils::ReadAndHashExtents(fd,
561 operation.src_extents(),
562 manifest.block_size(),
563 &source_hash)) {
564 return LogAndSetError(
565 error, FROM_HERE, "Failed to hash " + partition_path);
566 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400567 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800568 source_hash, operation, fd, &errorcode)) {
569 return false;
570 }
571 }
572 fd->Close();
573 }
574 return true;
575}
576
Alex Deymo5e3ea272016-01-28 13:42:23 -0800577void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
578 ErrorCode code) {
579 LOG(INFO) << "Processing Done.";
580
Yifan Hong90965502020-02-19 15:22:47 -0800581 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
582 TerminateUpdateAndNotify(code);
583 return;
584 }
585
Alex Deymo5990bf32016-07-19 17:01:41 -0700586 switch (code) {
587 case ErrorCode::kSuccess:
588 // Update succeeded.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400589 if (!WriteUpdateCompletedMarker()) {
590 LOG(ERROR) << "Failed to write update completion marker";
591 }
Alex Deymo5990bf32016-07-19 17:01:41 -0700592 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800593
Alex Deymo5990bf32016-07-19 17:01:41 -0700594 LOG(INFO) << "Update successfully applied, waiting to reboot.";
595 break;
596
597 case ErrorCode::kFilesystemCopierError:
598 case ErrorCode::kNewRootfsVerificationError:
599 case ErrorCode::kNewKernelVerificationError:
600 case ErrorCode::kFilesystemVerifierError:
601 case ErrorCode::kDownloadStateInitializationError:
602 // Reset the ongoing update for these errors so it starts from the
603 // beginning next time.
604 DeltaPerformer::ResetUpdateProgress(prefs_, false);
605 LOG(INFO) << "Resetting update progress.";
606 break;
607
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700608 case ErrorCode::kPayloadTimestampError:
609 // SafetyNet logging, b/36232423
610 android_errorWriteLog(0x534e4554, "36232423");
611 break;
612
Alex Deymo5990bf32016-07-19 17:01:41 -0700613 default:
614 // Ignore all other error codes.
615 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700616 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800617
618 TerminateUpdateAndNotify(code);
619}
620
621void UpdateAttempterAndroid::ProcessingStopped(
622 const ActionProcessor* processor) {
623 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
624}
625
626void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
627 AbstractAction* action,
628 ErrorCode code) {
629 // Reset download progress regardless of whether or not the download
630 // action succeeded.
631 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800632 if (type == CleanupPreviousUpdateAction::StaticType() ||
633 (type == NoOpAction::StaticType() &&
634 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
635 cleanup_previous_update_code_ = code;
636 NotifyCleanupPreviousUpdateCallbacksAndClear();
637 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000638 // download_progress_ is actually used by other actions, such as
639 // filesystem_verify_action. Therefore we always clear it.
640 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700641 if (type == PostinstallRunnerAction::StaticType()) {
642 bool succeeded =
643 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
644 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
645 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800646 if (code != ErrorCode::kSuccess) {
647 // If an action failed, the ActionProcessor will cancel the whole thing.
648 return;
649 }
Yifan Hong83517502020-02-19 15:34:13 -0800650 if (type == UpdateBootFlagsAction::StaticType()) {
651 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
652 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800653 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400654 auto download_action = static_cast<DownloadAction*>(action);
655 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000656 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700657 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000658 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700659 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800660 }
661}
662
663void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
664 uint64_t bytes_received,
665 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700666 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800667 if (total)
668 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700669 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800670 download_progress_ = progress;
671 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700672 } else {
673 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800674 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700675
676 // Update the bytes downloaded in prefs.
677 int64_t current_bytes_downloaded =
678 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
679 int64_t total_bytes_downloaded =
680 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
681 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
682 current_bytes_downloaded + bytes_progressed);
683 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
684 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800685}
686
687bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
688 // TODO(deymo): Notify the DownloadAction that it should cancel the update
689 // download.
690 return false;
691}
692
693void UpdateAttempterAndroid::DownloadComplete() {
694 // Nothing needs to be done when the download completes.
695}
696
Alex Deymo0d298542016-03-30 18:31:49 -0700697void UpdateAttempterAndroid::ProgressUpdate(double progress) {
698 // Self throttle based on progress. Also send notifications if progress is
699 // too slow.
700 if (progress == 1.0 ||
701 progress - download_progress_ >= kBroadcastThresholdProgress ||
702 TimeTicks::Now() - last_notify_time_ >=
703 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
704 download_progress_ = progress;
705 SetStatusAndNotify(status_);
706 }
707}
708
Kelvin Zhang70eef232020-06-12 20:32:40 +0000709void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
710 assert(status_ == UpdateStatus::VERIFYING);
711 ProgressUpdate(progress);
712}
713
Alex Deymo5e3ea272016-01-28 13:42:23 -0800714void UpdateAttempterAndroid::ScheduleProcessingStart() {
715 LOG(INFO) << "Scheduling an action processor start.";
Kelvin Zhang20982a52021-08-13 12:31:16 -0700716 processor_->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800717 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700718 FROM_HERE,
719 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
720 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800721}
722
723void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
724 if (status_ == UpdateStatus::IDLE) {
725 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
726 return;
727 }
728
Yifan Hong90965502020-02-19 15:22:47 -0800729 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400730 ClearUpdateCompletedMarker();
Yifan Hong90965502020-02-19 15:22:47 -0800731 LOG(INFO) << "Terminating cleanup previous update.";
732 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700733 for (auto observer : daemon_state_->service_observers())
734 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800735 return;
736 }
737
Yifan Hong9194ce82019-11-07 11:03:42 -0800738 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700739
Alex Deymo0d298542016-03-30 18:31:49 -0700740 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800741 UpdateStatus new_status =
742 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
743 : UpdateStatus::IDLE);
744 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900745 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800746
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700747 // The network id is only applicable to one download attempt and once it's
748 // done the network id should not be re-used anymore.
749 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
750 LOG(WARNING) << "Unable to unbind network.";
751 }
752
Alex Deymo5e3ea272016-01-28 13:42:23 -0800753 for (auto observer : daemon_state_->service_observers())
754 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700755
Tianjie Xu90aaa102017-10-10 17:39:03 -0700756 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
757 ClearMetricsPrefs();
758 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800759 // We should only reset the PayloadAttemptNumber if the update succeeds, or
760 // we switch to a different payload.
761 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700762 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700763 // Clear the total bytes downloaded if and only if the update succeeds.
764 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700765 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800766}
767
768void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
769 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700770 size_t payload_size =
771 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700772 UpdateEngineStatus status_to_send = {.status = status_,
773 .progress = download_progress_,
774 .new_size_bytes = payload_size};
775
Alex Deymo5e3ea272016-01-28 13:42:23 -0800776 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700777 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800778 }
779 last_notify_time_ = TimeTicks::Now();
780}
781
Amin Hassani667cf7b2018-07-25 14:32:00 -0700782void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800783 CHECK(!processor_->IsRunning());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800784
785 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700786 auto update_boot_flags_action =
787 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800788 auto cleanup_previous_update_action =
789 boot_control_->GetDynamicPartitionControl()
790 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700791 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
792 auto download_action =
793 std::make_unique<DownloadAction>(prefs_,
794 boot_control_,
795 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700796 fetcher, // passes ownership
Kelvin Zhang1304fe72021-10-06 19:12:12 -0700797 true /* interactive */,
798 update_certificates_path_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800799 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700800 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700801 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
802 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700803 auto postinstall_runner_action =
804 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000805 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700806 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800807
Alex Deymo5e3ea272016-01-28 13:42:23 -0800808 // Bond them together. We have to use the leaf-types when calling
809 // BondActions().
810 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700811 BondActions(download_action.get(), filesystem_verifier_action.get());
812 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800813 postinstall_runner_action.get());
814
Amin Hassani667cf7b2018-07-25 14:32:00 -0700815 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800816 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700817 processor_->EnqueueAction(std::move(install_plan_action));
818 processor_->EnqueueAction(std::move(download_action));
819 processor_->EnqueueAction(std::move(filesystem_verifier_action));
820 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800821}
822
Alex Deymo5e3ea272016-01-28 13:42:23 -0800823bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400824 LOG(INFO) << "Writing update complete marker.";
Alex Deymo5e3ea272016-01-28 13:42:23 -0800825 string boot_id;
826 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400827 TEST_AND_RETURN_FALSE(
828 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id));
829 TEST_AND_RETURN_FALSE(
830 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot()));
831 return true;
832}
833
834bool UpdateAttempterAndroid::ClearUpdateCompletedMarker() {
835 LOG(INFO) << "Clearing update complete marker.";
836 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsUpdateCompletedOnBootId));
837 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsPreviousSlot));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800838 return true;
839}
840
841bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
842 // In case of an update_engine restart without a reboot, we stored the boot_id
843 // when the update was completed by setting a pref, so we can check whether
844 // the last update was on this boot or a previous one.
845 string boot_id;
846 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
847
848 string update_completed_on_boot_id;
849 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
850 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
851 &update_completed_on_boot_id) &&
852 update_completed_on_boot_id == boot_id);
853}
854
Tianjie Xu90aaa102017-10-10 17:39:03 -0700855// Collect and report the android metrics when we terminate the update.
856void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
857 ErrorCode error_code) {
858 int64_t attempt_number =
859 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
860 PayloadType payload_type = kPayloadTypeFull;
861 int64_t payload_size = 0;
862 for (const auto& p : install_plan_.payloads) {
863 if (p.type == InstallPayloadType::kDelta)
864 payload_type = kPayloadTypeDelta;
865 payload_size += p.size;
866 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700867 // In some cases, e.g. after calling |setShouldSwitchSlotOnReboot()|, this
868 // function will be triggered, but payload_size in this case might be 0, if so
869 // skip reporting any metrics.
870 if (payload_size == 0) {
871 return;
872 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700873
874 metrics::AttemptResult attempt_result =
875 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700876 Time boot_time_start = Time::FromInternalValue(
877 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
878 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700879 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700880 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
881 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700882
883 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700884 static_cast<int>(attempt_number),
885 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700886 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700887 duration_uptime,
888 payload_size,
889 attempt_result,
890 error_code);
891
Tianjie Xud4777a12017-10-24 14:54:18 -0700892 int64_t current_bytes_downloaded =
893 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
894 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
895 current_bytes_downloaded,
896 0,
897 DownloadSource::kNumDownloadSources,
898 metrics::DownloadErrorCode::kUnset,
899 metrics::ConnectionType::kUnset);
900
Tianjie Xu90aaa102017-10-10 17:39:03 -0700901 if (error_code == ErrorCode::kSuccess) {
902 int64_t reboot_count =
903 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
904 string build_version;
905 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700906
907 // For android metrics, we only care about the total bytes downloaded
908 // for all sources; for now we assume the only download source is
909 // HttpsServer.
910 int64_t total_bytes_downloaded =
911 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
912 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
913 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
914 total_bytes_downloaded;
915
916 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700917 if (total_bytes_downloaded >= payload_size) {
918 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700919 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700920 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
921 } else {
922 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
923 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700924 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700925
Tianjie Xu90aaa102017-10-10 17:39:03 -0700926 metrics_reporter_->ReportSuccessfulUpdateMetrics(
927 static_cast<int>(attempt_number),
928 0, // update abandoned count
929 payload_type,
930 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700931 num_bytes_downloaded,
932 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700933 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700934 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700935 static_cast<int>(reboot_count),
936 0); // url_switch_count
937 }
938}
939
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400940bool UpdateAttempterAndroid::OTARebootSucceeded() const {
941 const auto current_slot = boot_control_->GetCurrentSlot();
942 const string current_version =
943 android::base::GetProperty("ro.build.version.incremental", "");
944 int64_t previous_slot = -1;
945 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot));
946 string previous_version;
947 TEST_AND_RETURN_FALSE(
948 prefs_->GetString(kPrefsPreviousVersion, &previous_version));
949 if (previous_slot != current_slot) {
950 LOG(INFO) << "Detected a slot switch, OTA succeeded, device updated from "
951 << previous_version << " to " << current_version;
952 if (previous_version == current_version) {
953 LOG(INFO) << "Previous version is the same as current version, this is "
954 "possibly a self-OTA.";
955 }
956 return true;
957 } else {
958 LOG(INFO) << "Slot didn't switch, either the OTA is rolled back, or slot "
959 "switch never happened, or system not rebooted at all.";
960 if (previous_version != current_version) {
961 LOG(INFO) << "Slot didn't change, but version changed from "
962 << previous_version << " to " << current_version
963 << " device could be flashed.";
964 }
965 return false;
966 }
967}
968
969OTAResult UpdateAttempterAndroid::GetOTAUpdateResult() const {
970 // We only set |kPrefsSystemUpdatedMarker| if slot is actually switched, so
971 // existence of this pref is sufficient indicator. Given that we have to
972 // delete this pref after checking it. This is done in
973 // |DeltaPerformer::ResetUpdateProgress|
974 auto slot_switch_attempted = prefs_->Exists(kPrefsUpdateCompletedOnBootId);
975 auto system_rebooted = DidSystemReboot(prefs_);
976 auto ota_successful = OTARebootSucceeded();
977 if (ota_successful) {
978 return OTAResult::OTA_SUCCESSFUL;
979 }
980 if (slot_switch_attempted) {
981 if (system_rebooted) {
982 // If we attempted slot switch, but still end up on the same slot, we
983 // probably rolled back.
984 return OTAResult::ROLLED_BACK;
985 } else {
986 return OTAResult::UPDATED_NEED_REBOOT;
987 }
988 }
989 return OTAResult::NOT_ATTEMPTED;
990}
991
992void UpdateAttempterAndroid::UpdateStateAfterReboot(const OTAResult result) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700993 // Example: [ro.build.version.incremental]: [4292972]
994 string current_version =
995 android::base::GetProperty("ro.build.version.incremental", "");
996 TEST_AND_RETURN(!current_version.empty());
997
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400998 // |UpdateStateAfterReboot()| is only called after system reboot, so record
999 // boot id unconditionally
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001000 string current_boot_id;
1001 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
1002 prefs_->SetString(kPrefsBootId, current_boot_id);
1003
Tianjie Xu90aaa102017-10-10 17:39:03 -07001004 // If there's no record of previous version (e.g. due to a data wipe), we
1005 // save the info of current boot and skip the metrics report.
1006 if (!prefs_->Exists(kPrefsPreviousVersion)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001007 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001008 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001009 ClearMetricsPrefs();
1010 return;
1011 }
Kelvin Zhang86603472021-05-11 12:16:27 -04001012 // update_engine restarted under the same build and same slot.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001013 if (result != OTAResult::OTA_SUCCESSFUL) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001014 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
1015 // set when we start a new update.
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001016 if (prefs_->Exists(kPrefsNumReboots)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001017 int64_t reboot_count =
1018 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1019 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
1020 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001021
1022 if (result == OTAResult::ROLLED_BACK) {
1023 // This will release all space previously allocated for apex
1024 // decompression. If we detect a rollback, we should release space and
1025 // return the space to user. Any subsequent attempt to install OTA will
1026 // allocate space again anyway.
1027 LOG(INFO) << "Detected a rollback, releasing space allocated for apex "
1028 "deompression.";
1029 apex_handler_android_->AllocateSpace({});
1030 DeltaPerformer::ResetUpdateProgress(prefs_, false);
1031 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001032 return;
1033 }
1034
1035 // Now that the build version changes, report the update metrics.
1036 // TODO(xunchang) check the build version is larger than the previous one.
Tianjie Xu90aaa102017-10-10 17:39:03 -07001037 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001038 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001039
1040 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
1041 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
1042 if (previous_attempt_exists) {
1043 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
1044 }
1045
1046 metrics_utils::LoadAndReportTimeToReboot(
1047 metrics_reporter_.get(), prefs_, clock_.get());
1048 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -08001049
1050 // Also reset the update progress if the build version has changed.
1051 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1052 LOG(WARNING) << "Unable to reset the update progress.";
1053 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001054}
1055
1056// Save the update start time. Reset the reboot count and attempt number if the
1057// update isn't a resume; otherwise increment the attempt number.
1058void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
1059 if (!is_resume) {
1060 metrics_utils::SetNumReboots(0, prefs_);
1061 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
1062 } else {
1063 int64_t attempt_number =
1064 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1065 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
1066 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001067 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
1068 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001069 ClearUpdateCompletedMarker();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001070}
1071
1072void UpdateAttempterAndroid::ClearMetricsPrefs() {
1073 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -07001074 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001075 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001076 prefs_->Delete(kPrefsSystemUpdatedMarker);
1077 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001078 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001079}
1080
Yifan Hongbd47d622019-12-13 14:59:58 -08001081BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
1082 return boot_control_->GetCurrentSlot();
1083}
1084
1085BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
1086 return GetCurrentSlot() == 0 ? 1 : 0;
1087}
1088
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001089uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
1090 const std::string& metadata_filename,
1091 const vector<string>& key_value_pair_headers,
1092 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -08001093 DeltaArchiveManifest manifest;
1094 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
1095 return 0;
1096 }
1097 std::map<string, string> headers;
1098 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1099 return 0;
1100 }
1101
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001102 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1103 manifest.apex_info().end());
1104 uint64_t apex_size_required = 0;
1105 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001106 auto result = apex_handler_android_->CalculateSize(apex_infos);
1107 if (!result.ok()) {
1108 LogAndSetError(error,
1109 FROM_HERE,
1110 "Failed to calculate size required for compressed APEX");
1111 return 0;
1112 }
1113 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001114 }
1115
Yifan Hong65613032020-01-09 17:52:13 -08001116 string payload_id = GetPayloadId(headers);
1117 uint64_t required_size = 0;
1118 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1119 boot_control_,
1120 GetTargetSlot(),
1121 manifest,
1122 payload_id,
1123 &required_size)) {
1124 if (required_size == 0) {
1125 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
1126 return 0;
1127 } else {
1128 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001129 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001130 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001131 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001132 }
1133 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001134
1135 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001136 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001137 LOG(ERROR) << "Insufficient space for apex decompression: "
1138 << apex_size_required << " bytes";
1139 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001140 }
Yifan Hong65613032020-01-09 17:52:13 -08001141
1142 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001143 return 0;
1144}
1145
Yifan Hong40bb0d02020-02-24 17:33:14 -08001146void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1147 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Yifan Hong2236ea02019-12-13 16:11:22 -08001148 brillo::ErrorPtr* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001149 if (cleanup_previous_update_code_.has_value()) {
1150 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1151 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1152 if (callback) {
1153 callback->OnCleanupComplete(
1154 static_cast<int32_t>(*cleanup_previous_update_code_));
1155 }
1156 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001157 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001158 if (callback) {
1159 auto callback_ptr = callback.get();
1160 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1161 callback_ptr->RegisterForDeathNotifications(
1162 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1163 base::Unretained(this),
1164 base::Unretained(callback_ptr)));
1165 }
1166 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001167}
1168
Tianjie7f8f2ab2021-07-23 17:08:50 -07001169bool UpdateAttempterAndroid::setShouldSwitchSlotOnReboot(
1170 const std::string& metadata_filename, brillo::ErrorPtr* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -07001171 LOG(INFO) << "setShouldSwitchSlotOnReboot(" << metadata_filename << ")";
Tianjie7f8f2ab2021-07-23 17:08:50 -07001172 if (processor_->IsRunning()) {
1173 return LogAndSetError(
1174 error, FROM_HERE, "Already processing an update, cancel it first.");
1175 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001176 DeltaArchiveManifest manifest;
1177 TEST_AND_RETURN_FALSE(
1178 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
1179
1180 if (!boot_control_->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
1181 GetCurrentSlot(),
1182 GetTargetSlot(),
1183 manifest,
1184 false /* should update */,
1185 nullptr)) {
1186 return LogAndSetError(
1187 error, FROM_HERE, "Failed to PreparePartitionsForUpdate");
1188 }
1189 InstallPlan install_plan_;
1190 install_plan_.source_slot = GetCurrentSlot();
1191 install_plan_.target_slot = GetTargetSlot();
1192 // Don't do verity computation, just hash the partitions
1193 install_plan_.write_verity = false;
1194 // Don't run postinstall, we just need PostinstallAction to switch the slots.
1195 install_plan_.run_post_install = false;
1196 install_plan_.is_resume = true;
1197
1198 CHECK_NE(install_plan_.source_slot, UINT32_MAX);
1199 CHECK_NE(install_plan_.target_slot, UINT32_MAX);
1200
Daniel Zhengda4f7292022-09-02 22:59:32 +00001201 ErrorCode error_code{};
Kelvin Zhang20982a52021-08-13 12:31:16 -07001202 if (!install_plan_.ParsePartitions(manifest.partitions(),
1203 boot_control_,
1204 manifest.block_size(),
1205 &error_code)) {
1206 return LogAndSetError(error,
1207 FROM_HERE,
1208 "Failed to LoadPartitionsFromSlots " +
1209 utils::ErrorCodeToString(error_code));
1210 }
1211
1212 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
1213 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
1214 boot_control_->GetDynamicPartitionControl());
1215 auto postinstall_runner_action =
1216 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
1217 SetStatusAndNotify(UpdateStatus::VERIFYING);
1218 filesystem_verifier_action->set_delegate(this);
1219 postinstall_runner_action->set_delegate(this);
1220
1221 // Bond them together. We have to use the leaf-types when calling
1222 // BondActions().
1223 BondActions(install_plan_action.get(), filesystem_verifier_action.get());
1224 BondActions(filesystem_verifier_action.get(),
1225 postinstall_runner_action.get());
1226
1227 processor_->EnqueueAction(std::move(install_plan_action));
1228 processor_->EnqueueAction(std::move(filesystem_verifier_action));
1229 processor_->EnqueueAction(std::move(postinstall_runner_action));
1230 ScheduleProcessingStart();
1231 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001232}
1233
1234bool UpdateAttempterAndroid::resetShouldSwitchSlotOnReboot(
1235 brillo::ErrorPtr* error) {
1236 if (processor_->IsRunning()) {
1237 return LogAndSetError(
1238 error, FROM_HERE, "Already processing an update, cancel it first.");
1239 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001240 // Update the boot flags so the current slot has higher priority.
1241 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot())) {
1242 return LogAndSetError(error, FROM_HERE, "Failed to SetActiveBootSlot");
1243 }
1244
1245 // Mark the current slot as successful again, since marking it as active
1246 // may reset the successful bit. We ignore the result of whether marking
1247 // the current slot as successful worked.
1248 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {}))) {
1249 return LogAndSetError(
1250 error, FROM_HERE, "Failed to MarkBootSuccessfulAsync");
1251 }
1252
1253 // Resets the warm reset property since we won't switch the slot.
1254 hardware_->SetWarmReset(false);
1255
1256 // Resets the vbmeta digest.
1257 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
1258 LOG(INFO) << "Slot switch cancelled.";
1259 SetStatusAndNotify(UpdateStatus::IDLE);
1260 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001261}
1262
Yifan Hong90965502020-02-19 15:22:47 -08001263void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1264 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1265 // is in progress, skip enqueueing the action.
1266 if (processor_->IsRunning()) {
1267 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1268 << "be done when the current update finishes.";
1269 return;
1270 }
1271 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1272 auto action =
1273 boot_control_->GetDynamicPartitionControl()
1274 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1275 processor_->EnqueueAction(std::move(action));
1276 processor_->set_delegate(this);
1277 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1278 processor_->StartProcessing();
1279}
1280
Yifan Hong40bb0d02020-02-24 17:33:14 -08001281void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1282 for (auto&& callback : cleanup_previous_update_callbacks_) {
1283 callback->OnCleanupProgressUpdate(progress);
1284 }
1285}
1286
1287void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1288 CHECK(cleanup_previous_update_code_.has_value());
1289 for (auto&& callback : cleanup_previous_update_callbacks_) {
1290 callback->OnCleanupComplete(
1291 static_cast<int32_t>(*cleanup_previous_update_code_));
1292 }
1293 cleanup_previous_update_callbacks_.clear();
1294}
1295
1296void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1297 CleanupSuccessfulUpdateCallbackInterface* callback) {
1298 auto end_it =
1299 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1300 cleanup_previous_update_callbacks_.end(),
1301 [&](const auto& e) { return e.get() == callback; });
1302 cleanup_previous_update_callbacks_.erase(
1303 end_it, cleanup_previous_update_callbacks_.end());
1304}
Yifan Hong90965502020-02-19 15:22:47 -08001305
Alex Deymo5e3ea272016-01-28 13:42:23 -08001306} // namespace chromeos_update_engine