update_attempter_android.cc revision fe5228282571154b51d3907cad4744e228e66a22
15e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo//
25e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo// Copyright (C) 2016 The Android Open Source Project
35e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo//
45e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo// Licensed under the Apache License, Version 2.0 (the "License");
55e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo// you may not use this file except in compliance with the License.
65e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo// You may obtain a copy of the License at
75e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo//
85e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo//      http://www.apache.org/licenses/LICENSE-2.0
95e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo//
105e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo// Unless required by applicable law or agreed to in writing, software
115e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo// distributed under the License is distributed on an "AS IS" BASIS,
125e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
135e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo// See the License for the specific language governing permissions and
145e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo// limitations under the License.
155e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo//
165e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
175e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo#include "update_engine/update_attempter_android.h"
185e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
195e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo#include <algorithm>
20218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo#include <map>
2190aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu#include <memory>
225e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo#include <utility>
235e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
2490aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu#include <android-base/properties.h>
255e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo#include <base/bind.h>
265e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo#include <base/logging.h>
27218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo#include <base/strings/string_number_conversions.h>
285e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo#include <brillo/bind_lambda.h>
292703ef4466066d64d8021904e233b120f38c0272Sen Jiang#include <brillo/data_encoding.h>
305e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo#include <brillo/message_loops/message_loop.h>
31218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo#include <brillo/strings/string_utils.h>
32acbdd1cc442e80df4ca35ba27fdeed1c8b00f5c1Sen Jiang#include <log/log_safetynet.h>
335e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
345e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo#include "update_engine/common/constants.h"
352c131bbf81d8c02ade163b939c96e44aa93765e9Alex Deymo#include "update_engine/common/file_fetcher.h"
365e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo#include "update_engine/common/utils.h"
3703a4de7dc77b058987fc0670f4f67ba10ff31bc8Alex Deymo#include "update_engine/daemon_state_interface.h"
38d4c5debc65bb35ee61c2764bda059b7f307fd093Tianjie Xu#include "update_engine/metrics_reporter_interface.h"
391b66114d367d1b85b4397bb559e274dbd0ebcd31Tianjie Xu#include "update_engine/metrics_utils.h"
4087792ea818a63f2d246bbba2b7429b85ee8d669fAlex Deymo#include "update_engine/network_selector.h"
415e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo#include "update_engine/payload_consumer/download_action.h"
425e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo#include "update_engine/payload_consumer/filesystem_verifier_action.h"
435e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo#include "update_engine/payload_consumer/postinstall_runner_action.h"
443b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo#include "update_engine/update_status_utils.h"
455e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
4614c0da88a93aa7b1aa71d5e7e923b537f0d419f3Alex Deymo#ifndef _UE_SIDELOAD
4714c0da88a93aa7b1aa71d5e7e923b537f0d419f3Alex Deymo// Do not include support for external HTTP(s) urls when building
4814c0da88a93aa7b1aa71d5e7e923b537f0d419f3Alex Deymo// update_engine_sideload.
4914c0da88a93aa7b1aa71d5e7e923b537f0d419f3Alex Deymo#include "update_engine/libcurl_http_fetcher.h"
5014c0da88a93aa7b1aa71d5e7e923b537f0d419f3Alex Deymo#endif
5114c0da88a93aa7b1aa71d5e7e923b537f0d419f3Alex Deymo
525e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymousing base::Bind;
5390aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xuusing base::Time;
545e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymousing base::TimeDelta;
555e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymousing base::TimeTicks;
565e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymousing std::shared_ptr;
575e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymousing std::string;
585e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymousing std::vector;
597f92e2b7060cb35719acf96ef96a4e273e165bc5Aaron Woodusing update_engine::UpdateEngineStatus;
605e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
615e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymonamespace chromeos_update_engine {
625e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
635e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymonamespace {
645e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
650d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo// Minimum threshold to broadcast an status update in progress and time.
660d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymoconst double kBroadcastThresholdProgress = 0.01;  // 1%
670d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymoconst int kBroadcastThresholdSeconds = 10;
680d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo
695e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymoconst char* const kErrorDomain = "update_engine";
705e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo// TODO(deymo): Convert the different errors to a numeric value to report them
715e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo// back on the service error.
725e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymoconst char* const kGenericError = "generic_error";
735e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
745e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo// Log and set the error on the passed ErrorPtr.
755e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymobool LogAndSetError(brillo::ErrorPtr* error,
765e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo                    const tracked_objects::Location& location,
775e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo                    const string& reason) {
785e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
795e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
805e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo             << reason;
815e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  return false;
825e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
835e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
84fe5228282571154b51d3907cad4744e228e66a22Sen Jiangbool GetHeaderAsBool(const string& header, bool default_value) {
85fe5228282571154b51d3907cad4744e228e66a22Sen Jiang  int value = 0;
86fe5228282571154b51d3907cad4744e228e66a22Sen Jiang  if (base::StringToInt(header, &value) && (value == 0 || value == 1))
87fe5228282571154b51d3907cad4744e228e66a22Sen Jiang    return value == 1;
88fe5228282571154b51d3907cad4744e228e66a22Sen Jiang  return default_value;
89fe5228282571154b51d3907cad4744e228e66a22Sen Jiang}
90fe5228282571154b51d3907cad4744e228e66a22Sen Jiang
915e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}  // namespace
925e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
935e3ea278d9e771be3b51bd72985ad582678baddcAlex DeymoUpdateAttempterAndroid::UpdateAttempterAndroid(
9403a4de7dc77b058987fc0670f4f67ba10ff31bc8Alex Deymo    DaemonStateInterface* daemon_state,
955e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    PrefsInterface* prefs,
965e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    BootControlInterface* boot_control,
975e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    HardwareInterface* hardware)
985e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    : daemon_state_(daemon_state),
995e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo      prefs_(prefs),
1005e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo      boot_control_(boot_control),
1015e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo      hardware_(hardware),
1021b66114d367d1b85b4397bb559e274dbd0ebcd31Tianjie Xu      processor_(new ActionProcessor()),
103d4c5debc65bb35ee61c2764bda059b7f307fd093Tianjie Xu      clock_(new Clock()) {
104d4c5debc65bb35ee61c2764bda059b7f307fd093Tianjie Xu  metrics_reporter_ = metrics::CreateMetricsReporter();
10587792ea818a63f2d246bbba2b7429b85ee8d669fAlex Deymo  network_selector_ = network::CreateNetworkSelector();
1065e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
1075e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
1085e3ea278d9e771be3b51bd72985ad582678baddcAlex DeymoUpdateAttempterAndroid::~UpdateAttempterAndroid() {
1095e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // Release ourselves as the ActionProcessor's delegate to prevent
1105e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // re-scheduling the updates due to the processing stopped.
1115e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  processor_->set_delegate(nullptr);
1125e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
1135e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
1145e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymovoid UpdateAttempterAndroid::Init() {
1155e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // In case of update_engine restart without a reboot we need to restore the
1165e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // reboot needed state.
11790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  if (UpdateCompletedOnThisBoot()) {
1180e061aebc651e041b6d1d8a3a91834feb87e0d62Alex Deymo    SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
11990aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  } else {
1200e061aebc651e041b6d1d8a3a91834feb87e0d62Alex Deymo    SetStatusAndNotify(UpdateStatus::IDLE);
12190aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    UpdatePrefsAndReportUpdateMetricsOnReboot();
12290aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  }
1235e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
1245e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
1255e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymobool UpdateAttempterAndroid::ApplyPayload(
1265e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    const string& payload_url,
1275e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    int64_t payload_offset,
1285e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    int64_t payload_size,
1295e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    const vector<string>& key_value_pair_headers,
1305e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    brillo::ErrorPtr* error) {
1315e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
1325e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    return LogAndSetError(
1335e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo        error, FROM_HERE, "An update already applied, waiting for reboot");
1345e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  }
1355e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  if (ongoing_update_) {
1365e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    return LogAndSetError(
1375e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo        error, FROM_HERE, "Already processing an update, cancel it first.");
1385e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  }
1395e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  DCHECK(status_ == UpdateStatus::IDLE);
1405e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
141218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo  std::map<string, string> headers;
142218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo  for (const string& key_value_pair : key_value_pair_headers) {
143218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo    string key;
144218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo    string value;
145218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo    if (!brillo::string_utils::SplitAtFirst(
146218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo            key_value_pair, "=", &key, &value, false)) {
147218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo      return LogAndSetError(
148218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo          error, FROM_HERE, "Passed invalid header: " + key_value_pair);
149218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo    }
150218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo    if (!headers.emplace(key, value).second)
151218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo      return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
152218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo  }
153218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo
154218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo  // Unique identifier for the payload. An empty string means that the payload
155218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo  // can't be resumed.
156218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo  string payload_id = (headers[kPayloadPropertyFileHash] +
157218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo                       headers[kPayloadPropertyMetadataHash]);
1585e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
1595e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // Setup the InstallPlan based on the request.
1605e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  install_plan_ = InstallPlan();
1615e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
1625e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  install_plan_.download_url = payload_url;
1635e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  install_plan_.version = "";
1640fd51ff8fd200aab7f9ab930b47736505a7b59c3Alex Deymo  base_offset_ = payload_offset;
1650affc2c099fac47b999ba39f8f1bacb418e65a97Sen Jiang  InstallPlan::Payload payload;
1660affc2c099fac47b999ba39f8f1bacb418e65a97Sen Jiang  payload.size = payload_size;
1670affc2c099fac47b999ba39f8f1bacb418e65a97Sen Jiang  if (!payload.size) {
168218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo    if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
1690affc2c099fac47b999ba39f8f1bacb418e65a97Sen Jiang                              &payload.size)) {
1700affc2c099fac47b999ba39f8f1bacb418e65a97Sen Jiang      payload.size = 0;
171218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo    }
172218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo  }
1732703ef4466066d64d8021904e233b120f38c0272Sen Jiang  if (!brillo::data_encoding::Base64Decode(headers[kPayloadPropertyFileHash],
1740affc2c099fac47b999ba39f8f1bacb418e65a97Sen Jiang                                           &payload.hash)) {
1752703ef4466066d64d8021904e233b120f38c0272Sen Jiang    LOG(WARNING) << "Unable to decode base64 file hash: "
1762703ef4466066d64d8021904e233b120f38c0272Sen Jiang                 << headers[kPayloadPropertyFileHash];
1772703ef4466066d64d8021904e233b120f38c0272Sen Jiang  }
178218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo  if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
1790affc2c099fac47b999ba39f8f1bacb418e65a97Sen Jiang                            &payload.metadata_size)) {
1800affc2c099fac47b999ba39f8f1bacb418e65a97Sen Jiang    payload.metadata_size = 0;
181218397ff42cbef9f1b95fdfe30e8e82145ba9908Alex Deymo  }
182cdd5206c6507fa5c70344c269053d30777f7d674Sen Jiang  // The |payload.type| is not used anymore since minor_version 3.
183cdd5206c6507fa5c70344c269053d30777f7d674Sen Jiang  payload.type = InstallPayloadType::kUnknown;
1840affc2c099fac47b999ba39f8f1bacb418e65a97Sen Jiang  install_plan_.payloads.push_back(payload);
1850affc2c099fac47b999ba39f8f1bacb418e65a97Sen Jiang
1865e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // The |public_key_rsa| key would override the public key stored on disk.
1875e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  install_plan_.public_key_rsa = "";
1885e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
1895e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
1905e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  install_plan_.is_resume = !payload_id.empty() &&
1915e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo                            DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
1925e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  if (!install_plan_.is_resume) {
1935e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
1945e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo      LOG(WARNING) << "Unable to reset the update progress.";
1955e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    }
1965e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
1975e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo      LOG(WARNING) << "Unable to save the update check response hash.";
1985e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    }
1995e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  }
2005e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  install_plan_.source_slot = boot_control_->GetCurrentSlot();
2015e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  install_plan_.target_slot = install_plan_.source_slot == 0 ? 1 : 0;
202fb905d9b8d49f8fe41297c7aba2dd0942f1be311Alex Deymo
203fb905d9b8d49f8fe41297c7aba2dd0942f1be311Alex Deymo  install_plan_.powerwash_required =
204fe5228282571154b51d3907cad4744e228e66a22Sen Jiang      GetHeaderAsBool(headers[kPayloadPropertyPowerwash], false);
205fe5228282571154b51d3907cad4744e228e66a22Sen Jiang
206fe5228282571154b51d3907cad4744e228e66a22Sen Jiang  install_plan_.switch_slot_on_reboot =
207fe5228282571154b51d3907cad4744e228e66a22Sen Jiang      GetHeaderAsBool(headers[kPayloadPropertySwitchSlotOnReboot], true);
208fe5228282571154b51d3907cad4744e228e66a22Sen Jiang
209fe5228282571154b51d3907cad4744e228e66a22Sen Jiang  install_plan_.run_post_install = true;
210fe5228282571154b51d3907cad4744e228e66a22Sen Jiang  // Optionally skip post install if and only if:
211fe5228282571154b51d3907cad4744e228e66a22Sen Jiang  // a) we're resuming
212fe5228282571154b51d3907cad4744e228e66a22Sen Jiang  // b) post install has already succeeded before
213fe5228282571154b51d3907cad4744e228e66a22Sen Jiang  // c) RUN_POST_INSTALL is set to 0.
214fe5228282571154b51d3907cad4744e228e66a22Sen Jiang  if (install_plan_.is_resume && prefs_->Exists(kPrefsPostInstallSucceeded)) {
215fe5228282571154b51d3907cad4744e228e66a22Sen Jiang    bool post_install_succeeded = false;
216fe5228282571154b51d3907cad4744e228e66a22Sen Jiang    prefs_->GetBoolean(kPrefsPostInstallSucceeded, &post_install_succeeded);
217fe5228282571154b51d3907cad4744e228e66a22Sen Jiang    if (post_install_succeeded) {
218fe5228282571154b51d3907cad4744e228e66a22Sen Jiang      install_plan_.run_post_install =
219fe5228282571154b51d3907cad4744e228e66a22Sen Jiang          GetHeaderAsBool(headers[kPayloadPropertyRunPostInstall], true);
220fe5228282571154b51d3907cad4744e228e66a22Sen Jiang    }
221fe5228282571154b51d3907cad4744e228e66a22Sen Jiang  }
2225e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
22387792ea818a63f2d246bbba2b7429b85ee8d669fAlex Deymo  NetworkId network_id = kDefaultNetworkId;
22487792ea818a63f2d246bbba2b7429b85ee8d669fAlex Deymo  if (!headers[kPayloadPropertyNetworkId].empty()) {
22587792ea818a63f2d246bbba2b7429b85ee8d669fAlex Deymo    if (!base::StringToUint64(headers[kPayloadPropertyNetworkId],
22687792ea818a63f2d246bbba2b7429b85ee8d669fAlex Deymo                              &network_id)) {
22787792ea818a63f2d246bbba2b7429b85ee8d669fAlex Deymo      return LogAndSetError(
22887792ea818a63f2d246bbba2b7429b85ee8d669fAlex Deymo          error,
22987792ea818a63f2d246bbba2b7429b85ee8d669fAlex Deymo          FROM_HERE,
23087792ea818a63f2d246bbba2b7429b85ee8d669fAlex Deymo          "Invalid network_id: " + headers[kPayloadPropertyNetworkId]);
23187792ea818a63f2d246bbba2b7429b85ee8d669fAlex Deymo    }
23287792ea818a63f2d246bbba2b7429b85ee8d669fAlex Deymo    if (!network_selector_->SetProcessNetwork(network_id)) {
233cbd37c68ca69ceec25a9609c0c36fa30ee707f6dSen Jiang      return LogAndSetError(
234cbd37c68ca69ceec25a9609c0c36fa30ee707f6dSen Jiang          error,
235cbd37c68ca69ceec25a9609c0c36fa30ee707f6dSen Jiang          FROM_HERE,
236cbd37c68ca69ceec25a9609c0c36fa30ee707f6dSen Jiang          "Unable to set network_id: " + headers[kPayloadPropertyNetworkId]);
23787792ea818a63f2d246bbba2b7429b85ee8d669fAlex Deymo    }
23887792ea818a63f2d246bbba2b7429b85ee8d669fAlex Deymo  }
23987792ea818a63f2d246bbba2b7429b85ee8d669fAlex Deymo
2405e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  LOG(INFO) << "Using this install plan:";
2415e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  install_plan_.Dump();
2425e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
2432c131bbf81d8c02ade163b939c96e44aa93765e9Alex Deymo  BuildUpdateActions(payload_url);
244fdd6dec9c4be2fbd667cf874c4cc6f4ffecaeef9Alex Deymo  // Setup extra headers.
245fdd6dec9c4be2fbd667cf874c4cc6f4ffecaeef9Alex Deymo  HttpFetcher* fetcher = download_action_->http_fetcher();
246fdd6dec9c4be2fbd667cf874c4cc6f4ffecaeef9Alex Deymo  if (!headers[kPayloadPropertyAuthorization].empty())
247fdd6dec9c4be2fbd667cf874c4cc6f4ffecaeef9Alex Deymo    fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
248fdd6dec9c4be2fbd667cf874c4cc6f4ffecaeef9Alex Deymo  if (!headers[kPayloadPropertyUserAgent].empty())
249fdd6dec9c4be2fbd667cf874c4cc6f4ffecaeef9Alex Deymo    fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
250fdd6dec9c4be2fbd667cf874c4cc6f4ffecaeef9Alex Deymo
2515e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
252f28585764e91b7c25a7c2856ff645c8bb22d64a9Alex Deymo  ongoing_update_ = true;
2535e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
2545e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // Just in case we didn't update boot flags yet, make sure they're updated
2555e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // before any update processing starts. This will start the update process.
2565e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  UpdateBootFlags();
25790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu
25890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  UpdatePrefsOnUpdateStart(install_plan_.is_resume);
25990aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  // TODO(xunchang) report the metrics for unresumable updates
26090aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu
2615e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  return true;
2625e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
2635e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
2645e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymobool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
265f28585764e91b7c25a7c2856ff645c8bb22d64a9Alex Deymo  if (!ongoing_update_)
266f28585764e91b7c25a7c2856ff645c8bb22d64a9Alex Deymo    return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
267f28585764e91b7c25a7c2856ff645c8bb22d64a9Alex Deymo  processor_->SuspendProcessing();
268f28585764e91b7c25a7c2856ff645c8bb22d64a9Alex Deymo  return true;
2695e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
2705e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
2715e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymobool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
272f28585764e91b7c25a7c2856ff645c8bb22d64a9Alex Deymo  if (!ongoing_update_)
273f28585764e91b7c25a7c2856ff645c8bb22d64a9Alex Deymo    return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
274f28585764e91b7c25a7c2856ff645c8bb22d64a9Alex Deymo  processor_->ResumeProcessing();
275f28585764e91b7c25a7c2856ff645c8bb22d64a9Alex Deymo  return true;
2765e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
2775e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
2785e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymobool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
279f28585764e91b7c25a7c2856ff645c8bb22d64a9Alex Deymo  if (!ongoing_update_)
2805e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
281f28585764e91b7c25a7c2856ff645c8bb22d64a9Alex Deymo  processor_->StopProcessing();
282f28585764e91b7c25a7c2856ff645c8bb22d64a9Alex Deymo  return true;
2835e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
2845e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
2853b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymobool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
2863b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo  LOG(INFO) << "Attempting to reset state from "
2873b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo            << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
2883b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo
2893b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo  switch (status_) {
2903b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo    case UpdateStatus::IDLE:
2913b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo      return true;
2923b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo
2933b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo    case UpdateStatus::UPDATED_NEED_REBOOT:  {
2943b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo      // Remove the reboot marker so that if the machine is rebooted
2953b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo      // after resetting to idle state, it doesn't go back to
2963b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo      // UpdateStatus::UPDATED_NEED_REBOOT state.
2973b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo      bool ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId);
29890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      ClearMetricsPrefs();
2993b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo
3003b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo      // Update the boot flags so the current slot has higher priority.
3013b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo      if (!boot_control_->SetActiveBootSlot(boot_control_->GetCurrentSlot()))
3023b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo        ret_value = false;
3033b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo
3045259033d23938ce3ce20e4a9b599be0eec113610Alex Deymo      // Mark the current slot as successful again, since marking it as active
3055259033d23938ce3ce20e4a9b599be0eec113610Alex Deymo      // may reset the successful bit. We ignore the result of whether marking
3065259033d23938ce3ce20e4a9b599be0eec113610Alex Deymo      // the current slot as successful worked.
3075259033d23938ce3ce20e4a9b599be0eec113610Alex Deymo      if (!boot_control_->MarkBootSuccessfulAsync(Bind([](bool successful){})))
3085259033d23938ce3ce20e4a9b599be0eec113610Alex Deymo        ret_value = false;
3095259033d23938ce3ce20e4a9b599be0eec113610Alex Deymo
3103b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo      if (!ret_value) {
3113b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo        return LogAndSetError(
3123b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo            error,
3133b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo            FROM_HERE,
3143b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo            "Failed to reset the status to ");
3153b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo      }
3163b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo
3173b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo      SetStatusAndNotify(UpdateStatus::IDLE);
3183b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo      LOG(INFO) << "Reset status successful";
3193b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo      return true;
3203b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo    }
3213b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo
3223b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo    default:
3233b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo      return LogAndSetError(
3243b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo          error,
3253b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo          FROM_HERE,
3263b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo          "Reset not allowed in this state. Cancel the ongoing update first");
3273b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo  }
3283b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo}
3293b678db2e7fd4baa38c6d6b8bb8334f7d88b8682Alex Deymo
3305e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymovoid UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
3315e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo                                            ErrorCode code) {
3325e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  LOG(INFO) << "Processing Done.";
3335e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
3345990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo  switch (code) {
3355990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo    case ErrorCode::kSuccess:
3365990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo      // Update succeeded.
3375990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo      WriteUpdateCompletedMarker();
3385990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo      prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
3395990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo
3405990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo      LOG(INFO) << "Update successfully applied, waiting to reboot.";
3415990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo      break;
3425990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo
3435990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo    case ErrorCode::kFilesystemCopierError:
3445990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo    case ErrorCode::kNewRootfsVerificationError:
3455990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo    case ErrorCode::kNewKernelVerificationError:
3465990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo    case ErrorCode::kFilesystemVerifierError:
3475990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo    case ErrorCode::kDownloadStateInitializationError:
3485990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo      // Reset the ongoing update for these errors so it starts from the
3495990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo      // beginning next time.
3505990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo      DeltaPerformer::ResetUpdateProgress(prefs_, false);
3515990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo      LOG(INFO) << "Resetting update progress.";
3525990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo      break;
3535e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
354acbdd1cc442e80df4ca35ba27fdeed1c8b00f5c1Sen Jiang    case ErrorCode::kPayloadTimestampError:
355acbdd1cc442e80df4ca35ba27fdeed1c8b00f5c1Sen Jiang      // SafetyNet logging, b/36232423
356acbdd1cc442e80df4ca35ba27fdeed1c8b00f5c1Sen Jiang      android_errorWriteLog(0x534e4554, "36232423");
357acbdd1cc442e80df4ca35ba27fdeed1c8b00f5c1Sen Jiang      break;
358acbdd1cc442e80df4ca35ba27fdeed1c8b00f5c1Sen Jiang
3595990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo    default:
3605990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo      // Ignore all other error codes.
3615990bf33b50beec0caf55a97f5ca87608ccbc694Alex Deymo      break;
36203a4de7dc77b058987fc0670f4f67ba10ff31bc8Alex Deymo  }
3635e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
3645e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  TerminateUpdateAndNotify(code);
3655e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
3665e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
3675e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymovoid UpdateAttempterAndroid::ProcessingStopped(
3685e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    const ActionProcessor* processor) {
3695e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
3705e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
3715e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
3725e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymovoid UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
3735e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo                                             AbstractAction* action,
3745e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo                                             ErrorCode code) {
3755e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // Reset download progress regardless of whether or not the download
3765e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // action succeeded.
3775e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  const string type = action->Type();
3785e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  if (type == DownloadAction::StaticType()) {
3790d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo    download_progress_ = 0;
3805e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  }
381fe5228282571154b51d3907cad4744e228e66a22Sen Jiang  if (type == PostinstallRunnerAction::StaticType()) {
382fe5228282571154b51d3907cad4744e228e66a22Sen Jiang    bool succeeded =
383fe5228282571154b51d3907cad4744e228e66a22Sen Jiang        code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive;
384fe5228282571154b51d3907cad4744e228e66a22Sen Jiang    prefs_->SetBoolean(kPrefsPostInstallSucceeded, succeeded);
385fe5228282571154b51d3907cad4744e228e66a22Sen Jiang  }
3865e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  if (code != ErrorCode::kSuccess) {
3875e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    // If an action failed, the ActionProcessor will cancel the whole thing.
3885e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    return;
3895e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  }
3905e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  if (type == DownloadAction::StaticType()) {
3915e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    SetStatusAndNotify(UpdateStatus::FINALIZING);
3925e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  }
3935e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
3945e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
3955e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymovoid UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
3965e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo                                           uint64_t bytes_received,
3975e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo                                           uint64_t total) {
3980d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo  double progress = 0;
3995e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  if (total)
4005e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    progress = static_cast<double>(bytes_received) / static_cast<double>(total);
4010d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo  if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
4025e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    download_progress_ = progress;
4035e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    SetStatusAndNotify(UpdateStatus::DOWNLOADING);
4040d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo  } else {
4050d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo    ProgressUpdate(progress);
4065e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  }
407d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu
408d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu  // Update the bytes downloaded in prefs.
409d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu  int64_t current_bytes_downloaded =
410d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu      metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
411d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu  int64_t total_bytes_downloaded =
412d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu      metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
413d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu  prefs_->SetInt64(kPrefsCurrentBytesDownloaded,
414d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu                   current_bytes_downloaded + bytes_progressed);
415d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu  prefs_->SetInt64(kPrefsTotalBytesDownloaded,
416d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu                   total_bytes_downloaded + bytes_progressed);
4175e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
4185e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
4195e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymobool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
4205e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // TODO(deymo): Notify the DownloadAction that it should cancel the update
4215e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // download.
4225e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  return false;
4235e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
4245e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
4255e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymovoid UpdateAttempterAndroid::DownloadComplete() {
4265e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // Nothing needs to be done when the download completes.
4275e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
4285e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
4290d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymovoid UpdateAttempterAndroid::ProgressUpdate(double progress) {
4300d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo  // Self throttle based on progress. Also send notifications if progress is
4310d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo  // too slow.
4320d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo  if (progress == 1.0 ||
4330d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo      progress - download_progress_ >= kBroadcastThresholdProgress ||
4340d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo      TimeTicks::Now() - last_notify_time_ >=
4350d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo          TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
4360d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo    download_progress_ = progress;
4370d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo    SetStatusAndNotify(status_);
4380d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo  }
4390d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo}
4400d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo
4415e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymovoid UpdateAttempterAndroid::UpdateBootFlags() {
4425e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  if (updated_boot_flags_) {
4435e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    LOG(INFO) << "Already updated boot flags. Skipping.";
4445e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    CompleteUpdateBootFlags(true);
4455e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    return;
4465e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  }
4475e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // This is purely best effort.
4485e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  LOG(INFO) << "Marking booted slot as good.";
4495e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  if (!boot_control_->MarkBootSuccessfulAsync(
4505e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo          Bind(&UpdateAttempterAndroid::CompleteUpdateBootFlags,
4515e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo               base::Unretained(this)))) {
4525e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    LOG(ERROR) << "Failed to mark current boot as successful.";
4535e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    CompleteUpdateBootFlags(false);
4545e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  }
4555e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
4565e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
4575e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymovoid UpdateAttempterAndroid::CompleteUpdateBootFlags(bool successful) {
4585e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  updated_boot_flags_ = true;
4595e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  ScheduleProcessingStart();
4605e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
4615e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
4625e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymovoid UpdateAttempterAndroid::ScheduleProcessingStart() {
4635e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  LOG(INFO) << "Scheduling an action processor start.";
4645e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  brillo::MessageLoop::current()->PostTask(
465f1cf34849efdc0158fb1987ba74a51f25016c5bdLuis Hector Chavez      FROM_HERE,
466f1cf34849efdc0158fb1987ba74a51f25016c5bdLuis Hector Chavez      Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
467f1cf34849efdc0158fb1987ba74a51f25016c5bdLuis Hector Chavez           base::Unretained(processor_.get())));
4685e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
4695e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
4705e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymovoid UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
4715e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  if (status_ == UpdateStatus::IDLE) {
4725e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
4735e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    return;
4745e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  }
4755e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
4760d29854cf5bb05a22cf161b50052539aa420a36eAlex Deymo  download_progress_ = 0;
4775e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  actions_.clear();
4785e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  UpdateStatus new_status =
4795e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo      (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
4805e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo                                         : UpdateStatus::IDLE);
4815e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  SetStatusAndNotify(new_status);
4825e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  ongoing_update_ = false;
4835e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
4845e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  for (auto observer : daemon_state_->service_observers())
4855e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    observer->SendPayloadApplicationComplete(error_code);
4861b66114d367d1b85b4397bb559e274dbd0ebcd31Tianjie Xu
48790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  CollectAndReportUpdateMetricsOnUpdateFinished(error_code);
48890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  ClearMetricsPrefs();
48990aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  if (error_code == ErrorCode::kSuccess) {
49090aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    metrics_utils::SetSystemUpdatedMarker(clock_.get(), prefs_);
491d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu    // Clear the total bytes downloaded if and only if the update succeeds.
492d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu    prefs_->SetInt64(kPrefsTotalBytesDownloaded, 0);
49390aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  }
4945e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
4955e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
4965e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymovoid UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
4975e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  status_ = status;
4982d1c87bbd55878c5b4dd93e97a8cc28e715137ecSen Jiang  size_t payload_size =
4992d1c87bbd55878c5b4dd93e97a8cc28e715137ecSen Jiang      install_plan_.payloads.empty() ? 0 : install_plan_.payloads[0].size;
5007f92e2b7060cb35719acf96ef96a4e273e165bc5Aaron Wood  UpdateEngineStatus status_to_send = {.status = status_,
5017f92e2b7060cb35719acf96ef96a4e273e165bc5Aaron Wood                                       .progress = download_progress_,
5027f92e2b7060cb35719acf96ef96a4e273e165bc5Aaron Wood                                       .new_size_bytes = payload_size};
5037f92e2b7060cb35719acf96ef96a4e273e165bc5Aaron Wood
5045e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  for (auto observer : daemon_state_->service_observers()) {
5057f92e2b7060cb35719acf96ef96a4e273e165bc5Aaron Wood    observer->SendStatusUpdate(status_to_send);
5065e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  }
5075e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  last_notify_time_ = TimeTicks::Now();
5085e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
5095e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
5102c131bbf81d8c02ade163b939c96e44aa93765e9Alex Deymovoid UpdateAttempterAndroid::BuildUpdateActions(const string& url) {
5115e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  CHECK(!processor_->IsRunning());
5125e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  processor_->set_delegate(this);
5135e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
5145e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // Actions:
5155e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  shared_ptr<InstallPlanAction> install_plan_action(
5165e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo      new InstallPlanAction(install_plan_));
5175e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
5182c131bbf81d8c02ade163b939c96e44aa93765e9Alex Deymo  HttpFetcher* download_fetcher = nullptr;
5192c131bbf81d8c02ade163b939c96e44aa93765e9Alex Deymo  if (FileFetcher::SupportedUrl(url)) {
5202c131bbf81d8c02ade163b939c96e44aa93765e9Alex Deymo    DLOG(INFO) << "Using FileFetcher for file URL.";
5212c131bbf81d8c02ade163b939c96e44aa93765e9Alex Deymo    download_fetcher = new FileFetcher();
5222c131bbf81d8c02ade163b939c96e44aa93765e9Alex Deymo  } else {
52314c0da88a93aa7b1aa71d5e7e923b537f0d419f3Alex Deymo#ifdef _UE_SIDELOAD
52414c0da88a93aa7b1aa71d5e7e923b537f0d419f3Alex Deymo    LOG(FATAL) << "Unsupported sideload URI: " << url;
52514c0da88a93aa7b1aa71d5e7e923b537f0d419f3Alex Deymo#else
5262c131bbf81d8c02ade163b939c96e44aa93765e9Alex Deymo    LibcurlHttpFetcher* libcurl_fetcher =
5272c131bbf81d8c02ade163b939c96e44aa93765e9Alex Deymo        new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
5282c131bbf81d8c02ade163b939c96e44aa93765e9Alex Deymo    libcurl_fetcher->set_server_to_check(ServerToCheck::kDownload);
5292c131bbf81d8c02ade163b939c96e44aa93765e9Alex Deymo    download_fetcher = libcurl_fetcher;
53014c0da88a93aa7b1aa71d5e7e923b537f0d419f3Alex Deymo#endif  // _UE_SIDELOAD
5312c131bbf81d8c02ade163b939c96e44aa93765e9Alex Deymo  }
5325ae865b431cc041feed82f1db28a38e99dbd631fSen Jiang  shared_ptr<DownloadAction> download_action(
5335ae865b431cc041feed82f1db28a38e99dbd631fSen Jiang      new DownloadAction(prefs_,
5345ae865b431cc041feed82f1db28a38e99dbd631fSen Jiang                         boot_control_,
5355ae865b431cc041feed82f1db28a38e99dbd631fSen Jiang                         hardware_,
5365ae865b431cc041feed82f1db28a38e99dbd631fSen Jiang                         nullptr,             // system_state, not used.
5375ae865b431cc041feed82f1db28a38e99dbd631fSen Jiang                         download_fetcher));  // passes ownership
538fef85fd9ece49941db274559a938fe8b2c5157bfSen Jiang  shared_ptr<FilesystemVerifierAction> filesystem_verifier_action(
539e6e4bb929acd73e57b68a30d1e3a33d76607aec3Sen Jiang      new FilesystemVerifierAction());
5405e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
5415e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
542fb905d9b8d49f8fe41297c7aba2dd0942f1be311Alex Deymo      new PostinstallRunnerAction(boot_control_, hardware_));
5435e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
5445e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  download_action->set_delegate(this);
5455ae865b431cc041feed82f1db28a38e99dbd631fSen Jiang  download_action->set_base_offset(base_offset_);
5465e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  download_action_ = download_action;
547b6eef73e20736b4b6a43611fa732d8bba72ff7ffAlex Deymo  postinstall_runner_action->set_delegate(this);
5485e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
5495e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  actions_.push_back(shared_ptr<AbstractAction>(install_plan_action));
5505e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  actions_.push_back(shared_ptr<AbstractAction>(download_action));
551fef85fd9ece49941db274559a938fe8b2c5157bfSen Jiang  actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action));
5525e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
5535e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
5545e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // Bond them together. We have to use the leaf-types when calling
5555e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // BondActions().
5565e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  BondActions(install_plan_action.get(), download_action.get());
557fef85fd9ece49941db274559a938fe8b2c5157bfSen Jiang  BondActions(download_action.get(), filesystem_verifier_action.get());
558fef85fd9ece49941db274559a938fe8b2c5157bfSen Jiang  BondActions(filesystem_verifier_action.get(),
5595e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo              postinstall_runner_action.get());
5605e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
5615e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // Enqueue the actions.
5625e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  for (const shared_ptr<AbstractAction>& action : actions_)
5635e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo    processor_->EnqueueAction(action.get());
5645e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
5655e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
5665e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymobool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
5675e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  string boot_id;
5685e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
5695e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
5705e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  return true;
5715e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
5725e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
5735e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymobool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
5745e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // In case of an update_engine restart without a reboot, we stored the boot_id
5755e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // when the update was completed by setting a pref, so we can check whether
5765e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  // the last update was on this boot or a previous one.
5775e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  string boot_id;
5785e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
5795e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
5805e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  string update_completed_on_boot_id;
5815e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo  return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
5825e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo          prefs_->GetString(kPrefsUpdateCompletedOnBootId,
5835e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo                            &update_completed_on_boot_id) &&
5845e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo          update_completed_on_boot_id == boot_id);
5855e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}
5865e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo
58790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu// Collect and report the android metrics when we terminate the update.
58890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xuvoid UpdateAttempterAndroid::CollectAndReportUpdateMetricsOnUpdateFinished(
58990aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    ErrorCode error_code) {
59090aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  int64_t attempt_number =
59190aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
59290aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  PayloadType payload_type = kPayloadTypeFull;
59390aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  int64_t payload_size = 0;
59490aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  for (const auto& p : install_plan_.payloads) {
59590aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    if (p.type == InstallPayloadType::kDelta)
59690aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      payload_type = kPayloadTypeDelta;
59790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    payload_size += p.size;
59890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  }
59990aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu
60090aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  metrics::AttemptResult attempt_result =
60190aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      metrics_utils::GetAttemptResult(error_code);
60290aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  Time attempt_start_time = Time::FromInternalValue(
60390aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      metrics_utils::GetPersistedValue(kPrefsUpdateTimestampStart, prefs_));
60452c678cddc5dd7bda8a29e74ce6ef4d67e8d1487Tianjie Xu  TimeDelta duration = clock_->GetBootTime() - attempt_start_time;
60590aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  TimeDelta duration_uptime = clock_->GetMonotonicTime() - attempt_start_time;
60690aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu
60790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  metrics_reporter_->ReportUpdateAttemptMetrics(
60890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      nullptr,  // system_state
60990aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      static_cast<int>(attempt_number),
61090aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      payload_type,
61152c678cddc5dd7bda8a29e74ce6ef4d67e8d1487Tianjie Xu      duration,
61290aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      duration_uptime,
61390aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      payload_size,
61490aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      attempt_result,
61590aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      error_code);
61690aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu
617d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu  int64_t current_bytes_downloaded =
618d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu      metrics_utils::GetPersistedValue(kPrefsCurrentBytesDownloaded, prefs_);
619d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu  metrics_reporter_->ReportUpdateAttemptDownloadMetrics(
620d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu      current_bytes_downloaded,
621d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu      0,
622d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu      DownloadSource::kNumDownloadSources,
623d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu      metrics::DownloadErrorCode::kUnset,
624d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu      metrics::ConnectionType::kUnset);
625d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu
62690aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  if (error_code == ErrorCode::kSuccess) {
62790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    int64_t reboot_count =
62890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu        metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
62990aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    string build_version;
63090aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    prefs_->GetString(kPrefsPreviousVersion, &build_version);
631d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu
632d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu    // For android metrics, we only care about the total bytes downloaded
633d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu    // for all sources; for now we assume the only download source is
634d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu    // HttpsServer.
635d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu    int64_t total_bytes_downloaded =
636d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu        metrics_utils::GetPersistedValue(kPrefsTotalBytesDownloaded, prefs_);
637d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu    int64_t num_bytes_downloaded[kNumDownloadSources] = {};
638d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu    num_bytes_downloaded[DownloadSource::kDownloadSourceHttpsServer] =
639d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu        total_bytes_downloaded;
640d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu
641d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu    int download_overhead_percentage = 0;
642d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu    if (current_bytes_downloaded > 0) {
643d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu      download_overhead_percentage =
644d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu          (total_bytes_downloaded - current_bytes_downloaded) * 100ull /
645d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu          current_bytes_downloaded;
646d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu    }
64790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    metrics_reporter_->ReportSuccessfulUpdateMetrics(
64890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu        static_cast<int>(attempt_number),
64990aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu        0,  // update abandoned count
65090aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu        payload_type,
65190aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu        payload_size,
652d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu        num_bytes_downloaded,
653d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu        download_overhead_percentage,
65452c678cddc5dd7bda8a29e74ce6ef4d67e8d1487Tianjie Xu        duration,
65590aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu        static_cast<int>(reboot_count),
65690aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu        0);  // url_switch_count
65790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  }
65890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu}
65990aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu
66090aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xuvoid UpdateAttempterAndroid::UpdatePrefsAndReportUpdateMetricsOnReboot() {
66190aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  string current_boot_id;
66290aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  TEST_AND_RETURN(utils::GetBootId(&current_boot_id));
66390aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  // Example: [ro.build.version.incremental]: [4292972]
66490aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  string current_version =
66590aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      android::base::GetProperty("ro.build.version.incremental", "");
66690aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  TEST_AND_RETURN(!current_version.empty());
66790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu
66890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  // If there's no record of previous version (e.g. due to a data wipe), we
66990aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  // save the info of current boot and skip the metrics report.
67090aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  if (!prefs_->Exists(kPrefsPreviousVersion)) {
67190aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    prefs_->SetString(kPrefsBootId, current_boot_id);
67290aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    prefs_->SetString(kPrefsPreviousVersion, current_version);
67390aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    ClearMetricsPrefs();
67490aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    return;
67590aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  }
67690aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  string previous_version;
67790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  // update_engine restarted under the same build.
67890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  // TODO(xunchang) identify and report rollback by checking UpdateMarker.
67990aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  if (prefs_->GetString(kPrefsPreviousVersion, &previous_version) &&
68090aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      previous_version == current_version) {
68190aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    string last_boot_id;
68290aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    bool is_reboot = prefs_->Exists(kPrefsBootId) &&
68390aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu                     (prefs_->GetString(kPrefsBootId, &last_boot_id) &&
68490aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu                      last_boot_id != current_boot_id);
68590aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    // Increment the reboot number if |kPrefsNumReboots| exists. That pref is
68690aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    // set when we start a new update.
68790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    if (is_reboot && prefs_->Exists(kPrefsNumReboots)) {
68890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      prefs_->SetString(kPrefsBootId, current_boot_id);
68990aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      int64_t reboot_count =
69090aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu          metrics_utils::GetPersistedValue(kPrefsNumReboots, prefs_);
69190aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      metrics_utils::SetNumReboots(reboot_count + 1, prefs_);
69290aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    }
69390aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    return;
69490aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  }
69590aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu
69690aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  // Now that the build version changes, report the update metrics.
69790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  // TODO(xunchang) check the build version is larger than the previous one.
69890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  prefs_->SetString(kPrefsBootId, current_boot_id);
69990aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  prefs_->SetString(kPrefsPreviousVersion, current_version);
70090aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu
70190aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  bool previous_attempt_exists = prefs_->Exists(kPrefsPayloadAttemptNumber);
70290aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  // |kPrefsPayloadAttemptNumber| should be cleared upon successful update.
70390aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  if (previous_attempt_exists) {
70490aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    metrics_reporter_->ReportAbnormallyTerminatedUpdateAttemptMetrics();
70590aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  }
70690aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu
70790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  metrics_utils::LoadAndReportTimeToReboot(
70890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu      metrics_reporter_.get(), prefs_, clock_.get());
70990aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  ClearMetricsPrefs();
71090aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu}
71190aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu
71290aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu// Save the update start time. Reset the reboot count and attempt number if the
71390aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu// update isn't a resume; otherwise increment the attempt number.
71490aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xuvoid UpdateAttempterAndroid::UpdatePrefsOnUpdateStart(bool is_resume) {
71590aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  if (!is_resume) {
71690aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    metrics_utils::SetNumReboots(0, prefs_);
71790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    metrics_utils::SetPayloadAttemptNumber(1, prefs_);
71890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  } else {
71990aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    int64_t attempt_number =
72090aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu        metrics_utils::GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_);
72190aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu    metrics_utils::SetPayloadAttemptNumber(attempt_number + 1, prefs_);
72290aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  }
72390aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  Time update_start_time = clock_->GetMonotonicTime();
72490aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  metrics_utils::SetUpdateTimestampStart(update_start_time, prefs_);
72590aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu}
72690aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu
72790aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xuvoid UpdateAttempterAndroid::ClearMetricsPrefs() {
72890aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  CHECK(prefs_);
729d4777a148bc822ca11b8355a9df733a5798852c1Tianjie Xu  prefs_->Delete(kPrefsCurrentBytesDownloaded);
73090aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  prefs_->Delete(kPrefsNumReboots);
73190aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  prefs_->Delete(kPrefsPayloadAttemptNumber);
73290aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  prefs_->Delete(kPrefsSystemUpdatedMarker);
73390aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu  prefs_->Delete(kPrefsUpdateTimestampStart);
73490aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu}
73590aaa109e38f147ec4bfc772439d9949f1b237c0Tianjie Xu
7365e3ea278d9e771be3b51bd72985ad582678baddcAlex Deymo}  // namespace chromeos_update_engine
737