blob: f0de4cbefd63d1ecbe699e09bb0774f2d7eaeba4 [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>
Alex Deymo5e3ea272016-01-28 13:42:23 -080025#include <base/bind.h>
26#include <base/logging.h>
Alex Deymo218397f2016-02-04 23:55:10 -080027#include <base/strings/string_number_conversions.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080028#include <brillo/bind_lambda.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"
Sen Jiang8371c1c2018-02-01 13:46:39 -080042#include "update_engine/payload_consumer/delta_performer.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080043#include "update_engine/payload_consumer/download_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080044#include "update_engine/payload_consumer/file_descriptor.h"
45#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080046#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Sen Jiang8371c1c2018-02-01 13:46:39 -080047#include "update_engine/payload_consumer/payload_constants.h"
48#include "update_engine/payload_consumer/payload_metadata.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080049#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070050#include "update_engine/update_boot_flags_action.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080051#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080052
Alex Deymo14c0da82016-07-20 16:45:45 -070053#ifndef _UE_SIDELOAD
54// Do not include support for external HTTP(s) urls when building
55// update_engine_sideload.
56#include "update_engine/libcurl_http_fetcher.h"
57#endif
58
Alex Deymo5e3ea272016-01-28 13:42:23 -080059using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070060using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080061using base::TimeDelta;
62using base::TimeTicks;
63using std::shared_ptr;
64using std::string;
65using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070066using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080067
68namespace chromeos_update_engine {
69
70namespace {
71
Alex Deymo0d298542016-03-30 18:31:49 -070072// Minimum threshold to broadcast an status update in progress and time.
73const double kBroadcastThresholdProgress = 0.01; // 1%
74const int kBroadcastThresholdSeconds = 10;
75
Alex Deymo5e3ea272016-01-28 13:42:23 -080076const char* const kErrorDomain = "update_engine";
77// TODO(deymo): Convert the different errors to a numeric value to report them
78// back on the service error.
79const char* const kGenericError = "generic_error";
80
81// Log and set the error on the passed ErrorPtr.
82bool LogAndSetError(brillo::ErrorPtr* error,
Jakub Pawlowski7e1dcf72018-07-26 00:29:42 -070083 const base::Location& location,
Alex Deymo5e3ea272016-01-28 13:42:23 -080084 const string& reason) {
85 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
86 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
87 << reason;
88 return false;
89}
90
Sen Jiangfe522822017-10-31 15:14:11 -070091bool GetHeaderAsBool(const string& header, bool default_value) {
92 int value = 0;
93 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
94 return value == 1;
95 return default_value;
96}
97
Alex Deymo5e3ea272016-01-28 13:42:23 -080098} // namespace
99
100UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700101 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800102 PrefsInterface* prefs,
103 BootControlInterface* boot_control,
104 HardwareInterface* hardware)
105 : daemon_state_(daemon_state),
106 prefs_(prefs),
107 boot_control_(boot_control),
108 hardware_(hardware),
Tianjie Xu1b661142017-09-28 14:03:42 -0700109 processor_(new ActionProcessor()),
Tianjie Xud4c5deb2017-10-24 11:17:03 -0700110 clock_(new Clock()) {
111 metrics_reporter_ = metrics::CreateMetricsReporter();
Alex Deymo87792ea2016-07-25 15:40:36 -0700112 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800113}
114
115UpdateAttempterAndroid::~UpdateAttempterAndroid() {
116 // Release ourselves as the ActionProcessor's delegate to prevent
117 // re-scheduling the updates due to the processing stopped.
118 processor_->set_delegate(nullptr);
119}
120
121void UpdateAttempterAndroid::Init() {
122 // In case of update_engine restart without a reboot we need to restore the
123 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700124 if (UpdateCompletedOnThisBoot()) {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800125 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700126 } else {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800127 SetStatusAndNotify(UpdateStatus::IDLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700128 UpdatePrefsAndReportUpdateMetricsOnReboot();
129 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800130}
131
132bool UpdateAttempterAndroid::ApplyPayload(
133 const string& payload_url,
134 int64_t payload_offset,
135 int64_t payload_size,
136 const vector<string>& key_value_pair_headers,
137 brillo::ErrorPtr* error) {
138 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
139 return LogAndSetError(
140 error, FROM_HERE, "An update already applied, waiting for reboot");
141 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700142 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800143 return LogAndSetError(
144 error, FROM_HERE, "Already processing an update, cancel it first.");
145 }
146 DCHECK(status_ == UpdateStatus::IDLE);
147
Alex Deymo218397f2016-02-04 23:55:10 -0800148 std::map<string, string> headers;
149 for (const string& key_value_pair : key_value_pair_headers) {
150 string key;
151 string value;
152 if (!brillo::string_utils::SplitAtFirst(
153 key_value_pair, "=", &key, &value, false)) {
154 return LogAndSetError(
155 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
156 }
157 if (!headers.emplace(key, value).second)
158 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
159 }
160
161 // Unique identifier for the payload. An empty string means that the payload
162 // can't be resumed.
163 string payload_id = (headers[kPayloadPropertyFileHash] +
164 headers[kPayloadPropertyMetadataHash]);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800165
166 // Setup the InstallPlan based on the request.
167 install_plan_ = InstallPlan();
168
169 install_plan_.download_url = payload_url;
170 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800171 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800172 InstallPlan::Payload payload;
173 payload.size = payload_size;
174 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800175 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800176 &payload.size)) {
177 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800178 }
179 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700180 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800181 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700182 LOG(WARNING) << "Unable to decode base64 file hash: "
183 << headers[kPayloadPropertyFileHash];
184 }
Alex Deymo218397f2016-02-04 23:55:10 -0800185 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800186 &payload.metadata_size)) {
187 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800188 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700189 // The |payload.type| is not used anymore since minor_version 3.
190 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800191 install_plan_.payloads.push_back(payload);
192
Alex Deymo5e3ea272016-01-28 13:42:23 -0800193 // The |public_key_rsa| key would override the public key stored on disk.
194 install_plan_.public_key_rsa = "";
195
196 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
197 install_plan_.is_resume = !payload_id.empty() &&
198 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
199 if (!install_plan_.is_resume) {
200 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
201 LOG(WARNING) << "Unable to reset the update progress.";
202 }
203 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
204 LOG(WARNING) << "Unable to save the update check response hash.";
205 }
206 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800207 install_plan_.source_slot = boot_control_->GetCurrentSlot();
208 install_plan_.target_slot = install_plan_.source_slot == 0 ? 1 : 0;
Alex Deymofb905d92016-06-03 19:26:58 -0700209
Alex Deymofb905d92016-06-03 19:26:58 -0700210 install_plan_.powerwash_required =
Sen Jiangfe522822017-10-31 15:14:11 -0700211 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
212
213 install_plan_.switch_slot_on_reboot =
214 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
215
216 install_plan_.run_post_install = true;
217 // Optionally skip post install if and only if:
218 // a) we're resuming
219 // b) post install has already succeeded before
220 // c) RUN_POST_INSTALL is set to 0.
221 if (install_plan_.is_resume && prefs_->Exists(kPrefsPostInstallSucceeded)) {
222 bool post_install_succeeded = false;
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700223 if (prefs_->GetBoolean(kPrefsPostInstallSucceeded,
224 &post_install_succeeded) &&
225 post_install_succeeded) {
Sen Jiangfe522822017-10-31 15:14:11 -0700226 install_plan_.run_post_install =
227 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
228 }
229 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800230
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700231 // Skip writing verity if we're resuming and verity has already been written.
232 install_plan_.write_verity = true;
233 if (install_plan_.is_resume && prefs_->Exists(kPrefsVerityWritten)) {
234 bool verity_written = false;
235 if (prefs_->GetBoolean(kPrefsVerityWritten, &verity_written) &&
236 verity_written) {
237 install_plan_.write_verity = false;
238 }
239 }
240
Alex Deymo87792ea2016-07-25 15:40:36 -0700241 NetworkId network_id = kDefaultNetworkId;
242 if (!headers[kPayloadPropertyNetworkId].empty()) {
243 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
244 &network_id)) {
245 return LogAndSetError(
246 error,
247 FROM_HERE,
248 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
249 }
250 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700251 return LogAndSetError(
252 error,
253 FROM_HERE,
254 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700255 }
256 }
257
Alex Deymo5e3ea272016-01-28 13:42:23 -0800258 LOG(INFO) << "Using this install plan:";
259 install_plan_.Dump();
260
Amin Hassani667cf7b2018-07-25 14:32:00 -0700261 HttpFetcher* fetcher = nullptr;
262 if (FileFetcher::SupportedUrl(payload_url)) {
263 DLOG(INFO) << "Using FileFetcher for file URL.";
264 fetcher = new FileFetcher();
265 } else {
266#ifdef _UE_SIDELOAD
267 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
268#else
269 LibcurlHttpFetcher* libcurl_fetcher =
270 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
271 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
272 fetcher = libcurl_fetcher;
273#endif // _UE_SIDELOAD
274 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800275 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800276 if (!headers[kPayloadPropertyAuthorization].empty())
277 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
278 if (!headers[kPayloadPropertyUserAgent].empty())
279 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
280
Amin Hassani667cf7b2018-07-25 14:32:00 -0700281 BuildUpdateActions(fetcher);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800282
Alex Deymo5e3ea272016-01-28 13:42:23 -0800283 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700284
285 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
286 // TODO(xunchang) report the metrics for unresumable updates
287
Amin Hassani667cf7b2018-07-25 14:32:00 -0700288 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800289 return true;
290}
291
292bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700293 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800294 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
295 processor_->SuspendProcessing();
296 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800297}
298
299bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700300 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800301 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
302 processor_->ResumeProcessing();
303 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800304}
305
306bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700307 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800308 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800309 processor_->StopProcessing();
310 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800311}
312
Alex Deymo3b678db2016-02-09 11:50:06 -0800313bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
314 LOG(INFO) << "Attempting to reset state from "
315 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
316
317 switch (status_) {
318 case UpdateStatus::IDLE:
319 return true;
320
321 case UpdateStatus::UPDATED_NEED_REBOOT: {
322 // Remove the reboot marker so that if the machine is rebooted
323 // after resetting to idle state, it doesn't go back to
324 // UpdateStatus::UPDATED_NEED_REBOOT state.
325 bool ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700326 ClearMetricsPrefs();
Alex Deymo3b678db2016-02-09 11:50:06 -0800327
328 // Update the boot flags so the current slot has higher priority.
329 if (!boot_control_->SetActiveBootSlot(boot_control_->GetCurrentSlot()))
330 ret_value = false;
331
Alex Deymo52590332016-11-29 18:29:13 -0800332 // Mark the current slot as successful again, since marking it as active
333 // may reset the successful bit. We ignore the result of whether marking
334 // the current slot as successful worked.
335 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful){})))
336 ret_value = false;
337
Alex Deymo3b678db2016-02-09 11:50:06 -0800338 if (!ret_value) {
339 return LogAndSetError(
340 error,
341 FROM_HERE,
342 "Failed to reset the status to ");
343 }
344
345 SetStatusAndNotify(UpdateStatus::IDLE);
346 LOG(INFO) << "Reset status successful";
347 return true;
348 }
349
350 default:
351 return LogAndSetError(
352 error,
353 FROM_HERE,
354 "Reset not allowed in this state. Cancel the ongoing update first");
355 }
356}
357
Sen Jiang8371c1c2018-02-01 13:46:39 -0800358bool UpdateAttempterAndroid::VerifyPayloadApplicable(
359 const std::string& metadata_filename, brillo::ErrorPtr* error) {
360 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
361 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
362 return LogAndSetError(
363 error, FROM_HERE, "Failed to open " + metadata_filename);
364 }
365 brillo::Blob metadata(kMaxPayloadHeaderSize);
366 if (!fd->Read(metadata.data(), metadata.size())) {
367 return LogAndSetError(
368 error,
369 FROM_HERE,
370 "Failed to read payload header from " + metadata_filename);
371 }
372 ErrorCode errorcode;
373 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700374 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800375 MetadataParseResult::kSuccess) {
376 return LogAndSetError(error,
377 FROM_HERE,
378 "Failed to parse payload header: " +
379 utils::ErrorCodeToString(errorcode));
380 }
381 metadata.resize(payload_metadata.GetMetadataSize() +
382 payload_metadata.GetMetadataSignatureSize());
383 if (metadata.size() < kMaxPayloadHeaderSize) {
384 return LogAndSetError(
385 error,
386 FROM_HERE,
387 "Metadata size too small: " + std::to_string(metadata.size()));
388 }
389 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
390 metadata.size() - kMaxPayloadHeaderSize)) {
391 return LogAndSetError(
392 error,
393 FROM_HERE,
394 "Failed to read metadata and signature from " + metadata_filename);
395 }
396 fd->Close();
397 errorcode = payload_metadata.ValidateMetadataSignature(
398 metadata, "", base::FilePath(constants::kUpdatePayloadPublicKeyPath));
399 if (errorcode != ErrorCode::kSuccess) {
400 return LogAndSetError(error,
401 FROM_HERE,
402 "Failed to validate metadata signature: " +
403 utils::ErrorCodeToString(errorcode));
404 }
405 DeltaArchiveManifest manifest;
406 if (!payload_metadata.GetManifest(metadata, &manifest)) {
407 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
408 }
409
410 BootControlInterface::Slot current_slot = boot_control_->GetCurrentSlot();
411 for (const PartitionUpdate& partition : manifest.partitions()) {
412 if (!partition.has_old_partition_info())
413 continue;
414 string partition_path;
415 if (!boot_control_->GetPartitionDevice(
416 partition.partition_name(), current_slot, &partition_path)) {
417 return LogAndSetError(
418 error,
419 FROM_HERE,
420 "Failed to get partition device for " + partition.partition_name());
421 }
422 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
423 return LogAndSetError(
424 error, FROM_HERE, "Failed to open " + partition_path);
425 }
426 for (const InstallOperation& operation : partition.operations()) {
427 if (!operation.has_src_sha256_hash())
428 continue;
429 brillo::Blob source_hash;
430 if (!fd_utils::ReadAndHashExtents(fd,
431 operation.src_extents(),
432 manifest.block_size(),
433 &source_hash)) {
434 return LogAndSetError(
435 error, FROM_HERE, "Failed to hash " + partition_path);
436 }
437 if (!DeltaPerformer::ValidateSourceHash(
438 source_hash, operation, fd, &errorcode)) {
439 return false;
440 }
441 }
442 fd->Close();
443 }
444 return true;
445}
446
Alex Deymo5e3ea272016-01-28 13:42:23 -0800447void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
448 ErrorCode code) {
449 LOG(INFO) << "Processing Done.";
450
Alex Deymo5990bf32016-07-19 17:01:41 -0700451 switch (code) {
452 case ErrorCode::kSuccess:
453 // Update succeeded.
454 WriteUpdateCompletedMarker();
455 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800456
Alex Deymo5990bf32016-07-19 17:01:41 -0700457 LOG(INFO) << "Update successfully applied, waiting to reboot.";
458 break;
459
460 case ErrorCode::kFilesystemCopierError:
461 case ErrorCode::kNewRootfsVerificationError:
462 case ErrorCode::kNewKernelVerificationError:
463 case ErrorCode::kFilesystemVerifierError:
464 case ErrorCode::kDownloadStateInitializationError:
465 // Reset the ongoing update for these errors so it starts from the
466 // beginning next time.
467 DeltaPerformer::ResetUpdateProgress(prefs_, false);
468 LOG(INFO) << "Resetting update progress.";
469 break;
470
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700471 case ErrorCode::kPayloadTimestampError:
472 // SafetyNet logging, b/36232423
473 android_errorWriteLog(0x534e4554, "36232423");
474 break;
475
Alex Deymo5990bf32016-07-19 17:01:41 -0700476 default:
477 // Ignore all other error codes.
478 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700479 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800480
481 TerminateUpdateAndNotify(code);
482}
483
484void UpdateAttempterAndroid::ProcessingStopped(
485 const ActionProcessor* processor) {
486 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
487}
488
489void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
490 AbstractAction* action,
491 ErrorCode code) {
492 // Reset download progress regardless of whether or not the download
493 // action succeeded.
494 const string type = action->Type();
495 if (type == DownloadAction::StaticType()) {
Alex Deymo0d298542016-03-30 18:31:49 -0700496 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800497 }
Sen Jiangfe522822017-10-31 15:14:11 -0700498 if (type == PostinstallRunnerAction::StaticType()) {
499 bool succeeded =
500 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
501 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
502 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800503 if (code != ErrorCode::kSuccess) {
504 // If an action failed, the ActionProcessor will cancel the whole thing.
505 return;
506 }
507 if (type == DownloadAction::StaticType()) {
508 SetStatusAndNotify(UpdateStatus::FINALIZING);
Sen Jiang3eeaf7d2018-10-11 13:55:32 -0700509 } else if (type == FilesystemVerifierAction::StaticType()) {
510 prefs_->SetBoolean(kPrefsVerityWritten, true);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800511 }
512}
513
514void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
515 uint64_t bytes_received,
516 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700517 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800518 if (total)
519 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700520 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800521 download_progress_ = progress;
522 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700523 } else {
524 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800525 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700526
527 // Update the bytes downloaded in prefs.
528 int64_t current_bytes_downloaded =
529 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
530 int64_t total_bytes_downloaded =
531 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
532 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
533 current_bytes_downloaded + bytes_progressed);
534 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
535 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800536}
537
538bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
539 // TODO(deymo): Notify the DownloadAction that it should cancel the update
540 // download.
541 return false;
542}
543
544void UpdateAttempterAndroid::DownloadComplete() {
545 // Nothing needs to be done when the download completes.
546}
547
Alex Deymo0d298542016-03-30 18:31:49 -0700548void UpdateAttempterAndroid::ProgressUpdate(double progress) {
549 // Self throttle based on progress. Also send notifications if progress is
550 // too slow.
551 if (progress == 1.0 ||
552 progress - download_progress_ >= kBroadcastThresholdProgress ||
553 TimeTicks::Now() - last_notify_time_ >=
554 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
555 download_progress_ = progress;
556 SetStatusAndNotify(status_);
557 }
558}
559
Alex Deymo5e3ea272016-01-28 13:42:23 -0800560void UpdateAttempterAndroid::ScheduleProcessingStart() {
561 LOG(INFO) << "Scheduling an action processor start.";
562 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700563 FROM_HERE,
564 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
565 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800566}
567
568void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
569 if (status_ == UpdateStatus::IDLE) {
570 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
571 return;
572 }
573
Yifan Hong537802d2018-08-15 13:15:42 -0700574 boot_control_->Cleanup();
575
Alex Deymo0d298542016-03-30 18:31:49 -0700576 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800577 UpdateStatus new_status =
578 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
579 : UpdateStatus::IDLE);
580 SetStatusAndNotify(new_status);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800581
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700582 // The network id is only applicable to one download attempt and once it's
583 // done the network id should not be re-used anymore.
584 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
585 LOG(WARNING) << "Unable to unbind network.";
586 }
587
Alex Deymo5e3ea272016-01-28 13:42:23 -0800588 for (auto observer : daemon_state_->service_observers())
589 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700590
Tianjie Xu90aaa102017-10-10 17:39:03 -0700591 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
592 ClearMetricsPrefs();
593 if (error_code == ErrorCode::kSuccess) {
594 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700595 // Clear the total bytes downloaded if and only if the update succeeds.
596 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700597 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800598}
599
600void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
601 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700602 size_t payload_size =
603 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700604 UpdateEngineStatus status_to_send = {.status = status_,
605 .progress = download_progress_,
606 .new_size_bytes = payload_size};
607
Alex Deymo5e3ea272016-01-28 13:42:23 -0800608 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700609 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800610 }
611 last_notify_time_ = TimeTicks::Now();
612}
613
Amin Hassani667cf7b2018-07-25 14:32:00 -0700614void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800615 CHECK(!processor_->IsRunning());
616 processor_->set_delegate(this);
617
618 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700619 auto update_boot_flags_action =
620 std::make_unique<UpdateBootFlagsAction>(boot_control_);
621 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
622 auto download_action =
623 std::make_unique<DownloadAction>(prefs_,
624 boot_control_,
625 hardware_,
626 nullptr, // system_state, not used.
627 fetcher, // passes ownership
628 true /* interactive */);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800629 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700630 download_action->set_base_offset(base_offset_);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700631 auto filesystem_verifier_action =
632 std::make_unique<FilesystemVerifierAction>();
633 auto postinstall_runner_action =
634 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Alex Deymob6eef732016-06-10 12:58:11 -0700635 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800636
Alex Deymo5e3ea272016-01-28 13:42:23 -0800637 // Bond them together. We have to use the leaf-types when calling
638 // BondActions().
639 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700640 BondActions(download_action.get(), filesystem_verifier_action.get());
641 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800642 postinstall_runner_action.get());
643
Amin Hassani667cf7b2018-07-25 14:32:00 -0700644 processor_->EnqueueAction(std::move(update_boot_flags_action));
645 processor_->EnqueueAction(std::move(install_plan_action));
646 processor_->EnqueueAction(std::move(download_action));
647 processor_->EnqueueAction(std::move(filesystem_verifier_action));
648 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800649}
650
Alex Deymo5e3ea272016-01-28 13:42:23 -0800651bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
652 string boot_id;
653 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
654 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
655 return true;
656}
657
658bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
659 // In case of an update_engine restart without a reboot, we stored the boot_id
660 // when the update was completed by setting a pref, so we can check whether
661 // the last update was on this boot or a previous one.
662 string boot_id;
663 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
664
665 string update_completed_on_boot_id;
666 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
667 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
668 &update_completed_on_boot_id) &&
669 update_completed_on_boot_id == boot_id);
670}
671
Tianjie Xu90aaa102017-10-10 17:39:03 -0700672// Collect and report the android metrics when we terminate the update.
673void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
674 ErrorCode error_code) {
675 int64_t attempt_number =
676 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
677 PayloadType payload_type = kPayloadTypeFull;
678 int64_t payload_size = 0;
679 for (const auto& p : install_plan_.payloads) {
680 if (p.type == InstallPayloadType::kDelta)
681 payload_type = kPayloadTypeDelta;
682 payload_size += p.size;
683 }
684
685 metrics::AttemptResult attempt_result =
686 metrics_utils::GetAttemptResult(error_code);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700687 Time boot_time_start = Time::FromInternalValue(
688 metrics_utils::GetPersistedValue(kPrefsUpdateBootTimestampStart, prefs_));
689 Time monotonic_time_start = Time::FromInternalValue(
Tianjie Xu90aaa102017-10-10 17:39:03 -0700690 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700691 TimeDelta duration = clock_->GetBootTime() - boot_time_start;
692 TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700693
694 metrics_reporter_->ReportUpdateAttemptMetrics(
695 nullptr, // system_state
696 static_cast<int>(attempt_number),
697 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700698 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700699 duration_uptime,
700 payload_size,
701 attempt_result,
702 error_code);
703
Tianjie Xud4777a12017-10-24 14:54:18 -0700704 int64_t current_bytes_downloaded =
705 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
706 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
707 current_bytes_downloaded,
708 0,
709 DownloadSource::kNumDownloadSources,
710 metrics::DownloadErrorCode::kUnset,
711 metrics::ConnectionType::kUnset);
712
Tianjie Xu90aaa102017-10-10 17:39:03 -0700713 if (error_code == ErrorCode::kSuccess) {
714 int64_t reboot_count =
715 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
716 string build_version;
717 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700718
719 // For android metrics, we only care about the total bytes downloaded
720 // for all sources; for now we assume the only download source is
721 // HttpsServer.
722 int64_t total_bytes_downloaded =
723 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
724 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
725 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
726 total_bytes_downloaded;
727
728 int download_overhead_percentage = 0;
729 if (current_bytes_downloaded > 0) {
730 download_overhead_percentage =
731 (total_bytes_downloaded - current_bytes_downloaded) * 100ull /
732 current_bytes_downloaded;
733 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700734 metrics_reporter_->ReportSuccessfulUpdateMetrics(
735 static_cast<int>(attempt_number),
736 0, // update abandoned count
737 payload_type,
738 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700739 num_bytes_downloaded,
740 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700741 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700742 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700743 static_cast<int>(reboot_count),
744 0); // url_switch_count
745 }
746}
747
748void UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
749 string current_boot_id;
750 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
751 // Example: [ro.build.version.incremental]: [4292972]
752 string current_version =
753 android::base::GetProperty("ro.build.version.incremental", "");
754 TEST_AND_RETURN(!current_version.empty());
755
756 // If there's no record of previous version (e.g. due to a data wipe), we
757 // save the info of current boot and skip the metrics report.
758 if (!prefs_->Exists(kPrefsPreviousVersion)) {
759 prefs_->SetString(kPrefsBootId, current_boot_id);
760 prefs_->SetString(kPrefsPreviousVersion, current_version);
761 ClearMetricsPrefs();
762 return;
763 }
764 string previous_version;
765 // update_engine restarted under the same build.
766 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
767 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
768 previous_version == current_version) {
769 string last_boot_id;
770 bool is_reboot = prefs_->Exists(kPrefsBootId) &&
771 (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
772 last_boot_id != current_boot_id);
773 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
774 // set when we start a new update.
775 if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
776 prefs_->SetString(kPrefsBootId, current_boot_id);
777 int64_t reboot_count =
778 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
779 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
780 }
781 return;
782 }
783
784 // Now that the build version changes, report the update metrics.
785 // TODO(xunchang) check the build version is larger than the previous one.
786 prefs_->SetString(kPrefsBootId, current_boot_id);
787 prefs_->SetString(kPrefsPreviousVersion, current_version);
788
789 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
790 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
791 if (previous_attempt_exists) {
792 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
793 }
794
795 metrics_utils::LoadAndReportTimeToReboot(
796 metrics_reporter_.get(), prefs_, clock_.get());
797 ClearMetricsPrefs();
798}
799
800// Save the update start time. Reset the reboot count and attempt number if the
801// update isn't a resume; otherwise increment the attempt number.
802void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
803 if (!is_resume) {
804 metrics_utils::SetNumReboots(0, prefs_);
805 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
806 } else {
807 int64_t attempt_number =
808 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
809 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
810 }
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700811 metrics_utils::SetUpdateTimestampStart(clock_->GetMonotonicTime(), prefs_);
812 metrics_utils::SetUpdateBootTimestampStart(clock_->GetBootTime(), prefs_);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700813}
814
815void UpdateAttempterAndroid::ClearMetricsPrefs() {
816 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700817 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700818 prefs_->Delete(kPrefsNumReboots);
819 prefs_->Delete(kPrefsPayloadAttemptNumber);
820 prefs_->Delete(kPrefsSystemUpdatedMarker);
821 prefs_->Delete(kPrefsUpdateTimestampStart);
Tianjie Xu2a0ea632018-08-06 12:59:23 -0700822 prefs_->Delete(kPrefsUpdateBootTimestampStart);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700823}
824
Alex Deymo5e3ea272016-01-28 13:42:23 -0800825} // namespace chromeos_update_engine