blob: 0dc7f839aae1885e38a1566bdf4d6e4d77d7846e [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();
Kelvin Zhangc54c9962022-10-20 13:44:59 -0700269 boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_);
270
Alex Deymo5e3ea272016-01-28 13:42:23 -0800271 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
272 LOG(WARNING) << "Unable to save the update check response hash.";
273 }
274 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800275 install_plan_.source_slot = GetCurrentSlot();
276 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700277
Alex Deymofb905d92016-06-03 19:26:58 -0700278 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700279 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
280
281 install_plan_.switch_slot_on_reboot =
282 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
283
Tianjie Xu087de9d2019-11-01 17:11:22 -0700284 install_plan_.run_post_install =
285 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800286
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700287 // Skip writing verity if we're resuming and verity has already been written.
288 install_plan_.write_verity = true;
289 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
290 bool verity_written = false;
291 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
292 verity_written) {
293 install_plan_.write_verity = false;
294 }
295 }
296
Alex Deymo87792ea2016-07-25 15:40:36 -0700297 NetworkId network_id = kDefaultNetworkId;
298 if (!headers[kPayloadPropertyNetworkId].empty()) {
299 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
300 &network_id)) {
301 return LogAndSetError(
302 error,
303 FROM_HERE,
304 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
305 }
306 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700307 return LogAndSetError(
308 error,
309 FROM_HERE,
310 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700311 }
312 }
313
Alex Deymo5e3ea272016-01-28 13:42:23 -0800314 LOG(INFO) << "Using this install plan:";
315 install_plan_.Dump();
316
Amin Hassani667cf7b2018-07-25 14:32:00 -0700317 HttpFetcher* fetcher = nullptr;
318 if (FileFetcher::SupportedUrl(payload_url)) {
319 DLOG(INFO) << "Using FileFetcher for file URL.";
320 fetcher = new FileFetcher();
321 } else {
322#ifdef _UE_SIDELOAD
323 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
324#else
Kelvin Zhangc7a1d1f2022-07-29 13:36:29 -0700325 LibcurlHttpFetcher* libcurl_fetcher = new LibcurlHttpFetcher(hardware_);
Kelvin Zhang3cc4fa32022-09-27 16:15:10 -0700326 if (!headers[kPayloadDownloadRetry].empty()) {
327 libcurl_fetcher->set_max_retry_count(
328 atoi(headers[kPayloadDownloadRetry].c_str()));
329 }
Amin Hassani667cf7b2018-07-25 14:32:00 -0700330 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
331 fetcher = libcurl_fetcher;
332#endif // _UE_SIDELOAD
333 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800334 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800335 if (!headers[kPayloadPropertyAuthorization].empty())
336 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
337 if (!headers[kPayloadPropertyUserAgent].empty())
338 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
339
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700340 if (!headers[kPayloadPropertyNetworkProxy].empty()) {
341 LOG(INFO) << "Using proxy url from payload headers: "
342 << headers[kPayloadPropertyNetworkProxy];
343 fetcher->SetProxies({headers[kPayloadPropertyNetworkProxy]});
344 }
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000345 if (!headers[kPayloadDisableVABC].empty()) {
346 install_plan_.disable_vabc = true;
347 }
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700348
Amin Hassani667cf7b2018-07-25 14:32:00 -0700349 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800350
Alex Deymo5e3ea272016-01-28 13:42:23 -0800351 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700352
353 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
354 // TODO(xunchang) report the metrics for unresumable updates
355
Amin Hassani667cf7b2018-07-25 14:32:00 -0700356 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800357 return true;
358}
359
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900360bool UpdateAttempterAndroid::ApplyPayload(
361 int fd,
362 int64_t payload_offset,
363 int64_t payload_size,
364 const vector<string>& key_value_pair_headers,
365 brillo::ErrorPtr* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100366 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000367 // already running update will be terminated (existing file descriptor will be
368 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100369 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
370 return LogAndSetError(
371 error, FROM_HERE, "An update already applied, waiting for reboot");
372 }
373 if (processor_->IsRunning()) {
374 return LogAndSetError(
375 error, FROM_HERE, "Already processing an update, cancel it first.");
376 }
377 DCHECK_EQ(status_, UpdateStatus::IDLE);
378
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900379 payload_fd_.reset(dup(fd));
380 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
381
382 return ApplyPayload(
383 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
384}
385
Alex Deymo5e3ea272016-01-28 13:42:23 -0800386bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700387 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800388 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
389 processor_->SuspendProcessing();
390 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800391}
392
393bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700394 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800395 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
396 processor_->ResumeProcessing();
397 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800398}
399
400bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700401 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800402 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800403 processor_->StopProcessing();
404 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800405}
406
Alex Deymo3b678db2016-02-09 11:50:06 -0800407bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
408 LOG(INFO) << "Attempting to reset state from "
409 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700410 if (processor_->IsRunning()) {
411 return LogAndSetError(
412 error, FROM_HERE, "Already processing an update, cancel it first.");
413 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800414
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000415 if (apex_handler_android_ != nullptr) {
416 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
417 std::vector<ApexInfo> apex_infos_blank;
418 apex_handler_android_->AllocateSpace(apex_infos_blank);
419 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400420 // Remove the reboot marker so that if the machine is rebooted
421 // after resetting to idle state, it doesn't go back to
422 // UpdateStatus::UPDATED_NEED_REBOOT state.
423 if (!ClearUpdateCompletedMarker()) {
424 return LogAndSetError(error,
425 FROM_HERE,
426 "Failed to reset the status because "
427 "ClearUpdateCompletedMarker() failed");
428 }
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000429
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700430 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
431 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000432 << "space might not be freed.";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700433 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800434 switch (status_) {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700435 case UpdateStatus::IDLE: {
Alex Deymo3b678db2016-02-09 11:50:06 -0800436 return true;
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700437 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800438
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800439 case UpdateStatus::UPDATED_NEED_REBOOT: {
Kelvin Zhang20982a52021-08-13 12:31:16 -0700440 const bool ret_value = resetShouldSwitchSlotOnReboot(error);
441 if (ret_value) {
442 LOG(INFO) << "Reset status successful";
Alex Deymo3b678db2016-02-09 11:50:06 -0800443 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700444 return ret_value;
Alex Deymo3b678db2016-02-09 11:50:06 -0800445 }
446
447 default:
448 return LogAndSetError(
449 error,
450 FROM_HERE,
451 "Reset not allowed in this state. Cancel the ongoing update first");
452 }
453}
454
Yifan Hongbd47d622019-12-13 14:59:58 -0800455bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
456 const std::string& metadata_filename,
457 DeltaArchiveManifest* manifest,
458 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800459 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
460 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
461 return LogAndSetError(
462 error, FROM_HERE, "Failed to open " + metadata_filename);
463 }
464 brillo::Blob metadata(kMaxPayloadHeaderSize);
465 if (!fd->Read(metadata.data(), metadata.size())) {
466 return LogAndSetError(
467 error,
468 FROM_HERE,
469 "Failed to read payload header from " + metadata_filename);
470 }
Daniel Zhengda4f7292022-09-02 22:59:32 +0000471 ErrorCode errorcode{};
Sen Jiang8371c1c2018-02-01 13:46:39 -0800472 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700473 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800474 MetadataParseResult::kSuccess) {
475 return LogAndSetError(error,
476 FROM_HERE,
477 "Failed to parse payload header: " +
478 utils::ErrorCodeToString(errorcode));
479 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700480 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
481 payload_metadata.GetMetadataSignatureSize();
482 if (metadata_size < kMaxPayloadHeaderSize ||
483 metadata_size >
484 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800485 return LogAndSetError(
486 error,
487 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700488 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800489 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700490 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800491 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
492 metadata.size() - kMaxPayloadHeaderSize)) {
493 return LogAndSetError(
494 error,
495 FROM_HERE,
496 "Failed to read metadata and signature from " + metadata_filename);
497 }
498 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800499
Tianjie Xu7a78d632019-10-08 16:32:39 -0700500 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
501 constants::kUpdateCertificatesPath);
502 if (!payload_verifier) {
503 return LogAndSetError(error,
504 FROM_HERE,
505 "Failed to create the payload verifier from " +
506 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800507 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700508 errorcode = payload_metadata.ValidateMetadataSignature(
509 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800510 if (errorcode != ErrorCode::kSuccess) {
511 return LogAndSetError(error,
512 FROM_HERE,
513 "Failed to validate metadata signature: " +
514 utils::ErrorCodeToString(errorcode));
515 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800516 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800517 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
518 }
519
Yifan Hongbd47d622019-12-13 14:59:58 -0800520 return true;
521}
522
523bool UpdateAttempterAndroid::VerifyPayloadApplicable(
524 const std::string& metadata_filename, brillo::ErrorPtr* error) {
525 DeltaArchiveManifest manifest;
526 TEST_AND_RETURN_FALSE(
527 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
528
529 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
Daniel Zhengda4f7292022-09-02 22:59:32 +0000530 ErrorCode errorcode{};
Yifan Hongbd47d622019-12-13 14:59:58 -0800531
532 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800533 for (const PartitionUpdate& partition : manifest.partitions()) {
534 if (!partition.has_old_partition_info())
535 continue;
536 string partition_path;
537 if (!boot_control_->GetPartitionDevice(
538 partition.partition_name(), current_slot, &partition_path)) {
539 return LogAndSetError(
540 error,
541 FROM_HERE,
542 "Failed to get partition device for " + partition.partition_name());
543 }
544 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
545 return LogAndSetError(
546 error, FROM_HERE, "Failed to open " + partition_path);
547 }
548 for (const InstallOperation& operation : partition.operations()) {
549 if (!operation.has_src_sha256_hash())
550 continue;
551 brillo::Blob source_hash;
552 if (!fd_utils::ReadAndHashExtents(fd,
553 operation.src_extents(),
554 manifest.block_size(),
555 &source_hash)) {
556 return LogAndSetError(
557 error, FROM_HERE, "Failed to hash " + partition_path);
558 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400559 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800560 source_hash, operation, fd, &errorcode)) {
561 return false;
562 }
563 }
564 fd->Close();
565 }
566 return true;
567}
568
Alex Deymo5e3ea272016-01-28 13:42:23 -0800569void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
570 ErrorCode code) {
571 LOG(INFO) << "Processing Done.";
572
Yifan Hong90965502020-02-19 15:22:47 -0800573 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
574 TerminateUpdateAndNotify(code);
575 return;
576 }
577
Alex Deymo5990bf32016-07-19 17:01:41 -0700578 switch (code) {
579 case ErrorCode::kSuccess:
580 // Update succeeded.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400581 if (!WriteUpdateCompletedMarker()) {
582 LOG(ERROR) << "Failed to write update completion marker";
583 }
Alex Deymo5990bf32016-07-19 17:01:41 -0700584 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800585
Alex Deymo5990bf32016-07-19 17:01:41 -0700586 LOG(INFO) << "Update successfully applied, waiting to reboot.";
587 break;
588
589 case ErrorCode::kFilesystemCopierError:
590 case ErrorCode::kNewRootfsVerificationError:
591 case ErrorCode::kNewKernelVerificationError:
592 case ErrorCode::kFilesystemVerifierError:
593 case ErrorCode::kDownloadStateInitializationError:
594 // Reset the ongoing update for these errors so it starts from the
595 // beginning next time.
596 DeltaPerformer::ResetUpdateProgress(prefs_, false);
597 LOG(INFO) << "Resetting update progress.";
598 break;
599
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700600 case ErrorCode::kPayloadTimestampError:
601 // SafetyNet logging, b/36232423
602 android_errorWriteLog(0x534e4554, "36232423");
603 break;
604
Alex Deymo5990bf32016-07-19 17:01:41 -0700605 default:
606 // Ignore all other error codes.
607 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700608 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800609
610 TerminateUpdateAndNotify(code);
611}
612
613void UpdateAttempterAndroid::ProcessingStopped(
614 const ActionProcessor* processor) {
615 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
616}
617
618void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
619 AbstractAction* action,
620 ErrorCode code) {
621 // Reset download progress regardless of whether or not the download
622 // action succeeded.
623 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800624 if (type == CleanupPreviousUpdateAction::StaticType() ||
625 (type == NoOpAction::StaticType() &&
626 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
627 cleanup_previous_update_code_ = code;
628 NotifyCleanupPreviousUpdateCallbacksAndClear();
629 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000630 // download_progress_ is actually used by other actions, such as
631 // filesystem_verify_action. Therefore we always clear it.
632 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700633 if (type == PostinstallRunnerAction::StaticType()) {
634 bool succeeded =
635 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
636 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
637 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800638 if (code != ErrorCode::kSuccess) {
639 // If an action failed, the ActionProcessor will cancel the whole thing.
640 return;
641 }
Yifan Hong83517502020-02-19 15:34:13 -0800642 if (type == UpdateBootFlagsAction::StaticType()) {
643 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
644 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800645 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400646 auto download_action = static_cast<DownloadAction*>(action);
647 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000648 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700649 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000650 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700651 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800652 }
653}
654
655void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
656 uint64_t bytes_received,
657 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700658 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800659 if (total)
660 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700661 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800662 download_progress_ = progress;
663 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700664 } else {
665 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800666 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700667
668 // Update the bytes downloaded in prefs.
669 int64_t current_bytes_downloaded =
670 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
671 int64_t total_bytes_downloaded =
672 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
673 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
674 current_bytes_downloaded + bytes_progressed);
675 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
676 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800677}
678
679bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
680 // TODO(deymo): Notify the DownloadAction that it should cancel the update
681 // download.
682 return false;
683}
684
685void UpdateAttempterAndroid::DownloadComplete() {
686 // Nothing needs to be done when the download completes.
687}
688
Alex Deymo0d298542016-03-30 18:31:49 -0700689void UpdateAttempterAndroid::ProgressUpdate(double progress) {
690 // Self throttle based on progress. Also send notifications if progress is
691 // too slow.
692 if (progress == 1.0 ||
693 progress - download_progress_ >= kBroadcastThresholdProgress ||
694 TimeTicks::Now() - last_notify_time_ >=
695 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
696 download_progress_ = progress;
697 SetStatusAndNotify(status_);
698 }
699}
700
Kelvin Zhang70eef232020-06-12 20:32:40 +0000701void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
702 assert(status_ == UpdateStatus::VERIFYING);
703 ProgressUpdate(progress);
704}
705
Alex Deymo5e3ea272016-01-28 13:42:23 -0800706void UpdateAttempterAndroid::ScheduleProcessingStart() {
707 LOG(INFO) << "Scheduling an action processor start.";
Kelvin Zhang20982a52021-08-13 12:31:16 -0700708 processor_->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800709 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700710 FROM_HERE,
711 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
712 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800713}
714
715void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
716 if (status_ == UpdateStatus::IDLE) {
717 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
718 return;
719 }
720
Yifan Hong90965502020-02-19 15:22:47 -0800721 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400722 ClearUpdateCompletedMarker();
Yifan Hong90965502020-02-19 15:22:47 -0800723 LOG(INFO) << "Terminating cleanup previous update.";
724 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700725 for (auto observer : daemon_state_->service_observers())
726 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800727 return;
728 }
729
Yifan Hong9194ce82019-11-07 11:03:42 -0800730 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700731
Alex Deymo0d298542016-03-30 18:31:49 -0700732 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800733 UpdateStatus new_status =
734 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
735 : UpdateStatus::IDLE);
736 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900737 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800738
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700739 // The network id is only applicable to one download attempt and once it's
740 // done the network id should not be re-used anymore.
741 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
742 LOG(WARNING) << "Unable to unbind network.";
743 }
744
Alex Deymo5e3ea272016-01-28 13:42:23 -0800745 for (auto observer : daemon_state_->service_observers())
746 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700747
Tianjie Xu90aaa102017-10-10 17:39:03 -0700748 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
749 ClearMetricsPrefs();
750 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800751 // We should only reset the PayloadAttemptNumber if the update succeeds, or
752 // we switch to a different payload.
753 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700754 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700755 // Clear the total bytes downloaded if and only if the update succeeds.
756 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700757 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800758}
759
760void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
761 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700762 size_t payload_size =
763 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700764 UpdateEngineStatus status_to_send = {.status = status_,
765 .progress = download_progress_,
766 .new_size_bytes = payload_size};
767
Alex Deymo5e3ea272016-01-28 13:42:23 -0800768 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700769 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800770 }
771 last_notify_time_ = TimeTicks::Now();
772}
773
Amin Hassani667cf7b2018-07-25 14:32:00 -0700774void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800775 CHECK(!processor_->IsRunning());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800776
777 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700778 auto update_boot_flags_action =
779 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800780 auto cleanup_previous_update_action =
781 boot_control_->GetDynamicPartitionControl()
782 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700783 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
784 auto download_action =
785 std::make_unique<DownloadAction>(prefs_,
786 boot_control_,
787 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700788 fetcher, // passes ownership
Kelvin Zhang1304fe72021-10-06 19:12:12 -0700789 true /* interactive */,
790 update_certificates_path_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800791 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700792 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700793 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
794 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700795 auto postinstall_runner_action =
796 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000797 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700798 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800799
Alex Deymo5e3ea272016-01-28 13:42:23 -0800800 // Bond them together. We have to use the leaf-types when calling
801 // BondActions().
802 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700803 BondActions(download_action.get(), filesystem_verifier_action.get());
804 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800805 postinstall_runner_action.get());
806
Amin Hassani667cf7b2018-07-25 14:32:00 -0700807 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800808 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700809 processor_->EnqueueAction(std::move(install_plan_action));
810 processor_->EnqueueAction(std::move(download_action));
811 processor_->EnqueueAction(std::move(filesystem_verifier_action));
812 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800813}
814
Alex Deymo5e3ea272016-01-28 13:42:23 -0800815bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400816 LOG(INFO) << "Writing update complete marker.";
Alex Deymo5e3ea272016-01-28 13:42:23 -0800817 string boot_id;
818 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400819 TEST_AND_RETURN_FALSE(
820 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id));
821 TEST_AND_RETURN_FALSE(
822 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot()));
823 return true;
824}
825
826bool UpdateAttempterAndroid::ClearUpdateCompletedMarker() {
827 LOG(INFO) << "Clearing update complete marker.";
828 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsUpdateCompletedOnBootId));
829 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsPreviousSlot));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800830 return true;
831}
832
833bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
834 // In case of an update_engine restart without a reboot, we stored the boot_id
835 // when the update was completed by setting a pref, so we can check whether
836 // the last update was on this boot or a previous one.
837 string boot_id;
838 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
839
840 string update_completed_on_boot_id;
841 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
842 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
843 &update_completed_on_boot_id) &&
844 update_completed_on_boot_id == boot_id);
845}
846
Tianjie Xu90aaa102017-10-10 17:39:03 -0700847// Collect and report the android metrics when we terminate the update.
848void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
849 ErrorCode error_code) {
850 int64_t attempt_number =
851 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
852 PayloadType payload_type = kPayloadTypeFull;
853 int64_t payload_size = 0;
854 for (const auto& p : install_plan_.payloads) {
855 if (p.type == InstallPayloadType::kDelta)
856 payload_type = kPayloadTypeDelta;
857 payload_size += p.size;
858 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700859 // In some cases, e.g. after calling |setShouldSwitchSlotOnReboot()|, this
860 // function will be triggered, but payload_size in this case might be 0, if so
861 // skip reporting any metrics.
862 if (payload_size == 0) {
863 return;
864 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700865
866 metrics::AttemptResult attempt_result =
867 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700868 Time boot_time_start = Time::FromInternalValue(
869 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
870 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700871 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700872 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
873 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700874
875 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700876 static_cast<int>(attempt_number),
877 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700878 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700879 duration_uptime,
880 payload_size,
881 attempt_result,
882 error_code);
883
Tianjie Xud4777a12017-10-24 14:54:18 -0700884 int64_t current_bytes_downloaded =
885 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
886 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
887 current_bytes_downloaded,
888 0,
889 DownloadSource::kNumDownloadSources,
890 metrics::DownloadErrorCode::kUnset,
891 metrics::ConnectionType::kUnset);
892
Tianjie Xu90aaa102017-10-10 17:39:03 -0700893 if (error_code == ErrorCode::kSuccess) {
894 int64_t reboot_count =
895 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
896 string build_version;
897 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700898
899 // For android metrics, we only care about the total bytes downloaded
900 // for all sources; for now we assume the only download source is
901 // HttpsServer.
902 int64_t total_bytes_downloaded =
903 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
904 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
905 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
906 total_bytes_downloaded;
907
908 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700909 if (total_bytes_downloaded >= payload_size) {
910 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700911 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700912 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
913 } else {
914 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
915 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700916 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700917
Tianjie Xu90aaa102017-10-10 17:39:03 -0700918 metrics_reporter_->ReportSuccessfulUpdateMetrics(
919 static_cast<int>(attempt_number),
920 0, // update abandoned count
921 payload_type,
922 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700923 num_bytes_downloaded,
924 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700925 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700926 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700927 static_cast<int>(reboot_count),
928 0); // url_switch_count
929 }
930}
931
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400932bool UpdateAttempterAndroid::OTARebootSucceeded() const {
933 const auto current_slot = boot_control_->GetCurrentSlot();
934 const string current_version =
935 android::base::GetProperty("ro.build.version.incremental", "");
936 int64_t previous_slot = -1;
937 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot));
938 string previous_version;
939 TEST_AND_RETURN_FALSE(
940 prefs_->GetString(kPrefsPreviousVersion, &previous_version));
941 if (previous_slot != current_slot) {
942 LOG(INFO) << "Detected a slot switch, OTA succeeded, device updated from "
943 << previous_version << " to " << current_version;
944 if (previous_version == current_version) {
945 LOG(INFO) << "Previous version is the same as current version, this is "
946 "possibly a self-OTA.";
947 }
948 return true;
949 } else {
950 LOG(INFO) << "Slot didn't switch, either the OTA is rolled back, or slot "
951 "switch never happened, or system not rebooted at all.";
952 if (previous_version != current_version) {
953 LOG(INFO) << "Slot didn't change, but version changed from "
954 << previous_version << " to " << current_version
955 << " device could be flashed.";
956 }
957 return false;
958 }
959}
960
961OTAResult UpdateAttempterAndroid::GetOTAUpdateResult() const {
962 // We only set |kPrefsSystemUpdatedMarker| if slot is actually switched, so
963 // existence of this pref is sufficient indicator. Given that we have to
964 // delete this pref after checking it. This is done in
965 // |DeltaPerformer::ResetUpdateProgress|
966 auto slot_switch_attempted = prefs_->Exists(kPrefsUpdateCompletedOnBootId);
967 auto system_rebooted = DidSystemReboot(prefs_);
968 auto ota_successful = OTARebootSucceeded();
969 if (ota_successful) {
970 return OTAResult::OTA_SUCCESSFUL;
971 }
972 if (slot_switch_attempted) {
973 if (system_rebooted) {
974 // If we attempted slot switch, but still end up on the same slot, we
975 // probably rolled back.
976 return OTAResult::ROLLED_BACK;
977 } else {
978 return OTAResult::UPDATED_NEED_REBOOT;
979 }
980 }
981 return OTAResult::NOT_ATTEMPTED;
982}
983
984void UpdateAttempterAndroid::UpdateStateAfterReboot(const OTAResult result) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700985 // Example: [ro.build.version.incremental]: [4292972]
986 string current_version =
987 android::base::GetProperty("ro.build.version.incremental", "");
988 TEST_AND_RETURN(!current_version.empty());
989
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400990 // |UpdateStateAfterReboot()| is only called after system reboot, so record
991 // boot id unconditionally
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400992 string current_boot_id;
993 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
994 prefs_->SetString(kPrefsBootId, current_boot_id);
995
Tianjie Xu90aaa102017-10-10 17:39:03 -0700996 // If there's no record of previous version (e.g. due to a data wipe), we
997 // save the info of current boot and skip the metrics report.
998 if (!prefs_->Exists(kPrefsPreviousVersion)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700999 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001000 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001001 ClearMetricsPrefs();
1002 return;
1003 }
Kelvin Zhang86603472021-05-11 12:16:27 -04001004 // update_engine restarted under the same build and same slot.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001005 if (result != OTAResult::OTA_SUCCESSFUL) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001006 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
1007 // set when we start a new update.
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001008 if (prefs_->Exists(kPrefsNumReboots)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001009 int64_t reboot_count =
1010 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1011 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
1012 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001013
1014 if (result == OTAResult::ROLLED_BACK) {
1015 // This will release all space previously allocated for apex
1016 // decompression. If we detect a rollback, we should release space and
1017 // return the space to user. Any subsequent attempt to install OTA will
1018 // allocate space again anyway.
1019 LOG(INFO) << "Detected a rollback, releasing space allocated for apex "
1020 "deompression.";
1021 apex_handler_android_->AllocateSpace({});
1022 DeltaPerformer::ResetUpdateProgress(prefs_, false);
1023 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001024 return;
1025 }
1026
1027 // Now that the build version changes, report the update metrics.
1028 // TODO(xunchang) check the build version is larger than the previous one.
Tianjie Xu90aaa102017-10-10 17:39:03 -07001029 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001030 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001031
1032 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
1033 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
1034 if (previous_attempt_exists) {
1035 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
1036 }
1037
1038 metrics_utils::LoadAndReportTimeToReboot(
1039 metrics_reporter_.get(), prefs_, clock_.get());
1040 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -08001041
1042 // Also reset the update progress if the build version has changed.
1043 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1044 LOG(WARNING) << "Unable to reset the update progress.";
1045 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001046}
1047
1048// Save the update start time. Reset the reboot count and attempt number if the
1049// update isn't a resume; otherwise increment the attempt number.
1050void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
1051 if (!is_resume) {
1052 metrics_utils::SetNumReboots(0, prefs_);
1053 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
1054 } else {
1055 int64_t attempt_number =
1056 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1057 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
1058 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001059 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
1060 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001061 ClearUpdateCompletedMarker();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001062}
1063
1064void UpdateAttempterAndroid::ClearMetricsPrefs() {
1065 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -07001066 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001067 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001068 prefs_->Delete(kPrefsSystemUpdatedMarker);
1069 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001070 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001071}
1072
Yifan Hongbd47d622019-12-13 14:59:58 -08001073BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
1074 return boot_control_->GetCurrentSlot();
1075}
1076
1077BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
1078 return GetCurrentSlot() == 0 ? 1 : 0;
1079}
1080
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001081uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
1082 const std::string& metadata_filename,
1083 const vector<string>& key_value_pair_headers,
1084 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -08001085 DeltaArchiveManifest manifest;
1086 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
1087 return 0;
1088 }
1089 std::map<string, string> headers;
1090 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1091 return 0;
1092 }
1093
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001094 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1095 manifest.apex_info().end());
1096 uint64_t apex_size_required = 0;
1097 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001098 auto result = apex_handler_android_->CalculateSize(apex_infos);
1099 if (!result.ok()) {
1100 LogAndSetError(error,
1101 FROM_HERE,
1102 "Failed to calculate size required for compressed APEX");
1103 return 0;
1104 }
1105 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001106 }
1107
Yifan Hong65613032020-01-09 17:52:13 -08001108 string payload_id = GetPayloadId(headers);
1109 uint64_t required_size = 0;
1110 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1111 boot_control_,
1112 GetTargetSlot(),
1113 manifest,
1114 payload_id,
1115 &required_size)) {
1116 if (required_size == 0) {
1117 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
1118 return 0;
1119 } else {
1120 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001121 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001122 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001123 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001124 }
1125 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001126
1127 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001128 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001129 LOG(ERROR) << "Insufficient space for apex decompression: "
1130 << apex_size_required << " bytes";
1131 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001132 }
Yifan Hong65613032020-01-09 17:52:13 -08001133
1134 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001135 return 0;
1136}
1137
Yifan Hong40bb0d02020-02-24 17:33:14 -08001138void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1139 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Yifan Hong2236ea02019-12-13 16:11:22 -08001140 brillo::ErrorPtr* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001141 if (cleanup_previous_update_code_.has_value()) {
1142 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1143 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1144 if (callback) {
1145 callback->OnCleanupComplete(
1146 static_cast<int32_t>(*cleanup_previous_update_code_));
1147 }
1148 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001149 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001150 if (callback) {
1151 auto callback_ptr = callback.get();
1152 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1153 callback_ptr->RegisterForDeathNotifications(
1154 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1155 base::Unretained(this),
1156 base::Unretained(callback_ptr)));
1157 }
1158 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001159}
1160
Tianjie7f8f2ab2021-07-23 17:08:50 -07001161bool UpdateAttempterAndroid::setShouldSwitchSlotOnReboot(
1162 const std::string& metadata_filename, brillo::ErrorPtr* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -07001163 LOG(INFO) << "setShouldSwitchSlotOnReboot(" << metadata_filename << ")";
Tianjie7f8f2ab2021-07-23 17:08:50 -07001164 if (processor_->IsRunning()) {
1165 return LogAndSetError(
1166 error, FROM_HERE, "Already processing an update, cancel it first.");
1167 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001168 DeltaArchiveManifest manifest;
1169 TEST_AND_RETURN_FALSE(
1170 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
1171
1172 if (!boot_control_->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
1173 GetCurrentSlot(),
1174 GetTargetSlot(),
1175 manifest,
1176 false /* should update */,
1177 nullptr)) {
1178 return LogAndSetError(
1179 error, FROM_HERE, "Failed to PreparePartitionsForUpdate");
1180 }
1181 InstallPlan install_plan_;
1182 install_plan_.source_slot = GetCurrentSlot();
1183 install_plan_.target_slot = GetTargetSlot();
1184 // Don't do verity computation, just hash the partitions
1185 install_plan_.write_verity = false;
1186 // Don't run postinstall, we just need PostinstallAction to switch the slots.
1187 install_plan_.run_post_install = false;
1188 install_plan_.is_resume = true;
1189
1190 CHECK_NE(install_plan_.source_slot, UINT32_MAX);
1191 CHECK_NE(install_plan_.target_slot, UINT32_MAX);
1192
Daniel Zhengda4f7292022-09-02 22:59:32 +00001193 ErrorCode error_code{};
Kelvin Zhang20982a52021-08-13 12:31:16 -07001194 if (!install_plan_.ParsePartitions(manifest.partitions(),
1195 boot_control_,
1196 manifest.block_size(),
1197 &error_code)) {
1198 return LogAndSetError(error,
1199 FROM_HERE,
1200 "Failed to LoadPartitionsFromSlots " +
1201 utils::ErrorCodeToString(error_code));
1202 }
1203
1204 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
1205 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
1206 boot_control_->GetDynamicPartitionControl());
1207 auto postinstall_runner_action =
1208 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
1209 SetStatusAndNotify(UpdateStatus::VERIFYING);
1210 filesystem_verifier_action->set_delegate(this);
1211 postinstall_runner_action->set_delegate(this);
1212
1213 // Bond them together. We have to use the leaf-types when calling
1214 // BondActions().
1215 BondActions(install_plan_action.get(), filesystem_verifier_action.get());
1216 BondActions(filesystem_verifier_action.get(),
1217 postinstall_runner_action.get());
1218
1219 processor_->EnqueueAction(std::move(install_plan_action));
1220 processor_->EnqueueAction(std::move(filesystem_verifier_action));
1221 processor_->EnqueueAction(std::move(postinstall_runner_action));
1222 ScheduleProcessingStart();
1223 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001224}
1225
1226bool UpdateAttempterAndroid::resetShouldSwitchSlotOnReboot(
1227 brillo::ErrorPtr* error) {
1228 if (processor_->IsRunning()) {
1229 return LogAndSetError(
1230 error, FROM_HERE, "Already processing an update, cancel it first.");
1231 }
Daniel Zhenge76cf562022-11-08 17:32:10 +00001232 TEST_AND_RETURN_FALSE(ClearUpdateCompletedMarker());
Kelvin Zhang20982a52021-08-13 12:31:16 -07001233 // Update the boot flags so the current slot has higher priority.
1234 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot())) {
1235 return LogAndSetError(error, FROM_HERE, "Failed to SetActiveBootSlot");
1236 }
1237
1238 // Mark the current slot as successful again, since marking it as active
1239 // may reset the successful bit. We ignore the result of whether marking
1240 // the current slot as successful worked.
1241 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {}))) {
1242 return LogAndSetError(
1243 error, FROM_HERE, "Failed to MarkBootSuccessfulAsync");
1244 }
1245
1246 // Resets the warm reset property since we won't switch the slot.
1247 hardware_->SetWarmReset(false);
1248
1249 // Resets the vbmeta digest.
1250 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
1251 LOG(INFO) << "Slot switch cancelled.";
1252 SetStatusAndNotify(UpdateStatus::IDLE);
1253 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001254}
1255
Yifan Hong90965502020-02-19 15:22:47 -08001256void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1257 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1258 // is in progress, skip enqueueing the action.
1259 if (processor_->IsRunning()) {
1260 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1261 << "be done when the current update finishes.";
1262 return;
1263 }
1264 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1265 auto action =
1266 boot_control_->GetDynamicPartitionControl()
1267 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1268 processor_->EnqueueAction(std::move(action));
1269 processor_->set_delegate(this);
1270 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1271 processor_->StartProcessing();
1272}
1273
Yifan Hong40bb0d02020-02-24 17:33:14 -08001274void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1275 for (auto&& callback : cleanup_previous_update_callbacks_) {
1276 callback->OnCleanupProgressUpdate(progress);
1277 }
1278}
1279
1280void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1281 CHECK(cleanup_previous_update_code_.has_value());
1282 for (auto&& callback : cleanup_previous_update_callbacks_) {
1283 callback->OnCleanupComplete(
1284 static_cast<int32_t>(*cleanup_previous_update_code_));
1285 }
1286 cleanup_previous_update_callbacks_.clear();
1287}
1288
1289void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1290 CleanupSuccessfulUpdateCallbackInterface* callback) {
1291 auto end_it =
1292 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1293 cleanup_previous_update_callbacks_.end(),
1294 [&](const auto& e) { return e.get() == callback; });
1295 cleanup_previous_update_callbacks_.erase(
1296 end_it, cleanup_previous_update_callbacks_.end());
1297}
Yifan Hong90965502020-02-19 15:22:47 -08001298
Alex Deymo5e3ea272016-01-28 13:42:23 -08001299} // namespace chromeos_update_engine