blob: a8a59536f9a6f7412a4bf3218bd0634e8da3f85f [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
34#include "update_engine/common/constants.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080035#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070036#include "update_engine/common/file_fetcher.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080037#include "update_engine/common/utils.h"
Alex Deymo03a4de72016-07-20 16:08:23 -070038#include "update_engine/daemon_state_interface.h"
Tianjie Xud4c5deb2017-10-24 11:17:03 -070039#include "update_engine/metrics_reporter_interface.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070040#include "update_engine/metrics_utils.h"
Alex Deymo87792ea2016-07-25 15:40:36 -070041#include "update_engine/network_selector.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070042#include "update_engine/payload_consumer/certificate_parser_interface.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080043#include "update_engine/payload_consumer/delta_performer.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080044#include "update_engine/payload_consumer/download_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080045#include "update_engine/payload_consumer/file_descriptor.h"
46#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080047#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080048#include "update_engine/payload_consumer/payload_constants.h"
49#include "update_engine/payload_consumer/payload_metadata.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070050#include "update_engine/payload_consumer/payload_verifier.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080051#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070052#include "update_engine/update_boot_flags_action.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080053#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080054
Alex Deymo14c0da82016-07-20 16:45:45 -070055#ifndef _UE_SIDELOAD
56// Do not include support for external HTTP(s) urls when building
57// update_engine_sideload.
58#include "update_engine/libcurl_http_fetcher.h"
59#endif
60
Kyeongkab.Nam500ca132019-06-26 13:48:07 +090061using android::base::unique_fd;
Alex Deymo5e3ea272016-01-28 13:42:23 -080062using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070063using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080064using base::TimeDelta;
65using base::TimeTicks;
66using std::shared_ptr;
67using std::string;
68using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070069using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080070
71namespace chromeos_update_engine {
72
73namespace {
74
Alex Deymo0d298542016-03-30 18:31:49 -070075// Minimum threshold to broadcast an status update in progress and time.
76const double kBroadcastThresholdProgress = 0.01; // 1%
77const int kBroadcastThresholdSeconds = 10;
78
Alex Deymo5e3ea272016-01-28 13:42:23 -080079const char* const kErrorDomain = "update_engine";
80// TODO(deymo): Convert the different errors to a numeric value to report them
81// back on the service error.
82const char* const kGenericError = "generic_error";
83
84// Log and set the error on the passed ErrorPtr.
85bool LogAndSetError(brillo::ErrorPtr* error,
Jakub Pawlowski7e1dcf72018-07-26 00:29:42 -070086 const base::Location& location,
Alex Deymo5e3ea272016-01-28 13:42:23 -080087 const string& reason) {
88 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
89 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
90 << reason;
91 return false;
92}
93
Sen Jiangfe522822017-10-31 15:14:11 -070094bool GetHeaderAsBool(const string& header, bool default_value) {
95 int value = 0;
96 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
97 return value == 1;
98 return default_value;
99}
100
Yifan Hongbd47d622019-12-13 14:59:58 -0800101bool ParseKeyValuePairHeaders(const vector<string>& key_value_pair_headers,
102 std::map<string, string>* headers,
103 brillo::ErrorPtr* error) {
104 for (const string& key_value_pair : key_value_pair_headers) {
105 string key;
106 string value;
107 if (!brillo::string_utils::SplitAtFirst(
108 key_value_pair, "=", &key, &value, false)) {
109 return LogAndSetError(
110 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
111 }
112 if (!headers->emplace(key, value).second)
113 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
114 }
115 return true;
116}
117
118// Unique identifier for the payload. An empty string means that the payload
119// can't be resumed.
120string GetPayloadId(const std::map<string, string>& headers) {
121 return (headers.count(kPayloadPropertyFileHash)
122 ? headers.at(kPayloadPropertyFileHash)
123 : "") +
124 (headers.count(kPayloadPropertyMetadataHash)
125 ? headers.at(kPayloadPropertyMetadataHash)
126 : "");
127}
128
Alex Deymo5e3ea272016-01-28 13:42:23 -0800129} // namespace
130
131UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700132 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800133 PrefsInterface* prefs,
134 BootControlInterface* boot_control,
135 HardwareInterface* hardware)
136 : daemon_state_(daemon_state),
137 prefs_(prefs),
138 boot_control_(boot_control),
139 hardware_(hardware),
Tianjie Xu1b661142017-09-28 14:03:42 -0700140 processor_(new ActionProcessor()),
Tianjie Xud4c5deb2017-10-24 11:17:03 -0700141 clock_(new Clock()) {
142 metrics_reporter_ = metrics::CreateMetricsReporter();
Alex Deymo87792ea2016-07-25 15:40:36 -0700143 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800144}
145
146UpdateAttempterAndroid::~UpdateAttempterAndroid() {
147 // Release ourselves as the ActionProcessor's delegate to prevent
148 // re-scheduling the updates due to the processing stopped.
149 processor_->set_delegate(nullptr);
150}
151
152void UpdateAttempterAndroid::Init() {
153 // In case of update_engine restart without a reboot we need to restore the
154 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700155 if (UpdateCompletedOnThisBoot()) {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800156 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700157 } else {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800158 SetStatusAndNotify(UpdateStatus::IDLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700159 UpdatePrefsAndReportUpdateMetricsOnReboot();
Yifan Hong90965502020-02-19 15:22:47 -0800160 ScheduleCleanupPreviousUpdate();
Tianjie Xu90aaa102017-10-10 17:39:03 -0700161 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800162}
163
164bool UpdateAttempterAndroid::ApplyPayload(
165 const string& payload_url,
166 int64_t payload_offset,
167 int64_t payload_size,
168 const vector<string>& key_value_pair_headers,
169 brillo::ErrorPtr* error) {
170 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
171 return LogAndSetError(
172 error, FROM_HERE, "An update already applied, waiting for reboot");
173 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700174 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800175 return LogAndSetError(
176 error, FROM_HERE, "Already processing an update, cancel it first.");
177 }
178 DCHECK(status_ == UpdateStatus::IDLE);
179
Alex Deymo218397f2016-02-04 23:55:10 -0800180 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800181 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
182 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800183 }
184
Yifan Hongbd47d622019-12-13 14:59:58 -0800185 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800186
187 // Setup the InstallPlan based on the request.
188 install_plan_ = InstallPlan();
189
190 install_plan_.download_url = payload_url;
191 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800192 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800193 InstallPlan::Payload payload;
194 payload.size = payload_size;
195 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800196 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800197 &payload.size)) {
198 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800199 }
200 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700201 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800202 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700203 LOG(WARNING) << "Unable to decode base64 file hash: "
204 << headers[kPayloadPropertyFileHash];
205 }
Alex Deymo218397f2016-02-04 23:55:10 -0800206 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800207 &payload.metadata_size)) {
208 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800209 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700210 // The |payload.type| is not used anymore since minor_version 3.
211 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800212 install_plan_.payloads.push_back(payload);
213
Alex Deymo5e3ea272016-01-28 13:42:23 -0800214 // The |public_key_rsa| key would override the public key stored on disk.
215 install_plan_.public_key_rsa = "";
216
217 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
218 install_plan_.is_resume = !payload_id.empty() &&
219 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
220 if (!install_plan_.is_resume) {
Yifan Hong55c2bfe2020-01-13 17:01:19 -0800221 // No need to reset dynamic_partititon_metadata_updated. If previous calls
222 // to AllocateSpaceForPayload uses the same payload_id, reuse preallocated
223 // space. Otherwise, DeltaPerformer re-allocates space when the payload is
224 // applied.
225 if (!DeltaPerformer::ResetUpdateProgress(
226 prefs_,
227 false /* quick */,
228 true /* skip_dynamic_partititon_metadata_updated */)) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800229 LOG(WARNING) << "Unable to reset the update progress.";
230 }
231 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
232 LOG(WARNING) << "Unable to save the update check response hash.";
233 }
234 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800235 install_plan_.source_slot = GetCurrentSlot();
236 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700237
Alex Deymofb905d92016-06-03 19:26:58 -0700238 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700239 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
240
241 install_plan_.switch_slot_on_reboot =
242 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
243
Tianjie Xu087de9d2019-11-01 17:11:22 -0700244 install_plan_.run_post_install =
245 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800246
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700247 // Skip writing verity if we're resuming and verity has already been written.
248 install_plan_.write_verity = true;
249 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
250 bool verity_written = false;
251 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
252 verity_written) {
253 install_plan_.write_verity = false;
254 }
255 }
256
Alex Deymo87792ea2016-07-25 15:40:36 -0700257 NetworkId network_id = kDefaultNetworkId;
258 if (!headers[kPayloadPropertyNetworkId].empty()) {
259 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
260 &network_id)) {
261 return LogAndSetError(
262 error,
263 FROM_HERE,
264 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
265 }
266 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700267 return LogAndSetError(
268 error,
269 FROM_HERE,
270 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700271 }
272 }
273
Alex Deymo5e3ea272016-01-28 13:42:23 -0800274 LOG(INFO) << "Using this install plan:";
275 install_plan_.Dump();
276
Amin Hassani667cf7b2018-07-25 14:32:00 -0700277 HttpFetcher* fetcher = nullptr;
278 if (FileFetcher::SupportedUrl(payload_url)) {
279 DLOG(INFO) << "Using FileFetcher for file URL.";
280 fetcher = new FileFetcher();
281 } else {
282#ifdef _UE_SIDELOAD
283 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
284#else
285 LibcurlHttpFetcher* libcurl_fetcher =
286 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
287 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
288 fetcher = libcurl_fetcher;
289#endif // _UE_SIDELOAD
290 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800291 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800292 if (!headers[kPayloadPropertyAuthorization].empty())
293 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
294 if (!headers[kPayloadPropertyUserAgent].empty())
295 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
296
Amin Hassani667cf7b2018-07-25 14:32:00 -0700297 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800298
Alex Deymo5e3ea272016-01-28 13:42:23 -0800299 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700300
301 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
302 // TODO(xunchang) report the metrics for unresumable updates
303
Amin Hassani667cf7b2018-07-25 14:32:00 -0700304 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800305 return true;
306}
307
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900308bool UpdateAttempterAndroid::ApplyPayload(
309 int fd,
310 int64_t payload_offset,
311 int64_t payload_size,
312 const vector<string>& key_value_pair_headers,
313 brillo::ErrorPtr* error) {
314 payload_fd_.reset(dup(fd));
315 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
316
317 return ApplyPayload(
318 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
319}
320
Alex Deymo5e3ea272016-01-28 13:42:23 -0800321bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700322 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800323 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
324 processor_->SuspendProcessing();
325 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800326}
327
328bool UpdateAttempterAndroid::ResumeUpdate(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 resume.");
331 processor_->ResumeProcessing();
332 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800333}
334
335bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700336 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800337 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800338 processor_->StopProcessing();
339 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800340}
341
Alex Deymo3b678db2016-02-09 11:50:06 -0800342bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
343 LOG(INFO) << "Attempting to reset state from "
344 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
345
346 switch (status_) {
347 case UpdateStatus::IDLE:
348 return true;
349
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800350 case UpdateStatus::UPDATED_NEED_REBOOT: {
Alex Deymo3b678db2016-02-09 11:50:06 -0800351 // Remove the reboot marker so that if the machine is rebooted
352 // after resetting to idle state, it doesn't go back to
353 // UpdateStatus::UPDATED_NEED_REBOOT state.
354 bool ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700355 ClearMetricsPrefs();
Alex Deymo3b678db2016-02-09 11:50:06 -0800356
357 // Update the boot flags so the current slot has higher priority.
Yifan Hongbd47d622019-12-13 14:59:58 -0800358 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot()))
Alex Deymo3b678db2016-02-09 11:50:06 -0800359 ret_value = false;
360
Alex Deymo52590332016-11-29 18:29:13 -0800361 // Mark the current slot as successful again, since marking it as active
362 // may reset the successful bit. We ignore the result of whether marking
363 // the current slot as successful worked.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800364 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {})))
Alex Deymo52590332016-11-29 18:29:13 -0800365 ret_value = false;
366
Tianjie Xud6aa91f2019-11-14 11:55:10 -0800367 // Resets the warm reset property since we won't switch the slot.
368 hardware_->SetWarmReset(false);
369
Alex Deymo3b678db2016-02-09 11:50:06 -0800370 if (!ret_value) {
371 return LogAndSetError(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800372 error, FROM_HERE, "Failed to reset the status to ");
Alex Deymo3b678db2016-02-09 11:50:06 -0800373 }
374
375 SetStatusAndNotify(UpdateStatus::IDLE);
376 LOG(INFO) << "Reset status successful";
377 return true;
378 }
379
380 default:
381 return LogAndSetError(
382 error,
383 FROM_HERE,
384 "Reset not allowed in this state. Cancel the ongoing update first");
385 }
386}
387
Yifan Hongbd47d622019-12-13 14:59:58 -0800388bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
389 const std::string& metadata_filename,
390 DeltaArchiveManifest* manifest,
391 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800392 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
393 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
394 return LogAndSetError(
395 error, FROM_HERE, "Failed to open " + metadata_filename);
396 }
397 brillo::Blob metadata(kMaxPayloadHeaderSize);
398 if (!fd->Read(metadata.data(), metadata.size())) {
399 return LogAndSetError(
400 error,
401 FROM_HERE,
402 "Failed to read payload header from " + metadata_filename);
403 }
404 ErrorCode errorcode;
405 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700406 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800407 MetadataParseResult::kSuccess) {
408 return LogAndSetError(error,
409 FROM_HERE,
410 "Failed to parse payload header: " +
411 utils::ErrorCodeToString(errorcode));
412 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700413 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
414 payload_metadata.GetMetadataSignatureSize();
415 if (metadata_size < kMaxPayloadHeaderSize ||
416 metadata_size >
417 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800418 return LogAndSetError(
419 error,
420 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700421 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800422 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700423 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800424 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
425 metadata.size() - kMaxPayloadHeaderSize)) {
426 return LogAndSetError(
427 error,
428 FROM_HERE,
429 "Failed to read metadata and signature from " + metadata_filename);
430 }
431 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800432
Tianjie Xu7a78d632019-10-08 16:32:39 -0700433 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
434 constants::kUpdateCertificatesPath);
435 if (!payload_verifier) {
436 return LogAndSetError(error,
437 FROM_HERE,
438 "Failed to create the payload verifier from " +
439 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800440 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700441 errorcode = payload_metadata.ValidateMetadataSignature(
442 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800443 if (errorcode != ErrorCode::kSuccess) {
444 return LogAndSetError(error,
445 FROM_HERE,
446 "Failed to validate metadata signature: " +
447 utils::ErrorCodeToString(errorcode));
448 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800449 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800450 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
451 }
452
Yifan Hongbd47d622019-12-13 14:59:58 -0800453 return true;
454}
455
456bool UpdateAttempterAndroid::VerifyPayloadApplicable(
457 const std::string& metadata_filename, brillo::ErrorPtr* error) {
458 DeltaArchiveManifest manifest;
459 TEST_AND_RETURN_FALSE(
460 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
461
462 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
463 ErrorCode errorcode;
464
465 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800466 for (const PartitionUpdate& partition : manifest.partitions()) {
467 if (!partition.has_old_partition_info())
468 continue;
469 string partition_path;
470 if (!boot_control_->GetPartitionDevice(
471 partition.partition_name(), current_slot, &partition_path)) {
472 return LogAndSetError(
473 error,
474 FROM_HERE,
475 "Failed to get partition device for " + partition.partition_name());
476 }
477 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
478 return LogAndSetError(
479 error, FROM_HERE, "Failed to open " + partition_path);
480 }
481 for (const InstallOperation& operation : partition.operations()) {
482 if (!operation.has_src_sha256_hash())
483 continue;
484 brillo::Blob source_hash;
485 if (!fd_utils::ReadAndHashExtents(fd,
486 operation.src_extents(),
487 manifest.block_size(),
488 &source_hash)) {
489 return LogAndSetError(
490 error, FROM_HERE, "Failed to hash " + partition_path);
491 }
492 if (!DeltaPerformer::ValidateSourceHash(
493 source_hash, operation, fd, &errorcode)) {
494 return false;
495 }
496 }
497 fd->Close();
498 }
499 return true;
500}
501
Alex Deymo5e3ea272016-01-28 13:42:23 -0800502void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
503 ErrorCode code) {
504 LOG(INFO) << "Processing Done.";
505
Yifan Hong90965502020-02-19 15:22:47 -0800506 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
507 TerminateUpdateAndNotify(code);
508 return;
509 }
510
Alex Deymo5990bf32016-07-19 17:01:41 -0700511 switch (code) {
512 case ErrorCode::kSuccess:
513 // Update succeeded.
514 WriteUpdateCompletedMarker();
515 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800516
Alex Deymo5990bf32016-07-19 17:01:41 -0700517 LOG(INFO) << "Update successfully applied, waiting to reboot.";
518 break;
519
520 case ErrorCode::kFilesystemCopierError:
521 case ErrorCode::kNewRootfsVerificationError:
522 case ErrorCode::kNewKernelVerificationError:
523 case ErrorCode::kFilesystemVerifierError:
524 case ErrorCode::kDownloadStateInitializationError:
525 // Reset the ongoing update for these errors so it starts from the
526 // beginning next time.
527 DeltaPerformer::ResetUpdateProgress(prefs_, false);
528 LOG(INFO) << "Resetting update progress.";
529 break;
530
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700531 case ErrorCode::kPayloadTimestampError:
532 // SafetyNet logging, b/36232423
533 android_errorWriteLog(0x534e4554, "36232423");
534 break;
535
Alex Deymo5990bf32016-07-19 17:01:41 -0700536 default:
537 // Ignore all other error codes.
538 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700539 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800540
541 TerminateUpdateAndNotify(code);
542}
543
544void UpdateAttempterAndroid::ProcessingStopped(
545 const ActionProcessor* processor) {
546 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
547}
548
549void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
550 AbstractAction* action,
551 ErrorCode code) {
552 // Reset download progress regardless of whether or not the download
553 // action succeeded.
554 const string type = action->Type();
555 if (type == DownloadAction::StaticType()) {
Alex Deymo0d298542016-03-30 18:31:49 -0700556 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800557 }
Sen Jiangfe522822017-10-31 15:14:11 -0700558 if (type == PostinstallRunnerAction::StaticType()) {
559 bool succeeded =
560 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
561 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
562 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800563 if (code != ErrorCode::kSuccess) {
564 // If an action failed, the ActionProcessor will cancel the whole thing.
565 return;
566 }
567 if (type == DownloadAction::StaticType()) {
568 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700569 } else if (type == FilesystemVerifierAction::StaticType()) {
570 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800571 }
572}
573
574void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
575 uint64_t bytes_received,
576 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700577 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800578 if (total)
579 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700580 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800581 download_progress_ = progress;
582 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700583 } else {
584 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800585 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700586
587 // Update the bytes downloaded in prefs.
588 int64_t current_bytes_downloaded =
589 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
590 int64_t total_bytes_downloaded =
591 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
592 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
593 current_bytes_downloaded + bytes_progressed);
594 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
595 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800596}
597
598bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
599 // TODO(deymo): Notify the DownloadAction that it should cancel the update
600 // download.
601 return false;
602}
603
604void UpdateAttempterAndroid::DownloadComplete() {
605 // Nothing needs to be done when the download completes.
606}
607
Alex Deymo0d298542016-03-30 18:31:49 -0700608void UpdateAttempterAndroid::ProgressUpdate(double progress) {
609 // Self throttle based on progress. Also send notifications if progress is
610 // too slow.
611 if (progress == 1.0 ||
612 progress - download_progress_ >= kBroadcastThresholdProgress ||
613 TimeTicks::Now() - last_notify_time_ >=
614 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
615 download_progress_ = progress;
616 SetStatusAndNotify(status_);
617 }
618}
619
Alex Deymo5e3ea272016-01-28 13:42:23 -0800620void UpdateAttempterAndroid::ScheduleProcessingStart() {
621 LOG(INFO) << "Scheduling an action processor start.";
622 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700623 FROM_HERE,
624 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
625 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800626}
627
628void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
629 if (status_ == UpdateStatus::IDLE) {
630 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
631 return;
632 }
633
Yifan Hong90965502020-02-19 15:22:47 -0800634 if (status_ == UpdateStatus::CLEANUP_PREVIOUS_UPDATE) {
635 LOG(INFO) << "Terminating cleanup previous update.";
636 SetStatusAndNotify(UpdateStatus::IDLE);
637 return;
638 }
639
Yifan Hong9194ce82019-11-07 11:03:42 -0800640 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700641
Alex Deymo0d298542016-03-30 18:31:49 -0700642 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800643 UpdateStatus new_status =
644 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
645 : UpdateStatus::IDLE);
646 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900647 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800648
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700649 // The network id is only applicable to one download attempt and once it's
650 // done the network id should not be re-used anymore.
651 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
652 LOG(WARNING) << "Unable to unbind network.";
653 }
654
Alex Deymo5e3ea272016-01-28 13:42:23 -0800655 for (auto observer : daemon_state_->service_observers())
656 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700657
Tianjie Xu90aaa102017-10-10 17:39:03 -0700658 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
659 ClearMetricsPrefs();
660 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800661 // We should only reset the PayloadAttemptNumber if the update succeeds, or
662 // we switch to a different payload.
663 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700664 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700665 // Clear the total bytes downloaded if and only if the update succeeds.
666 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700667 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800668}
669
670void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
671 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700672 size_t payload_size =
673 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700674 UpdateEngineStatus status_to_send = {.status = status_,
675 .progress = download_progress_,
676 .new_size_bytes = payload_size};
677
Alex Deymo5e3ea272016-01-28 13:42:23 -0800678 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700679 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800680 }
681 last_notify_time_ = TimeTicks::Now();
682}
683
Amin Hassani667cf7b2018-07-25 14:32:00 -0700684void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800685 CHECK(!processor_->IsRunning());
686 processor_->set_delegate(this);
687
688 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700689 auto update_boot_flags_action =
690 std::make_unique<UpdateBootFlagsAction>(boot_control_);
691 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
692 auto download_action =
693 std::make_unique<DownloadAction>(prefs_,
694 boot_control_,
695 hardware_,
696 nullptr, // system_state, not used.
697 fetcher, // passes ownership
698 true /* interactive */);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800699 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700700 download_action->set_base_offset(base_offset_);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700701 auto filesystem_verifier_action =
702 std::make_unique<FilesystemVerifierAction>();
703 auto postinstall_runner_action =
704 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Alex Deymob6eef732016-06-10 12:58:11 -0700705 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800706
Alex Deymo5e3ea272016-01-28 13:42:23 -0800707 // Bond them together. We have to use the leaf-types when calling
708 // BondActions().
709 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700710 BondActions(download_action.get(), filesystem_verifier_action.get());
711 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800712 postinstall_runner_action.get());
713
Amin Hassani667cf7b2018-07-25 14:32:00 -0700714 processor_->EnqueueAction(std::move(update_boot_flags_action));
715 processor_->EnqueueAction(std::move(install_plan_action));
716 processor_->EnqueueAction(std::move(download_action));
717 processor_->EnqueueAction(std::move(filesystem_verifier_action));
718 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800719}
720
Alex Deymo5e3ea272016-01-28 13:42:23 -0800721bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
722 string boot_id;
723 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
724 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
725 return true;
726}
727
728bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
729 // In case of an update_engine restart without a reboot, we stored the boot_id
730 // when the update was completed by setting a pref, so we can check whether
731 // the last update was on this boot or a previous one.
732 string boot_id;
733 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
734
735 string update_completed_on_boot_id;
736 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
737 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
738 &update_completed_on_boot_id) &&
739 update_completed_on_boot_id == boot_id);
740}
741
Tianjie Xu90aaa102017-10-10 17:39:03 -0700742// Collect and report the android metrics when we terminate the update.
743void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
744 ErrorCode error_code) {
745 int64_t attempt_number =
746 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
747 PayloadType payload_type = kPayloadTypeFull;
748 int64_t payload_size = 0;
749 for (const auto& p : install_plan_.payloads) {
750 if (p.type == InstallPayloadType::kDelta)
751 payload_type = kPayloadTypeDelta;
752 payload_size += p.size;
753 }
754
755 metrics::AttemptResult attempt_result =
756 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700757 Time boot_time_start = Time::FromInternalValue(
758 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
759 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700760 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700761 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
762 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700763
764 metrics_reporter_->ReportUpdateAttemptMetrics(
765 nullptr, // system_state
766 static_cast<int>(attempt_number),
767 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700768 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700769 duration_uptime,
770 payload_size,
771 attempt_result,
772 error_code);
773
Tianjie Xud4777a12017-10-24 14:54:18 -0700774 int64_t current_bytes_downloaded =
775 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
776 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
777 current_bytes_downloaded,
778 0,
779 DownloadSource::kNumDownloadSources,
780 metrics::DownloadErrorCode::kUnset,
781 metrics::ConnectionType::kUnset);
782
Tianjie Xu90aaa102017-10-10 17:39:03 -0700783 if (error_code == ErrorCode::kSuccess) {
784 int64_t reboot_count =
785 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
786 string build_version;
787 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700788
789 // For android metrics, we only care about the total bytes downloaded
790 // for all sources; for now we assume the only download source is
791 // HttpsServer.
792 int64_t total_bytes_downloaded =
793 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
794 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
795 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
796 total_bytes_downloaded;
797
798 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700799 if (total_bytes_downloaded >= payload_size) {
800 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700801 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700802 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
803 } else {
804 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
805 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700806 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700807
Tianjie Xu90aaa102017-10-10 17:39:03 -0700808 metrics_reporter_->ReportSuccessfulUpdateMetrics(
809 static_cast<int>(attempt_number),
810 0, // update abandoned count
811 payload_type,
812 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700813 num_bytes_downloaded,
814 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700815 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700816 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700817 static_cast<int>(reboot_count),
818 0); // url_switch_count
819 }
820}
821
822void UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
823 string current_boot_id;
824 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
825 // Example: [ro.build.version.incremental]: [4292972]
826 string current_version =
827 android::base::GetProperty("ro.build.version.incremental", "");
828 TEST_AND_RETURN(!current_version.empty());
829
830 // If there's no record of previous version (e.g. due to a data wipe), we
831 // save the info of current boot and skip the metrics report.
832 if (!prefs_->Exists(kPrefsPreviousVersion)) {
833 prefs_->SetString(kPrefsBootId, current_boot_id);
834 prefs_->SetString(kPrefsPreviousVersion, current_version);
835 ClearMetricsPrefs();
836 return;
837 }
838 string previous_version;
839 // update_engine restarted under the same build.
840 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
841 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
842 previous_version == current_version) {
843 string last_boot_id;
844 bool is_reboot = prefs_->Exists(kPrefsBootId) &&
845 (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
846 last_boot_id != current_boot_id);
847 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
848 // set when we start a new update.
849 if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
850 prefs_->SetString(kPrefsBootId, current_boot_id);
851 int64_t reboot_count =
852 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
853 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
854 }
855 return;
856 }
857
858 // Now that the build version changes, report the update metrics.
859 // TODO(xunchang) check the build version is larger than the previous one.
860 prefs_->SetString(kPrefsBootId, current_boot_id);
861 prefs_->SetString(kPrefsPreviousVersion, current_version);
862
863 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
864 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
865 if (previous_attempt_exists) {
866 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
867 }
868
869 metrics_utils::LoadAndReportTimeToReboot(
870 metrics_reporter_.get(), prefs_, clock_.get());
871 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -0800872
873 // Also reset the update progress if the build version has changed.
874 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
875 LOG(WARNING) << "Unable to reset the update progress.";
876 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700877}
878
879// Save the update start time. Reset the reboot count and attempt number if the
880// update isn't a resume; otherwise increment the attempt number.
881void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
882 if (!is_resume) {
883 metrics_utils::SetNumReboots(0, prefs_);
884 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
885 } else {
886 int64_t attempt_number =
887 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
888 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
889 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700890 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
891 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700892}
893
894void UpdateAttempterAndroid::ClearMetricsPrefs() {
895 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700896 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700897 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700898 prefs_->Delete(kPrefsSystemUpdatedMarker);
899 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700900 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700901}
902
Yifan Hongbd47d622019-12-13 14:59:58 -0800903BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
904 return boot_control_->GetCurrentSlot();
905}
906
907BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
908 return GetCurrentSlot() == 0 ? 1 : 0;
909}
910
Yifan Hong6f7e29f2019-12-13 14:41:06 -0800911uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
912 const std::string& metadata_filename,
913 const vector<string>& key_value_pair_headers,
914 brillo::ErrorPtr* error) {
Yifan Hong65613032020-01-09 17:52:13 -0800915 DeltaArchiveManifest manifest;
916 if (!VerifyPayloadParseManifest(metadata_filename, &manifest, error)) {
917 return 0;
918 }
919 std::map<string, string> headers;
920 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
921 return 0;
922 }
923
924 string payload_id = GetPayloadId(headers);
925 uint64_t required_size = 0;
926 if (!DeltaPerformer::PreparePartitionsForUpdate(prefs_,
927 boot_control_,
928 GetTargetSlot(),
929 manifest,
930 payload_id,
931 &required_size)) {
932 if (required_size == 0) {
933 LogAndSetError(error, FROM_HERE, "Failed to allocate space for payload.");
934 return 0;
935 } else {
936 LOG(ERROR) << "Insufficient space for payload: " << required_size
937 << " bytes";
938 return required_size;
939 }
940 }
941
942 LOG(INFO) << "Successfully allocated space for payload.";
Yifan Hong6f7e29f2019-12-13 14:41:06 -0800943 return 0;
944}
945
Yifan Hong2236ea02019-12-13 16:11:22 -0800946int32_t UpdateAttempterAndroid::CleanupSuccessfulUpdate(
947 brillo::ErrorPtr* error) {
Yifan Hong4f611562020-01-15 23:41:33 -0800948 ErrorCode error_code =
949 boot_control_->GetDynamicPartitionControl()->CleanupSuccessfulUpdate();
950 if (error_code == ErrorCode::kSuccess) {
951 LOG(INFO) << "Previous update is merged and cleaned up successfully.";
952 } else {
953 LOG(ERROR) << "CleanupSuccessfulUpdate failed with "
954 << utils::ErrorCodeToString(error_code);
955 }
956 return static_cast<int32_t>(error_code);
Yifan Hong2236ea02019-12-13 16:11:22 -0800957}
958
Yifan Hong90965502020-02-19 15:22:47 -0800959void UpdateAttempterAndroid::ScheduleCleanupPreviousUpdate() {
960 // If a previous CleanupSuccessfulUpdate call has not finished, or an update
961 // is in progress, skip enqueueing the action.
962 if (processor_->IsRunning()) {
963 LOG(INFO) << "Already processing an update. CleanupPreviousUpdate should "
964 << "be done when the current update finishes.";
965 return;
966 }
967 LOG(INFO) << "Scheduling CleanupPreviousUpdateAction.";
968 auto action =
969 boot_control_->GetDynamicPartitionControl()
970 ->GetCleanupPreviousUpdateAction(boot_control_, prefs_, this);
971 processor_->EnqueueAction(std::move(action));
972 processor_->set_delegate(this);
973 SetStatusAndNotify(UpdateStatus::CLEANUP_PREVIOUS_UPDATE);
974 processor_->StartProcessing();
975}
976
977void UpdateAttempterAndroid::OnCleanupProgressUpdate(double progress) {}
978
Alex Deymo5e3ea272016-01-28 13:42:23 -0800979} // namespace chromeos_update_engine