blob: eecd2daf0ef796f83bb1d886cbe24c40642bcb0c [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
17#include "update_engine/update_attempter_android.h"
18
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
Yifan Hong40bb0d02020-02-24 17:33:14 -080034#include "update_engine/cleanup_previous_update_action.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080035#include "update_engine/common/constants.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080036#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070037#include "update_engine/common/file_fetcher.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080038#include "update_engine/common/utils.h"
Alex Deymo03a4de72016-07-20 16:08:23 -070039#include "update_engine/daemon_state_interface.h"
Tianjie Xud4c5deb2017-10-24 11:17:03 -070040#include "update_engine/metrics_reporter_interface.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070041#include "update_engine/metrics_utils.h"
Alex Deymo87792ea2016-07-25 15:40:36 -070042#include "update_engine/network_selector.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070043#include "update_engine/payload_consumer/certificate_parser_interface.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080044#include "update_engine/payload_consumer/delta_performer.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080045#include "update_engine/payload_consumer/download_action.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 Hong90965502020-02-19 15:22:47 -0800161 ScheduleCleanupPreviousUpdate();
Tianjie Xu90aaa102017-10-10 17:39:03 -0700162 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800163}
164
165bool UpdateAttempterAndroid::ApplyPayload(
166 const string& payload_url,
167 int64_t payload_offset,
168 int64_t payload_size,
169 const vector<string>& key_value_pair_headers,
170 brillo::ErrorPtr* error) {
171 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
172 return LogAndSetError(
173 error, FROM_HERE, "An update already applied, waiting for reboot");
174 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700175 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800176 return LogAndSetError(
177 error, FROM_HERE, "Already processing an update, cancel it first.");
178 }
179 DCHECK(status_ == UpdateStatus::IDLE);
180
Alex Deymo218397f2016-02-04 23:55:10 -0800181 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800182 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
183 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800184 }
185
Yifan Hongbd47d622019-12-13 14:59:58 -0800186 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800187
188 // Setup the InstallPlan based on the request.
189 install_plan_ = InstallPlan();
190
191 install_plan_.download_url = payload_url;
192 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800193 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800194 InstallPlan::Payload payload;
195 payload.size = payload_size;
196 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800197 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800198 &payload.size)) {
199 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800200 }
201 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700202 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800203 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700204 LOG(WARNING) << "Unable to decode base64 file hash: "
205 << headers[kPayloadPropertyFileHash];
206 }
Alex Deymo218397f2016-02-04 23:55:10 -0800207 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800208 &payload.metadata_size)) {
209 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800210 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700211 // The |payload.type| is not used anymore since minor_version 3.
212 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800213 install_plan_.payloads.push_back(payload);
214
Alex Deymo5e3ea272016-01-28 13:42:23 -0800215 // The |public_key_rsa| key would override the public key stored on disk.
216 install_plan_.public_key_rsa = "";
217
218 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
219 install_plan_.is_resume = !payload_id.empty() &&
220 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
221 if (!install_plan_.is_resume) {
Yifan Hong55c2bfe2020-01-13 17:01:19 -0800222 // No need to reset dynamic_partititon_metadata_updated. If previous calls
223 // to AllocateSpaceForPayload uses the same payload_id, reuse preallocated
224 // space. Otherwise, DeltaPerformer re-allocates space when the payload is
225 // applied.
226 if (!DeltaPerformer::ResetUpdateProgress(
227 prefs_,
228 false /* quick */,
229 true /* skip_dynamic_partititon_metadata_updated */)) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800230 LOG(WARNING) << "Unable to reset the update progress.";
231 }
232 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
233 LOG(WARNING) << "Unable to save the update check response hash.";
234 }
235 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800236 install_plan_.source_slot = GetCurrentSlot();
237 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700238
Alex Deymofb905d92016-06-03 19:26:58 -0700239 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700240 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
241
242 install_plan_.switch_slot_on_reboot =
243 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
244
Tianjie Xu087de9d2019-11-01 17:11:22 -0700245 install_plan_.run_post_install =
246 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800247
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700248 // Skip writing verity if we're resuming and verity has already been written.
249 install_plan_.write_verity = true;
250 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
251 bool verity_written = false;
252 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
253 verity_written) {
254 install_plan_.write_verity = false;
255 }
256 }
257
Alex Deymo87792ea2016-07-25 15:40:36 -0700258 NetworkId network_id = kDefaultNetworkId;
259 if (!headers[kPayloadPropertyNetworkId].empty()) {
260 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
261 &network_id)) {
262 return LogAndSetError(
263 error,
264 FROM_HERE,
265 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
266 }
267 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700268 return LogAndSetError(
269 error,
270 FROM_HERE,
271 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700272 }
273 }
274
Alex Deymo5e3ea272016-01-28 13:42:23 -0800275 LOG(INFO) << "Using this install plan:";
276 install_plan_.Dump();
277
Amin Hassani667cf7b2018-07-25 14:32:00 -0700278 HttpFetcher* fetcher = nullptr;
279 if (FileFetcher::SupportedUrl(payload_url)) {
280 DLOG(INFO) << "Using FileFetcher for file URL.";
281 fetcher = new FileFetcher();
282 } else {
283#ifdef _UE_SIDELOAD
284 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
285#else
286 LibcurlHttpFetcher* libcurl_fetcher =
287 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
288 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
289 fetcher = libcurl_fetcher;
290#endif // _UE_SIDELOAD
291 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800292 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800293 if (!headers[kPayloadPropertyAuthorization].empty())
294 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
295 if (!headers[kPayloadPropertyUserAgent].empty())
296 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
297
Amin Hassani667cf7b2018-07-25 14:32:00 -0700298 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800299
Alex Deymo5e3ea272016-01-28 13:42:23 -0800300 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700301
302 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
303 // TODO(xunchang) report the metrics for unresumable updates
304
Amin Hassani667cf7b2018-07-25 14:32:00 -0700305 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800306 return true;
307}
308
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900309bool UpdateAttempterAndroid::ApplyPayload(
310 int fd,
311 int64_t payload_offset,
312 int64_t payload_size,
313 const vector<string>& key_value_pair_headers,
314 brillo::ErrorPtr* error) {
315 payload_fd_.reset(dup(fd));
316 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
317
318 return ApplyPayload(
319 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
320}
321
Alex Deymo5e3ea272016-01-28 13:42:23 -0800322bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700323 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800324 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
325 processor_->SuspendProcessing();
326 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800327}
328
329bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700330 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800331 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
332 processor_->ResumeProcessing();
333 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800334}
335
336bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700337 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800338 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800339 processor_->StopProcessing();
340 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800341}
342
Alex Deymo3b678db2016-02-09 11:50:06 -0800343bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
344 LOG(INFO) << "Attempting to reset state from "
345 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
346
347 switch (status_) {
348 case UpdateStatus::IDLE:
349 return true;
350
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800351 case UpdateStatus::UPDATED_NEED_REBOOT: {
Alex Deymo3b678db2016-02-09 11:50:06 -0800352 // Remove the reboot marker so that if the machine is rebooted
353 // after resetting to idle state, it doesn't go back to
354 // UpdateStatus::UPDATED_NEED_REBOOT state.
355 bool ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700356 ClearMetricsPrefs();
Alex Deymo3b678db2016-02-09 11:50:06 -0800357
358 // Update the boot flags so the current slot has higher priority.
Yifan Hongbd47d622019-12-13 14:59:58 -0800359 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot()))
Alex Deymo3b678db2016-02-09 11:50:06 -0800360 ret_value = false;
361
Alex Deymo52590332016-11-29 18:29:13 -0800362 // Mark the current slot as successful again, since marking it as active
363 // may reset the successful bit. We ignore the result of whether marking
364 // the current slot as successful worked.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800365 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {})))
Alex Deymo52590332016-11-29 18:29:13 -0800366 ret_value = false;
367
Tianjie Xud6aa91f2019-11-14 11:55:10 -0800368 // Resets the warm reset property since we won't switch the slot.
369 hardware_->SetWarmReset(false);
370
Alex Deymo3b678db2016-02-09 11:50:06 -0800371 if (!ret_value) {
372 return LogAndSetError(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800373 error, FROM_HERE, "Failed to reset the status to ");
Alex Deymo3b678db2016-02-09 11:50:06 -0800374 }
375
376 SetStatusAndNotify(UpdateStatus::IDLE);
377 LOG(INFO) << "Reset status successful";
378 return true;
379 }
380
381 default:
382 return LogAndSetError(
383 error,
384 FROM_HERE,
385 "Reset not allowed in this state. Cancel the ongoing update first");
386 }
387}
388
Yifan Hongbd47d622019-12-13 14:59:58 -0800389bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
390 const std::string& metadata_filename,
391 DeltaArchiveManifest* manifest,
392 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800393 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
394 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
395 return LogAndSetError(
396 error, FROM_HERE, "Failed to open " + metadata_filename);
397 }
398 brillo::Blob metadata(kMaxPayloadHeaderSize);
399 if (!fd->Read(metadata.data(), metadata.size())) {
400 return LogAndSetError(
401 error,
402 FROM_HERE,
403 "Failed to read payload header from " + metadata_filename);
404 }
405 ErrorCode errorcode;
406 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700407 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800408 MetadataParseResult::kSuccess) {
409 return LogAndSetError(error,
410 FROM_HERE,
411 "Failed to parse payload header: " +
412 utils::ErrorCodeToString(errorcode));
413 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700414 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
415 payload_metadata.GetMetadataSignatureSize();
416 if (metadata_size < kMaxPayloadHeaderSize ||
417 metadata_size >
418 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800419 return LogAndSetError(
420 error,
421 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700422 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800423 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700424 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800425 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
426 metadata.size() - kMaxPayloadHeaderSize)) {
427 return LogAndSetError(
428 error,
429 FROM_HERE,
430 "Failed to read metadata and signature from " + metadata_filename);
431 }
432 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800433
Tianjie Xu7a78d632019-10-08 16:32:39 -0700434 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
435 constants::kUpdateCertificatesPath);
436 if (!payload_verifier) {
437 return LogAndSetError(error,
438 FROM_HERE,
439 "Failed to create the payload verifier from " +
440 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800441 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700442 errorcode = payload_metadata.ValidateMetadataSignature(
443 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800444 if (errorcode != ErrorCode::kSuccess) {
445 return LogAndSetError(error,
446 FROM_HERE,
447 "Failed to validate metadata signature: " +
448 utils::ErrorCodeToString(errorcode));
449 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800450 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800451 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
452 }
453
Yifan Hongbd47d622019-12-13 14:59:58 -0800454 return true;
455}
456
457bool UpdateAttempterAndroid::VerifyPayloadApplicable(
458 const std::string& metadata_filename, brillo::ErrorPtr* error) {
459 DeltaArchiveManifest manifest;
460 TEST_AND_RETURN_FALSE(
461 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
462
463 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
464 ErrorCode errorcode;
465
466 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800467 for (const PartitionUpdate& partition : manifest.partitions()) {
468 if (!partition.has_old_partition_info())
469 continue;
470 string partition_path;
471 if (!boot_control_->GetPartitionDevice(
472 partition.partition_name(), current_slot, &partition_path)) {
473 return LogAndSetError(
474 error,
475 FROM_HERE,
476 "Failed to get partition device for " + partition.partition_name());
477 }
478 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
479 return LogAndSetError(
480 error, FROM_HERE, "Failed to open " + partition_path);
481 }
482 for (const InstallOperation& operation : partition.operations()) {
483 if (!operation.has_src_sha256_hash())
484 continue;
485 brillo::Blob source_hash;
486 if (!fd_utils::ReadAndHashExtents(fd,
487 operation.src_extents(),
488 manifest.block_size(),
489 &source_hash)) {
490 return LogAndSetError(
491 error, FROM_HERE, "Failed to hash " + partition_path);
492 }
493 if (!DeltaPerformer::ValidateSourceHash(
494 source_hash, operation, fd, &errorcode)) {
495 return false;
496 }
497 }
498 fd->Close();
499 }
500 return true;
501}
502
Alex Deymo5e3ea272016-01-28 13:42:23 -0800503void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
504 ErrorCode code) {
505 LOG(INFO) << "Processing Done.";
506
Yifan Hong90965502020-02-19 15:22:47 -0800507 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
508 TerminateUpdateAndNotify(code);
509 return;
510 }
511
Alex Deymo5990bf32016-07-19 17:01:41 -0700512 switch (code) {
513 case ErrorCode::kSuccess:
514 // Update succeeded.
515 WriteUpdateCompletedMarker();
516 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800517
Alex Deymo5990bf32016-07-19 17:01:41 -0700518 LOG(INFO) << "Update successfully applied, waiting to reboot.";
519 break;
520
521 case ErrorCode::kFilesystemCopierError:
522 case ErrorCode::kNewRootfsVerificationError:
523 case ErrorCode::kNewKernelVerificationError:
524 case ErrorCode::kFilesystemVerifierError:
525 case ErrorCode::kDownloadStateInitializationError:
526 // Reset the ongoing update for these errors so it starts from the
527 // beginning next time.
528 DeltaPerformer::ResetUpdateProgress(prefs_, false);
529 LOG(INFO) << "Resetting update progress.";
530 break;
531
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700532 case ErrorCode::kPayloadTimestampError:
533 // SafetyNet logging, b/36232423
534 android_errorWriteLog(0x534e4554, "36232423");
535 break;
536
Alex Deymo5990bf32016-07-19 17:01:41 -0700537 default:
538 // Ignore all other error codes.
539 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700540 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800541
542 TerminateUpdateAndNotify(code);
543}
544
545void UpdateAttempterAndroid::ProcessingStopped(
546 const ActionProcessor* processor) {
547 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
548}
549
550void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
551 AbstractAction* action,
552 ErrorCode code) {
553 // Reset download progress regardless of whether or not the download
554 // action succeeded.
555 const string type = action->Type();
Yifan Hong40bb0d02020-02-24 17:33:14 -0800556 if (type == CleanupPreviousUpdateAction::StaticType() ||
557 (type == NoOpAction::StaticType() &&
558 status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE)) {
559 cleanup_previous_update_code_ = code;
560 NotifyCleanupPreviousUpdateCallbacksAndClear();
561 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800562 if (type == DownloadAction::StaticType()) {
Alex Deymo0d298542016-03-30 18:31:49 -0700563 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800564 }
Sen Jiangfe522822017-10-31 15:14:11 -0700565 if (type == PostinstallRunnerAction::StaticType()) {
566 bool succeeded =
567 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
568 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
569 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800570 if (code != ErrorCode::kSuccess) {
571 // If an action failed, the ActionProcessor will cancel the whole thing.
572 return;
573 }
Yifan Hong83517502020-02-19 15:34:13 -0800574 if (type == UpdateBootFlagsAction::StaticType()) {
575 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
576 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800577 if (type == DownloadAction::StaticType()) {
578 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700579 } else if (type == FilesystemVerifierAction::StaticType()) {
580 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800581 }
582}
583
584void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
585 uint64_t bytes_received,
586 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700587 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800588 if (total)
589 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700590 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800591 download_progress_ = progress;
592 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700593 } else {
594 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800595 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700596
597 // Update the bytes downloaded in prefs.
598 int64_t current_bytes_downloaded =
599 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
600 int64_t total_bytes_downloaded =
601 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
602 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
603 current_bytes_downloaded + bytes_progressed);
604 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
605 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800606}
607
608bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
609 // TODO(deymo): Notify the DownloadAction that it should cancel the update
610 // download.
611 return false;
612}
613
614void UpdateAttempterAndroid::DownloadComplete() {
615 // Nothing needs to be done when the download completes.
616}
617
Alex Deymo0d298542016-03-30 18:31:49 -0700618void UpdateAttempterAndroid::ProgressUpdate(double progress) {
619 // Self throttle based on progress. Also send notifications if progress is
620 // too slow.
621 if (progress == 1.0 ||
622 progress - download_progress_ >= kBroadcastThresholdProgress ||
623 TimeTicks::Now() - last_notify_time_ >=
624 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
625 download_progress_ = progress;
626 SetStatusAndNotify(status_);
627 }
628}
629
Alex Deymo5e3ea272016-01-28 13:42:23 -0800630void UpdateAttempterAndroid::ScheduleProcessingStart() {
631 LOG(INFO) << "Scheduling an action processor start.";
632 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700633 FROM_HERE,
634 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
635 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800636}
637
638void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
639 if (status_ == UpdateStatus::IDLE) {
640 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
641 return;
642 }
643
Yifan Hong90965502020-02-19 15:22:47 -0800644 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
645 LOG(INFO) << "Terminating cleanup previous update.";
646 SetStatusAndNotify(UpdateStatus::IDLE);
647 return;
648 }
649
Yifan Hong9194ce82019-11-07 11:03:42 -0800650 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700651
Alex Deymo0d298542016-03-30 18:31:49 -0700652 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800653 UpdateStatus new_status =
654 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
655 : UpdateStatus::IDLE);
656 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900657 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800658
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700659 // The network id is only applicable to one download attempt and once it's
660 // done the network id should not be re-used anymore.
661 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
662 LOG(WARNING) << "Unable to unbind network.";
663 }
664
Alex Deymo5e3ea272016-01-28 13:42:23 -0800665 for (auto observer : daemon_state_->service_observers())
666 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700667
Tianjie Xu90aaa102017-10-10 17:39:03 -0700668 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
669 ClearMetricsPrefs();
670 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800671 // We should only reset the PayloadAttemptNumber if the update succeeds, or
672 // we switch to a different payload.
673 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700674 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700675 // Clear the total bytes downloaded if and only if the update succeeds.
676 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700677 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800678}
679
680void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
681 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700682 size_t payload_size =
683 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700684 UpdateEngineStatus status_to_send = {.status = status_,
685 .progress = download_progress_,
686 .new_size_bytes = payload_size};
687
Alex Deymo5e3ea272016-01-28 13:42:23 -0800688 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700689 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800690 }
691 last_notify_time_ = TimeTicks::Now();
692}
693
Amin Hassani667cf7b2018-07-25 14:32:00 -0700694void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800695 CHECK(!processor_->IsRunning());
696 processor_->set_delegate(this);
697
698 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700699 auto update_boot_flags_action =
700 std::make_unique<UpdateBootFlagsAction>(boot_control_);
Yifan Hong83517502020-02-19 15:34:13 -0800701 auto cleanup_previous_update_action =
702 boot_control_->GetDynamicPartitionControl()
703 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700704 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
705 auto download_action =
706 std::make_unique<DownloadAction>(prefs_,
707 boot_control_,
708 hardware_,
709 nullptr, // system_state, not used.
710 fetcher, // passes ownership
711 true /* interactive */);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800712 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700713 download_action->set_base_offset(base_offset_);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700714 auto filesystem_verifier_action =
715 std::make_unique<FilesystemVerifierAction>();
716 auto postinstall_runner_action =
717 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Alex Deymob6eef732016-06-10 12:58:11 -0700718 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800719
Alex Deymo5e3ea272016-01-28 13:42:23 -0800720 // Bond them together. We have to use the leaf-types when calling
721 // BondActions().
722 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700723 BondActions(download_action.get(), filesystem_verifier_action.get());
724 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800725 postinstall_runner_action.get());
726
Amin Hassani667cf7b2018-07-25 14:32:00 -0700727 processor_->EnqueueAction(std::move(update_boot_flags_action));
Yifan Hong83517502020-02-19 15:34:13 -0800728 processor_->EnqueueAction(std::move(cleanup_previous_update_action));
Amin Hassani667cf7b2018-07-25 14:32:00 -0700729 processor_->EnqueueAction(std::move(install_plan_action));
730 processor_->EnqueueAction(std::move(download_action));
731 processor_->EnqueueAction(std::move(filesystem_verifier_action));
732 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800733}
734
Alex Deymo5e3ea272016-01-28 13:42:23 -0800735bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
736 string boot_id;
737 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
738 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
739 return true;
740}
741
742bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
743 // In case of an update_engine restart without a reboot, we stored the boot_id
744 // when the update was completed by setting a pref, so we can check whether
745 // the last update was on this boot or a previous one.
746 string boot_id;
747 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
748
749 string update_completed_on_boot_id;
750 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
751 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
752 &update_completed_on_boot_id) &&
753 update_completed_on_boot_id == boot_id);
754}
755
Tianjie Xu90aaa102017-10-10 17:39:03 -0700756// Collect and report the android metrics when we terminate the update.
757void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
758 ErrorCode error_code) {
759 int64_t attempt_number =
760 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
761 PayloadType payload_type = kPayloadTypeFull;
762 int64_t payload_size = 0;
763 for (const auto& p : install_plan_.payloads) {
764 if (p.type == InstallPayloadType::kDelta)
765 payload_type = kPayloadTypeDelta;
766 payload_size += p.size;
767 }
768
769 metrics::AttemptResult attempt_result =
770 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700771 Time boot_time_start = Time::FromInternalValue(
772 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
773 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700774 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700775 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
776 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700777
778 metrics_reporter_->ReportUpdateAttemptMetrics(
779 nullptr, // system_state
780 static_cast<int>(attempt_number),
781 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700782 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700783 duration_uptime,
784 payload_size,
785 attempt_result,
786 error_code);
787
Tianjie Xud4777a12017-10-24 14:54:18 -0700788 int64_t current_bytes_downloaded =
789 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
790 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
791 current_bytes_downloaded,
792 0,
793 DownloadSource::kNumDownloadSources,
794 metrics::DownloadErrorCode::kUnset,
795 metrics::ConnectionType::kUnset);
796
Tianjie Xu90aaa102017-10-10 17:39:03 -0700797 if (error_code == ErrorCode::kSuccess) {
798 int64_t reboot_count =
799 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
800 string build_version;
801 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700802
803 // For android metrics, we only care about the total bytes downloaded
804 // for all sources; for now we assume the only download source is
805 // HttpsServer.
806 int64_t total_bytes_downloaded =
807 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
808 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
809 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
810 total_bytes_downloaded;
811
812 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700813 if (total_bytes_downloaded >= payload_size) {
814 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700815 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700816 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
817 } else {
818 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
819 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700820 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700821
Tianjie Xu90aaa102017-10-10 17:39:03 -0700822 metrics_reporter_->ReportSuccessfulUpdateMetrics(
823 static_cast<int>(attempt_number),
824 0, // update abandoned count
825 payload_type,
826 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700827 num_bytes_downloaded,
828 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700829 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700830 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700831 static_cast<int>(reboot_count),
832 0); // url_switch_count
833 }
834}
835
836void UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
837 string current_boot_id;
838 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
839 // Example: [ro.build.version.incremental]: [4292972]
840 string current_version =
841 android::base::GetProperty("ro.build.version.incremental", "");
842 TEST_AND_RETURN(!current_version.empty());
843
844 // If there's no record of previous version (e.g. due to a data wipe), we
845 // save the info of current boot and skip the metrics report.
846 if (!prefs_->Exists(kPrefsPreviousVersion)) {
847 prefs_->SetString(kPrefsBootId, current_boot_id);
848 prefs_->SetString(kPrefsPreviousVersion, current_version);
849 ClearMetricsPrefs();
850 return;
851 }
852 string previous_version;
853 // update_engine restarted under the same build.
854 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
855 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
856 previous_version == current_version) {
857 string last_boot_id;
858 bool is_reboot = prefs_->Exists(kPrefsBootId) &&
859 (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
860 last_boot_id != current_boot_id);
861 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
862 // set when we start a new update.
863 if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
864 prefs_->SetString(kPrefsBootId, current_boot_id);
865 int64_t reboot_count =
866 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
867 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
868 }
869 return;
870 }
871
872 // Now that the build version changes, report the update metrics.
873 // TODO(xunchang) check the build version is larger than the previous one.
874 prefs_->SetString(kPrefsBootId, current_boot_id);
875 prefs_->SetString(kPrefsPreviousVersion, current_version);
876
877 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
878 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
879 if (previous_attempt_exists) {
880 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
881 }
882
883 metrics_utils::LoadAndReportTimeToReboot(
884 metrics_reporter_.get(), prefs_, clock_.get());
885 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -0800886
887 // Also reset the update progress if the build version has changed.
888 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
889 LOG(WARNING) << "Unable to reset the update progress.";
890 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700891}
892
893// Save the update start time. Reset the reboot count and attempt number if the
894// update isn't a resume; otherwise increment the attempt number.
895void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
896 if (!is_resume) {
897 metrics_utils::SetNumReboots(0, prefs_);
898 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
899 } else {
900 int64_t attempt_number =
901 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
902 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
903 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700904 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
905 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700906}
907
908void UpdateAttempterAndroid::ClearMetricsPrefs() {
909 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700910 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700911 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700912 prefs_->Delete(kPrefsSystemUpdatedMarker);
913 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700914 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700915}
916
Yifan Hongbd47d622019-12-13 14:59:58 -0800917BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
918 return boot_control_->GetCurrentSlot();
919}
920
921BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
922 return GetCurrentSlot() == 0 ? 1 : 0;
923}
924
Yifan Hong6f7e29f2019-12-13 14:41:06 -0800925uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
926 const std::string& metadata_filename,
927 const vector<string>& key_value_pair_headers,
928 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -0800929 DeltaArchiveManifest manifest;
930 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
931 return 0;
932 }
933 std::map<string, string> headers;
934 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
935 return 0;
936 }
937
938 string payload_id = GetPayloadId(headers);
939 uint64_t required_size = 0;
940 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
941 boot_control_,
942 GetTargetSlot(),
943 manifest,
944 payload_id,
945 &required_size)) {
946 if (required_size == 0) {
947 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
948 return 0;
949 } else {
950 LOG(ERROR) << "Insufficient space for payload: " << required_size
951 << " bytes";
952 return required_size;
953 }
954 }
955
956 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -0800957 return 0;
958}
959
Yifan Hong40bb0d02020-02-24 17:33:14 -0800960void UpdateAttempterAndroid::CleanupSuccessfulUpdate(
961 std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
Yifan Hong2236ea02019-12-13 16:11:22 -0800962 brillo::ErrorPtr* error) {
Yifan Hong40bb0d02020-02-24 17:33:14 -0800963 if (cleanup_previous_update_code_.has_value()) {
964 LOG(INFO) << "CleanupSuccessfulUpdate has previously completed with "
965 << utils::ErrorCodeToString(*cleanup_previous_update_code_);
966 if (callback) {
967 callback->OnCleanupComplete(
968 static_cast<int32_t>(*cleanup_previous_update_code_));
969 }
970 return;
Yifan Hong4f611562020-01-15 23:41:33 -0800971 }
Yifan Hong40bb0d02020-02-24 17:33:14 -0800972 if (callback) {
973 auto callback_ptr = callback.get();
974 cleanup_previous_update_callbacks_.emplace_back(std::move(callback));
975 callback_ptr->RegisterForDeathNotifications(
976 base::Bind(&UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback,
977 base::Unretained(this),
978 base::Unretained(callback_ptr)));
979 }
980 ScheduleCleanupPreviousUpdate();
Yifan Hong2236ea02019-12-13 16:11:22 -0800981}
982
Yifan Hong90965502020-02-19 15:22:47 -0800983void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
984 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
985 // is in progress, skip enqueueing the action.
986 if (processor_->IsRunning()) {
987 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
988 << "be done when the current update finishes.";
989 return;
990 }
991 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
992 auto action =
993 boot_control_->GetDynamicPartitionControl()
994 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
995 processor_->EnqueueAction(std::move(action));
996 processor_->set_delegate(this);
997 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
998 processor_->StartProcessing();
999}
1000
Yifan Hong40bb0d02020-02-24 17:33:14 -08001001void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {
1002 for (auto&& callback : cleanup_previous_update_callbacks_) {
1003 callback->OnCleanupProgressUpdate(progress);
1004 }
1005}
1006
1007void UpdateAttempterAndroid::NotifyCleanupPreviousUpdateCallbacksAndClear() {
1008 CHECK(cleanup_previous_update_code_.has_value());
1009 for (auto&& callback : cleanup_previous_update_callbacks_) {
1010 callback->OnCleanupComplete(
1011 static_cast<int32_t>(*cleanup_previous_update_code_));
1012 }
1013 cleanup_previous_update_callbacks_.clear();
1014}
1015
1016void UpdateAttempterAndroid::RemoveCleanupPreviousUpdateCallback(
1017 CleanupSuccessfulUpdateCallbackInterface* callback) {
1018 auto end_it =
1019 std::remove_if(cleanup_previous_update_callbacks_.begin(),
1020 cleanup_previous_update_callbacks_.end(),
1021 [&](const auto& e) { return e.get() == callback; });
1022 cleanup_previous_update_callbacks_.erase(
1023 end_it, cleanup_previous_update_callbacks_.end());
1024}
Yifan Hong90965502020-02-19 15:22:47 -08001025
Alex Deymo5e3ea272016-01-28 13:42:23 -08001026} // namespace chromeos_update_engine