blob: ff74f4dc7715b7a4c04f6963a7d7cff1165f021b [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()),
Tianjie Xud4c5deb2017-10-24 11:17:03 -0700147 clock_(new Clock()) {
Yifan Hongc514f662021-02-04 11:18:43 -0800148 metrics_reporter_ = metrics::CreateMetricsReporter(
Kelvin Zhang9a5e3682021-03-29 12:58:48 -0400149 boot_control_->GetDynamicPartitionControl(), &install_plan_);
Alex Deymo87792ea2016-07-25 15:40:36 -0700150 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800151}
152
153UpdateAttempterAndroid::~UpdateAttempterAndroid() {
154 // Release ourselves as the ActionProcessor's delegate to prevent
155 // re-scheduling the updates due to the processing stopped.
156 processor_->set_delegate(nullptr);
157}
158
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400159[[nodiscard]] static bool DidSystemReboot(PrefsInterface* prefs) {
160 string boot_id;
161 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
162 string old_boot_id;
163 // If no previous boot id found, treat as a reboot and write boot ID.
164 if (!prefs->GetString(kPrefsBootId, &old_boot_id)) {
165 return true;
166 }
167 return old_boot_id != boot_id;
168}
169
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400170std::ostream& operator<<(std::ostream& out, OTAResult result) {
171 switch (result) {
172 case OTAResult::NOT_ATTEMPTED:
173 out << "OTAResult::NOT_ATTEMPTED";
174 break;
175 case OTAResult::ROLLED_BACK:
176 out << "OTAResult::ROLLED_BACK";
177 break;
178 case OTAResult::UPDATED_NEED_REBOOT:
179 out << "OTAResult::UPDATED_NEED_REBOOT";
180 break;
181 case OTAResult::OTA_SUCCESSFUL:
182 out << "OTAResult::OTA_SUCCESSFUL";
183 break;
184 }
185 return out;
186}
187
Alex Deymo5e3ea272016-01-28 13:42:23 -0800188void UpdateAttempterAndroid::Init() {
189 // In case of update_engine restart without a reboot we need to restore the
190 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700191 if (UpdateCompletedOnThisBoot()) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400192 LOG(INFO) << "Updated installed but update_engine is restarted without "
193 "device reboot. Resuming old state.";
Alex Deymo0e061ae2016-02-09 17:49:03 -0800194 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700195 } else {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400196 const auto result = GetOTAUpdateResult();
197 LOG(INFO) << result;
Alex Deymo0e061ae2016-02-09 17:49:03 -0800198 SetStatusAndNotify(UpdateStatus::IDLE);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400199 if (DidSystemReboot(prefs_)) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400200 UpdateStateAfterReboot(result);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400201 }
202
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700203#ifdef _UE_SIDELOAD
204 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
205 << "ApplyPayload will call it later.";
206#else
Yifan Hong90965502020-02-19 15:22:47 -0800207 ScheduleCleanupPreviousUpdate();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700208#endif
Tianjie Xu90aaa102017-10-10 17:39:03 -0700209 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800210}
211
212bool UpdateAttempterAndroid::ApplyPayload(
213 const string& payload_url,
214 int64_t payload_offset,
215 int64_t payload_size,
216 const vector<string>& key_value_pair_headers,
217 brillo::ErrorPtr* error) {
218 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
219 return LogAndSetError(
220 error, FROM_HERE, "An update already applied, waiting for reboot");
221 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700222 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800223 return LogAndSetError(
224 error, FROM_HERE, "Already processing an update, cancel it first.");
225 }
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100226 DCHECK_EQ(status_, UpdateStatus::IDLE);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800227
Alex Deymo218397f2016-02-04 23:55:10 -0800228 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800229 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
230 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800231 }
232
Yifan Hongbd47d622019-12-13 14:59:58 -0800233 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800234
235 // Setup the InstallPlan based on the request.
236 install_plan_ = InstallPlan();
237
238 install_plan_.download_url = payload_url;
239 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800240 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800241 InstallPlan::Payload payload;
242 payload.size = payload_size;
243 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800244 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800245 &payload.size)) {
246 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800247 }
248 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700249 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800250 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700251 LOG(WARNING) << "Unable to decode base64 file hash: "
252 << headers[kPayloadPropertyFileHash];
253 }
Alex Deymo218397f2016-02-04 23:55:10 -0800254 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800255 &payload.metadata_size)) {
256 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800257 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700258 // The |payload.type| is not used anymore since minor_version 3.
259 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800260 install_plan_.payloads.push_back(payload);
261
Alex Deymo5e3ea272016-01-28 13:42:23 -0800262 // The |public_key_rsa| key would override the public key stored on disk.
263 install_plan_.public_key_rsa = "";
264
265 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
266 install_plan_.is_resume = !payload_id.empty() &&
267 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
268 if (!install_plan_.is_resume) {
Kelvin Zhang42c2d552022-07-25 11:04:00 -0700269 boot_control_->GetDynamicPartitionControl()->Cleanup();
Kelvin Zhangc54c9962022-10-20 13:44:59 -0700270 boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_);
271
Alex Deymo5e3ea272016-01-28 13:42:23 -0800272 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
273 LOG(WARNING) << "Unable to save the update check response hash.";
274 }
275 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800276 install_plan_.source_slot = GetCurrentSlot();
277 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700278
Alex Deymofb905d92016-06-03 19:26:58 -0700279 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700280 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
281
282 install_plan_.switch_slot_on_reboot =
283 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
284
Tianjie Xu087de9d2019-11-01 17:11:22 -0700285 install_plan_.run_post_install =
286 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800287
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700288 // Skip writing verity if we're resuming and verity has already been written.
289 install_plan_.write_verity = true;
290 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
291 bool verity_written = false;
292 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
293 verity_written) {
294 install_plan_.write_verity = false;
295 }
296 }
297
Alex Deymo87792ea2016-07-25 15:40:36 -0700298 NetworkId network_id = kDefaultNetworkId;
299 if (!headers[kPayloadPropertyNetworkId].empty()) {
300 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
301 &network_id)) {
302 return LogAndSetError(
303 error,
304 FROM_HERE,
305 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
306 }
307 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700308 return LogAndSetError(
309 error,
310 FROM_HERE,
311 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700312 }
313 }
314
Alex Deymo5e3ea272016-01-28 13:42:23 -0800315 LOG(INFO) << "Using this install plan:";
316 install_plan_.Dump();
317
Amin Hassani667cf7b2018-07-25 14:32:00 -0700318 HttpFetcher* fetcher = nullptr;
319 if (FileFetcher::SupportedUrl(payload_url)) {
320 DLOG(INFO) << "Using FileFetcher for file URL.";
321 fetcher = new FileFetcher();
322 } else {
323#ifdef _UE_SIDELOAD
324 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
325#else
Kelvin Zhangc7a1d1f2022-07-29 13:36:29 -0700326 LibcurlHttpFetcher* libcurl_fetcher = new LibcurlHttpFetcher(hardware_);
Kelvin Zhang3cc4fa32022-09-27 16:15:10 -0700327 if (!headers[kPayloadDownloadRetry].empty()) {
328 libcurl_fetcher->set_max_retry_count(
329 atoi(headers[kPayloadDownloadRetry].c_str()));
330 }
Amin Hassani667cf7b2018-07-25 14:32:00 -0700331 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
332 fetcher = libcurl_fetcher;
333#endif // _UE_SIDELOAD
334 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800335 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800336 if (!headers[kPayloadPropertyAuthorization].empty())
337 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
338 if (!headers[kPayloadPropertyUserAgent].empty())
339 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
340
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700341 if (!headers[kPayloadPropertyNetworkProxy].empty()) {
342 LOG(INFO) << "Using proxy url from payload headers: "
343 << headers[kPayloadPropertyNetworkProxy];
344 fetcher->SetProxies({headers[kPayloadPropertyNetworkProxy]});
345 }
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000346 if (!headers[kPayloadDisableVABC].empty()) {
347 install_plan_.disable_vabc = true;
348 }
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700349
Amin Hassani667cf7b2018-07-25 14:32:00 -0700350 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800351
Alex Deymo5e3ea272016-01-28 13:42:23 -0800352 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700353
354 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
355 // TODO(xunchang) report the metrics for unresumable updates
356
Amin Hassani667cf7b2018-07-25 14:32:00 -0700357 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800358 return true;
359}
360
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900361bool UpdateAttempterAndroid::ApplyPayload(
362 int fd,
363 int64_t payload_offset,
364 int64_t payload_size,
365 const vector<string>& key_value_pair_headers,
366 brillo::ErrorPtr* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100367 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000368 // already running update will be terminated (existing file descriptor will be
369 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100370 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
371 return LogAndSetError(
372 error, FROM_HERE, "An update already applied, waiting for reboot");
373 }
374 if (processor_->IsRunning()) {
375 return LogAndSetError(
376 error, FROM_HERE, "Already processing an update, cancel it first.");
377 }
378 DCHECK_EQ(status_, UpdateStatus::IDLE);
379
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900380 payload_fd_.reset(dup(fd));
381 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
382
383 return ApplyPayload(
384 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
385}
386
Alex Deymo5e3ea272016-01-28 13:42:23 -0800387bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700388 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800389 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
390 processor_->SuspendProcessing();
391 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800392}
393
394bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700395 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800396 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
397 processor_->ResumeProcessing();
398 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800399}
400
401bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700402 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800403 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800404 processor_->StopProcessing();
405 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800406}
407
Alex Deymo3b678db2016-02-09 11:50:06 -0800408bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
409 LOG(INFO) << "Attempting to reset state from "
410 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700411 if (processor_->IsRunning()) {
412 return LogAndSetError(
413 error, FROM_HERE, "Already processing an update, cancel it first.");
414 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800415
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000416 if (apex_handler_android_ != nullptr) {
417 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
418 std::vector<ApexInfo> apex_infos_blank;
419 apex_handler_android_->AllocateSpace(apex_infos_blank);
420 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400421 // Remove the reboot marker so that if the machine is rebooted
422 // after resetting to idle state, it doesn't go back to
423 // UpdateStatus::UPDATED_NEED_REBOOT state.
424 if (!ClearUpdateCompletedMarker()) {
425 return LogAndSetError(error,
426 FROM_HERE,
427 "Failed to reset the status because "
428 "ClearUpdateCompletedMarker() failed");
429 }
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000430
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700431 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
432 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000433 << "space might not be freed.";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700434 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800435 switch (status_) {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700436 case UpdateStatus::IDLE: {
Alex Deymo3b678db2016-02-09 11:50:06 -0800437 return true;
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700438 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800439
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800440 case UpdateStatus::UPDATED_NEED_REBOOT: {
Kelvin Zhang20982a52021-08-13 12:31:16 -0700441 const bool ret_value = resetShouldSwitchSlotOnReboot(error);
442 if (ret_value) {
443 LOG(INFO) << "Reset status successful";
Alex Deymo3b678db2016-02-09 11:50:06 -0800444 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700445 return ret_value;
Alex Deymo3b678db2016-02-09 11:50:06 -0800446 }
447
448 default:
449 return LogAndSetError(
450 error,
451 FROM_HERE,
452 "Reset not allowed in this state. Cancel the ongoing update first");
453 }
454}
455
Yifan Hongbd47d622019-12-13 14:59:58 -0800456bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
457 const std::string& metadata_filename,
458 DeltaArchiveManifest* manifest,
459 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800460 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
461 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
462 return LogAndSetError(
463 error, FROM_HERE, "Failed to open " + metadata_filename);
464 }
465 brillo::Blob metadata(kMaxPayloadHeaderSize);
466 if (!fd->Read(metadata.data(), metadata.size())) {
467 return LogAndSetError(
468 error,
469 FROM_HERE,
470 "Failed to read payload header from " + metadata_filename);
471 }
Daniel Zhengda4f7292022-09-02 22:59:32 +0000472 ErrorCode errorcode{};
Sen Jiang8371c1c2018-02-01 13:46:39 -0800473 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700474 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800475 MetadataParseResult::kSuccess) {
476 return LogAndSetError(error,
477 FROM_HERE,
478 "Failed to parse payload header: " +
479 utils::ErrorCodeToString(errorcode));
480 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700481 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
482 payload_metadata.GetMetadataSignatureSize();
483 if (metadata_size < kMaxPayloadHeaderSize ||
484 metadata_size >
485 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800486 return LogAndSetError(
487 error,
488 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700489 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800490 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700491 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800492 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
493 metadata.size() - kMaxPayloadHeaderSize)) {
494 return LogAndSetError(
495 error,
496 FROM_HERE,
497 "Failed to read metadata and signature from " + metadata_filename);
498 }
499 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800500
Tianjie Xu7a78d632019-10-08 16:32:39 -0700501 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
502 constants::kUpdateCertificatesPath);
503 if (!payload_verifier) {
504 return LogAndSetError(error,
505 FROM_HERE,
506 "Failed to create the payload verifier from " +
507 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800508 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700509 errorcode = payload_metadata.ValidateMetadataSignature(
510 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800511 if (errorcode != ErrorCode::kSuccess) {
512 return LogAndSetError(error,
513 FROM_HERE,
514 "Failed to validate metadata signature: " +
515 utils::ErrorCodeToString(errorcode));
516 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800517 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800518 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
519 }
520
Yifan Hongbd47d622019-12-13 14:59:58 -0800521 return true;
522}
523
524bool UpdateAttempterAndroid::VerifyPayloadApplicable(
525 const std::string& metadata_filename, brillo::ErrorPtr* error) {
526 DeltaArchiveManifest manifest;
527 TEST_AND_RETURN_FALSE(
528 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
529
530 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
Daniel Zhengda4f7292022-09-02 22:59:32 +0000531 ErrorCode errorcode{};
Yifan Hongbd47d622019-12-13 14:59:58 -0800532
533 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800534 for (const PartitionUpdate& partition : manifest.partitions()) {
535 if (!partition.has_old_partition_info())
536 continue;
537 string partition_path;
538 if (!boot_control_->GetPartitionDevice(
539 partition.partition_name(), current_slot, &partition_path)) {
540 return LogAndSetError(
541 error,
542 FROM_HERE,
543 "Failed to get partition device for " + partition.partition_name());
544 }
545 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
546 return LogAndSetError(
547 error, FROM_HERE, "Failed to open " + partition_path);
548 }
549 for (const InstallOperation& operation : partition.operations()) {
550 if (!operation.has_src_sha256_hash())
551 continue;
552 brillo::Blob source_hash;
553 if (!fd_utils::ReadAndHashExtents(fd,
554 operation.src_extents(),
555 manifest.block_size(),
556 &source_hash)) {
557 return LogAndSetError(
558 error, FROM_HERE, "Failed to hash " + partition_path);
559 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400560 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800561 source_hash, operation, fd, &errorcode)) {
562 return false;
563 }
564 }
565 fd->Close();
566 }
567 return true;
568}
569
Alex Deymo5e3ea272016-01-28 13:42:23 -0800570void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
571 ErrorCode code) {
572 LOG(INFO) << "Processing Done.";
Kelvin Zhangf8441982022-12-07 18:18:47 -0800573 last_error_ = code;
Yifan Hong90965502020-02-19 15:22:47 -0800574 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
575 TerminateUpdateAndNotify(code);
576 return;
577 }
578
Alex Deymo5990bf32016-07-19 17:01:41 -0700579 switch (code) {
580 case ErrorCode::kSuccess:
581 // Update succeeded.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400582 if (!WriteUpdateCompletedMarker()) {
583 LOG(ERROR) << "Failed to write update completion marker";
584 }
Alex Deymo5990bf32016-07-19 17:01:41 -0700585 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800586
Alex Deymo5990bf32016-07-19 17:01:41 -0700587 LOG(INFO) << "Update successfully applied, waiting to reboot.";
588 break;
589
590 case ErrorCode::kFilesystemCopierError:
591 case ErrorCode::kNewRootfsVerificationError:
592 case ErrorCode::kNewKernelVerificationError:
593 case ErrorCode::kFilesystemVerifierError:
594 case ErrorCode::kDownloadStateInitializationError:
595 // Reset the ongoing update for these errors so it starts from the
596 // beginning next time.
597 DeltaPerformer::ResetUpdateProgress(prefs_, false);
598 LOG(INFO) << "Resetting update progress.";
599 break;
600
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700601 case ErrorCode::kPayloadTimestampError:
602 // SafetyNet logging, b/36232423
603 android_errorWriteLog(0x534e4554, "36232423");
604 break;
605
Alex Deymo5990bf32016-07-19 17:01:41 -0700606 default:
607 // Ignore all other error codes.
608 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700609 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800610
611 TerminateUpdateAndNotify(code);
612}
613
614void UpdateAttempterAndroid::ProcessingStopped(
615 const ActionProcessor* processor) {
616 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
617}
618
619void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
620 AbstractAction* action,
621 ErrorCode code) {
622 // Reset download progress regardless of whether or not the download
623 // action succeeded.
624 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800625 if (type == CleanupPreviousUpdateAction::StaticType() ||
626 (type == NoOpAction::StaticType() &&
627 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
628 cleanup_previous_update_code_ = code;
629 NotifyCleanupPreviousUpdateCallbacksAndClear();
630 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000631 // download_progress_ is actually used by other actions, such as
632 // filesystem_verify_action. Therefore we always clear it.
633 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700634 if (type == PostinstallRunnerAction::StaticType()) {
635 bool succeeded =
636 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
637 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
638 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800639 if (code != ErrorCode::kSuccess) {
640 // If an action failed, the ActionProcessor will cancel the whole thing.
641 return;
642 }
Yifan Hong83517502020-02-19 15:34:13 -0800643 if (type == UpdateBootFlagsAction::StaticType()) {
644 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
645 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800646 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400647 auto download_action = static_cast<DownloadAction*>(action);
648 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000649 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700650 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000651 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700652 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800653 }
654}
655
656void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
657 uint64_t bytes_received,
658 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700659 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800660 if (total)
661 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700662 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800663 download_progress_ = progress;
664 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700665 } else {
666 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800667 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700668
669 // Update the bytes downloaded in prefs.
670 int64_t current_bytes_downloaded =
671 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
672 int64_t total_bytes_downloaded =
673 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
674 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
675 current_bytes_downloaded + bytes_progressed);
676 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
677 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800678}
679
680bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
681 // TODO(deymo): Notify the DownloadAction that it should cancel the update
682 // download.
683 return false;
684}
685
686void UpdateAttempterAndroid::DownloadComplete() {
687 // Nothing needs to be done when the download completes.
688}
689
Alex Deymo0d298542016-03-30 18:31:49 -0700690void UpdateAttempterAndroid::ProgressUpdate(double progress) {
691 // Self throttle based on progress. Also send notifications if progress is
692 // too slow.
693 if (progress == 1.0 ||
694 progress - download_progress_ >= kBroadcastThresholdProgress ||
695 TimeTicks::Now() - last_notify_time_ >=
696 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
697 download_progress_ = progress;
698 SetStatusAndNotify(status_);
699 }
700}
701
Kelvin Zhang70eef232020-06-12 20:32:40 +0000702void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
703 assert(status_ == UpdateStatus::VERIFYING);
704 ProgressUpdate(progress);
705}
706
Alex Deymo5e3ea272016-01-28 13:42:23 -0800707void UpdateAttempterAndroid::ScheduleProcessingStart() {
708 LOG(INFO) << "Scheduling an action processor start.";
Kelvin Zhang20982a52021-08-13 12:31:16 -0700709 processor_->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800710 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700711 FROM_HERE,
712 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
713 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800714}
715
716void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
717 if (status_ == UpdateStatus::IDLE) {
718 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
719 return;
720 }
721
Yifan Hong90965502020-02-19 15:22:47 -0800722 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400723 ClearUpdateCompletedMarker();
Yifan Hong90965502020-02-19 15:22:47 -0800724 LOG(INFO) << "Terminating cleanup previous update.";
725 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700726 for (auto observer : daemon_state_->service_observers())
727 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800728 return;
729 }
730
Yifan Hong9194ce82019-11-07 11:03:42 -0800731 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700732
Alex Deymo0d298542016-03-30 18:31:49 -0700733 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800734 UpdateStatus new_status =
735 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
736 : UpdateStatus::IDLE);
737 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900738 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800739
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700740 // The network id is only applicable to one download attempt and once it's
741 // done the network id should not be re-used anymore.
742 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
743 LOG(WARNING) << "Unable to unbind network.";
744 }
745
Alex Deymo5e3ea272016-01-28 13:42:23 -0800746 for (auto observer : daemon_state_->service_observers())
747 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700748
Tianjie Xu90aaa102017-10-10 17:39:03 -0700749 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
750 ClearMetricsPrefs();
751 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800752 // We should only reset the PayloadAttemptNumber if the update succeeds, or
753 // we switch to a different payload.
754 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700755 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700756 // Clear the total bytes downloaded if and only if the update succeeds.
757 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700758 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800759}
760
761void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
762 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700763 size_t payload_size =
764 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700765 UpdateEngineStatus status_to_send = {.status = status_,
766 .progress = download_progress_,
767 .new_size_bytes = payload_size};
768
Alex Deymo5e3ea272016-01-28 13:42:23 -0800769 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700770 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800771 }
772 last_notify_time_ = TimeTicks::Now();
773}
774
Amin Hassani667cf7b2018-07-25 14:32:00 -0700775void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800776 CHECK(!processor_->IsRunning());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800777
778 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700779 auto update_boot_flags_action =
780 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800781 auto cleanup_previous_update_action =
782 boot_control_->GetDynamicPartitionControl()
783 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700784 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
785 auto download_action =
786 std::make_unique<DownloadAction>(prefs_,
787 boot_control_,
788 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700789 fetcher, // passes ownership
Kelvin Zhang1304fe72021-10-06 19:12:12 -0700790 true /* interactive */,
791 update_certificates_path_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800792 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700793 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700794 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
795 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700796 auto postinstall_runner_action =
797 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000798 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700799 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800800
Alex Deymo5e3ea272016-01-28 13:42:23 -0800801 // Bond them together. We have to use the leaf-types when calling
802 // BondActions().
803 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700804 BondActions(download_action.get(), filesystem_verifier_action.get());
805 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800806 postinstall_runner_action.get());
807
Amin Hassani667cf7b2018-07-25 14:32:00 -0700808 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800809 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700810 processor_->EnqueueAction(std::move(install_plan_action));
811 processor_->EnqueueAction(std::move(download_action));
812 processor_->EnqueueAction(std::move(filesystem_verifier_action));
813 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800814}
815
Alex Deymo5e3ea272016-01-28 13:42:23 -0800816bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400817 LOG(INFO) << "Writing update complete marker.";
Alex Deymo5e3ea272016-01-28 13:42:23 -0800818 string boot_id;
819 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400820 TEST_AND_RETURN_FALSE(
821 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id));
822 TEST_AND_RETURN_FALSE(
823 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot()));
824 return true;
825}
826
827bool UpdateAttempterAndroid::ClearUpdateCompletedMarker() {
828 LOG(INFO) << "Clearing update complete marker.";
829 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsUpdateCompletedOnBootId));
830 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsPreviousSlot));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800831 return true;
832}
833
834bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
835 // In case of an update_engine restart without a reboot, we stored the boot_id
836 // when the update was completed by setting a pref, so we can check whether
837 // the last update was on this boot or a previous one.
838 string boot_id;
839 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
840
841 string update_completed_on_boot_id;
842 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
843 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
844 &update_completed_on_boot_id) &&
845 update_completed_on_boot_id == boot_id);
846}
847
Tianjie Xu90aaa102017-10-10 17:39:03 -0700848// Collect and report the android metrics when we terminate the update.
849void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
850 ErrorCode error_code) {
851 int64_t attempt_number =
852 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
853 PayloadType payload_type = kPayloadTypeFull;
854 int64_t payload_size = 0;
855 for (const auto& p : install_plan_.payloads) {
856 if (p.type == InstallPayloadType::kDelta)
857 payload_type = kPayloadTypeDelta;
858 payload_size += p.size;
859 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700860 // In some cases, e.g. after calling |setShouldSwitchSlotOnReboot()|, this
861 // function will be triggered, but payload_size in this case might be 0, if so
862 // skip reporting any metrics.
863 if (payload_size == 0) {
864 return;
865 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700866
867 metrics::AttemptResult attempt_result =
868 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700869 Time boot_time_start = Time::FromInternalValue(
870 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
871 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700872 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700873 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
874 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700875
876 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700877 static_cast<int>(attempt_number),
878 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700879 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700880 duration_uptime,
881 payload_size,
882 attempt_result,
883 error_code);
884
Tianjie Xud4777a12017-10-24 14:54:18 -0700885 int64_t current_bytes_downloaded =
886 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
887 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
888 current_bytes_downloaded,
889 0,
890 DownloadSource::kNumDownloadSources,
891 metrics::DownloadErrorCode::kUnset,
892 metrics::ConnectionType::kUnset);
893
Tianjie Xu90aaa102017-10-10 17:39:03 -0700894 if (error_code == ErrorCode::kSuccess) {
895 int64_t reboot_count =
896 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
897 string build_version;
898 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700899
900 // For android metrics, we only care about the total bytes downloaded
901 // for all sources; for now we assume the only download source is
902 // HttpsServer.
903 int64_t total_bytes_downloaded =
904 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
905 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
906 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
907 total_bytes_downloaded;
908
909 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700910 if (total_bytes_downloaded >= payload_size) {
911 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700912 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700913 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
914 } else {
915 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
916 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700917 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700918
Tianjie Xu90aaa102017-10-10 17:39:03 -0700919 metrics_reporter_->ReportSuccessfulUpdateMetrics(
920 static_cast<int>(attempt_number),
921 0, // update abandoned count
922 payload_type,
923 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700924 num_bytes_downloaded,
925 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700926 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700927 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700928 static_cast<int>(reboot_count),
929 0); // url_switch_count
930 }
931}
932
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400933bool UpdateAttempterAndroid::OTARebootSucceeded() const {
934 const auto current_slot = boot_control_->GetCurrentSlot();
935 const string current_version =
936 android::base::GetProperty("ro.build.version.incremental", "");
937 int64_t previous_slot = -1;
938 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot));
939 string previous_version;
940 TEST_AND_RETURN_FALSE(
941 prefs_->GetString(kPrefsPreviousVersion, &previous_version));
942 if (previous_slot != current_slot) {
943 LOG(INFO) << "Detected a slot switch, OTA succeeded, device updated from "
944 << previous_version << " to " << current_version;
945 if (previous_version == current_version) {
946 LOG(INFO) << "Previous version is the same as current version, this is "
947 "possibly a self-OTA.";
948 }
949 return true;
950 } else {
951 LOG(INFO) << "Slot didn't switch, either the OTA is rolled back, or slot "
952 "switch never happened, or system not rebooted at all.";
953 if (previous_version != current_version) {
954 LOG(INFO) << "Slot didn't change, but version changed from "
955 << previous_version << " to " << current_version
956 << " device could be flashed.";
957 }
958 return false;
959 }
960}
961
962OTAResult UpdateAttempterAndroid::GetOTAUpdateResult() const {
963 // We only set |kPrefsSystemUpdatedMarker| if slot is actually switched, so
964 // existence of this pref is sufficient indicator. Given that we have to
965 // delete this pref after checking it. This is done in
966 // |DeltaPerformer::ResetUpdateProgress|
967 auto slot_switch_attempted = prefs_->Exists(kPrefsUpdateCompletedOnBootId);
968 auto system_rebooted = DidSystemReboot(prefs_);
969 auto ota_successful = OTARebootSucceeded();
970 if (ota_successful) {
971 return OTAResult::OTA_SUCCESSFUL;
972 }
973 if (slot_switch_attempted) {
974 if (system_rebooted) {
975 // If we attempted slot switch, but still end up on the same slot, we
976 // probably rolled back.
977 return OTAResult::ROLLED_BACK;
978 } else {
979 return OTAResult::UPDATED_NEED_REBOOT;
980 }
981 }
982 return OTAResult::NOT_ATTEMPTED;
983}
984
985void UpdateAttempterAndroid::UpdateStateAfterReboot(const OTAResult result) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700986 // Example: [ro.build.version.incremental]: [4292972]
987 string current_version =
988 android::base::GetProperty("ro.build.version.incremental", "");
989 TEST_AND_RETURN(!current_version.empty());
990
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400991 // |UpdateStateAfterReboot()| is only called after system reboot, so record
992 // boot id unconditionally
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400993 string current_boot_id;
994 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
995 prefs_->SetString(kPrefsBootId, current_boot_id);
996
Tianjie Xu90aaa102017-10-10 17:39:03 -0700997 // If there's no record of previous version (e.g. due to a data wipe), we
998 // save the info of current boot and skip the metrics report.
999 if (!prefs_->Exists(kPrefsPreviousVersion)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001000 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001001 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001002 ClearMetricsPrefs();
1003 return;
1004 }
Kelvin Zhang86603472021-05-11 12:16:27 -04001005 // update_engine restarted under the same build and same slot.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001006 if (result != OTAResult::OTA_SUCCESSFUL) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001007 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
1008 // set when we start a new update.
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001009 if (prefs_->Exists(kPrefsNumReboots)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001010 int64_t reboot_count =
1011 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1012 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
1013 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001014
1015 if (result == OTAResult::ROLLED_BACK) {
1016 // This will release all space previously allocated for apex
1017 // decompression. If we detect a rollback, we should release space and
1018 // return the space to user. Any subsequent attempt to install OTA will
1019 // allocate space again anyway.
1020 LOG(INFO) << "Detected a rollback, releasing space allocated for apex "
1021 "deompression.";
1022 apex_handler_android_->AllocateSpace({});
1023 DeltaPerformer::ResetUpdateProgress(prefs_, false);
1024 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001025 return;
1026 }
1027
1028 // Now that the build version changes, report the update metrics.
1029 // TODO(xunchang) check the build version is larger than the previous one.
Tianjie Xu90aaa102017-10-10 17:39:03 -07001030 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001031 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001032
1033 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
1034 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
1035 if (previous_attempt_exists) {
1036 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
1037 }
1038
1039 metrics_utils::LoadAndReportTimeToReboot(
1040 metrics_reporter_.get(), prefs_, clock_.get());
1041 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -08001042
1043 // Also reset the update progress if the build version has changed.
1044 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1045 LOG(WARNING) << "Unable to reset the update progress.";
1046 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001047}
1048
1049// Save the update start time. Reset the reboot count and attempt number if the
1050// update isn't a resume; otherwise increment the attempt number.
1051void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
1052 if (!is_resume) {
1053 metrics_utils::SetNumReboots(0, prefs_);
1054 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
1055 } else {
1056 int64_t attempt_number =
1057 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1058 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
1059 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001060 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
1061 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001062 ClearUpdateCompletedMarker();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001063}
1064
1065void UpdateAttempterAndroid::ClearMetricsPrefs() {
1066 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -07001067 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001068 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001069 prefs_->Delete(kPrefsSystemUpdatedMarker);
1070 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001071 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001072}
1073
Yifan Hongbd47d622019-12-13 14:59:58 -08001074BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
1075 return boot_control_->GetCurrentSlot();
1076}
1077
1078BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
1079 return GetCurrentSlot() == 0 ? 1 : 0;
1080}
1081
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001082uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
1083 const std::string& metadata_filename,
1084 const vector<string>& key_value_pair_headers,
1085 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -08001086 DeltaArchiveManifest manifest;
1087 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
1088 return 0;
1089 }
1090 std::map<string, string> headers;
1091 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1092 return 0;
1093 }
1094
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001095 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1096 manifest.apex_info().end());
1097 uint64_t apex_size_required = 0;
1098 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001099 auto result = apex_handler_android_->CalculateSize(apex_infos);
1100 if (!result.ok()) {
1101 LogAndSetError(error,
1102 FROM_HERE,
1103 "Failed to calculate size required for compressed APEX");
1104 return 0;
1105 }
1106 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001107 }
1108
Yifan Hong65613032020-01-09 17:52:13 -08001109 string payload_id = GetPayloadId(headers);
1110 uint64_t required_size = 0;
1111 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1112 boot_control_,
1113 GetTargetSlot(),
1114 manifest,
1115 payload_id,
1116 &required_size)) {
1117 if (required_size == 0) {
1118 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
1119 return 0;
1120 } else {
1121 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001122 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001123 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001124 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001125 }
1126 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001127
1128 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001129 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001130 LOG(ERROR) << "Insufficient space for apex decompression: "
1131 << apex_size_required << " bytes";
1132 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001133 }
Yifan Hong65613032020-01-09 17:52:13 -08001134
1135 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001136 return 0;
1137}
1138
Yifan Hong40bb0d02020-02-24 17:33:14 -08001139void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1140 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Yifan Hong2236ea02019-12-13 16:11:22 -08001141 brillo::ErrorPtr* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001142 if (cleanup_previous_update_code_.has_value()) {
1143 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1144 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1145 if (callback) {
1146 callback->OnCleanupComplete(
1147 static_cast<int32_t>(*cleanup_previous_update_code_));
1148 }
1149 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001150 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001151 if (callback) {
1152 auto callback_ptr = callback.get();
1153 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1154 callback_ptr->RegisterForDeathNotifications(
1155 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1156 base::Unretained(this),
1157 base::Unretained(callback_ptr)));
1158 }
1159 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001160}
1161
Tianjie7f8f2ab2021-07-23 17:08:50 -07001162bool UpdateAttempterAndroid::setShouldSwitchSlotOnReboot(
1163 const std::string& metadata_filename, brillo::ErrorPtr* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -07001164 LOG(INFO) << "setShouldSwitchSlotOnReboot(" << metadata_filename << ")";
Tianjie7f8f2ab2021-07-23 17:08:50 -07001165 if (processor_->IsRunning()) {
1166 return LogAndSetError(
1167 error, FROM_HERE, "Already processing an update, cancel it first.");
1168 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001169 DeltaArchiveManifest manifest;
1170 TEST_AND_RETURN_FALSE(
1171 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
1172
1173 if (!boot_control_->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
1174 GetCurrentSlot(),
1175 GetTargetSlot(),
1176 manifest,
1177 false /* should update */,
1178 nullptr)) {
1179 return LogAndSetError(
1180 error, FROM_HERE, "Failed to PreparePartitionsForUpdate");
1181 }
1182 InstallPlan install_plan_;
1183 install_plan_.source_slot = GetCurrentSlot();
1184 install_plan_.target_slot = GetTargetSlot();
1185 // Don't do verity computation, just hash the partitions
1186 install_plan_.write_verity = false;
1187 // Don't run postinstall, we just need PostinstallAction to switch the slots.
1188 install_plan_.run_post_install = false;
1189 install_plan_.is_resume = true;
1190
1191 CHECK_NE(install_plan_.source_slot, UINT32_MAX);
1192 CHECK_NE(install_plan_.target_slot, UINT32_MAX);
1193
Daniel Zhengda4f7292022-09-02 22:59:32 +00001194 ErrorCode error_code{};
Kelvin Zhang20982a52021-08-13 12:31:16 -07001195 if (!install_plan_.ParsePartitions(manifest.partitions(),
1196 boot_control_,
1197 manifest.block_size(),
1198 &error_code)) {
1199 return LogAndSetError(error,
1200 FROM_HERE,
1201 "Failed to LoadPartitionsFromSlots " +
1202 utils::ErrorCodeToString(error_code));
1203 }
1204
1205 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
Kelvin Zhang20982a52021-08-13 12:31:16 -07001206 auto postinstall_runner_action =
1207 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
1208 SetStatusAndNotify(UpdateStatus::VERIFYING);
Kelvin Zhang20982a52021-08-13 12:31:16 -07001209 postinstall_runner_action->set_delegate(this);
1210
Kelvin Zhangf8441982022-12-07 18:18:47 -08001211 // If last error code is kUpdatedButNotActive, we know that we reached this
1212 // state by calling applyPayload() with switch_slot=false. That applyPayload()
1213 // call would have already performed filesystem verification, therefore, we
1214 // can safely skip the verification to save time.
1215 if (last_error_ == ErrorCode::kUpdatedButNotActive) {
1216 BondActions(install_plan_action.get(), postinstall_runner_action.get());
1217 processor_->EnqueueAction(std::move(install_plan_action));
1218 } else {
1219 auto filesystem_verifier_action =
1220 std::make_unique<FilesystemVerifierAction>(
1221 boot_control_->GetDynamicPartitionControl());
1222 filesystem_verifier_action->set_delegate(this);
1223 BondActions(install_plan_action.get(), filesystem_verifier_action.get());
1224 BondActions(filesystem_verifier_action.get(),
1225 postinstall_runner_action.get());
1226 processor_->EnqueueAction(std::move(install_plan_action));
1227 processor_->EnqueueAction(std::move(filesystem_verifier_action));
1228 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001229
Kelvin Zhang20982a52021-08-13 12:31:16 -07001230 processor_->EnqueueAction(std::move(postinstall_runner_action));
1231 ScheduleProcessingStart();
1232 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001233}
1234
1235bool UpdateAttempterAndroid::resetShouldSwitchSlotOnReboot(
1236 brillo::ErrorPtr* error) {
1237 if (processor_->IsRunning()) {
1238 return LogAndSetError(
1239 error, FROM_HERE, "Already processing an update, cancel it first.");
1240 }
Daniel Zhenge76cf562022-11-08 17:32:10 +00001241 TEST_AND_RETURN_FALSE(ClearUpdateCompletedMarker());
Kelvin Zhang20982a52021-08-13 12:31:16 -07001242 // Update the boot flags so the current slot has higher priority.
1243 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot())) {
1244 return LogAndSetError(error, FROM_HERE, "Failed to SetActiveBootSlot");
1245 }
1246
1247 // Mark the current slot as successful again, since marking it as active
1248 // may reset the successful bit. We ignore the result of whether marking
1249 // the current slot as successful worked.
1250 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {}))) {
1251 return LogAndSetError(
1252 error, FROM_HERE, "Failed to MarkBootSuccessfulAsync");
1253 }
1254
1255 // Resets the warm reset property since we won't switch the slot.
1256 hardware_->SetWarmReset(false);
1257
1258 // Resets the vbmeta digest.
1259 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
1260 LOG(INFO) << "Slot switch cancelled.";
1261 SetStatusAndNotify(UpdateStatus::IDLE);
1262 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001263}
1264
Yifan Hong90965502020-02-19 15:22:47 -08001265void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1266 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1267 // is in progress, skip enqueueing the action.
1268 if (processor_->IsRunning()) {
1269 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1270 << "be done when the current update finishes.";
1271 return;
1272 }
1273 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1274 auto action =
1275 boot_control_->GetDynamicPartitionControl()
1276 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1277 processor_->EnqueueAction(std::move(action));
1278 processor_->set_delegate(this);
1279 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1280 processor_->StartProcessing();
1281}
1282
Yifan Hong40bb0d02020-02-24 17:33:14 -08001283void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1284 for (auto&& callback : cleanup_previous_update_callbacks_) {
1285 callback->OnCleanupProgressUpdate(progress);
1286 }
1287}
1288
1289void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1290 CHECK(cleanup_previous_update_code_.has_value());
1291 for (auto&& callback : cleanup_previous_update_callbacks_) {
1292 callback->OnCleanupComplete(
1293 static_cast<int32_t>(*cleanup_previous_update_code_));
1294 }
1295 cleanup_previous_update_callbacks_.clear();
1296}
1297
1298void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1299 CleanupSuccessfulUpdateCallbackInterface* callback) {
1300 auto end_it =
1301 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1302 cleanup_previous_update_callbacks_.end(),
1303 [&](const auto& e) { return e.get() == callback; });
1304 cleanup_previous_update_callbacks_.erase(
1305 end_it, cleanup_previous_update_callbacks_.end());
1306}
Yifan Hong90965502020-02-19 15:22:47 -08001307
Alex Deymo5e3ea272016-01-28 13:42:23 -08001308} // namespace chromeos_update_engine