blob: 96bb67c7a44be113a1189d526751f5b09b5859bf [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;
67using std::shared_ptr;
68using 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,
136 HardwareInterface* hardware)
137 : daemon_state_(daemon_state),
138 prefs_(prefs),
139 boot_control_(boot_control),
140 hardware_(hardware),
Tianjie Xu1b661142017-09-28 14:03:42 -0700141 processor_(new ActionProcessor()),
Tianjie Xud4c5deb2017-10-24 11:17:03 -0700142 clock_(new Clock()) {
143 metrics_reporter_ = metrics::CreateMetricsReporter();
Alex Deymo87792ea2016-07-25 15:40:36 -0700144 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800145}
146
147UpdateAttempterAndroid::~UpdateAttempterAndroid() {
148 // Release ourselves as the ActionProcessor's delegate to prevent
149 // re-scheduling the updates due to the processing stopped.
150 processor_->set_delegate(nullptr);
151}
152
153void UpdateAttempterAndroid::Init() {
154 // In case of update_engine restart without a reboot we need to restore the
155 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700156 if (UpdateCompletedOnThisBoot()) {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800157 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700158 } else {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800159 SetStatusAndNotify(UpdateStatus::IDLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700160 UpdatePrefsAndReportUpdateMetricsOnReboot();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700161#ifdef _UE_SIDELOAD
162 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
163 << "ApplyPayload will call it later.";
164#else
Yifan Hong90965502020-02-19 15:22:47 -0800165 ScheduleCleanupPreviousUpdate();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700166#endif
Tianjie Xu90aaa102017-10-10 17:39:03 -0700167 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800168}
169
170bool UpdateAttempterAndroid::ApplyPayload(
171 const string& payload_url,
172 int64_t payload_offset,
173 int64_t payload_size,
174 const vector<string>& key_value_pair_headers,
175 brillo::ErrorPtr* error) {
176 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
177 return LogAndSetError(
178 error, FROM_HERE, "An update already applied, waiting for reboot");
179 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700180 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800181 return LogAndSetError(
182 error, FROM_HERE, "Already processing an update, cancel it first.");
183 }
184 DCHECK(status_ == UpdateStatus::IDLE);
185
Alex Deymo218397f2016-02-04 23:55:10 -0800186 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800187 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
188 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800189 }
190
Yifan Hongbd47d622019-12-13 14:59:58 -0800191 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800192
193 // Setup the InstallPlan based on the request.
194 install_plan_ = InstallPlan();
195
196 install_plan_.download_url = payload_url;
197 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800198 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800199 InstallPlan::Payload payload;
200 payload.size = payload_size;
201 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800202 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800203 &payload.size)) {
204 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800205 }
206 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700207 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800208 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700209 LOG(WARNING) << "Unable to decode base64 file hash: "
210 << headers[kPayloadPropertyFileHash];
211 }
Alex Deymo218397f2016-02-04 23:55:10 -0800212 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800213 &payload.metadata_size)) {
214 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800215 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700216 // The |payload.type| is not used anymore since minor_version 3.
217 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800218 install_plan_.payloads.push_back(payload);
219
Alex Deymo5e3ea272016-01-28 13:42:23 -0800220 // The |public_key_rsa| key would override the public key stored on disk.
221 install_plan_.public_key_rsa = "";
222
223 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
224 install_plan_.is_resume = !payload_id.empty() &&
225 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
226 if (!install_plan_.is_resume) {
Yifan Hong55c2bfe2020-01-13 17:01:19 -0800227 // No need to reset dynamic_partititon_metadata_updated. If previous calls
228 // to AllocateSpaceForPayload uses the same payload_id, reuse preallocated
229 // space. Otherwise, DeltaPerformer re-allocates space when the payload is
230 // applied.
231 if (!DeltaPerformer::ResetUpdateProgress(
232 prefs_,
233 false /* quick */,
234 true /* skip_dynamic_partititon_metadata_updated */)) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800235 LOG(WARNING) << "Unable to reset the update progress.";
236 }
237 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
238 LOG(WARNING) << "Unable to save the update check response hash.";
239 }
240 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800241 install_plan_.source_slot = GetCurrentSlot();
242 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700243
Alex Deymofb905d92016-06-03 19:26:58 -0700244 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700245 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
246
247 install_plan_.switch_slot_on_reboot =
248 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
249
Tianjie Xu087de9d2019-11-01 17:11:22 -0700250 install_plan_.run_post_install =
251 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800252
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700253 // Skip writing verity if we're resuming and verity has already been written.
254 install_plan_.write_verity = true;
255 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
256 bool verity_written = false;
257 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
258 verity_written) {
259 install_plan_.write_verity = false;
260 }
261 }
262
Alex Deymo87792ea2016-07-25 15:40:36 -0700263 NetworkId network_id = kDefaultNetworkId;
264 if (!headers[kPayloadPropertyNetworkId].empty()) {
265 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
266 &network_id)) {
267 return LogAndSetError(
268 error,
269 FROM_HERE,
270 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
271 }
272 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700273 return LogAndSetError(
274 error,
275 FROM_HERE,
276 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700277 }
278 }
279
Alex Deymo5e3ea272016-01-28 13:42:23 -0800280 LOG(INFO) << "Using this install plan:";
281 install_plan_.Dump();
282
Amin Hassani667cf7b2018-07-25 14:32:00 -0700283 HttpFetcher* fetcher = nullptr;
284 if (FileFetcher::SupportedUrl(payload_url)) {
285 DLOG(INFO) << "Using FileFetcher for file URL.";
286 fetcher = new FileFetcher();
287 } else {
288#ifdef _UE_SIDELOAD
289 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
290#else
291 LibcurlHttpFetcher* libcurl_fetcher =
292 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
293 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
294 fetcher = libcurl_fetcher;
295#endif // _UE_SIDELOAD
296 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800297 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800298 if (!headers[kPayloadPropertyAuthorization].empty())
299 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
300 if (!headers[kPayloadPropertyUserAgent].empty())
301 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
302
Amin Hassani667cf7b2018-07-25 14:32:00 -0700303 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800304
Alex Deymo5e3ea272016-01-28 13:42:23 -0800305 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700306
307 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
308 // TODO(xunchang) report the metrics for unresumable updates
309
Amin Hassani667cf7b2018-07-25 14:32:00 -0700310 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800311 return true;
312}
313
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900314bool UpdateAttempterAndroid::ApplyPayload(
315 int fd,
316 int64_t payload_offset,
317 int64_t payload_size,
318 const vector<string>& key_value_pair_headers,
319 brillo::ErrorPtr* error) {
320 payload_fd_.reset(dup(fd));
321 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
322
323 return ApplyPayload(
324 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
325}
326
Alex Deymo5e3ea272016-01-28 13:42:23 -0800327bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700328 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800329 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
330 processor_->SuspendProcessing();
331 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800332}
333
334bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700335 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800336 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
337 processor_->ResumeProcessing();
338 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800339}
340
341bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700342 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800343 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800344 processor_->StopProcessing();
345 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800346}
347
Alex Deymo3b678db2016-02-09 11:50:06 -0800348bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
349 LOG(INFO) << "Attempting to reset state from "
350 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
351
352 switch (status_) {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700353 case UpdateStatus::IDLE: {
354 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
355 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
356 << "space might not be freed.";
357 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800358 return true;
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700359 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800360
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800361 case UpdateStatus::UPDATED_NEED_REBOOT: {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700362 bool ret_value = true;
Alex Deymo3b678db2016-02-09 11:50:06 -0800363
364 // Update the boot flags so the current slot has higher priority.
Yifan Hongbd47d622019-12-13 14:59:58 -0800365 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot()))
Alex Deymo3b678db2016-02-09 11:50:06 -0800366 ret_value = false;
367
Alex Deymo52590332016-11-29 18:29:13 -0800368 // Mark the current slot as successful again, since marking it as active
369 // may reset the successful bit. We ignore the result of whether marking
370 // the current slot as successful worked.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800371 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {})))
Alex Deymo52590332016-11-29 18:29:13 -0800372 ret_value = false;
373
Tianjie Xud6aa91f2019-11-14 11:55:10 -0800374 // Resets the warm reset property since we won't switch the slot.
375 hardware_->SetWarmReset(false);
376
Tianjie838793d2021-01-14 22:05:13 -0800377 // Resets the vbmeta digest.
378 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
379
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700380 // Remove update progress for DeltaPerformer and remove snapshots.
381 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_))
382 ret_value = false;
383
384 // Remove the reboot marker so that if the machine is rebooted
385 // after resetting to idle state, it doesn't go back to
386 // UpdateStatus::UPDATED_NEED_REBOOT state.
387 if (!prefs_->Delete(kPrefsUpdateCompletedOnBootId))
388 ret_value = false;
389 ClearMetricsPrefs();
390
Alex Deymo3b678db2016-02-09 11:50:06 -0800391 if (!ret_value) {
392 return LogAndSetError(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800393 error, FROM_HERE, "Failed to reset the status to ");
Alex Deymo3b678db2016-02-09 11:50:06 -0800394 }
395
396 SetStatusAndNotify(UpdateStatus::IDLE);
397 LOG(INFO) << "Reset status successful";
398 return true;
399 }
400
401 default:
402 return LogAndSetError(
403 error,
404 FROM_HERE,
405 "Reset not allowed in this state. Cancel the ongoing update first");
406 }
407}
408
Yifan Hongbd47d622019-12-13 14:59:58 -0800409bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
410 const std::string& metadata_filename,
411 DeltaArchiveManifest* manifest,
412 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800413 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
414 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
415 return LogAndSetError(
416 error, FROM_HERE, "Failed to open " + metadata_filename);
417 }
418 brillo::Blob metadata(kMaxPayloadHeaderSize);
419 if (!fd->Read(metadata.data(), metadata.size())) {
420 return LogAndSetError(
421 error,
422 FROM_HERE,
423 "Failed to read payload header from " + metadata_filename);
424 }
425 ErrorCode errorcode;
426 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700427 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800428 MetadataParseResult::kSuccess) {
429 return LogAndSetError(error,
430 FROM_HERE,
431 "Failed to parse payload header: " +
432 utils::ErrorCodeToString(errorcode));
433 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700434 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
435 payload_metadata.GetMetadataSignatureSize();
436 if (metadata_size < kMaxPayloadHeaderSize ||
437 metadata_size >
438 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800439 return LogAndSetError(
440 error,
441 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700442 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800443 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700444 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800445 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
446 metadata.size() - kMaxPayloadHeaderSize)) {
447 return LogAndSetError(
448 error,
449 FROM_HERE,
450 "Failed to read metadata and signature from " + metadata_filename);
451 }
452 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800453
Tianjie Xu7a78d632019-10-08 16:32:39 -0700454 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
455 constants::kUpdateCertificatesPath);
456 if (!payload_verifier) {
457 return LogAndSetError(error,
458 FROM_HERE,
459 "Failed to create the payload verifier from " +
460 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800461 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700462 errorcode = payload_metadata.ValidateMetadataSignature(
463 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800464 if (errorcode != ErrorCode::kSuccess) {
465 return LogAndSetError(error,
466 FROM_HERE,
467 "Failed to validate metadata signature: " +
468 utils::ErrorCodeToString(errorcode));
469 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800470 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800471 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
472 }
473
Yifan Hongbd47d622019-12-13 14:59:58 -0800474 return true;
475}
476
477bool UpdateAttempterAndroid::VerifyPayloadApplicable(
478 const std::string& metadata_filename, brillo::ErrorPtr* error) {
479 DeltaArchiveManifest manifest;
480 TEST_AND_RETURN_FALSE(
481 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
482
483 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
484 ErrorCode errorcode;
485
486 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800487 for (const PartitionUpdate& partition : manifest.partitions()) {
488 if (!partition.has_old_partition_info())
489 continue;
490 string partition_path;
491 if (!boot_control_->GetPartitionDevice(
492 partition.partition_name(), current_slot, &partition_path)) {
493 return LogAndSetError(
494 error,
495 FROM_HERE,
496 "Failed to get partition device for " + partition.partition_name());
497 }
498 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
499 return LogAndSetError(
500 error, FROM_HERE, "Failed to open " + partition_path);
501 }
502 for (const InstallOperation& operation : partition.operations()) {
503 if (!operation.has_src_sha256_hash())
504 continue;
505 brillo::Blob source_hash;
506 if (!fd_utils::ReadAndHashExtents(fd,
507 operation.src_extents(),
508 manifest.block_size(),
509 &source_hash)) {
510 return LogAndSetError(
511 error, FROM_HERE, "Failed to hash " + partition_path);
512 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400513 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800514 source_hash, operation, fd, &errorcode)) {
515 return false;
516 }
517 }
518 fd->Close();
519 }
520 return true;
521}
522
Alex Deymo5e3ea272016-01-28 13:42:23 -0800523void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
524 ErrorCode code) {
525 LOG(INFO) << "Processing Done.";
526
Yifan Hong90965502020-02-19 15:22:47 -0800527 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
528 TerminateUpdateAndNotify(code);
529 return;
530 }
531
Alex Deymo5990bf32016-07-19 17:01:41 -0700532 switch (code) {
533 case ErrorCode::kSuccess:
534 // Update succeeded.
535 WriteUpdateCompletedMarker();
536 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800537
Alex Deymo5990bf32016-07-19 17:01:41 -0700538 LOG(INFO) << "Update successfully applied, waiting to reboot.";
539 break;
540
541 case ErrorCode::kFilesystemCopierError:
542 case ErrorCode::kNewRootfsVerificationError:
543 case ErrorCode::kNewKernelVerificationError:
544 case ErrorCode::kFilesystemVerifierError:
545 case ErrorCode::kDownloadStateInitializationError:
546 // Reset the ongoing update for these errors so it starts from the
547 // beginning next time.
548 DeltaPerformer::ResetUpdateProgress(prefs_, false);
549 LOG(INFO) << "Resetting update progress.";
550 break;
551
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700552 case ErrorCode::kPayloadTimestampError:
553 // SafetyNet logging, b/36232423
554 android_errorWriteLog(0x534e4554, "36232423");
555 break;
556
Alex Deymo5990bf32016-07-19 17:01:41 -0700557 default:
558 // Ignore all other error codes.
559 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700560 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800561
562 TerminateUpdateAndNotify(code);
563}
564
565void UpdateAttempterAndroid::ProcessingStopped(
566 const ActionProcessor* processor) {
567 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
568}
569
570void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
571 AbstractAction* action,
572 ErrorCode code) {
573 // Reset download progress regardless of whether or not the download
574 // action succeeded.
575 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800576 if (type == CleanupPreviousUpdateAction::StaticType() ||
577 (type == NoOpAction::StaticType() &&
578 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
579 cleanup_previous_update_code_ = code;
580 NotifyCleanupPreviousUpdateCallbacksAndClear();
581 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000582 // download_progress_ is actually used by other actions, such as
583 // filesystem_verify_action. Therefore we always clear it.
584 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700585 if (type == PostinstallRunnerAction::StaticType()) {
586 bool succeeded =
587 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
588 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
589 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800590 if (code != ErrorCode::kSuccess) {
591 // If an action failed, the ActionProcessor will cancel the whole thing.
592 return;
593 }
Yifan Hong83517502020-02-19 15:34:13 -0800594 if (type == UpdateBootFlagsAction::StaticType()) {
595 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
596 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800597 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400598 auto download_action = static_cast<DownloadAction*>(action);
599 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000600 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700601 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000602 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700603 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800604 }
605}
606
607void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
608 uint64_t bytes_received,
609 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700610 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800611 if (total)
612 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700613 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800614 download_progress_ = progress;
615 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700616 } else {
617 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800618 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700619
620 // Update the bytes downloaded in prefs.
621 int64_t current_bytes_downloaded =
622 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
623 int64_t total_bytes_downloaded =
624 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
625 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
626 current_bytes_downloaded + bytes_progressed);
627 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
628 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800629}
630
631bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
632 // TODO(deymo): Notify the DownloadAction that it should cancel the update
633 // download.
634 return false;
635}
636
637void UpdateAttempterAndroid::DownloadComplete() {
638 // Nothing needs to be done when the download completes.
639}
640
Alex Deymo0d298542016-03-30 18:31:49 -0700641void UpdateAttempterAndroid::ProgressUpdate(double progress) {
642 // Self throttle based on progress. Also send notifications if progress is
643 // too slow.
644 if (progress == 1.0 ||
645 progress - download_progress_ >= kBroadcastThresholdProgress ||
646 TimeTicks::Now() - last_notify_time_ >=
647 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
648 download_progress_ = progress;
649 SetStatusAndNotify(status_);
650 }
651}
652
Kelvin Zhang70eef232020-06-12 20:32:40 +0000653void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
654 assert(status_ == UpdateStatus::VERIFYING);
655 ProgressUpdate(progress);
656}
657
Alex Deymo5e3ea272016-01-28 13:42:23 -0800658void UpdateAttempterAndroid::ScheduleProcessingStart() {
659 LOG(INFO) << "Scheduling an action processor start.";
660 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700661 FROM_HERE,
662 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
663 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800664}
665
666void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
667 if (status_ == UpdateStatus::IDLE) {
668 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
669 return;
670 }
671
Yifan Hong90965502020-02-19 15:22:47 -0800672 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
673 LOG(INFO) << "Terminating cleanup previous update.";
674 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700675 for (auto observer : daemon_state_->service_observers())
676 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800677 return;
678 }
679
Yifan Hong9194ce82019-11-07 11:03:42 -0800680 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700681
Alex Deymo0d298542016-03-30 18:31:49 -0700682 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800683 UpdateStatus new_status =
684 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
685 : UpdateStatus::IDLE);
686 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900687 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800688
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700689 // The network id is only applicable to one download attempt and once it's
690 // done the network id should not be re-used anymore.
691 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
692 LOG(WARNING) << "Unable to unbind network.";
693 }
694
Alex Deymo5e3ea272016-01-28 13:42:23 -0800695 for (auto observer : daemon_state_->service_observers())
696 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700697
Tianjie Xu90aaa102017-10-10 17:39:03 -0700698 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
699 ClearMetricsPrefs();
700 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800701 // We should only reset the PayloadAttemptNumber if the update succeeds, or
702 // we switch to a different payload.
703 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700704 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700705 // Clear the total bytes downloaded if and only if the update succeeds.
706 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700707 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800708}
709
710void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
711 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700712 size_t payload_size =
713 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700714 UpdateEngineStatus status_to_send = {.status = status_,
715 .progress = download_progress_,
716 .new_size_bytes = payload_size};
717
Alex Deymo5e3ea272016-01-28 13:42:23 -0800718 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700719 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800720 }
721 last_notify_time_ = TimeTicks::Now();
722}
723
Amin Hassani667cf7b2018-07-25 14:32:00 -0700724void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800725 CHECK(!processor_->IsRunning());
726 processor_->set_delegate(this);
727
728 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700729 auto update_boot_flags_action =
730 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800731 auto cleanup_previous_update_action =
732 boot_control_->GetDynamicPartitionControl()
733 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700734 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
735 auto download_action =
736 std::make_unique<DownloadAction>(prefs_,
737 boot_control_,
738 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700739 fetcher, // passes ownership
740 true /* interactive */);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800741 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700742 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700743 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
744 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700745 auto postinstall_runner_action =
746 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000747 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700748 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800749
Alex Deymo5e3ea272016-01-28 13:42:23 -0800750 // Bond them together. We have to use the leaf-types when calling
751 // BondActions().
752 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700753 BondActions(download_action.get(), filesystem_verifier_action.get());
754 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800755 postinstall_runner_action.get());
756
Amin Hassani667cf7b2018-07-25 14:32:00 -0700757 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800758 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700759 processor_->EnqueueAction(std::move(install_plan_action));
760 processor_->EnqueueAction(std::move(download_action));
761 processor_->EnqueueAction(std::move(filesystem_verifier_action));
762 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800763}
764
Alex Deymo5e3ea272016-01-28 13:42:23 -0800765bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
766 string boot_id;
767 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
768 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
769 return true;
770}
771
772bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
773 // In case of an update_engine restart without a reboot, we stored the boot_id
774 // when the update was completed by setting a pref, so we can check whether
775 // the last update was on this boot or a previous one.
776 string boot_id;
777 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
778
779 string update_completed_on_boot_id;
780 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
781 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
782 &update_completed_on_boot_id) &&
783 update_completed_on_boot_id == boot_id);
784}
785
Tianjie Xu90aaa102017-10-10 17:39:03 -0700786// Collect and report the android metrics when we terminate the update.
787void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
788 ErrorCode error_code) {
789 int64_t attempt_number =
790 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
791 PayloadType payload_type = kPayloadTypeFull;
792 int64_t payload_size = 0;
793 for (const auto& p : install_plan_.payloads) {
794 if (p.type == InstallPayloadType::kDelta)
795 payload_type = kPayloadTypeDelta;
796 payload_size += p.size;
797 }
798
799 metrics::AttemptResult attempt_result =
800 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700801 Time boot_time_start = Time::FromInternalValue(
802 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
803 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700804 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700805 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
806 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700807
808 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700809 static_cast<int>(attempt_number),
810 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700811 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700812 duration_uptime,
813 payload_size,
814 attempt_result,
815 error_code);
816
Tianjie Xud4777a12017-10-24 14:54:18 -0700817 int64_t current_bytes_downloaded =
818 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
819 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
820 current_bytes_downloaded,
821 0,
822 DownloadSource::kNumDownloadSources,
823 metrics::DownloadErrorCode::kUnset,
824 metrics::ConnectionType::kUnset);
825
Tianjie Xu90aaa102017-10-10 17:39:03 -0700826 if (error_code == ErrorCode::kSuccess) {
827 int64_t reboot_count =
828 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
829 string build_version;
830 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700831
832 // For android metrics, we only care about the total bytes downloaded
833 // for all sources; for now we assume the only download source is
834 // HttpsServer.
835 int64_t total_bytes_downloaded =
836 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
837 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
838 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
839 total_bytes_downloaded;
840
841 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700842 if (total_bytes_downloaded >= payload_size) {
843 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700844 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700845 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
846 } else {
847 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
848 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700849 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700850
Tianjie Xu90aaa102017-10-10 17:39:03 -0700851 metrics_reporter_->ReportSuccessfulUpdateMetrics(
852 static_cast<int>(attempt_number),
853 0, // update abandoned count
854 payload_type,
855 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700856 num_bytes_downloaded,
857 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700858 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700859 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700860 static_cast<int>(reboot_count),
861 0); // url_switch_count
862 }
863}
864
865void UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
866 string current_boot_id;
867 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
868 // Example: [ro.build.version.incremental]: [4292972]
869 string current_version =
870 android::base::GetProperty("ro.build.version.incremental", "");
871 TEST_AND_RETURN(!current_version.empty());
872
873 // If there's no record of previous version (e.g. due to a data wipe), we
874 // save the info of current boot and skip the metrics report.
875 if (!prefs_->Exists(kPrefsPreviousVersion)) {
876 prefs_->SetString(kPrefsBootId, current_boot_id);
877 prefs_->SetString(kPrefsPreviousVersion, current_version);
878 ClearMetricsPrefs();
879 return;
880 }
881 string previous_version;
882 // update_engine restarted under the same build.
883 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
884 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
885 previous_version == current_version) {
886 string last_boot_id;
887 bool is_reboot = prefs_->Exists(kPrefsBootId) &&
888 (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
889 last_boot_id != current_boot_id);
890 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
891 // set when we start a new update.
892 if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
893 prefs_->SetString(kPrefsBootId, current_boot_id);
894 int64_t reboot_count =
895 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
896 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
897 }
898 return;
899 }
900
901 // Now that the build version changes, report the update metrics.
902 // TODO(xunchang) check the build version is larger than the previous one.
903 prefs_->SetString(kPrefsBootId, current_boot_id);
904 prefs_->SetString(kPrefsPreviousVersion, current_version);
905
906 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
907 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
908 if (previous_attempt_exists) {
909 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
910 }
911
912 metrics_utils::LoadAndReportTimeToReboot(
913 metrics_reporter_.get(), prefs_, clock_.get());
914 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -0800915
916 // Also reset the update progress if the build version has changed.
917 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
918 LOG(WARNING) << "Unable to reset the update progress.";
919 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700920}
921
922// Save the update start time. Reset the reboot count and attempt number if the
923// update isn't a resume; otherwise increment the attempt number.
924void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
925 if (!is_resume) {
926 metrics_utils::SetNumReboots(0, prefs_);
927 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
928 } else {
929 int64_t attempt_number =
930 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
931 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
932 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700933 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
934 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700935}
936
937void UpdateAttempterAndroid::ClearMetricsPrefs() {
938 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700939 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700940 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700941 prefs_->Delete(kPrefsSystemUpdatedMarker);
942 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700943 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700944}
945
Yifan Hongbd47d622019-12-13 14:59:58 -0800946BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
947 return boot_control_->GetCurrentSlot();
948}
949
950BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
951 return GetCurrentSlot() == 0 ? 1 : 0;
952}
953
Yifan Hong6f7e29f2019-12-13 14:41:06 -0800954uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
955 const std::string& metadata_filename,
956 const vector<string>& key_value_pair_headers,
957 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -0800958 DeltaArchiveManifest manifest;
959 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
960 return 0;
961 }
962 std::map<string, string> headers;
963 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
964 return 0;
965 }
966
967 string payload_id = GetPayloadId(headers);
968 uint64_t required_size = 0;
969 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
970 boot_control_,
971 GetTargetSlot(),
972 manifest,
973 payload_id,
974 &required_size)) {
975 if (required_size == 0) {
976 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
977 return 0;
978 } else {
979 LOG(ERROR) << "Insufficient space for payload: " << required_size
980 << " bytes";
981 return required_size;
982 }
983 }
984
985 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -0800986 return 0;
987}
988
Yifan Hong40bb0d02020-02-24 17:33:14 -0800989void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
990 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Yifan Hong2236ea02019-12-13 16:11:22 -0800991 brillo::ErrorPtr* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -0800992 if (cleanup_previous_update_code_.has_value()) {
993 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
994 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
995 if (callback) {
996 callback->OnCleanupComplete(
997 static_cast<int32_t>(*cleanup_previous_update_code_));
998 }
999 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001000 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001001 if (callback) {
1002 auto callback_ptr = callback.get();
1003 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1004 callback_ptr->RegisterForDeathNotifications(
1005 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1006 base::Unretained(this),
1007 base::Unretained(callback_ptr)));
1008 }
1009 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001010}
1011
Yifan Hong90965502020-02-19 15:22:47 -08001012void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1013 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1014 // is in progress, skip enqueueing the action.
1015 if (processor_->IsRunning()) {
1016 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1017 << "be done when the current update finishes.";
1018 return;
1019 }
1020 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1021 auto action =
1022 boot_control_->GetDynamicPartitionControl()
1023 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1024 processor_->EnqueueAction(std::move(action));
1025 processor_->set_delegate(this);
1026 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1027 processor_->StartProcessing();
1028}
1029
Yifan Hong40bb0d02020-02-24 17:33:14 -08001030void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1031 for (auto&& callback : cleanup_previous_update_callbacks_) {
1032 callback->OnCleanupProgressUpdate(progress);
1033 }
1034}
1035
1036void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1037 CHECK(cleanup_previous_update_code_.has_value());
1038 for (auto&& callback : cleanup_previous_update_callbacks_) {
1039 callback->OnCleanupComplete(
1040 static_cast<int32_t>(*cleanup_previous_update_code_));
1041 }
1042 cleanup_previous_update_callbacks_.clear();
1043}
1044
1045void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1046 CleanupSuccessfulUpdateCallbackInterface* callback) {
1047 auto end_it =
1048 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1049 cleanup_previous_update_callbacks_.end(),
1050 [&](const auto& e) { return e.get() == callback; });
1051 cleanup_previous_update_callbacks_.erase(
1052 end_it, cleanup_previous_update_callbacks_.end());
1053}
Yifan Hong90965502020-02-19 15:22:47 -08001054
Alex Deymo5e3ea272016-01-28 13:42:23 -08001055} // namespace chromeos_update_engine