blob: d7de6e6256749f38a64cd24d49401ce8fecd6577 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 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//
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080016
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/cros/payload_state.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080018
Jay Srinivasan08262882012-12-28 19:29:43 -080019#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070020#include <string>
Jay Srinivasan08262882012-12-28 19:29:43 -080021
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080022#include <base/logging.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070023#include <base/strings/string_util.h>
24#include <base/strings/stringprintf.h>
Alex Deymoa2591792015-11-17 00:39:40 -030025#include <metrics/metrics_library.h>
Gilad Arnold1f847232014-04-07 12:07:49 -070026#include <policy/device_policy.h>
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080027
Alex Deymo39910dc2015-11-09 17:04:30 -080028#include "update_engine/common/clock.h"
29#include "update_engine/common/constants.h"
Alex Deymoe88e9fe2016-02-03 16:38:00 -080030#include "update_engine/common/error_code_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080031#include "update_engine/common/hardware_interface.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070032#include "update_engine/common/metrics_reporter_interface.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080033#include "update_engine/common/prefs.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070034#include "update_engine/common/system_state.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080035#include "update_engine/common/utils.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070036#include "update_engine/cros/connection_manager_interface.h"
37#include "update_engine/cros/omaha_request_params.h"
38#include "update_engine/cros/update_attempter.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080039#include "update_engine/metrics_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080040#include "update_engine/payload_consumer/install_plan.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080041
Jay Srinivasan08262882012-12-28 19:29:43 -080042using base::Time;
43using base::TimeDelta;
44using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080045using std::string;
46
47namespace chromeos_update_engine {
48
Tianjie Xu90aaa102017-10-10 17:39:03 -070049using metrics_utils::GetPersistedValue;
50
David Zeuthen9a017f22013-04-11 16:10:26 -070051const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
52
Jay Srinivasan08262882012-12-28 19:29:43 -080053// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070054static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080055
Jay Srinivasan08262882012-12-28 19:29:43 -080056// We want to randomize retry attempts after the backoff by +/- 6 hours.
57static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080058
Colin Howes0e452c92018-11-02 13:18:44 -070059// Limit persisting current update duration uptime to once per second
60static const uint64_t kUptimeResolution = 1;
61
Jay Srinivasan19409b72013-04-12 19:23:36 -070062PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070063 : prefs_(nullptr),
Jae Hoon Kim5e8e30b2020-05-06 14:59:06 -070064 powerwash_safe_prefs_(nullptr),
65 excluder_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070066 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070067 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070068 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070069 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070070 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070071 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070072 url_switch_count_(0),
Marton Hunyadye58bddb2018-04-10 20:27:26 +020073 rollback_happened_(false),
David Zeuthenafed4a12014-04-09 15:28:44 -070074 attempt_num_bytes_downloaded_(0),
75 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070076 attempt_type_(AttemptType::kUpdate) {
77 for (int i = 0; i <= kNumDownloadSources; i++)
78 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070079}
80
Amin Hassani538bd592020-11-04 20:46:08 -080081bool PayloadState::Initialize() {
82 prefs_ = SystemState::Get()->prefs();
83 powerwash_safe_prefs_ = SystemState::Get()->powerwash_safe_prefs();
84 excluder_ = SystemState::Get()->update_attempter()->GetExcluder();
Jay Srinivasan08262882012-12-28 19:29:43 -080085 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080086 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070087 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080088 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080089 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070090 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080091 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070092 LoadUpdateTimestampStart();
93 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
94 // being called before it. Don't reorder.
95 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070096 for (int i = 0; i < kNumDownloadSources; i++) {
97 DownloadSource source = static_cast<DownloadSource>(i);
98 LoadCurrentBytesDownloaded(source);
99 LoadTotalBytesDownloaded(source);
100 }
Chris Sosabe45bef2013-04-09 18:25:12 -0700101 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -0700102 LoadNumResponsesSeen();
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200103 LoadRollbackHappened();
Chris Sosaaa18e162013-06-20 13:20:30 -0700104 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700105 LoadP2PFirstAttemptTimestamp();
106 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800107 return true;
108}
109
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800110void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800111 // Always store the latest response.
112 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800113
Jay Srinivasan53173b92013-05-17 17:13:01 -0700114 // Compute the candidate URLs first as they are used to calculate the
115 // response signature so that a change in enterprise policy for
116 // HTTP downloads being enabled or not could be honored as soon as the
117 // next update check happens.
118 ComputeCandidateUrls();
119
Jay Srinivasan08262882012-12-28 19:29:43 -0800120 // Check if the "signature" of this response (i.e. the fields we care about)
121 // has changed.
122 string new_response_signature = CalculateResponseSignature();
123 bool has_response_changed = (response_signature_ != new_response_signature);
124
125 // If the response has changed, we should persist the new signature and
126 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800127 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800128 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700129 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800130 SetResponseSignature(new_response_signature);
131 ResetPersistedState();
132 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800133 }
134
Sen Jiang97eba342017-05-22 14:34:11 -0700135 // Always start from payload index 0, even for resume, to download partition
136 // info from previous payloads.
137 payload_index_ = 0;
138
Jay Srinivasan08262882012-12-28 19:29:43 -0800139 // This is the earliest point at which we can validate whether the URL index
140 // we loaded from the persisted state is a valid value. If the response
141 // hasn't changed but the URL index is invalid, it's indicative of some
142 // tampering of the persisted state.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800143 if (payload_index_ >= candidate_urls_.size() ||
144 url_index_ >= candidate_urls_[payload_index_].size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800145 LOG(INFO) << "Resetting all payload state as the url index seems to have "
146 "been tampered with";
147 ResetPersistedState();
148 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800149 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700150
151 // Update the current download source which depends on the latest value of
152 // the response.
153 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800154}
155
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700156void PayloadState::SetUsingP2PForDownloading(bool value) {
157 using_p2p_for_downloading_ = value;
158 // Update the current download source which depends on whether we are
159 // using p2p or not.
160 UpdateCurrentDownloadSource();
161}
162
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800163void PayloadState::DownloadComplete() {
164 LOG(INFO) << "Payload downloaded successfully";
165 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700166 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800167}
168
169void PayloadState::DownloadProgress(size_t count) {
170 if (count == 0)
171 return;
172
David Zeuthen9a017f22013-04-11 16:10:26 -0700173 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700174 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700175
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800176 // We've received non-zero bytes from a recent download operation. Since our
177 // URL failure count is meant to penalize a URL only for consecutive
178 // failures, downloading bytes successfully means we should reset the failure
179 // count (as we know at least that the URL is working). In future, we can
180 // design this to be more sophisticated to check for more intelligent failure
181 // patterns, but right now, even 1 byte downloaded will mark the URL to be
182 // good unless it hits 10 (or configured number of) consecutive failures
183 // again.
184
185 if (GetUrlFailureCount() == 0)
186 return;
187
188 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
189 << " to 0 as we received " << count << " bytes successfully";
190 SetUrlFailureCount(0);
191}
192
David Zeuthenafed4a12014-04-09 15:28:44 -0700193void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700194 // Flush previous state from abnormal attempt failure, if any.
195 ReportAndClearPersistedAttemptMetrics();
196
David Zeuthenafed4a12014-04-09 15:28:44 -0700197 attempt_type_ = attempt_type;
198
Amin Hassani538bd592020-11-04 20:46:08 -0800199 ClockInterface* clock = SystemState::Get()->clock();
David Zeuthen33bae492014-02-25 16:16:18 -0800200 attempt_start_time_boot_ = clock->GetBootTime();
201 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800202 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700203
204 metrics::ConnectionType type;
Sen Jiang255e22b2016-05-20 16:15:29 -0700205 ConnectionType network_connection_type;
206 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700207 ConnectionManagerInterface* connection_manager =
Amin Hassani538bd592020-11-04 20:46:08 -0800208 SystemState::Get()->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700209 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700210 &tethering)) {
211 LOG(ERROR) << "Failed to determine connection type.";
212 type = metrics::ConnectionType::kUnknown;
213 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800214 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700215 }
216 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700217
218 if (attempt_type == AttemptType::kUpdate)
219 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800220}
221
Chris Sosabe45bef2013-04-09 18:25:12 -0700222void PayloadState::UpdateResumed() {
223 LOG(INFO) << "Resuming an update that was previously started.";
224 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700225 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700226}
227
Jay Srinivasan19409b72013-04-12 19:23:36 -0700228void PayloadState::UpdateRestarted() {
229 LOG(INFO) << "Starting a new update";
230 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700231 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700232 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700233}
234
David Zeuthen9a017f22013-04-11 16:10:26 -0700235void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700236 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700237 CalculateUpdateDurationUptime();
Amin Hassani538bd592020-11-04 20:46:08 -0800238 SetUpdateTimestampEnd(SystemState::Get()->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800239
David Zeuthen96197df2014-04-16 12:22:39 -0700240 switch (attempt_type_) {
241 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700242 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700243 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700244 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700245 break;
246
247 case AttemptType::kRollback:
Amin Hassani538bd592020-11-04 20:46:08 -0800248 SystemState::Get()->metrics_reporter()->ReportRollbackMetrics(
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700249 metrics::RollbackResult::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700250 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700251 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700252
253 // Reset the number of responses seen since it counts from the last
254 // successful update, e.g. now.
255 SetNumResponsesSeen(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700256 SetPayloadIndex(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700257
Amin Hassani538bd592020-11-04 20:46:08 -0800258 metrics_utils::SetSystemUpdatedMarker(SystemState::Get()->clock(), prefs_);
David Zeuthen9a017f22013-04-11 16:10:26 -0700259}
260
David Zeuthena99981f2013-04-29 13:42:47 -0700261void PayloadState::UpdateFailed(ErrorCode error) {
262 ErrorCode base_error = utils::GetBaseErrorCode(error);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800263 LOG(INFO) << "Updating payload state for error code: " << base_error << " ("
264 << utils::ErrorCodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800265
Jay Srinivasan53173b92013-05-17 17:13:01 -0700266 if (candidate_urls_.size() == 0) {
267 // This means we got this error even before we got a valid Omaha response
268 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800269 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800270 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
271 return;
272 }
273
David Zeuthen96197df2014-04-16 12:22:39 -0700274 switch (attempt_type_) {
275 case AttemptType::kUpdate:
276 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700277 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700278 break;
279
280 case AttemptType::kRollback:
Amin Hassani538bd592020-11-04 20:46:08 -0800281 SystemState::Get()->metrics_reporter()->ReportRollbackMetrics(
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700282 metrics::RollbackResult::kFailed);
David Zeuthen96197df2014-04-16 12:22:39 -0700283 break;
284 }
David Zeuthen33bae492014-02-25 16:16:18 -0800285
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800286 switch (base_error) {
287 // Errors which are good indicators of a problem with a particular URL or
288 // the protocol used in the URL or entities in the communication channel
289 // (e.g. proxies). We should try the next available URL in the next update
290 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700291 case ErrorCode::kPayloadHashMismatchError:
292 case ErrorCode::kPayloadSizeMismatchError:
293 case ErrorCode::kDownloadPayloadVerificationError:
294 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
295 case ErrorCode::kSignedDeltaPayloadExpectedError:
296 case ErrorCode::kDownloadInvalidMetadataMagicString:
297 case ErrorCode::kDownloadSignatureMissingInManifest:
298 case ErrorCode::kDownloadManifestParseError:
299 case ErrorCode::kDownloadMetadataSignatureError:
300 case ErrorCode::kDownloadMetadataSignatureVerificationError:
301 case ErrorCode::kDownloadMetadataSignatureMismatch:
302 case ErrorCode::kDownloadOperationHashVerificationError:
303 case ErrorCode::kDownloadOperationExecutionError:
304 case ErrorCode::kDownloadOperationHashMismatch:
305 case ErrorCode::kDownloadInvalidMetadataSize:
306 case ErrorCode::kDownloadInvalidMetadataSignature:
307 case ErrorCode::kDownloadOperationHashMissingError:
308 case ErrorCode::kDownloadMetadataSignatureMissingError:
309 case ErrorCode::kPayloadMismatchedType:
310 case ErrorCode::kUnsupportedMajorPayloadVersion:
311 case ErrorCode::kUnsupportedMinorPayloadVersion:
Sen Jiang8e768e92017-06-28 17:13:19 -0700312 case ErrorCode::kPayloadTimestampError:
Sen Jiang57f91802017-11-14 17:42:13 -0800313 case ErrorCode::kVerityCalculationError:
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700314 ExcludeCurrentPayload();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800315 IncrementUrlIndex();
316 break;
317
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800318 // Errors which seem to be just transient network/communication related
319 // failures and do not indicate any inherent problem with the URL itself.
320 // So, we should keep the current URL but just increment the
321 // failure count to give it more chances. This way, while we maximize our
322 // chances of downloading from the URLs that appear earlier in the
323 // response (because download from a local server URL that appears earlier
324 // in a response is preferable than downloading from the next URL which
325 // could be a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700326
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700327 case ErrorCode::kError:
328 case ErrorCode::kDownloadTransferError:
329 case ErrorCode::kDownloadWriteError:
330 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700331 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800332 IncrementFailureCount();
333 break;
334
335 // Errors which are not specific to a URL and hence shouldn't result in
336 // the URL being penalized. This can happen in two cases:
337 // 1. We haven't started downloading anything: These errors don't cost us
338 // anything in terms of actual payload bytes, so we should just do the
339 // regular retries at the next update check.
340 // 2. We have successfully downloaded the payload: In this case, the
341 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800342 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800343 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700344 case ErrorCode::kOmahaRequestError:
345 case ErrorCode::kOmahaResponseHandlerError:
346 case ErrorCode::kPostinstallRunnerError:
347 case ErrorCode::kFilesystemCopierError:
348 case ErrorCode::kInstallDeviceOpenError:
349 case ErrorCode::kKernelDeviceOpenError:
350 case ErrorCode::kDownloadNewPartitionInfoError:
351 case ErrorCode::kNewRootfsVerificationError:
352 case ErrorCode::kNewKernelVerificationError:
353 case ErrorCode::kPostinstallBootedFromFirmwareB:
354 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
355 case ErrorCode::kOmahaRequestEmptyResponseError:
356 case ErrorCode::kOmahaRequestXMLParseError:
357 case ErrorCode::kOmahaResponseInvalid:
358 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
359 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700360 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700361 case ErrorCode::kOmahaUpdateDeferredForBackoff:
362 case ErrorCode::kPostinstallPowerwashError:
363 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400364 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700365 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800366 case ErrorCode::kUserCanceled:
Weidong Guo421ff332017-04-17 10:08:38 -0700367 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
Sen Jiangfe522822017-10-31 15:14:11 -0700368 case ErrorCode::kUpdatedButNotActive:
Sen Jiang89e24c12018-03-22 18:05:44 -0700369 case ErrorCode::kNoUpdate:
Marton Hunyady199152d2018-05-07 19:08:48 +0200370 case ErrorCode::kRollbackNotPossible:
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700371 case ErrorCode::kFirstActiveOmahaPingSentPersistenceError:
Amin Hassanid3d84212019-08-17 00:27:44 -0700372 case ErrorCode::kInternalLibCurlError:
373 case ErrorCode::kUnresolvedHostError:
374 case ErrorCode::kUnresolvedHostRecovered:
Yifan Hong46e37d42019-12-13 12:01:42 -0800375 case ErrorCode::kNotEnoughSpace:
Yifan Hong77279902019-12-17 16:38:21 -0800376 case ErrorCode::kDeviceCorrupted:
Jae Hoon Kim3e69b4c2020-06-16 09:23:39 -0700377 case ErrorCode::kPackageExcludedFromUpdate:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800378 LOG(INFO) << "Not incrementing URL index or failure count for this error";
379 break;
380
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800381 case ErrorCode::kSuccess: // success code
382 case ErrorCode::kUmaReportedMax: // not an error code
383 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
384 case ErrorCode::kDevModeFlag: // not an error code
385 case ErrorCode::kResumedFlag: // not an error code
386 case ErrorCode::kTestImageFlag: // not an error code
387 case ErrorCode::kTestOmahaUrlFlag: // not an error code
388 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800389 // These shouldn't happen. Enumerating these explicitly here so that we
390 // can let the compiler warn about new error codes that are added to
391 // action_processor.h but not added here.
392 LOG(WARNING) << "Unexpected error code for UpdateFailed";
393 break;
394
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800395 // Note: Not adding a default here so as to let the compiler warn us of
396 // any new enums that were added in the .h but not listed in this switch.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800397 }
398}
399
Jay Srinivasan08262882012-12-28 19:29:43 -0800400bool PayloadState::ShouldBackoffDownload() {
401 if (response_.disable_payload_backoff) {
402 LOG(INFO) << "Payload backoff logic is disabled. "
403 "Can proceed with the download";
404 return false;
405 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700406 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700407 LOG(INFO) << "Payload backoff logic is disabled because download "
408 << "will happen from local peer (via p2p).";
409 return false;
410 }
Amin Hassani538bd592020-11-04 20:46:08 -0800411 if (SystemState::Get()->request_params()->interactive()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700412 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
413 return false;
414 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700415 for (const auto& package : response_.packages) {
416 if (package.is_delta) {
417 // If delta payloads fail, we want to fallback quickly to full payloads as
418 // they are more likely to succeed. Exponential backoffs would greatly
419 // slow down the fallback to full payloads. So we don't backoff for delta
420 // payloads.
421 LOG(INFO) << "No backoffs for delta payloads. "
422 << "Can proceed with the download";
423 return false;
424 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800425 }
426
Amin Hassani538bd592020-11-04 20:46:08 -0800427 if (!SystemState::Get()->hardware()->IsOfficialBuild() &&
Amin Hassaniffb6d802018-03-30 11:43:57 -0700428 !prefs_->Exists(kPrefsNoIgnoreBackoff)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800429 // Backoffs are needed only for official builds. We do not want any delays
Amin Hassaniffb6d802018-03-30 11:43:57 -0700430 // or update failures due to backoffs during testing or development. Unless
431 // the |kPrefsNoIgnoreBackoff| is manually set.
Jay Srinivasan08262882012-12-28 19:29:43 -0800432 LOG(INFO) << "No backoffs for test/dev images. "
433 << "Can proceed with the download";
434 return false;
435 }
436
437 if (backoff_expiry_time_.is_null()) {
438 LOG(INFO) << "No backoff expiry time has been set. "
439 << "Can proceed with the download";
440 return false;
441 }
442
443 if (backoff_expiry_time_ < Time::Now()) {
444 LOG(INFO) << "The backoff expiry time ("
445 << utils::ToString(backoff_expiry_time_)
446 << ") has elapsed. Can proceed with the download";
447 return false;
448 }
449
450 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
451 << utils::ToString(backoff_expiry_time_);
452 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800453}
454
Chris Sosaaa18e162013-06-20 13:20:30 -0700455void PayloadState::Rollback() {
Amin Hassani538bd592020-11-04 20:46:08 -0800456 SetRollbackVersion(SystemState::Get()->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700457 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700458}
459
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800460void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700461 // Update the payload attempt number for both payload types: full and delta.
462 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
463}
464
465void PayloadState::IncrementFullPayloadAttemptNumber() {
Jae Hoon Kim76583912020-06-23 10:24:03 -0700466 DCHECK(payload_index_ < response_.packages.size());
Alex Deymo820cc702013-06-28 15:43:46 -0700467 // Update the payload attempt number for full payloads and the backoff time.
Sen Jiangcdd52062017-05-18 15:33:10 -0700468 if (response_.packages[payload_index_].is_delta) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800469 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
470 return;
471 }
472
Alex Deymo29b51d92013-07-09 15:26:24 -0700473 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700474 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800475 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800476}
477
478void PayloadState::IncrementUrlIndex() {
Jae Hoon Kim76583912020-06-23 10:24:03 -0700479 DCHECK(payload_index_ < candidate_urls_.size());
Sen Jiang0affc2c2017-02-10 15:55:05 -0800480 size_t next_url_index = url_index_ + 1;
Jae Hoon Kima3210e62020-05-07 11:32:44 -0700481 size_t max_url_size = candidate_urls_[payload_index_].size();
Sen Jiang0affc2c2017-02-10 15:55:05 -0800482 if (next_url_index < max_url_size) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800483 LOG(INFO) << "Incrementing the URL index for next attempt";
484 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800485 } else {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800486 LOG(INFO) << "Resetting the current URL index (" << url_index_ << ") to "
487 << "0 as we only have " << max_url_size << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800488 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700489 IncrementPayloadAttemptNumber();
490 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800491 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800492
David Zeuthencc6f9962013-04-18 11:57:24 -0700493 // If we have multiple URLs, record that we just switched to another one
Sen Jiang0affc2c2017-02-10 15:55:05 -0800494 if (max_url_size > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700495 SetUrlSwitchCount(url_switch_count_ + 1);
496
Jay Srinivasan08262882012-12-28 19:29:43 -0800497 // Whenever we update the URL index, we should also clear the URL failure
498 // count so we can start over fresh for the new URL.
499 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800500}
501
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800502void PayloadState::IncrementFailureCount() {
503 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800504 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800505 LOG(INFO) << "Incrementing the URL failure count";
506 SetUrlFailureCount(next_url_failure_count);
507 } else {
508 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
509 << ". Trying next available URL";
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700510 ExcludeCurrentPayload();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800511 IncrementUrlIndex();
512 }
513}
514
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700515void PayloadState::ExcludeCurrentPayload() {
Jae Hoon Kim76583912020-06-23 10:24:03 -0700516 if (payload_index_ >= response_.packages.size()) {
517 LOG(INFO) << "Skipping exclusion of the current payload.";
518 return;
519 }
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700520 const auto& package = response_.packages[payload_index_];
521 if (!package.can_exclude) {
522 LOG(INFO) << "Not excluding as marked non-excludable for package hash="
523 << package.hash;
524 return;
525 }
526 auto exclusion_name = utils::GetExclusionName(GetCurrentUrl());
527 if (!excluder_->Exclude(exclusion_name))
528 LOG(WARNING) << "Failed to exclude "
529 << " Package Hash=" << package.hash
530 << " CurrentUrl=" << GetCurrentUrl();
531 else
532 LOG(INFO) << "Excluded "
533 << " Package Hash=" << package.hash
534 << " CurrentUrl=" << GetCurrentUrl();
535}
536
Jay Srinivasan08262882012-12-28 19:29:43 -0800537void PayloadState::UpdateBackoffExpiryTime() {
538 if (response_.disable_payload_backoff) {
539 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
540 SetBackoffExpiryTime(Time());
541 return;
542 }
543
Alex Deymo820cc702013-06-28 15:43:46 -0700544 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800545 SetBackoffExpiryTime(Time());
546 return;
547 }
548
549 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700550 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800551 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700552 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700553 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800554
555 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
556 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700557 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800558
559 // The number of days is the minimum of 2 raised to (payload_attempt_number
560 // - 1) or kMaxBackoffDays.
561 num_days = min(num_days << power, kMaxBackoffDays);
562
563 // We don't want all retries to happen exactly at the same time when
564 // retrying after backoff. So add some random minutes to fuzz.
565 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800566 TimeDelta next_backoff_interval =
567 TimeDelta::FromDays(num_days) + TimeDelta::FromMinutes(fuzz_minutes);
Jay Srinivasan08262882012-12-28 19:29:43 -0800568 LOG(INFO) << "Incrementing the backoff expiry time by "
569 << utils::FormatTimeDelta(next_backoff_interval);
570 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
571}
572
Jay Srinivasan19409b72013-04-12 19:23:36 -0700573void PayloadState::UpdateCurrentDownloadSource() {
574 current_download_source_ = kNumDownloadSources;
575
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700576 if (using_p2p_for_downloading_) {
577 current_download_source_ = kDownloadSourceHttpPeer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800578 } else if (payload_index_ < candidate_urls_.size() &&
579 candidate_urls_[payload_index_].size() != 0) {
580 const string& current_url = candidate_urls_[payload_index_][GetUrlIndex()];
581 if (base::StartsWith(
582 current_url, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700583 current_download_source_ = kDownloadSourceHttpsServer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800584 } else if (base::StartsWith(current_url,
585 "http://",
Alex Vakulenko0103c362016-01-20 07:56:15 -0800586 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700587 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800588 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700589 }
590
591 LOG(INFO) << "Current download source: "
592 << utils::ToString(current_download_source_);
593}
594
595void PayloadState::UpdateBytesDownloaded(size_t count) {
596 SetCurrentBytesDownloaded(
597 current_download_source_,
598 GetCurrentBytesDownloaded(current_download_source_) + count,
599 false);
600 SetTotalBytesDownloaded(
601 current_download_source_,
602 GetTotalBytesDownloaded(current_download_source_) + count,
603 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800604
605 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700606}
607
David Zeuthen33bae492014-02-25 16:16:18 -0800608PayloadType PayloadState::CalculatePayloadType() {
Sen Jiangcdd52062017-05-18 15:33:10 -0700609 for (const auto& package : response_.packages) {
610 if (package.is_delta) {
611 return kPayloadTypeDelta;
612 }
David Zeuthen33bae492014-02-25 16:16:18 -0800613 }
Amin Hassani538bd592020-11-04 20:46:08 -0800614 OmahaRequestParams* params = SystemState::Get()->request_params();
Sen Jiangcdd52062017-05-18 15:33:10 -0700615 if (params->delta_okay()) {
616 return kPayloadTypeFull;
617 }
618 // Full payload, delta was not allowed by request.
619 return kPayloadTypeForcedFull;
David Zeuthen33bae492014-02-25 16:16:18 -0800620}
621
David Zeuthen33bae492014-02-25 16:16:18 -0800622void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
623 int attempt_number = GetPayloadAttemptNumber();
624
625 PayloadType payload_type = CalculatePayloadType();
626
Sen Jiang0affc2c2017-02-10 15:55:05 -0800627 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800628
629 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
630
Amin Hassani538bd592020-11-04 20:46:08 -0800631 ClockInterface* clock = SystemState::Get()->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700632 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800633 TimeDelta duration_uptime =
634 clock->GetMonotonicTime() - attempt_start_time_monotonic_;
David Zeuthen33bae492014-02-25 16:16:18 -0800635
636 int64_t payload_download_speed_bps = 0;
637 int64_t usec = duration_uptime.InMicroseconds();
638 if (usec > 0) {
639 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
640 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
641 payload_download_speed_bps = static_cast<int64_t>(bps);
642 }
643
644 DownloadSource download_source = current_download_source_;
645
646 metrics::DownloadErrorCode payload_download_error_code =
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800647 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700648 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800649 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800650
651 // Add additional detail to AttemptResult
652 switch (attempt_result) {
653 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800654 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800655 break;
656
657 case metrics::AttemptResult::kInternalError:
658 internal_error_code = code;
659 break;
660
661 // Explicit fall-through for cases where we do not have additional
662 // detail. We avoid the default keyword to force people adding new
663 // AttemptResult values to visit this code and examine whether
664 // additional detail is needed.
665 case metrics::AttemptResult::kUpdateSucceeded:
666 case metrics::AttemptResult::kMetadataMalformed:
667 case metrics::AttemptResult::kOperationMalformed:
668 case metrics::AttemptResult::kOperationExecutionError:
669 case metrics::AttemptResult::kMetadataVerificationFailed:
670 case metrics::AttemptResult::kPayloadVerificationFailed:
671 case metrics::AttemptResult::kVerificationFailed:
672 case metrics::AttemptResult::kPostInstallFailed:
673 case metrics::AttemptResult::kAbnormalTermination:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800674 case metrics::AttemptResult::kUpdateCanceled:
Sen Jiangfe522822017-10-31 15:14:11 -0700675 case metrics::AttemptResult::kUpdateSucceededNotActive:
Andrewb57c16e2020-07-22 14:32:39 -0700676 case metrics::AttemptResult::kUpdateSkipped:
David Zeuthen33bae492014-02-25 16:16:18 -0800677 case metrics::AttemptResult::kNumConstants:
678 case metrics::AttemptResult::kUnset:
679 break;
680 }
681
Amin Hassani538bd592020-11-04 20:46:08 -0800682 SystemState::Get()->metrics_reporter()->ReportUpdateAttemptMetrics(
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700683 attempt_number,
684 payload_type,
685 duration,
686 duration_uptime,
687 payload_size,
Tianjie Xu1f93d092017-10-09 12:13:29 -0700688 attempt_result,
689 internal_error_code);
690
Amin Hassani538bd592020-11-04 20:46:08 -0800691 SystemState::Get()->metrics_reporter()->ReportUpdateAttemptDownloadMetrics(
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700692 payload_bytes_downloaded,
693 payload_download_speed_bps,
694 download_source,
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700695 payload_download_error_code,
696 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800697}
698
David Zeuthen4e1d1492014-04-25 13:12:27 -0700699void PayloadState::PersistAttemptMetrics() {
700 // TODO(zeuthen): For now we only persist whether an attempt was in
701 // progress and not values/metrics related to the attempt. This
702 // means that when this happens, of all the UpdateEngine.Attempt.*
703 // metrics, only UpdateEngine.Attempt.Result is reported (with the
704 // value |kAbnormalTermination|). In the future we might want to
705 // persist more data so we can report other metrics in the
706 // UpdateEngine.Attempt.* namespace when this happens.
707 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
708}
709
710void PayloadState::ClearPersistedAttemptMetrics() {
711 prefs_->Delete(kPrefsAttemptInProgress);
712}
713
714void PayloadState::ReportAndClearPersistedAttemptMetrics() {
715 bool attempt_in_progress = false;
716 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
717 return;
718 if (!attempt_in_progress)
719 return;
720
Amin Hassani538bd592020-11-04 20:46:08 -0800721 SystemState::Get()
722 ->metrics_reporter()
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700723 ->ReportAbnormallyTerminatedUpdateAttemptMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700724
725 ClearPersistedAttemptMetrics();
726}
727
David Zeuthen33bae492014-02-25 16:16:18 -0800728void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700729 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800730
731 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800732 int64_t total_bytes_by_source[kNumDownloadSources];
733 int64_t successful_bytes = 0;
734 int64_t total_bytes = 0;
735 int64_t successful_mbs = 0;
736 int64_t total_mbs = 0;
737
Jay Srinivasan19409b72013-04-12 19:23:36 -0700738 for (int i = 0; i < kNumDownloadSources; i++) {
739 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800740 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700741
David Zeuthen44848602013-06-24 13:32:14 -0700742 // Only consider this download source (and send byte counts) as
743 // having been used if we downloaded a non-trivial amount of bytes
744 // (e.g. at least 1 MiB) that contributed to the final success of
745 // the update. Otherwise we're going to end up with a lot of
746 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700747
David Zeuthen33bae492014-02-25 16:16:18 -0800748 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800749 successful_bytes += bytes;
750 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700751 SetCurrentBytesDownloaded(source, 0, true);
752
David Zeuthen33bae492014-02-25 16:16:18 -0800753 bytes = GetTotalBytesDownloaded(source);
754 total_bytes_by_source[i] = bytes;
755 total_bytes += bytes;
756 total_mbs += bytes / kNumBytesInOneMiB;
757 SetTotalBytesDownloaded(source, 0, true);
758 }
759
760 int download_overhead_percentage = 0;
761 if (successful_bytes > 0) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800762 download_overhead_percentage =
763 (total_bytes - successful_bytes) * 100ULL / successful_bytes;
David Zeuthen33bae492014-02-25 16:16:18 -0800764 }
765
766 int url_switch_count = static_cast<int>(url_switch_count_);
767
768 int reboot_count = GetNumReboots();
769
770 SetNumReboots(0);
771
772 TimeDelta duration = GetUpdateDuration();
Sen Jiang8712e962018-05-08 12:12:28 -0700773 TimeDelta duration_uptime = GetUpdateDurationUptime();
David Zeuthen33bae492014-02-25 16:16:18 -0800774
775 prefs_->Delete(kPrefsUpdateTimestampStart);
776 prefs_->Delete(kPrefsUpdateDurationUptime);
777
778 PayloadType payload_type = CalculatePayloadType();
779
Sen Jiang0affc2c2017-02-10 15:55:05 -0800780 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800781
782 int attempt_count = GetPayloadAttemptNumber();
783
784 int updates_abandoned_count = num_responses_seen_ - 1;
785
Amin Hassani538bd592020-11-04 20:46:08 -0800786 SystemState::Get()->metrics_reporter()->ReportSuccessfulUpdateMetrics(
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700787 attempt_count,
788 updates_abandoned_count,
789 payload_type,
790 payload_size,
791 total_bytes_by_source,
792 download_overhead_percentage,
793 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700794 duration_uptime,
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700795 reboot_count,
796 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700797}
798
799void PayloadState::UpdateNumReboots() {
800 // We only update the reboot count when the system has been detected to have
801 // been rebooted.
Amin Hassani538bd592020-11-04 20:46:08 -0800802 if (!SystemState::Get()->system_rebooted()) {
Chris Sosabe45bef2013-04-09 18:25:12 -0700803 return;
804 }
805
806 SetNumReboots(GetNumReboots() + 1);
807}
808
809void PayloadState::SetNumReboots(uint32_t num_reboots) {
Chris Sosabe45bef2013-04-09 18:25:12 -0700810 num_reboots_ = num_reboots;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700811 metrics_utils::SetNumReboots(num_reboots, prefs_);
Chris Sosabe45bef2013-04-09 18:25:12 -0700812}
813
Jay Srinivasan08262882012-12-28 19:29:43 -0800814void PayloadState::ResetPersistedState() {
815 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700816 SetFullPayloadAttemptNumber(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700817 SetPayloadIndex(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800818 SetUrlIndex(0);
819 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700820 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700821 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
Amin Hassani538bd592020-11-04 20:46:08 -0800822 SetUpdateTimestampStart(SystemState::Get()->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700823 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700824 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700825 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700826 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700827 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700828 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700829 SetScatteringWaitPeriod(TimeDelta());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700830 SetStagingWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700831}
832
833void PayloadState::ResetRollbackVersion() {
834 CHECK(powerwash_safe_prefs_);
835 rollback_version_ = "";
836 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700837}
838
839void PayloadState::ResetDownloadSourcesOnNewUpdate() {
840 for (int i = 0; i < kNumDownloadSources; i++) {
841 DownloadSource source = static_cast<DownloadSource>(i);
842 SetCurrentBytesDownloaded(source, 0, true);
843 // Note: Not resetting the TotalBytesDownloaded as we want that metric
844 // to count the bytes downloaded across various update attempts until
845 // we have successfully applied the update.
846 }
847}
848
Jay Srinivasan08262882012-12-28 19:29:43 -0800849string PayloadState::CalculateResponseSignature() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800850 string response_sign;
851 for (size_t i = 0; i < response_.packages.size(); i++) {
852 const auto& package = response_.packages[i];
853 response_sign += base::StringPrintf(
854 "Payload %zu:\n"
855 " Size = %ju\n"
856 " Sha256 Hash = %s\n"
857 " Metadata Size = %ju\n"
858 " Metadata Signature = %s\n"
Sen Jiangcdd52062017-05-18 15:33:10 -0700859 " Is Delta = %d\n"
Sen Jiang0affc2c2017-02-10 15:55:05 -0800860 " NumURLs = %zu\n",
861 i,
862 static_cast<uintmax_t>(package.size),
863 package.hash.c_str(),
864 static_cast<uintmax_t>(package.metadata_size),
865 package.metadata_signature.c_str(),
Sen Jiangcdd52062017-05-18 15:33:10 -0700866 package.is_delta,
Sen Jiang0affc2c2017-02-10 15:55:05 -0800867 candidate_urls_[i].size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800868
Sen Jiang0affc2c2017-02-10 15:55:05 -0800869 for (size_t j = 0; j < candidate_urls_[i].size(); j++)
870 response_sign += base::StringPrintf(
871 " Candidate Url%zu = %s\n", j, candidate_urls_[i][j].c_str());
872 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800873
Alex Vakulenko75039d72014-03-25 12:36:28 -0700874 response_sign += base::StringPrintf(
Alex Vakulenko75039d72014-03-25 12:36:28 -0700875 "Max Failure Count Per Url = %d\n"
876 "Disable Payload Backoff = %d\n",
Alex Vakulenko75039d72014-03-25 12:36:28 -0700877 response_.max_failure_count_per_url,
878 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800879 return response_sign;
880}
881
882void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800883 CHECK(prefs_);
884 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800885 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
886 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
887 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800888 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800889}
890
Jay Srinivasan19409b72013-04-12 19:23:36 -0700891void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800892 CHECK(prefs_);
893 response_signature_ = response_signature;
894 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
895 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
896}
897
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800898void PayloadState::LoadPayloadAttemptNumber() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700899 SetPayloadAttemptNumber(
900 GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800901}
902
Alex Deymo820cc702013-06-28 15:43:46 -0700903void PayloadState::LoadFullPayloadAttemptNumber() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700904 SetFullPayloadAttemptNumber(
905 GetPersistedValue(kPrefsFullPayloadAttemptNumber, prefs_));
Alex Deymo820cc702013-06-28 15:43:46 -0700906}
907
908void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800909 payload_attempt_number_ = payload_attempt_number;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700910 metrics_utils::SetPayloadAttemptNumber(payload_attempt_number, prefs_);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800911}
912
Alex Deymo820cc702013-06-28 15:43:46 -0700913void PayloadState::SetFullPayloadAttemptNumber(
914 int full_payload_attempt_number) {
915 CHECK(prefs_);
916 full_payload_attempt_number_ = full_payload_attempt_number;
917 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
918 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800919 full_payload_attempt_number_);
Alex Deymo820cc702013-06-28 15:43:46 -0700920}
921
Sen Jiang5ae865b2017-04-18 14:24:40 -0700922void PayloadState::SetPayloadIndex(size_t payload_index) {
923 CHECK(prefs_);
924 payload_index_ = payload_index;
925 LOG(INFO) << "Payload Index = " << payload_index_;
926 prefs_->SetInt64(kPrefsUpdateStatePayloadIndex, payload_index_);
927}
928
929bool PayloadState::NextPayload() {
Jae Hoon Kim76583912020-06-23 10:24:03 -0700930 if (payload_index_ >= candidate_urls_.size())
931 return false;
932 SetPayloadIndex(payload_index_ + 1);
933 if (payload_index_ >= candidate_urls_.size())
Sen Jiang5ae865b2017-04-18 14:24:40 -0700934 return false;
Jae Hoon Kima3210e62020-05-07 11:32:44 -0700935 SetUrlIndex(0);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700936 return true;
937}
938
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800939void PayloadState::LoadUrlIndex() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700940 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex, prefs_));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800941}
942
943void PayloadState::SetUrlIndex(uint32_t url_index) {
944 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800945 url_index_ = url_index;
946 LOG(INFO) << "Current URL Index = " << url_index_;
947 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700948
949 // Also update the download source, which is purely dependent on the
950 // current URL index alone.
951 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800952}
953
Gilad Arnold519cfc72014-10-02 10:34:54 -0700954void PayloadState::LoadScatteringWaitPeriod() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700955 SetScatteringWaitPeriod(TimeDelta::FromSeconds(
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700956 GetPersistedValue(kPrefsWallClockScatteringWaitPeriod, prefs_)));
Gilad Arnold519cfc72014-10-02 10:34:54 -0700957}
958
Alex Deymof329b932014-10-30 01:37:48 -0700959void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700960 CHECK(prefs_);
961 scattering_wait_period_ = wait_period;
962 LOG(INFO) << "Scattering Wait Period (seconds) = "
963 << scattering_wait_period_.InSeconds();
964 if (scattering_wait_period_.InSeconds() > 0) {
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700965 prefs_->SetInt64(kPrefsWallClockScatteringWaitPeriod,
Gilad Arnold519cfc72014-10-02 10:34:54 -0700966 scattering_wait_period_.InSeconds());
967 } else {
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700968 prefs_->Delete(kPrefsWallClockScatteringWaitPeriod);
969 }
970}
971
972void PayloadState::LoadStagingWaitPeriod() {
973 SetStagingWaitPeriod(TimeDelta::FromSeconds(
974 GetPersistedValue(kPrefsWallClockStagingWaitPeriod, prefs_)));
975}
976
977void PayloadState::SetStagingWaitPeriod(TimeDelta wait_period) {
978 CHECK(prefs_);
979 staging_wait_period_ = wait_period;
980 LOG(INFO) << "Staging Wait Period (days) =" << staging_wait_period_.InDays();
981 if (staging_wait_period_.InSeconds() > 0) {
982 prefs_->SetInt64(kPrefsWallClockStagingWaitPeriod,
983 staging_wait_period_.InSeconds());
984 } else {
985 prefs_->Delete(kPrefsWallClockStagingWaitPeriod);
Gilad Arnold519cfc72014-10-02 10:34:54 -0700986 }
987}
988
David Zeuthencc6f9962013-04-18 11:57:24 -0700989void PayloadState::LoadUrlSwitchCount() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700990 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount, prefs_));
David Zeuthencc6f9962013-04-18 11:57:24 -0700991}
992
993void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
994 CHECK(prefs_);
995 url_switch_count_ = url_switch_count;
996 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
997 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
998}
999
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001000void PayloadState::LoadUrlFailureCount() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001001 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount, prefs_));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001002}
1003
1004void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
1005 CHECK(prefs_);
1006 url_failure_count_ = url_failure_count;
1007 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
1008 << ")'s Failure Count = " << url_failure_count_;
1009 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001010}
1011
Jay Srinivasan08262882012-12-28 19:29:43 -08001012void PayloadState::LoadBackoffExpiryTime() {
1013 CHECK(prefs_);
1014 int64_t stored_value;
1015 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
1016 return;
1017
1018 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
1019 return;
1020
1021 Time stored_time = Time::FromInternalValue(stored_value);
1022 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
1023 LOG(ERROR) << "Invalid backoff expiry time ("
1024 << utils::ToString(stored_time)
1025 << ") in persisted state. Resetting.";
1026 stored_time = Time();
1027 }
1028 SetBackoffExpiryTime(stored_time);
1029}
1030
1031void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
1032 CHECK(prefs_);
1033 backoff_expiry_time_ = new_time;
1034 LOG(INFO) << "Backoff Expiry Time = "
1035 << utils::ToString(backoff_expiry_time_);
1036 prefs_->SetInt64(kPrefsBackoffExpiryTime,
1037 backoff_expiry_time_.ToInternalValue());
1038}
1039
David Zeuthen9a017f22013-04-11 16:10:26 -07001040TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001041 Time end_time = update_timestamp_end_.is_null()
Amin Hassani538bd592020-11-04 20:46:08 -08001042 ? SystemState::Get()->clock()->GetWallclockTime()
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001043 : update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001044 return end_time - update_timestamp_start_;
1045}
1046
1047void PayloadState::LoadUpdateTimestampStart() {
1048 int64_t stored_value;
1049 Time stored_time;
1050
1051 CHECK(prefs_);
1052
Amin Hassani538bd592020-11-04 20:46:08 -08001053 Time now = SystemState::Get()->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001054
1055 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1056 // The preference missing is not unexpected - in that case, just
1057 // use the current time as start time
1058 stored_time = now;
1059 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1060 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1061 stored_time = now;
1062 } else {
1063 stored_time = Time::FromInternalValue(stored_value);
1064 }
1065
Tianjiee283ce42020-07-29 11:37:51 -07001066 // Validation check: If the time read from disk is in the future
David Zeuthen9a017f22013-04-11 16:10:26 -07001067 // (modulo some slack to account for possible NTP drift
1068 // adjustments), something is fishy and we should report and
1069 // reset.
1070 TimeDelta duration_according_to_stored_time = now - stored_time;
1071 if (duration_according_to_stored_time < -kDurationSlack) {
1072 LOG(ERROR) << "The UpdateTimestampStart value ("
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001073 << utils::ToString(stored_time) << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001074 << utils::FormatTimeDelta(duration_according_to_stored_time)
1075 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001076 stored_time = now;
1077 }
1078
1079 SetUpdateTimestampStart(stored_time);
1080}
1081
1082void PayloadState::SetUpdateTimestampStart(const Time& value) {
David Zeuthen9a017f22013-04-11 16:10:26 -07001083 update_timestamp_start_ = value;
Tianjie Xu90aaa102017-10-10 17:39:03 -07001084 metrics_utils::SetUpdateTimestampStart(value, prefs_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001085}
1086
1087void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1088 update_timestamp_end_ = value;
1089 LOG(INFO) << "Update Timestamp End = "
1090 << utils::ToString(update_timestamp_end_);
1091}
1092
1093TimeDelta PayloadState::GetUpdateDurationUptime() {
1094 return update_duration_uptime_;
1095}
1096
1097void PayloadState::LoadUpdateDurationUptime() {
1098 int64_t stored_value;
1099 TimeDelta stored_delta;
1100
1101 CHECK(prefs_);
1102
1103 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1104 // The preference missing is not unexpected - in that case, just
1105 // we'll use zero as the delta
1106 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1107 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1108 stored_delta = TimeDelta::FromSeconds(0);
1109 } else {
1110 stored_delta = TimeDelta::FromInternalValue(stored_value);
1111 }
1112
Tianjiee283ce42020-07-29 11:37:51 -07001113 // Validation check: Uptime can never be greater than the wall-clock
David Zeuthen9a017f22013-04-11 16:10:26 -07001114 // difference (modulo some slack). If it is, report and reset
1115 // to the wall-clock difference.
1116 TimeDelta diff = GetUpdateDuration() - stored_delta;
1117 if (diff < -kDurationSlack) {
1118 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001119 << utils::FormatTimeDelta(stored_delta)
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001120 << ") in persisted state is " << utils::FormatTimeDelta(diff)
David Zeuthen674c3182013-04-18 14:05:20 -07001121 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001122 stored_delta = update_duration_current_;
1123 }
1124
1125 SetUpdateDurationUptime(stored_delta);
1126}
1127
Chris Sosabe45bef2013-04-09 18:25:12 -07001128void PayloadState::LoadNumReboots() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001129 SetNumReboots(GetPersistedValue(kPrefsNumReboots, prefs_));
Chris Sosaaa18e162013-06-20 13:20:30 -07001130}
1131
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001132void PayloadState::LoadRollbackHappened() {
1133 CHECK(powerwash_safe_prefs_);
1134 bool rollback_happened = false;
1135 powerwash_safe_prefs_->GetBoolean(kPrefsRollbackHappened, &rollback_happened);
1136 SetRollbackHappened(rollback_happened);
1137}
1138
1139void PayloadState::SetRollbackHappened(bool rollback_happened) {
1140 CHECK(powerwash_safe_prefs_);
1141 LOG(INFO) << "Setting rollback-happened to " << rollback_happened << ".";
1142 rollback_happened_ = rollback_happened;
1143 if (rollback_happened) {
1144 powerwash_safe_prefs_->SetBoolean(kPrefsRollbackHappened,
1145 rollback_happened);
1146 } else {
1147 powerwash_safe_prefs_->Delete(kPrefsRollbackHappened);
1148 }
1149}
1150
Chris Sosaaa18e162013-06-20 13:20:30 -07001151void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001152 CHECK(powerwash_safe_prefs_);
1153 string rollback_version;
1154 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1155 &rollback_version)) {
1156 SetRollbackVersion(rollback_version);
1157 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001158}
1159
1160void PayloadState::SetRollbackVersion(const string& rollback_version) {
1161 CHECK(powerwash_safe_prefs_);
Andrewcc6ab9f2020-06-25 07:41:40 -07001162 LOG(INFO) << "Excluding version " << rollback_version;
Chris Sosaaa18e162013-06-20 13:20:30 -07001163 rollback_version_ = rollback_version;
1164 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001165}
1166
David Zeuthen9a017f22013-04-11 16:10:26 -07001167void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1168 const Time& timestamp,
1169 bool use_logging) {
1170 CHECK(prefs_);
1171 update_duration_uptime_ = value;
1172 update_duration_uptime_timestamp_ = timestamp;
1173 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1174 update_duration_uptime_.ToInternalValue());
1175 if (use_logging) {
1176 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001177 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001178 }
1179}
1180
1181void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
Amin Hassani538bd592020-11-04 20:46:08 -08001182 Time now = SystemState::Get()->clock()->GetMonotonicTime();
David Zeuthenf413fe52013-04-22 14:04:39 -07001183 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001184}
1185
1186void PayloadState::CalculateUpdateDurationUptime() {
Amin Hassani538bd592020-11-04 20:46:08 -08001187 Time now = SystemState::Get()->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001188 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
Colin Howes0e452c92018-11-02 13:18:44 -07001189
1190 if (uptime_since_last_update > TimeDelta::FromSeconds(kUptimeResolution)) {
1191 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1192 // We're frequently called so avoid logging this write
1193 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1194 }
David Zeuthen9a017f22013-04-11 16:10:26 -07001195}
1196
Jay Srinivasan19409b72013-04-12 19:23:36 -07001197string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1198 return prefix + "-from-" + utils::ToString(source);
1199}
1200
1201void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1202 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001203 SetCurrentBytesDownloaded(source, GetPersistedValue(key, prefs_), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001204}
1205
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001206void PayloadState::SetCurrentBytesDownloaded(DownloadSource source,
1207 uint64_t current_bytes_downloaded,
1208 bool log) {
Jay Srinivasan19409b72013-04-12 19:23:36 -07001209 CHECK(prefs_);
1210
1211 if (source >= kNumDownloadSources)
1212 return;
1213
1214 // Update the in-memory value.
1215 current_bytes_downloaded_[source] = current_bytes_downloaded;
1216
1217 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1218 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1219 LOG_IF(INFO, log) << "Current bytes downloaded for "
1220 << utils::ToString(source) << " = "
1221 << GetCurrentBytesDownloaded(source);
1222}
1223
1224void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1225 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001226 SetTotalBytesDownloaded(source, GetPersistedValue(key, prefs_), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001227}
1228
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001229void PayloadState::SetTotalBytesDownloaded(DownloadSource source,
1230 uint64_t total_bytes_downloaded,
1231 bool log) {
Jay Srinivasan19409b72013-04-12 19:23:36 -07001232 CHECK(prefs_);
1233
1234 if (source >= kNumDownloadSources)
1235 return;
1236
1237 // Update the in-memory value.
1238 total_bytes_downloaded_[source] = total_bytes_downloaded;
1239
1240 // Persist.
1241 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1242 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001243 LOG_IF(INFO, log) << "Total bytes downloaded for " << utils::ToString(source)
1244 << " = " << GetTotalBytesDownloaded(source);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001245}
1246
David Zeuthena573d6f2013-06-14 16:13:36 -07001247void PayloadState::LoadNumResponsesSeen() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001248 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen, prefs_));
David Zeuthena573d6f2013-06-14 16:13:36 -07001249}
1250
1251void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1252 CHECK(prefs_);
1253 num_responses_seen_ = num_responses_seen;
1254 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1255 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1256}
1257
Jay Srinivasan53173b92013-05-17 17:13:01 -07001258void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001259 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001260
Amin Hassani538bd592020-11-04 20:46:08 -08001261 if (SystemState::Get()->hardware()->IsOfficialBuild()) {
1262 const policy::DevicePolicy* policy = SystemState::Get()->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001263 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001264 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1265 } else {
1266 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1267 http_url_ok = true;
1268 }
1269
1270 candidate_urls_.clear();
Sen Jiang0affc2c2017-02-10 15:55:05 -08001271 for (const auto& package : response_.packages) {
1272 candidate_urls_.emplace_back();
1273 for (const string& candidate_url : package.payload_urls) {
1274 if (base::StartsWith(
1275 candidate_url, "http://", base::CompareCase::INSENSITIVE_ASCII) &&
1276 !http_url_ok) {
1277 continue;
1278 }
1279 candidate_urls_.back().push_back(candidate_url);
1280 LOG(INFO) << "Candidate Url" << (candidate_urls_.back().size() - 1)
1281 << ": " << candidate_url;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001282 }
Sen Jiang0affc2c2017-02-10 15:55:05 -08001283 LOG(INFO) << "Found " << candidate_urls_.back().size() << " candidate URLs "
1284 << "out of " << package.payload_urls.size()
1285 << " URLs supplied in package " << candidate_urls_.size() - 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001286 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001287}
1288
David Zeuthene4c58bf2013-06-18 17:26:50 -07001289void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001290 // Flush previous state from abnormal attempt failure, if any.
1291 ReportAndClearPersistedAttemptMetrics();
1292
Alex Deymo569c4242013-07-24 12:01:01 -07001293 // Avoid the UpdateEngineStarted actions if this is not the first time we
1294 // run the update engine since reboot.
Amin Hassani538bd592020-11-04 20:46:08 -08001295 if (!SystemState::Get()->system_rebooted())
Alex Deymo569c4242013-07-24 12:01:01 -07001296 return;
1297
Tianjie Xu90aaa102017-10-10 17:39:03 -07001298 // Report time_to_reboot if we booted into a new update.
1299 metrics_utils::LoadAndReportTimeToReboot(
Amin Hassani538bd592020-11-04 20:46:08 -08001300 SystemState::Get()->metrics_reporter(),
1301 prefs_,
1302 SystemState::Get()->clock());
Tianjie Xu90aaa102017-10-10 17:39:03 -07001303 prefs_->Delete(kPrefsSystemUpdatedMarker);
1304
Alex Deymo42432912013-07-12 20:21:15 -07001305 // Check if it is needed to send metrics about a failed reboot into a new
1306 // version.
1307 ReportFailedBootIfNeeded();
1308}
1309
1310void PayloadState::ReportFailedBootIfNeeded() {
1311 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1312 // payload was marked as ready immediately before the last reboot, and we
1313 // need to check if such payload successfully rebooted or not.
1314 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001315 int64_t installed_from = 0;
1316 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001317 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1318 return;
1319 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001320 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1321 // partition number. We are now using slot numbers (0 or 1) instead, so
1322 // the following comparison will not match if we are comparing an old
1323 // partition number against a new slot number, which is the correct outcome
1324 // since we successfully booted the new update in that case. If the boot
1325 // failed, we will read this value from the same version, so it will always
1326 // be compatible.
Amin Hassani538bd592020-11-04 20:46:08 -08001327 if (installed_from ==
1328 SystemState::Get()->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001329 // A reboot was pending, but the chromebook is again in the same
1330 // BootDevice where the update was installed from.
1331 int64_t target_attempt;
1332 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1333 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1334 "TargetVersionInstalledFrom was present.";
1335 target_attempt = 1;
1336 }
1337
1338 // Report the UMA metric of the current boot failure.
Amin Hassani538bd592020-11-04 20:46:08 -08001339 SystemState::Get()->metrics_reporter()->ReportFailedUpdateCount(
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001340 target_attempt);
Alex Deymo42432912013-07-12 20:21:15 -07001341 } else {
1342 prefs_->Delete(kPrefsTargetVersionAttempt);
1343 prefs_->Delete(kPrefsTargetVersionUniqueId);
1344 }
1345 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1346 }
1347}
1348
1349void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1350 // Expect to boot into the new partition in the next reboot setting the
1351 // TargetVersion* flags in the Prefs.
1352 string stored_target_version_uid;
1353 string target_version_id;
1354 string target_partition;
1355 int64_t target_attempt;
1356
1357 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1358 prefs_->GetString(kPrefsTargetVersionUniqueId,
1359 &stored_target_version_uid) &&
1360 stored_target_version_uid == target_version_uid) {
1361 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1362 target_attempt = 0;
1363 } else {
1364 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1365 target_attempt = 0;
1366 }
1367 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1368
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001369 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Amin Hassani538bd592020-11-04 20:46:08 -08001370 SystemState::Get()->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001371}
1372
1373void PayloadState::ResetUpdateStatus() {
1374 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1375 // rebooted the next boot is not flagged as failed to rebooted into the
1376 // new applied payload.
1377 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1378
1379 // Also decrement the attempt number if it exists.
1380 int64_t target_attempt;
1381 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001382 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001383}
1384
David Zeuthendcba8092013-08-06 12:16:35 -07001385int PayloadState::GetP2PNumAttempts() {
1386 return p2p_num_attempts_;
1387}
1388
1389void PayloadState::SetP2PNumAttempts(int value) {
1390 p2p_num_attempts_ = value;
1391 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1392 CHECK(prefs_);
1393 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1394}
1395
1396void PayloadState::LoadP2PNumAttempts() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001397 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts, prefs_));
David Zeuthendcba8092013-08-06 12:16:35 -07001398}
1399
1400Time PayloadState::GetP2PFirstAttemptTimestamp() {
1401 return p2p_first_attempt_timestamp_;
1402}
1403
1404void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1405 p2p_first_attempt_timestamp_ = time;
1406 LOG(INFO) << "p2p First Attempt Timestamp = "
1407 << utils::ToString(p2p_first_attempt_timestamp_);
1408 CHECK(prefs_);
1409 int64_t stored_value = time.ToInternalValue();
1410 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1411}
1412
1413void PayloadState::LoadP2PFirstAttemptTimestamp() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001414 int64_t stored_value =
1415 GetPersistedValue(kPrefsP2PFirstAttemptTimestamp, prefs_);
David Zeuthendcba8092013-08-06 12:16:35 -07001416 Time stored_time = Time::FromInternalValue(stored_value);
1417 SetP2PFirstAttemptTimestamp(stored_time);
1418}
1419
1420void PayloadState::P2PNewAttempt() {
1421 CHECK(prefs_);
1422 // Set timestamp, if it hasn't been set already
1423 if (p2p_first_attempt_timestamp_.is_null()) {
Amin Hassani538bd592020-11-04 20:46:08 -08001424 SetP2PFirstAttemptTimestamp(
1425 SystemState::Get()->clock()->GetWallclockTime());
David Zeuthendcba8092013-08-06 12:16:35 -07001426 }
1427 // Increase number of attempts
1428 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1429}
1430
1431bool PayloadState::P2PAttemptAllowed() {
1432 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1433 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001434 << " which is greater than " << kMaxP2PAttempts
David Zeuthendcba8092013-08-06 12:16:35 -07001435 << " - disallowing p2p.";
1436 return false;
1437 }
1438
1439 if (!p2p_first_attempt_timestamp_.is_null()) {
Amin Hassani538bd592020-11-04 20:46:08 -08001440 Time now = SystemState::Get()->clock()->GetWallclockTime();
David Zeuthendcba8092013-08-06 12:16:35 -07001441 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1442 if (time_spent_attempting_p2p.InSeconds() < 0) {
1443 LOG(ERROR) << "Time spent attempting p2p is negative"
1444 << " - disallowing p2p.";
1445 return false;
1446 }
1447 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1448 LOG(INFO) << "Time spent attempting p2p is "
1449 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1450 << " which is greater than "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001451 << utils::FormatTimeDelta(
1452 TimeDelta::FromSeconds(kMaxP2PAttemptTimeSeconds))
David Zeuthendcba8092013-08-06 12:16:35 -07001453 << " - disallowing p2p.";
1454 return false;
1455 }
1456 }
1457
1458 return true;
1459}
1460
Sen Jiang0affc2c2017-02-10 15:55:05 -08001461int64_t PayloadState::GetPayloadSize() {
1462 int64_t payload_size = 0;
1463 for (const auto& package : response_.packages)
1464 payload_size += package.size;
1465 return payload_size;
1466}
1467
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001468} // namespace chromeos_update_engine