blob: bcae3aa210628002a60998e4379e2212d7794b84 [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>
Alex Deymo5e3ea272016-01-28 13:42:23 -080022#include <utility>
23
Tianjie Xu90aaa102017-10-10 17:39:03 -070024#include <android-base/properties.h>
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090025#include <android-base/unique_fd.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080026#include <base/bind.h>
27#include <base/logging.h>
Alex Deymo218397f2016-02-04 23:55:10 -080028#include <base/strings/string_number_conversions.h>
Sen Jiang2703ef42017-03-16 13:36:21 -070029#include <brillo/data_encoding.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080030#include <brillo/message_loops/message_loop.h>
Alex Deymo218397f2016-02-04 23:55:10 -080031#include <brillo/strings/string_utils.h>
Sen Jiangacbdd1c2017-10-19 13:30:19 -070032#include <log/log_safetynet.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080033
Amin Hassaniec7bc112020-10-29 16:47:58 -070034#include "update_engine/aosp/cleanup_previous_update_action.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080035#include "update_engine/common/constants.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070036#include "update_engine/common/daemon_state_interface.h"
37#include "update_engine/common/download_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080038#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070039#include "update_engine/common/file_fetcher.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070040#include "update_engine/common/metrics_reporter_interface.h"
41#include "update_engine/common/network_selector.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080042#include "update_engine/common/utils.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070043#include "update_engine/metrics_utils.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070044#include "update_engine/payload_consumer/certificate_parser_interface.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080045#include "update_engine/payload_consumer/delta_performer.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080046#include "update_engine/payload_consumer/file_descriptor.h"
47#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080048#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080049#include "update_engine/payload_consumer/payload_constants.h"
50#include "update_engine/payload_consumer/payload_metadata.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070051#include "update_engine/payload_consumer/payload_verifier.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080052#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070053#include "update_engine/update_boot_flags_action.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080054#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080055
Alex Deymo14c0da82016-07-20 16:45:45 -070056#ifndef _UE_SIDELOAD
57// Do not include support for external HTTP(s) urls when building
58// update_engine_sideload.
59#include "update_engine/libcurl_http_fetcher.h"
60#endif
61
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090062using android::base::unique_fd;
Alex Deymo5e3ea272016-01-28 13:42:23 -080063using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070064using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080065using base::TimeDelta;
66using base::TimeTicks;
Alex Deymo5e3ea272016-01-28 13:42:23 -080067using std::string;
68using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070069using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080070
71namespace chromeos_update_engine {
72
73namespace {
74
Alex Deymo0d298542016-03-30 18:31:49 -070075// Minimum threshold to broadcast an status update in progress and time.
76const double kBroadcastThresholdProgress = 0.01; // 1%
77const int kBroadcastThresholdSeconds = 10;
78
Alex Deymo5e3ea272016-01-28 13:42:23 -080079const char* const kErrorDomain = "update_engine";
80// TODO(deymo): Convert the different errors to a numeric value to report them
81// back on the service error.
82const char* const kGenericError = "generic_error";
83
84// Log and set the error on the passed ErrorPtr.
85bool LogAndSetError(brillo::ErrorPtr* error,
Jakub Pawlowski7e1dcf72018-07-26 00:29:42 -070086 const base::Location& location,
Alex Deymo5e3ea272016-01-28 13:42:23 -080087 const string& reason) {
88 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
89 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
90 << reason;
91 return false;
92}
93
Sen Jiangfe522822017-10-31 15:14:11 -070094bool GetHeaderAsBool(const string& header, bool default_value) {
95 int value = 0;
96 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
97 return value == 1;
98 return default_value;
99}
100
Yifan Hongbd47d622019-12-13 14:59:58 -0800101bool ParseKeyValuePairHeaders(const vector<string>& key_value_pair_headers,
102 std::map<string, string>* headers,
103 brillo::ErrorPtr* error) {
104 for (const string& key_value_pair : key_value_pair_headers) {
105 string key;
106 string value;
107 if (!brillo::string_utils::SplitAtFirst(
108 key_value_pair, "=", &key, &value, false)) {
109 return LogAndSetError(
110 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
111 }
112 if (!headers->emplace(key, value).second)
113 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
114 }
115 return true;
116}
117
118// Unique identifier for the payload. An empty string means that the payload
119// can't be resumed.
120string GetPayloadId(const std::map<string, string>& headers) {
121 return (headers.count(kPayloadPropertyFileHash)
122 ? headers.at(kPayloadPropertyFileHash)
123 : "") +
124 (headers.count(kPayloadPropertyMetadataHash)
125 ? headers.at(kPayloadPropertyMetadataHash)
126 : "");
127}
128
Alex Deymo5e3ea272016-01-28 13:42:23 -0800129} // namespace
130
131UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700132 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800133 PrefsInterface* prefs,
134 BootControlInterface* boot_control,
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000135 HardwareInterface* hardware,
136 std::unique_ptr<ApexHandlerInterface> apex_handler)
Alex Deymo5e3ea272016-01-28 13:42:23 -0800137 : daemon_state_(daemon_state),
138 prefs_(prefs),
139 boot_control_(boot_control),
140 hardware_(hardware),
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +0000141 apex_handler_android_(std::move(apex_handler)),
Tianjie Xu1b661142017-09-28 14:03:42 -0700142 processor_(new ActionProcessor()),
Tianjie Xud4c5deb2017-10-24 11:17:03 -0700143 clock_(new Clock()) {
Yifan Hongc514f662021-02-04 11:18:43 -0800144 metrics_reporter_ = metrics::CreateMetricsReporter(
Kelvin Zhang9a5e3682021-03-29 12:58:48 -0400145 boot_control_->GetDynamicPartitionControl(), &install_plan_);
Alex Deymo87792ea2016-07-25 15:40:36 -0700146 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800147}
148
149UpdateAttempterAndroid::~UpdateAttempterAndroid() {
150 // Release ourselves as the ActionProcessor's delegate to prevent
151 // re-scheduling the updates due to the processing stopped.
152 processor_->set_delegate(nullptr);
153}
154
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400155[[nodiscard]] static bool DidSystemReboot(PrefsInterface* prefs) {
156 string boot_id;
157 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
158 string old_boot_id;
159 // If no previous boot id found, treat as a reboot and write boot ID.
160 if (!prefs->GetString(kPrefsBootId, &old_boot_id)) {
161 return true;
162 }
163 return old_boot_id != boot_id;
164}
165
Alex Deymo5e3ea272016-01-28 13:42:23 -0800166void UpdateAttempterAndroid::Init() {
167 // In case of update_engine restart without a reboot we need to restore the
168 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700169 if (UpdateCompletedOnThisBoot()) {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800170 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700171 } else {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800172 SetStatusAndNotify(UpdateStatus::IDLE);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400173 if (DidSystemReboot(prefs_)) {
174 UpdateStateAfterReboot();
175 }
176
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700177#ifdef _UE_SIDELOAD
178 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
179 << "ApplyPayload will call it later.";
180#else
Yifan Hong90965502020-02-19 15:22:47 -0800181 ScheduleCleanupPreviousUpdate();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700182#endif
Tianjie Xu90aaa102017-10-10 17:39:03 -0700183 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800184}
185
186bool UpdateAttempterAndroid::ApplyPayload(
187 const string& payload_url,
188 int64_t payload_offset,
189 int64_t payload_size,
190 const vector<string>& key_value_pair_headers,
191 brillo::ErrorPtr* error) {
192 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
193 return LogAndSetError(
194 error, FROM_HERE, "An update already applied, waiting for reboot");
195 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700196 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800197 return LogAndSetError(
198 error, FROM_HERE, "Already processing an update, cancel it first.");
199 }
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100200 DCHECK_EQ(status_, UpdateStatus::IDLE);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800201
Alex Deymo218397f2016-02-04 23:55:10 -0800202 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800203 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
204 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800205 }
206
Yifan Hongbd47d622019-12-13 14:59:58 -0800207 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800208
209 // Setup the InstallPlan based on the request.
210 install_plan_ = InstallPlan();
211
212 install_plan_.download_url = payload_url;
213 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800214 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800215 InstallPlan::Payload payload;
216 payload.size = payload_size;
217 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800218 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800219 &payload.size)) {
220 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800221 }
222 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700223 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800224 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700225 LOG(WARNING) << "Unable to decode base64 file hash: "
226 << headers[kPayloadPropertyFileHash];
227 }
Alex Deymo218397f2016-02-04 23:55:10 -0800228 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800229 &payload.metadata_size)) {
230 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800231 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700232 // The |payload.type| is not used anymore since minor_version 3.
233 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800234 install_plan_.payloads.push_back(payload);
235
Alex Deymo5e3ea272016-01-28 13:42:23 -0800236 // The |public_key_rsa| key would override the public key stored on disk.
237 install_plan_.public_key_rsa = "";
238
239 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
240 install_plan_.is_resume = !payload_id.empty() &&
241 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
242 if (!install_plan_.is_resume) {
Yifan Hong55c2bfe2020-01-13 17:01:19 -0800243 // No need to reset dynamic_partititon_metadata_updated. If previous calls
244 // to AllocateSpaceForPayload uses the same payload_id, reuse preallocated
245 // space. Otherwise, DeltaPerformer re-allocates space when the payload is
246 // applied.
247 if (!DeltaPerformer::ResetUpdateProgress(
248 prefs_,
249 false /* quick */,
250 true /* skip_dynamic_partititon_metadata_updated */)) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800251 LOG(WARNING) << "Unable to reset the update progress.";
252 }
253 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
254 LOG(WARNING) << "Unable to save the update check response hash.";
255 }
256 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800257 install_plan_.source_slot = GetCurrentSlot();
258 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700259
Alex Deymofb905d92016-06-03 19:26:58 -0700260 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700261 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
262
263 install_plan_.switch_slot_on_reboot =
264 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
265
Tianjie Xu087de9d2019-11-01 17:11:22 -0700266 install_plan_.run_post_install =
267 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800268
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700269 // Skip writing verity if we're resuming and verity has already been written.
270 install_plan_.write_verity = true;
271 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
272 bool verity_written = false;
273 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
274 verity_written) {
275 install_plan_.write_verity = false;
276 }
277 }
278
Alex Deymo87792ea2016-07-25 15:40:36 -0700279 NetworkId network_id = kDefaultNetworkId;
280 if (!headers[kPayloadPropertyNetworkId].empty()) {
281 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
282 &network_id)) {
283 return LogAndSetError(
284 error,
285 FROM_HERE,
286 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
287 }
288 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700289 return LogAndSetError(
290 error,
291 FROM_HERE,
292 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700293 }
294 }
295
Alex Deymo5e3ea272016-01-28 13:42:23 -0800296 LOG(INFO) << "Using this install plan:";
297 install_plan_.Dump();
298
Amin Hassani667cf7b2018-07-25 14:32:00 -0700299 HttpFetcher* fetcher = nullptr;
300 if (FileFetcher::SupportedUrl(payload_url)) {
301 DLOG(INFO) << "Using FileFetcher for file URL.";
302 fetcher = new FileFetcher();
303 } else {
304#ifdef _UE_SIDELOAD
305 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
306#else
307 LibcurlHttpFetcher* libcurl_fetcher =
308 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
309 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
310 fetcher = libcurl_fetcher;
311#endif // _UE_SIDELOAD
312 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800313 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800314 if (!headers[kPayloadPropertyAuthorization].empty())
315 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
316 if (!headers[kPayloadPropertyUserAgent].empty())
317 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
318
Amin Hassani667cf7b2018-07-25 14:32:00 -0700319 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800320
Alex Deymo5e3ea272016-01-28 13:42:23 -0800321 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700322
323 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
324 // TODO(xunchang) report the metrics for unresumable updates
325
Amin Hassani667cf7b2018-07-25 14:32:00 -0700326 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800327 return true;
328}
329
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900330bool UpdateAttempterAndroid::ApplyPayload(
331 int fd,
332 int64_t payload_offset,
333 int64_t payload_size,
334 const vector<string>& key_value_pair_headers,
335 brillo::ErrorPtr* error) {
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100336 // update_engine state must be checked before modifying payload_fd_ otherwise
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +0000337 // already running update will be terminated (existing file descriptor will be
338 // closed)
HÃ¥kan Kvistb00089b2021-01-29 14:09:49 +0100339 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
340 return LogAndSetError(
341 error, FROM_HERE, "An update already applied, waiting for reboot");
342 }
343 if (processor_->IsRunning()) {
344 return LogAndSetError(
345 error, FROM_HERE, "Already processing an update, cancel it first.");
346 }
347 DCHECK_EQ(status_, UpdateStatus::IDLE);
348
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900349 payload_fd_.reset(dup(fd));
350 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
351
352 return ApplyPayload(
353 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
354}
355
Alex Deymo5e3ea272016-01-28 13:42:23 -0800356bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700357 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800358 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
359 processor_->SuspendProcessing();
360 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800361}
362
363bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700364 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800365 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
366 processor_->ResumeProcessing();
367 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800368}
369
370bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700371 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800372 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800373 processor_->StopProcessing();
374 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800375}
376
Alex Deymo3b678db2016-02-09 11:50:06 -0800377bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
378 LOG(INFO) << "Attempting to reset state from "
379 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
380
Mohammad Samiul Islamb5c07bf2021-03-05 10:02:46 +0000381 if (apex_handler_android_ != nullptr) {
382 LOG(INFO) << "Cleaning up reserved space for compressed APEX (if any)";
383 std::vector<ApexInfo> apex_infos_blank;
384 apex_handler_android_->AllocateSpace(apex_infos_blank);
385 }
386
Alex Deymo3b678db2016-02-09 11:50:06 -0800387 switch (status_) {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700388 case UpdateStatus::IDLE: {
389 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
390 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
391 << "space might not be freed.";
392 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800393 return true;
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700394 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800395
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800396 case UpdateStatus::UPDATED_NEED_REBOOT: {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700397 bool ret_value = true;
Alex Deymo3b678db2016-02-09 11:50:06 -0800398
399 // Update the boot flags so the current slot has higher priority.
Yifan Hongbd47d622019-12-13 14:59:58 -0800400 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot()))
Alex Deymo3b678db2016-02-09 11:50:06 -0800401 ret_value = false;
402
Alex Deymo52590332016-11-29 18:29:13 -0800403 // Mark the current slot as successful again, since marking it as active
404 // may reset the successful bit. We ignore the result of whether marking
405 // the current slot as successful worked.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800406 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {})))
Alex Deymo52590332016-11-29 18:29:13 -0800407 ret_value = false;
408
Tianjie Xud6aa91f2019-11-14 11:55:10 -0800409 // Resets the warm reset property since we won't switch the slot.
410 hardware_->SetWarmReset(false);
411
Tianjie838793d2021-01-14 22:05:13 -0800412 // Resets the vbmeta digest.
413 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
414
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700415 // Remove update progress for DeltaPerformer and remove snapshots.
416 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_))
417 ret_value = false;
418
419 // 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 (!prefs_->Delete(kPrefsUpdateCompletedOnBootId))
423 ret_value = false;
424 ClearMetricsPrefs();
425
Alex Deymo3b678db2016-02-09 11:50:06 -0800426 if (!ret_value) {
427 return LogAndSetError(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800428 error, FROM_HERE, "Failed to reset the status to ");
Alex Deymo3b678db2016-02-09 11:50:06 -0800429 }
430
431 SetStatusAndNotify(UpdateStatus::IDLE);
432 LOG(INFO) << "Reset status successful";
433 return true;
434 }
435
436 default:
437 return LogAndSetError(
438 error,
439 FROM_HERE,
440 "Reset not allowed in this state. Cancel the ongoing update first");
441 }
442}
443
Yifan Hongbd47d622019-12-13 14:59:58 -0800444bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
445 const std::string& metadata_filename,
446 DeltaArchiveManifest* manifest,
447 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800448 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
449 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
450 return LogAndSetError(
451 error, FROM_HERE, "Failed to open " + metadata_filename);
452 }
453 brillo::Blob metadata(kMaxPayloadHeaderSize);
454 if (!fd->Read(metadata.data(), metadata.size())) {
455 return LogAndSetError(
456 error,
457 FROM_HERE,
458 "Failed to read payload header from " + metadata_filename);
459 }
460 ErrorCode errorcode;
461 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700462 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800463 MetadataParseResult::kSuccess) {
464 return LogAndSetError(error,
465 FROM_HERE,
466 "Failed to parse payload header: " +
467 utils::ErrorCodeToString(errorcode));
468 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700469 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
470 payload_metadata.GetMetadataSignatureSize();
471 if (metadata_size < kMaxPayloadHeaderSize ||
472 metadata_size >
473 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800474 return LogAndSetError(
475 error,
476 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700477 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800478 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700479 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800480 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
481 metadata.size() - kMaxPayloadHeaderSize)) {
482 return LogAndSetError(
483 error,
484 FROM_HERE,
485 "Failed to read metadata and signature from " + metadata_filename);
486 }
487 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800488
Tianjie Xu7a78d632019-10-08 16:32:39 -0700489 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
490 constants::kUpdateCertificatesPath);
491 if (!payload_verifier) {
492 return LogAndSetError(error,
493 FROM_HERE,
494 "Failed to create the payload verifier from " +
495 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800496 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700497 errorcode = payload_metadata.ValidateMetadataSignature(
498 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800499 if (errorcode != ErrorCode::kSuccess) {
500 return LogAndSetError(error,
501 FROM_HERE,
502 "Failed to validate metadata signature: " +
503 utils::ErrorCodeToString(errorcode));
504 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800505 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800506 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
507 }
508
Yifan Hongbd47d622019-12-13 14:59:58 -0800509 return true;
510}
511
512bool UpdateAttempterAndroid::VerifyPayloadApplicable(
513 const std::string& metadata_filename, brillo::ErrorPtr* error) {
514 DeltaArchiveManifest manifest;
515 TEST_AND_RETURN_FALSE(
516 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
517
518 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
519 ErrorCode errorcode;
520
521 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800522 for (const PartitionUpdate& partition : manifest.partitions()) {
523 if (!partition.has_old_partition_info())
524 continue;
525 string partition_path;
526 if (!boot_control_->GetPartitionDevice(
527 partition.partition_name(), current_slot, &partition_path)) {
528 return LogAndSetError(
529 error,
530 FROM_HERE,
531 "Failed to get partition device for " + partition.partition_name());
532 }
533 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
534 return LogAndSetError(
535 error, FROM_HERE, "Failed to open " + partition_path);
536 }
537 for (const InstallOperation& operation : partition.operations()) {
538 if (!operation.has_src_sha256_hash())
539 continue;
540 brillo::Blob source_hash;
541 if (!fd_utils::ReadAndHashExtents(fd,
542 operation.src_extents(),
543 manifest.block_size(),
544 &source_hash)) {
545 return LogAndSetError(
546 error, FROM_HERE, "Failed to hash " + partition_path);
547 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400548 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800549 source_hash, operation, fd, &errorcode)) {
550 return false;
551 }
552 }
553 fd->Close();
554 }
555 return true;
556}
557
Alex Deymo5e3ea272016-01-28 13:42:23 -0800558void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
559 ErrorCode code) {
560 LOG(INFO) << "Processing Done.";
561
Yifan Hong90965502020-02-19 15:22:47 -0800562 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
563 TerminateUpdateAndNotify(code);
564 return;
565 }
566
Alex Deymo5990bf32016-07-19 17:01:41 -0700567 switch (code) {
568 case ErrorCode::kSuccess:
569 // Update succeeded.
570 WriteUpdateCompletedMarker();
571 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800572
Alex Deymo5990bf32016-07-19 17:01:41 -0700573 LOG(INFO) << "Update successfully applied, waiting to reboot.";
574 break;
575
576 case ErrorCode::kFilesystemCopierError:
577 case ErrorCode::kNewRootfsVerificationError:
578 case ErrorCode::kNewKernelVerificationError:
579 case ErrorCode::kFilesystemVerifierError:
580 case ErrorCode::kDownloadStateInitializationError:
581 // Reset the ongoing update for these errors so it starts from the
582 // beginning next time.
583 DeltaPerformer::ResetUpdateProgress(prefs_, false);
584 LOG(INFO) << "Resetting update progress.";
585 break;
586
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700587 case ErrorCode::kPayloadTimestampError:
588 // SafetyNet logging, b/36232423
589 android_errorWriteLog(0x534e4554, "36232423");
590 break;
591
Alex Deymo5990bf32016-07-19 17:01:41 -0700592 default:
593 // Ignore all other error codes.
594 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700595 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800596
597 TerminateUpdateAndNotify(code);
598}
599
600void UpdateAttempterAndroid::ProcessingStopped(
601 const ActionProcessor* processor) {
602 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
603}
604
605void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
606 AbstractAction* action,
607 ErrorCode code) {
608 // Reset download progress regardless of whether or not the download
609 // action succeeded.
610 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800611 if (type == CleanupPreviousUpdateAction::StaticType() ||
612 (type == NoOpAction::StaticType() &&
613 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
614 cleanup_previous_update_code_ = code;
615 NotifyCleanupPreviousUpdateCallbacksAndClear();
616 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000617 // download_progress_ is actually used by other actions, such as
618 // filesystem_verify_action. Therefore we always clear it.
619 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700620 if (type == PostinstallRunnerAction::StaticType()) {
621 bool succeeded =
622 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
623 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
624 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800625 if (code != ErrorCode::kSuccess) {
626 // If an action failed, the ActionProcessor will cancel the whole thing.
627 return;
628 }
Yifan Hong83517502020-02-19 15:34:13 -0800629 if (type == UpdateBootFlagsAction::StaticType()) {
630 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
631 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800632 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400633 auto download_action = static_cast<DownloadAction*>(action);
634 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000635 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700636 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000637 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700638 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800639 }
640}
641
642void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
643 uint64_t bytes_received,
644 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700645 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800646 if (total)
647 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700648 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800649 download_progress_ = progress;
650 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700651 } else {
652 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800653 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700654
655 // Update the bytes downloaded in prefs.
656 int64_t current_bytes_downloaded =
657 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
658 int64_t total_bytes_downloaded =
659 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
660 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
661 current_bytes_downloaded + bytes_progressed);
662 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
663 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800664}
665
666bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
667 // TODO(deymo): Notify the DownloadAction that it should cancel the update
668 // download.
669 return false;
670}
671
672void UpdateAttempterAndroid::DownloadComplete() {
673 // Nothing needs to be done when the download completes.
674}
675
Alex Deymo0d298542016-03-30 18:31:49 -0700676void UpdateAttempterAndroid::ProgressUpdate(double progress) {
677 // Self throttle based on progress. Also send notifications if progress is
678 // too slow.
679 if (progress == 1.0 ||
680 progress - download_progress_ >= kBroadcastThresholdProgress ||
681 TimeTicks::Now() - last_notify_time_ >=
682 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
683 download_progress_ = progress;
684 SetStatusAndNotify(status_);
685 }
686}
687
Kelvin Zhang70eef232020-06-12 20:32:40 +0000688void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
689 assert(status_ == UpdateStatus::VERIFYING);
690 ProgressUpdate(progress);
691}
692
Alex Deymo5e3ea272016-01-28 13:42:23 -0800693void UpdateAttempterAndroid::ScheduleProcessingStart() {
694 LOG(INFO) << "Scheduling an action processor start.";
695 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700696 FROM_HERE,
697 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
698 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800699}
700
701void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
702 if (status_ == UpdateStatus::IDLE) {
703 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
704 return;
705 }
706
Yifan Hong90965502020-02-19 15:22:47 -0800707 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
708 LOG(INFO) << "Terminating cleanup previous update.";
709 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700710 for (auto observer : daemon_state_->service_observers())
711 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800712 return;
713 }
714
Yifan Hong9194ce82019-11-07 11:03:42 -0800715 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700716
Alex Deymo0d298542016-03-30 18:31:49 -0700717 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800718 UpdateStatus new_status =
719 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
720 : UpdateStatus::IDLE);
721 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900722 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800723
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700724 // The network id is only applicable to one download attempt and once it's
725 // done the network id should not be re-used anymore.
726 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
727 LOG(WARNING) << "Unable to unbind network.";
728 }
729
Alex Deymo5e3ea272016-01-28 13:42:23 -0800730 for (auto observer : daemon_state_->service_observers())
731 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700732
Tianjie Xu90aaa102017-10-10 17:39:03 -0700733 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
734 ClearMetricsPrefs();
735 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800736 // We should only reset the PayloadAttemptNumber if the update succeeds, or
737 // we switch to a different payload.
738 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700739 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700740 // Clear the total bytes downloaded if and only if the update succeeds.
741 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700742 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800743}
744
745void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
746 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700747 size_t payload_size =
748 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700749 UpdateEngineStatus status_to_send = {.status = status_,
750 .progress = download_progress_,
751 .new_size_bytes = payload_size};
752
Alex Deymo5e3ea272016-01-28 13:42:23 -0800753 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700754 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800755 }
756 last_notify_time_ = TimeTicks::Now();
757}
758
Amin Hassani667cf7b2018-07-25 14:32:00 -0700759void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800760 CHECK(!processor_->IsRunning());
761 processor_->set_delegate(this);
762
763 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700764 auto update_boot_flags_action =
765 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800766 auto cleanup_previous_update_action =
767 boot_control_->GetDynamicPartitionControl()
768 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700769 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
770 auto download_action =
771 std::make_unique<DownloadAction>(prefs_,
772 boot_control_,
773 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700774 fetcher, // passes ownership
775 true /* interactive */);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800776 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700777 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700778 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
779 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700780 auto postinstall_runner_action =
781 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000782 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700783 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800784
Alex Deymo5e3ea272016-01-28 13:42:23 -0800785 // Bond them together. We have to use the leaf-types when calling
786 // BondActions().
787 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700788 BondActions(download_action.get(), filesystem_verifier_action.get());
789 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800790 postinstall_runner_action.get());
791
Amin Hassani667cf7b2018-07-25 14:32:00 -0700792 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800793 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700794 processor_->EnqueueAction(std::move(install_plan_action));
795 processor_->EnqueueAction(std::move(download_action));
796 processor_->EnqueueAction(std::move(filesystem_verifier_action));
797 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800798}
799
Alex Deymo5e3ea272016-01-28 13:42:23 -0800800bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
801 string boot_id;
802 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
803 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
804 return true;
805}
806
807bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
808 // In case of an update_engine restart without a reboot, we stored the boot_id
809 // when the update was completed by setting a pref, so we can check whether
810 // the last update was on this boot or a previous one.
811 string boot_id;
812 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
813
814 string update_completed_on_boot_id;
815 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
816 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
817 &update_completed_on_boot_id) &&
818 update_completed_on_boot_id == boot_id);
819}
820
Tianjie Xu90aaa102017-10-10 17:39:03 -0700821// Collect and report the android metrics when we terminate the update.
822void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
823 ErrorCode error_code) {
824 int64_t attempt_number =
825 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
826 PayloadType payload_type = kPayloadTypeFull;
827 int64_t payload_size = 0;
828 for (const auto& p : install_plan_.payloads) {
829 if (p.type == InstallPayloadType::kDelta)
830 payload_type = kPayloadTypeDelta;
831 payload_size += p.size;
832 }
833
834 metrics::AttemptResult attempt_result =
835 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700836 Time boot_time_start = Time::FromInternalValue(
837 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
838 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700839 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700840 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
841 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700842
843 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700844 static_cast<int>(attempt_number),
845 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700846 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700847 duration_uptime,
848 payload_size,
849 attempt_result,
850 error_code);
851
Tianjie Xud4777a12017-10-24 14:54:18 -0700852 int64_t current_bytes_downloaded =
853 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
854 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
855 current_bytes_downloaded,
856 0,
857 DownloadSource::kNumDownloadSources,
858 metrics::DownloadErrorCode::kUnset,
859 metrics::ConnectionType::kUnset);
860
Tianjie Xu90aaa102017-10-10 17:39:03 -0700861 if (error_code == ErrorCode::kSuccess) {
862 int64_t reboot_count =
863 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
864 string build_version;
865 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700866
867 // For android metrics, we only care about the total bytes downloaded
868 // for all sources; for now we assume the only download source is
869 // HttpsServer.
870 int64_t total_bytes_downloaded =
871 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
872 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
873 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
874 total_bytes_downloaded;
875
876 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700877 if (total_bytes_downloaded >= payload_size) {
878 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700879 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700880 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
881 } else {
882 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
883 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700884 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700885
Tianjie Xu90aaa102017-10-10 17:39:03 -0700886 metrics_reporter_->ReportSuccessfulUpdateMetrics(
887 static_cast<int>(attempt_number),
888 0, // update abandoned count
889 payload_type,
890 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700891 num_bytes_downloaded,
892 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700893 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700894 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700895 static_cast<int>(reboot_count),
896 0); // url_switch_count
897 }
898}
899
Kelvin Zhang4061c512021-05-25 13:42:55 -0400900void UpdateAttempterAndroid::UpdateStateAfterReboot() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700901 // Example: [ro.build.version.incremental]: [4292972]
902 string current_version =
903 android::base::GetProperty("ro.build.version.incremental", "");
904 TEST_AND_RETURN(!current_version.empty());
Kelvin Zhang86603472021-05-11 12:16:27 -0400905 const auto current_slot = boot_control_->GetCurrentSlot();
Tianjie Xu90aaa102017-10-10 17:39:03 -0700906
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400907 // |InitAfterReboot()| is only called after system reboot, so record boot id
908 // unconditionally
909 string current_boot_id;
910 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
911 prefs_->SetString(kPrefsBootId, current_boot_id);
912
Tianjie Xu90aaa102017-10-10 17:39:03 -0700913 // If there's no record of previous version (e.g. due to a data wipe), we
914 // save the info of current boot and skip the metrics report.
915 if (!prefs_->Exists(kPrefsPreviousVersion)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700916 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400917 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -0700918 ClearMetricsPrefs();
919 return;
920 }
Kelvin Zhang86603472021-05-11 12:16:27 -0400921 int64_t previous_slot = -1;
922 prefs_->GetInt64(kPrefsPreviousSlot, &previous_slot);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700923 string previous_version;
Kelvin Zhang86603472021-05-11 12:16:27 -0400924 // update_engine restarted under the same build and same slot.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700925 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
926 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
Kelvin Zhang86603472021-05-11 12:16:27 -0400927 previous_version == current_version && previous_slot == current_slot) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700928 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
929 // set when we start a new update.
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400930 if (prefs_->Exists(kPrefsNumReboots)) {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700931 int64_t reboot_count =
932 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
933 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
934 }
935 return;
936 }
937
938 // Now that the build version changes, report the update metrics.
939 // TODO(xunchang) check the build version is larger than the previous one.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700940 prefs_->SetString(kPrefsPreviousVersion, current_version);
Kelvin Zhangd6fd6822021-05-26 09:50:56 -0400941 prefs_->SetInt64(kPrefsPreviousSlot, boot_control_->GetCurrentSlot());
Tianjie Xu90aaa102017-10-10 17:39:03 -0700942
943 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
944 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
945 if (previous_attempt_exists) {
946 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
947 }
948
949 metrics_utils::LoadAndReportTimeToReboot(
950 metrics_reporter_.get(), prefs_, clock_.get());
951 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -0800952
953 // Also reset the update progress if the build version has changed.
954 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
955 LOG(WARNING) << "Unable to reset the update progress.";
956 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700957}
958
959// Save the update start time. Reset the reboot count and attempt number if the
960// update isn't a resume; otherwise increment the attempt number.
961void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
962 if (!is_resume) {
963 metrics_utils::SetNumReboots(0, prefs_);
964 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
965 } else {
966 int64_t attempt_number =
967 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
968 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
969 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700970 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
971 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700972}
973
974void UpdateAttempterAndroid::ClearMetricsPrefs() {
975 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700976 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700977 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700978 prefs_->Delete(kPrefsSystemUpdatedMarker);
979 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700980 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700981}
982
Yifan Hongbd47d622019-12-13 14:59:58 -0800983BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
984 return boot_control_->GetCurrentSlot();
985}
986
987BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
988 return GetCurrentSlot() == 0 ? 1 : 0;
989}
990
Yifan Hong6f7e29f2019-12-13 14:41:06 -0800991uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
992 const std::string& metadata_filename,
993 const vector<string>& key_value_pair_headers,
994 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -0800995 DeltaArchiveManifest manifest;
996 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
997 return 0;
998 }
999 std::map<string, string> headers;
1000 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
1001 return 0;
1002 }
1003
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001004 std::vector<ApexInfo> apex_infos(manifest.apex_info().begin(),
1005 manifest.apex_info().end());
1006 uint64_t apex_size_required = 0;
1007 if (apex_handler_android_ != nullptr) {
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001008 auto result = apex_handler_android_->CalculateSize(apex_infos);
1009 if (!result.ok()) {
1010 LogAndSetError(error,
1011 FROM_HERE,
1012 "Failed to calculate size required for compressed APEX");
1013 return 0;
1014 }
1015 apex_size_required = *result;
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001016 }
1017
Yifan Hong65613032020-01-09 17:52:13 -08001018 string payload_id = GetPayloadId(headers);
1019 uint64_t required_size = 0;
1020 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
1021 boot_control_,
1022 GetTargetSlot(),
1023 manifest,
1024 payload_id,
1025 &required_size)) {
1026 if (required_size == 0) {
1027 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
1028 return 0;
1029 } else {
1030 LOG(ERROR) << "Insufficient space for payload: " << required_size
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001031 << " bytes, apex decompression: " << apex_size_required
Yifan Hong65613032020-01-09 17:52:13 -08001032 << " bytes";
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001033 return required_size + apex_size_required;
Yifan Hong65613032020-01-09 17:52:13 -08001034 }
1035 }
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001036
1037 if (apex_size_required > 0 && apex_handler_android_ != nullptr &&
Mohammad Samiul Islamb0ab8652021-02-26 14:04:17 +00001038 !apex_handler_android_->AllocateSpace(apex_infos)) {
Mohammad Samiul Islam24a82792021-02-12 16:52:36 +00001039 LOG(ERROR) << "Insufficient space for apex decompression: "
1040 << apex_size_required << " bytes";
1041 return apex_size_required;
Kelvin Zhang8933d572021-01-28 10:17:34 -05001042 }
Yifan Hong65613032020-01-09 17:52:13 -08001043
1044 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -08001045 return 0;
1046}
1047
Yifan Hong40bb0d02020-02-24 17:33:14 -08001048void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
1049 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Yifan Hong2236ea02019-12-13 16:11:22 -08001050 brillo::ErrorPtr* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -08001051 if (cleanup_previous_update_code_.has_value()) {
1052 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
1053 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
1054 if (callback) {
1055 callback->OnCleanupComplete(
1056 static_cast<int32_t>(*cleanup_previous_update_code_));
1057 }
1058 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001059 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001060 if (callback) {
1061 auto callback_ptr = callback.get();
1062 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1063 callback_ptr->RegisterForDeathNotifications(
1064 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1065 base::Unretained(this),
1066 base::Unretained(callback_ptr)));
1067 }
1068 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001069}
1070
Yifan Hong90965502020-02-19 15:22:47 -08001071void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1072 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1073 // is in progress, skip enqueueing the action.
1074 if (processor_->IsRunning()) {
1075 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1076 << "be done when the current update finishes.";
1077 return;
1078 }
1079 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1080 auto action =
1081 boot_control_->GetDynamicPartitionControl()
1082 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1083 processor_->EnqueueAction(std::move(action));
1084 processor_->set_delegate(this);
1085 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1086 processor_->StartProcessing();
1087}
1088
Yifan Hong40bb0d02020-02-24 17:33:14 -08001089void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1090 for (auto&& callback : cleanup_previous_update_callbacks_) {
1091 callback->OnCleanupProgressUpdate(progress);
1092 }
1093}
1094
1095void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1096 CHECK(cleanup_previous_update_code_.has_value());
1097 for (auto&& callback : cleanup_previous_update_callbacks_) {
1098 callback->OnCleanupComplete(
1099 static_cast<int32_t>(*cleanup_previous_update_code_));
1100 }
1101 cleanup_previous_update_callbacks_.clear();
1102}
1103
1104void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1105 CleanupSuccessfulUpdateCallbackInterface* callback) {
1106 auto end_it =
1107 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1108 cleanup_previous_update_callbacks_.end(),
1109 [&](const auto& e) { return e.get() == callback; });
1110 cleanup_previous_update_callbacks_.erase(
1111 end_it, cleanup_previous_update_callbacks_.end());
1112}
Yifan Hong90965502020-02-19 15:22:47 -08001113
Alex Deymo5e3ea272016-01-28 13:42:23 -08001114} // namespace chromeos_update_engine