blob: 3ddfd8546eea8f9dda6cf3f55c2658e6a15d85b9 [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"
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 Jiangfe522822017-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 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700141 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800142 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 Jiangfe522822017-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
Alex Deymo2c131bb2016-05-26 16:43:13 -0700249 BuildUpdateActions(payload_url);
Alex Deymofdd6dec2016-03-03 22:35:43 -0800250 // Setup extra headers.
251 HttpFetcher* fetcher = download_action_->http_fetcher();
252 if (!headers[kPayloadPropertyAuthorization].empty())
253 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
254 if (!headers[kPayloadPropertyUserAgent].empty())
255 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
256
Alex Deymo5e3ea272016-01-28 13:42:23 -0800257 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
258
259 // Just in case we didn't update boot flags yet, make sure they're updated
260 // before any update processing starts. This will start the update process.
261 UpdateBootFlags();
Tianjie Xu90aaa102017-10-10 17:39:03 -0700262
263 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
264 // TODO(xunchang) report the metrics for unresumable updates
265
Alex Deymo5e3ea272016-01-28 13:42:23 -0800266 return true;
267}
268
269bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700270 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800271 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
272 processor_->SuspendProcessing();
273 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800274}
275
276bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700277 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800278 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
279 processor_->ResumeProcessing();
280 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800281}
282
283bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700284 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800285 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800286 processor_->StopProcessing();
287 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800288}
289
Alex Deymo3b678db2016-02-09 11:50:06 -0800290bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
291 LOG(INFO) << "Attempting to reset state from "
292 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
293
294 switch (status_) {
295 case UpdateStatus::IDLE:
296 return true;
297
298 case UpdateStatus::UPDATED_NEED_REBOOT: {
299 // Remove the reboot marker so that if the machine is rebooted
300 // after resetting to idle state, it doesn't go back to
301 // UpdateStatus::UPDATED_NEED_REBOOT state.
302 bool ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700303 ClearMetricsPrefs();
Alex Deymo3b678db2016-02-09 11:50:06 -0800304
305 // Update the boot flags so the current slot has higher priority.
306 if (!boot_control_->SetActiveBootSlot(boot_control_->GetCurrentSlot()))
307 ret_value = false;
308
Alex Deymo52590332016-11-29 18:29:13 -0800309 // Mark the current slot as successful again, since marking it as active
310 // may reset the successful bit. We ignore the result of whether marking
311 // the current slot as successful worked.
312 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful){})))
313 ret_value = false;
314
Alex Deymo3b678db2016-02-09 11:50:06 -0800315 if (!ret_value) {
316 return LogAndSetError(
317 error,
318 FROM_HERE,
319 "Failed to reset the status to ");
320 }
321
322 SetStatusAndNotify(UpdateStatus::IDLE);
323 LOG(INFO) << "Reset status successful";
324 return true;
325 }
326
327 default:
328 return LogAndSetError(
329 error,
330 FROM_HERE,
331 "Reset not allowed in this state. Cancel the ongoing update first");
332 }
333}
334
Sen Jiang8371c1c2018-02-01 13:46:39 -0800335bool UpdateAttempterAndroid::VerifyPayloadApplicable(
336 const std::string& metadata_filename, brillo::ErrorPtr* error) {
337 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
338 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
339 return LogAndSetError(
340 error, FROM_HERE, "Failed to open " + metadata_filename);
341 }
342 brillo::Blob metadata(kMaxPayloadHeaderSize);
343 if (!fd->Read(metadata.data(), metadata.size())) {
344 return LogAndSetError(
345 error,
346 FROM_HERE,
347 "Failed to read payload header from " + metadata_filename);
348 }
349 ErrorCode errorcode;
350 PayloadMetadata payload_metadata;
Sen Jiangf1236632018-05-11 16:03:23 -0700351 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang8371c1c2018-02-01 13:46:39 -0800352 MetadataParseResult::kSuccess) {
353 return LogAndSetError(error,
354 FROM_HERE,
355 "Failed to parse payload header: " +
356 utils::ErrorCodeToString(errorcode));
357 }
358 metadata.resize(payload_metadata.GetMetadataSize() +
359 payload_metadata.GetMetadataSignatureSize());
360 if (metadata.size() < kMaxPayloadHeaderSize) {
361 return LogAndSetError(
362 error,
363 FROM_HERE,
364 "Metadata size too small: " + std::to_string(metadata.size()));
365 }
366 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
367 metadata.size() - kMaxPayloadHeaderSize)) {
368 return LogAndSetError(
369 error,
370 FROM_HERE,
371 "Failed to read metadata and signature from " + metadata_filename);
372 }
373 fd->Close();
374 errorcode = payload_metadata.ValidateMetadataSignature(
375 metadata, "", base::FilePath(constants::kUpdatePayloadPublicKeyPath));
376 if (errorcode != ErrorCode::kSuccess) {
377 return LogAndSetError(error,
378 FROM_HERE,
379 "Failed to validate metadata signature: " +
380 utils::ErrorCodeToString(errorcode));
381 }
382 DeltaArchiveManifest manifest;
383 if (!payload_metadata.GetManifest(metadata, &manifest)) {
384 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
385 }
386
387 BootControlInterface::Slot current_slot = boot_control_->GetCurrentSlot();
388 for (const PartitionUpdate& partition : manifest.partitions()) {
389 if (!partition.has_old_partition_info())
390 continue;
391 string partition_path;
392 if (!boot_control_->GetPartitionDevice(
393 partition.partition_name(), current_slot, &partition_path)) {
394 return LogAndSetError(
395 error,
396 FROM_HERE,
397 "Failed to get partition device for " + partition.partition_name());
398 }
399 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
400 return LogAndSetError(
401 error, FROM_HERE, "Failed to open " + partition_path);
402 }
403 for (const InstallOperation& operation : partition.operations()) {
404 if (!operation.has_src_sha256_hash())
405 continue;
406 brillo::Blob source_hash;
407 if (!fd_utils::ReadAndHashExtents(fd,
408 operation.src_extents(),
409 manifest.block_size(),
410 &source_hash)) {
411 return LogAndSetError(
412 error, FROM_HERE, "Failed to hash " + partition_path);
413 }
414 if (!DeltaPerformer::ValidateSourceHash(
415 source_hash, operation, fd, &errorcode)) {
416 return false;
417 }
418 }
419 fd->Close();
420 }
421 return true;
422}
423
Alex Deymo5e3ea272016-01-28 13:42:23 -0800424void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
425 ErrorCode code) {
426 LOG(INFO) << "Processing Done.";
427
Alex Deymo5990bf32016-07-19 17:01:41 -0700428 switch (code) {
429 case ErrorCode::kSuccess:
430 // Update succeeded.
431 WriteUpdateCompletedMarker();
432 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800433
Alex Deymo5990bf32016-07-19 17:01:41 -0700434 LOG(INFO) << "Update successfully applied, waiting to reboot.";
435 break;
436
437 case ErrorCode::kFilesystemCopierError:
438 case ErrorCode::kNewRootfsVerificationError:
439 case ErrorCode::kNewKernelVerificationError:
440 case ErrorCode::kFilesystemVerifierError:
441 case ErrorCode::kDownloadStateInitializationError:
442 // Reset the ongoing update for these errors so it starts from the
443 // beginning next time.
444 DeltaPerformer::ResetUpdateProgress(prefs_, false);
445 LOG(INFO) << "Resetting update progress.";
446 break;
447
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700448 case ErrorCode::kPayloadTimestampError:
449 // SafetyNet logging, b/36232423
450 android_errorWriteLog(0x534e4554, "36232423");
451 break;
452
Alex Deymo5990bf32016-07-19 17:01:41 -0700453 default:
454 // Ignore all other error codes.
455 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700456 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800457
458 TerminateUpdateAndNotify(code);
459}
460
461void UpdateAttempterAndroid::ProcessingStopped(
462 const ActionProcessor* processor) {
463 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
464}
465
466void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
467 AbstractAction* action,
468 ErrorCode code) {
469 // Reset download progress regardless of whether or not the download
470 // action succeeded.
471 const string type = action->Type();
472 if (type == DownloadAction::StaticType()) {
Alex Deymo0d298542016-03-30 18:31:49 -0700473 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800474 }
Sen Jiangfe522822017-10-31 15:14:11 -0700475 if (type == PostinstallRunnerAction::StaticType()) {
476 bool succeeded =
477 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
478 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
479 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800480 if (code != ErrorCode::kSuccess) {
481 // If an action failed, the ActionProcessor will cancel the whole thing.
482 return;
483 }
484 if (type == DownloadAction::StaticType()) {
485 SetStatusAndNotify(UpdateStatus::FINALIZING);
486 }
487}
488
489void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
490 uint64_t bytes_received,
491 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700492 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800493 if (total)
494 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700495 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800496 download_progress_ = progress;
497 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700498 } else {
499 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800500 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700501
502 // Update the bytes downloaded in prefs.
503 int64_t current_bytes_downloaded =
504 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
505 int64_t total_bytes_downloaded =
506 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
507 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
508 current_bytes_downloaded + bytes_progressed);
509 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
510 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800511}
512
513bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
514 // TODO(deymo): Notify the DownloadAction that it should cancel the update
515 // download.
516 return false;
517}
518
519void UpdateAttempterAndroid::DownloadComplete() {
520 // Nothing needs to be done when the download completes.
521}
522
Alex Deymo0d298542016-03-30 18:31:49 -0700523void UpdateAttempterAndroid::ProgressUpdate(double progress) {
524 // Self throttle based on progress. Also send notifications if progress is
525 // too slow.
526 if (progress == 1.0 ||
527 progress - download_progress_ >= kBroadcastThresholdProgress ||
528 TimeTicks::Now() - last_notify_time_ >=
529 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
530 download_progress_ = progress;
531 SetStatusAndNotify(status_);
532 }
533}
534
Alex Deymo5e3ea272016-01-28 13:42:23 -0800535void UpdateAttempterAndroid::UpdateBootFlags() {
536 if (updated_boot_flags_) {
537 LOG(INFO) << "Already updated boot flags. Skipping.";
538 CompleteUpdateBootFlags(true);
539 return;
540 }
541 // This is purely best effort.
542 LOG(INFO) << "Marking booted slot as good.";
543 if (!boot_control_->MarkBootSuccessfulAsync(
544 Bind(&UpdateAttempterAndroid::CompleteUpdateBootFlags,
545 base::Unretained(this)))) {
546 LOG(ERROR) << "Failed to mark current boot as successful.";
547 CompleteUpdateBootFlags(false);
548 }
549}
550
551void UpdateAttempterAndroid::CompleteUpdateBootFlags(bool successful) {
552 updated_boot_flags_ = true;
553 ScheduleProcessingStart();
554}
555
556void UpdateAttempterAndroid::ScheduleProcessingStart() {
557 LOG(INFO) << "Scheduling an action processor start.";
558 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700559 FROM_HERE,
560 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
561 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800562}
563
564void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
565 if (status_ == UpdateStatus::IDLE) {
566 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
567 return;
568 }
569
Alex Deymo0d298542016-03-30 18:31:49 -0700570 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800571 actions_.clear();
572 UpdateStatus new_status =
573 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
574 : UpdateStatus::IDLE);
575 SetStatusAndNotify(new_status);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800576
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700577 // The network id is only applicable to one download attempt and once it's
578 // done the network id should not be re-used anymore.
579 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
580 LOG(WARNING) << "Unable to unbind network.";
581 }
582
Alex Deymo5e3ea272016-01-28 13:42:23 -0800583 for (auto observer : daemon_state_->service_observers())
584 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700585
Tianjie Xu90aaa102017-10-10 17:39:03 -0700586 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
587 ClearMetricsPrefs();
588 if (error_code == ErrorCode::kSuccess) {
589 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700590 // Clear the total bytes downloaded if and only if the update succeeds.
591 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700592 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800593}
594
595void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
596 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700597 size_t payload_size =
598 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700599 UpdateEngineStatus status_to_send = {.status = status_,
600 .progress = download_progress_,
601 .new_size_bytes = payload_size};
602
Alex Deymo5e3ea272016-01-28 13:42:23 -0800603 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700604 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800605 }
606 last_notify_time_ = TimeTicks::Now();
607}
608
Alex Deymo2c131bb2016-05-26 16:43:13 -0700609void UpdateAttempterAndroid::BuildUpdateActions(const string& url) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800610 CHECK(!processor_->IsRunning());
611 processor_->set_delegate(this);
612
613 // Actions:
614 shared_ptr<InstallPlanAction> install_plan_action(
615 new InstallPlanAction(install_plan_));
616
Alex Deymo2c131bb2016-05-26 16:43:13 -0700617 HttpFetcher* download_fetcher = nullptr;
618 if (FileFetcher::SupportedUrl(url)) {
619 DLOG(INFO) << "Using FileFetcher for file URL.";
620 download_fetcher = new FileFetcher();
621 } else {
Alex Deymo14c0da82016-07-20 16:45:45 -0700622#ifdef _UE_SIDELOAD
623 LOG(FATAL) << "Unsupported sideload URI: " << url;
624#else
Alex Deymo2c131bb2016-05-26 16:43:13 -0700625 LibcurlHttpFetcher* libcurl_fetcher =
626 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
627 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
628 download_fetcher = libcurl_fetcher;
Alex Deymo14c0da82016-07-20 16:45:45 -0700629#endif // _UE_SIDELOAD
Alex Deymo2c131bb2016-05-26 16:43:13 -0700630 }
Sen Jiang5ae865b2017-04-18 14:24:40 -0700631 shared_ptr<DownloadAction> download_action(
632 new DownloadAction(prefs_,
633 boot_control_,
634 hardware_,
Sen Jiang44906962018-01-08 17:39:04 -0800635 nullptr, // system_state, not used.
636 download_fetcher, // passes ownership
Amin Hassanied37d682018-04-06 13:22:00 -0700637 true /* interactive */));
Sen Jiangfef85fd2016-03-25 15:32:49 -0700638 shared_ptr<FilesystemVerifierAction> filesystem_verifier_action(
Sen Jiange6e4bb92016-04-05 14:59:12 -0700639 new FilesystemVerifierAction());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800640
641 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
Alex Deymofb905d92016-06-03 19:26:58 -0700642 new PostinstallRunnerAction(boot_control_, hardware_));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800643
644 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700645 download_action->set_base_offset(base_offset_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800646 download_action_ = download_action;
Alex Deymob6eef732016-06-10 12:58:11 -0700647 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800648
649 actions_.push_back(shared_ptr<AbstractAction>(install_plan_action));
650 actions_.push_back(shared_ptr<AbstractAction>(download_action));
Sen Jiangfef85fd2016-03-25 15:32:49 -0700651 actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800652 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
653
654 // Bond them together. We have to use the leaf-types when calling
655 // BondActions().
656 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700657 BondActions(download_action.get(), filesystem_verifier_action.get());
658 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800659 postinstall_runner_action.get());
660
661 // Enqueue the actions.
662 for (const shared_ptr<AbstractAction>& action : actions_)
663 processor_->EnqueueAction(action.get());
664}
665
Alex Deymo5e3ea272016-01-28 13:42:23 -0800666bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
667 string boot_id;
668 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
669 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
670 return true;
671}
672
673bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
674 // In case of an update_engine restart without a reboot, we stored the boot_id
675 // when the update was completed by setting a pref, so we can check whether
676 // the last update was on this boot or a previous one.
677 string boot_id;
678 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
679
680 string update_completed_on_boot_id;
681 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
682 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
683 &update_completed_on_boot_id) &&
684 update_completed_on_boot_id == boot_id);
685}
686
Tianjie Xu90aaa102017-10-10 17:39:03 -0700687// Collect and report the android metrics when we terminate the update.
688void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
689 ErrorCode error_code) {
690 int64_t attempt_number =
691 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
692 PayloadType payload_type = kPayloadTypeFull;
693 int64_t payload_size = 0;
694 for (const auto& p : install_plan_.payloads) {
695 if (p.type == InstallPayloadType::kDelta)
696 payload_type = kPayloadTypeDelta;
697 payload_size += p.size;
698 }
699
700 metrics::AttemptResult attempt_result =
701 metrics_utils::GetAttemptResult(error_code);
702 Time attempt_start_time = Time::FromInternalValue(
703 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu52c678c2017-10-18 15:52:27 -0700704 TimeDelta duration = clock_->GetBootTime() - attempt_start_time;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700705 TimeDelta duration_uptime = clock_->GetMonotonicTime() - attempt_start_time;
706
707 metrics_reporter_->ReportUpdateAttemptMetrics(
708 nullptr, // system_state
709 static_cast<int>(attempt_number),
710 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700711 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700712 duration_uptime,
713 payload_size,
714 attempt_result,
715 error_code);
716
Tianjie Xud4777a12017-10-24 14:54:18 -0700717 int64_t current_bytes_downloaded =
718 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
719 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
720 current_bytes_downloaded,
721 0,
722 DownloadSource::kNumDownloadSources,
723 metrics::DownloadErrorCode::kUnset,
724 metrics::ConnectionType::kUnset);
725
Tianjie Xu90aaa102017-10-10 17:39:03 -0700726 if (error_code == ErrorCode::kSuccess) {
727 int64_t reboot_count =
728 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
729 string build_version;
730 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700731
732 // For android metrics, we only care about the total bytes downloaded
733 // for all sources; for now we assume the only download source is
734 // HttpsServer.
735 int64_t total_bytes_downloaded =
736 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
737 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
738 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
739 total_bytes_downloaded;
740
741 int download_overhead_percentage = 0;
742 if (current_bytes_downloaded > 0) {
743 download_overhead_percentage =
744 (total_bytes_downloaded - current_bytes_downloaded) * 100ull /
745 current_bytes_downloaded;
746 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700747 metrics_reporter_->ReportSuccessfulUpdateMetrics(
748 static_cast<int>(attempt_number),
749 0, // update abandoned count
750 payload_type,
751 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700752 num_bytes_downloaded,
753 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700754 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700755 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700756 static_cast<int>(reboot_count),
757 0); // url_switch_count
758 }
759}
760
761void UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
762 string current_boot_id;
763 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
764 // Example: [ro.build.version.incremental]: [4292972]
765 string current_version =
766 android::base::GetProperty("ro.build.version.incremental", "");
767 TEST_AND_RETURN(!current_version.empty());
768
769 // If there's no record of previous version (e.g. due to a data wipe), we
770 // save the info of current boot and skip the metrics report.
771 if (!prefs_->Exists(kPrefsPreviousVersion)) {
772 prefs_->SetString(kPrefsBootId, current_boot_id);
773 prefs_->SetString(kPrefsPreviousVersion, current_version);
774 ClearMetricsPrefs();
775 return;
776 }
777 string previous_version;
778 // update_engine restarted under the same build.
779 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
780 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
781 previous_version == current_version) {
782 string last_boot_id;
783 bool is_reboot = prefs_->Exists(kPrefsBootId) &&
784 (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
785 last_boot_id != current_boot_id);
786 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
787 // set when we start a new update.
788 if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
789 prefs_->SetString(kPrefsBootId, current_boot_id);
790 int64_t reboot_count =
791 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
792 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
793 }
794 return;
795 }
796
797 // Now that the build version changes, report the update metrics.
798 // TODO(xunchang) check the build version is larger than the previous one.
799 prefs_->SetString(kPrefsBootId, current_boot_id);
800 prefs_->SetString(kPrefsPreviousVersion, current_version);
801
802 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
803 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
804 if (previous_attempt_exists) {
805 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
806 }
807
808 metrics_utils::LoadAndReportTimeToReboot(
809 metrics_reporter_.get(), prefs_, clock_.get());
810 ClearMetricsPrefs();
811}
812
813// Save the update start time. Reset the reboot count and attempt number if the
814// update isn't a resume; otherwise increment the attempt number.
815void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
816 if (!is_resume) {
817 metrics_utils::SetNumReboots(0, prefs_);
818 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
819 } else {
820 int64_t attempt_number =
821 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
822 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
823 }
824 Time update_start_time = clock_->GetMonotonicTime();
825 metrics_utils::SetUpdateTimestampStart(update_start_time, prefs_);
826}
827
828void UpdateAttempterAndroid::ClearMetricsPrefs() {
829 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700830 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700831 prefs_->Delete(kPrefsNumReboots);
832 prefs_->Delete(kPrefsPayloadAttemptNumber);
833 prefs_->Delete(kPrefsSystemUpdatedMarker);
834 prefs_->Delete(kPrefsUpdateTimestampStart);
835}
836
Alex Deymo5e3ea272016-01-28 13:42:23 -0800837} // namespace chromeos_update_engine