blob: 263498b551621c96138fa7c532e6930ef55ffaf5 [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();
160 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800161}
162
163bool UpdateAttempterAndroid::ApplyPayload(
164 const string& payload_url,
165 int64_t payload_offset,
166 int64_t payload_size,
167 const vector<string>& key_value_pair_headers,
168 brillo::ErrorPtr* error) {
169 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
170 return LogAndSetError(
171 error, FROM_HERE, "An update already applied, waiting for reboot");
172 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700173 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800174 return LogAndSetError(
175 error, FROM_HERE, "Already processing an update, cancel it first.");
176 }
177 DCHECK(status_ == UpdateStatus::IDLE);
178
Alex Deymo218397f2016-02-04 23:55:10 -0800179 std::map<string, string> headers;
Yifan Hongbd47d622019-12-13 14:59:58 -0800180 if (!ParseKeyValuePairHeaders(key_value_pair_headers, &headers, error)) {
181 return false;
Alex Deymo218397f2016-02-04 23:55:10 -0800182 }
183
Yifan Hongbd47d622019-12-13 14:59:58 -0800184 string payload_id = GetPayloadId(headers);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800185
186 // Setup the InstallPlan based on the request.
187 install_plan_ = InstallPlan();
188
189 install_plan_.download_url = payload_url;
190 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800191 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800192 InstallPlan::Payload payload;
193 payload.size = payload_size;
194 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800195 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800196 &payload.size)) {
197 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800198 }
199 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700200 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800201 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700202 LOG(WARNING) << "Unable to decode base64 file hash: "
203 << headers[kPayloadPropertyFileHash];
204 }
Alex Deymo218397f2016-02-04 23:55:10 -0800205 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800206 &payload.metadata_size)) {
207 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800208 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700209 // The |payload.type| is not used anymore since minor_version 3.
210 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800211 install_plan_.payloads.push_back(payload);
212
Alex Deymo5e3ea272016-01-28 13:42:23 -0800213 // The |public_key_rsa| key would override the public key stored on disk.
214 install_plan_.public_key_rsa = "";
215
216 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
217 install_plan_.is_resume = !payload_id.empty() &&
218 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
219 if (!install_plan_.is_resume) {
220 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
221 LOG(WARNING) << "Unable to reset the update progress.";
222 }
223 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
224 LOG(WARNING) << "Unable to save the update check response hash.";
225 }
226 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800227 install_plan_.source_slot = GetCurrentSlot();
228 install_plan_.target_slot = GetTargetSlot();
Alex Deymofb905d92016-06-03 19:26:58 -0700229
Alex Deymofb905d92016-06-03 19:26:58 -0700230 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700231 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
232
233 install_plan_.switch_slot_on_reboot =
234 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
235
236 install_plan_.run_post_install = true;
237 // Optionally skip post install if and only if:
238 // a) we're resuming
239 // b) post install has already succeeded before
240 // c) RUN_POST_INSTALL is set to 0.
241 if (install_plan_.is_resume && prefs_->Exists(kPrefsPostInstallSucceeded)) {
242 bool post_install_succeeded = false;
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700243 if (prefs_->GetBoolean(kPrefsPostInstallSucceeded,
244 &post_install_succeeded) &&
245 post_install_succeeded) {
Sen Jiangfe522822017-10-31 15:14:11 -0700246 install_plan_.run_post_install =
247 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
248 }
249 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800250
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700251 // Skip writing verity if we're resuming and verity has already been written.
252 install_plan_.write_verity = true;
253 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
254 bool verity_written = false;
255 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
256 verity_written) {
257 install_plan_.write_verity = false;
258 }
259 }
260
Alex Deymo87792ea2016-07-25 15:40:36 -0700261 NetworkId network_id = kDefaultNetworkId;
262 if (!headers[kPayloadPropertyNetworkId].empty()) {
263 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
264 &network_id)) {
265 return LogAndSetError(
266 error,
267 FROM_HERE,
268 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
269 }
270 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700271 return LogAndSetError(
272 error,
273 FROM_HERE,
274 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700275 }
276 }
277
Alex Deymo5e3ea272016-01-28 13:42:23 -0800278 LOG(INFO) << "Using this install plan:";
279 install_plan_.Dump();
280
Amin Hassani667cf7b2018-07-25 14:32:00 -0700281 HttpFetcher* fetcher = nullptr;
282 if (FileFetcher::SupportedUrl(payload_url)) {
283 DLOG(INFO) << "Using FileFetcher for file URL.";
284 fetcher = new FileFetcher();
285 } else {
286#ifdef _UE_SIDELOAD
287 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
288#else
289 LibcurlHttpFetcher* libcurl_fetcher =
290 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
291 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
292 fetcher = libcurl_fetcher;
293#endif // _UE_SIDELOAD
294 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800295 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800296 if (!headers[kPayloadPropertyAuthorization].empty())
297 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
298 if (!headers[kPayloadPropertyUserAgent].empty())
299 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
300
Amin Hassani667cf7b2018-07-25 14:32:00 -0700301 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800302
Alex Deymo5e3ea272016-01-28 13:42:23 -0800303 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700304
305 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
306 // TODO(xunchang) report the metrics for unresumable updates
307
Amin Hassani667cf7b2018-07-25 14:32:00 -0700308 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800309 return true;
310}
311
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900312bool UpdateAttempterAndroid::ApplyPayload(
313 int fd,
314 int64_t payload_offset,
315 int64_t payload_size,
316 const vector<string>& key_value_pair_headers,
317 brillo::ErrorPtr* error) {
318 payload_fd_.reset(dup(fd));
319 const string payload_url = "fd://" + std::to_string(payload_fd_.get());
320
321 return ApplyPayload(
322 payload_url, payload_offset, payload_size, key_value_pair_headers, error);
323}
324
Alex Deymo5e3ea272016-01-28 13:42:23 -0800325bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700326 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800327 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
328 processor_->SuspendProcessing();
329 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800330}
331
332bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700333 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800334 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
335 processor_->ResumeProcessing();
336 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800337}
338
339bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700340 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800341 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800342 processor_->StopProcessing();
343 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800344}
345
Alex Deymo3b678db2016-02-09 11:50:06 -0800346bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
347 LOG(INFO) << "Attempting to reset state from "
348 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
349
350 switch (status_) {
351 case UpdateStatus::IDLE:
352 return true;
353
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800354 case UpdateStatus::UPDATED_NEED_REBOOT: {
Alex Deymo3b678db2016-02-09 11:50:06 -0800355 // Remove the reboot marker so that if the machine is rebooted
356 // after resetting to idle state, it doesn't go back to
357 // UpdateStatus::UPDATED_NEED_REBOOT state.
358 bool ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700359 ClearMetricsPrefs();
Alex Deymo3b678db2016-02-09 11:50:06 -0800360
361 // Update the boot flags so the current slot has higher priority.
Yifan Hongbd47d622019-12-13 14:59:58 -0800362 if (!boot_control_->SetActiveBootSlot(GetCurrentSlot()))
Alex Deymo3b678db2016-02-09 11:50:06 -0800363 ret_value = false;
364
Alex Deymo52590332016-11-29 18:29:13 -0800365 // Mark the current slot as successful again, since marking it as active
366 // may reset the successful bit. We ignore the result of whether marking
367 // the current slot as successful worked.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800368 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful) {})))
Alex Deymo52590332016-11-29 18:29:13 -0800369 ret_value = false;
370
Tianjie Xud6aa91f2019-11-14 11:55:10 -0800371 // Resets the warm reset property since we won't switch the slot.
372 hardware_->SetWarmReset(false);
373
Alex Deymo3b678db2016-02-09 11:50:06 -0800374 if (!ret_value) {
375 return LogAndSetError(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800376 error, FROM_HERE, "Failed to reset the status to ");
Alex Deymo3b678db2016-02-09 11:50:06 -0800377 }
378
379 SetStatusAndNotify(UpdateStatus::IDLE);
380 LOG(INFO) << "Reset status successful";
381 return true;
382 }
383
384 default:
385 return LogAndSetError(
386 error,
387 FROM_HERE,
388 "Reset not allowed in this state. Cancel the ongoing update first");
389 }
390}
391
Yifan Hongbd47d622019-12-13 14:59:58 -0800392bool UpdateAttempterAndroid::VerifyPayloadParseManifest(
393 const std::string& metadata_filename,
394 DeltaArchiveManifest* manifest,
395 brillo::ErrorPtr* error) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800396 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
397 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
398 return LogAndSetError(
399 error, FROM_HERE, "Failed to open " + metadata_filename);
400 }
401 brillo::Blob metadata(kMaxPayloadHeaderSize);
402 if (!fd->Read(metadata.data(), metadata.size())) {
403 return LogAndSetError(
404 error,
405 FROM_HERE,
406 "Failed to read payload header from " + metadata_filename);
407 }
408 ErrorCode errorcode;
409 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700410 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800411 MetadataParseResult::kSuccess) {
412 return LogAndSetError(error,
413 FROM_HERE,
414 "Failed to parse payload header: " +
415 utils::ErrorCodeToString(errorcode));
416 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700417 uint64_t metadata_size = payload_metadata.GetMetadataSize() +
418 payload_metadata.GetMetadataSignatureSize();
419 if (metadata_size < kMaxPayloadHeaderSize ||
420 metadata_size >
421 static_cast<uint64_t>(utils::FileSize(metadata_filename))) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800422 return LogAndSetError(
423 error,
424 FROM_HERE,
Sen Jiang840a7ea2018-09-19 14:29:44 -0700425 "Invalid metadata size: " + std::to_string(metadata_size));
Sen Jiang8371c1c2018-02-01 13:46:39 -0800426 }
Sen Jiang840a7ea2018-09-19 14:29:44 -0700427 metadata.resize(metadata_size);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800428 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
429 metadata.size() - kMaxPayloadHeaderSize)) {
430 return LogAndSetError(
431 error,
432 FROM_HERE,
433 "Failed to read metadata and signature from " + metadata_filename);
434 }
435 fd->Close();
Sen Jiang08c6da12019-01-07 18:28:56 -0800436
Tianjie Xu7a78d632019-10-08 16:32:39 -0700437 auto payload_verifier = PayloadVerifier::CreateInstanceFromZipPath(
438 constants::kUpdateCertificatesPath);
439 if (!payload_verifier) {
440 return LogAndSetError(error,
441 FROM_HERE,
442 "Failed to create the payload verifier from " +
443 std::string(constants::kUpdateCertificatesPath));
Sen Jiang08c6da12019-01-07 18:28:56 -0800444 }
Tianjie Xu7a78d632019-10-08 16:32:39 -0700445 errorcode = payload_metadata.ValidateMetadataSignature(
446 metadata, "", *payload_verifier);
Sen Jiang8371c1c2018-02-01 13:46:39 -0800447 if (errorcode != ErrorCode::kSuccess) {
448 return LogAndSetError(error,
449 FROM_HERE,
450 "Failed to validate metadata signature: " +
451 utils::ErrorCodeToString(errorcode));
452 }
Yifan Hongbd47d622019-12-13 14:59:58 -0800453 if (!payload_metadata.GetManifest(metadata, manifest)) {
Sen Jiang8371c1c2018-02-01 13:46:39 -0800454 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
455 }
456
Yifan Hongbd47d622019-12-13 14:59:58 -0800457 return true;
458}
459
460bool UpdateAttempterAndroid::VerifyPayloadApplicable(
461 const std::string& metadata_filename, brillo::ErrorPtr* error) {
462 DeltaArchiveManifest manifest;
463 TEST_AND_RETURN_FALSE(
464 VerifyPayloadParseManifest(metadata_filename, &manifest, error));
465
466 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
467 ErrorCode errorcode;
468
469 BootControlInterface::Slot current_slot = GetCurrentSlot();
Sen Jiang8371c1c2018-02-01 13:46:39 -0800470 for (const PartitionUpdate& partition : manifest.partitions()) {
471 if (!partition.has_old_partition_info())
472 continue;
473 string partition_path;
474 if (!boot_control_->GetPartitionDevice(
475 partition.partition_name(), current_slot, &partition_path)) {
476 return LogAndSetError(
477 error,
478 FROM_HERE,
479 "Failed to get partition device for " + partition.partition_name());
480 }
481 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
482 return LogAndSetError(
483 error, FROM_HERE, "Failed to open " + partition_path);
484 }
485 for (const InstallOperation& operation : partition.operations()) {
486 if (!operation.has_src_sha256_hash())
487 continue;
488 brillo::Blob source_hash;
489 if (!fd_utils::ReadAndHashExtents(fd,
490 operation.src_extents(),
491 manifest.block_size(),
492 &source_hash)) {
493 return LogAndSetError(
494 error, FROM_HERE, "Failed to hash " + partition_path);
495 }
496 if (!DeltaPerformer::ValidateSourceHash(
497 source_hash, operation, fd, &errorcode)) {
498 return false;
499 }
500 }
501 fd->Close();
502 }
503 return true;
504}
505
Alex Deymo5e3ea272016-01-28 13:42:23 -0800506void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
507 ErrorCode code) {
508 LOG(INFO) << "Processing Done.";
509
Alex Deymo5990bf32016-07-19 17:01:41 -0700510 switch (code) {
511 case ErrorCode::kSuccess:
512 // Update succeeded.
513 WriteUpdateCompletedMarker();
514 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800515
Alex Deymo5990bf32016-07-19 17:01:41 -0700516 LOG(INFO) << "Update successfully applied, waiting to reboot.";
517 break;
518
519 case ErrorCode::kFilesystemCopierError:
520 case ErrorCode::kNewRootfsVerificationError:
521 case ErrorCode::kNewKernelVerificationError:
522 case ErrorCode::kFilesystemVerifierError:
523 case ErrorCode::kDownloadStateInitializationError:
524 // Reset the ongoing update for these errors so it starts from the
525 // beginning next time.
526 DeltaPerformer::ResetUpdateProgress(prefs_, false);
527 LOG(INFO) << "Resetting update progress.";
528 break;
529
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700530 case ErrorCode::kPayloadTimestampError:
531 // SafetyNet logging, b/36232423
532 android_errorWriteLog(0x534e4554, "36232423");
533 break;
534
Alex Deymo5990bf32016-07-19 17:01:41 -0700535 default:
536 // Ignore all other error codes.
537 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700538 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800539
540 TerminateUpdateAndNotify(code);
541}
542
543void UpdateAttempterAndroid::ProcessingStopped(
544 const ActionProcessor* processor) {
545 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
546}
547
548void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
549 AbstractAction* action,
550 ErrorCode code) {
551 // Reset download progress regardless of whether or not the download
552 // action succeeded.
553 const string type = action->Type();
554 if (type == DownloadAction::StaticType()) {
Alex Deymo0d298542016-03-30 18:31:49 -0700555 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800556 }
Sen Jiangfe522822017-10-31 15:14:11 -0700557 if (type == PostinstallRunnerAction::StaticType()) {
558 bool succeeded =
559 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
560 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
561 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800562 if (code != ErrorCode::kSuccess) {
563 // If an action failed, the ActionProcessor will cancel the whole thing.
564 return;
565 }
566 if (type == DownloadAction::StaticType()) {
567 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700568 } else if (type == FilesystemVerifierAction::StaticType()) {
569 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800570 }
571}
572
573void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
574 uint64_t bytes_received,
575 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700576 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800577 if (total)
578 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700579 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800580 download_progress_ = progress;
581 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700582 } else {
583 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800584 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700585
586 // Update the bytes downloaded in prefs.
587 int64_t current_bytes_downloaded =
588 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
589 int64_t total_bytes_downloaded =
590 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
591 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
592 current_bytes_downloaded + bytes_progressed);
593 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
594 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800595}
596
597bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
598 // TODO(deymo): Notify the DownloadAction that it should cancel the update
599 // download.
600 return false;
601}
602
603void UpdateAttempterAndroid::DownloadComplete() {
604 // Nothing needs to be done when the download completes.
605}
606
Alex Deymo0d298542016-03-30 18:31:49 -0700607void UpdateAttempterAndroid::ProgressUpdate(double progress) {
608 // Self throttle based on progress. Also send notifications if progress is
609 // too slow.
610 if (progress == 1.0 ||
611 progress - download_progress_ >= kBroadcastThresholdProgress ||
612 TimeTicks::Now() - last_notify_time_ >=
613 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
614 download_progress_ = progress;
615 SetStatusAndNotify(status_);
616 }
617}
618
Alex Deymo5e3ea272016-01-28 13:42:23 -0800619void UpdateAttempterAndroid::ScheduleProcessingStart() {
620 LOG(INFO) << "Scheduling an action processor start.";
621 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700622 FROM_HERE,
623 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
624 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800625}
626
627void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
628 if (status_ == UpdateStatus::IDLE) {
629 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
630 return;
631 }
632
Yifan Hong9194ce82019-11-07 11:03:42 -0800633 boot_control_->GetDynamicPartitionControl()->Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700634
Alex Deymo0d298542016-03-30 18:31:49 -0700635 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800636 UpdateStatus new_status =
637 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
638 : UpdateStatus::IDLE);
639 SetStatusAndNotify(new_status);
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900640 payload_fd_.reset();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800641
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700642 // The network id is only applicable to one download attempt and once it's
643 // done the network id should not be re-used anymore.
644 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
645 LOG(WARNING) << "Unable to unbind network.";
646 }
647
Alex Deymo5e3ea272016-01-28 13:42:23 -0800648 for (auto observer : daemon_state_->service_observers())
649 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700650
Tianjie Xu90aaa102017-10-10 17:39:03 -0700651 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
652 ClearMetricsPrefs();
653 if (error_code == ErrorCode::kSuccess) {
xunchang9cf52622019-01-25 11:04:58 -0800654 // We should only reset the PayloadAttemptNumber if the update succeeds, or
655 // we switch to a different payload.
656 prefs_->Delete(kPrefsPayloadAttemptNumber);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700657 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700658 // Clear the total bytes downloaded if and only if the update succeeds.
659 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700660 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800661}
662
663void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
664 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700665 size_t payload_size =
666 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700667 UpdateEngineStatus status_to_send = {.status = status_,
668 .progress = download_progress_,
669 .new_size_bytes = payload_size};
670
Alex Deymo5e3ea272016-01-28 13:42:23 -0800671 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700672 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800673 }
674 last_notify_time_ = TimeTicks::Now();
675}
676
Amin Hassani667cf7b2018-07-25 14:32:00 -0700677void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800678 CHECK(!processor_->IsRunning());
679 processor_->set_delegate(this);
680
681 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700682 auto update_boot_flags_action =
683 std::make_unique<UpdateBootFlagsAction>(boot_control_);
684 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
685 auto download_action =
686 std::make_unique<DownloadAction>(prefs_,
687 boot_control_,
688 hardware_,
689 nullptr, // system_state, not used.
690 fetcher, // passes ownership
691 true /* interactive */);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800692 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700693 download_action->set_base_offset(base_offset_);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700694 auto filesystem_verifier_action =
695 std::make_unique<FilesystemVerifierAction>();
696 auto postinstall_runner_action =
697 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Alex Deymob6eef732016-06-10 12:58:11 -0700698 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800699
Alex Deymo5e3ea272016-01-28 13:42:23 -0800700 // Bond them together. We have to use the leaf-types when calling
701 // BondActions().
702 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700703 BondActions(download_action.get(), filesystem_verifier_action.get());
704 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800705 postinstall_runner_action.get());
706
Amin Hassani667cf7b2018-07-25 14:32:00 -0700707 processor_->EnqueueAction(std::move(update_boot_flags_action));
708 processor_->EnqueueAction(std::move(install_plan_action));
709 processor_->EnqueueAction(std::move(download_action));
710 processor_->EnqueueAction(std::move(filesystem_verifier_action));
711 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800712}
713
Alex Deymo5e3ea272016-01-28 13:42:23 -0800714bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
715 string boot_id;
716 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
717 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
718 return true;
719}
720
721bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
722 // In case of an update_engine restart without a reboot, we stored the boot_id
723 // when the update was completed by setting a pref, so we can check whether
724 // the last update was on this boot or a previous one.
725 string boot_id;
726 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
727
728 string update_completed_on_boot_id;
729 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
730 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
731 &update_completed_on_boot_id) &&
732 update_completed_on_boot_id == boot_id);
733}
734
Tianjie Xu90aaa102017-10-10 17:39:03 -0700735// Collect and report the android metrics when we terminate the update.
736void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
737 ErrorCode error_code) {
738 int64_t attempt_number =
739 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
740 PayloadType payload_type = kPayloadTypeFull;
741 int64_t payload_size = 0;
742 for (const auto& p : install_plan_.payloads) {
743 if (p.type == InstallPayloadType::kDelta)
744 payload_type = kPayloadTypeDelta;
745 payload_size += p.size;
746 }
747
748 metrics::AttemptResult attempt_result =
749 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700750 Time boot_time_start = Time::FromInternalValue(
751 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
752 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700753 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700754 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
755 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700756
757 metrics_reporter_->ReportUpdateAttemptMetrics(
758 nullptr, // system_state
759 static_cast<int>(attempt_number),
760 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700761 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700762 duration_uptime,
763 payload_size,
764 attempt_result,
765 error_code);
766
Tianjie Xud4777a12017-10-24 14:54:18 -0700767 int64_t current_bytes_downloaded =
768 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
769 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
770 current_bytes_downloaded,
771 0,
772 DownloadSource::kNumDownloadSources,
773 metrics::DownloadErrorCode::kUnset,
774 metrics::ConnectionType::kUnset);
775
Tianjie Xu90aaa102017-10-10 17:39:03 -0700776 if (error_code == ErrorCode::kSuccess) {
777 int64_t reboot_count =
778 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
779 string build_version;
780 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700781
782 // For android metrics, we only care about the total bytes downloaded
783 // for all sources; for now we assume the only download source is
784 // HttpsServer.
785 int64_t total_bytes_downloaded =
786 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
787 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
788 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
789 total_bytes_downloaded;
790
791 int download_overhead_percentage = 0;
Tianjie Xu21030c12019-08-14 13:00:23 -0700792 if (total_bytes_downloaded >= payload_size) {
793 CHECK_GT(payload_size, 0);
Tianjie Xud4777a12017-10-24 14:54:18 -0700794 download_overhead_percentage =
Tianjie Xu21030c12019-08-14 13:00:23 -0700795 (total_bytes_downloaded - payload_size) * 100ull / payload_size;
796 } else {
797 LOG(WARNING) << "Downloaded bytes " << total_bytes_downloaded
798 << " is smaller than the payload size " << payload_size;
Tianjie Xud4777a12017-10-24 14:54:18 -0700799 }
Tianjie Xu21030c12019-08-14 13:00:23 -0700800
Tianjie Xu90aaa102017-10-10 17:39:03 -0700801 metrics_reporter_->ReportSuccessfulUpdateMetrics(
802 static_cast<int>(attempt_number),
803 0, // update abandoned count
804 payload_type,
805 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700806 num_bytes_downloaded,
807 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700808 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700809 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700810 static_cast<int>(reboot_count),
811 0); // url_switch_count
812 }
813}
814
815void UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
816 string current_boot_id;
817 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
818 // Example: [ro.build.version.incremental]: [4292972]
819 string current_version =
820 android::base::GetProperty("ro.build.version.incremental", "");
821 TEST_AND_RETURN(!current_version.empty());
822
823 // If there's no record of previous version (e.g. due to a data wipe), we
824 // save the info of current boot and skip the metrics report.
825 if (!prefs_->Exists(kPrefsPreviousVersion)) {
826 prefs_->SetString(kPrefsBootId, current_boot_id);
827 prefs_->SetString(kPrefsPreviousVersion, current_version);
828 ClearMetricsPrefs();
829 return;
830 }
831 string previous_version;
832 // update_engine restarted under the same build.
833 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
834 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
835 previous_version == current_version) {
836 string last_boot_id;
837 bool is_reboot = prefs_->Exists(kPrefsBootId) &&
838 (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
839 last_boot_id != current_boot_id);
840 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
841 // set when we start a new update.
842 if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
843 prefs_->SetString(kPrefsBootId, current_boot_id);
844 int64_t reboot_count =
845 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
846 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
847 }
848 return;
849 }
850
851 // Now that the build version changes, report the update metrics.
852 // TODO(xunchang) check the build version is larger than the previous one.
853 prefs_->SetString(kPrefsBootId, current_boot_id);
854 prefs_->SetString(kPrefsPreviousVersion, current_version);
855
856 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
857 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
858 if (previous_attempt_exists) {
859 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
860 }
861
862 metrics_utils::LoadAndReportTimeToReboot(
863 metrics_reporter_.get(), prefs_, clock_.get());
864 ClearMetricsPrefs();
Sen Jiang1bafff82019-01-02 15:54:40 -0800865
866 // Also reset the update progress if the build version has changed.
867 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
868 LOG(WARNING) << "Unable to reset the update progress.";
869 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700870}
871
872// Save the update start time. Reset the reboot count and attempt number if the
873// update isn't a resume; otherwise increment the attempt number.
874void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
875 if (!is_resume) {
876 metrics_utils::SetNumReboots(0, prefs_);
877 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
878 } else {
879 int64_t attempt_number =
880 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
881 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
882 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700883 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
884 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700885}
886
887void UpdateAttempterAndroid::ClearMetricsPrefs() {
888 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700889 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700890 prefs_->Delete(kPrefsNumReboots);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700891 prefs_->Delete(kPrefsSystemUpdatedMarker);
892 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700893 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700894}
895
Yifan Hongbd47d622019-12-13 14:59:58 -0800896BootControlInterface::Slot UpdateAttempterAndroid::GetCurrentSlot() const {
897 return boot_control_->GetCurrentSlot();
898}
899
900BootControlInterface::Slot UpdateAttempterAndroid::GetTargetSlot() const {
901 return GetCurrentSlot() == 0 ? 1 : 0;
902}
903
Yifan Hong6f7e29f2019-12-13 14:41:06 -0800904uint64_t UpdateAttempterAndroid::AllocateSpaceForPayload(
905 const std::string& metadata_filename,
906 const vector<string>& key_value_pair_headers,
907 brillo::ErrorPtr* error) {
908 // TODO(elsk): implement b/138808058
909 LogAndSetError(error, FROM_HERE, "Not implemented.");
910 return 0;
911}
912
Yifan Hong2236ea02019-12-13 16:11:22 -0800913int32_t UpdateAttempterAndroid::CleanupSuccessfulUpdate(
914 brillo::ErrorPtr* error) {
915 // TODO(elsk): implement b/138808328
916 LogAndSetError(error, FROM_HERE, "Not implemented.");
917 return static_cast<int32_t>(ErrorCode::kError);
918}
919
Alex Deymo5e3ea272016-01-28 13:42:23 -0800920} // namespace chromeos_update_engine