blob: 08a5e581b97a229c4ee2cc7671395b621c05099d [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"
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"
Alex Deymo5e3ea272016-01-28 13:42:23 -080041#include "update_engine/payload_consumer/download_action.h"
42#include "update_engine/payload_consumer/filesystem_verifier_action.h"
43#include "update_engine/payload_consumer/postinstall_runner_action.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080044#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080045
Alex Deymo14c0da82016-07-20 16:45:45 -070046#ifndef _UE_SIDELOAD
47// Do not include support for external HTTP(s) urls when building
48// update_engine_sideload.
49#include "update_engine/libcurl_http_fetcher.h"
50#endif
51
Alex Deymo5e3ea272016-01-28 13:42:23 -080052using base::Bind;
Tianjie Xu90aaa102017-10-10 17:39:03 -070053using base::Time;
Alex Deymo5e3ea272016-01-28 13:42:23 -080054using base::TimeDelta;
55using base::TimeTicks;
56using std::shared_ptr;
57using std::string;
58using std::vector;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070059using update_engine::UpdateEngineStatus;
Alex Deymo5e3ea272016-01-28 13:42:23 -080060
61namespace chromeos_update_engine {
62
63namespace {
64
Alex Deymo0d298542016-03-30 18:31:49 -070065// Minimum threshold to broadcast an status update in progress and time.
66const double kBroadcastThresholdProgress = 0.01; // 1%
67const int kBroadcastThresholdSeconds = 10;
68
Alex Deymo5e3ea272016-01-28 13:42:23 -080069const char* const kErrorDomain = "update_engine";
70// TODO(deymo): Convert the different errors to a numeric value to report them
71// back on the service error.
72const char* const kGenericError = "generic_error";
73
74// Log and set the error on the passed ErrorPtr.
75bool LogAndSetError(brillo::ErrorPtr* error,
76 const tracked_objects::Location& location,
77 const string& reason) {
78 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
79 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
80 << reason;
81 return false;
82}
83
84} // namespace
85
86UpdateAttempterAndroid::UpdateAttempterAndroid(
Alex Deymo03a4de72016-07-20 16:08:23 -070087 DaemonStateInterface* daemon_state,
Alex Deymo5e3ea272016-01-28 13:42:23 -080088 PrefsInterface* prefs,
89 BootControlInterface* boot_control,
90 HardwareInterface* hardware)
91 : daemon_state_(daemon_state),
92 prefs_(prefs),
93 boot_control_(boot_control),
94 hardware_(hardware),
Tianjie Xu1b661142017-09-28 14:03:42 -070095 processor_(new ActionProcessor()),
Tianjie Xud4c5deb2017-10-24 11:17:03 -070096 clock_(new Clock()) {
97 metrics_reporter_ = metrics::CreateMetricsReporter();
Alex Deymo87792ea2016-07-25 15:40:36 -070098 network_selector_ = network::CreateNetworkSelector();
Alex Deymo5e3ea272016-01-28 13:42:23 -080099}
100
101UpdateAttempterAndroid::~UpdateAttempterAndroid() {
102 // Release ourselves as the ActionProcessor's delegate to prevent
103 // re-scheduling the updates due to the processing stopped.
104 processor_->set_delegate(nullptr);
105}
106
107void UpdateAttempterAndroid::Init() {
108 // In case of update_engine restart without a reboot we need to restore the
109 // reboot needed state.
Tianjie Xu90aaa102017-10-10 17:39:03 -0700110 if (UpdateCompletedOnThisBoot()) {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800111 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700112 } else {
Alex Deymo0e061ae2016-02-09 17:49:03 -0800113 SetStatusAndNotify(UpdateStatus::IDLE);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700114 UpdatePrefsAndReportUpdateMetricsOnReboot();
115 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800116}
117
118bool UpdateAttempterAndroid::ApplyPayload(
119 const string& payload_url,
120 int64_t payload_offset,
121 int64_t payload_size,
122 const vector<string>& key_value_pair_headers,
123 brillo::ErrorPtr* error) {
124 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
125 return LogAndSetError(
126 error, FROM_HERE, "An update already applied, waiting for reboot");
127 }
128 if (ongoing_update_) {
129 return LogAndSetError(
130 error, FROM_HERE, "Already processing an update, cancel it first.");
131 }
132 DCHECK(status_ == UpdateStatus::IDLE);
133
Alex Deymo218397f2016-02-04 23:55:10 -0800134 std::map<string, string> headers;
135 for (const string& key_value_pair : key_value_pair_headers) {
136 string key;
137 string value;
138 if (!brillo::string_utils::SplitAtFirst(
139 key_value_pair, "=", &key, &value, false)) {
140 return LogAndSetError(
141 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
142 }
143 if (!headers.emplace(key, value).second)
144 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
145 }
146
147 // Unique identifier for the payload. An empty string means that the payload
148 // can't be resumed.
149 string payload_id = (headers[kPayloadPropertyFileHash] +
150 headers[kPayloadPropertyMetadataHash]);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800151
152 // Setup the InstallPlan based on the request.
153 install_plan_ = InstallPlan();
154
155 install_plan_.download_url = payload_url;
156 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800157 base_offset_ = payload_offset;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800158 InstallPlan::Payload payload;
159 payload.size = payload_size;
160 if (!payload.size) {
Alex Deymo218397f2016-02-04 23:55:10 -0800161 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800162 &payload.size)) {
163 payload.size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800164 }
165 }
Sen Jiang2703ef42017-03-16 13:36:21 -0700166 if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800167 &payload.hash)) {
Sen Jiang2703ef42017-03-16 13:36:21 -0700168 LOG(WARNING) << "Unable to decode base64 file hash: "
169 << headers[kPayloadPropertyFileHash];
170 }
Alex Deymo218397f2016-02-04 23:55:10 -0800171 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
Sen Jiang0affc2c2017-02-10 15:55:05 -0800172 &payload.metadata_size)) {
173 payload.metadata_size = 0;
Alex Deymo218397f2016-02-04 23:55:10 -0800174 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700175 // The |payload.type| is not used anymore since minor_version 3.
176 payload.type = InstallPayloadType::kUnknown;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800177 install_plan_.payloads.push_back(payload);
178
Alex Deymo5e3ea272016-01-28 13:42:23 -0800179 // The |public_key_rsa| key would override the public key stored on disk.
180 install_plan_.public_key_rsa = "";
181
182 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
183 install_plan_.is_resume = !payload_id.empty() &&
184 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
185 if (!install_plan_.is_resume) {
186 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
187 LOG(WARNING) << "Unable to reset the update progress.";
188 }
189 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
190 LOG(WARNING) << "Unable to save the update check response hash.";
191 }
192 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800193 install_plan_.source_slot = boot_control_->GetCurrentSlot();
194 install_plan_.target_slot = install_plan_.source_slot == 0 ? 1 : 0;
Alex Deymofb905d92016-06-03 19:26:58 -0700195
196 int data_wipe = 0;
197 install_plan_.powerwash_required =
198 base::StringToInt(headers[kPayloadPropertyPowerwash], &data_wipe) &&
199 data_wipe != 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800200
Alex Deymo87792ea2016-07-25 15:40:36 -0700201 NetworkId network_id = kDefaultNetworkId;
202 if (!headers[kPayloadPropertyNetworkId].empty()) {
203 if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
204 &network_id)) {
205 return LogAndSetError(
206 error,
207 FROM_HERE,
208 "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
209 }
210 if (!network_selector_->SetProcessNetwork(network_id)) {
Sen Jiangcbd37c62017-09-12 15:04:35 -0700211 return LogAndSetError(
212 error,
213 FROM_HERE,
214 "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
Alex Deymo87792ea2016-07-25 15:40:36 -0700215 }
216 }
217
Alex Deymo5e3ea272016-01-28 13:42:23 -0800218 LOG(INFO) << "Using this install plan:";
219 install_plan_.Dump();
220
Alex Deymo2c131bb2016-05-26 16:43:13 -0700221 BuildUpdateActions(payload_url);
Alex Deymofdd6dec2016-03-03 22:35:43 -0800222 // Setup extra headers.
223 HttpFetcher* fetcher = download_action_->http_fetcher();
224 if (!headers[kPayloadPropertyAuthorization].empty())
225 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
226 if (!headers[kPayloadPropertyUserAgent].empty())
227 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
228
Alex Deymo5e3ea272016-01-28 13:42:23 -0800229 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
Alex Deymof2858572016-02-25 11:20:13 -0800230 ongoing_update_ = true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800231
232 // Just in case we didn't update boot flags yet, make sure they're updated
233 // before any update processing starts. This will start the update process.
234 UpdateBootFlags();
Tianjie Xu90aaa102017-10-10 17:39:03 -0700235
236 UpdatePrefsOnUpdateStart(install_plan_.is_resume);
237 // TODO(xunchang) report the metrics for unresumable updates
238
Alex Deymo5e3ea272016-01-28 13:42:23 -0800239 return true;
240}
241
242bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Alex Deymof2858572016-02-25 11:20:13 -0800243 if (!ongoing_update_)
244 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
245 processor_->SuspendProcessing();
246 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800247}
248
249bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Alex Deymof2858572016-02-25 11:20:13 -0800250 if (!ongoing_update_)
251 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
252 processor_->ResumeProcessing();
253 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800254}
255
256bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Alex Deymof2858572016-02-25 11:20:13 -0800257 if (!ongoing_update_)
Alex Deymo5e3ea272016-01-28 13:42:23 -0800258 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800259 processor_->StopProcessing();
260 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800261}
262
Alex Deymo3b678db2016-02-09 11:50:06 -0800263bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
264 LOG(INFO) << "Attempting to reset state from "
265 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
266
267 switch (status_) {
268 case UpdateStatus::IDLE:
269 return true;
270
271 case UpdateStatus::UPDATED_NEED_REBOOT: {
272 // Remove the reboot marker so that if the machine is rebooted
273 // after resetting to idle state, it doesn't go back to
274 // UpdateStatus::UPDATED_NEED_REBOOT state.
275 bool ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700276 ClearMetricsPrefs();
Alex Deymo3b678db2016-02-09 11:50:06 -0800277
278 // Update the boot flags so the current slot has higher priority.
279 if (!boot_control_->SetActiveBootSlot(boot_control_->GetCurrentSlot()))
280 ret_value = false;
281
Alex Deymo52590332016-11-29 18:29:13 -0800282 // Mark the current slot as successful again, since marking it as active
283 // may reset the successful bit. We ignore the result of whether marking
284 // the current slot as successful worked.
285 if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful){})))
286 ret_value = false;
287
Alex Deymo3b678db2016-02-09 11:50:06 -0800288 if (!ret_value) {
289 return LogAndSetError(
290 error,
291 FROM_HERE,
292 "Failed to reset the status to ");
293 }
294
295 SetStatusAndNotify(UpdateStatus::IDLE);
296 LOG(INFO) << "Reset status successful";
297 return true;
298 }
299
300 default:
301 return LogAndSetError(
302 error,
303 FROM_HERE,
304 "Reset not allowed in this state. Cancel the ongoing update first");
305 }
306}
307
Alex Deymo5e3ea272016-01-28 13:42:23 -0800308void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
309 ErrorCode code) {
310 LOG(INFO) << "Processing Done.";
311
Alex Deymo5990bf32016-07-19 17:01:41 -0700312 switch (code) {
313 case ErrorCode::kSuccess:
314 // Update succeeded.
315 WriteUpdateCompletedMarker();
316 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
317 DeltaPerformer::ResetUpdateProgress(prefs_, false);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800318
Alex Deymo5990bf32016-07-19 17:01:41 -0700319 LOG(INFO) << "Update successfully applied, waiting to reboot.";
320 break;
321
322 case ErrorCode::kFilesystemCopierError:
323 case ErrorCode::kNewRootfsVerificationError:
324 case ErrorCode::kNewKernelVerificationError:
325 case ErrorCode::kFilesystemVerifierError:
326 case ErrorCode::kDownloadStateInitializationError:
327 // Reset the ongoing update for these errors so it starts from the
328 // beginning next time.
329 DeltaPerformer::ResetUpdateProgress(prefs_, false);
330 LOG(INFO) << "Resetting update progress.";
331 break;
332
Sen Jiangacbdd1c2017-10-19 13:30:19 -0700333 case ErrorCode::kPayloadTimestampError:
334 // SafetyNet logging, b/36232423
335 android_errorWriteLog(0x534e4554, "36232423");
336 break;
337
Alex Deymo5990bf32016-07-19 17:01:41 -0700338 default:
339 // Ignore all other error codes.
340 break;
Alex Deymo03a4de72016-07-20 16:08:23 -0700341 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800342
343 TerminateUpdateAndNotify(code);
344}
345
346void UpdateAttempterAndroid::ProcessingStopped(
347 const ActionProcessor* processor) {
348 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
349}
350
351void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
352 AbstractAction* action,
353 ErrorCode code) {
354 // Reset download progress regardless of whether or not the download
355 // action succeeded.
356 const string type = action->Type();
357 if (type == DownloadAction::StaticType()) {
Alex Deymo0d298542016-03-30 18:31:49 -0700358 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800359 }
360 if (code != ErrorCode::kSuccess) {
361 // If an action failed, the ActionProcessor will cancel the whole thing.
362 return;
363 }
364 if (type == DownloadAction::StaticType()) {
365 SetStatusAndNotify(UpdateStatus::FINALIZING);
366 }
367}
368
369void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
370 uint64_t bytes_received,
371 uint64_t total) {
Alex Deymo0d298542016-03-30 18:31:49 -0700372 double progress = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800373 if (total)
374 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
Alex Deymo0d298542016-03-30 18:31:49 -0700375 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800376 download_progress_ = progress;
377 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
Alex Deymo0d298542016-03-30 18:31:49 -0700378 } else {
379 ProgressUpdate(progress);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800380 }
Tianjie Xud4777a12017-10-24 14:54:18 -0700381
382 // Update the bytes downloaded in prefs.
383 int64_t current_bytes_downloaded =
384 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
385 int64_t total_bytes_downloaded =
386 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
387 prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
388 current_bytes_downloaded + bytes_progressed);
389 prefs_->SetInt64(kPrefsTotalBytesDownloaded,
390 total_bytes_downloaded + bytes_progressed);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800391}
392
393bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
394 // TODO(deymo): Notify the DownloadAction that it should cancel the update
395 // download.
396 return false;
397}
398
399void UpdateAttempterAndroid::DownloadComplete() {
400 // Nothing needs to be done when the download completes.
401}
402
Alex Deymo0d298542016-03-30 18:31:49 -0700403void UpdateAttempterAndroid::ProgressUpdate(double progress) {
404 // Self throttle based on progress. Also send notifications if progress is
405 // too slow.
406 if (progress == 1.0 ||
407 progress - download_progress_ >= kBroadcastThresholdProgress ||
408 TimeTicks::Now() - last_notify_time_ >=
409 TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
410 download_progress_ = progress;
411 SetStatusAndNotify(status_);
412 }
413}
414
Alex Deymo5e3ea272016-01-28 13:42:23 -0800415void UpdateAttempterAndroid::UpdateBootFlags() {
416 if (updated_boot_flags_) {
417 LOG(INFO) << "Already updated boot flags. Skipping.";
418 CompleteUpdateBootFlags(true);
419 return;
420 }
421 // This is purely best effort.
422 LOG(INFO) << "Marking booted slot as good.";
423 if (!boot_control_->MarkBootSuccessfulAsync(
424 Bind(&UpdateAttempterAndroid::CompleteUpdateBootFlags,
425 base::Unretained(this)))) {
426 LOG(ERROR) << "Failed to mark current boot as successful.";
427 CompleteUpdateBootFlags(false);
428 }
429}
430
431void UpdateAttempterAndroid::CompleteUpdateBootFlags(bool successful) {
432 updated_boot_flags_ = true;
433 ScheduleProcessingStart();
434}
435
436void UpdateAttempterAndroid::ScheduleProcessingStart() {
437 LOG(INFO) << "Scheduling an action processor start.";
438 brillo::MessageLoop::current()->PostTask(
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700439 FROM_HERE,
440 Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
441 base::Unretained(processor_.get())));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800442}
443
444void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
445 if (status_ == UpdateStatus::IDLE) {
446 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
447 return;
448 }
449
Alex Deymo0d298542016-03-30 18:31:49 -0700450 download_progress_ = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800451 actions_.clear();
452 UpdateStatus new_status =
453 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
454 : UpdateStatus::IDLE);
455 SetStatusAndNotify(new_status);
456 ongoing_update_ = false;
457
458 for (auto observer : daemon_state_->service_observers())
459 observer->SendPayloadApplicationComplete(error_code);
Tianjie Xu1b661142017-09-28 14:03:42 -0700460
Tianjie Xu90aaa102017-10-10 17:39:03 -0700461 CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
462 ClearMetricsPrefs();
463 if (error_code == ErrorCode::kSuccess) {
464 metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700465 // Clear the total bytes downloaded if and only if the update succeeds.
466 prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700467 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800468}
469
470void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
471 status_ = status;
Sen Jiang2d1c87b2017-07-14 10:46:14 -0700472 size_t payload_size =
473 install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700474 UpdateEngineStatus status_to_send = {.status = status_,
475 .progress = download_progress_,
476 .new_size_bytes = payload_size};
477
Alex Deymo5e3ea272016-01-28 13:42:23 -0800478 for (auto observer : daemon_state_->service_observers()) {
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700479 observer->SendStatusUpdate(status_to_send);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800480 }
481 last_notify_time_ = TimeTicks::Now();
482}
483
Alex Deymo2c131bb2016-05-26 16:43:13 -0700484void UpdateAttempterAndroid::BuildUpdateActions(const string& url) {
Alex Deymo5e3ea272016-01-28 13:42:23 -0800485 CHECK(!processor_->IsRunning());
486 processor_->set_delegate(this);
487
488 // Actions:
489 shared_ptr<InstallPlanAction> install_plan_action(
490 new InstallPlanAction(install_plan_));
491
Alex Deymo2c131bb2016-05-26 16:43:13 -0700492 HttpFetcher* download_fetcher = nullptr;
493 if (FileFetcher::SupportedUrl(url)) {
494 DLOG(INFO) << "Using FileFetcher for file URL.";
495 download_fetcher = new FileFetcher();
496 } else {
Alex Deymo14c0da82016-07-20 16:45:45 -0700497#ifdef _UE_SIDELOAD
498 LOG(FATAL) << "Unsupported sideload URI: " << url;
499#else
Alex Deymo2c131bb2016-05-26 16:43:13 -0700500 LibcurlHttpFetcher* libcurl_fetcher =
501 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
502 libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
503 download_fetcher = libcurl_fetcher;
Alex Deymo14c0da82016-07-20 16:45:45 -0700504#endif // _UE_SIDELOAD
Alex Deymo2c131bb2016-05-26 16:43:13 -0700505 }
Sen Jiang5ae865b2017-04-18 14:24:40 -0700506 shared_ptr<DownloadAction> download_action(
507 new DownloadAction(prefs_,
508 boot_control_,
509 hardware_,
510 nullptr, // system_state, not used.
511 download_fetcher)); // passes ownership
Sen Jiangfef85fd2016-03-25 15:32:49 -0700512 shared_ptr<FilesystemVerifierAction> filesystem_verifier_action(
Sen Jiange6e4bb92016-04-05 14:59:12 -0700513 new FilesystemVerifierAction());
Alex Deymo5e3ea272016-01-28 13:42:23 -0800514
515 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
Alex Deymofb905d92016-06-03 19:26:58 -0700516 new PostinstallRunnerAction(boot_control_, hardware_));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800517
518 download_action->set_delegate(this);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700519 download_action->set_base_offset(base_offset_);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800520 download_action_ = download_action;
Alex Deymob6eef732016-06-10 12:58:11 -0700521 postinstall_runner_action->set_delegate(this);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800522
523 actions_.push_back(shared_ptr<AbstractAction>(install_plan_action));
524 actions_.push_back(shared_ptr<AbstractAction>(download_action));
Sen Jiangfef85fd2016-03-25 15:32:49 -0700525 actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action));
Alex Deymo5e3ea272016-01-28 13:42:23 -0800526 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
527
528 // Bond them together. We have to use the leaf-types when calling
529 // BondActions().
530 BondActions(install_plan_action.get(), download_action.get());
Sen Jiangfef85fd2016-03-25 15:32:49 -0700531 BondActions(download_action.get(), filesystem_verifier_action.get());
532 BondActions(filesystem_verifier_action.get(),
Alex Deymo5e3ea272016-01-28 13:42:23 -0800533 postinstall_runner_action.get());
534
535 // Enqueue the actions.
536 for (const shared_ptr<AbstractAction>& action : actions_)
537 processor_->EnqueueAction(action.get());
538}
539
Alex Deymo5e3ea272016-01-28 13:42:23 -0800540bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
541 string boot_id;
542 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
543 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
544 return true;
545}
546
547bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
548 // In case of an update_engine restart without a reboot, we stored the boot_id
549 // when the update was completed by setting a pref, so we can check whether
550 // the last update was on this boot or a previous one.
551 string boot_id;
552 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
553
554 string update_completed_on_boot_id;
555 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
556 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
557 &update_completed_on_boot_id) &&
558 update_completed_on_boot_id == boot_id);
559}
560
Tianjie Xu90aaa102017-10-10 17:39:03 -0700561// Collect and report the android metrics when we terminate the update.
562void UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
563 ErrorCode error_code) {
564 int64_t attempt_number =
565 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
566 PayloadType payload_type = kPayloadTypeFull;
567 int64_t payload_size = 0;
568 for (const auto& p : install_plan_.payloads) {
569 if (p.type == InstallPayloadType::kDelta)
570 payload_type = kPayloadTypeDelta;
571 payload_size += p.size;
572 }
573
574 metrics::AttemptResult attempt_result =
575 metrics_utils::GetAttemptResult(error_code);
576 Time attempt_start_time = Time::FromInternalValue(
577 metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
Tianjie Xu52c678c2017-10-18 15:52:27 -0700578 TimeDelta duration = clock_->GetBootTime() - attempt_start_time;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700579 TimeDelta duration_uptime = clock_->GetMonotonicTime() - attempt_start_time;
580
581 metrics_reporter_->ReportUpdateAttemptMetrics(
582 nullptr, // system_state
583 static_cast<int>(attempt_number),
584 payload_type,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700585 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700586 duration_uptime,
587 payload_size,
588 attempt_result,
589 error_code);
590
Tianjie Xud4777a12017-10-24 14:54:18 -0700591 int64_t current_bytes_downloaded =
592 metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
593 metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
594 current_bytes_downloaded,
595 0,
596 DownloadSource::kNumDownloadSources,
597 metrics::DownloadErrorCode::kUnset,
598 metrics::ConnectionType::kUnset);
599
Tianjie Xu90aaa102017-10-10 17:39:03 -0700600 if (error_code == ErrorCode::kSuccess) {
601 int64_t reboot_count =
602 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
603 string build_version;
604 prefs_->GetString(kPrefsPreviousVersion, &build_version);
Tianjie Xud4777a12017-10-24 14:54:18 -0700605
606 // For android metrics, we only care about the total bytes downloaded
607 // for all sources; for now we assume the only download source is
608 // HttpsServer.
609 int64_t total_bytes_downloaded =
610 metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
611 int64_t num_bytes_downloaded[kNumDownloadSources] = {};
612 num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
613 total_bytes_downloaded;
614
615 int download_overhead_percentage = 0;
616 if (current_bytes_downloaded > 0) {
617 download_overhead_percentage =
618 (total_bytes_downloaded - current_bytes_downloaded) * 100ull /
619 current_bytes_downloaded;
620 }
Tianjie Xu90aaa102017-10-10 17:39:03 -0700621 metrics_reporter_->ReportSuccessfulUpdateMetrics(
622 static_cast<int>(attempt_number),
623 0, // update abandoned count
624 payload_type,
625 payload_size,
Tianjie Xud4777a12017-10-24 14:54:18 -0700626 num_bytes_downloaded,
627 download_overhead_percentage,
Tianjie Xu52c678c2017-10-18 15:52:27 -0700628 duration,
Tianjie Xu90aaa102017-10-10 17:39:03 -0700629 static_cast<int>(reboot_count),
630 0); // url_switch_count
631 }
632}
633
634void UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
635 string current_boot_id;
636 TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
637 // Example: [ro.build.version.incremental]: [4292972]
638 string current_version =
639 android::base::GetProperty("ro.build.version.incremental", "");
640 TEST_AND_RETURN(!current_version.empty());
641
642 // If there's no record of previous version (e.g. due to a data wipe), we
643 // save the info of current boot and skip the metrics report.
644 if (!prefs_->Exists(kPrefsPreviousVersion)) {
645 prefs_->SetString(kPrefsBootId, current_boot_id);
646 prefs_->SetString(kPrefsPreviousVersion, current_version);
647 ClearMetricsPrefs();
648 return;
649 }
650 string previous_version;
651 // update_engine restarted under the same build.
652 // TODO(xunchang) identify and report rollback by checking UpdateMarker.
653 if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
654 previous_version == current_version) {
655 string last_boot_id;
656 bool is_reboot = prefs_->Exists(kPrefsBootId) &&
657 (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
658 last_boot_id != current_boot_id);
659 // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
660 // set when we start a new update.
661 if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
662 prefs_->SetString(kPrefsBootId, current_boot_id);
663 int64_t reboot_count =
664 metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
665 metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
666 }
667 return;
668 }
669
670 // Now that the build version changes, report the update metrics.
671 // TODO(xunchang) check the build version is larger than the previous one.
672 prefs_->SetString(kPrefsBootId, current_boot_id);
673 prefs_->SetString(kPrefsPreviousVersion, current_version);
674
675 bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
676 // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
677 if (previous_attempt_exists) {
678 metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
679 }
680
681 metrics_utils::LoadAndReportTimeToReboot(
682 metrics_reporter_.get(), prefs_, clock_.get());
683 ClearMetricsPrefs();
684}
685
686// Save the update start time. Reset the reboot count and attempt number if the
687// update isn't a resume; otherwise increment the attempt number.
688void UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
689 if (!is_resume) {
690 metrics_utils::SetNumReboots(0, prefs_);
691 metrics_utils::SetPayloadAttemptNumber(1, prefs_);
692 } else {
693 int64_t attempt_number =
694 metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
695 metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
696 }
697 Time update_start_time = clock_->GetMonotonicTime();
698 metrics_utils::SetUpdateTimestampStart(update_start_time, prefs_);
699}
700
701void UpdateAttempterAndroid::ClearMetricsPrefs() {
702 CHECK(prefs_);
Tianjie Xud4777a12017-10-24 14:54:18 -0700703 prefs_->Delete(kPrefsCurrentBytesDownloaded);
Tianjie Xu90aaa102017-10-10 17:39:03 -0700704 prefs_->Delete(kPrefsNumReboots);
705 prefs_->Delete(kPrefsPayloadAttemptNumber);
706 prefs_->Delete(kPrefsSystemUpdatedMarker);
707 prefs_->Delete(kPrefsUpdateTimestampStart);
708}
709
Alex Deymo5e3ea272016-01-28 13:42:23 -0800710} // namespace chromeos_update_engine