blob: eda82e2847e0fe22d568664db7d4fa4577b79658 [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"
Kelvin Zhangf8441982022-12-07 18:18:47 -080041#include "update_engine/common/error_code.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080042#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070043#include "update_engine/common/file_fetcher.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070044#include "update_engine/common/metrics_reporter_interface.h"
45#include "update_engine/common/network_selector.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080046#include "update_engine/common/utils.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070047#include "update_engine/metrics_utils.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080048#include "update_engine/payload_consumer/delta_performer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080049#include "update_engine/payload_consumer/file_descriptor.h"
50#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080051#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Kelvin Zhangcfc531f2022-08-24 17:58:53 +000052#include "update_engine/payload_consumer/partition_writer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080053#include "update_engine/payload_consumer/payload_constants.h"
54#include "update_engine/payload_consumer/payload_metadata.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070055#include "update_engine/payload_consumer/payload_verifier.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080056#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070057#include "update_engine/update_boot_flags_action.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080058#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080059
Alex Deymo14c0da82016-07-20 16:45:45 -070060#ifndef _UE_SIDELOAD
61// Do not include support for external HTTP(s) urls when building
62// update_engine_sideload.
63#include "update_engine/libcurl_http_fetcher.h"
64#endif
65
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090066using android::base::unique_fd;
Alex Deymo5e3ea272016-01-28 13:42:23 -080067using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070068using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080069using base::TimeDelta;
70using base::TimeTicks;
Alex Deymo5e3ea272016-01-28 13:42:23 -080071using std::string;
72using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070073using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080074
75namespace chromeos_update_engine {
76
77namespace {
78
Alex Deymo0d298542016-03-30 18:31:49 -070079// Minimum threshold to broadcast an status update in progress and time.
80const double kBroadcastThresholdProgress = 0.01; // 1%
81const int kBroadcastThresholdSeconds = 10;
82
Alex Deymo5e3ea272016-01-28 13:42:23 -080083const char* const kErrorDomain = "update_engine";
84// TODO(deymo): Convert the different errors to a numeric value to report them
85// back on the service error.
86const char* const kGenericError = "generic_error";
87
88// Log and set the error on the passed ErrorPtr.
89bool LogAndSetError(brillo::ErrorPtr* error,
Jakub Pawlowski7e1dcf72018-07-26 00:29:42 -070090 const base::Location& location,
Alex Deymo5e3ea272016-01-28 13:42:23 -080091 const string& reason) {
92 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
93 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
94 << reason;
95 return false;
96}
97
Sen Jiangfe522822017-10-31 15:14:11 -070098bool GetHeaderAsBool(const string& header, bool default_value) {
99 int value = 0;
100 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
101 return value == 1;
102 return default_value;
103}
104
Yifan Hongbd47d622019-12-13 14:59:58 -0800105bool ParseKeyValuePairHeaders(const vector<string>& key_value_pair_headers,
106 std::map<string, string>* headers,
107 brillo::ErrorPtr* error) {
108 for (const string& key_value_pair : key_value_pair_headers) {
109 string key;
110 string value;
111 if (!brillo::string_utils::SplitAtFirst(
112 key_value_pair, "=", &key, &value, false)) {
113 return LogAndSetError(
114 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
115 }
116 if (!headers->emplace(key, value).second)
117 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
118 }
119 return true;
120}
121
122// Unique identifier for the payload. An empty string means that the payload
123// can't be resumed.
124string GetPayloadId(const std::map<string, string>& headers) {
125 return (headers.count(kPayloadPropertyFileHash)
126 ? headers.at(kPayloadPropertyFileHash)
127 : "") +
128 (headers.count(kPayloadPropertyMetadataHash)
129 ? headers.at(kPayloadPropertyMetadataHash)
130 : "");
131}
132
Alex Deymo5e3ea272016-01-28 13:42:23 -0800133} // namespace
134
135UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700136 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800137 PrefsInterface* prefs,
138 BootControlInterface* boot_control,
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000139 HardwareInterface* hardware,
140 std::unique_ptr<ApexHandlerInterface> apex_handler)
Alex Deymo5e3ea272016-01-28 13:42:23 -0800141 : daemon_state_(daemon_state),
142 prefs_(prefs),
143 boot_control_(boot_control),
144 hardware_(hardware),
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000145 apex_handler_android_(std::move(apex_handler)),
Tianjie Xu1b661142017-09-28 14:03:42 -0700146 processor_(new ActionProcessor()),
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800147 clock_(new Clock()),
148 metric_bytes_downloaded_(kPrefsCurrentBytesDownloaded, prefs_),
149 metric_total_bytes_downloaded_(kPrefsTotalBytesDownloaded, prefs_) {
Yifan Hongc514f662021-02-04 11:18:43 -0800150 metrics_reporter_ = metrics::CreateMetricsReporter(
Kelvin Zhang9a5e3682021-03-29 12:58:48 -0400151 boot_control_->GetDynamicPartitionControl(), &install_plan_);
Alex Deymo87792ea2016-07-25 15:40:36 -0700152 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800153}
154
155UpdateAttempterAndroid::~UpdateAttempterAndroid() {
156 // Release ourselves as the ActionProcessor's delegate to prevent
157 // re-scheduling the updates due to the processing stopped.
158 processor_->set_delegate(nullptr);
159}
160
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400161[[nodiscard]] static bool DidSystemReboot(PrefsInterface* prefs) {
162 string boot_id;
163 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
164 string old_boot_id;
165 // If no previous boot id found, treat as a reboot and write boot ID.
166 if (!prefs->GetString(kPrefsBootId, &old_boot_id)) {
167 return true;
168 }
169 return old_boot_id != boot_id;
170}
171
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400172std::ostream& operator<<(std::ostream& out, OTAResult result) {
173 switch (result) {
174 case OTAResult::NOT_ATTEMPTED:
175 out << "OTAResult::NOT_ATTEMPTED";
176 break;
177 case OTAResult::ROLLED_BACK:
178 out << "OTAResult::ROLLED_BACK";
179 break;
180 case OTAResult::UPDATED_NEED_REBOOT:
181 out << "OTAResult::UPDATED_NEED_REBOOT";
182 break;
183 case OTAResult::OTA_SUCCESSFUL:
184 out << "OTAResult::OTA_SUCCESSFUL";
185 break;
186 }
187 return out;
188}
189
Alex Deymo5e3ea272016-01-28 13:42:23 -0800190void UpdateAttempterAndroid::Init() {
191 // In case of update_engine restart without a reboot we need to restore the
192 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700193 if (UpdateCompletedOnThisBoot()) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400194 LOG(INFO) << "Updated installed but update_engine is restarted without "
195 "device reboot. Resuming old state.";
Alex Deymo0e061ae2016-02-09 17:49:03 -0800196 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700197 } else {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400198 const auto result = GetOTAUpdateResult();
199 LOG(INFO) << result;
Alex Deymo0e061ae2016-02-09 17:49:03 -0800200 SetStatusAndNotify(UpdateStatus::IDLE);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400201 if (DidSystemReboot(prefs_)) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400202 UpdateStateAfterReboot(result);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400203 }
204
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700205#ifdef _UE_SIDELOAD
206 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
207 << "ApplyPayload will call it later.";
208#else
Yifan Hong90965502020-02-19 15:22:47 -0800209 ScheduleCleanupPreviousUpdate();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700210#endif
Tianjie Xu90aaa102017-10-10 17:39:03 -0700211 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800212}
213
214bool UpdateAttempterAndroid::ApplyPayload(
215 const string& payload_url,
216 int64_t payload_offset,
217 int64_t payload_size,
218 const vector<string>& key_value_pair_headers,
219 brillo::ErrorPtr* error) {
220 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
221 return LogAndSetError(
222 error, FROM_HERE, "An update already applied, waiting for reboot");
223 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700224 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800225 return LogAndSetError(
226 error, FROM_HERE, "Already processing an update, cancel it first.");
227 }
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100228 DCHECK_EQ(status_, UpdateStatus::IDLE);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800229
Alex Deymo218397f2016-02-04 23:55:10 -0800230 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800231 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
232 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800233 }
234
Yifan Hongbd47d622019-12-13 14:59:58 -0800235 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800236
237 // Setup the InstallPlan based on the request.
238 install_plan_ = InstallPlan();
239
240 install_plan_.download_url = payload_url;
241 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800242 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800243 InstallPlan::Payload payload;
244 payload.size = payload_size;
245 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800246 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800247 &payload.size)) {
248 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800249 }
250 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700251 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800252 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700253 LOG(WARNING) << "Unable to decode base64 file hash: "
254 << headers[kPayloadPropertyFileHash];
255 }
Alex Deymo218397f2016-02-04 23:55:10 -0800256 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800257 &payload.metadata_size)) {
258 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800259 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700260 // The |payload.type| is not used anymore since minor_version 3.
261 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800262 install_plan_.payloads.push_back(payload);
263
Alex Deymo5e3ea272016-01-28 13:42:23 -0800264 // The |public_key_rsa| key would override the public key stored on disk.
265 install_plan_.public_key_rsa = "";
266
267 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
268 install_plan_.is_resume = !payload_id.empty() &&
269 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
270 if (!install_plan_.is_resume) {
Kelvin Zhang42c2d552022-07-25 11:04:00 -0700271 boot_control_->GetDynamicPartitionControl()->Cleanup();
Kelvin Zhangc54c9962022-10-20 13:44:59 -0700272 boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_);
273
Alex Deymo5e3ea272016-01-28 13:42:23 -0800274 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
275 LOG(WARNING) << "Unable to save the update check response hash.";
276 }
277 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800278 install_plan_.source_slot = GetCurrentSlot();
279 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700280
Alex Deymofb905d92016-06-03 19:26:58 -0700281 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700282 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
283
284 install_plan_.switch_slot_on_reboot =
285 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
286
Tianjie Xu087de9d2019-11-01 17:11:22 -0700287 install_plan_.run_post_install =
288 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800289
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700290 // Skip writing verity if we're resuming and verity has already been written.
291 install_plan_.write_verity = true;
292 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
293 bool verity_written = false;
294 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
295 verity_written) {
296 install_plan_.write_verity = false;
297 }
298 }
299
Alex Deymo87792ea2016-07-25 15:40:36 -0700300 NetworkId network_id = kDefaultNetworkId;
301 if (!headers[kPayloadPropertyNetworkId].empty()) {
302 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
303 &network_id)) {
304 return LogAndSetError(
305 error,
306 FROM_HERE,
307 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
308 }
309 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700310 return LogAndSetError(
311 error,
312 FROM_HERE,
313 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700314 }
315 }
316
Alex Deymo5e3ea272016-01-28 13:42:23 -0800317 LOG(INFO) << "Using this install plan:";
318 install_plan_.Dump();
319
Amin Hassani667cf7b2018-07-25 14:32:00 -0700320 HttpFetcher* fetcher = nullptr;
321 if (FileFetcher::SupportedUrl(payload_url)) {
322 DLOG(INFO) << "Using FileFetcher for file URL.";
323 fetcher = new FileFetcher();
324 } else {
325#ifdef _UE_SIDELOAD
326 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
327#else
Kelvin Zhangc7a1d1f2022-07-29 13:36:29 -0700328 LibcurlHttpFetcher* libcurl_fetcher = new LibcurlHttpFetcher(hardware_);
Kelvin Zhang3cc4fa32022-09-27 16:15:10 -0700329 if (!headers[kPayloadDownloadRetry].empty()) {
330 libcurl_fetcher->set_max_retry_count(
331 atoi(headers[kPayloadDownloadRetry].c_str()));
332 }
Amin Hassani667cf7b2018-07-25 14:32:00 -0700333 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
334 fetcher = libcurl_fetcher;
335#endif // _UE_SIDELOAD
336 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800337 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800338 if (!headers[kPayloadPropertyAuthorization].empty())
339 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
340 if (!headers[kPayloadPropertyUserAgent].empty())
341 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
342
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700343 if (!headers[kPayloadPropertyNetworkProxy].empty()) {
344 LOG(INFO) << "Using proxy url from payload headers: "
345 << headers[kPayloadPropertyNetworkProxy];
346 fetcher->SetProxies({headers[kPayloadPropertyNetworkProxy]});
347 }
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000348 if (!headers[kPayloadDisableVABC].empty()) {
349 install_plan_.disable_vabc = true;
350 }
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700351
Amin Hassani667cf7b2018-07-25 14:32:00 -0700352 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800353
Alex Deymo5e3ea272016-01-28 13:42:23 -0800354 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700355
356 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
357 // TODO(xunchang) report the metrics for unresumable updates
358
Amin Hassani667cf7b2018-07-25 14:32:00 -0700359 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800360 return true;
361}
362
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900363bool UpdateAttempterAndroid::ApplyPayload(
364 int fd,
365 int64_t payload_offset,
366 int64_t payload_size,
367 const vector<string>& key_value_pair_headers,
368 brillo::ErrorPtr* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100369 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000370 // already running update will be terminated (existing file descriptor will be
371 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100372 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
373 return LogAndSetError(
374 error, FROM_HERE, "An update already applied, waiting for reboot");
375 }
376 if (processor_->IsRunning()) {
377 return LogAndSetError(
378 error, FROM_HERE, "Already processing an update, cancel it first.");
379 }
380 DCHECK_EQ(status_, UpdateStatus::IDLE);
381
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900382 payload_fd_.reset(dup(fd));
383 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
384
385 return ApplyPayload(
386 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
387}
388
Alex Deymo5e3ea272016-01-28 13:42:23 -0800389bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700390 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800391 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
392 processor_->SuspendProcessing();
393 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800394}
395
396bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700397 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800398 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
399 processor_->ResumeProcessing();
400 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800401}
402
403bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700404 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800405 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800406 processor_->StopProcessing();
407 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800408}
409
Alex Deymo3b678db2016-02-09 11:50:06 -0800410bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
411 LOG(INFO) << "Attempting to reset state from "
412 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700413 if (processor_->IsRunning()) {
414 return LogAndSetError(
415 error, FROM_HERE, "Already processing an update, cancel it first.");
416 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800417
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000418 if (apex_handler_android_ != nullptr) {
419 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
420 std::vector<ApexInfo> apex_infos_blank;
421 apex_handler_android_->AllocateSpace(apex_infos_blank);
422 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400423 // Remove the reboot marker so that if the machine is rebooted
424 // after resetting to idle state, it doesn't go back to
425 // UpdateStatus::UPDATED_NEED_REBOOT state.
426 if (!ClearUpdateCompletedMarker()) {
427 return LogAndSetError(error,
428 FROM_HERE,
429 "Failed to reset the status because "
430 "ClearUpdateCompletedMarker() failed");
431 }
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000432
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700433 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
434 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000435 << "space might not be freed.";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700436 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800437 switch (status_) {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700438 case UpdateStatus::IDLE: {
Alex Deymo3b678db2016-02-09 11:50:06 -0800439 return true;
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700440 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800441
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800442 case UpdateStatus::UPDATED_NEED_REBOOT: {
Kelvin Zhang20982a52021-08-13 12:31:16 -0700443 const bool ret_value = resetShouldSwitchSlotOnReboot(error);
444 if (ret_value) {
445 LOG(INFO) << "Reset status successful";
Alex Deymo3b678db2016-02-09 11:50:06 -0800446 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700447 return ret_value;
Alex Deymo3b678db2016-02-09 11:50:06 -0800448 }
449
450 default:
451 return LogAndSetError(
452 error,
453 FROM_HERE,
454 "Reset not allowed in this state. Cancel the ongoing update first");
455 }
456}
457
Yifan Hongbd47d622019-12-13 14:59:58 -0800458bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
459 const std::string& metadata_filename,
460 DeltaArchiveManifest* manifest,
461 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800462 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
463 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
464 return LogAndSetError(
465 error, FROM_HERE, "Failed to open " + metadata_filename);
466 }
467 brillo::Blob metadata(kMaxPayloadHeaderSize);
468 if (!fd->Read(metadata.data(), metadata.size())) {
469 return LogAndSetError(
470 error,
471 FROM_HERE,
472 "Failed to read payload header from " + metadata_filename);
473 }
Daniel Zhengda4f7292022-09-02 22:59:32 +0000474 ErrorCode errorcode{};
Sen Jiang8371c1c2018-02-01 13:46:39 -0800475 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700476 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800477 MetadataParseResult::kSuccess) {
478 return LogAndSetError(error,
479 FROM_HERE,
480 "Failed to parse payload header: " +
481 utils::ErrorCodeToString(errorcode));
482 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700483 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
484 payload_metadata.GetMetadataSignatureSize();
485 if (metadata_size < kMaxPayloadHeaderSize ||
486 metadata_size >
487 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800488 return LogAndSetError(
489 error,
490 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700491 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800492 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700493 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800494 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
495 metadata.size() - kMaxPayloadHeaderSize)) {
496 return LogAndSetError(
497 error,
498 FROM_HERE,
499 "Failed to read metadata and signature from " + metadata_filename);
500 }
501 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800502
Tianjie Xu7a78d632019-10-08 16:32:39 -0700503 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
504 constants::kUpdateCertificatesPath);
505 if (!payload_verifier) {
506 return LogAndSetError(error,
507 FROM_HERE,
508 "Failed to create the payload verifier from " +
509 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800510 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700511 errorcode = payload_metadata.ValidateMetadataSignature(
512 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800513 if (errorcode != ErrorCode::kSuccess) {
514 return LogAndSetError(error,
515 FROM_HERE,
516 "Failed to validate metadata signature: " +
517 utils::ErrorCodeToString(errorcode));
518 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800519 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800520 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
521 }
522
Yifan Hongbd47d622019-12-13 14:59:58 -0800523 return true;
524}
525
526bool UpdateAttempterAndroid::VerifyPayloadApplicable(
527 const std::string& metadata_filename, brillo::ErrorPtr* error) {
528 DeltaArchiveManifest manifest;
529 TEST_AND_RETURN_FALSE(
530 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
531
532 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
Daniel Zhengda4f7292022-09-02 22:59:32 +0000533 ErrorCode errorcode{};
Yifan Hongbd47d622019-12-13 14:59:58 -0800534
535 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800536 for (const PartitionUpdate& partition : manifest.partitions()) {
537 if (!partition.has_old_partition_info())
538 continue;
539 string partition_path;
540 if (!boot_control_->GetPartitionDevice(
541 partition.partition_name(), current_slot, &partition_path)) {
542 return LogAndSetError(
543 error,
544 FROM_HERE,
545 "Failed to get partition device for " + partition.partition_name());
546 }
547 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
548 return LogAndSetError(
549 error, FROM_HERE, "Failed to open " + partition_path);
550 }
551 for (const InstallOperation& operation : partition.operations()) {
552 if (!operation.has_src_sha256_hash())
553 continue;
554 brillo::Blob source_hash;
555 if (!fd_utils::ReadAndHashExtents(fd,
556 operation.src_extents(),
557 manifest.block_size(),
558 &source_hash)) {
559 return LogAndSetError(
560 error, FROM_HERE, "Failed to hash " + partition_path);
561 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400562 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800563 source_hash, operation, fd, &errorcode)) {
564 return false;
565 }
566 }
567 fd->Close();
568 }
569 return true;
570}
571
Alex Deymo5e3ea272016-01-28 13:42:23 -0800572void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
573 ErrorCode code) {
574 LOG(INFO) << "Processing Done.";
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800575 metric_bytes_downloaded_.Flush(true);
576 metric_total_bytes_downloaded_.Flush(true);
Kelvin Zhangf8441982022-12-07 18:18:47 -0800577 last_error_ = code;
Yifan Hong90965502020-02-19 15:22:47 -0800578 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
579 TerminateUpdateAndNotify(code);
580 return;
581 }
582
Alex Deymo5990bf32016-07-19 17:01:41 -0700583 switch (code) {
584 case ErrorCode::kSuccess:
585 // Update succeeded.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400586 if (!WriteUpdateCompletedMarker()) {
587 LOG(ERROR) << "Failed to write update completion marker";
588 }
Alex Deymo5990bf32016-07-19 17:01:41 -0700589 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800590
Alex Deymo5990bf32016-07-19 17:01:41 -0700591 LOG(INFO) << "Update successfully applied, waiting to reboot.";
592 break;
593
594 case ErrorCode::kFilesystemCopierError:
595 case ErrorCode::kNewRootfsVerificationError:
596 case ErrorCode::kNewKernelVerificationError:
597 case ErrorCode::kFilesystemVerifierError:
598 case ErrorCode::kDownloadStateInitializationError:
599 // Reset the ongoing update for these errors so it starts from the
600 // beginning next time.
601 DeltaPerformer::ResetUpdateProgress(prefs_, false);
602 LOG(INFO) << "Resetting update progress.";
603 break;
604
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700605 case ErrorCode::kPayloadTimestampError:
606 // SafetyNet logging, b/36232423
607 android_errorWriteLog(0x534e4554, "36232423");
608 break;
609
Alex Deymo5990bf32016-07-19 17:01:41 -0700610 default:
611 // Ignore all other error codes.
612 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700613 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800614
615 TerminateUpdateAndNotify(code);
616}
617
618void UpdateAttempterAndroid::ProcessingStopped(
619 const ActionProcessor* processor) {
620 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
621}
622
623void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
624 AbstractAction* action,
625 ErrorCode code) {
626 // Reset download progress regardless of whether or not the download
627 // action succeeded.
628 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800629 if (type == CleanupPreviousUpdateAction::StaticType() ||
630 (type == NoOpAction::StaticType() &&
631 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
632 cleanup_previous_update_code_ = code;
633 NotifyCleanupPreviousUpdateCallbacksAndClear();
634 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000635 // download_progress_ is actually used by other actions, such as
636 // filesystem_verify_action. Therefore we always clear it.
637 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700638 if (type == PostinstallRunnerAction::StaticType()) {
639 bool succeeded =
640 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
641 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
642 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800643 if (code != ErrorCode::kSuccess) {
644 // If an action failed, the ActionProcessor will cancel the whole thing.
645 return;
646 }
Yifan Hong83517502020-02-19 15:34:13 -0800647 if (type == UpdateBootFlagsAction::StaticType()) {
648 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
649 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800650 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400651 auto download_action = static_cast<DownloadAction*>(action);
652 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000653 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700654 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000655 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700656 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800657 }
658}
659
660void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
661 uint64_t bytes_received,
662 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700663 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800664 if (total)
665 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700666 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800667 download_progress_ = progress;
668 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700669 } else {
670 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800671 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700672
673 // Update the bytes downloaded in prefs.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800674 metric_bytes_downloaded_ += bytes_progressed;
675 metric_total_bytes_downloaded_ += bytes_progressed;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800676}
677
678bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
679 // TODO(deymo): Notify the DownloadAction that it should cancel the update
680 // download.
681 return false;
682}
683
684void UpdateAttempterAndroid::DownloadComplete() {
685 // Nothing needs to be done when the download completes.
686}
687
Alex Deymo0d298542016-03-30 18:31:49 -0700688void UpdateAttempterAndroid::ProgressUpdate(double progress) {
689 // Self throttle based on progress. Also send notifications if progress is
690 // too slow.
691 if (progress == 1.0 ||
692 progress - download_progress_ >= kBroadcastThresholdProgress ||
693 TimeTicks::Now() - last_notify_time_ >=
694 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
695 download_progress_ = progress;
696 SetStatusAndNotify(status_);
697 }
698}
699
Kelvin Zhang70eef232020-06-12 20:32:40 +0000700void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
701 assert(status_ == UpdateStatus::VERIFYING);
702 ProgressUpdate(progress);
703}
704
Alex Deymo5e3ea272016-01-28 13:42:23 -0800705void UpdateAttempterAndroid::ScheduleProcessingStart() {
706 LOG(INFO) << "Scheduling an action processor start.";
Kelvin Zhang20982a52021-08-13 12:31:16 -0700707 processor_->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800708 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700709 FROM_HERE,
710 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
711 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800712}
713
714void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
715 if (status_ == UpdateStatus::IDLE) {
716 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
717 return;
718 }
719
Yifan Hong90965502020-02-19 15:22:47 -0800720 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400721 ClearUpdateCompletedMarker();
Yifan Hong90965502020-02-19 15:22:47 -0800722 LOG(INFO) << "Terminating cleanup previous update.";
723 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700724 for (auto observer : daemon_state_->service_observers())
725 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800726 return;
727 }
728
Yifan Hong9194ce82019-11-07 11:03:42 -0800729 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700730
Alex Deymo0d298542016-03-30 18:31:49 -0700731 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800732 UpdateStatus new_status =
733 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
734 : UpdateStatus::IDLE);
735 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900736 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800737
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700738 // The network id is only applicable to one download attempt and once it's
739 // done the network id should not be re-used anymore.
740 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
741 LOG(WARNING) << "Unable to unbind network.";
742 }
743
Alex Deymo5e3ea272016-01-28 13:42:23 -0800744 for (auto observer : daemon_state_->service_observers())
745 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700746
Tianjie Xu90aaa102017-10-10 17:39:03 -0700747 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
748 ClearMetricsPrefs();
749 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800750 // We should only reset the PayloadAttemptNumber if the update succeeds, or
751 // we switch to a different payload.
752 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700753 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700754 // Clear the total bytes downloaded if and only if the update succeeds.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800755 metric_total_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -0700756 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800757}
758
759void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
760 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700761 size_t payload_size =
762 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700763 UpdateEngineStatus status_to_send = {.status = status_,
764 .progress = download_progress_,
765 .new_size_bytes = payload_size};
766
Alex Deymo5e3ea272016-01-28 13:42:23 -0800767 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700768 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800769 }
770 last_notify_time_ = TimeTicks::Now();
771}
772
Amin Hassani667cf7b2018-07-25 14:32:00 -0700773void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800774 CHECK(!processor_->IsRunning());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800775
776 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700777 auto update_boot_flags_action =
778 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800779 auto cleanup_previous_update_action =
780 boot_control_->GetDynamicPartitionControl()
781 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700782 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
783 auto download_action =
784 std::make_unique<DownloadAction>(prefs_,
785 boot_control_,
786 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700787 fetcher, // passes ownership
Kelvin Zhang1304fe72021-10-06 19:12:12 -0700788 true /* interactive */,
789 update_certificates_path_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800790 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700791 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700792 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
793 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700794 auto postinstall_runner_action =
795 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000796 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700797 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800798
Alex Deymo5e3ea272016-01-28 13:42:23 -0800799 // Bond them together. We have to use the leaf-types when calling
800 // BondActions().
801 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700802 BondActions(download_action.get(), filesystem_verifier_action.get());
803 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800804 postinstall_runner_action.get());
805
Amin Hassani667cf7b2018-07-25 14:32:00 -0700806 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800807 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700808 processor_->EnqueueAction(std::move(install_plan_action));
809 processor_->EnqueueAction(std::move(download_action));
810 processor_->EnqueueAction(std::move(filesystem_verifier_action));
811 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800812}
813
Alex Deymo5e3ea272016-01-28 13:42:23 -0800814bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400815 LOG(INFO) << "Writing update complete marker.";
Alex Deymo5e3ea272016-01-28 13:42:23 -0800816 string boot_id;
817 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400818 TEST_AND_RETURN_FALSE(
819 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id));
820 TEST_AND_RETURN_FALSE(
821 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot()));
822 return true;
823}
824
825bool UpdateAttempterAndroid::ClearUpdateCompletedMarker() {
826 LOG(INFO) << "Clearing update complete marker.";
827 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsUpdateCompletedOnBootId));
828 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsPreviousSlot));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800829 return true;
830}
831
832bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
833 // In case of an update_engine restart without a reboot, we stored the boot_id
834 // when the update was completed by setting a pref, so we can check whether
835 // the last update was on this boot or a previous one.
836 string boot_id;
837 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
838
839 string update_completed_on_boot_id;
840 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
841 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
842 &update_completed_on_boot_id) &&
843 update_completed_on_boot_id == boot_id);
844}
845
Tianjie Xu90aaa102017-10-10 17:39:03 -0700846// Collect and report the android metrics when we terminate the update.
847void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
848 ErrorCode error_code) {
849 int64_t attempt_number =
850 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
851 PayloadType payload_type = kPayloadTypeFull;
852 int64_t payload_size = 0;
853 for (const auto& p : install_plan_.payloads) {
854 if (p.type == InstallPayloadType::kDelta)
855 payload_type = kPayloadTypeDelta;
856 payload_size += p.size;
857 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700858 // In some cases, e.g. after calling |setShouldSwitchSlotOnReboot()|, this
859 // function will be triggered, but payload_size in this case might be 0, if so
860 // skip reporting any metrics.
861 if (payload_size == 0) {
862 return;
863 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700864
865 metrics::AttemptResult attempt_result =
866 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700867 Time boot_time_start = Time::FromInternalValue(
868 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
869 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700870 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700871 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
872 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700873
874 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700875 static_cast<int>(attempt_number),
876 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700877 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700878 duration_uptime,
879 payload_size,
880 attempt_result,
881 error_code);
882
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800883 int64_t current_bytes_downloaded = metric_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -0700884 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
885 current_bytes_downloaded,
886 0,
887 DownloadSource::kNumDownloadSources,
888 metrics::DownloadErrorCode::kUnset,
889 metrics::ConnectionType::kUnset);
890
Tianjie Xu90aaa102017-10-10 17:39:03 -0700891 if (error_code == ErrorCode::kSuccess) {
892 int64_t reboot_count =
893 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
894 string build_version;
895 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700896
897 // For android metrics, we only care about the total bytes downloaded
898 // for all sources; for now we assume the only download source is
899 // HttpsServer.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800900 int64_t total_bytes_downloaded = metric_total_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -0700901 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
902 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
903 total_bytes_downloaded;
904
905 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700906 if (total_bytes_downloaded >= payload_size) {
907 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700908 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700909 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
910 } else {
911 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
912 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700913 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700914
Tianjie Xu90aaa102017-10-10 17:39:03 -0700915 metrics_reporter_->ReportSuccessfulUpdateMetrics(
916 static_cast<int>(attempt_number),
917 0, // update abandoned count
918 payload_type,
919 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700920 num_bytes_downloaded,
921 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700922 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700923 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700924 static_cast<int>(reboot_count),
925 0); // url_switch_count
926 }
927}
928
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400929bool UpdateAttempterAndroid::OTARebootSucceeded() const {
930 const auto current_slot = boot_control_->GetCurrentSlot();
931 const string current_version =
932 android::base::GetProperty("ro.build.version.incremental", "");
933 int64_t previous_slot = -1;
934 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot));
935 string previous_version;
936 TEST_AND_RETURN_FALSE(
937 prefs_->GetString(kPrefsPreviousVersion, &previous_version));
938 if (previous_slot != current_slot) {
939 LOG(INFO) << "Detected a slot switch, OTA succeeded, device updated from "
940 << previous_version << " to " << current_version;
941 if (previous_version == current_version) {
942 LOG(INFO) << "Previous version is the same as current version, this is "
943 "possibly a self-OTA.";
944 }
945 return true;
946 } else {
947 LOG(INFO) << "Slot didn't switch, either the OTA is rolled back, or slot "
948 "switch never happened, or system not rebooted at all.";
949 if (previous_version != current_version) {
950 LOG(INFO) << "Slot didn't change, but version changed from "
951 << previous_version << " to " << current_version
952 << " device could be flashed.";
953 }
954 return false;
955 }
956}
957
958OTAResult UpdateAttempterAndroid::GetOTAUpdateResult() const {
959 // We only set |kPrefsSystemUpdatedMarker| if slot is actually switched, so
960 // existence of this pref is sufficient indicator. Given that we have to
961 // delete this pref after checking it. This is done in
962 // |DeltaPerformer::ResetUpdateProgress|
963 auto slot_switch_attempted = prefs_->Exists(kPrefsUpdateCompletedOnBootId);
964 auto system_rebooted = DidSystemReboot(prefs_);
965 auto ota_successful = OTARebootSucceeded();
966 if (ota_successful) {
967 return OTAResult::OTA_SUCCESSFUL;
968 }
969 if (slot_switch_attempted) {
970 if (system_rebooted) {
971 // If we attempted slot switch, but still end up on the same slot, we
972 // probably rolled back.
973 return OTAResult::ROLLED_BACK;
974 } else {
975 return OTAResult::UPDATED_NEED_REBOOT;
976 }
977 }
978 return OTAResult::NOT_ATTEMPTED;
979}
980
981void UpdateAttempterAndroid::UpdateStateAfterReboot(const OTAResult result) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700982 // Example: [ro.build.version.incremental]: [4292972]
983 string current_version =
984 android::base::GetProperty("ro.build.version.incremental", "");
985 TEST_AND_RETURN(!current_version.empty());
986
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400987 // |UpdateStateAfterReboot()| is only called after system reboot, so record
988 // boot id unconditionally
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400989 string current_boot_id;
990 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
991 prefs_->SetString(kPrefsBootId, current_boot_id);
992
Tianjie Xu90aaa102017-10-10 17:39:03 -0700993 // If there's no record of previous version (e.g. due to a data wipe), we
994 // save the info of current boot and skip the metrics report.
995 if (!prefs_->Exists(kPrefsPreviousVersion)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700996 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400997 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -0700998 ClearMetricsPrefs();
999 return;
1000 }
Kelvin Zhang86603472021-05-11 12:16:27 -04001001 // update_engine restarted under the same build and same slot.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001002 if (result != OTAResult::OTA_SUCCESSFUL) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001003 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
1004 // set when we start a new update.
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001005 if (prefs_->Exists(kPrefsNumReboots)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001006 int64_t reboot_count =
1007 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1008 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
1009 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001010
1011 if (result == OTAResult::ROLLED_BACK) {
1012 // This will release all space previously allocated for apex
1013 // decompression. If we detect a rollback, we should release space and
1014 // return the space to user. Any subsequent attempt to install OTA will
1015 // allocate space again anyway.
1016 LOG(INFO) << "Detected a rollback, releasing space allocated for apex "
1017 "deompression.";
1018 apex_handler_android_->AllocateSpace({});
1019 DeltaPerformer::ResetUpdateProgress(prefs_, false);
1020 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001021 return;
1022 }
1023
1024 // Now that the build version changes, report the update metrics.
1025 // TODO(xunchang) check the build version is larger than the previous one.
Tianjie Xu90aaa102017-10-10 17:39:03 -07001026 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001027 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001028
1029 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
1030 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
1031 if (previous_attempt_exists) {
1032 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
1033 }
1034
1035 metrics_utils::LoadAndReportTimeToReboot(
1036 metrics_reporter_.get(), prefs_, clock_.get());
1037 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -08001038
1039 // Also reset the update progress if the build version has changed.
1040 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1041 LOG(WARNING) << "Unable to reset the update progress.";
1042 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001043}
1044
1045// Save the update start time. Reset the reboot count and attempt number if the
1046// update isn't a resume; otherwise increment the attempt number.
1047void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
1048 if (!is_resume) {
1049 metrics_utils::SetNumReboots(0, prefs_);
1050 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
1051 } else {
1052 int64_t attempt_number =
1053 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1054 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
1055 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001056 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
1057 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001058 ClearUpdateCompletedMarker();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001059}
1060
1061void UpdateAttempterAndroid::ClearMetricsPrefs() {
1062 CHECK(prefs_);
Kelvin Zhang32a73a92022-12-19 12:27:41 -08001063 metric_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001064 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001065 prefs_->Delete(kPrefsSystemUpdatedMarker);
1066 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001067 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001068}
1069
Yifan Hongbd47d622019-12-13 14:59:58 -08001070BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
1071 return boot_control_->GetCurrentSlot();
1072}
1073
1074BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
1075 return GetCurrentSlot() == 0 ? 1 : 0;
1076}
1077
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001078uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
1079 const std::string& metadata_filename,
1080 const vector<string>& key_value_pair_headers,
1081 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -08001082 DeltaArchiveManifest manifest;
1083 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
1084 return 0;
1085 }
1086 std::map<string, string> headers;
1087 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1088 return 0;
1089 }
1090
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001091 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1092 manifest.apex_info().end());
1093 uint64_t apex_size_required = 0;
1094 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001095 auto result = apex_handler_android_->CalculateSize(apex_infos);
1096 if (!result.ok()) {
1097 LogAndSetError(error,
1098 FROM_HERE,
1099 "Failed to calculate size required for compressed APEX");
1100 return 0;
1101 }
1102 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001103 }
1104
Yifan Hong65613032020-01-09 17:52:13 -08001105 string payload_id = GetPayloadId(headers);
1106 uint64_t required_size = 0;
1107 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1108 boot_control_,
1109 GetTargetSlot(),
1110 manifest,
1111 payload_id,
1112 &required_size)) {
1113 if (required_size == 0) {
1114 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
1115 return 0;
1116 } else {
1117 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001118 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001119 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001120 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001121 }
1122 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001123
1124 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001125 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001126 LOG(ERROR) << "Insufficient space for apex decompression: "
1127 << apex_size_required << " bytes";
1128 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001129 }
Yifan Hong65613032020-01-09 17:52:13 -08001130
1131 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001132 return 0;
1133}
1134
Yifan Hong40bb0d02020-02-24 17:33:14 -08001135void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1136 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Yifan Hong2236ea02019-12-13 16:11:22 -08001137 brillo::ErrorPtr* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001138 if (cleanup_previous_update_code_.has_value()) {
1139 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1140 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1141 if (callback) {
1142 callback->OnCleanupComplete(
1143 static_cast<int32_t>(*cleanup_previous_update_code_));
1144 }
1145 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001146 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001147 if (callback) {
1148 auto callback_ptr = callback.get();
1149 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1150 callback_ptr->RegisterForDeathNotifications(
1151 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1152 base::Unretained(this),
1153 base::Unretained(callback_ptr)));
1154 }
1155 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001156}
1157
Tianjie7f8f2ab2021-07-23 17:08:50 -07001158bool UpdateAttempterAndroid::setShouldSwitchSlotOnReboot(
1159 const std::string& metadata_filename, brillo::ErrorPtr* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -07001160 LOG(INFO) << "setShouldSwitchSlotOnReboot(" << metadata_filename << ")";
Tianjie7f8f2ab2021-07-23 17:08:50 -07001161 if (processor_->IsRunning()) {
1162 return LogAndSetError(
1163 error, FROM_HERE, "Already processing an update, cancel it first.");
1164 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001165 DeltaArchiveManifest manifest;
1166 TEST_AND_RETURN_FALSE(
1167 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
1168
Kelvin Zhang20982a52021-08-13 12:31:16 -07001169 InstallPlan install_plan_;
1170 install_plan_.source_slot = GetCurrentSlot();
1171 install_plan_.target_slot = GetTargetSlot();
1172 // Don't do verity computation, just hash the partitions
1173 install_plan_.write_verity = false;
1174 // Don't run postinstall, we just need PostinstallAction to switch the slots.
1175 install_plan_.run_post_install = false;
1176 install_plan_.is_resume = true;
1177
1178 CHECK_NE(install_plan_.source_slot, UINT32_MAX);
1179 CHECK_NE(install_plan_.target_slot, UINT32_MAX);
1180
Kelvin Zhang20982a52021-08-13 12:31:16 -07001181 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
Kelvin Zhang20982a52021-08-13 12:31:16 -07001182 auto postinstall_runner_action =
1183 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
1184 SetStatusAndNotify(UpdateStatus::VERIFYING);
Kelvin Zhang20982a52021-08-13 12:31:16 -07001185 postinstall_runner_action->set_delegate(this);
1186
Kelvin Zhangf8441982022-12-07 18:18:47 -08001187 // If last error code is kUpdatedButNotActive, we know that we reached this
1188 // state by calling applyPayload() with switch_slot=false. That applyPayload()
1189 // call would have already performed filesystem verification, therefore, we
1190 // can safely skip the verification to save time.
1191 if (last_error_ == ErrorCode::kUpdatedButNotActive) {
1192 BondActions(install_plan_action.get(), postinstall_runner_action.get());
1193 processor_->EnqueueAction(std::move(install_plan_action));
1194 } else {
Kelvin Zhang263a5402022-12-08 23:03:32 -08001195 if (!boot_control_->GetDynamicPartitionControl()
1196 ->PreparePartitionsForUpdate(GetCurrentSlot(),
1197 GetTargetSlot(),
1198 manifest,
1199 false /* should update */,
1200 nullptr)) {
1201 return LogAndSetError(
1202 error, FROM_HERE, "Failed to PreparePartitionsForUpdate");
1203 }
1204 ErrorCode error_code{};
1205 if (!install_plan_.ParsePartitions(manifest.partitions(),
1206 boot_control_,
1207 manifest.block_size(),
1208 &error_code)) {
1209 return LogAndSetError(error,
1210 FROM_HERE,
1211 "Failed to LoadPartitionsFromSlots " +
1212 utils::ErrorCodeToString(error_code));
1213 }
1214
Kelvin Zhangf8441982022-12-07 18:18:47 -08001215 auto filesystem_verifier_action =
1216 std::make_unique<FilesystemVerifierAction>(
1217 boot_control_->GetDynamicPartitionControl());
1218 filesystem_verifier_action->set_delegate(this);
1219 BondActions(install_plan_action.get(), filesystem_verifier_action.get());
1220 BondActions(filesystem_verifier_action.get(),
1221 postinstall_runner_action.get());
1222 processor_->EnqueueAction(std::move(install_plan_action));
1223 processor_->EnqueueAction(std::move(filesystem_verifier_action));
1224 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001225
Kelvin Zhang20982a52021-08-13 12:31:16 -07001226 processor_->EnqueueAction(std::move(postinstall_runner_action));
1227 ScheduleProcessingStart();
1228 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001229}
1230
1231bool UpdateAttempterAndroid::resetShouldSwitchSlotOnReboot(
1232 brillo::ErrorPtr* error) {
1233 if (processor_->IsRunning()) {
1234 return LogAndSetError(
1235 error, FROM_HERE, "Already processing an update, cancel it first.");
1236 }
Daniel Zhenge76cf562022-11-08 17:32:10 +00001237 TEST_AND_RETURN_FALSE(ClearUpdateCompletedMarker());
Kelvin Zhang20982a52021-08-13 12:31:16 -07001238 // Update the boot flags so the current slot has higher priority.
1239 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot())) {
1240 return LogAndSetError(error, FROM_HERE, "Failed to SetActiveBootSlot");
1241 }
1242
1243 // Mark the current slot as successful again, since marking it as active
1244 // may reset the successful bit. We ignore the result of whether marking
1245 // the current slot as successful worked.
1246 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {}))) {
1247 return LogAndSetError(
1248 error, FROM_HERE, "Failed to MarkBootSuccessfulAsync");
1249 }
1250
1251 // Resets the warm reset property since we won't switch the slot.
1252 hardware_->SetWarmReset(false);
1253
1254 // Resets the vbmeta digest.
1255 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
1256 LOG(INFO) << "Slot switch cancelled.";
1257 SetStatusAndNotify(UpdateStatus::IDLE);
1258 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001259}
1260
Yifan Hong90965502020-02-19 15:22:47 -08001261void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1262 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1263 // is in progress, skip enqueueing the action.
1264 if (processor_->IsRunning()) {
1265 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1266 << "be done when the current update finishes.";
1267 return;
1268 }
1269 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1270 auto action =
1271 boot_control_->GetDynamicPartitionControl()
1272 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1273 processor_->EnqueueAction(std::move(action));
1274 processor_->set_delegate(this);
1275 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1276 processor_->StartProcessing();
1277}
1278
Yifan Hong40bb0d02020-02-24 17:33:14 -08001279void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1280 for (auto&& callback : cleanup_previous_update_callbacks_) {
1281 callback->OnCleanupProgressUpdate(progress);
1282 }
1283}
1284
1285void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1286 CHECK(cleanup_previous_update_code_.has_value());
1287 for (auto&& callback : cleanup_previous_update_callbacks_) {
1288 callback->OnCleanupComplete(
1289 static_cast<int32_t>(*cleanup_previous_update_code_));
1290 }
1291 cleanup_previous_update_callbacks_.clear();
1292}
1293
1294void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1295 CleanupSuccessfulUpdateCallbackInterface* callback) {
1296 auto end_it =
1297 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1298 cleanup_previous_update_callbacks_.end(),
1299 [&](const auto& e) { return e.get() == callback; });
1300 cleanup_previous_update_callbacks_.erase(
1301 end_it, cleanup_previous_update_callbacks_.end());
1302}
Yifan Hong90965502020-02-19 15:22:47 -08001303
Alex Deymo5e3ea272016-01-28 13:42:23 -08001304} // namespace chromeos_update_engine