blob: e12678d8fb72669efc913f6032b23bd253817b67 [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
Daniel Zheng9fc62b82023-03-24 22:57:20 +0000284 if (!IsProductionBuild()) {
285 install_plan_.disable_vabc =
286 GetHeaderAsBool(headers[kPayloadDisableVABC], false);
287 }
288
Sen Jiangfe522822017-10-31 15:14:11 -0700289 install_plan_.switch_slot_on_reboot =
290 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
291
Tianjie Xu087de9d2019-11-01 17:11:22 -0700292 install_plan_.run_post_install =
293 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800294
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700295 // Skip writing verity if we're resuming and verity has already been written.
296 install_plan_.write_verity = true;
297 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
298 bool verity_written = false;
299 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
300 verity_written) {
301 install_plan_.write_verity = false;
302 }
303 }
304
Alex Deymo87792ea2016-07-25 15:40:36 -0700305 NetworkId network_id = kDefaultNetworkId;
306 if (!headers[kPayloadPropertyNetworkId].empty()) {
307 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
308 &network_id)) {
309 return LogAndSetError(
310 error,
311 FROM_HERE,
312 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
313 }
314 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700315 return LogAndSetError(
316 error,
317 FROM_HERE,
318 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700319 }
320 }
321
Alex Deymo5e3ea272016-01-28 13:42:23 -0800322 LOG(INFO) << "Using this install plan:";
323 install_plan_.Dump();
324
Amin Hassani667cf7b2018-07-25 14:32:00 -0700325 HttpFetcher* fetcher = nullptr;
326 if (FileFetcher::SupportedUrl(payload_url)) {
327 DLOG(INFO) << "Using FileFetcher for file URL.";
328 fetcher = new FileFetcher();
329 } else {
330#ifdef _UE_SIDELOAD
331 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
Chih-Hung Hsieh6e4f3452022-12-21 12:20:45 -0800332 return false; // NOLINT, unreached but analyzer might not know.
333 // Suppress warnings about null 'fetcher' after this.
Amin Hassani667cf7b2018-07-25 14:32:00 -0700334#else
Kelvin Zhangc7a1d1f2022-07-29 13:36:29 -0700335 LibcurlHttpFetcher* libcurl_fetcher = new LibcurlHttpFetcher(hardware_);
Kelvin Zhang3cc4fa32022-09-27 16:15:10 -0700336 if (!headers[kPayloadDownloadRetry].empty()) {
337 libcurl_fetcher->set_max_retry_count(
338 atoi(headers[kPayloadDownloadRetry].c_str()));
339 }
Amin Hassani667cf7b2018-07-25 14:32:00 -0700340 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
341 fetcher = libcurl_fetcher;
342#endif // _UE_SIDELOAD
343 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800344 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800345 if (!headers[kPayloadPropertyAuthorization].empty())
346 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
347 if (!headers[kPayloadPropertyUserAgent].empty())
348 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
349
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700350 if (!headers[kPayloadPropertyNetworkProxy].empty()) {
351 LOG(INFO) << "Using proxy url from payload headers: "
352 << headers[kPayloadPropertyNetworkProxy];
353 fetcher->SetProxies({headers[kPayloadPropertyNetworkProxy]});
354 }
Kelvin Zhanga7407b52023-03-13 15:05:14 -0700355 if (!headers[kPayloadVABCNone].empty()) {
356 install_plan_.vabc_none = true;
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000357 }
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800358 if (!headers[kPayloadEnableThreading].empty()) {
359 install_plan_.enable_threading = true;
360 }
361 if (!headers[kPayloadBatchedWrites].empty()) {
362 install_plan_.batched_writes = true;
363 }
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700364
Amin Hassani667cf7b2018-07-25 14:32:00 -0700365 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800366
Alex Deymo5e3ea272016-01-28 13:42:23 -0800367 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700368
369 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
370 // TODO(xunchang) report the metrics for unresumable updates
371
Amin Hassani667cf7b2018-07-25 14:32:00 -0700372 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800373 return true;
374}
375
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900376bool UpdateAttempterAndroid::ApplyPayload(
377 int fd,
378 int64_t payload_offset,
379 int64_t payload_size,
380 const vector<string>& key_value_pair_headers,
381 brillo::ErrorPtr* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100382 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000383 // already running update will be terminated (existing file descriptor will be
384 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100385 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
386 return LogAndSetError(
387 error, FROM_HERE, "An update already applied, waiting for reboot");
388 }
389 if (processor_->IsRunning()) {
390 return LogAndSetError(
391 error, FROM_HERE, "Already processing an update, cancel it first.");
392 }
393 DCHECK_EQ(status_, UpdateStatus::IDLE);
394
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900395 payload_fd_.reset(dup(fd));
396 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
397
398 return ApplyPayload(
399 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
400}
401
Alex Deymo5e3ea272016-01-28 13:42:23 -0800402bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700403 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800404 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
405 processor_->SuspendProcessing();
406 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800407}
408
409bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700410 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800411 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
412 processor_->ResumeProcessing();
413 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800414}
415
416bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700417 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800418 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800419 processor_->StopProcessing();
420 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800421}
422
Alex Deymo3b678db2016-02-09 11:50:06 -0800423bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
424 LOG(INFO) << "Attempting to reset state from "
425 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700426 if (processor_->IsRunning()) {
427 return LogAndSetError(
428 error, FROM_HERE, "Already processing an update, cancel it first.");
429 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800430
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000431 if (apex_handler_android_ != nullptr) {
432 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
433 std::vector<ApexInfo> apex_infos_blank;
434 apex_handler_android_->AllocateSpace(apex_infos_blank);
435 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400436 // Remove the reboot marker so that if the machine is rebooted
437 // after resetting to idle state, it doesn't go back to
438 // UpdateStatus::UPDATED_NEED_REBOOT state.
439 if (!ClearUpdateCompletedMarker()) {
440 return LogAndSetError(error,
441 FROM_HERE,
442 "Failed to reset the status because "
443 "ClearUpdateCompletedMarker() failed");
444 }
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000445
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700446 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
447 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000448 << "space might not be freed.";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700449 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800450 switch (status_) {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700451 case UpdateStatus::IDLE: {
Alex Deymo3b678db2016-02-09 11:50:06 -0800452 return true;
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700453 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800454
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800455 case UpdateStatus::UPDATED_NEED_REBOOT: {
Kelvin Zhang20982a52021-08-13 12:31:16 -0700456 const bool ret_value = resetShouldSwitchSlotOnReboot(error);
457 if (ret_value) {
458 LOG(INFO) << "Reset status successful";
Alex Deymo3b678db2016-02-09 11:50:06 -0800459 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700460 return ret_value;
Alex Deymo3b678db2016-02-09 11:50:06 -0800461 }
462
463 default:
464 return LogAndSetError(
465 error,
466 FROM_HERE,
467 "Reset not allowed in this state. Cancel the ongoing update first");
468 }
469}
470
Yifan Hongbd47d622019-12-13 14:59:58 -0800471bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
472 const std::string& metadata_filename,
473 DeltaArchiveManifest* manifest,
474 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800475 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
476 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
477 return LogAndSetError(
478 error, FROM_HERE, "Failed to open " + metadata_filename);
479 }
480 brillo::Blob metadata(kMaxPayloadHeaderSize);
481 if (!fd->Read(metadata.data(), metadata.size())) {
482 return LogAndSetError(
483 error,
484 FROM_HERE,
485 "Failed to read payload header from " + metadata_filename);
486 }
Daniel Zhengda4f7292022-09-02 22:59:32 +0000487 ErrorCode errorcode{};
Sen Jiang8371c1c2018-02-01 13:46:39 -0800488 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700489 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800490 MetadataParseResult::kSuccess) {
491 return LogAndSetError(error,
492 FROM_HERE,
493 "Failed to parse payload header: " +
494 utils::ErrorCodeToString(errorcode));
495 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700496 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
497 payload_metadata.GetMetadataSignatureSize();
498 if (metadata_size < kMaxPayloadHeaderSize ||
499 metadata_size >
500 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800501 return LogAndSetError(
502 error,
503 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700504 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800505 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700506 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800507 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
508 metadata.size() - kMaxPayloadHeaderSize)) {
509 return LogAndSetError(
510 error,
511 FROM_HERE,
512 "Failed to read metadata and signature from " + metadata_filename);
513 }
514 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800515
Tianjie Xu7a78d632019-10-08 16:32:39 -0700516 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
517 constants::kUpdateCertificatesPath);
518 if (!payload_verifier) {
519 return LogAndSetError(error,
520 FROM_HERE,
521 "Failed to create the payload verifier from " +
522 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800523 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700524 errorcode = payload_metadata.ValidateMetadataSignature(
525 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800526 if (errorcode != ErrorCode::kSuccess) {
527 return LogAndSetError(error,
528 FROM_HERE,
529 "Failed to validate metadata signature: " +
530 utils::ErrorCodeToString(errorcode));
531 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800532 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800533 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
534 }
535
Yifan Hongbd47d622019-12-13 14:59:58 -0800536 return true;
537}
538
539bool UpdateAttempterAndroid::VerifyPayloadApplicable(
540 const std::string& metadata_filename, brillo::ErrorPtr* error) {
541 DeltaArchiveManifest manifest;
542 TEST_AND_RETURN_FALSE(
543 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
544
545 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
Daniel Zhengda4f7292022-09-02 22:59:32 +0000546 ErrorCode errorcode{};
Yifan Hongbd47d622019-12-13 14:59:58 -0800547
548 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800549 for (const PartitionUpdate& partition : manifest.partitions()) {
550 if (!partition.has_old_partition_info())
551 continue;
552 string partition_path;
553 if (!boot_control_->GetPartitionDevice(
554 partition.partition_name(), current_slot, &partition_path)) {
555 return LogAndSetError(
556 error,
557 FROM_HERE,
558 "Failed to get partition device for " + partition.partition_name());
559 }
560 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
561 return LogAndSetError(
562 error, FROM_HERE, "Failed to open " + partition_path);
563 }
564 for (const InstallOperation& operation : partition.operations()) {
565 if (!operation.has_src_sha256_hash())
566 continue;
567 brillo::Blob source_hash;
568 if (!fd_utils::ReadAndHashExtents(fd,
569 operation.src_extents(),
570 manifest.block_size(),
571 &source_hash)) {
572 return LogAndSetError(
573 error, FROM_HERE, "Failed to hash " + partition_path);
574 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400575 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800576 source_hash, operation, fd, &errorcode)) {
577 return false;
578 }
579 }
580 fd->Close();
581 }
582 return true;
583}
584
Alex Deymo5e3ea272016-01-28 13:42:23 -0800585void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
586 ErrorCode code) {
587 LOG(INFO) << "Processing Done.";
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800588 metric_bytes_downloaded_.Flush(true);
589 metric_total_bytes_downloaded_.Flush(true);
Kelvin Zhangf8441982022-12-07 18:18:47 -0800590 last_error_ = code;
Yifan Hong90965502020-02-19 15:22:47 -0800591 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
592 TerminateUpdateAndNotify(code);
593 return;
594 }
595
Alex Deymo5990bf32016-07-19 17:01:41 -0700596 switch (code) {
597 case ErrorCode::kSuccess:
598 // Update succeeded.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400599 if (!WriteUpdateCompletedMarker()) {
600 LOG(ERROR) << "Failed to write update completion marker";
601 }
Alex Deymo5990bf32016-07-19 17:01:41 -0700602 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800603
Alex Deymo5990bf32016-07-19 17:01:41 -0700604 LOG(INFO) << "Update successfully applied, waiting to reboot.";
605 break;
606
607 case ErrorCode::kFilesystemCopierError:
608 case ErrorCode::kNewRootfsVerificationError:
609 case ErrorCode::kNewKernelVerificationError:
610 case ErrorCode::kFilesystemVerifierError:
611 case ErrorCode::kDownloadStateInitializationError:
612 // Reset the ongoing update for these errors so it starts from the
613 // beginning next time.
614 DeltaPerformer::ResetUpdateProgress(prefs_, false);
615 LOG(INFO) << "Resetting update progress.";
616 break;
617
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700618 case ErrorCode::kPayloadTimestampError:
619 // SafetyNet logging, b/36232423
620 android_errorWriteLog(0x534e4554, "36232423");
621 break;
622
Alex Deymo5990bf32016-07-19 17:01:41 -0700623 default:
624 // Ignore all other error codes.
625 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700626 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800627
628 TerminateUpdateAndNotify(code);
629}
630
631void UpdateAttempterAndroid::ProcessingStopped(
632 const ActionProcessor* processor) {
633 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
634}
635
636void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
637 AbstractAction* action,
638 ErrorCode code) {
639 // Reset download progress regardless of whether or not the download
640 // action succeeded.
641 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800642 if (type == CleanupPreviousUpdateAction::StaticType() ||
643 (type == NoOpAction::StaticType() &&
644 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
645 cleanup_previous_update_code_ = code;
646 NotifyCleanupPreviousUpdateCallbacksAndClear();
647 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000648 // download_progress_ is actually used by other actions, such as
649 // filesystem_verify_action. Therefore we always clear it.
650 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700651 if (type == PostinstallRunnerAction::StaticType()) {
652 bool succeeded =
653 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
654 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
655 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800656 if (code != ErrorCode::kSuccess) {
657 // If an action failed, the ActionProcessor will cancel the whole thing.
658 return;
659 }
Yifan Hong83517502020-02-19 15:34:13 -0800660 if (type == UpdateBootFlagsAction::StaticType()) {
661 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
662 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800663 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400664 auto download_action = static_cast<DownloadAction*>(action);
665 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000666 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700667 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000668 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700669 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800670 }
671}
672
673void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
674 uint64_t bytes_received,
675 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700676 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800677 if (total)
678 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700679 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800680 download_progress_ = progress;
681 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700682 } else {
683 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800684 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700685
686 // Update the bytes downloaded in prefs.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800687 metric_bytes_downloaded_ += bytes_progressed;
688 metric_total_bytes_downloaded_ += bytes_progressed;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800689}
690
691bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
692 // TODO(deymo): Notify the DownloadAction that it should cancel the update
693 // download.
694 return false;
695}
696
697void UpdateAttempterAndroid::DownloadComplete() {
698 // Nothing needs to be done when the download completes.
699}
700
Alex Deymo0d298542016-03-30 18:31:49 -0700701void UpdateAttempterAndroid::ProgressUpdate(double progress) {
702 // Self throttle based on progress. Also send notifications if progress is
703 // too slow.
704 if (progress == 1.0 ||
705 progress - download_progress_ >= kBroadcastThresholdProgress ||
706 TimeTicks::Now() - last_notify_time_ >=
707 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
708 download_progress_ = progress;
709 SetStatusAndNotify(status_);
710 }
711}
712
Kelvin Zhang70eef232020-06-12 20:32:40 +0000713void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
714 assert(status_ == UpdateStatus::VERIFYING);
715 ProgressUpdate(progress);
716}
717
Alex Deymo5e3ea272016-01-28 13:42:23 -0800718void UpdateAttempterAndroid::ScheduleProcessingStart() {
719 LOG(INFO) << "Scheduling an action processor start.";
Kelvin Zhang20982a52021-08-13 12:31:16 -0700720 processor_->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800721 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700722 FROM_HERE,
723 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
724 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800725}
726
727void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
728 if (status_ == UpdateStatus::IDLE) {
729 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
730 return;
731 }
732
Yifan Hong90965502020-02-19 15:22:47 -0800733 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400734 ClearUpdateCompletedMarker();
Yifan Hong90965502020-02-19 15:22:47 -0800735 LOG(INFO) << "Terminating cleanup previous update.";
736 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700737 for (auto observer : daemon_state_->service_observers())
738 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800739 return;
740 }
741
Yifan Hong9194ce82019-11-07 11:03:42 -0800742 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700743
Alex Deymo0d298542016-03-30 18:31:49 -0700744 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800745 UpdateStatus new_status =
746 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
747 : UpdateStatus::IDLE);
748 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900749 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800750
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700751 // The network id is only applicable to one download attempt and once it's
752 // done the network id should not be re-used anymore.
753 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
754 LOG(WARNING) << "Unable to unbind network.";
755 }
756
Alex Deymo5e3ea272016-01-28 13:42:23 -0800757 for (auto observer : daemon_state_->service_observers())
758 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700759
Tianjie Xu90aaa102017-10-10 17:39:03 -0700760 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
761 ClearMetricsPrefs();
762 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800763 // We should only reset the PayloadAttemptNumber if the update succeeds, or
764 // we switch to a different payload.
765 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700766 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700767 // Clear the total bytes downloaded if and only if the update succeeds.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800768 metric_total_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -0700769 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800770}
771
772void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
773 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700774 size_t payload_size =
775 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700776 UpdateEngineStatus status_to_send = {.status = status_,
777 .progress = download_progress_,
778 .new_size_bytes = payload_size};
779
Alex Deymo5e3ea272016-01-28 13:42:23 -0800780 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700781 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800782 }
783 last_notify_time_ = TimeTicks::Now();
784}
785
Amin Hassani667cf7b2018-07-25 14:32:00 -0700786void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800787 CHECK(!processor_->IsRunning());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800788
789 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700790 auto update_boot_flags_action =
791 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800792 auto cleanup_previous_update_action =
793 boot_control_->GetDynamicPartitionControl()
794 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700795 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
796 auto download_action =
797 std::make_unique<DownloadAction>(prefs_,
798 boot_control_,
799 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700800 fetcher, // passes ownership
Kelvin Zhang1304fe72021-10-06 19:12:12 -0700801 true /* interactive */,
802 update_certificates_path_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800803 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700804 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700805 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
806 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700807 auto postinstall_runner_action =
808 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000809 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700810 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800811
Alex Deymo5e3ea272016-01-28 13:42:23 -0800812 // Bond them together. We have to use the leaf-types when calling
813 // BondActions().
814 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700815 BondActions(download_action.get(), filesystem_verifier_action.get());
816 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800817 postinstall_runner_action.get());
818
Amin Hassani667cf7b2018-07-25 14:32:00 -0700819 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800820 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700821 processor_->EnqueueAction(std::move(install_plan_action));
822 processor_->EnqueueAction(std::move(download_action));
823 processor_->EnqueueAction(std::move(filesystem_verifier_action));
824 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800825}
826
Alex Deymo5e3ea272016-01-28 13:42:23 -0800827bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
828 string boot_id;
829 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800830 LOG(INFO) << "Writing update complete marker, slot "
831 << boot_control_->GetCurrentSlot() << ", boot id: " << boot_id;
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400832 TEST_AND_RETURN_FALSE(
833 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id));
834 TEST_AND_RETURN_FALSE(
835 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot()));
836 return true;
837}
838
839bool UpdateAttempterAndroid::ClearUpdateCompletedMarker() {
840 LOG(INFO) << "Clearing update complete marker.";
841 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsUpdateCompletedOnBootId));
842 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsPreviousSlot));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800843 return true;
844}
845
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800846bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() const {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800847 // In case of an update_engine restart without a reboot, we stored the boot_id
848 // when the update was completed by setting a pref, so we can check whether
849 // the last update was on this boot or a previous one.
850 string boot_id;
851 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
852
853 string update_completed_on_boot_id;
854 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
855 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
856 &update_completed_on_boot_id) &&
857 update_completed_on_boot_id == boot_id);
858}
859
Tianjie Xu90aaa102017-10-10 17:39:03 -0700860// Collect and report the android metrics when we terminate the update.
861void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
862 ErrorCode error_code) {
863 int64_t attempt_number =
864 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
865 PayloadType payload_type = kPayloadTypeFull;
866 int64_t payload_size = 0;
867 for (const auto& p : install_plan_.payloads) {
868 if (p.type == InstallPayloadType::kDelta)
869 payload_type = kPayloadTypeDelta;
870 payload_size += p.size;
871 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700872 // In some cases, e.g. after calling |setShouldSwitchSlotOnReboot()|, this
873 // function will be triggered, but payload_size in this case might be 0, if so
874 // skip reporting any metrics.
875 if (payload_size == 0) {
876 return;
877 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700878
879 metrics::AttemptResult attempt_result =
880 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700881 Time boot_time_start = Time::FromInternalValue(
882 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
883 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700884 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700885 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
886 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700887
888 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700889 static_cast<int>(attempt_number),
890 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700891 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700892 duration_uptime,
893 payload_size,
894 attempt_result,
895 error_code);
896
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800897 int64_t current_bytes_downloaded = metric_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -0700898 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
899 current_bytes_downloaded,
900 0,
901 DownloadSource::kNumDownloadSources,
902 metrics::DownloadErrorCode::kUnset,
903 metrics::ConnectionType::kUnset);
904
Tianjie Xu90aaa102017-10-10 17:39:03 -0700905 if (error_code == ErrorCode::kSuccess) {
906 int64_t reboot_count =
907 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
908 string build_version;
909 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700910
911 // For android metrics, we only care about the total bytes downloaded
912 // for all sources; for now we assume the only download source is
913 // HttpsServer.
Kelvin Zhang32a73a92022-12-19 12:27:41 -0800914 int64_t total_bytes_downloaded = metric_total_bytes_downloaded_.get();
Tianjie Xud4777a12017-10-24 14:54:18 -0700915 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
916 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
917 total_bytes_downloaded;
918
919 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700920 if (total_bytes_downloaded >= payload_size) {
921 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700922 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700923 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
924 } else {
925 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
926 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700927 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700928
Tianjie Xu90aaa102017-10-10 17:39:03 -0700929 metrics_reporter_->ReportSuccessfulUpdateMetrics(
930 static_cast<int>(attempt_number),
931 0, // update abandoned count
932 payload_type,
933 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700934 num_bytes_downloaded,
935 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700936 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700937 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700938 static_cast<int>(reboot_count),
939 0); // url_switch_count
940 }
941}
942
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400943bool UpdateAttempterAndroid::OTARebootSucceeded() const {
944 const auto current_slot = boot_control_->GetCurrentSlot();
945 const string current_version =
946 android::base::GetProperty("ro.build.version.incremental", "");
947 int64_t previous_slot = -1;
948 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot));
949 string previous_version;
950 TEST_AND_RETURN_FALSE(
951 prefs_->GetString(kPrefsPreviousVersion, &previous_version));
952 if (previous_slot != current_slot) {
953 LOG(INFO) << "Detected a slot switch, OTA succeeded, device updated from "
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800954 << previous_version << " to " << current_version
955 << ", previous slot: " << previous_slot
956 << " current slot: " << current_slot;
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400957 if (previous_version == current_version) {
958 LOG(INFO) << "Previous version is the same as current version, this is "
959 "possibly a self-OTA.";
960 }
961 return true;
962 } else {
963 LOG(INFO) << "Slot didn't switch, either the OTA is rolled back, or slot "
964 "switch never happened, or system not rebooted at all.";
965 if (previous_version != current_version) {
966 LOG(INFO) << "Slot didn't change, but version changed from "
967 << previous_version << " to " << current_version
968 << " device could be flashed.";
969 }
970 return false;
971 }
972}
973
974OTAResult UpdateAttempterAndroid::GetOTAUpdateResult() const {
975 // We only set |kPrefsSystemUpdatedMarker| if slot is actually switched, so
976 // existence of this pref is sufficient indicator. Given that we have to
977 // delete this pref after checking it. This is done in
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -0800978 // |DeltaPerformer::ResetUpdateProgress| and
979 // |UpdateAttempterAndroid::UpdateStateAfterReboot|
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400980 auto slot_switch_attempted = prefs_->Exists(kPrefsUpdateCompletedOnBootId);
981 auto system_rebooted = DidSystemReboot(prefs_);
982 auto ota_successful = OTARebootSucceeded();
983 if (ota_successful) {
984 return OTAResult::OTA_SUCCESSFUL;
985 }
986 if (slot_switch_attempted) {
987 if (system_rebooted) {
988 // If we attempted slot switch, but still end up on the same slot, we
989 // probably rolled back.
990 return OTAResult::ROLLED_BACK;
991 } else {
992 return OTAResult::UPDATED_NEED_REBOOT;
993 }
994 }
995 return OTAResult::NOT_ATTEMPTED;
996}
997
998void UpdateAttempterAndroid::UpdateStateAfterReboot(const OTAResult result) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700999 // Example: [ro.build.version.incremental]: [4292972]
1000 string current_version =
1001 android::base::GetProperty("ro.build.version.incremental", "");
1002 TEST_AND_RETURN(!current_version.empty());
1003
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001004 // |UpdateStateAfterReboot()| is only called after system reboot, so record
1005 // boot id unconditionally
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001006 string current_boot_id;
1007 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
1008 prefs_->SetString(kPrefsBootId, current_boot_id);
Kelvin Zhang1bcd7d72023-02-14 16:43:34 -08001009 std::string slot_switch_indicator;
1010 prefs_->GetString(kPrefsUpdateCompletedOnBootId, &slot_switch_indicator);
1011 if (slot_switch_indicator != current_boot_id) {
1012 ClearUpdateCompletedMarker();
1013 }
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001014
Tianjie Xu90aaa102017-10-10 17:39:03 -07001015 // If there's no record of previous version (e.g. due to a data wipe), we
1016 // save the info of current boot and skip the metrics report.
1017 if (!prefs_->Exists(kPrefsPreviousVersion)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001018 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001019 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001020 ClearMetricsPrefs();
1021 return;
1022 }
Kelvin Zhang86603472021-05-11 12:16:27 -04001023 // update_engine restarted under the same build and same slot.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001024 if (result != OTAResult::OTA_SUCCESSFUL) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001025 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
1026 // set when we start a new update.
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001027 if (prefs_->Exists(kPrefsNumReboots)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001028 int64_t reboot_count =
1029 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1030 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
1031 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001032
1033 if (result == OTAResult::ROLLED_BACK) {
1034 // This will release all space previously allocated for apex
1035 // decompression. If we detect a rollback, we should release space and
1036 // return the space to user. Any subsequent attempt to install OTA will
1037 // allocate space again anyway.
1038 LOG(INFO) << "Detected a rollback, releasing space allocated for apex "
1039 "deompression.";
1040 apex_handler_android_->AllocateSpace({});
1041 DeltaPerformer::ResetUpdateProgress(prefs_, false);
1042 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001043 return;
1044 }
1045
1046 // Now that the build version changes, report the update metrics.
1047 // TODO(xunchang) check the build version is larger than the previous one.
Tianjie Xu90aaa102017-10-10 17:39:03 -07001048 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001049 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001050
1051 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
1052 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
1053 if (previous_attempt_exists) {
1054 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
1055 }
1056
1057 metrics_utils::LoadAndReportTimeToReboot(
1058 metrics_reporter_.get(), prefs_, clock_.get());
1059 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -08001060
1061 // Also reset the update progress if the build version has changed.
1062 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1063 LOG(WARNING) << "Unable to reset the update progress.";
1064 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001065}
1066
1067// Save the update start time. Reset the reboot count and attempt number if the
1068// update isn't a resume; otherwise increment the attempt number.
1069void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
1070 if (!is_resume) {
1071 metrics_utils::SetNumReboots(0, prefs_);
1072 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
1073 } else {
1074 int64_t attempt_number =
1075 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1076 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
1077 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001078 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
1079 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001080 ClearUpdateCompletedMarker();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001081}
1082
1083void UpdateAttempterAndroid::ClearMetricsPrefs() {
1084 CHECK(prefs_);
Kelvin Zhang32a73a92022-12-19 12:27:41 -08001085 metric_bytes_downloaded_.Delete();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001086 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001087 prefs_->Delete(kPrefsSystemUpdatedMarker);
1088 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001089 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001090}
1091
Yifan Hongbd47d622019-12-13 14:59:58 -08001092BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
1093 return boot_control_->GetCurrentSlot();
1094}
1095
1096BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
1097 return GetCurrentSlot() == 0 ? 1 : 0;
1098}
1099
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001100uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
1101 const std::string& metadata_filename,
1102 const vector<string>& key_value_pair_headers,
1103 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -08001104 DeltaArchiveManifest manifest;
1105 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
1106 return 0;
1107 }
1108 std::map<string, string> headers;
1109 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1110 return 0;
1111 }
1112
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001113 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1114 manifest.apex_info().end());
1115 uint64_t apex_size_required = 0;
1116 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001117 auto result = apex_handler_android_->CalculateSize(apex_infos);
1118 if (!result.ok()) {
1119 LogAndSetError(error,
1120 FROM_HERE,
1121 "Failed to calculate size required for compressed APEX");
1122 return 0;
1123 }
1124 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001125 }
1126
Yifan Hong65613032020-01-09 17:52:13 -08001127 string payload_id = GetPayloadId(headers);
1128 uint64_t required_size = 0;
1129 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1130 boot_control_,
1131 GetTargetSlot(),
1132 manifest,
1133 payload_id,
1134 &required_size)) {
1135 if (required_size == 0) {
1136 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
1137 return 0;
1138 } else {
1139 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001140 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001141 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001142 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001143 }
1144 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001145
1146 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001147 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001148 LOG(ERROR) << "Insufficient space for apex decompression: "
1149 << apex_size_required << " bytes";
1150 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001151 }
Yifan Hong65613032020-01-09 17:52:13 -08001152
1153 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001154 return 0;
1155}
1156
Yifan Hong40bb0d02020-02-24 17:33:14 -08001157void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1158 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Yifan Hong2236ea02019-12-13 16:11:22 -08001159 brillo::ErrorPtr* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001160 if (cleanup_previous_update_code_.has_value()) {
1161 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1162 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1163 if (callback) {
1164 callback->OnCleanupComplete(
1165 static_cast<int32_t>(*cleanup_previous_update_code_));
1166 }
1167 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001168 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001169 if (callback) {
1170 auto callback_ptr = callback.get();
1171 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1172 callback_ptr->RegisterForDeathNotifications(
1173 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1174 base::Unretained(this),
1175 base::Unretained(callback_ptr)));
1176 }
1177 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001178}
1179
Tianjie7f8f2ab2021-07-23 17:08:50 -07001180bool UpdateAttempterAndroid::setShouldSwitchSlotOnReboot(
1181 const std::string& metadata_filename, brillo::ErrorPtr* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -07001182 LOG(INFO) << "setShouldSwitchSlotOnReboot(" << metadata_filename << ")";
Tianjie7f8f2ab2021-07-23 17:08:50 -07001183 if (processor_->IsRunning()) {
1184 return LogAndSetError(
1185 error, FROM_HERE, "Already processing an update, cancel it first.");
1186 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001187 DeltaArchiveManifest manifest;
1188 TEST_AND_RETURN_FALSE(
1189 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
1190
Kelvin Zhang20982a52021-08-13 12:31:16 -07001191 InstallPlan install_plan_;
1192 install_plan_.source_slot = GetCurrentSlot();
1193 install_plan_.target_slot = GetTargetSlot();
1194 // Don't do verity computation, just hash the partitions
1195 install_plan_.write_verity = false;
1196 // Don't run postinstall, we just need PostinstallAction to switch the slots.
1197 install_plan_.run_post_install = false;
1198 install_plan_.is_resume = true;
1199
1200 CHECK_NE(install_plan_.source_slot, UINT32_MAX);
1201 CHECK_NE(install_plan_.target_slot, UINT32_MAX);
1202
Kelvin Zhang20982a52021-08-13 12:31:16 -07001203 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
Kelvin Zhang20982a52021-08-13 12:31:16 -07001204 auto postinstall_runner_action =
1205 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
1206 SetStatusAndNotify(UpdateStatus::VERIFYING);
Kelvin Zhang20982a52021-08-13 12:31:16 -07001207 postinstall_runner_action->set_delegate(this);
1208
Kelvin Zhangf8441982022-12-07 18:18:47 -08001209 // If last error code is kUpdatedButNotActive, we know that we reached this
1210 // state by calling applyPayload() with switch_slot=false. That applyPayload()
1211 // call would have already performed filesystem verification, therefore, we
1212 // can safely skip the verification to save time.
1213 if (last_error_ == ErrorCode::kUpdatedButNotActive) {
1214 BondActions(install_plan_action.get(), postinstall_runner_action.get());
1215 processor_->EnqueueAction(std::move(install_plan_action));
1216 } else {
Kelvin Zhang263a5402022-12-08 23:03:32 -08001217 if (!boot_control_->GetDynamicPartitionControl()
1218 ->PreparePartitionsForUpdate(GetCurrentSlot(),
1219 GetTargetSlot(),
1220 manifest,
1221 false /* should update */,
1222 nullptr)) {
1223 return LogAndSetError(
1224 error, FROM_HERE, "Failed to PreparePartitionsForUpdate");
1225 }
1226 ErrorCode error_code{};
1227 if (!install_plan_.ParsePartitions(manifest.partitions(),
1228 boot_control_,
1229 manifest.block_size(),
1230 &error_code)) {
1231 return LogAndSetError(error,
1232 FROM_HERE,
1233 "Failed to LoadPartitionsFromSlots " +
1234 utils::ErrorCodeToString(error_code));
1235 }
1236
Kelvin Zhangf8441982022-12-07 18:18:47 -08001237 auto filesystem_verifier_action =
1238 std::make_unique<FilesystemVerifierAction>(
1239 boot_control_->GetDynamicPartitionControl());
1240 filesystem_verifier_action->set_delegate(this);
1241 BondActions(install_plan_action.get(), filesystem_verifier_action.get());
1242 BondActions(filesystem_verifier_action.get(),
1243 postinstall_runner_action.get());
1244 processor_->EnqueueAction(std::move(install_plan_action));
1245 processor_->EnqueueAction(std::move(filesystem_verifier_action));
1246 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001247
Kelvin Zhang20982a52021-08-13 12:31:16 -07001248 processor_->EnqueueAction(std::move(postinstall_runner_action));
1249 ScheduleProcessingStart();
1250 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001251}
1252
1253bool UpdateAttempterAndroid::resetShouldSwitchSlotOnReboot(
1254 brillo::ErrorPtr* error) {
1255 if (processor_->IsRunning()) {
1256 return LogAndSetError(
1257 error, FROM_HERE, "Already processing an update, cancel it first.");
1258 }
Daniel Zhenge76cf562022-11-08 17:32:10 +00001259 TEST_AND_RETURN_FALSE(ClearUpdateCompletedMarker());
Kelvin Zhang20982a52021-08-13 12:31:16 -07001260 // Update the boot flags so the current slot has higher priority.
1261 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot())) {
1262 return LogAndSetError(error, FROM_HERE, "Failed to SetActiveBootSlot");
1263 }
1264
1265 // Mark the current slot as successful again, since marking it as active
1266 // may reset the successful bit. We ignore the result of whether marking
1267 // the current slot as successful worked.
1268 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {}))) {
1269 return LogAndSetError(
1270 error, FROM_HERE, "Failed to MarkBootSuccessfulAsync");
1271 }
1272
1273 // Resets the warm reset property since we won't switch the slot.
1274 hardware_->SetWarmReset(false);
1275
1276 // Resets the vbmeta digest.
1277 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
1278 LOG(INFO) << "Slot switch cancelled.";
1279 SetStatusAndNotify(UpdateStatus::IDLE);
1280 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001281}
1282
Yifan Hong90965502020-02-19 15:22:47 -08001283void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1284 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1285 // is in progress, skip enqueueing the action.
1286 if (processor_->IsRunning()) {
1287 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1288 << "be done when the current update finishes.";
1289 return;
1290 }
1291 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1292 auto action =
1293 boot_control_->GetDynamicPartitionControl()
1294 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1295 processor_->EnqueueAction(std::move(action));
1296 processor_->set_delegate(this);
1297 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1298 processor_->StartProcessing();
1299}
1300
Yifan Hong40bb0d02020-02-24 17:33:14 -08001301void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1302 for (auto&& callback : cleanup_previous_update_callbacks_) {
1303 callback->OnCleanupProgressUpdate(progress);
1304 }
1305}
1306
1307void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1308 CHECK(cleanup_previous_update_code_.has_value());
1309 for (auto&& callback : cleanup_previous_update_callbacks_) {
1310 callback->OnCleanupComplete(
1311 static_cast<int32_t>(*cleanup_previous_update_code_));
1312 }
1313 cleanup_previous_update_callbacks_.clear();
1314}
1315
1316void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1317 CleanupSuccessfulUpdateCallbackInterface* callback) {
1318 auto end_it =
1319 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1320 cleanup_previous_update_callbacks_.end(),
1321 [&](const auto& e) { return e.get() == callback; });
1322 cleanup_previous_update_callbacks_.erase(
1323 end_it, cleanup_previous_update_callbacks_.end());
1324}
Yifan Hong90965502020-02-19 15:22:47 -08001325
Daniel Zheng9fc62b82023-03-24 22:57:20 +00001326bool UpdateAttempterAndroid::IsProductionBuild() {
1327 if (android::base::GetProperty("ro.build.type", "") != "userdebug" ||
1328 android::base::GetProperty("ro.build.tags", "") == "release-keys" ||
1329 android::base::GetProperty("ro.boot.verifiedbootstate", "") == "green") {
1330 return true;
1331 }
1332 return false;
1333}
1334
Alex Deymo5e3ea272016-01-28 13:42:23 -08001335} // namespace chromeos_update_engine