blob: aab6d2dd07a5dafe9e0437a9b0898686ec9ed622 [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_);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700334 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
335 fetcher = libcurl_fetcher;
336#endif // _UE_SIDELOAD
337 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800338 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800339 if (!headers[kPayloadPropertyAuthorization].empty())
340 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
341 if (!headers[kPayloadPropertyUserAgent].empty())
342 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
343
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700344 if (!headers[kPayloadPropertyNetworkProxy].empty()) {
345 LOG(INFO) << "Using proxy url from payload headers: "
346 << headers[kPayloadPropertyNetworkProxy];
347 fetcher->SetProxies({headers[kPayloadPropertyNetworkProxy]});
348 }
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000349 if (!headers[kPayloadDisableVABC].empty()) {
350 install_plan_.disable_vabc = true;
351 }
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700352
Amin Hassani667cf7b2018-07-25 14:32:00 -0700353 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800354
Alex Deymo5e3ea272016-01-28 13:42:23 -0800355 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700356
357 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
358 // TODO(xunchang) report the metrics for unresumable updates
359
Amin Hassani667cf7b2018-07-25 14:32:00 -0700360 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800361 return true;
362}
363
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900364bool UpdateAttempterAndroid::ApplyPayload(
365 int fd,
366 int64_t payload_offset,
367 int64_t payload_size,
368 const vector<string>& key_value_pair_headers,
369 brillo::ErrorPtr* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100370 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000371 // already running update will be terminated (existing file descriptor will be
372 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100373 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
374 return LogAndSetError(
375 error, FROM_HERE, "An update already applied, waiting for reboot");
376 }
377 if (processor_->IsRunning()) {
378 return LogAndSetError(
379 error, FROM_HERE, "Already processing an update, cancel it first.");
380 }
381 DCHECK_EQ(status_, UpdateStatus::IDLE);
382
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900383 payload_fd_.reset(dup(fd));
384 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
385
386 return ApplyPayload(
387 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
388}
389
Alex Deymo5e3ea272016-01-28 13:42:23 -0800390bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700391 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800392 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
393 processor_->SuspendProcessing();
394 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800395}
396
397bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700398 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800399 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
400 processor_->ResumeProcessing();
401 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800402}
403
404bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700405 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800406 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800407 processor_->StopProcessing();
408 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800409}
410
Alex Deymo3b678db2016-02-09 11:50:06 -0800411bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
412 LOG(INFO) << "Attempting to reset state from "
413 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700414 if (processor_->IsRunning()) {
415 return LogAndSetError(
416 error, FROM_HERE, "Already processing an update, cancel it first.");
417 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800418
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000419 if (apex_handler_android_ != nullptr) {
420 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
421 std::vector<ApexInfo> apex_infos_blank;
422 apex_handler_android_->AllocateSpace(apex_infos_blank);
423 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400424 // Remove the reboot marker so that if the machine is rebooted
425 // after resetting to idle state, it doesn't go back to
426 // UpdateStatus::UPDATED_NEED_REBOOT state.
427 if (!ClearUpdateCompletedMarker()) {
428 return LogAndSetError(error,
429 FROM_HERE,
430 "Failed to reset the status because "
431 "ClearUpdateCompletedMarker() failed");
432 }
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000433
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700434 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
435 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000436 << "space might not be freed.";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700437 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800438 switch (status_) {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700439 case UpdateStatus::IDLE: {
Alex Deymo3b678db2016-02-09 11:50:06 -0800440 return true;
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700441 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800442
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800443 case UpdateStatus::UPDATED_NEED_REBOOT: {
Kelvin Zhang20982a52021-08-13 12:31:16 -0700444 const bool ret_value = resetShouldSwitchSlotOnReboot(error);
445 if (ret_value) {
446 LOG(INFO) << "Reset status successful";
Alex Deymo3b678db2016-02-09 11:50:06 -0800447 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700448 return ret_value;
Alex Deymo3b678db2016-02-09 11:50:06 -0800449 }
450
451 default:
452 return LogAndSetError(
453 error,
454 FROM_HERE,
455 "Reset not allowed in this state. Cancel the ongoing update first");
456 }
457}
458
Yifan Hongbd47d622019-12-13 14:59:58 -0800459bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
460 const std::string& metadata_filename,
461 DeltaArchiveManifest* manifest,
462 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800463 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
464 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
465 return LogAndSetError(
466 error, FROM_HERE, "Failed to open " + metadata_filename);
467 }
468 brillo::Blob metadata(kMaxPayloadHeaderSize);
469 if (!fd->Read(metadata.data(), metadata.size())) {
470 return LogAndSetError(
471 error,
472 FROM_HERE,
473 "Failed to read payload header from " + metadata_filename);
474 }
Daniel Zhengda4f7292022-09-02 22:59:32 +0000475 ErrorCode errorcode{};
Sen Jiang8371c1c2018-02-01 13:46:39 -0800476 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700477 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800478 MetadataParseResult::kSuccess) {
479 return LogAndSetError(error,
480 FROM_HERE,
481 "Failed to parse payload header: " +
482 utils::ErrorCodeToString(errorcode));
483 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700484 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
485 payload_metadata.GetMetadataSignatureSize();
486 if (metadata_size < kMaxPayloadHeaderSize ||
487 metadata_size >
488 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800489 return LogAndSetError(
490 error,
491 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700492 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800493 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700494 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800495 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
496 metadata.size() - kMaxPayloadHeaderSize)) {
497 return LogAndSetError(
498 error,
499 FROM_HERE,
500 "Failed to read metadata and signature from " + metadata_filename);
501 }
502 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800503
Tianjie Xu7a78d632019-10-08 16:32:39 -0700504 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
505 constants::kUpdateCertificatesPath);
506 if (!payload_verifier) {
507 return LogAndSetError(error,
508 FROM_HERE,
509 "Failed to create the payload verifier from " +
510 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800511 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700512 errorcode = payload_metadata.ValidateMetadataSignature(
513 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800514 if (errorcode != ErrorCode::kSuccess) {
515 return LogAndSetError(error,
516 FROM_HERE,
517 "Failed to validate metadata signature: " +
518 utils::ErrorCodeToString(errorcode));
519 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800520 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800521 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
522 }
523
Yifan Hongbd47d622019-12-13 14:59:58 -0800524 return true;
525}
526
527bool UpdateAttempterAndroid::VerifyPayloadApplicable(
528 const std::string& metadata_filename, brillo::ErrorPtr* error) {
529 DeltaArchiveManifest manifest;
530 TEST_AND_RETURN_FALSE(
531 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
532
533 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
Daniel Zhengda4f7292022-09-02 22:59:32 +0000534 ErrorCode errorcode{};
Yifan Hongbd47d622019-12-13 14:59:58 -0800535
536 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800537 for (const PartitionUpdate& partition : manifest.partitions()) {
538 if (!partition.has_old_partition_info())
539 continue;
540 string partition_path;
541 if (!boot_control_->GetPartitionDevice(
542 partition.partition_name(), current_slot, &partition_path)) {
543 return LogAndSetError(
544 error,
545 FROM_HERE,
546 "Failed to get partition device for " + partition.partition_name());
547 }
548 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
549 return LogAndSetError(
550 error, FROM_HERE, "Failed to open " + partition_path);
551 }
552 for (const InstallOperation& operation : partition.operations()) {
553 if (!operation.has_src_sha256_hash())
554 continue;
555 brillo::Blob source_hash;
556 if (!fd_utils::ReadAndHashExtents(fd,
557 operation.src_extents(),
558 manifest.block_size(),
559 &source_hash)) {
560 return LogAndSetError(
561 error, FROM_HERE, "Failed to hash " + partition_path);
562 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400563 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800564 source_hash, operation, fd, &errorcode)) {
565 return false;
566 }
567 }
568 fd->Close();
569 }
570 return true;
571}
572
Alex Deymo5e3ea272016-01-28 13:42:23 -0800573void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
574 ErrorCode code) {
575 LOG(INFO) << "Processing Done.";
576
Yifan Hong90965502020-02-19 15:22:47 -0800577 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
578 TerminateUpdateAndNotify(code);
579 return;
580 }
581
Alex Deymo5990bf32016-07-19 17:01:41 -0700582 switch (code) {
583 case ErrorCode::kSuccess:
584 // Update succeeded.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400585 if (!WriteUpdateCompletedMarker()) {
586 LOG(ERROR) << "Failed to write update completion marker";
587 }
Alex Deymo5990bf32016-07-19 17:01:41 -0700588 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800589
Alex Deymo5990bf32016-07-19 17:01:41 -0700590 LOG(INFO) << "Update successfully applied, waiting to reboot.";
591 break;
592
593 case ErrorCode::kFilesystemCopierError:
594 case ErrorCode::kNewRootfsVerificationError:
595 case ErrorCode::kNewKernelVerificationError:
596 case ErrorCode::kFilesystemVerifierError:
597 case ErrorCode::kDownloadStateInitializationError:
598 // Reset the ongoing update for these errors so it starts from the
599 // beginning next time.
600 DeltaPerformer::ResetUpdateProgress(prefs_, false);
601 LOG(INFO) << "Resetting update progress.";
602 break;
603
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700604 case ErrorCode::kPayloadTimestampError:
605 // SafetyNet logging, b/36232423
606 android_errorWriteLog(0x534e4554, "36232423");
607 break;
608
Alex Deymo5990bf32016-07-19 17:01:41 -0700609 default:
610 // Ignore all other error codes.
611 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700612 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800613
614 TerminateUpdateAndNotify(code);
615}
616
617void UpdateAttempterAndroid::ProcessingStopped(
618 const ActionProcessor* processor) {
619 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
620}
621
622void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
623 AbstractAction* action,
624 ErrorCode code) {
625 // Reset download progress regardless of whether or not the download
626 // action succeeded.
627 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800628 if (type == CleanupPreviousUpdateAction::StaticType() ||
629 (type == NoOpAction::StaticType() &&
630 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
631 cleanup_previous_update_code_ = code;
632 NotifyCleanupPreviousUpdateCallbacksAndClear();
633 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000634 // download_progress_ is actually used by other actions, such as
635 // filesystem_verify_action. Therefore we always clear it.
636 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700637 if (type == PostinstallRunnerAction::StaticType()) {
638 bool succeeded =
639 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
640 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
641 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800642 if (code != ErrorCode::kSuccess) {
643 // If an action failed, the ActionProcessor will cancel the whole thing.
644 return;
645 }
Yifan Hong83517502020-02-19 15:34:13 -0800646 if (type == UpdateBootFlagsAction::StaticType()) {
647 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
648 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800649 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400650 auto download_action = static_cast<DownloadAction*>(action);
651 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000652 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700653 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000654 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700655 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800656 }
657}
658
659void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
660 uint64_t bytes_received,
661 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700662 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800663 if (total)
664 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700665 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800666 download_progress_ = progress;
667 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700668 } else {
669 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800670 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700671
672 // Update the bytes downloaded in prefs.
673 int64_t current_bytes_downloaded =
674 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
675 int64_t total_bytes_downloaded =
676 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
677 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
678 current_bytes_downloaded + bytes_progressed);
679 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
680 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800681}
682
683bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
684 // TODO(deymo): Notify the DownloadAction that it should cancel the update
685 // download.
686 return false;
687}
688
689void UpdateAttempterAndroid::DownloadComplete() {
690 // Nothing needs to be done when the download completes.
691}
692
Alex Deymo0d298542016-03-30 18:31:49 -0700693void UpdateAttempterAndroid::ProgressUpdate(double progress) {
694 // Self throttle based on progress. Also send notifications if progress is
695 // too slow.
696 if (progress == 1.0 ||
697 progress - download_progress_ >= kBroadcastThresholdProgress ||
698 TimeTicks::Now() - last_notify_time_ >=
699 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
700 download_progress_ = progress;
701 SetStatusAndNotify(status_);
702 }
703}
704
Kelvin Zhang70eef232020-06-12 20:32:40 +0000705void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
706 assert(status_ == UpdateStatus::VERIFYING);
707 ProgressUpdate(progress);
708}
709
Alex Deymo5e3ea272016-01-28 13:42:23 -0800710void UpdateAttempterAndroid::ScheduleProcessingStart() {
711 LOG(INFO) << "Scheduling an action processor start.";
Kelvin Zhang20982a52021-08-13 12:31:16 -0700712 processor_->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800713 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700714 FROM_HERE,
715 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
716 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800717}
718
719void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
720 if (status_ == UpdateStatus::IDLE) {
721 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
722 return;
723 }
724
Yifan Hong90965502020-02-19 15:22:47 -0800725 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400726 ClearUpdateCompletedMarker();
Yifan Hong90965502020-02-19 15:22:47 -0800727 LOG(INFO) << "Terminating cleanup previous update.";
728 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700729 for (auto observer : daemon_state_->service_observers())
730 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800731 return;
732 }
733
Yifan Hong9194ce82019-11-07 11:03:42 -0800734 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700735
Alex Deymo0d298542016-03-30 18:31:49 -0700736 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800737 UpdateStatus new_status =
738 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
739 : UpdateStatus::IDLE);
740 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900741 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800742
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700743 // The network id is only applicable to one download attempt and once it's
744 // done the network id should not be re-used anymore.
745 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
746 LOG(WARNING) << "Unable to unbind network.";
747 }
748
Alex Deymo5e3ea272016-01-28 13:42:23 -0800749 for (auto observer : daemon_state_->service_observers())
750 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700751
Tianjie Xu90aaa102017-10-10 17:39:03 -0700752 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
753 ClearMetricsPrefs();
754 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800755 // We should only reset the PayloadAttemptNumber if the update succeeds, or
756 // we switch to a different payload.
757 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700758 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700759 // Clear the total bytes downloaded if and only if the update succeeds.
760 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700761 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800762}
763
764void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
765 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700766 size_t payload_size =
767 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700768 UpdateEngineStatus status_to_send = {.status = status_,
769 .progress = download_progress_,
770 .new_size_bytes = payload_size};
771
Alex Deymo5e3ea272016-01-28 13:42:23 -0800772 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700773 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800774 }
775 last_notify_time_ = TimeTicks::Now();
776}
777
Amin Hassani667cf7b2018-07-25 14:32:00 -0700778void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800779 CHECK(!processor_->IsRunning());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800780
781 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700782 auto update_boot_flags_action =
783 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800784 auto cleanup_previous_update_action =
785 boot_control_->GetDynamicPartitionControl()
786 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700787 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
788 auto download_action =
789 std::make_unique<DownloadAction>(prefs_,
790 boot_control_,
791 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700792 fetcher, // passes ownership
Kelvin Zhang1304fe72021-10-06 19:12:12 -0700793 true /* interactive */,
794 update_certificates_path_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800795 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700796 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700797 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
798 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700799 auto postinstall_runner_action =
800 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000801 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700802 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800803
Alex Deymo5e3ea272016-01-28 13:42:23 -0800804 // Bond them together. We have to use the leaf-types when calling
805 // BondActions().
806 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700807 BondActions(download_action.get(), filesystem_verifier_action.get());
808 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800809 postinstall_runner_action.get());
810
Amin Hassani667cf7b2018-07-25 14:32:00 -0700811 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800812 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700813 processor_->EnqueueAction(std::move(install_plan_action));
814 processor_->EnqueueAction(std::move(download_action));
815 processor_->EnqueueAction(std::move(filesystem_verifier_action));
816 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800817}
818
Alex Deymo5e3ea272016-01-28 13:42:23 -0800819bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400820 LOG(INFO) << "Writing update complete marker.";
Alex Deymo5e3ea272016-01-28 13:42:23 -0800821 string boot_id;
822 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400823 TEST_AND_RETURN_FALSE(
824 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id));
825 TEST_AND_RETURN_FALSE(
826 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot()));
827 return true;
828}
829
830bool UpdateAttempterAndroid::ClearUpdateCompletedMarker() {
831 LOG(INFO) << "Clearing update complete marker.";
832 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsUpdateCompletedOnBootId));
833 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsPreviousSlot));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800834 return true;
835}
836
837bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
838 // In case of an update_engine restart without a reboot, we stored the boot_id
839 // when the update was completed by setting a pref, so we can check whether
840 // the last update was on this boot or a previous one.
841 string boot_id;
842 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
843
844 string update_completed_on_boot_id;
845 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
846 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
847 &update_completed_on_boot_id) &&
848 update_completed_on_boot_id == boot_id);
849}
850
Tianjie Xu90aaa102017-10-10 17:39:03 -0700851// Collect and report the android metrics when we terminate the update.
852void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
853 ErrorCode error_code) {
854 int64_t attempt_number =
855 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
856 PayloadType payload_type = kPayloadTypeFull;
857 int64_t payload_size = 0;
858 for (const auto& p : install_plan_.payloads) {
859 if (p.type == InstallPayloadType::kDelta)
860 payload_type = kPayloadTypeDelta;
861 payload_size += p.size;
862 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700863 // In some cases, e.g. after calling |setShouldSwitchSlotOnReboot()|, this
864 // function will be triggered, but payload_size in this case might be 0, if so
865 // skip reporting any metrics.
866 if (payload_size == 0) {
867 return;
868 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700869
870 metrics::AttemptResult attempt_result =
871 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700872 Time boot_time_start = Time::FromInternalValue(
873 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
874 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700875 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700876 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
877 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700878
879 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700880 static_cast<int>(attempt_number),
881 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700882 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700883 duration_uptime,
884 payload_size,
885 attempt_result,
886 error_code);
887
Tianjie Xud4777a12017-10-24 14:54:18 -0700888 int64_t current_bytes_downloaded =
889 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
890 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
891 current_bytes_downloaded,
892 0,
893 DownloadSource::kNumDownloadSources,
894 metrics::DownloadErrorCode::kUnset,
895 metrics::ConnectionType::kUnset);
896
Tianjie Xu90aaa102017-10-10 17:39:03 -0700897 if (error_code == ErrorCode::kSuccess) {
898 int64_t reboot_count =
899 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
900 string build_version;
901 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700902
903 // For android metrics, we only care about the total bytes downloaded
904 // for all sources; for now we assume the only download source is
905 // HttpsServer.
906 int64_t total_bytes_downloaded =
907 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
908 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
909 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
910 total_bytes_downloaded;
911
912 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700913 if (total_bytes_downloaded >= payload_size) {
914 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700915 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700916 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
917 } else {
918 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
919 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700920 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700921
Tianjie Xu90aaa102017-10-10 17:39:03 -0700922 metrics_reporter_->ReportSuccessfulUpdateMetrics(
923 static_cast<int>(attempt_number),
924 0, // update abandoned count
925 payload_type,
926 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700927 num_bytes_downloaded,
928 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700929 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700930 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700931 static_cast<int>(reboot_count),
932 0); // url_switch_count
933 }
934}
935
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400936bool UpdateAttempterAndroid::OTARebootSucceeded() const {
937 const auto current_slot = boot_control_->GetCurrentSlot();
938 const string current_version =
939 android::base::GetProperty("ro.build.version.incremental", "");
940 int64_t previous_slot = -1;
941 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot));
942 string previous_version;
943 TEST_AND_RETURN_FALSE(
944 prefs_->GetString(kPrefsPreviousVersion, &previous_version));
945 if (previous_slot != current_slot) {
946 LOG(INFO) << "Detected a slot switch, OTA succeeded, device updated from "
947 << previous_version << " to " << current_version;
948 if (previous_version == current_version) {
949 LOG(INFO) << "Previous version is the same as current version, this is "
950 "possibly a self-OTA.";
951 }
952 return true;
953 } else {
954 LOG(INFO) << "Slot didn't switch, either the OTA is rolled back, or slot "
955 "switch never happened, or system not rebooted at all.";
956 if (previous_version != current_version) {
957 LOG(INFO) << "Slot didn't change, but version changed from "
958 << previous_version << " to " << current_version
959 << " device could be flashed.";
960 }
961 return false;
962 }
963}
964
965OTAResult UpdateAttempterAndroid::GetOTAUpdateResult() const {
966 // We only set |kPrefsSystemUpdatedMarker| if slot is actually switched, so
967 // existence of this pref is sufficient indicator. Given that we have to
968 // delete this pref after checking it. This is done in
969 // |DeltaPerformer::ResetUpdateProgress|
970 auto slot_switch_attempted = prefs_->Exists(kPrefsUpdateCompletedOnBootId);
971 auto system_rebooted = DidSystemReboot(prefs_);
972 auto ota_successful = OTARebootSucceeded();
973 if (ota_successful) {
974 return OTAResult::OTA_SUCCESSFUL;
975 }
976 if (slot_switch_attempted) {
977 if (system_rebooted) {
978 // If we attempted slot switch, but still end up on the same slot, we
979 // probably rolled back.
980 return OTAResult::ROLLED_BACK;
981 } else {
982 return OTAResult::UPDATED_NEED_REBOOT;
983 }
984 }
985 return OTAResult::NOT_ATTEMPTED;
986}
987
988void UpdateAttempterAndroid::UpdateStateAfterReboot(const OTAResult result) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700989 // Example: [ro.build.version.incremental]: [4292972]
990 string current_version =
991 android::base::GetProperty("ro.build.version.incremental", "");
992 TEST_AND_RETURN(!current_version.empty());
993
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400994 // |UpdateStateAfterReboot()| is only called after system reboot, so record
995 // boot id unconditionally
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400996 string current_boot_id;
997 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
998 prefs_->SetString(kPrefsBootId, current_boot_id);
999
Tianjie Xu90aaa102017-10-10 17:39:03 -07001000 // If there's no record of previous version (e.g. due to a data wipe), we
1001 // save the info of current boot and skip the metrics report.
1002 if (!prefs_->Exists(kPrefsPreviousVersion)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001003 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001004 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001005 ClearMetricsPrefs();
1006 return;
1007 }
Kelvin Zhang86603472021-05-11 12:16:27 -04001008 // update_engine restarted under the same build and same slot.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001009 if (result != OTAResult::OTA_SUCCESSFUL) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001010 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
1011 // set when we start a new update.
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001012 if (prefs_->Exists(kPrefsNumReboots)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001013 int64_t reboot_count =
1014 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1015 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
1016 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001017
1018 if (result == OTAResult::ROLLED_BACK) {
1019 // This will release all space previously allocated for apex
1020 // decompression. If we detect a rollback, we should release space and
1021 // return the space to user. Any subsequent attempt to install OTA will
1022 // allocate space again anyway.
1023 LOG(INFO) << "Detected a rollback, releasing space allocated for apex "
1024 "deompression.";
1025 apex_handler_android_->AllocateSpace({});
1026 DeltaPerformer::ResetUpdateProgress(prefs_, false);
1027 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001028 return;
1029 }
1030
1031 // Now that the build version changes, report the update metrics.
1032 // TODO(xunchang) check the build version is larger than the previous one.
Tianjie Xu90aaa102017-10-10 17:39:03 -07001033 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001034 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001035
1036 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
1037 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
1038 if (previous_attempt_exists) {
1039 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
1040 }
1041
1042 metrics_utils::LoadAndReportTimeToReboot(
1043 metrics_reporter_.get(), prefs_, clock_.get());
1044 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -08001045
1046 // Also reset the update progress if the build version has changed.
1047 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1048 LOG(WARNING) << "Unable to reset the update progress.";
1049 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001050}
1051
1052// Save the update start time. Reset the reboot count and attempt number if the
1053// update isn't a resume; otherwise increment the attempt number.
1054void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
1055 if (!is_resume) {
1056 metrics_utils::SetNumReboots(0, prefs_);
1057 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
1058 } else {
1059 int64_t attempt_number =
1060 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1061 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
1062 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001063 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
1064 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001065 ClearUpdateCompletedMarker();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001066}
1067
1068void UpdateAttempterAndroid::ClearMetricsPrefs() {
1069 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -07001070 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001071 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001072 prefs_->Delete(kPrefsSystemUpdatedMarker);
1073 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001074 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001075}
1076
Yifan Hongbd47d622019-12-13 14:59:58 -08001077BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
1078 return boot_control_->GetCurrentSlot();
1079}
1080
1081BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
1082 return GetCurrentSlot() == 0 ? 1 : 0;
1083}
1084
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001085uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
1086 const std::string& metadata_filename,
1087 const vector<string>& key_value_pair_headers,
1088 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -08001089 DeltaArchiveManifest manifest;
1090 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
1091 return 0;
1092 }
1093 std::map<string, string> headers;
1094 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1095 return 0;
1096 }
1097
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001098 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1099 manifest.apex_info().end());
1100 uint64_t apex_size_required = 0;
1101 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001102 auto result = apex_handler_android_->CalculateSize(apex_infos);
1103 if (!result.ok()) {
1104 LogAndSetError(error,
1105 FROM_HERE,
1106 "Failed to calculate size required for compressed APEX");
1107 return 0;
1108 }
1109 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001110 }
1111
Yifan Hong65613032020-01-09 17:52:13 -08001112 string payload_id = GetPayloadId(headers);
1113 uint64_t required_size = 0;
1114 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1115 boot_control_,
1116 GetTargetSlot(),
1117 manifest,
1118 payload_id,
1119 &required_size)) {
1120 if (required_size == 0) {
1121 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
1122 return 0;
1123 } else {
1124 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001125 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001126 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001127 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001128 }
1129 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001130
1131 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001132 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001133 LOG(ERROR) << "Insufficient space for apex decompression: "
1134 << apex_size_required << " bytes";
1135 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001136 }
Yifan Hong65613032020-01-09 17:52:13 -08001137
1138 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001139 return 0;
1140}
1141
Yifan Hong40bb0d02020-02-24 17:33:14 -08001142void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1143 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Yifan Hong2236ea02019-12-13 16:11:22 -08001144 brillo::ErrorPtr* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001145 if (cleanup_previous_update_code_.has_value()) {
1146 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1147 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1148 if (callback) {
1149 callback->OnCleanupComplete(
1150 static_cast<int32_t>(*cleanup_previous_update_code_));
1151 }
1152 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001153 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001154 if (callback) {
1155 auto callback_ptr = callback.get();
1156 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1157 callback_ptr->RegisterForDeathNotifications(
1158 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1159 base::Unretained(this),
1160 base::Unretained(callback_ptr)));
1161 }
1162 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001163}
1164
Tianjie7f8f2ab2021-07-23 17:08:50 -07001165bool UpdateAttempterAndroid::setShouldSwitchSlotOnReboot(
1166 const std::string& metadata_filename, brillo::ErrorPtr* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -07001167 LOG(INFO) << "setShouldSwitchSlotOnReboot(" << metadata_filename << ")";
Tianjie7f8f2ab2021-07-23 17:08:50 -07001168 if (processor_->IsRunning()) {
1169 return LogAndSetError(
1170 error, FROM_HERE, "Already processing an update, cancel it first.");
1171 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001172 DeltaArchiveManifest manifest;
1173 TEST_AND_RETURN_FALSE(
1174 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
1175
1176 if (!boot_control_->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
1177 GetCurrentSlot(),
1178 GetTargetSlot(),
1179 manifest,
1180 false /* should update */,
1181 nullptr)) {
1182 return LogAndSetError(
1183 error, FROM_HERE, "Failed to PreparePartitionsForUpdate");
1184 }
1185 InstallPlan install_plan_;
1186 install_plan_.source_slot = GetCurrentSlot();
1187 install_plan_.target_slot = GetTargetSlot();
1188 // Don't do verity computation, just hash the partitions
1189 install_plan_.write_verity = false;
1190 // Don't run postinstall, we just need PostinstallAction to switch the slots.
1191 install_plan_.run_post_install = false;
1192 install_plan_.is_resume = true;
1193
1194 CHECK_NE(install_plan_.source_slot, UINT32_MAX);
1195 CHECK_NE(install_plan_.target_slot, UINT32_MAX);
1196
Daniel Zhengda4f7292022-09-02 22:59:32 +00001197 ErrorCode error_code{};
Kelvin Zhang20982a52021-08-13 12:31:16 -07001198 if (!install_plan_.ParsePartitions(manifest.partitions(),
1199 boot_control_,
1200 manifest.block_size(),
1201 &error_code)) {
1202 return LogAndSetError(error,
1203 FROM_HERE,
1204 "Failed to LoadPartitionsFromSlots " +
1205 utils::ErrorCodeToString(error_code));
1206 }
1207
1208 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
1209 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
1210 boot_control_->GetDynamicPartitionControl());
1211 auto postinstall_runner_action =
1212 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
1213 SetStatusAndNotify(UpdateStatus::VERIFYING);
1214 filesystem_verifier_action->set_delegate(this);
1215 postinstall_runner_action->set_delegate(this);
1216
1217 // Bond them together. We have to use the leaf-types when calling
1218 // BondActions().
1219 BondActions(install_plan_action.get(), filesystem_verifier_action.get());
1220 BondActions(filesystem_verifier_action.get(),
1221 postinstall_runner_action.get());
1222
1223 processor_->EnqueueAction(std::move(install_plan_action));
1224 processor_->EnqueueAction(std::move(filesystem_verifier_action));
1225 processor_->EnqueueAction(std::move(postinstall_runner_action));
1226 ScheduleProcessingStart();
1227 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001228}
1229
1230bool UpdateAttempterAndroid::resetShouldSwitchSlotOnReboot(
1231 brillo::ErrorPtr* error) {
1232 if (processor_->IsRunning()) {
1233 return LogAndSetError(
1234 error, FROM_HERE, "Already processing an update, cancel it first.");
1235 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001236 // Update the boot flags so the current slot has higher priority.
1237 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot())) {
1238 return LogAndSetError(error, FROM_HERE, "Failed to SetActiveBootSlot");
1239 }
1240
1241 // Mark the current slot as successful again, since marking it as active
1242 // may reset the successful bit. We ignore the result of whether marking
1243 // the current slot as successful worked.
1244 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {}))) {
1245 return LogAndSetError(
1246 error, FROM_HERE, "Failed to MarkBootSuccessfulAsync");
1247 }
1248
1249 // Resets the warm reset property since we won't switch the slot.
1250 hardware_->SetWarmReset(false);
1251
1252 // Resets the vbmeta digest.
1253 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
1254 LOG(INFO) << "Slot switch cancelled.";
1255 SetStatusAndNotify(UpdateStatus::IDLE);
1256 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001257}
1258
Yifan Hong90965502020-02-19 15:22:47 -08001259void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1260 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1261 // is in progress, skip enqueueing the action.
1262 if (processor_->IsRunning()) {
1263 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1264 << "be done when the current update finishes.";
1265 return;
1266 }
1267 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1268 auto action =
1269 boot_control_->GetDynamicPartitionControl()
1270 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1271 processor_->EnqueueAction(std::move(action));
1272 processor_->set_delegate(this);
1273 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1274 processor_->StartProcessing();
1275}
1276
Yifan Hong40bb0d02020-02-24 17:33:14 -08001277void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1278 for (auto&& callback : cleanup_previous_update_callbacks_) {
1279 callback->OnCleanupProgressUpdate(progress);
1280 }
1281}
1282
1283void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1284 CHECK(cleanup_previous_update_code_.has_value());
1285 for (auto&& callback : cleanup_previous_update_callbacks_) {
1286 callback->OnCleanupComplete(
1287 static_cast<int32_t>(*cleanup_previous_update_code_));
1288 }
1289 cleanup_previous_update_callbacks_.clear();
1290}
1291
1292void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1293 CleanupSuccessfulUpdateCallbackInterface* callback) {
1294 auto end_it =
1295 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1296 cleanup_previous_update_callbacks_.end(),
1297 [&](const auto& e) { return e.get() == callback; });
1298 cleanup_previous_update_callbacks_.erase(
1299 end_it, cleanup_previous_update_callbacks_.end());
1300}
Yifan Hong90965502020-02-19 15:22:47 -08001301
Alex Deymo5e3ea272016-01-28 13:42:23 -08001302} // namespace chromeos_update_engine