blob: 5c6614137a7ba2611933f1abe75a7fcc4ad9d9fa [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()) {
Yifan Hongc514f662021-02-04 11:18:43 -0800143 metrics_reporter_ = metrics::CreateMetricsReporter(
144 boot_control_->GetDynamicPartitionControl());
Alex Deymo87792ea2016-07-25 15:40:36 -0700145 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800146}
147
148UpdateAttempterAndroid::~UpdateAttempterAndroid() {
149 // Release ourselves as the ActionProcessor's delegate to prevent
150 // re-scheduling the updates due to the processing stopped.
151 processor_->set_delegate(nullptr);
152}
153
154void UpdateAttempterAndroid::Init() {
155 // In case of update_engine restart without a reboot we need to restore the
156 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700157 if (UpdateCompletedOnThisBoot()) {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800158 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700159 } else {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800160 SetStatusAndNotify(UpdateStatus::IDLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700161 UpdatePrefsAndReportUpdateMetricsOnReboot();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700162#ifdef _UE_SIDELOAD
163 LOG(INFO) << "Skip ScheduleCleanupPreviousUpdate in sideload because "
164 << "ApplyPayload will call it later.";
165#else
Yifan Hong90965502020-02-19 15:22:47 -0800166 ScheduleCleanupPreviousUpdate();
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700167#endif
Tianjie Xu90aaa102017-10-10 17:39:03 -0700168 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800169}
170
171bool UpdateAttempterAndroid::ApplyPayload(
172 const string& payload_url,
173 int64_t payload_offset,
174 int64_t payload_size,
175 const vector<string>& key_value_pair_headers,
176 brillo::ErrorPtr* error) {
177 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
178 return LogAndSetError(
179 error, FROM_HERE, "An update already applied, waiting for reboot");
180 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700181 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800182 return LogAndSetError(
183 error, FROM_HERE, "Already processing an update, cancel it first.");
184 }
185 DCHECK(status_ == UpdateStatus::IDLE);
186
Alex Deymo218397f2016-02-04 23:55:10 -0800187 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800188 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
189 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800190 }
191
Yifan Hongbd47d622019-12-13 14:59:58 -0800192 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800193
194 // Setup the InstallPlan based on the request.
195 install_plan_ = InstallPlan();
196
197 install_plan_.download_url = payload_url;
198 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800199 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800200 InstallPlan::Payload payload;
201 payload.size = payload_size;
202 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800203 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800204 &payload.size)) {
205 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800206 }
207 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700208 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800209 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700210 LOG(WARNING) << "Unable to decode base64 file hash: "
211 << headers[kPayloadPropertyFileHash];
212 }
Alex Deymo218397f2016-02-04 23:55:10 -0800213 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800214 &payload.metadata_size)) {
215 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800216 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700217 // The |payload.type| is not used anymore since minor_version 3.
218 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800219 install_plan_.payloads.push_back(payload);
220
Alex Deymo5e3ea272016-01-28 13:42:23 -0800221 // The |public_key_rsa| key would override the public key stored on disk.
222 install_plan_.public_key_rsa = "";
223
224 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
225 install_plan_.is_resume = !payload_id.empty() &&
226 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
227 if (!install_plan_.is_resume) {
Yifan Hong55c2bfe2020-01-13 17:01:19 -0800228 // No need to reset dynamic_partititon_metadata_updated. If previous calls
229 // to AllocateSpaceForPayload uses the same payload_id, reuse preallocated
230 // space. Otherwise, DeltaPerformer re-allocates space when the payload is
231 // applied.
232 if (!DeltaPerformer::ResetUpdateProgress(
233 prefs_,
234 false /* quick */,
235 true /* skip_dynamic_partititon_metadata_updated */)) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800236 LOG(WARNING) << "Unable to reset the update progress.";
237 }
238 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
239 LOG(WARNING) << "Unable to save the update check response hash.";
240 }
241 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800242 install_plan_.source_slot = GetCurrentSlot();
243 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700244
Alex Deymofb905d92016-06-03 19:26:58 -0700245 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700246 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
247
248 install_plan_.switch_slot_on_reboot =
249 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
250
Tianjie Xu087de9d2019-11-01 17:11:22 -0700251 install_plan_.run_post_install =
252 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800253
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700254 // Skip writing verity if we're resuming and verity has already been written.
255 install_plan_.write_verity = true;
256 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
257 bool verity_written = false;
258 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
259 verity_written) {
260 install_plan_.write_verity = false;
261 }
262 }
263
Alex Deymo87792ea2016-07-25 15:40:36 -0700264 NetworkId network_id = kDefaultNetworkId;
265 if (!headers[kPayloadPropertyNetworkId].empty()) {
266 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
267 &network_id)) {
268 return LogAndSetError(
269 error,
270 FROM_HERE,
271 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
272 }
273 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700274 return LogAndSetError(
275 error,
276 FROM_HERE,
277 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700278 }
279 }
280
Alex Deymo5e3ea272016-01-28 13:42:23 -0800281 LOG(INFO) << "Using this install plan:";
282 install_plan_.Dump();
283
Amin Hassani667cf7b2018-07-25 14:32:00 -0700284 HttpFetcher* fetcher = nullptr;
285 if (FileFetcher::SupportedUrl(payload_url)) {
286 DLOG(INFO) << "Using FileFetcher for file URL.";
287 fetcher = new FileFetcher();
288 } else {
289#ifdef _UE_SIDELOAD
290 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
291#else
292 LibcurlHttpFetcher* libcurl_fetcher =
293 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
294 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
295 fetcher = libcurl_fetcher;
296#endif // _UE_SIDELOAD
297 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800298 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800299 if (!headers[kPayloadPropertyAuthorization].empty())
300 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
301 if (!headers[kPayloadPropertyUserAgent].empty())
302 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
303
Amin Hassani667cf7b2018-07-25 14:32:00 -0700304 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800305
Alex Deymo5e3ea272016-01-28 13:42:23 -0800306 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700307
308 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
309 // TODO(xunchang) report the metrics for unresumable updates
310
Amin Hassani667cf7b2018-07-25 14:32:00 -0700311 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800312 return true;
313}
314
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900315bool UpdateAttempterAndroid::ApplyPayload(
316 int fd,
317 int64_t payload_offset,
318 int64_t payload_size,
319 const vector<string>& key_value_pair_headers,
320 brillo::ErrorPtr* error) {
321 payload_fd_.reset(dup(fd));
322 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
323
324 return ApplyPayload(
325 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
326}
327
Alex Deymo5e3ea272016-01-28 13:42:23 -0800328bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700329 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800330 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
331 processor_->SuspendProcessing();
332 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800333}
334
335bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700336 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800337 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
338 processor_->ResumeProcessing();
339 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800340}
341
342bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700343 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800344 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800345 processor_->StopProcessing();
346 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800347}
348
Alex Deymo3b678db2016-02-09 11:50:06 -0800349bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
350 LOG(INFO) << "Attempting to reset state from "
351 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
352
353 switch (status_) {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700354 case UpdateStatus::IDLE: {
355 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_)) {
356 LOG(WARNING) << "Failed to reset snapshots. UpdateStatus is IDLE but"
357 << "space might not be freed.";
358 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800359 return true;
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700360 }
Alex Deymo3b678db2016-02-09 11:50:06 -0800361
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800362 case UpdateStatus::UPDATED_NEED_REBOOT: {
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700363 bool ret_value = true;
Alex Deymo3b678db2016-02-09 11:50:06 -0800364
365 // Update the boot flags so the current slot has higher priority.
Yifan Hongbd47d622019-12-13 14:59:58 -0800366 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot()))
Alex Deymo3b678db2016-02-09 11:50:06 -0800367 ret_value = false;
368
Alex Deymo52590332016-11-29 18:29:13 -0800369 // Mark the current slot as successful again, since marking it as active
370 // may reset the successful bit. We ignore the result of whether marking
371 // the current slot as successful worked.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800372 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {})))
Alex Deymo52590332016-11-29 18:29:13 -0800373 ret_value = false;
374
Tianjie Xud6aa91f2019-11-14 11:55:10 -0800375 // Resets the warm reset property since we won't switch the slot.
376 hardware_->SetWarmReset(false);
377
Tianjie838793d2021-01-14 22:05:13 -0800378 // Resets the vbmeta digest.
379 hardware_->SetVbmetaDigestForInactiveSlot(true /* reset */);
380
Yifan Hong6a6d0f12020-03-11 13:20:52 -0700381 // Remove update progress for DeltaPerformer and remove snapshots.
382 if (!boot_control_->GetDynamicPartitionControl()->ResetUpdate(prefs_))
383 ret_value = false;
384
385 // Remove the reboot marker so that if the machine is rebooted
386 // after resetting to idle state, it doesn't go back to
387 // UpdateStatus::UPDATED_NEED_REBOOT state.
388 if (!prefs_->Delete(kPrefsUpdateCompletedOnBootId))
389 ret_value = false;
390 ClearMetricsPrefs();
391
Alex Deymo3b678db2016-02-09 11:50:06 -0800392 if (!ret_value) {
393 return LogAndSetError(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800394 error, FROM_HERE, "Failed to reset the status to ");
Alex Deymo3b678db2016-02-09 11:50:06 -0800395 }
396
397 SetStatusAndNotify(UpdateStatus::IDLE);
398 LOG(INFO) << "Reset status successful";
399 return true;
400 }
401
402 default:
403 return LogAndSetError(
404 error,
405 FROM_HERE,
406 "Reset not allowed in this state. Cancel the ongoing update first");
407 }
408}
409
Yifan Hongbd47d622019-12-13 14:59:58 -0800410bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
411 const std::string& metadata_filename,
412 DeltaArchiveManifest* manifest,
413 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800414 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
415 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
416 return LogAndSetError(
417 error, FROM_HERE, "Failed to open " + metadata_filename);
418 }
419 brillo::Blob metadata(kMaxPayloadHeaderSize);
420 if (!fd->Read(metadata.data(), metadata.size())) {
421 return LogAndSetError(
422 error,
423 FROM_HERE,
424 "Failed to read payload header from " + metadata_filename);
425 }
426 ErrorCode errorcode;
427 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700428 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800429 MetadataParseResult::kSuccess) {
430 return LogAndSetError(error,
431 FROM_HERE,
432 "Failed to parse payload header: " +
433 utils::ErrorCodeToString(errorcode));
434 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700435 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
436 payload_metadata.GetMetadataSignatureSize();
437 if (metadata_size < kMaxPayloadHeaderSize ||
438 metadata_size >
439 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800440 return LogAndSetError(
441 error,
442 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700443 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800444 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700445 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800446 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
447 metadata.size() - kMaxPayloadHeaderSize)) {
448 return LogAndSetError(
449 error,
450 FROM_HERE,
451 "Failed to read metadata and signature from " + metadata_filename);
452 }
453 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800454
Tianjie Xu7a78d632019-10-08 16:32:39 -0700455 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
456 constants::kUpdateCertificatesPath);
457 if (!payload_verifier) {
458 return LogAndSetError(error,
459 FROM_HERE,
460 "Failed to create the payload verifier from " +
461 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800462 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700463 errorcode = payload_metadata.ValidateMetadataSignature(
464 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800465 if (errorcode != ErrorCode::kSuccess) {
466 return LogAndSetError(error,
467 FROM_HERE,
468 "Failed to validate metadata signature: " +
469 utils::ErrorCodeToString(errorcode));
470 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800471 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800472 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
473 }
474
Yifan Hongbd47d622019-12-13 14:59:58 -0800475 return true;
476}
477
478bool UpdateAttempterAndroid::VerifyPayloadApplicable(
479 const std::string& metadata_filename, brillo::ErrorPtr* error) {
480 DeltaArchiveManifest manifest;
481 TEST_AND_RETURN_FALSE(
482 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
483
484 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
485 ErrorCode errorcode;
486
487 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800488 for (const PartitionUpdate& partition : manifest.partitions()) {
489 if (!partition.has_old_partition_info())
490 continue;
491 string partition_path;
492 if (!boot_control_->GetPartitionDevice(
493 partition.partition_name(), current_slot, &partition_path)) {
494 return LogAndSetError(
495 error,
496 FROM_HERE,
497 "Failed to get partition device for " + partition.partition_name());
498 }
499 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
500 return LogAndSetError(
501 error, FROM_HERE, "Failed to open " + partition_path);
502 }
503 for (const InstallOperation& operation : partition.operations()) {
504 if (!operation.has_src_sha256_hash())
505 continue;
506 brillo::Blob source_hash;
507 if (!fd_utils::ReadAndHashExtents(fd,
508 operation.src_extents(),
509 manifest.block_size(),
510 &source_hash)) {
511 return LogAndSetError(
512 error, FROM_HERE, "Failed to hash " + partition_path);
513 }
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400514 if (!PartitionWriter::ValidateSourceHash(
Sen Jiang8371c1c2018-02-01 13:46:39 -0800515 source_hash, operation, fd, &errorcode)) {
516 return false;
517 }
518 }
519 fd->Close();
520 }
521 return true;
522}
523
Alex Deymo5e3ea272016-01-28 13:42:23 -0800524void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
525 ErrorCode code) {
526 LOG(INFO) << "Processing Done.";
527
Yifan Hong90965502020-02-19 15:22:47 -0800528 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
529 TerminateUpdateAndNotify(code);
530 return;
531 }
532
Alex Deymo5990bf32016-07-19 17:01:41 -0700533 switch (code) {
534 case ErrorCode::kSuccess:
535 // Update succeeded.
536 WriteUpdateCompletedMarker();
537 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800538
Alex Deymo5990bf32016-07-19 17:01:41 -0700539 LOG(INFO) << "Update successfully applied, waiting to reboot.";
540 break;
541
542 case ErrorCode::kFilesystemCopierError:
543 case ErrorCode::kNewRootfsVerificationError:
544 case ErrorCode::kNewKernelVerificationError:
545 case ErrorCode::kFilesystemVerifierError:
546 case ErrorCode::kDownloadStateInitializationError:
547 // Reset the ongoing update for these errors so it starts from the
548 // beginning next time.
549 DeltaPerformer::ResetUpdateProgress(prefs_, false);
550 LOG(INFO) << "Resetting update progress.";
551 break;
552
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700553 case ErrorCode::kPayloadTimestampError:
554 // SafetyNet logging, b/36232423
555 android_errorWriteLog(0x534e4554, "36232423");
556 break;
557
Alex Deymo5990bf32016-07-19 17:01:41 -0700558 default:
559 // Ignore all other error codes.
560 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700561 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800562
563 TerminateUpdateAndNotify(code);
564}
565
566void UpdateAttempterAndroid::ProcessingStopped(
567 const ActionProcessor* processor) {
568 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
569}
570
571void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
572 AbstractAction* action,
573 ErrorCode code) {
574 // Reset download progress regardless of whether or not the download
575 // action succeeded.
576 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800577 if (type == CleanupPreviousUpdateAction::StaticType() ||
578 (type == NoOpAction::StaticType() &&
579 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
580 cleanup_previous_update_code_ = code;
581 NotifyCleanupPreviousUpdateCallbacksAndClear();
582 }
Kelvin Zhang70eef232020-06-12 20:32:40 +0000583 // download_progress_ is actually used by other actions, such as
584 // filesystem_verify_action. Therefore we always clear it.
585 download_progress_ = 0;
Sen Jiangfe522822017-10-31 15:14:11 -0700586 if (type == PostinstallRunnerAction::StaticType()) {
587 bool succeeded =
588 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
589 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
590 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800591 if (code != ErrorCode::kSuccess) {
592 // If an action failed, the ActionProcessor will cancel the whole thing.
593 return;
594 }
Yifan Hong83517502020-02-19 15:34:13 -0800595 if (type == UpdateBootFlagsAction::StaticType()) {
596 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
597 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800598 if (type == DownloadAction::StaticType()) {
Kelvin Zhangd2da7b12020-07-07 17:19:21 -0400599 auto download_action = static_cast<DownloadAction*>(action);
600 install_plan_ = *download_action->install_plan();
Kelvin Zhang70eef232020-06-12 20:32:40 +0000601 SetStatusAndNotify(UpdateStatus::VERIFYING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700602 } else if (type == FilesystemVerifierAction::StaticType()) {
Kelvin Zhang70eef232020-06-12 20:32:40 +0000603 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700604 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800605 }
606}
607
608void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
609 uint64_t bytes_received,
610 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700611 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800612 if (total)
613 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700614 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800615 download_progress_ = progress;
616 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700617 } else {
618 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800619 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700620
621 // Update the bytes downloaded in prefs.
622 int64_t current_bytes_downloaded =
623 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
624 int64_t total_bytes_downloaded =
625 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
626 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
627 current_bytes_downloaded + bytes_progressed);
628 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
629 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800630}
631
632bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
633 // TODO(deymo): Notify the DownloadAction that it should cancel the update
634 // download.
635 return false;
636}
637
638void UpdateAttempterAndroid::DownloadComplete() {
639 // Nothing needs to be done when the download completes.
640}
641
Alex Deymo0d298542016-03-30 18:31:49 -0700642void UpdateAttempterAndroid::ProgressUpdate(double progress) {
643 // Self throttle based on progress. Also send notifications if progress is
644 // too slow.
645 if (progress == 1.0 ||
646 progress - download_progress_ >= kBroadcastThresholdProgress ||
647 TimeTicks::Now() - last_notify_time_ >=
648 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
649 download_progress_ = progress;
650 SetStatusAndNotify(status_);
651 }
652}
653
Kelvin Zhang70eef232020-06-12 20:32:40 +0000654void UpdateAttempterAndroid::OnVerifyProgressUpdate(double progress) {
655 assert(status_ == UpdateStatus::VERIFYING);
656 ProgressUpdate(progress);
657}
658
Alex Deymo5e3ea272016-01-28 13:42:23 -0800659void UpdateAttempterAndroid::ScheduleProcessingStart() {
660 LOG(INFO) << "Scheduling an action processor start.";
661 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700662 FROM_HERE,
663 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
664 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800665}
666
667void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
668 if (status_ == UpdateStatus::IDLE) {
669 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
670 return;
671 }
672
Yifan Hong90965502020-02-19 15:22:47 -0800673 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
674 LOG(INFO) << "Terminating cleanup previous update.";
675 SetStatusAndNotify(UpdateStatus::IDLE);
Yifan Hong5cd63fa2020-03-16 12:31:16 -0700676 for (auto observer : daemon_state_->service_observers())
677 observer->SendPayloadApplicationComplete(error_code);
Yifan Hong90965502020-02-19 15:22:47 -0800678 return;
679 }
680
Yifan Hong9194ce82019-11-07 11:03:42 -0800681 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700682
Alex Deymo0d298542016-03-30 18:31:49 -0700683 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800684 UpdateStatus new_status =
685 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
686 : UpdateStatus::IDLE);
687 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900688 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800689
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700690 // The network id is only applicable to one download attempt and once it's
691 // done the network id should not be re-used anymore.
692 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
693 LOG(WARNING) << "Unable to unbind network.";
694 }
695
Alex Deymo5e3ea272016-01-28 13:42:23 -0800696 for (auto observer : daemon_state_->service_observers())
697 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700698
Tianjie Xu90aaa102017-10-10 17:39:03 -0700699 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
700 ClearMetricsPrefs();
701 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800702 // We should only reset the PayloadAttemptNumber if the update succeeds, or
703 // we switch to a different payload.
704 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700705 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700706 // Clear the total bytes downloaded if and only if the update succeeds.
707 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700708 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800709}
710
711void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
712 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700713 size_t payload_size =
714 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700715 UpdateEngineStatus status_to_send = {.status = status_,
716 .progress = download_progress_,
717 .new_size_bytes = payload_size};
718
Alex Deymo5e3ea272016-01-28 13:42:23 -0800719 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700720 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800721 }
722 last_notify_time_ = TimeTicks::Now();
723}
724
Amin Hassani667cf7b2018-07-25 14:32:00 -0700725void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800726 CHECK(!processor_->IsRunning());
727 processor_->set_delegate(this);
728
729 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700730 auto update_boot_flags_action =
731 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800732 auto cleanup_previous_update_action =
733 boot_control_->GetDynamicPartitionControl()
734 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700735 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
736 auto download_action =
737 std::make_unique<DownloadAction>(prefs_,
738 boot_control_,
739 hardware_,
Amin Hassani667cf7b2018-07-25 14:32:00 -0700740 fetcher, // passes ownership
741 true /* interactive */);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800742 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700743 download_action->set_base_offset(base_offset_);
Tianjie24f96092020-06-30 12:26:25 -0700744 auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
745 boot_control_->GetDynamicPartitionControl());
Amin Hassani667cf7b2018-07-25 14:32:00 -0700746 auto postinstall_runner_action =
747 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Kelvin Zhang70eef232020-06-12 20:32:40 +0000748 filesystem_verifier_action->set_delegate(this);
Alex Deymob6eef732016-06-10 12:58:11 -0700749 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800750
Alex Deymo5e3ea272016-01-28 13:42:23 -0800751 // Bond them together. We have to use the leaf-types when calling
752 // BondActions().
753 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700754 BondActions(download_action.get(), filesystem_verifier_action.get());
755 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800756 postinstall_runner_action.get());
757
Amin Hassani667cf7b2018-07-25 14:32:00 -0700758 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800759 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700760 processor_->EnqueueAction(std::move(install_plan_action));
761 processor_->EnqueueAction(std::move(download_action));
762 processor_->EnqueueAction(std::move(filesystem_verifier_action));
763 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800764}
765
Alex Deymo5e3ea272016-01-28 13:42:23 -0800766bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
767 string boot_id;
768 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
769 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
770 return true;
771}
772
773bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
774 // In case of an update_engine restart without a reboot, we stored the boot_id
775 // when the update was completed by setting a pref, so we can check whether
776 // the last update was on this boot or a previous one.
777 string boot_id;
778 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
779
780 string update_completed_on_boot_id;
781 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
782 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
783 &update_completed_on_boot_id) &&
784 update_completed_on_boot_id == boot_id);
785}
786
Tianjie Xu90aaa102017-10-10 17:39:03 -0700787// Collect and report the android metrics when we terminate the update.
788void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
789 ErrorCode error_code) {
790 int64_t attempt_number =
791 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
792 PayloadType payload_type = kPayloadTypeFull;
793 int64_t payload_size = 0;
794 for (const auto& p : install_plan_.payloads) {
795 if (p.type == InstallPayloadType::kDelta)
796 payload_type = kPayloadTypeDelta;
797 payload_size += p.size;
798 }
799
800 metrics::AttemptResult attempt_result =
801 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700802 Time boot_time_start = Time::FromInternalValue(
803 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
804 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700805 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700806 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
807 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700808
809 metrics_reporter_->ReportUpdateAttemptMetrics(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700810 static_cast<int>(attempt_number),
811 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700812 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700813 duration_uptime,
814 payload_size,
815 attempt_result,
816 error_code);
817
Tianjie Xud4777a12017-10-24 14:54:18 -0700818 int64_t current_bytes_downloaded =
819 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
820 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
821 current_bytes_downloaded,
822 0,
823 DownloadSource::kNumDownloadSources,
824 metrics::DownloadErrorCode::kUnset,
825 metrics::ConnectionType::kUnset);
826
Tianjie Xu90aaa102017-10-10 17:39:03 -0700827 if (error_code == ErrorCode::kSuccess) {
828 int64_t reboot_count =
829 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
830 string build_version;
831 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700832
833 // For android metrics, we only care about the total bytes downloaded
834 // for all sources; for now we assume the only download source is
835 // HttpsServer.
836 int64_t total_bytes_downloaded =
837 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
838 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
839 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
840 total_bytes_downloaded;
841
842 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700843 if (total_bytes_downloaded >= payload_size) {
844 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700845 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700846 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
847 } else {
848 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
849 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700850 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700851
Tianjie Xu90aaa102017-10-10 17:39:03 -0700852 metrics_reporter_->ReportSuccessfulUpdateMetrics(
853 static_cast<int>(attempt_number),
854 0, // update abandoned count
855 payload_type,
856 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700857 num_bytes_downloaded,
858 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700859 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700860 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700861 static_cast<int>(reboot_count),
862 0); // url_switch_count
863 }
864}
865
866void UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
867 string current_boot_id;
868 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
869 // Example: [ro.build.version.incremental]: [4292972]
870 string current_version =
871 android::base::GetProperty("ro.build.version.incremental", "");
872 TEST_AND_RETURN(!current_version.empty());
873
874 // If there's no record of previous version (e.g. due to a data wipe), we
875 // save the info of current boot and skip the metrics report.
876 if (!prefs_->Exists(kPrefsPreviousVersion)) {
877 prefs_->SetString(kPrefsBootId, current_boot_id);
878 prefs_->SetString(kPrefsPreviousVersion, current_version);
879 ClearMetricsPrefs();
880 return;
881 }
882 string previous_version;
883 // update_engine restarted under the same build.
884 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
885 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
886 previous_version == current_version) {
887 string last_boot_id;
888 bool is_reboot = prefs_->Exists(kPrefsBootId) &&
889 (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
890 last_boot_id != current_boot_id);
891 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
892 // set when we start a new update.
893 if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
894 prefs_->SetString(kPrefsBootId, current_boot_id);
895 int64_t reboot_count =
896 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
897 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
898 }
899 return;
900 }
901
902 // Now that the build version changes, report the update metrics.
903 // TODO(xunchang) check the build version is larger than the previous one.
904 prefs_->SetString(kPrefsBootId, current_boot_id);
905 prefs_->SetString(kPrefsPreviousVersion, current_version);
906
907 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
908 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
909 if (previous_attempt_exists) {
910 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
911 }
912
913 metrics_utils::LoadAndReportTimeToReboot(
914 metrics_reporter_.get(), prefs_, clock_.get());
915 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -0800916
917 // Also reset the update progress if the build version has changed.
918 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
919 LOG(WARNING) << "Unable to reset the update progress.";
920 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700921}
922
923// Save the update start time. Reset the reboot count and attempt number if the
924// update isn't a resume; otherwise increment the attempt number.
925void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
926 if (!is_resume) {
927 metrics_utils::SetNumReboots(0, prefs_);
928 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
929 } else {
930 int64_t attempt_number =
931 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
932 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
933 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700934 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
935 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700936}
937
938void UpdateAttempterAndroid::ClearMetricsPrefs() {
939 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700940 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700941 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700942 prefs_->Delete(kPrefsSystemUpdatedMarker);
943 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700944 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700945}
946
Yifan Hongbd47d622019-12-13 14:59:58 -0800947BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
948 return boot_control_->GetCurrentSlot();
949}
950
951BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
952 return GetCurrentSlot() == 0 ? 1 : 0;
953}
954
Yifan Hong6f7e29f2019-12-13 14:41:06 -0800955uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
956 const std::string& metadata_filename,
957 const vector<string>& key_value_pair_headers,
958 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -0800959 DeltaArchiveManifest manifest;
960 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
961 return 0;
962 }
963 std::map<string, string> headers;
964 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
965 return 0;
966 }
967
968 string payload_id = GetPayloadId(headers);
969 uint64_t required_size = 0;
970 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
971 boot_control_,
972 GetTargetSlot(),
973 manifest,
974 payload_id,
975 &required_size)) {
976 if (required_size == 0) {
977 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
978 return 0;
979 } else {
980 LOG(ERROR) << "Insufficient space for payload: " << required_size
981 << " bytes";
982 return required_size;
983 }
984 }
985
986 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -0800987 return 0;
988}
989
Yifan Hong40bb0d02020-02-24 17:33:14 -0800990void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
991 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Yifan Hong2236ea02019-12-13 16:11:22 -0800992 brillo::ErrorPtr* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -0800993 if (cleanup_previous_update_code_.has_value()) {
994 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
995 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
996 if (callback) {
997 callback->OnCleanupComplete(
998 static_cast<int32_t>(*cleanup_previous_update_code_));
999 }
1000 return;
Yifan Hong4f611562020-01-15 23:41:33 -08001001 }
Yifan Hong40bb0d02020-02-24 17:33:14 -08001002 if (callback) {
1003 auto callback_ptr = callback.get();
1004 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
1005 callback_ptr->RegisterForDeathNotifications(
1006 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
1007 base::Unretained(this),
1008 base::Unretained(callback_ptr)));
1009 }
1010 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -08001011}
1012
Yifan Hong90965502020-02-19 15:22:47 -08001013void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
1014 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
1015 // is in progress, skip enqueueing the action.
1016 if (processor_->IsRunning()) {
1017 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
1018 << "be done when the current update finishes.";
1019 return;
1020 }
1021 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
1022 auto action =
1023 boot_control_->GetDynamicPartitionControl()
1024 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
1025 processor_->EnqueueAction(std::move(action));
1026 processor_->set_delegate(this);
1027 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
1028 processor_->StartProcessing();
1029}
1030
Yifan Hong40bb0d02020-02-24 17:33:14 -08001031void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1032 for (auto&& callback : cleanup_previous_update_callbacks_) {
1033 callback->OnCleanupProgressUpdate(progress);
1034 }
1035}
1036
1037void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1038 CHECK(cleanup_previous_update_code_.has_value());
1039 for (auto&& callback : cleanup_previous_update_callbacks_) {
1040 callback->OnCleanupComplete(
1041 static_cast<int32_t>(*cleanup_previous_update_code_));
1042 }
1043 cleanup_previous_update_callbacks_.clear();
1044}
1045
1046void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1047 CleanupSuccessfulUpdateCallbackInterface* callback) {
1048 auto end_it =
1049 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1050 cleanup_previous_update_callbacks_.end(),
1051 [&](const auto& e) { return e.get() == callback; });
1052 cleanup_previous_update_callbacks_.erase(
1053 end_it, cleanup_previous_update_callbacks_.end());
1054}
Yifan Hong90965502020-02-19 15:22:47 -08001055
Alex Deymo5e3ea272016-01-28 13:42:23 -08001056} // namespace chromeos_update_engine