blob: 76fa92e67741b712fb7402ce10728bf15b69a29c [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"
Alex Deymo3b678db2016-02-09 11:50:06 -080049#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080050
Alex Deymo14c0da82016-07-20 16:45:45 -070051#ifndef _UE_SIDELOAD
52// Do not include support for external HTTP(s) urls when building
53// update_engine_sideload.
54#include "update_engine/libcurl_http_fetcher.h"
55#endif
56
Alex Deymo5e3ea272016-01-28 13:42:23 -080057using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070058using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080059using base::TimeDelta;
60using base::TimeTicks;
61using std::shared_ptr;
62using std::string;
63using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070064using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080065
66namespace chromeos_update_engine {
67
68namespace {
69
Alex Deymo0d298542016-03-30 18:31:49 -070070// Minimum threshold to broadcast an status update in progress and time.
71const double kBroadcastThresholdProgress = 0.01; // 1%
72const int kBroadcastThresholdSeconds = 10;
73
Alex Deymo5e3ea272016-01-28 13:42:23 -080074const char* const kErrorDomain = "update_engine";
75// TODO(deymo): Convert the different errors to a numeric value to report them
76// back on the service error.
77const char* const kGenericError = "generic_error";
78
79// Log and set the error on the passed ErrorPtr.
80bool LogAndSetError(brillo::ErrorPtr* error,
81 const tracked_objects::Location& location,
82 const string& reason) {
83 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
84 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
85 << reason;
86 return false;
87}
88
Sen Jiang02c49422017-10-31 15:14:11 -070089bool GetHeaderAsBool(const string& header, bool default_value) {
90 int value = 0;
91 if (base::StringToInt(header, &value) && (value == 0 || value == 1))
92 return value == 1;
93 return default_value;
94}
95
Alex Deymo5e3ea272016-01-28 13:42:23 -080096} // namespace
97
98UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -070099 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -0800100 PrefsInterface* prefs,
101 BootControlInterface* boot_control,
102 HardwareInterface* hardware)
103 : daemon_state_(daemon_state),
104 prefs_(prefs),
105 boot_control_(boot_control),
106 hardware_(hardware),
Tianjie Xu1b661142017-09-28 14:03:42 -0700107 processor_(new ActionProcessor()),
Tianjie Xud4c5deb2017-10-24 11:17:03 -0700108 clock_(new Clock()) {
109 metrics_reporter_ = metrics::CreateMetricsReporter();
Alex Deymo87792ea2016-07-25 15:40:36 -0700110 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -0800111}
112
113UpdateAttempterAndroid::~UpdateAttempterAndroid() {
114 // Release ourselves as the ActionProcessor's delegate to prevent
115 // re-scheduling the updates due to the processing stopped.
116 processor_->set_delegate(nullptr);
117}
118
119void UpdateAttempterAndroid::Init() {
120 // In case of update_engine restart without a reboot we need to restore the
121 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700122 if (UpdateCompletedOnThisBoot()) {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800123 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700124 } else {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800125 SetStatusAndNotify(UpdateStatus::IDLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700126 UpdatePrefsAndReportUpdateMetricsOnReboot();
127 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800128}
129
130bool UpdateAttempterAndroid::ApplyPayload(
131 const string& payload_url,
132 int64_t payload_offset,
133 int64_t payload_size,
134 const vector<string>& key_value_pair_headers,
135 brillo::ErrorPtr* error) {
136 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
137 return LogAndSetError(
138 error, FROM_HERE, "An update already applied, waiting for reboot");
139 }
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700140 if (processor_->IsRunning()) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800141 return LogAndSetError(
142 error, FROM_HERE, "Already processing an update, cancel it first.");
143 }
144 DCHECK(status_ == UpdateStatus::IDLE);
145
Alex Deymo218397f2016-02-04 23:55:10 -0800146 std::map<string, string> headers;
147 for (const string& key_value_pair : key_value_pair_headers) {
148 string key;
149 string value;
150 if (!brillo::string_utils::SplitAtFirst(
151 key_value_pair, "=", &key, &value, false)) {
152 return LogAndSetError(
153 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
154 }
155 if (!headers.emplace(key, value).second)
156 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
157 }
158
159 // Unique identifier for the payload. An empty string means that the payload
160 // can't be resumed.
161 string payload_id = (headers[kPayloadPropertyFileHash] +
162 headers[kPayloadPropertyMetadataHash]);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800163
164 // Setup the InstallPlan based on the request.
165 install_plan_ = InstallPlan();
166
167 install_plan_.download_url = payload_url;
168 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800169 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800170 InstallPlan::Payload payload;
171 payload.size = payload_size;
172 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800173 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800174 &payload.size)) {
175 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800176 }
177 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700178 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800179 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700180 LOG(WARNING) << "Unable to decode base64 file hash: "
181 << headers[kPayloadPropertyFileHash];
182 }
Alex Deymo218397f2016-02-04 23:55:10 -0800183 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800184 &payload.metadata_size)) {
185 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800186 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700187 // The |payload.type| is not used anymore since minor_version 3.
188 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800189 install_plan_.payloads.push_back(payload);
190
Alex Deymo5e3ea272016-01-28 13:42:23 -0800191 // The |public_key_rsa| key would override the public key stored on disk.
192 install_plan_.public_key_rsa = "";
193
194 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
195 install_plan_.is_resume = !payload_id.empty() &&
196 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
197 if (!install_plan_.is_resume) {
198 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
199 LOG(WARNING) << "Unable to reset the update progress.";
200 }
201 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
202 LOG(WARNING) << "Unable to save the update check response hash.";
203 }
204 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800205 install_plan_.source_slot = boot_control_->GetCurrentSlot();
206 install_plan_.target_slot = install_plan_.source_slot == 0 ? 1 : 0;
Alex Deymofb905d92016-06-03 19:26:58 -0700207
Alex Deymofb905d92016-06-03 19:26:58 -0700208 install_plan_.powerwash_required =
Sen Jiang02c49422017-10-31 15:14:11 -0700209 GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
210
211 install_plan_.switch_slot_on_reboot =
212 GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
213
214 install_plan_.run_post_install = true;
215 // Optionally skip post install if and only if:
216 // a) we're resuming
217 // b) post install has already succeeded before
218 // c) RUN_POST_INSTALL is set to 0.
219 if (install_plan_.is_resume && prefs_->Exists(kPrefsPostInstallSucceeded)) {
220 bool post_install_succeeded = false;
221 prefs_->GetBoolean(kPrefsPostInstallSucceeded, &post_install_succeeded);
222 if (post_install_succeeded) {
223 install_plan_.run_post_install =
224 GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
225 }
226 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800227
Alex Deymo87792ea2016-07-25 15:40:36 -0700228 NetworkId network_id = kDefaultNetworkId;
229 if (!headers[kPayloadPropertyNetworkId].empty()) {
230 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
231 &network_id)) {
232 return LogAndSetError(
233 error,
234 FROM_HERE,
235 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
236 }
237 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700238 return LogAndSetError(
239 error,
240 FROM_HERE,
241 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700242 }
243 }
244
Alex Deymo5e3ea272016-01-28 13:42:23 -0800245 LOG(INFO) << "Using this install plan:";
246 install_plan_.Dump();
247
Alex Deymo2c131bb2016-05-26 16:43:13 -0700248 BuildUpdateActions(payload_url);
Alex Deymofdd6dec2016-03-03 22:35:43 -0800249 // Setup extra headers.
250 HttpFetcher* fetcher = download_action_->http_fetcher();
251 if (!headers[kPayloadPropertyAuthorization].empty())
252 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
253 if (!headers[kPayloadPropertyUserAgent].empty())
254 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
255
Alex Deymo5e3ea272016-01-28 13:42:23 -0800256 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
257
258 // Just in case we didn't update boot flags yet, make sure they're updated
259 // before any update processing starts. This will start the update process.
260 UpdateBootFlags();
Tianjie Xu90aaa102017-10-10 17:39:03 -0700261
262 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
263 // TODO(xunchang) report the metrics for unresumable updates
264
Alex Deymo5e3ea272016-01-28 13:42:23 -0800265 return true;
266}
267
268bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700269 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800270 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
271 processor_->SuspendProcessing();
272 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800273}
274
275bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700276 if (!processor_->IsRunning())
Alex Deymof2858572016-02-25 11:20:13 -0800277 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
278 processor_->ResumeProcessing();
279 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800280}
281
282bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Sen Jiang91f8d2a2018-07-12 14:27:04 -0700283 if (!processor_->IsRunning())
Alex Deymo5e3ea272016-01-28 13:42:23 -0800284 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800285 processor_->StopProcessing();
286 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800287}
288
Alex Deymo3b678db2016-02-09 11:50:06 -0800289bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
290 LOG(INFO) << "Attempting to reset state from "
291 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
292
293 switch (status_) {
294 case UpdateStatus::IDLE:
295 return true;
296
297 case UpdateStatus::UPDATED_NEED_REBOOT: {
298 // Remove the reboot marker so that if the machine is rebooted
299 // after resetting to idle state, it doesn't go back to
300 // UpdateStatus::UPDATED_NEED_REBOOT state.
301 bool ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700302 ClearMetricsPrefs();
Alex Deymo3b678db2016-02-09 11:50:06 -0800303
304 // Update the boot flags so the current slot has higher priority.
305 if (!boot_control_->SetActiveBootSlot(boot_control_->GetCurrentSlot()))
306 ret_value = false;
307
Alex Deymo52590332016-11-29 18:29:13 -0800308 // Mark the current slot as successful again, since marking it as active
309 // may reset the successful bit. We ignore the result of whether marking
310 // the current slot as successful worked.
311 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful){})))
312 ret_value = false;
313
Alex Deymo3b678db2016-02-09 11:50:06 -0800314 if (!ret_value) {
315 return LogAndSetError(
316 error,
317 FROM_HERE,
318 "Failed to reset the status to ");
319 }
320
321 SetStatusAndNotify(UpdateStatus::IDLE);
322 LOG(INFO) << "Reset status successful";
323 return true;
324 }
325
326 default:
327 return LogAndSetError(
328 error,
329 FROM_HERE,
330 "Reset not allowed in this state. Cancel the ongoing update first");
331 }
332}
333
Sen Jiang28d8ed92018-02-01 13:46:39 -0800334bool UpdateAttempterAndroid::VerifyPayloadApplicable(
335 const std::string& metadata_filename, brillo::ErrorPtr* error) {
336 FileDescriptorPtr fd(new EintrSafeFileDescriptor);
337 if (!fd->Open(metadata_filename.c_str(), O_RDONLY)) {
338 return LogAndSetError(
339 error, FROM_HERE, "Failed to open " + metadata_filename);
340 }
341 brillo::Blob metadata(kMaxPayloadHeaderSize);
342 if (!fd->Read(metadata.data(), metadata.size())) {
343 return LogAndSetError(
344 error,
345 FROM_HERE,
346 "Failed to read payload header from " + metadata_filename);
347 }
348 ErrorCode errorcode;
349 PayloadMetadata payload_metadata;
Sen Jiangdcaf7972018-05-11 16:03:23 -0700350 if (payload_metadata.ParsePayloadHeader(metadata, &errorcode) !=
Sen Jiang28d8ed92018-02-01 13:46:39 -0800351 MetadataParseResult::kSuccess) {
352 return LogAndSetError(error,
353 FROM_HERE,
354 "Failed to parse payload header: " +
355 utils::ErrorCodeToString(errorcode));
356 }
357 metadata.resize(payload_metadata.GetMetadataSize() +
358 payload_metadata.GetMetadataSignatureSize());
359 if (metadata.size() < kMaxPayloadHeaderSize) {
360 return LogAndSetError(
361 error,
362 FROM_HERE,
363 "Metadata size too small: " + std::to_string(metadata.size()));
364 }
365 if (!fd->Read(metadata.data() + kMaxPayloadHeaderSize,
366 metadata.size() - kMaxPayloadHeaderSize)) {
367 return LogAndSetError(
368 error,
369 FROM_HERE,
370 "Failed to read metadata and signature from " + metadata_filename);
371 }
372 fd->Close();
373 errorcode = payload_metadata.ValidateMetadataSignature(
374 metadata, "", base::FilePath(constants::kUpdatePayloadPublicKeyPath));
375 if (errorcode != ErrorCode::kSuccess) {
376 return LogAndSetError(error,
377 FROM_HERE,
378 "Failed to validate metadata signature: " +
379 utils::ErrorCodeToString(errorcode));
380 }
381 DeltaArchiveManifest manifest;
382 if (!payload_metadata.GetManifest(metadata, &manifest)) {
383 return LogAndSetError(error, FROM_HERE, "Failed to parse manifest.");
384 }
385
386 BootControlInterface::Slot current_slot = boot_control_->GetCurrentSlot();
387 for (const PartitionUpdate& partition : manifest.partitions()) {
388 if (!partition.has_old_partition_info())
389 continue;
390 string partition_path;
391 if (!boot_control_->GetPartitionDevice(
392 partition.partition_name(), current_slot, &partition_path)) {
393 return LogAndSetError(
394 error,
395 FROM_HERE,
396 "Failed to get partition device for " + partition.partition_name());
397 }
398 if (!fd->Open(partition_path.c_str(), O_RDONLY)) {
399 return LogAndSetError(
400 error, FROM_HERE, "Failed to open " + partition_path);
401 }
402 for (const InstallOperation& operation : partition.operations()) {
403 if (!operation.has_src_sha256_hash())
404 continue;
405 brillo::Blob source_hash;
406 if (!fd_utils::ReadAndHashExtents(fd,
407 operation.src_extents(),
408 manifest.block_size(),
409 &source_hash)) {
410 return LogAndSetError(
411 error, FROM_HERE, "Failed to hash " + partition_path);
412 }
413 if (!DeltaPerformer::ValidateSourceHash(
414 source_hash, operation, fd, &errorcode)) {
415 return false;
416 }
417 }
418 fd->Close();
419 }
420 return true;
421}
422
Alex Deymo5e3ea272016-01-28 13:42:23 -0800423void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
424 ErrorCode code) {
425 LOG(INFO) << "Processing Done.";
426
Alex Deymo5990bf32016-07-19 17:01:41 -0700427 switch (code) {
428 case ErrorCode::kSuccess:
429 // Update succeeded.
430 WriteUpdateCompletedMarker();
431 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800432
Alex Deymo5990bf32016-07-19 17:01:41 -0700433 LOG(INFO) << "Update successfully applied, waiting to reboot.";
434 break;
435
436 case ErrorCode::kFilesystemCopierError:
437 case ErrorCode::kNewRootfsVerificationError:
438 case ErrorCode::kNewKernelVerificationError:
439 case ErrorCode::kFilesystemVerifierError:
440 case ErrorCode::kDownloadStateInitializationError:
441 // Reset the ongoing update for these errors so it starts from the
442 // beginning next time.
443 DeltaPerformer::ResetUpdateProgress(prefs_, false);
444 LOG(INFO) << "Resetting update progress.";
445 break;
446
447 default:
448 // Ignore all other error codes.
449 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700450 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800451
452 TerminateUpdateAndNotify(code);
453}
454
455void UpdateAttempterAndroid::ProcessingStopped(
456 const ActionProcessor* processor) {
457 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
458}
459
460void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
461 AbstractAction* action,
462 ErrorCode code) {
463 // Reset download progress regardless of whether or not the download
464 // action succeeded.
465 const string type = action->Type();
466 if (type == DownloadAction::StaticType()) {
Alex Deymo0d298542016-03-30 18:31:49 -0700467 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800468 }
Sen Jiang02c49422017-10-31 15:14:11 -0700469 if (type == PostinstallRunnerAction::StaticType()) {
470 bool succeeded =
471 code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
472 prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
473 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800474 if (code != ErrorCode::kSuccess) {
475 // If an action failed, the ActionProcessor will cancel the whole thing.
476 return;
477 }
478 if (type == DownloadAction::StaticType()) {
479 SetStatusAndNotify(UpdateStatus::FINALIZING);
480 }
481}
482
483void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
484 uint64_t bytes_received,
485 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700486 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800487 if (total)
488 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700489 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800490 download_progress_ = progress;
491 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700492 } else {
493 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800494 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700495
496 // Update the bytes downloaded in prefs.
497 int64_t current_bytes_downloaded =
498 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
499 int64_t total_bytes_downloaded =
500 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
501 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
502 current_bytes_downloaded + bytes_progressed);
503 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
504 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800505}
506
507bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
508 // TODO(deymo): Notify the DownloadAction that it should cancel the update
509 // download.
510 return false;
511}
512
513void UpdateAttempterAndroid::DownloadComplete() {
514 // Nothing needs to be done when the download completes.
515}
516
Alex Deymo0d298542016-03-30 18:31:49 -0700517void UpdateAttempterAndroid::ProgressUpdate(double progress) {
518 // Self throttle based on progress. Also send notifications if progress is
519 // too slow.
520 if (progress == 1.0 ||
521 progress - download_progress_ >= kBroadcastThresholdProgress ||
522 TimeTicks::Now() - last_notify_time_ >=
523 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
524 download_progress_ = progress;
525 SetStatusAndNotify(status_);
526 }
527}
528
Alex Deymo5e3ea272016-01-28 13:42:23 -0800529void UpdateAttempterAndroid::UpdateBootFlags() {
530 if (updated_boot_flags_) {
531 LOG(INFO) << "Already updated boot flags. Skipping.";
532 CompleteUpdateBootFlags(true);
533 return;
534 }
535 // This is purely best effort.
536 LOG(INFO) << "Marking booted slot as good.";
537 if (!boot_control_->MarkBootSuccessfulAsync(
538 Bind(&UpdateAttempterAndroid::CompleteUpdateBootFlags,
539 base::Unretained(this)))) {
540 LOG(ERROR) << "Failed to mark current boot as successful.";
541 CompleteUpdateBootFlags(false);
542 }
543}
544
545void UpdateAttempterAndroid::CompleteUpdateBootFlags(bool successful) {
546 updated_boot_flags_ = true;
547 ScheduleProcessingStart();
548}
549
550void UpdateAttempterAndroid::ScheduleProcessingStart() {
551 LOG(INFO) << "Scheduling an action processor start.";
552 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700553 FROM_HERE,
554 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
555 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800556}
557
558void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
559 if (status_ == UpdateStatus::IDLE) {
560 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
561 return;
562 }
563
Alex Deymo0d298542016-03-30 18:31:49 -0700564 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800565 actions_.clear();
566 UpdateStatus new_status =
567 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
568 : UpdateStatus::IDLE);
569 SetStatusAndNotify(new_status);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800570
Sen Jiangb19c3ec2017-10-06 15:18:46 -0700571 // The network id is only applicable to one download attempt and once it's
572 // done the network id should not be re-used anymore.
573 if (!network_selector_->SetProcessNetwork(kDefaultNetworkId)) {
574 LOG(WARNING) << "Unable to unbind network.";
575 }
576
Alex Deymo5e3ea272016-01-28 13:42:23 -0800577 for (auto observer : daemon_state_->service_observers())
578 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700579
Tianjie Xu90aaa102017-10-10 17:39:03 -0700580 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
581 ClearMetricsPrefs();
582 if (error_code == ErrorCode::kSuccess) {
583 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700584 // Clear the total bytes downloaded if and only if the update succeeds.
585 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700586 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800587}
588
589void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
590 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700591 size_t payload_size =
592 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700593 UpdateEngineStatus status_to_send = {.status = status_,
594 .progress = download_progress_,
595 .new_size_bytes = payload_size};
596
Alex Deymo5e3ea272016-01-28 13:42:23 -0800597 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700598 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800599 }
600 last_notify_time_ = TimeTicks::Now();
601}
602
Alex Deymo2c131bb2016-05-26 16:43:13 -0700603void UpdateAttempterAndroid::BuildUpdateActions(const string& url) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800604 CHECK(!processor_->IsRunning());
605 processor_->set_delegate(this);
606
607 // Actions:
608 shared_ptr<InstallPlanAction> install_plan_action(
609 new InstallPlanAction(install_plan_));
610
Alex Deymo2c131bb2016-05-26 16:43:13 -0700611 HttpFetcher* download_fetcher = nullptr;
612 if (FileFetcher::SupportedUrl(url)) {
613 DLOG(INFO) << "Using FileFetcher for file URL.";
614 download_fetcher = new FileFetcher();
615 } else {
Alex Deymo14c0da82016-07-20 16:45:45 -0700616#ifdef _UE_SIDELOAD
617 LOG(FATAL) << "Unsupported sideload URI: " << url;
618#else
Alex Deymo2c131bb2016-05-26 16:43:13 -0700619 LibcurlHttpFetcher* libcurl_fetcher =
620 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
621 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
622 download_fetcher = libcurl_fetcher;
Alex Deymo14c0da82016-07-20 16:45:45 -0700623#endif // _UE_SIDELOAD
Alex Deymo2c131bb2016-05-26 16:43:13 -0700624 }
Sen Jiang5ae865b2017-04-18 14:24:40 -0700625 shared_ptr<DownloadAction> download_action(
626 new DownloadAction(prefs_,
627 boot_control_,
628 hardware_,
Sen Jiang18414082018-01-11 14:50:36 -0800629 nullptr, // system_state, not used.
630 download_fetcher, // passes ownership
Amin Hassanied37d682018-04-06 13:22:00 -0700631 true /* interactive */));
Sen Jiangfef85fd2016-03-25 15:32:49 -0700632 shared_ptr<FilesystemVerifierAction> filesystem_verifier_action(
Sen Jiange6e4bb92016-04-05 14:59:12 -0700633 new FilesystemVerifierAction());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800634
635 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
Alex Deymofb905d92016-06-03 19:26:58 -0700636 new PostinstallRunnerAction(boot_control_, hardware_));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800637
638 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700639 download_action->set_base_offset(base_offset_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800640 download_action_ = download_action;
Alex Deymob6eef732016-06-10 12:58:11 -0700641 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800642
643 actions_.push_back(shared_ptr<AbstractAction>(install_plan_action));
644 actions_.push_back(shared_ptr<AbstractAction>(download_action));
Sen Jiangfef85fd2016-03-25 15:32:49 -0700645 actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800646 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
647
648 // Bond them together. We have to use the leaf-types when calling
649 // BondActions().
650 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700651 BondActions(download_action.get(), filesystem_verifier_action.get());
652 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800653 postinstall_runner_action.get());
654
655 // Enqueue the actions.
656 for (const shared_ptr<AbstractAction>& action : actions_)
657 processor_->EnqueueAction(action.get());
658}
659
Alex Deymo5e3ea272016-01-28 13:42:23 -0800660bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
661 string boot_id;
662 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
663 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
664 return true;
665}
666
667bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
668 // In case of an update_engine restart without a reboot, we stored the boot_id
669 // when the update was completed by setting a pref, so we can check whether
670 // the last update was on this boot or a previous one.
671 string boot_id;
672 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
673
674 string update_completed_on_boot_id;
675 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
676 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
677 &update_completed_on_boot_id) &&
678 update_completed_on_boot_id == boot_id);
679}
680
Tianjie Xu90aaa102017-10-10 17:39:03 -0700681// Collect and report the android metrics when we terminate the update.
682void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
683 ErrorCode error_code) {
684 int64_t attempt_number =
685 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
686 PayloadType payload_type = kPayloadTypeFull;
687 int64_t payload_size = 0;
688 for (const auto& p : install_plan_.payloads) {
689 if (p.type == InstallPayloadType::kDelta)
690 payload_type = kPayloadTypeDelta;
691 payload_size += p.size;
692 }
693
694 metrics::AttemptResult attempt_result =
695 metrics_utils::GetAttemptResult(error_code);
696 Time attempt_start_time = Time::FromInternalValue(
697 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu52c678c2017-10-18 15:52:27 -0700698 TimeDelta duration = clock_->GetBootTime() - attempt_start_time;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700699 TimeDelta duration_uptime = clock_->GetMonotonicTime() - attempt_start_time;
700
701 metrics_reporter_->ReportUpdateAttemptMetrics(
702 nullptr, // system_state
703 static_cast<int>(attempt_number),
704 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700705 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700706 duration_uptime,
707 payload_size,
708 attempt_result,
709 error_code);
710
Tianjie Xud4777a12017-10-24 14:54:18 -0700711 int64_t current_bytes_downloaded =
712 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
713 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
714 current_bytes_downloaded,
715 0,
716 DownloadSource::kNumDownloadSources,
717 metrics::DownloadErrorCode::kUnset,
718 metrics::ConnectionType::kUnset);
719
Tianjie Xu90aaa102017-10-10 17:39:03 -0700720 if (error_code == ErrorCode::kSuccess) {
721 int64_t reboot_count =
722 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
723 string build_version;
724 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700725
726 // For android metrics, we only care about the total bytes downloaded
727 // for all sources; for now we assume the only download source is
728 // HttpsServer.
729 int64_t total_bytes_downloaded =
730 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
731 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
732 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
733 total_bytes_downloaded;
734
735 int download_overhead_percentage = 0;
736 if (current_bytes_downloaded > 0) {
737 download_overhead_percentage =
738 (total_bytes_downloaded - current_bytes_downloaded) * 100ull /
739 current_bytes_downloaded;
740 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700741 metrics_reporter_->ReportSuccessfulUpdateMetrics(
742 static_cast<int>(attempt_number),
743 0, // update abandoned count
744 payload_type,
745 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700746 num_bytes_downloaded,
747 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700748 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700749 duration_uptime,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700750 static_cast<int>(reboot_count),
751 0); // url_switch_count
752 }
753}
754
755void UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
756 string current_boot_id;
757 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
758 // Example: [ro.build.version.incremental]: [4292972]
759 string current_version =
760 android::base::GetProperty("ro.build.version.incremental", "");
761 TEST_AND_RETURN(!current_version.empty());
762
763 // If there's no record of previous version (e.g. due to a data wipe), we
764 // save the info of current boot and skip the metrics report.
765 if (!prefs_->Exists(kPrefsPreviousVersion)) {
766 prefs_->SetString(kPrefsBootId, current_boot_id);
767 prefs_->SetString(kPrefsPreviousVersion, current_version);
768 ClearMetricsPrefs();
769 return;
770 }
771 string previous_version;
772 // update_engine restarted under the same build.
773 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
774 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
775 previous_version == current_version) {
776 string last_boot_id;
777 bool is_reboot = prefs_->Exists(kPrefsBootId) &&
778 (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
779 last_boot_id != current_boot_id);
780 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
781 // set when we start a new update.
782 if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
783 prefs_->SetString(kPrefsBootId, current_boot_id);
784 int64_t reboot_count =
785 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
786 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
787 }
788 return;
789 }
790
791 // Now that the build version changes, report the update metrics.
792 // TODO(xunchang) check the build version is larger than the previous one.
793 prefs_->SetString(kPrefsBootId, current_boot_id);
794 prefs_->SetString(kPrefsPreviousVersion, current_version);
795
796 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
797 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
798 if (previous_attempt_exists) {
799 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
800 }
801
802 metrics_utils::LoadAndReportTimeToReboot(
803 metrics_reporter_.get(), prefs_, clock_.get());
804 ClearMetricsPrefs();
805}
806
807// Save the update start time. Reset the reboot count and attempt number if the
808// update isn't a resume; otherwise increment the attempt number.
809void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
810 if (!is_resume) {
811 metrics_utils::SetNumReboots(0, prefs_);
812 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
813 } else {
814 int64_t attempt_number =
815 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
816 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
817 }
818 Time update_start_time = clock_->GetMonotonicTime();
819 metrics_utils::SetUpdateTimestampStart(update_start_time, prefs_);
820}
821
822void UpdateAttempterAndroid::ClearMetricsPrefs() {
823 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700824 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700825 prefs_->Delete(kPrefsNumReboots);
826 prefs_->Delete(kPrefsPayloadAttemptNumber);
827 prefs_->Delete(kPrefsSystemUpdatedMarker);
828 prefs_->Delete(kPrefsUpdateTimestampStart);
829}
830
Alex Deymo5e3ea272016-01-28 13:42:23 -0800831} // namespace chromeos_update_engine