blob: 9b0b42ad5969cfcba1759cc10aa3648df9cf9f6a [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>
Alex Deymo5e3ea272016-01-28 13:42:23 -080032
33#include "update_engine/common/constants.h"
Sen Jiang28d8ed92018-02-01 13:46:39 -080034#include "update_engine/common/error_code_utils.h"
Alex Deymo2c131bb2016-05-26 16:43:13 -070035#include "update_engine/common/file_fetcher.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080036#include "update_engine/common/utils.h"
Alex Deymo03a4de72016-07-20 16:08:23 -070037#include "update_engine/daemon_state_interface.h"
Tianjie Xud4c5deb2017-10-24 11:17:03 -070038#include "update_engine/metrics_reporter_interface.h"
Tianjie Xu1b661142017-09-28 14:03:42 -070039#include "update_engine/metrics_utils.h"
Alex Deymo87792ea2016-07-25 15:40:36 -070040#include "update_engine/network_selector.h"
Sen Jiang28d8ed92018-02-01 13:46:39 -080041#include "update_engine/payload_consumer/delta_performer.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080042#include "update_engine/payload_consumer/download_action.h"
Sen Jiang28d8ed92018-02-01 13:46:39 -080043#include "update_engine/payload_consumer/file_descriptor.h"
44#include "update_engine/payload_consumer/file_descriptor_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080045#include "update_engine/payload_consumer/filesystem_verifier_action.h"
Sen Jiang28d8ed92018-02-01 13:46:39 -080046#include "update_engine/payload_consumer/payload_constants.h"
47#include "update_engine/payload_consumer/payload_metadata.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080048#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani667cf7b2018-07-25 14:32:00 -070049#include "update_engine/update_boot_flags_action.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080050#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080051
Alex Deymo14c0da82016-07-20 16:45:45 -070052#ifndef _UE_SIDELOAD
53// Do not include support for external HTTP(s) urls when building
54// update_engine_sideload.
55#include "update_engine/libcurl_http_fetcher.h"
56#endif
57
Alex Deymo5e3ea272016-01-28 13:42:23 -080058using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070059using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080060using base::TimeDelta;
61using base::TimeTicks;
62using std::shared_ptr;
63using std::string;
64using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070065using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080066
67namespace chromeos_update_engine {
68
69namespace {
70
Alex Deymo0d298542016-03-30 18:31:49 -070071// Minimum threshold to broadcast an status update in progress and time.
72const double kBroadcastThresholdProgress = 0.01; // 1%
73const int kBroadcastThresholdSeconds = 10;
74
Alex Deymo5e3ea272016-01-28 13:42:23 -080075const char* const kErrorDomain = "update_engine";
76// TODO(deymo): Convert the different errors to a numeric value to report them
77// back on the service error.
78const char* const kGenericError = "generic_error";
79
80// Log and set the error on the passed ErrorPtr.
81bool LogAndSetError(brillo::ErrorPtr* error,
82 const tracked_objects::Location& location,
83 const string& reason) {
84 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
85 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
86 << reason;
87 return false;
88}
89
Sen Jiang02c49422017-10-31 15:14:11 -070090bool GetHeaderAsBool(const string& header, bool default_value) {
91 int value = 0;
92 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
93 return value == 1;
94 return default_value;
95}
96
Alex Deymo5e3ea272016-01-28 13:42:23 -080097} // namespace
98
99UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -0700100 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800101 PrefsInterface* prefs,
102 BootControlInterface* boot_control,
103 HardwareInterface* hardware)
104 : daemon_state_(daemon_state),
105 prefs_(prefs),
106 boot_control_(boot_control),
107 hardware_(hardware),
Tianjie Xu1b661142017-09-28 14:03:42 -0700108 processor_(new ActionProcessor()),
Tianjie Xud4c5deb2017-10-24 11:17:03 -0700109 clock_(new Clock()) {
110 metrics_reporter_ = metrics::CreateMetricsReporter();
Alex Deymo87792ea2016-07-25 15:40:36 -0700111 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800112}
113
114UpdateAttempterAndroid::~UpdateAttempterAndroid() {
115 // Release ourselves as the ActionProcessor's delegate to prevent
116 // re-scheduling the updates due to the processing stopped.
117 processor_->set_delegate(nullptr);
118}
119
120void UpdateAttempterAndroid::Init() {
121 // In case of update_engine restart without a reboot we need to restore the
122 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700123 if (UpdateCompletedOnThisBoot()) {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800124 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700125 } else {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800126 SetStatusAndNotify(UpdateStatus::IDLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700127 UpdatePrefsAndReportUpdateMetricsOnReboot();
128 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800129}
130
131bool UpdateAttempterAndroid::ApplyPayload(
132 const string& payload_url,
133 int64_t payload_offset,
134 int64_t payload_size,
135 const vector<string>& key_value_pair_headers,
136 brillo::ErrorPtr* error) {
137 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
138 return LogAndSetError(
139 error, FROM_HERE, "An update already applied, waiting for reboot");
140 }
141 if (ongoing_update_) {
142 return LogAndSetError(
143 error, FROM_HERE, "Already processing an update, cancel it first.");
144 }
145 DCHECK(status_ == UpdateStatus::IDLE);
146
Alex Deymo218397f2016-02-04 23:55:10 -0800147 std::map<string, string> headers;
148 for (const string& key_value_pair : key_value_pair_headers) {
149 string key;
150 string value;
151 if (!brillo::string_utils::SplitAtFirst(
152 key_value_pair, "=", &key, &value, false)) {
153 return LogAndSetError(
154 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
155 }
156 if (!headers.emplace(key, value).second)
157 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
158 }
159
160 // Unique identifier for the payload. An empty string means that the payload
161 // can't be resumed.
162 string payload_id = (headers[kPayloadPropertyFileHash] +
163 headers[kPayloadPropertyMetadataHash]);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800164
165 // Setup the InstallPlan based on the request.
166 install_plan_ = InstallPlan();
167
168 install_plan_.download_url = payload_url;
169 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800170 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800171 InstallPlan::Payload payload;
172 payload.size = payload_size;
173 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800174 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800175 &payload.size)) {
176 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800177 }
178 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700179 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800180 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700181 LOG(WARNING) << "Unable to decode base64 file hash: "
182 << headers[kPayloadPropertyFileHash];
183 }
Alex Deymo218397f2016-02-04 23:55:10 -0800184 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800185 &payload.metadata_size)) {
186 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800187 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700188 // The |payload.type| is not used anymore since minor_version 3.
189 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800190 install_plan_.payloads.push_back(payload);
191
Alex Deymo5e3ea272016-01-28 13:42:23 -0800192 // The |public_key_rsa| key would override the public key stored on disk.
193 install_plan_.public_key_rsa = "";
194
195 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
196 install_plan_.is_resume = !payload_id.empty() &&
197 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
198 if (!install_plan_.is_resume) {
199 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
200 LOG(WARNING) << "Unable to reset the update progress.";
201 }
202 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
203 LOG(WARNING) << "Unable to save the update check response hash.";
204 }
205 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800206 install_plan_.source_slot = boot_control_->GetCurrentSlot();
207 install_plan_.target_slot = install_plan_.source_slot == 0 ? 1 : 0;
Alex Deymofb905d92016-06-03 19:26:58 -0700208
Alex Deymofb905d92016-06-03 19:26:58 -0700209 install_plan_.powerwash_required =
Sen Jiang02c49422017-10-31 15:14:11 -0700210 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
211
212 install_plan_.switch_slot_on_reboot =
213 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
214
215 install_plan_.run_post_install = true;
216 // Optionally skip post install if and only if:
217 // a) we're resuming
218 // b) post install has already succeeded before
219 // c) RUN_POST_INSTALL is set to 0.
220 if (install_plan_.is_resume && prefs_->Exists(kPrefsPostInstallSucceeded)) {
221 bool post_install_succeeded = false;
222 prefs_->GetBoolean(kPrefsPostInstallSucceeded, &post_install_succeeded);
223 if (post_install_succeeded) {
224 install_plan_.run_post_install =
225 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
226 }
227 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800228
Alex Deymo87792ea2016-07-25 15:40:36 -0700229 NetworkId network_id = kDefaultNetworkId;
230 if (!headers[kPayloadPropertyNetworkId].empty()) {
231 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
232 &network_id)) {
233 return LogAndSetError(
234 error,
235 FROM_HERE,
236 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
237 }
238 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700239 return LogAndSetError(
240 error,
241 FROM_HERE,
242 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700243 }
244 }
245
Alex Deymo5e3ea272016-01-28 13:42:23 -0800246 LOG(INFO) << "Using this install plan:";
247 install_plan_.Dump();
248
Amin Hassani667cf7b2018-07-25 14:32:00 -0700249 HttpFetcher* fetcher = nullptr;
250 if (FileFetcher::SupportedUrl(payload_url)) {
251 DLOG(INFO) << "Using FileFetcher for file URL.";
252 fetcher = new FileFetcher();
253 } else {
254#ifdef _UE_SIDELOAD
255 LOG(FATAL) << "Unsupported sideload URI: " << payload_url;
256#else
257 LibcurlHttpFetcher* libcurl_fetcher =
258 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
259 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
260 fetcher = libcurl_fetcher;
261#endif // _UE_SIDELOAD
262 }
Alex Deymofdd6dec2016-03-03 22:35:43 -0800263 // Setup extra headers.
Alex Deymofdd6dec2016-03-03 22:35:43 -0800264 if (!headers[kPayloadPropertyAuthorization].empty())
265 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
266 if (!headers[kPayloadPropertyUserAgent].empty())
267 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
268
Amin Hassani667cf7b2018-07-25 14:32:00 -0700269 BuildUpdateActions(fetcher);
270
Alex Deymo5e3ea272016-01-28 13:42:23 -0800271 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Alex Deymof2858572016-02-25 11:20:13 -0800272 ongoing_update_ = true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800273
Tianjie Xu90aaa102017-10-10 17:39:03 -0700274 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
275 // TODO(xunchang) report the metrics for unresumable updates
276
Amin Hassani667cf7b2018-07-25 14:32:00 -0700277 ScheduleProcessingStart();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800278 return true;
279}
280
281bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Alex Deymof2858572016-02-25 11:20:13 -0800282 if (!ongoing_update_)
283 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
284 processor_->SuspendProcessing();
285 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800286}
287
288bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Alex Deymof2858572016-02-25 11:20:13 -0800289 if (!ongoing_update_)
290 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
291 processor_->ResumeProcessing();
292 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800293}
294
295bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Alex Deymof2858572016-02-25 11:20:13 -0800296 if (!ongoing_update_)
Alex Deymo5e3ea272016-01-28 13:42:23 -0800297 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800298 processor_->StopProcessing();
299 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800300}
301
Alex Deymo3b678db2016-02-09 11:50:06 -0800302bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
303 LOG(INFO) << "Attempting to reset state from "
304 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
305
306 switch (status_) {
307 case UpdateStatus::IDLE:
308 return true;
309
310 case UpdateStatus::UPDATED_NEED_REBOOT: {
311 // Remove the reboot marker so that if the machine is rebooted
312 // after resetting to idle state, it doesn't go back to
313 // UpdateStatus::UPDATED_NEED_REBOOT state.
314 bool ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700315 ClearMetricsPrefs();
Alex Deymo3b678db2016-02-09 11:50:06 -0800316
317 // Update the boot flags so the current slot has higher priority.
318 if (!boot_control_->SetActiveBootSlot(boot_control_->GetCurrentSlot()))
319 ret_value = false;
320
Alex Deymo52590332016-11-29 18:29:13 -0800321 // Mark the current slot as successful again, since marking it as active
322 // may reset the successful bit. We ignore the result of whether marking
323 // the current slot as successful worked.
324 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful){})))
325 ret_value = false;
326
Alex Deymo3b678db2016-02-09 11:50:06 -0800327 if (!ret_value) {
328 return LogAndSetError(
329 error,
330 FROM_HERE,
331 "Failed to reset the status to ");
332 }
333
334 SetStatusAndNotify(UpdateStatus::IDLE);
335 LOG(INFO) << "Reset status successful";
336 return true;
337 }
338
339 default:
340 return LogAndSetError(
341 error,
342 FROM_HERE,
343 "Reset not allowed in this state. Cancel the ongoing update first");
344 }
345}
346
Sen Jiang28d8ed92018-02-01 13:46:39 -0800347bool UpdateAttempterAndroid::VerifyPayloadApplicable(
348 const std::string& metadata_filename, brillo::ErrorPtr* error) {
349 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
350 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
351 return LogAndSetError(
352 error, FROM_HERE, "Failed to open " + metadata_filename);
353 }
354 brillo::Blob metadata(kMaxPayloadHeaderSize);
355 if (!fd->Read(metadata.data(), metadata.size())) {
356 return LogAndSetError(
357 error,
358 FROM_HERE,
359 "Failed to read payload header from " + metadata_filename);
360 }
361 ErrorCode errorcode;
362 PayloadMetadata payload_metadata;
Sen Jiangdcaf7972018-05-11 16:03:23 -0700363 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang28d8ed92018-02-01 13:46:39 -0800364 MetadataParseResult::kSuccess) {
365 return LogAndSetError(error,
366 FROM_HERE,
367 "Failed to parse payload header: " +
368 utils::ErrorCodeToString(errorcode));
369 }
370 metadata.resize(payload_metadata.GetMetadataSize() +
371 payload_metadata.GetMetadataSignatureSize());
372 if (metadata.size() < kMaxPayloadHeaderSize) {
373 return LogAndSetError(
374 error,
375 FROM_HERE,
376 "Metadata size too small: " + std::to_string(metadata.size()));
377 }
378 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
379 metadata.size() - kMaxPayloadHeaderSize)) {
380 return LogAndSetError(
381 error,
382 FROM_HERE,
383 "Failed to read metadata and signature from " + metadata_filename);
384 }
385 fd->Close();
386 errorcode = payload_metadata.ValidateMetadataSignature(
387 metadata, "", base::FilePath(constants::kUpdatePayloadPublicKeyPath));
388 if (errorcode != ErrorCode::kSuccess) {
389 return LogAndSetError(error,
390 FROM_HERE,
391 "Failed to validate metadata signature: " +
392 utils::ErrorCodeToString(errorcode));
393 }
394 DeltaArchiveManifest manifest;
395 if (!payload_metadata.GetManifest(metadata, &manifest)) {
396 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
397 }
398
399 BootControlInterface::Slot current_slot = boot_control_->GetCurrentSlot();
400 for (const PartitionUpdate& partition : manifest.partitions()) {
401 if (!partition.has_old_partition_info())
402 continue;
403 string partition_path;
404 if (!boot_control_->GetPartitionDevice(
405 partition.partition_name(), current_slot, &partition_path)) {
406 return LogAndSetError(
407 error,
408 FROM_HERE,
409 "Failed to get partition device for " + partition.partition_name());
410 }
411 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
412 return LogAndSetError(
413 error, FROM_HERE, "Failed to open " + partition_path);
414 }
415 for (const InstallOperation& operation : partition.operations()) {
416 if (!operation.has_src_sha256_hash())
417 continue;
418 brillo::Blob source_hash;
419 if (!fd_utils::ReadAndHashExtents(fd,
420 operation.src_extents(),
421 manifest.block_size(),
422 &source_hash)) {
423 return LogAndSetError(
424 error, FROM_HERE, "Failed to hash " + partition_path);
425 }
426 if (!DeltaPerformer::ValidateSourceHash(
427 source_hash, operation, fd, &errorcode)) {
428 return false;
429 }
430 }
431 fd->Close();
432 }
433 return true;
434}
435
Alex Deymo5e3ea272016-01-28 13:42:23 -0800436void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
437 ErrorCode code) {
438 LOG(INFO) << "Processing Done.";
439
Alex Deymo5990bf32016-07-19 17:01:41 -0700440 switch (code) {
441 case ErrorCode::kSuccess:
442 // Update succeeded.
443 WriteUpdateCompletedMarker();
444 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800445
Alex Deymo5990bf32016-07-19 17:01:41 -0700446 LOG(INFO) << "Update successfully applied, waiting to reboot.";
447 break;
448
449 case ErrorCode::kFilesystemCopierError:
450 case ErrorCode::kNewRootfsVerificationError:
451 case ErrorCode::kNewKernelVerificationError:
452 case ErrorCode::kFilesystemVerifierError:
453 case ErrorCode::kDownloadStateInitializationError:
454 // Reset the ongoing update for these errors so it starts from the
455 // beginning next time.
456 DeltaPerformer::ResetUpdateProgress(prefs_, false);
457 LOG(INFO) << "Resetting update progress.";
458 break;
459
460 default:
461 // Ignore all other error codes.
462 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700463 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800464
465 TerminateUpdateAndNotify(code);
466}
467
468void UpdateAttempterAndroid::ProcessingStopped(
469 const ActionProcessor* processor) {
470 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
471}
472
473void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
474 AbstractAction* action,
475 ErrorCode code) {
476 // Reset download progress regardless of whether or not the download
477 // action succeeded.
478 const string type = action->Type();
479 if (type == DownloadAction::StaticType()) {
Alex Deymo0d298542016-03-30 18:31:49 -0700480 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800481 }
Sen Jiang02c49422017-10-31 15:14:11 -0700482 if (type == PostinstallRunnerAction::StaticType()) {
483 bool succeeded =
484 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
485 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
486 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800487 if (code != ErrorCode::kSuccess) {
488 // If an action failed, the ActionProcessor will cancel the whole thing.
489 return;
490 }
491 if (type == DownloadAction::StaticType()) {
492 SetStatusAndNotify(UpdateStatus::FINALIZING);
493 }
494}
495
496void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
497 uint64_t bytes_received,
498 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700499 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800500 if (total)
501 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700502 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800503 download_progress_ = progress;
504 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700505 } else {
506 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800507 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700508
509 // Update the bytes downloaded in prefs.
510 int64_t current_bytes_downloaded =
511 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
512 int64_t total_bytes_downloaded =
513 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
514 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
515 current_bytes_downloaded + bytes_progressed);
516 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
517 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800518}
519
520bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
521 // TODO(deymo): Notify the DownloadAction that it should cancel the update
522 // download.
523 return false;
524}
525
526void UpdateAttempterAndroid::DownloadComplete() {
527 // Nothing needs to be done when the download completes.
528}
529
Alex Deymo0d298542016-03-30 18:31:49 -0700530void UpdateAttempterAndroid::ProgressUpdate(double progress) {
531 // Self throttle based on progress. Also send notifications if progress is
532 // too slow.
533 if (progress == 1.0 ||
534 progress - download_progress_ >= kBroadcastThresholdProgress ||
535 TimeTicks::Now() - last_notify_time_ >=
536 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
537 download_progress_ = progress;
538 SetStatusAndNotify(status_);
539 }
540}
541
Alex Deymo5e3ea272016-01-28 13:42:23 -0800542void UpdateAttempterAndroid::ScheduleProcessingStart() {
543 LOG(INFO) << "Scheduling an action processor start.";
544 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700545 FROM_HERE,
546 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
547 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800548}
549
550void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
551 if (status_ == UpdateStatus::IDLE) {
552 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
553 return;
554 }
555
Alex Deymo0d298542016-03-30 18:31:49 -0700556 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800557 UpdateStatus new_status =
558 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
559 : UpdateStatus::IDLE);
560 SetStatusAndNotify(new_status);
561 ongoing_update_ = false;
562
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700563 // The network id is only applicable to one download attempt and once it's
564 // done the network id should not be re-used anymore.
565 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
566 LOG(WARNING) << "Unable to unbind network.";
567 }
568
Alex Deymo5e3ea272016-01-28 13:42:23 -0800569 for (auto observer : daemon_state_->service_observers())
570 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700571
Tianjie Xu90aaa102017-10-10 17:39:03 -0700572 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
573 ClearMetricsPrefs();
574 if (error_code == ErrorCode::kSuccess) {
575 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700576 // Clear the total bytes downloaded if and only if the update succeeds.
577 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700578 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800579}
580
581void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
582 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700583 size_t payload_size =
584 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700585 UpdateEngineStatus status_to_send = {.status = status_,
586 .progress = download_progress_,
587 .new_size_bytes = payload_size};
588
Alex Deymo5e3ea272016-01-28 13:42:23 -0800589 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700590 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800591 }
592 last_notify_time_ = TimeTicks::Now();
593}
594
Amin Hassani667cf7b2018-07-25 14:32:00 -0700595void UpdateAttempterAndroid::BuildUpdateActions(HttpFetcher* fetcher) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800596 CHECK(!processor_->IsRunning());
597 processor_->set_delegate(this);
598
599 // Actions:
Amin Hassani667cf7b2018-07-25 14:32:00 -0700600 auto update_boot_flags_action =
601 std::make_unique<UpdateBootFlagsAction>(boot_control_);
602 auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan_);
603 auto download_action =
604 std::make_unique<DownloadAction>(prefs_,
605 boot_control_,
606 hardware_,
607 nullptr, // system_state, not used.
608 fetcher, // passes ownership
609 true /* interactive */);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800610 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700611 download_action->set_base_offset(base_offset_);
Amin Hassani667cf7b2018-07-25 14:32:00 -0700612 auto filesystem_verifier_action =
613 std::make_unique<FilesystemVerifierAction>();
614 auto postinstall_runner_action =
615 std::make_unique<PostinstallRunnerAction>(boot_control_, hardware_);
Alex Deymob6eef732016-06-10 12:58:11 -0700616 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800617
Alex Deymo5e3ea272016-01-28 13:42:23 -0800618 // Bond them together. We have to use the leaf-types when calling
619 // BondActions().
620 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700621 BondActions(download_action.get(), filesystem_verifier_action.get());
622 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800623 postinstall_runner_action.get());
624
Amin Hassani667cf7b2018-07-25 14:32:00 -0700625 processor_->EnqueueAction(std::move(update_boot_flags_action));
626 processor_->EnqueueAction(std::move(install_plan_action));
627 processor_->EnqueueAction(std::move(download_action));
628 processor_->EnqueueAction(std::move(filesystem_verifier_action));
629 processor_->EnqueueAction(std::move(postinstall_runner_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800630}
631
Alex Deymo5e3ea272016-01-28 13:42:23 -0800632bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
633 string boot_id;
634 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
635 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
636 return true;
637}
638
639bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
640 // In case of an update_engine restart without a reboot, we stored the boot_id
641 // when the update was completed by setting a pref, so we can check whether
642 // the last update was on this boot or a previous one.
643 string boot_id;
644 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
645
646 string update_completed_on_boot_id;
647 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
648 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
649 &update_completed_on_boot_id) &&
650 update_completed_on_boot_id == boot_id);
651}
652
Tianjie Xu90aaa102017-10-10 17:39:03 -0700653// Collect and report the android metrics when we terminate the update.
654void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
655 ErrorCode error_code) {
656 int64_t attempt_number =
657 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
658 PayloadType payload_type = kPayloadTypeFull;
659 int64_t payload_size = 0;
660 for (const auto& p : install_plan_.payloads) {
661 if (p.type == InstallPayloadType::kDelta)
662 payload_type = kPayloadTypeDelta;
663 payload_size += p.size;
664 }
665
666 metrics::AttemptResult attempt_result =
667 metrics_utils::GetAttemptResult(error_code);
668 Time attempt_start_time = Time::FromInternalValue(
669 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu52c678c2017-10-18 15:52:27 -0700670 TimeDelta duration = clock_->GetBootTime() - attempt_start_time;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700671 TimeDelta duration_uptime = clock_->GetMonotonicTime() - attempt_start_time;
672
673 metrics_reporter_->ReportUpdateAttemptMetrics(
674 nullptr, // system_state
675 static_cast<int>(attempt_number),
676 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700677 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700678 duration_uptime,
679 payload_size,
680 attempt_result,
681 error_code);
682
Tianjie Xud4777a12017-10-24 14:54:18 -0700683 int64_t current_bytes_downloaded =
684 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
685 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
686 current_bytes_downloaded,
687 0,
688 DownloadSource::kNumDownloadSources,
689 metrics::DownloadErrorCode::kUnset,
690 metrics::ConnectionType::kUnset);
691
Tianjie Xu90aaa102017-10-10 17:39:03 -0700692 if (error_code == ErrorCode::kSuccess) {
693 int64_t reboot_count =
694 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
695 string build_version;
696 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700697
698 // For android metrics, we only care about the total bytes downloaded
699 // for all sources; for now we assume the only download source is
700 // HttpsServer.
701 int64_t total_bytes_downloaded =
702 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
703 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
704 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
705 total_bytes_downloaded;
706
707 int download_overhead_percentage = 0;
708 if (current_bytes_downloaded > 0) {
709 download_overhead_percentage =
710 (total_bytes_downloaded - current_bytes_downloaded) * 100ull /
711 current_bytes_downloaded;
712 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700713 metrics_reporter_->ReportSuccessfulUpdateMetrics(
714 static_cast<int>(attempt_number),
715 0, // update abandoned count
716 payload_type,
717 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700718 num_bytes_downloaded,
719 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700720 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700721 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700722 static_cast<int>(reboot_count),
723 0); // url_switch_count
724 }
725}
726
727void UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
728 string current_boot_id;
729 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
730 // Example: [ro.build.version.incremental]: [4292972]
731 string current_version =
732 android::base::GetProperty("ro.build.version.incremental", "");
733 TEST_AND_RETURN(!current_version.empty());
734
735 // If there's no record of previous version (e.g. due to a data wipe), we
736 // save the info of current boot and skip the metrics report.
737 if (!prefs_->Exists(kPrefsPreviousVersion)) {
738 prefs_->SetString(kPrefsBootId, current_boot_id);
739 prefs_->SetString(kPrefsPreviousVersion, current_version);
740 ClearMetricsPrefs();
741 return;
742 }
743 string previous_version;
744 // update_engine restarted under the same build.
745 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
746 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
747 previous_version == current_version) {
748 string last_boot_id;
749 bool is_reboot = prefs_->Exists(kPrefsBootId) &&
750 (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
751 last_boot_id != current_boot_id);
752 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
753 // set when we start a new update.
754 if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
755 prefs_->SetString(kPrefsBootId, current_boot_id);
756 int64_t reboot_count =
757 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
758 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
759 }
760 return;
761 }
762
763 // Now that the build version changes, report the update metrics.
764 // TODO(xunchang) check the build version is larger than the previous one.
765 prefs_->SetString(kPrefsBootId, current_boot_id);
766 prefs_->SetString(kPrefsPreviousVersion, current_version);
767
768 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
769 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
770 if (previous_attempt_exists) {
771 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
772 }
773
774 metrics_utils::LoadAndReportTimeToReboot(
775 metrics_reporter_.get(), prefs_, clock_.get());
776 ClearMetricsPrefs();
777}
778
779// Save the update start time. Reset the reboot count and attempt number if the
780// update isn't a resume; otherwise increment the attempt number.
781void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
782 if (!is_resume) {
783 metrics_utils::SetNumReboots(0, prefs_);
784 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
785 } else {
786 int64_t attempt_number =
787 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
788 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
789 }
790 Time update_start_time = clock_->GetMonotonicTime();
791 metrics_utils::SetUpdateTimestampStart(update_start_time, prefs_);
792}
793
794void UpdateAttempterAndroid::ClearMetricsPrefs() {
795 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700796 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700797 prefs_->Delete(kPrefsNumReboots);
798 prefs_->Delete(kPrefsPayloadAttemptNumber);
799 prefs_->Delete(kPrefsSystemUpdatedMarker);
800 prefs_->Delete(kPrefsUpdateTimestampStart);
801}
802
Alex Deymo5e3ea272016-01-28 13:42:23 -0800803} // namespace chromeos_update_engine