blob: b95da946b1d73751fb5d3d40bca27cbc4fed6d3a [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>
24
Tianjie Xu90aaa102017-10-10 17:39:03 -070025#include <android-base/properties.h>
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090026#include <android-base/unique_fd.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080027#include <base/bind.h>
28#include <base/logging.h>
Alex Deymo218397f2016-02-04 23:55:10 -080029#include <base/strings/string_number_conversions.h>
Sen Jiang2703ef42017-03-16 13:36:21 -070030#include <brillo/data_encoding.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080031#include <brillo/message_loops/message_loop.h>
Alex Deymo218397f2016-02-04 23:55:10 -080032#include <brillo/strings/string_utils.h>
Sen Jiangacbdd1c2017-10-19 13:30:19 -070033#include <log/log_safetynet.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080034
Amin Hassaniec7bc112020-10-29 16:47:58 -070035#include "update_engine/aosp/cleanup_previous_update_action.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080036#include "update_engine/common/constants.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070037#include "update_engine/common/daemon_state_interface.h"
Kelvin Zhangc7a1d1f2022-07-29 13:36:29 -070038#include "update_engine/common/clock.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070039#include "update_engine/common/download_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080040#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070041#include "update_engine/common/file_fetcher.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070042#include "update_engine/common/metrics_reporter_interface.h"
43#include "update_engine/common/network_selector.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080044#include "update_engine/common/utils.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070045#include "update_engine/metrics_utils.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080046#include "update_engine/payload_consumer/delta_performer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080047#include "update_engine/payload_consumer/file_descriptor.h"
48#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080049#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080050#include "update_engine/payload_consumer/payload_constants.h"
51#include "update_engine/payload_consumer/payload_metadata.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070052#include "update_engine/payload_consumer/payload_verifier.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080053#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070054#include "update_engine/update_boot_flags_action.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080055#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080056
Alex Deymo14c0da82016-07-20 16:45:45 -070057#ifndef _UE_SIDELOAD
58// Do not include support for external HTTP(s) urls when building
59// update_engine_sideload.
60#include "update_engine/libcurl_http_fetcher.h"
61#endif
62
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090063using android::base::unique_fd;
Alex Deymo5e3ea272016-01-28 13:42:23 -080064using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070065using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080066using base::TimeDelta;
67using base::TimeTicks;
Alex Deymo5e3ea272016-01-28 13:42:23 -080068using std::string;
69using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070070using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080071
72namespace chromeos_update_engine {
73
74namespace {
75
Alex Deymo0d298542016-03-30 18:31:49 -070076// Minimum threshold to broadcast an status update in progress and time.
77const double kBroadcastThresholdProgress = 0.01; // 1%
78const int kBroadcastThresholdSeconds = 10;
79
Alex Deymo5e3ea272016-01-28 13:42:23 -080080const char* const kErrorDomain = "update_engine";
81// TODO(deymo): Convert the different errors to a numeric value to report them
82// back on the service error.
83const char* const kGenericError = "generic_error";
84
85// Log and set the error on the passed ErrorPtr.
86bool LogAndSetError(brillo::ErrorPtr* error,
Jakub Pawlowski7e1dcf72018-07-26 00:29:42 -070087 const base::Location& location,
Alex Deymo5e3ea272016-01-28 13:42:23 -080088 const string& reason) {
89 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
90 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
91 << reason;
92 return false;
93}
94
Sen Jiangfe522822017-10-31 15:14:11 -070095bool GetHeaderAsBool(const string& header, bool default_value) {
96 int value = 0;
97 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
98 return value == 1;
99 return default_value;
100}
101
Yifan Hongbd47d622019-12-13 14:59:58 -0800102bool ParseKeyValuePairHeaders(const vector<string>& key_value_pair_headers,
103 std::map<string, string>* headers,
104 brillo::ErrorPtr* error) {
105 for (const string& key_value_pair : key_value_pair_headers) {
106 string key;
107 string value;
108 if (!brillo::string_utils::SplitAtFirst(
109 key_value_pair, "=", &key, &value, false)) {
110 return LogAndSetError(
111 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
112 }
113 if (!headers->emplace(key, value).second)
114 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
115 }
116 return true;
117}
118
119// Unique identifier for the payload. An empty string means that the payload
120// can't be resumed.
121string GetPayloadId(const std::map<string, string>& headers) {
122 return (headers.count(kPayloadPropertyFileHash)
123 ? headers.at(kPayloadPropertyFileHash)
124 : "") +
125 (headers.count(kPayloadPropertyMetadataHash)
126 ? headers.at(kPayloadPropertyMetadataHash)
127 : "");
128}
129
Alex Deymo5e3ea272016-01-28 13:42:23 -0800130} // namespace
131
132UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700133 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800134 PrefsInterface* prefs,
135 BootControlInterface* boot_control,
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000136 HardwareInterface* hardware,
137 std::unique_ptr<ApexHandlerInterface> apex_handler)
Alex Deymo5e3ea272016-01-28 13:42:23 -0800138 : daemon_state_(daemon_state),
139 prefs_(prefs),
140 boot_control_(boot_control),
141 hardware_(hardware),
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000142 apex_handler_android_(std::move(apex_handler)),
Tianjie Xu1b661142017-09-28 14:03:42 -0700143 processor_(new ActionProcessor()),
Tianjie Xud4c5deb2017-10-24 11:17:03 -0700144 clock_(new Clock()) {
Yifan Hongc514f662021-02-04 11:18:43 -0800145 metrics_reporter_ = metrics::CreateMetricsReporter(
Kelvin Zhang9a5e3682021-03-29 12:58:48 -0400146 boot_control_->GetDynamicPartitionControl(), &install_plan_);
Alex Deymo87792ea2016-07-25 15:40:36 -0700147 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800148}
149
150UpdateAttempterAndroid::~UpdateAttempterAndroid() {
151 // Release ourselves as the ActionProcessor's delegate to prevent
152 // re-scheduling the updates due to the processing stopped.
153 processor_->set_delegate(nullptr);
154}
155
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400156[[nodiscard]] static bool DidSystemReboot(PrefsInterface* prefs) {
157 string boot_id;
158 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
159 string old_boot_id;
160 // If no previous boot id found, treat as a reboot and write boot ID.
161 if (!prefs->GetString(kPrefsBootId, &old_boot_id)) {
162 return true;
163 }
164 return old_boot_id != boot_id;
165}
166
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400167std::ostream& operator<<(std::ostream& out, OTAResult result) {
168 switch (result) {
169 case OTAResult::NOT_ATTEMPTED:
170 out << "OTAResult::NOT_ATTEMPTED";
171 break;
172 case OTAResult::ROLLED_BACK:
173 out << "OTAResult::ROLLED_BACK";
174 break;
175 case OTAResult::UPDATED_NEED_REBOOT:
176 out << "OTAResult::UPDATED_NEED_REBOOT";
177 break;
178 case OTAResult::OTA_SUCCESSFUL:
179 out << "OTAResult::OTA_SUCCESSFUL";
180 break;
181 }
182 return out;
183}
184
Alex Deymo5e3ea272016-01-28 13:42:23 -0800185void UpdateAttempterAndroid::Init() {
186 // In case of update_engine restart without a reboot we need to restore the
187 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700188 if (UpdateCompletedOnThisBoot()) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400189 LOG(INFO) << "Updated installed but update_engine is restarted without "
190 "device reboot. Resuming old state.";
Alex Deymo0e061ae2016-02-09 17:49:03 -0800191 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700192 } else {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400193 const auto result = GetOTAUpdateResult();
194 LOG(INFO) << result;
Alex Deymo0e061ae2016-02-09 17:49:03 -0800195 SetStatusAndNotify(UpdateStatus::IDLE);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400196 if (DidSystemReboot(prefs_)) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400197 UpdateStateAfterReboot(result);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400198 }
199
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700200#ifdef _UE_SIDELOAD
201 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
202 << "ApplyPayload will call it later.";
203#else
Yifan Hong90965502020-02-19 15:22:47 -0800204 ScheduleCleanupPreviousUpdate();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700205#endif
Tianjie Xu90aaa102017-10-10 17:39:03 -0700206 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800207}
208
209bool UpdateAttempterAndroid::ApplyPayload(
210 const string& payload_url,
211 int64_t payload_offset,
212 int64_t payload_size,
213 const vector<string>& key_value_pair_headers,
214 brillo::ErrorPtr* error) {
215 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
216 return LogAndSetError(
217 error, FROM_HERE, "An update already applied, waiting for reboot");
218 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700219 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800220 return LogAndSetError(
221 error, FROM_HERE, "Already processing an update, cancel it first.");
222 }
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100223 DCHECK_EQ(status_, UpdateStatus::IDLE);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800224
Alex Deymo218397f2016-02-04 23:55:10 -0800225 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800226 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
227 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800228 }
229
Yifan Hongbd47d622019-12-13 14:59:58 -0800230 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800231
232 // Setup the InstallPlan based on the request.
233 install_plan_ = InstallPlan();
234
235 install_plan_.download_url = payload_url;
236 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800237 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800238 InstallPlan::Payload payload;
239 payload.size = payload_size;
240 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800241 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800242 &payload.size)) {
243 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800244 }
245 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700246 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800247 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700248 LOG(WARNING) << "Unable to decode base64 file hash: "
249 << headers[kPayloadPropertyFileHash];
250 }
Alex Deymo218397f2016-02-04 23:55:10 -0800251 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800252 &payload.metadata_size)) {
253 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800254 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700255 // The |payload.type| is not used anymore since minor_version 3.
256 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800257 install_plan_.payloads.push_back(payload);
258
Alex Deymo5e3ea272016-01-28 13:42:23 -0800259 // The |public_key_rsa| key would override the public key stored on disk.
260 install_plan_.public_key_rsa = "";
261
262 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
263 install_plan_.is_resume = !payload_id.empty() &&
264 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
265 if (!install_plan_.is_resume) {
Kelvin Zhang42c2d552022-07-25 11:04:00 -0700266 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong55c2bfe2020-01-13 17:01:19 -0800267 // No need to reset dynamic_partititon_metadata_updated. If previous calls
268 // to AllocateSpaceForPayload uses the same payload_id, reuse preallocated
269 // space. Otherwise, DeltaPerformer re-allocates space when the payload is
270 // applied.
271 if (!DeltaPerformer::ResetUpdateProgress(
272 prefs_,
273 false /* quick */,
274 true /* skip_dynamic_partititon_metadata_updated */)) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800275 LOG(WARNING) << "Unable to reset the update progress.";
276 }
277 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
278 LOG(WARNING) << "Unable to save the update check response hash.";
279 }
280 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800281 install_plan_.source_slot = GetCurrentSlot();
282 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700283
Alex Deymofb905d92016-06-03 19:26:58 -0700284 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700285 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
286
287 install_plan_.switch_slot_on_reboot =
288 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
289
Tianjie Xu087de9d2019-11-01 17:11:22 -0700290 install_plan_.run_post_install =
291 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800292
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700293 // Skip writing verity if we're resuming and verity has already been written.
294 install_plan_.write_verity = true;
295 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
296 bool verity_written = false;
297 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
298 verity_written) {
299 install_plan_.write_verity = false;
300 }
301 }
302
Alex Deymo87792ea2016-07-25 15:40:36 -0700303 NetworkId network_id = kDefaultNetworkId;
304 if (!headers[kPayloadPropertyNetworkId].empty()) {
305 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
306 &network_id)) {
307 return LogAndSetError(
308 error,
309 FROM_HERE,
310 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
311 }
312 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700313 return LogAndSetError(
314 error,
315 FROM_HERE,
316 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700317 }
318 }
319
Alex Deymo5e3ea272016-01-28 13:42:23 -0800320 LOG(INFO) << "Using this install plan:";
321 install_plan_.Dump();
322
Amin Hassani667cf7b2018-07-25 14:32:00 -0700323 HttpFetcher* fetcher = nullptr;
324 if (FileFetcher::SupportedUrl(payload_url)) {
325 DLOG(INFO) << "Using FileFetcher for file URL.";
326 fetcher = new FileFetcher();
327 } else {
328#ifdef _UE_SIDELOAD
329 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
330#else
Kelvin Zhangc7a1d1f2022-07-29 13:36:29 -0700331 LibcurlHttpFetcher* libcurl_fetcher = new LibcurlHttpFetcher(hardware_);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700332 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
333 fetcher = libcurl_fetcher;
334#endif // _UE_SIDELOAD
335 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800336 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800337 if (!headers[kPayloadPropertyAuthorization].empty())
338 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
339 if (!headers[kPayloadPropertyUserAgent].empty())
340 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
341
Kelvin Zhang98cb8f72022-08-03 12:42:02 -0700342 if (!headers[kPayloadPropertyNetworkProxy].empty()) {
343 LOG(INFO) << "Using proxy url from payload headers: "
344 << headers[kPayloadPropertyNetworkProxy];
345 fetcher->SetProxies({headers[kPayloadPropertyNetworkProxy]});
346 }
347
Amin Hassani667cf7b2018-07-25 14:32:00 -0700348 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800349
Alex Deymo5e3ea272016-01-28 13:42:23 -0800350 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700351
352 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
353 // TODO(xunchang) report the metrics for unresumable updates
354
Amin Hassani667cf7b2018-07-25 14:32:00 -0700355 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800356 return true;
357}
358
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900359bool UpdateAttempterAndroid::ApplyPayload(
360 int fd,
361 int64_t payload_offset,
362 int64_t payload_size,
363 const vector<string>& key_value_pair_headers,
364 brillo::ErrorPtr* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100365 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000366 // already running update will be terminated (existing file descriptor will be
367 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100368 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
369 return LogAndSetError(
370 error, FROM_HERE, "An update already applied, waiting for reboot");
371 }
372 if (processor_->IsRunning()) {
373 return LogAndSetError(
374 error, FROM_HERE, "Already processing an update, cancel it first.");
375 }
376 DCHECK_EQ(status_, UpdateStatus::IDLE);
377
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900378 payload_fd_.reset(dup(fd));
379 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
380
381 return ApplyPayload(
382 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
383}
384
Alex Deymo5e3ea272016-01-28 13:42:23 -0800385bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700386 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800387 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
388 processor_->SuspendProcessing();
389 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800390}
391
392bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700393 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800394 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
395 processor_->ResumeProcessing();
396 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800397}
398
399bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700400 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800401 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800402 processor_->StopProcessing();
403 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800404}
405
Alex Deymo3b678db2016-02-09 11:50:06 -0800406bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
407 LOG(INFO) << "Attempting to reset state from "
408 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700409 if (processor_->IsRunning()) {
410 return LogAndSetError(
411 error, FROM_HERE, "Already processing an update, cancel it first.");
412 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800413
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000414 if (apex_handler_android_ != nullptr) {
415 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
416 std::vector<ApexInfo> apex_infos_blank;
417 apex_handler_android_->AllocateSpace(apex_infos_blank);
418 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400419 // Remove the reboot marker so that if the machine is rebooted
420 // after resetting to idle state, it doesn't go back to
421 // UpdateStatus::UPDATED_NEED_REBOOT state.
422 if (!ClearUpdateCompletedMarker()) {
423 return LogAndSetError(error,
424 FROM_HERE,
425 "Failed to reset the status because "
426 "ClearUpdateCompletedMarker() failed");
427 }
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000428
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700429 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
430 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
431 << "space might not be freed.";
432 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800433 switch (status_) {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700434 case UpdateStatus::IDLE: {
Alex Deymo3b678db2016-02-09 11:50:06 -0800435 return true;
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700436 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800437
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800438 case UpdateStatus::UPDATED_NEED_REBOOT: {
Kelvin Zhang20982a52021-08-13 12:31:16 -0700439 const bool ret_value = resetShouldSwitchSlotOnReboot(error);
440 if (ret_value) {
441 LOG(INFO) << "Reset status successful";
Alex Deymo3b678db2016-02-09 11:50:06 -0800442 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700443 return ret_value;
Alex Deymo3b678db2016-02-09 11:50:06 -0800444 }
445
446 default:
447 return LogAndSetError(
448 error,
449 FROM_HERE,
450 "Reset not allowed in this state. Cancel the ongoing update first");
451 }
452}
453
Yifan Hongbd47d622019-12-13 14:59:58 -0800454bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
455 const std::string& metadata_filename,
456 DeltaArchiveManifest* manifest,
457 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800458 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
459 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
460 return LogAndSetError(
461 error, FROM_HERE, "Failed to open " + metadata_filename);
462 }
463 brillo::Blob metadata(kMaxPayloadHeaderSize);
464 if (!fd->Read(metadata.data(), metadata.size())) {
465 return LogAndSetError(
466 error,
467 FROM_HERE,
468 "Failed to read payload header from " + metadata_filename);
469 }
470 ErrorCode errorcode;
471 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700472 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800473 MetadataParseResult::kSuccess) {
474 return LogAndSetError(error,
475 FROM_HERE,
476 "Failed to parse payload header: " +
477 utils::ErrorCodeToString(errorcode));
478 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700479 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
480 payload_metadata.GetMetadataSignatureSize();
481 if (metadata_size < kMaxPayloadHeaderSize ||
482 metadata_size >
483 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800484 return LogAndSetError(
485 error,
486 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700487 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800488 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700489 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800490 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
491 metadata.size() - kMaxPayloadHeaderSize)) {
492 return LogAndSetError(
493 error,
494 FROM_HERE,
495 "Failed to read metadata and signature from " + metadata_filename);
496 }
497 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800498
Tianjie Xu7a78d632019-10-08 16:32:39 -0700499 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
500 constants::kUpdateCertificatesPath);
501 if (!payload_verifier) {
502 return LogAndSetError(error,
503 FROM_HERE,
504 "Failed to create the payload verifier from " +
505 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800506 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700507 errorcode = payload_metadata.ValidateMetadataSignature(
508 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800509 if (errorcode != ErrorCode::kSuccess) {
510 return LogAndSetError(error,
511 FROM_HERE,
512 "Failed to validate metadata signature: " +
513 utils::ErrorCodeToString(errorcode));
514 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800515 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800516 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
517 }
518
Yifan Hongbd47d622019-12-13 14:59:58 -0800519 return true;
520}
521
522bool UpdateAttempterAndroid::VerifyPayloadApplicable(
523 const std::string& metadata_filename, brillo::ErrorPtr* error) {
524 DeltaArchiveManifest manifest;
525 TEST_AND_RETURN_FALSE(
526 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
527
528 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
529 ErrorCode errorcode;
530
531 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800532 for (const PartitionUpdate& partition : manifest.partitions()) {
533 if (!partition.has_old_partition_info())
534 continue;
535 string partition_path;
536 if (!boot_control_->GetPartitionDevice(
537 partition.partition_name(), current_slot, &partition_path)) {
538 return LogAndSetError(
539 error,
540 FROM_HERE,
541 "Failed to get partition device for " + partition.partition_name());
542 }
543 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
544 return LogAndSetError(
545 error, FROM_HERE, "Failed to open " + partition_path);
546 }
547 for (const InstallOperation& operation : partition.operations()) {
548 if (!operation.has_src_sha256_hash())
549 continue;
550 brillo::Blob source_hash;
551 if (!fd_utils::ReadAndHashExtents(fd,
552 operation.src_extents(),
553 manifest.block_size(),
554 &source_hash)) {
555 return LogAndSetError(
556 error, FROM_HERE, "Failed to hash " + partition_path);
557 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400558 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800559 source_hash, operation, fd, &errorcode)) {
560 return false;
561 }
562 }
563 fd->Close();
564 }
565 return true;
566}
567
Alex Deymo5e3ea272016-01-28 13:42:23 -0800568void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
569 ErrorCode code) {
570 LOG(INFO) << "Processing Done.";
571
Yifan Hong90965502020-02-19 15:22:47 -0800572 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
573 TerminateUpdateAndNotify(code);
574 return;
575 }
576
Alex Deymo5990bf32016-07-19 17:01:41 -0700577 switch (code) {
578 case ErrorCode::kSuccess:
579 // Update succeeded.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400580 if (!WriteUpdateCompletedMarker()) {
581 LOG(ERROR) << "Failed to write update completion marker";
582 }
Alex Deymo5990bf32016-07-19 17:01:41 -0700583 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800584
Alex Deymo5990bf32016-07-19 17:01:41 -0700585 LOG(INFO) << "Update successfully applied, waiting to reboot.";
586 break;
587
588 case ErrorCode::kFilesystemCopierError:
589 case ErrorCode::kNewRootfsVerificationError:
590 case ErrorCode::kNewKernelVerificationError:
591 case ErrorCode::kFilesystemVerifierError:
592 case ErrorCode::kDownloadStateInitializationError:
593 // Reset the ongoing update for these errors so it starts from the
594 // beginning next time.
595 DeltaPerformer::ResetUpdateProgress(prefs_, false);
596 LOG(INFO) << "Resetting update progress.";
597 break;
598
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700599 case ErrorCode::kPayloadTimestampError:
600 // SafetyNet logging, b/36232423
601 android_errorWriteLog(0x534e4554, "36232423");
602 break;
603
Alex Deymo5990bf32016-07-19 17:01:41 -0700604 default:
605 // Ignore all other error codes.
606 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700607 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800608
609 TerminateUpdateAndNotify(code);
610}
611
612void UpdateAttempterAndroid::ProcessingStopped(
613 const ActionProcessor* processor) {
614 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
615}
616
617void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
618 AbstractAction* action,
619 ErrorCode code) {
620 // Reset download progress regardless of whether or not the download
621 // action succeeded.
622 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800623 if (type == CleanupPreviousUpdateAction::StaticType() ||
624 (type == NoOpAction::StaticType() &&
625 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
626 cleanup_previous_update_code_ = code;
627 NotifyCleanupPreviousUpdateCallbacksAndClear();
628 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000629 // download_progress_ is actually used by other actions, such as
630 // filesystem_verify_action. Therefore we always clear it.
631 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700632 if (type == PostinstallRunnerAction::StaticType()) {
633 bool succeeded =
634 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
635 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
636 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800637 if (code != ErrorCode::kSuccess) {
638 // If an action failed, the ActionProcessor will cancel the whole thing.
639 return;
640 }
Yifan Hong83517502020-02-19 15:34:13 -0800641 if (type == UpdateBootFlagsAction::StaticType()) {
642 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
643 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800644 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400645 auto download_action = static_cast<DownloadAction*>(action);
646 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000647 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700648 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000649 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700650 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800651 }
652}
653
654void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
655 uint64_t bytes_received,
656 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700657 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800658 if (total)
659 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700660 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800661 download_progress_ = progress;
662 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700663 } else {
664 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800665 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700666
667 // Update the bytes downloaded in prefs.
668 int64_t current_bytes_downloaded =
669 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
670 int64_t total_bytes_downloaded =
671 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
672 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
673 current_bytes_downloaded + bytes_progressed);
674 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
675 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800676}
677
678bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
679 // TODO(deymo): Notify the DownloadAction that it should cancel the update
680 // download.
681 return false;
682}
683
684void UpdateAttempterAndroid::DownloadComplete() {
685 // Nothing needs to be done when the download completes.
686}
687
Alex Deymo0d298542016-03-30 18:31:49 -0700688void UpdateAttempterAndroid::ProgressUpdate(double progress) {
689 // Self throttle based on progress. Also send notifications if progress is
690 // too slow.
691 if (progress == 1.0 ||
692 progress - download_progress_ >= kBroadcastThresholdProgress ||
693 TimeTicks::Now() - last_notify_time_ >=
694 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
695 download_progress_ = progress;
696 SetStatusAndNotify(status_);
697 }
698}
699
Kelvin Zhang70eef232020-06-12 20:32:40 +0000700void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
701 assert(status_ == UpdateStatus::VERIFYING);
702 ProgressUpdate(progress);
703}
704
Alex Deymo5e3ea272016-01-28 13:42:23 -0800705void UpdateAttempterAndroid::ScheduleProcessingStart() {
706 LOG(INFO) << "Scheduling an action processor start.";
Kelvin Zhang20982a52021-08-13 12:31:16 -0700707 processor_->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800708 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700709 FROM_HERE,
710 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
711 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800712}
713
714void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
715 if (status_ == UpdateStatus::IDLE) {
716 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
717 return;
718 }
719
Yifan Hong90965502020-02-19 15:22:47 -0800720 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400721 ClearUpdateCompletedMarker();
Yifan Hong90965502020-02-19 15:22:47 -0800722 LOG(INFO) << "Terminating cleanup previous update.";
723 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700724 for (auto observer : daemon_state_->service_observers())
725 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800726 return;
727 }
728
Yifan Hong9194ce82019-11-07 11:03:42 -0800729 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700730
Alex Deymo0d298542016-03-30 18:31:49 -0700731 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800732 UpdateStatus new_status =
733 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
734 : UpdateStatus::IDLE);
735 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900736 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800737
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700738 // The network id is only applicable to one download attempt and once it's
739 // done the network id should not be re-used anymore.
740 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
741 LOG(WARNING) << "Unable to unbind network.";
742 }
743
Alex Deymo5e3ea272016-01-28 13:42:23 -0800744 for (auto observer : daemon_state_->service_observers())
745 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700746
Tianjie Xu90aaa102017-10-10 17:39:03 -0700747 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
748 ClearMetricsPrefs();
749 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800750 // We should only reset the PayloadAttemptNumber if the update succeeds, or
751 // we switch to a different payload.
752 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700753 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700754 // Clear the total bytes downloaded if and only if the update succeeds.
755 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700756 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800757}
758
759void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
760 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700761 size_t payload_size =
762 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700763 UpdateEngineStatus status_to_send = {.status = status_,
764 .progress = download_progress_,
765 .new_size_bytes = payload_size};
766
Alex Deymo5e3ea272016-01-28 13:42:23 -0800767 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700768 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800769 }
770 last_notify_time_ = TimeTicks::Now();
771}
772
Amin Hassani667cf7b2018-07-25 14:32:00 -0700773void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800774 CHECK(!processor_->IsRunning());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800775
776 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700777 auto update_boot_flags_action =
778 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800779 auto cleanup_previous_update_action =
780 boot_control_->GetDynamicPartitionControl()
781 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700782 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
783 auto download_action =
784 std::make_unique<DownloadAction>(prefs_,
785 boot_control_,
786 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700787 fetcher, // passes ownership
Kelvin Zhang1304fe72021-10-06 19:12:12 -0700788 true /* interactive */,
789 update_certificates_path_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800790 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700791 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700792 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
793 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700794 auto postinstall_runner_action =
795 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000796 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700797 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800798
Alex Deymo5e3ea272016-01-28 13:42:23 -0800799 // Bond them together. We have to use the leaf-types when calling
800 // BondActions().
801 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700802 BondActions(download_action.get(), filesystem_verifier_action.get());
803 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800804 postinstall_runner_action.get());
805
Amin Hassani667cf7b2018-07-25 14:32:00 -0700806 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800807 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700808 processor_->EnqueueAction(std::move(install_plan_action));
809 processor_->EnqueueAction(std::move(download_action));
810 processor_->EnqueueAction(std::move(filesystem_verifier_action));
811 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800812}
813
Alex Deymo5e3ea272016-01-28 13:42:23 -0800814bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400815 LOG(INFO) << "Writing update complete marker.";
Alex Deymo5e3ea272016-01-28 13:42:23 -0800816 string boot_id;
817 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400818 TEST_AND_RETURN_FALSE(
819 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id));
820 TEST_AND_RETURN_FALSE(
821 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot()));
822 return true;
823}
824
825bool UpdateAttempterAndroid::ClearUpdateCompletedMarker() {
826 LOG(INFO) << "Clearing update complete marker.";
827 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsUpdateCompletedOnBootId));
828 TEST_AND_RETURN_FALSE(prefs_->Delete(kPrefsPreviousSlot));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800829 return true;
830}
831
832bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
833 // In case of an update_engine restart without a reboot, we stored the boot_id
834 // when the update was completed by setting a pref, so we can check whether
835 // the last update was on this boot or a previous one.
836 string boot_id;
837 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
838
839 string update_completed_on_boot_id;
840 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
841 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
842 &update_completed_on_boot_id) &&
843 update_completed_on_boot_id == boot_id);
844}
845
Tianjie Xu90aaa102017-10-10 17:39:03 -0700846// Collect and report the android metrics when we terminate the update.
847void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
848 ErrorCode error_code) {
849 int64_t attempt_number =
850 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
851 PayloadType payload_type = kPayloadTypeFull;
852 int64_t payload_size = 0;
853 for (const auto& p : install_plan_.payloads) {
854 if (p.type == InstallPayloadType::kDelta)
855 payload_type = kPayloadTypeDelta;
856 payload_size += p.size;
857 }
Kelvin Zhang20982a52021-08-13 12:31:16 -0700858 // In some cases, e.g. after calling |setShouldSwitchSlotOnReboot()|, this
859 // function will be triggered, but payload_size in this case might be 0, if so
860 // skip reporting any metrics.
861 if (payload_size == 0) {
862 return;
863 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700864
865 metrics::AttemptResult attempt_result =
866 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700867 Time boot_time_start = Time::FromInternalValue(
868 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
869 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700870 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700871 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
872 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700873
874 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700875 static_cast<int>(attempt_number),
876 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700877 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700878 duration_uptime,
879 payload_size,
880 attempt_result,
881 error_code);
882
Tianjie Xud4777a12017-10-24 14:54:18 -0700883 int64_t current_bytes_downloaded =
884 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
885 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
886 current_bytes_downloaded,
887 0,
888 DownloadSource::kNumDownloadSources,
889 metrics::DownloadErrorCode::kUnset,
890 metrics::ConnectionType::kUnset);
891
Tianjie Xu90aaa102017-10-10 17:39:03 -0700892 if (error_code == ErrorCode::kSuccess) {
893 int64_t reboot_count =
894 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
895 string build_version;
896 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700897
898 // For android metrics, we only care about the total bytes downloaded
899 // for all sources; for now we assume the only download source is
900 // HttpsServer.
901 int64_t total_bytes_downloaded =
902 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
903 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
904 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
905 total_bytes_downloaded;
906
907 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700908 if (total_bytes_downloaded >= payload_size) {
909 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700910 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700911 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
912 } else {
913 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
914 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700915 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700916
Tianjie Xu90aaa102017-10-10 17:39:03 -0700917 metrics_reporter_->ReportSuccessfulUpdateMetrics(
918 static_cast<int>(attempt_number),
919 0, // update abandoned count
920 payload_type,
921 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700922 num_bytes_downloaded,
923 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700924 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700925 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700926 static_cast<int>(reboot_count),
927 0); // url_switch_count
928 }
929}
930
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400931bool UpdateAttempterAndroid::OTARebootSucceeded() const {
932 const auto current_slot = boot_control_->GetCurrentSlot();
933 const string current_version =
934 android::base::GetProperty("ro.build.version.incremental", "");
935 int64_t previous_slot = -1;
936 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot));
937 string previous_version;
938 TEST_AND_RETURN_FALSE(
939 prefs_->GetString(kPrefsPreviousVersion, &previous_version));
940 if (previous_slot != current_slot) {
941 LOG(INFO) << "Detected a slot switch, OTA succeeded, device updated from "
942 << previous_version << " to " << current_version;
943 if (previous_version == current_version) {
944 LOG(INFO) << "Previous version is the same as current version, this is "
945 "possibly a self-OTA.";
946 }
947 return true;
948 } else {
949 LOG(INFO) << "Slot didn't switch, either the OTA is rolled back, or slot "
950 "switch never happened, or system not rebooted at all.";
951 if (previous_version != current_version) {
952 LOG(INFO) << "Slot didn't change, but version changed from "
953 << previous_version << " to " << current_version
954 << " device could be flashed.";
955 }
956 return false;
957 }
958}
959
960OTAResult UpdateAttempterAndroid::GetOTAUpdateResult() const {
961 // We only set |kPrefsSystemUpdatedMarker| if slot is actually switched, so
962 // existence of this pref is sufficient indicator. Given that we have to
963 // delete this pref after checking it. This is done in
964 // |DeltaPerformer::ResetUpdateProgress|
965 auto slot_switch_attempted = prefs_->Exists(kPrefsUpdateCompletedOnBootId);
966 auto system_rebooted = DidSystemReboot(prefs_);
967 auto ota_successful = OTARebootSucceeded();
968 if (ota_successful) {
969 return OTAResult::OTA_SUCCESSFUL;
970 }
971 if (slot_switch_attempted) {
972 if (system_rebooted) {
973 // If we attempted slot switch, but still end up on the same slot, we
974 // probably rolled back.
975 return OTAResult::ROLLED_BACK;
976 } else {
977 return OTAResult::UPDATED_NEED_REBOOT;
978 }
979 }
980 return OTAResult::NOT_ATTEMPTED;
981}
982
983void UpdateAttempterAndroid::UpdateStateAfterReboot(const OTAResult result) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700984 // Example: [ro.build.version.incremental]: [4292972]
985 string current_version =
986 android::base::GetProperty("ro.build.version.incremental", "");
987 TEST_AND_RETURN(!current_version.empty());
988
Kelvin Zhanga43d6e82021-05-26 10:14:42 -0400989 // |UpdateStateAfterReboot()| is only called after system reboot, so record
990 // boot id unconditionally
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400991 string current_boot_id;
992 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
993 prefs_->SetString(kPrefsBootId, current_boot_id);
994
Tianjie Xu90aaa102017-10-10 17:39:03 -0700995 // If there's no record of previous version (e.g. due to a data wipe), we
996 // save the info of current boot and skip the metrics report.
997 if (!prefs_->Exists(kPrefsPreviousVersion)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700998 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400999 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001000 ClearMetricsPrefs();
1001 return;
1002 }
Kelvin Zhang86603472021-05-11 12:16:27 -04001003 // update_engine restarted under the same build and same slot.
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001004 if (result != OTAResult::OTA_SUCCESSFUL) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001005 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
1006 // set when we start a new update.
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001007 if (prefs_->Exists(kPrefsNumReboots)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001008 int64_t reboot_count =
1009 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
1010 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
1011 }
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001012
1013 if (result == OTAResult::ROLLED_BACK) {
1014 // This will release all space previously allocated for apex
1015 // decompression. If we detect a rollback, we should release space and
1016 // return the space to user. Any subsequent attempt to install OTA will
1017 // allocate space again anyway.
1018 LOG(INFO) << "Detected a rollback, releasing space allocated for apex "
1019 "deompression.";
1020 apex_handler_android_->AllocateSpace({});
1021 DeltaPerformer::ResetUpdateProgress(prefs_, false);
1022 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001023 return;
1024 }
1025
1026 // Now that the build version changes, report the update metrics.
1027 // TODO(xunchang) check the build version is larger than the previous one.
Tianjie Xu90aaa102017-10-10 17:39:03 -07001028 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -04001029 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001030
1031 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
1032 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
1033 if (previous_attempt_exists) {
1034 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
1035 }
1036
1037 metrics_utils::LoadAndReportTimeToReboot(
1038 metrics_reporter_.get(), prefs_, clock_.get());
1039 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -08001040
1041 // Also reset the update progress if the build version has changed.
1042 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1043 LOG(WARNING) << "Unable to reset the update progress.";
1044 }
Tianjie Xu90aaa102017-10-10 17:39:03 -07001045}
1046
1047// Save the update start time. Reset the reboot count and attempt number if the
1048// update isn't a resume; otherwise increment the attempt number.
1049void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
1050 if (!is_resume) {
1051 metrics_utils::SetNumReboots(0, prefs_);
1052 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
1053 } else {
1054 int64_t attempt_number =
1055 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
1056 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
1057 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001058 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
1059 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Kelvin Zhanga43d6e82021-05-26 10:14:42 -04001060 ClearUpdateCompletedMarker();
Tianjie Xu90aaa102017-10-10 17:39:03 -07001061}
1062
1063void UpdateAttempterAndroid::ClearMetricsPrefs() {
1064 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -07001065 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001066 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001067 prefs_->Delete(kPrefsSystemUpdatedMarker);
1068 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -07001069 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001070}
1071
Yifan Hongbd47d622019-12-13 14:59:58 -08001072BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
1073 return boot_control_->GetCurrentSlot();
1074}
1075
1076BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
1077 return GetCurrentSlot() == 0 ? 1 : 0;
1078}
1079
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001080uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
1081 const std::string& metadata_filename,
1082 const vector<string>& key_value_pair_headers,
1083 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -08001084 DeltaArchiveManifest manifest;
1085 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
1086 return 0;
1087 }
1088 std::map<string, string> headers;
1089 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1090 return 0;
1091 }
1092
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001093 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1094 manifest.apex_info().end());
1095 uint64_t apex_size_required = 0;
1096 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001097 auto result = apex_handler_android_->CalculateSize(apex_infos);
1098 if (!result.ok()) {
1099 LogAndSetError(error,
1100 FROM_HERE,
1101 "Failed to calculate size required for compressed APEX");
1102 return 0;
1103 }
1104 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001105 }
1106
Yifan Hong65613032020-01-09 17:52:13 -08001107 string payload_id = GetPayloadId(headers);
1108 uint64_t required_size = 0;
1109 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1110 boot_control_,
1111 GetTargetSlot(),
1112 manifest,
1113 payload_id,
1114 &required_size)) {
1115 if (required_size == 0) {
1116 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
1117 return 0;
1118 } else {
1119 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001120 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001121 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001122 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001123 }
1124 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001125
1126 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001127 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001128 LOG(ERROR) << "Insufficient space for apex decompression: "
1129 << apex_size_required << " bytes";
1130 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001131 }
Yifan Hong65613032020-01-09 17:52:13 -08001132
1133 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001134 return 0;
1135}
1136
Yifan Hong40bb0d02020-02-24 17:33:14 -08001137void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1138 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Yifan Hong2236ea02019-12-13 16:11:22 -08001139 brillo::ErrorPtr* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001140 if (cleanup_previous_update_code_.has_value()) {
1141 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1142 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1143 if (callback) {
1144 callback->OnCleanupComplete(
1145 static_cast<int32_t>(*cleanup_previous_update_code_));
1146 }
1147 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001148 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001149 if (callback) {
1150 auto callback_ptr = callback.get();
1151 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1152 callback_ptr->RegisterForDeathNotifications(
1153 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1154 base::Unretained(this),
1155 base::Unretained(callback_ptr)));
1156 }
1157 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001158}
1159
Tianjie7f8f2ab2021-07-23 17:08:50 -07001160bool UpdateAttempterAndroid::setShouldSwitchSlotOnReboot(
1161 const std::string& metadata_filename, brillo::ErrorPtr* error) {
Kelvin Zhang20982a52021-08-13 12:31:16 -07001162 LOG(INFO) << "setShouldSwitchSlotOnReboot(" << metadata_filename << ")";
Tianjie7f8f2ab2021-07-23 17:08:50 -07001163 if (processor_->IsRunning()) {
1164 return LogAndSetError(
1165 error, FROM_HERE, "Already processing an update, cancel it first.");
1166 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001167 DeltaArchiveManifest manifest;
1168 TEST_AND_RETURN_FALSE(
1169 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
1170
1171 if (!boot_control_->GetDynamicPartitionControl()->PreparePartitionsForUpdate(
1172 GetCurrentSlot(),
1173 GetTargetSlot(),
1174 manifest,
1175 false /* should update */,
1176 nullptr)) {
1177 return LogAndSetError(
1178 error, FROM_HERE, "Failed to PreparePartitionsForUpdate");
1179 }
1180 InstallPlan install_plan_;
1181 install_plan_.source_slot = GetCurrentSlot();
1182 install_plan_.target_slot = GetTargetSlot();
1183 // Don't do verity computation, just hash the partitions
1184 install_plan_.write_verity = false;
1185 // Don't run postinstall, we just need PostinstallAction to switch the slots.
1186 install_plan_.run_post_install = false;
1187 install_plan_.is_resume = true;
1188
1189 CHECK_NE(install_plan_.source_slot, UINT32_MAX);
1190 CHECK_NE(install_plan_.target_slot, UINT32_MAX);
1191
1192 ErrorCode error_code;
1193 if (!install_plan_.ParsePartitions(manifest.partitions(),
1194 boot_control_,
1195 manifest.block_size(),
1196 &error_code)) {
1197 return LogAndSetError(error,
1198 FROM_HERE,
1199 "Failed to LoadPartitionsFromSlots " +
1200 utils::ErrorCodeToString(error_code));
1201 }
1202
1203 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
1204 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
1205 boot_control_->GetDynamicPartitionControl());
1206 auto postinstall_runner_action =
1207 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
1208 SetStatusAndNotify(UpdateStatus::VERIFYING);
1209 filesystem_verifier_action->set_delegate(this);
1210 postinstall_runner_action->set_delegate(this);
1211
1212 // Bond them together. We have to use the leaf-types when calling
1213 // BondActions().
1214 BondActions(install_plan_action.get(), filesystem_verifier_action.get());
1215 BondActions(filesystem_verifier_action.get(),
1216 postinstall_runner_action.get());
1217
1218 processor_->EnqueueAction(std::move(install_plan_action));
1219 processor_->EnqueueAction(std::move(filesystem_verifier_action));
1220 processor_->EnqueueAction(std::move(postinstall_runner_action));
1221 ScheduleProcessingStart();
1222 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001223}
1224
1225bool UpdateAttempterAndroid::resetShouldSwitchSlotOnReboot(
1226 brillo::ErrorPtr* error) {
1227 if (processor_->IsRunning()) {
1228 return LogAndSetError(
1229 error, FROM_HERE, "Already processing an update, cancel it first.");
1230 }
Kelvin Zhang20982a52021-08-13 12:31:16 -07001231 // Update the boot flags so the current slot has higher priority.
1232 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot())) {
1233 return LogAndSetError(error, FROM_HERE, "Failed to SetActiveBootSlot");
1234 }
1235
1236 // Mark the current slot as successful again, since marking it as active
1237 // may reset the successful bit. We ignore the result of whether marking
1238 // the current slot as successful worked.
1239 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {}))) {
1240 return LogAndSetError(
1241 error, FROM_HERE, "Failed to MarkBootSuccessfulAsync");
1242 }
1243
1244 // Resets the warm reset property since we won't switch the slot.
1245 hardware_->SetWarmReset(false);
1246
1247 // Resets the vbmeta digest.
1248 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
1249 LOG(INFO) << "Slot switch cancelled.";
1250 SetStatusAndNotify(UpdateStatus::IDLE);
1251 return true;
Tianjie7f8f2ab2021-07-23 17:08:50 -07001252}
1253
Yifan Hong90965502020-02-19 15:22:47 -08001254void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1255 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1256 // is in progress, skip enqueueing the action.
1257 if (processor_->IsRunning()) {
1258 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1259 << "be done when the current update finishes.";
1260 return;
1261 }
1262 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1263 auto action =
1264 boot_control_->GetDynamicPartitionControl()
1265 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1266 processor_->EnqueueAction(std::move(action));
1267 processor_->set_delegate(this);
1268 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1269 processor_->StartProcessing();
1270}
1271
Yifan Hong40bb0d02020-02-24 17:33:14 -08001272void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1273 for (auto&& callback : cleanup_previous_update_callbacks_) {
1274 callback->OnCleanupProgressUpdate(progress);
1275 }
1276}
1277
1278void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1279 CHECK(cleanup_previous_update_code_.has_value());
1280 for (auto&& callback : cleanup_previous_update_callbacks_) {
1281 callback->OnCleanupComplete(
1282 static_cast<int32_t>(*cleanup_previous_update_code_));
1283 }
1284 cleanup_previous_update_callbacks_.clear();
1285}
1286
1287void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1288 CleanupSuccessfulUpdateCallbackInterface* callback) {
1289 auto end_it =
1290 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1291 cleanup_previous_update_callbacks_.end(),
1292 [&](const auto& e) { return e.get() == callback; });
1293 cleanup_previous_update_callbacks_.erase(
1294 end_it, cleanup_previous_update_callbacks_.end());
1295}
Yifan Hong90965502020-02-19 15:22:47 -08001296
Alex Deymo5e3ea272016-01-28 13:42:23 -08001297} // namespace chromeos_update_engine