blob: f227026ed76c6e282e56c7b72dee925590f314e8 [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
17#include "update_engine/payload_state.h"
18
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"
32#include "update_engine/common/prefs.h"
33#include "update_engine/common/utils.h"
Sen Jiang255e22b2016-05-20 16:15:29 -070034#include "update_engine/connection_manager_interface.h"
Tianjie Xu282aa1f2017-09-05 13:42:45 -070035#include "update_engine/metrics_reporter_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080036#include "update_engine/metrics_utils.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070037#include "update_engine/omaha_request_params.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080038#include "update_engine/payload_consumer/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070039#include "update_engine/system_state.h"
Jae Hoon Kim5e8e30b2020-05-06 14:59:06 -070040#include "update_engine/update_attempter.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
81bool PayloadState::Initialize(SystemState* system_state) {
82 system_state_ = system_state;
83 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070084 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jae Hoon Kim5e8e30b2020-05-06 14:59:06 -070085 excluder_ = system_state_->update_attempter()->GetExcluder();
Jay Srinivasan08262882012-12-28 19:29:43 -080086 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080087 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070088 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080089 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080090 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070091 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080092 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070093 LoadUpdateTimestampStart();
94 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
95 // being called before it. Don't reorder.
96 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070097 for (int i = 0; i < kNumDownloadSources; i++) {
98 DownloadSource source = static_cast<DownloadSource>(i);
99 LoadCurrentBytesDownloaded(source);
100 LoadTotalBytesDownloaded(source);
101 }
Chris Sosabe45bef2013-04-09 18:25:12 -0700102 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -0700103 LoadNumResponsesSeen();
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200104 LoadRollbackHappened();
Chris Sosaaa18e162013-06-20 13:20:30 -0700105 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700106 LoadP2PFirstAttemptTimestamp();
107 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800108 return true;
109}
110
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800111void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800112 // Always store the latest response.
113 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800114
Jay Srinivasan53173b92013-05-17 17:13:01 -0700115 // Compute the candidate URLs first as they are used to calculate the
116 // response signature so that a change in enterprise policy for
117 // HTTP downloads being enabled or not could be honored as soon as the
118 // next update check happens.
119 ComputeCandidateUrls();
120
Jay Srinivasan08262882012-12-28 19:29:43 -0800121 // Check if the "signature" of this response (i.e. the fields we care about)
122 // has changed.
123 string new_response_signature = CalculateResponseSignature();
124 bool has_response_changed = (response_signature_ != new_response_signature);
125
126 // If the response has changed, we should persist the new signature and
127 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800128 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800129 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700130 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800131 SetResponseSignature(new_response_signature);
132 ResetPersistedState();
133 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800134 }
135
Sen Jiang97eba342017-05-22 14:34:11 -0700136 // Always start from payload index 0, even for resume, to download partition
137 // info from previous payloads.
138 payload_index_ = 0;
139
Jay Srinivasan08262882012-12-28 19:29:43 -0800140 // This is the earliest point at which we can validate whether the URL index
141 // we loaded from the persisted state is a valid value. If the response
142 // hasn't changed but the URL index is invalid, it's indicative of some
143 // tampering of the persisted state.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800144 if (payload_index_ >= candidate_urls_.size() ||
145 url_index_ >= candidate_urls_[payload_index_].size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800146 LOG(INFO) << "Resetting all payload state as the url index seems to have "
147 "been tampered with";
148 ResetPersistedState();
149 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800150 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700151
152 // Update the current download source which depends on the latest value of
153 // the response.
154 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800155}
156
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700157void PayloadState::SetUsingP2PForDownloading(bool value) {
158 using_p2p_for_downloading_ = value;
159 // Update the current download source which depends on whether we are
160 // using p2p or not.
161 UpdateCurrentDownloadSource();
162}
163
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800164void PayloadState::DownloadComplete() {
165 LOG(INFO) << "Payload downloaded successfully";
166 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700167 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800168}
169
170void PayloadState::DownloadProgress(size_t count) {
171 if (count == 0)
172 return;
173
David Zeuthen9a017f22013-04-11 16:10:26 -0700174 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700175 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700176
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800177 // We've received non-zero bytes from a recent download operation. Since our
178 // URL failure count is meant to penalize a URL only for consecutive
179 // failures, downloading bytes successfully means we should reset the failure
180 // count (as we know at least that the URL is working). In future, we can
181 // design this to be more sophisticated to check for more intelligent failure
182 // patterns, but right now, even 1 byte downloaded will mark the URL to be
183 // good unless it hits 10 (or configured number of) consecutive failures
184 // again.
185
186 if (GetUrlFailureCount() == 0)
187 return;
188
189 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
190 << " to 0 as we received " << count << " bytes successfully";
191 SetUrlFailureCount(0);
192}
193
David Zeuthenafed4a12014-04-09 15:28:44 -0700194void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700195 // Flush previous state from abnormal attempt failure, if any.
196 ReportAndClearPersistedAttemptMetrics();
197
David Zeuthenafed4a12014-04-09 15:28:44 -0700198 attempt_type_ = attempt_type;
199
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800200 ClockInterface* clock = system_state_->clock();
David Zeuthen33bae492014-02-25 16:16:18 -0800201 attempt_start_time_boot_ = clock->GetBootTime();
202 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800203 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700204
205 metrics::ConnectionType type;
Sen Jiang255e22b2016-05-20 16:15:29 -0700206 ConnectionType network_connection_type;
207 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700208 ConnectionManagerInterface* connection_manager =
209 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700210 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700211 &tethering)) {
212 LOG(ERROR) << "Failed to determine connection type.";
213 type = metrics::ConnectionType::kUnknown;
214 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800215 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700216 }
217 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700218
219 if (attempt_type == AttemptType::kUpdate)
220 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800221}
222
Chris Sosabe45bef2013-04-09 18:25:12 -0700223void PayloadState::UpdateResumed() {
224 LOG(INFO) << "Resuming an update that was previously started.";
225 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700226 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700227}
228
Jay Srinivasan19409b72013-04-12 19:23:36 -0700229void PayloadState::UpdateRestarted() {
230 LOG(INFO) << "Starting a new update";
231 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700232 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700233 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700234}
235
David Zeuthen9a017f22013-04-11 16:10:26 -0700236void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700237 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700238 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700239 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800240
David Zeuthen96197df2014-04-16 12:22:39 -0700241 switch (attempt_type_) {
242 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700243 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700244 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700245 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700246 break;
247
248 case AttemptType::kRollback:
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700249 system_state_->metrics_reporter()->ReportRollbackMetrics(
250 metrics::RollbackResult::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700251 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700252 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700253
254 // Reset the number of responses seen since it counts from the last
255 // successful update, e.g. now.
256 SetNumResponsesSeen(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700257 SetPayloadIndex(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700258
Tianjie Xu90aaa102017-10-10 17:39:03 -0700259 metrics_utils::SetSystemUpdatedMarker(system_state_->clock(), prefs_);
David Zeuthen9a017f22013-04-11 16:10:26 -0700260}
261
David Zeuthena99981f2013-04-29 13:42:47 -0700262void PayloadState::UpdateFailed(ErrorCode error) {
263 ErrorCode base_error = utils::GetBaseErrorCode(error);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800264 LOG(INFO) << "Updating payload state for error code: " << base_error << " ("
265 << utils::ErrorCodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800266
Jay Srinivasan53173b92013-05-17 17:13:01 -0700267 if (candidate_urls_.size() == 0) {
268 // This means we got this error even before we got a valid Omaha response
269 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800270 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800271 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
272 return;
273 }
274
David Zeuthen96197df2014-04-16 12:22:39 -0700275 switch (attempt_type_) {
276 case AttemptType::kUpdate:
277 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700278 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700279 break;
280
281 case AttemptType::kRollback:
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700282 system_state_->metrics_reporter()->ReportRollbackMetrics(
283 metrics::RollbackResult::kFailed);
David Zeuthen96197df2014-04-16 12:22:39 -0700284 break;
285 }
David Zeuthen33bae492014-02-25 16:16:18 -0800286
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800287 switch (base_error) {
288 // Errors which are good indicators of a problem with a particular URL or
289 // the protocol used in the URL or entities in the communication channel
290 // (e.g. proxies). We should try the next available URL in the next update
291 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700292 case ErrorCode::kPayloadHashMismatchError:
293 case ErrorCode::kPayloadSizeMismatchError:
294 case ErrorCode::kDownloadPayloadVerificationError:
295 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
296 case ErrorCode::kSignedDeltaPayloadExpectedError:
297 case ErrorCode::kDownloadInvalidMetadataMagicString:
298 case ErrorCode::kDownloadSignatureMissingInManifest:
299 case ErrorCode::kDownloadManifestParseError:
300 case ErrorCode::kDownloadMetadataSignatureError:
301 case ErrorCode::kDownloadMetadataSignatureVerificationError:
302 case ErrorCode::kDownloadMetadataSignatureMismatch:
303 case ErrorCode::kDownloadOperationHashVerificationError:
304 case ErrorCode::kDownloadOperationExecutionError:
305 case ErrorCode::kDownloadOperationHashMismatch:
306 case ErrorCode::kDownloadInvalidMetadataSize:
307 case ErrorCode::kDownloadInvalidMetadataSignature:
308 case ErrorCode::kDownloadOperationHashMissingError:
309 case ErrorCode::kDownloadMetadataSignatureMissingError:
310 case ErrorCode::kPayloadMismatchedType:
311 case ErrorCode::kUnsupportedMajorPayloadVersion:
312 case ErrorCode::kUnsupportedMinorPayloadVersion:
Sen Jiang8e768e92017-06-28 17:13:19 -0700313 case ErrorCode::kPayloadTimestampError:
Sen Jiang57f91802017-11-14 17:42:13 -0800314 case ErrorCode::kVerityCalculationError:
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700315 ExcludeCurrentPayload();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800316 IncrementUrlIndex();
317 break;
318
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800319 // Errors which seem to be just transient network/communication related
320 // failures and do not indicate any inherent problem with the URL itself.
321 // So, we should keep the current URL but just increment the
322 // failure count to give it more chances. This way, while we maximize our
323 // chances of downloading from the URLs that appear earlier in the
324 // response (because download from a local server URL that appears earlier
325 // in a response is preferable than downloading from the next URL which
326 // could be a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700327
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700328 case ErrorCode::kError:
329 case ErrorCode::kDownloadTransferError:
330 case ErrorCode::kDownloadWriteError:
331 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700332 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800333 IncrementFailureCount();
334 break;
335
336 // Errors which are not specific to a URL and hence shouldn't result in
337 // the URL being penalized. This can happen in two cases:
338 // 1. We haven't started downloading anything: These errors don't cost us
339 // anything in terms of actual payload bytes, so we should just do the
340 // regular retries at the next update check.
341 // 2. We have successfully downloaded the payload: In this case, the
342 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800343 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800344 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700345 case ErrorCode::kOmahaRequestError:
346 case ErrorCode::kOmahaResponseHandlerError:
347 case ErrorCode::kPostinstallRunnerError:
348 case ErrorCode::kFilesystemCopierError:
349 case ErrorCode::kInstallDeviceOpenError:
350 case ErrorCode::kKernelDeviceOpenError:
351 case ErrorCode::kDownloadNewPartitionInfoError:
352 case ErrorCode::kNewRootfsVerificationError:
353 case ErrorCode::kNewKernelVerificationError:
354 case ErrorCode::kPostinstallBootedFromFirmwareB:
355 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
356 case ErrorCode::kOmahaRequestEmptyResponseError:
357 case ErrorCode::kOmahaRequestXMLParseError:
358 case ErrorCode::kOmahaResponseInvalid:
359 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
360 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700361 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700362 case ErrorCode::kOmahaUpdateDeferredForBackoff:
363 case ErrorCode::kPostinstallPowerwashError:
364 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400365 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700366 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800367 case ErrorCode::kUserCanceled:
Weidong Guo421ff332017-04-17 10:08:38 -0700368 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
Sen Jiangfe522822017-10-31 15:14:11 -0700369 case ErrorCode::kUpdatedButNotActive:
Sen Jiang89e24c12018-03-22 18:05:44 -0700370 case ErrorCode::kNoUpdate:
Marton Hunyady199152d2018-05-07 19:08:48 +0200371 case ErrorCode::kRollbackNotPossible:
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700372 case ErrorCode::kFirstActiveOmahaPingSentPersistenceError:
Amin Hassanid3d84212019-08-17 00:27:44 -0700373 case ErrorCode::kInternalLibCurlError:
374 case ErrorCode::kUnresolvedHostError:
375 case ErrorCode::kUnresolvedHostRecovered:
Jae Hoon Kim3e69b4c2020-06-16 09:23:39 -0700376 case ErrorCode::kPackageExcludedFromUpdate:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800377 LOG(INFO) << "Not incrementing URL index or failure count for this error";
378 break;
379
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800380 case ErrorCode::kSuccess: // success code
381 case ErrorCode::kUmaReportedMax: // not an error code
382 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
383 case ErrorCode::kDevModeFlag: // not an error code
384 case ErrorCode::kResumedFlag: // not an error code
385 case ErrorCode::kTestImageFlag: // not an error code
386 case ErrorCode::kTestOmahaUrlFlag: // not an error code
387 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800388 // These shouldn't happen. Enumerating these explicitly here so that we
389 // can let the compiler warn about new error codes that are added to
390 // action_processor.h but not added here.
391 LOG(WARNING) << "Unexpected error code for UpdateFailed";
392 break;
393
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800394 // Note: Not adding a default here so as to let the compiler warn us of
395 // any new enums that were added in the .h but not listed in this switch.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800396 }
397}
398
Jay Srinivasan08262882012-12-28 19:29:43 -0800399bool PayloadState::ShouldBackoffDownload() {
400 if (response_.disable_payload_backoff) {
401 LOG(INFO) << "Payload backoff logic is disabled. "
402 "Can proceed with the download";
403 return false;
404 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700405 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700406 LOG(INFO) << "Payload backoff logic is disabled because download "
407 << "will happen from local peer (via p2p).";
408 return false;
409 }
410 if (system_state_->request_params()->interactive()) {
411 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
412 return false;
413 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700414 for (const auto& package : response_.packages) {
415 if (package.is_delta) {
416 // If delta payloads fail, we want to fallback quickly to full payloads as
417 // they are more likely to succeed. Exponential backoffs would greatly
418 // slow down the fallback to full payloads. So we don't backoff for delta
419 // payloads.
420 LOG(INFO) << "No backoffs for delta payloads. "
421 << "Can proceed with the download";
422 return false;
423 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800424 }
425
Amin Hassaniffb6d802018-03-30 11:43:57 -0700426 if (!system_state_->hardware()->IsOfficialBuild() &&
427 !prefs_->Exists(kPrefsNoIgnoreBackoff)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800428 // Backoffs are needed only for official builds. We do not want any delays
Amin Hassaniffb6d802018-03-30 11:43:57 -0700429 // or update failures due to backoffs during testing or development. Unless
430 // the |kPrefsNoIgnoreBackoff| is manually set.
Jay Srinivasan08262882012-12-28 19:29:43 -0800431 LOG(INFO) << "No backoffs for test/dev images. "
432 << "Can proceed with the download";
433 return false;
434 }
435
436 if (backoff_expiry_time_.is_null()) {
437 LOG(INFO) << "No backoff expiry time has been set. "
438 << "Can proceed with the download";
439 return false;
440 }
441
442 if (backoff_expiry_time_ < Time::Now()) {
443 LOG(INFO) << "The backoff expiry time ("
444 << utils::ToString(backoff_expiry_time_)
445 << ") has elapsed. Can proceed with the download";
446 return false;
447 }
448
449 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
450 << utils::ToString(backoff_expiry_time_);
451 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800452}
453
Chris Sosaaa18e162013-06-20 13:20:30 -0700454void PayloadState::Rollback() {
455 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700456 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700457}
458
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800459void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700460 // Update the payload attempt number for both payload types: full and delta.
461 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
462}
463
464void PayloadState::IncrementFullPayloadAttemptNumber() {
Jae Hoon Kim76583912020-06-23 10:24:03 -0700465 DCHECK(payload_index_ < response_.packages.size());
Alex Deymo820cc702013-06-28 15:43:46 -0700466 // Update the payload attempt number for full payloads and the backoff time.
Sen Jiangcdd52062017-05-18 15:33:10 -0700467 if (response_.packages[payload_index_].is_delta) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800468 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
469 return;
470 }
471
Alex Deymo29b51d92013-07-09 15:26:24 -0700472 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700473 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800474 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800475}
476
477void PayloadState::IncrementUrlIndex() {
Jae Hoon Kim76583912020-06-23 10:24:03 -0700478 DCHECK(payload_index_ < candidate_urls_.size());
Sen Jiang0affc2c2017-02-10 15:55:05 -0800479 size_t next_url_index = url_index_ + 1;
Jae Hoon Kima3210e62020-05-07 11:32:44 -0700480 size_t max_url_size = candidate_urls_[payload_index_].size();
Sen Jiang0affc2c2017-02-10 15:55:05 -0800481 if (next_url_index < max_url_size) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800482 LOG(INFO) << "Incrementing the URL index for next attempt";
483 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800484 } else {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800485 LOG(INFO) << "Resetting the current URL index (" << url_index_ << ") to "
486 << "0 as we only have " << max_url_size << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800487 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700488 IncrementPayloadAttemptNumber();
489 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800490 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800491
David Zeuthencc6f9962013-04-18 11:57:24 -0700492 // If we have multiple URLs, record that we just switched to another one
Sen Jiang0affc2c2017-02-10 15:55:05 -0800493 if (max_url_size > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700494 SetUrlSwitchCount(url_switch_count_ + 1);
495
Jay Srinivasan08262882012-12-28 19:29:43 -0800496 // Whenever we update the URL index, we should also clear the URL failure
497 // count so we can start over fresh for the new URL.
498 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800499}
500
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800501void PayloadState::IncrementFailureCount() {
502 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800503 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800504 LOG(INFO) << "Incrementing the URL failure count";
505 SetUrlFailureCount(next_url_failure_count);
506 } else {
507 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
508 << ". Trying next available URL";
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700509 ExcludeCurrentPayload();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800510 IncrementUrlIndex();
511 }
512}
513
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700514void PayloadState::ExcludeCurrentPayload() {
Jae Hoon Kim76583912020-06-23 10:24:03 -0700515 if (payload_index_ >= response_.packages.size()) {
516 LOG(INFO) << "Skipping exclusion of the current payload.";
517 return;
518 }
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700519 const auto& package = response_.packages[payload_index_];
520 if (!package.can_exclude) {
521 LOG(INFO) << "Not excluding as marked non-excludable for package hash="
522 << package.hash;
523 return;
524 }
525 auto exclusion_name = utils::GetExclusionName(GetCurrentUrl());
526 if (!excluder_->Exclude(exclusion_name))
527 LOG(WARNING) << "Failed to exclude "
528 << " Package Hash=" << package.hash
529 << " CurrentUrl=" << GetCurrentUrl();
530 else
531 LOG(INFO) << "Excluded "
532 << " Package Hash=" << package.hash
533 << " CurrentUrl=" << GetCurrentUrl();
534}
535
Jay Srinivasan08262882012-12-28 19:29:43 -0800536void PayloadState::UpdateBackoffExpiryTime() {
537 if (response_.disable_payload_backoff) {
538 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
539 SetBackoffExpiryTime(Time());
540 return;
541 }
542
Alex Deymo820cc702013-06-28 15:43:46 -0700543 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800544 SetBackoffExpiryTime(Time());
545 return;
546 }
547
548 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700549 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800550 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700551 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700552 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800553
554 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
555 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700556 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800557
558 // The number of days is the minimum of 2 raised to (payload_attempt_number
559 // - 1) or kMaxBackoffDays.
560 num_days = min(num_days << power, kMaxBackoffDays);
561
562 // We don't want all retries to happen exactly at the same time when
563 // retrying after backoff. So add some random minutes to fuzz.
564 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800565 TimeDelta next_backoff_interval =
566 TimeDelta::FromDays(num_days) + TimeDelta::FromMinutes(fuzz_minutes);
Jay Srinivasan08262882012-12-28 19:29:43 -0800567 LOG(INFO) << "Incrementing the backoff expiry time by "
568 << utils::FormatTimeDelta(next_backoff_interval);
569 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
570}
571
Jay Srinivasan19409b72013-04-12 19:23:36 -0700572void PayloadState::UpdateCurrentDownloadSource() {
573 current_download_source_ = kNumDownloadSources;
574
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700575 if (using_p2p_for_downloading_) {
576 current_download_source_ = kDownloadSourceHttpPeer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800577 } else if (payload_index_ < candidate_urls_.size() &&
578 candidate_urls_[payload_index_].size() != 0) {
579 const string& current_url = candidate_urls_[payload_index_][GetUrlIndex()];
580 if (base::StartsWith(
581 current_url, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700582 current_download_source_ = kDownloadSourceHttpsServer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800583 } else if (base::StartsWith(current_url,
584 "http://",
Alex Vakulenko0103c362016-01-20 07:56:15 -0800585 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700586 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800587 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700588 }
589
590 LOG(INFO) << "Current download source: "
591 << utils::ToString(current_download_source_);
592}
593
594void PayloadState::UpdateBytesDownloaded(size_t count) {
595 SetCurrentBytesDownloaded(
596 current_download_source_,
597 GetCurrentBytesDownloaded(current_download_source_) + count,
598 false);
599 SetTotalBytesDownloaded(
600 current_download_source_,
601 GetTotalBytesDownloaded(current_download_source_) + count,
602 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800603
604 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700605}
606
David Zeuthen33bae492014-02-25 16:16:18 -0800607PayloadType PayloadState::CalculatePayloadType() {
Sen Jiangcdd52062017-05-18 15:33:10 -0700608 for (const auto& package : response_.packages) {
609 if (package.is_delta) {
610 return kPayloadTypeDelta;
611 }
David Zeuthen33bae492014-02-25 16:16:18 -0800612 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700613 OmahaRequestParams* params = system_state_->request_params();
614 if (params->delta_okay()) {
615 return kPayloadTypeFull;
616 }
617 // Full payload, delta was not allowed by request.
618 return kPayloadTypeForcedFull;
David Zeuthen33bae492014-02-25 16:16:18 -0800619}
620
David Zeuthen33bae492014-02-25 16:16:18 -0800621void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
622 int attempt_number = GetPayloadAttemptNumber();
623
624 PayloadType payload_type = CalculatePayloadType();
625
Sen Jiang0affc2c2017-02-10 15:55:05 -0800626 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800627
628 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
629
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800630 ClockInterface* clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700631 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800632 TimeDelta duration_uptime =
633 clock->GetMonotonicTime() - attempt_start_time_monotonic_;
David Zeuthen33bae492014-02-25 16:16:18 -0800634
635 int64_t payload_download_speed_bps = 0;
636 int64_t usec = duration_uptime.InMicroseconds();
637 if (usec > 0) {
638 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
639 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
640 payload_download_speed_bps = static_cast<int64_t>(bps);
641 }
642
643 DownloadSource download_source = current_download_source_;
644
645 metrics::DownloadErrorCode payload_download_error_code =
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800646 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700647 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800648 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800649
650 // Add additional detail to AttemptResult
651 switch (attempt_result) {
652 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800653 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800654 break;
655
656 case metrics::AttemptResult::kInternalError:
657 internal_error_code = code;
658 break;
659
660 // Explicit fall-through for cases where we do not have additional
661 // detail. We avoid the default keyword to force people adding new
662 // AttemptResult values to visit this code and examine whether
663 // additional detail is needed.
664 case metrics::AttemptResult::kUpdateSucceeded:
665 case metrics::AttemptResult::kMetadataMalformed:
666 case metrics::AttemptResult::kOperationMalformed:
667 case metrics::AttemptResult::kOperationExecutionError:
668 case metrics::AttemptResult::kMetadataVerificationFailed:
669 case metrics::AttemptResult::kPayloadVerificationFailed:
670 case metrics::AttemptResult::kVerificationFailed:
671 case metrics::AttemptResult::kPostInstallFailed:
672 case metrics::AttemptResult::kAbnormalTermination:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800673 case metrics::AttemptResult::kUpdateCanceled:
Sen Jiangfe522822017-10-31 15:14:11 -0700674 case metrics::AttemptResult::kUpdateSucceededNotActive:
David Zeuthen33bae492014-02-25 16:16:18 -0800675 case metrics::AttemptResult::kNumConstants:
676 case metrics::AttemptResult::kUnset:
677 break;
678 }
679
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700680 system_state_->metrics_reporter()->ReportUpdateAttemptMetrics(
681 system_state_,
682 attempt_number,
683 payload_type,
684 duration,
685 duration_uptime,
686 payload_size,
Tianjie Xu1f93d092017-10-09 12:13:29 -0700687 attempt_result,
688 internal_error_code);
689
690 system_state_->metrics_reporter()->ReportUpdateAttemptDownloadMetrics(
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700691 payload_bytes_downloaded,
692 payload_download_speed_bps,
693 download_source,
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700694 payload_download_error_code,
695 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800696}
697
David Zeuthen4e1d1492014-04-25 13:12:27 -0700698void PayloadState::PersistAttemptMetrics() {
699 // TODO(zeuthen): For now we only persist whether an attempt was in
700 // progress and not values/metrics related to the attempt. This
701 // means that when this happens, of all the UpdateEngine.Attempt.*
702 // metrics, only UpdateEngine.Attempt.Result is reported (with the
703 // value |kAbnormalTermination|). In the future we might want to
704 // persist more data so we can report other metrics in the
705 // UpdateEngine.Attempt.* namespace when this happens.
706 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
707}
708
709void PayloadState::ClearPersistedAttemptMetrics() {
710 prefs_->Delete(kPrefsAttemptInProgress);
711}
712
713void PayloadState::ReportAndClearPersistedAttemptMetrics() {
714 bool attempt_in_progress = false;
715 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
716 return;
717 if (!attempt_in_progress)
718 return;
719
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700720 system_state_->metrics_reporter()
721 ->ReportAbnormallyTerminatedUpdateAttemptMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700722
723 ClearPersistedAttemptMetrics();
724}
725
David Zeuthen33bae492014-02-25 16:16:18 -0800726void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700727 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800728
729 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800730 int64_t total_bytes_by_source[kNumDownloadSources];
731 int64_t successful_bytes = 0;
732 int64_t total_bytes = 0;
733 int64_t successful_mbs = 0;
734 int64_t total_mbs = 0;
735
Jay Srinivasan19409b72013-04-12 19:23:36 -0700736 for (int i = 0; i < kNumDownloadSources; i++) {
737 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800738 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700739
David Zeuthen44848602013-06-24 13:32:14 -0700740 // Only consider this download source (and send byte counts) as
741 // having been used if we downloaded a non-trivial amount of bytes
742 // (e.g. at least 1 MiB) that contributed to the final success of
743 // the update. Otherwise we're going to end up with a lot of
744 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700745
David Zeuthen33bae492014-02-25 16:16:18 -0800746 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800747 successful_bytes += bytes;
748 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700749 SetCurrentBytesDownloaded(source, 0, true);
750
David Zeuthen33bae492014-02-25 16:16:18 -0800751 bytes = GetTotalBytesDownloaded(source);
752 total_bytes_by_source[i] = bytes;
753 total_bytes += bytes;
754 total_mbs += bytes / kNumBytesInOneMiB;
755 SetTotalBytesDownloaded(source, 0, true);
756 }
757
758 int download_overhead_percentage = 0;
759 if (successful_bytes > 0) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800760 download_overhead_percentage =
761 (total_bytes - successful_bytes) * 100ULL / successful_bytes;
David Zeuthen33bae492014-02-25 16:16:18 -0800762 }
763
764 int url_switch_count = static_cast<int>(url_switch_count_);
765
766 int reboot_count = GetNumReboots();
767
768 SetNumReboots(0);
769
770 TimeDelta duration = GetUpdateDuration();
Sen Jiang8712e962018-05-08 12:12:28 -0700771 TimeDelta duration_uptime = GetUpdateDurationUptime();
David Zeuthen33bae492014-02-25 16:16:18 -0800772
773 prefs_->Delete(kPrefsUpdateTimestampStart);
774 prefs_->Delete(kPrefsUpdateDurationUptime);
775
776 PayloadType payload_type = CalculatePayloadType();
777
Sen Jiang0affc2c2017-02-10 15:55:05 -0800778 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800779
780 int attempt_count = GetPayloadAttemptNumber();
781
782 int updates_abandoned_count = num_responses_seen_ - 1;
783
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700784 system_state_->metrics_reporter()->ReportSuccessfulUpdateMetrics(
785 attempt_count,
786 updates_abandoned_count,
787 payload_type,
788 payload_size,
789 total_bytes_by_source,
790 download_overhead_percentage,
791 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700792 duration_uptime,
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700793 reboot_count,
794 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700795}
796
797void PayloadState::UpdateNumReboots() {
798 // We only update the reboot count when the system has been detected to have
799 // been rebooted.
800 if (!system_state_->system_rebooted()) {
801 return;
802 }
803
804 SetNumReboots(GetNumReboots() + 1);
805}
806
807void PayloadState::SetNumReboots(uint32_t num_reboots) {
Chris Sosabe45bef2013-04-09 18:25:12 -0700808 num_reboots_ = num_reboots;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700809 metrics_utils::SetNumReboots(num_reboots, prefs_);
Chris Sosabe45bef2013-04-09 18:25:12 -0700810}
811
Jay Srinivasan08262882012-12-28 19:29:43 -0800812void PayloadState::ResetPersistedState() {
813 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700814 SetFullPayloadAttemptNumber(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700815 SetPayloadIndex(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800816 SetUrlIndex(0);
817 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700818 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700819 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700820 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700821 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700822 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700823 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700824 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700825 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700826 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700827 SetScatteringWaitPeriod(TimeDelta());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700828 SetStagingWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700829}
830
831void PayloadState::ResetRollbackVersion() {
832 CHECK(powerwash_safe_prefs_);
833 rollback_version_ = "";
834 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700835}
836
837void PayloadState::ResetDownloadSourcesOnNewUpdate() {
838 for (int i = 0; i < kNumDownloadSources; i++) {
839 DownloadSource source = static_cast<DownloadSource>(i);
840 SetCurrentBytesDownloaded(source, 0, true);
841 // Note: Not resetting the TotalBytesDownloaded as we want that metric
842 // to count the bytes downloaded across various update attempts until
843 // we have successfully applied the update.
844 }
845}
846
Jay Srinivasan08262882012-12-28 19:29:43 -0800847string PayloadState::CalculateResponseSignature() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800848 string response_sign;
849 for (size_t i = 0; i < response_.packages.size(); i++) {
850 const auto& package = response_.packages[i];
851 response_sign += base::StringPrintf(
852 "Payload %zu:\n"
853 " Size = %ju\n"
854 " Sha256 Hash = %s\n"
855 " Metadata Size = %ju\n"
856 " Metadata Signature = %s\n"
Sen Jiangcdd52062017-05-18 15:33:10 -0700857 " Is Delta = %d\n"
Sen Jiang0affc2c2017-02-10 15:55:05 -0800858 " NumURLs = %zu\n",
859 i,
860 static_cast<uintmax_t>(package.size),
861 package.hash.c_str(),
862 static_cast<uintmax_t>(package.metadata_size),
863 package.metadata_signature.c_str(),
Sen Jiangcdd52062017-05-18 15:33:10 -0700864 package.is_delta,
Sen Jiang0affc2c2017-02-10 15:55:05 -0800865 candidate_urls_[i].size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800866
Sen Jiang0affc2c2017-02-10 15:55:05 -0800867 for (size_t j = 0; j < candidate_urls_[i].size(); j++)
868 response_sign += base::StringPrintf(
869 " Candidate Url%zu = %s\n", j, candidate_urls_[i][j].c_str());
870 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800871
Alex Vakulenko75039d72014-03-25 12:36:28 -0700872 response_sign += base::StringPrintf(
Alex Vakulenko75039d72014-03-25 12:36:28 -0700873 "Max Failure Count Per Url = %d\n"
874 "Disable Payload Backoff = %d\n",
Alex Vakulenko75039d72014-03-25 12:36:28 -0700875 response_.max_failure_count_per_url,
876 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800877 return response_sign;
878}
879
880void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800881 CHECK(prefs_);
882 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800883 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
884 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
885 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800886 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800887}
888
Jay Srinivasan19409b72013-04-12 19:23:36 -0700889void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800890 CHECK(prefs_);
891 response_signature_ = response_signature;
892 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
893 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
894}
895
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800896void PayloadState::LoadPayloadAttemptNumber() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700897 SetPayloadAttemptNumber(
898 GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800899}
900
Alex Deymo820cc702013-06-28 15:43:46 -0700901void PayloadState::LoadFullPayloadAttemptNumber() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700902 SetFullPayloadAttemptNumber(
903 GetPersistedValue(kPrefsFullPayloadAttemptNumber, prefs_));
Alex Deymo820cc702013-06-28 15:43:46 -0700904}
905
906void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800907 payload_attempt_number_ = payload_attempt_number;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700908 metrics_utils::SetPayloadAttemptNumber(payload_attempt_number, prefs_);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800909}
910
Alex Deymo820cc702013-06-28 15:43:46 -0700911void PayloadState::SetFullPayloadAttemptNumber(
912 int full_payload_attempt_number) {
913 CHECK(prefs_);
914 full_payload_attempt_number_ = full_payload_attempt_number;
915 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
916 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800917 full_payload_attempt_number_);
Alex Deymo820cc702013-06-28 15:43:46 -0700918}
919
Sen Jiang5ae865b2017-04-18 14:24:40 -0700920void PayloadState::SetPayloadIndex(size_t payload_index) {
921 CHECK(prefs_);
922 payload_index_ = payload_index;
923 LOG(INFO) << "Payload Index = " << payload_index_;
924 prefs_->SetInt64(kPrefsUpdateStatePayloadIndex, payload_index_);
925}
926
927bool PayloadState::NextPayload() {
Jae Hoon Kim76583912020-06-23 10:24:03 -0700928 if (payload_index_ >= candidate_urls_.size())
929 return false;
930 SetPayloadIndex(payload_index_ + 1);
931 if (payload_index_ >= candidate_urls_.size())
Sen Jiang5ae865b2017-04-18 14:24:40 -0700932 return false;
Jae Hoon Kima3210e62020-05-07 11:32:44 -0700933 SetUrlIndex(0);
Sen Jiang5ae865b2017-04-18 14:24:40 -0700934 return true;
935}
936
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800937void PayloadState::LoadUrlIndex() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700938 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex, prefs_));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800939}
940
941void PayloadState::SetUrlIndex(uint32_t url_index) {
942 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800943 url_index_ = url_index;
944 LOG(INFO) << "Current URL Index = " << url_index_;
945 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700946
947 // Also update the download source, which is purely dependent on the
948 // current URL index alone.
949 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800950}
951
Gilad Arnold519cfc72014-10-02 10:34:54 -0700952void PayloadState::LoadScatteringWaitPeriod() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700953 SetScatteringWaitPeriod(TimeDelta::FromSeconds(
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700954 GetPersistedValue(kPrefsWallClockScatteringWaitPeriod, prefs_)));
Gilad Arnold519cfc72014-10-02 10:34:54 -0700955}
956
Alex Deymof329b932014-10-30 01:37:48 -0700957void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700958 CHECK(prefs_);
959 scattering_wait_period_ = wait_period;
960 LOG(INFO) << "Scattering Wait Period (seconds) = "
961 << scattering_wait_period_.InSeconds();
962 if (scattering_wait_period_.InSeconds() > 0) {
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700963 prefs_->SetInt64(kPrefsWallClockScatteringWaitPeriod,
Gilad Arnold519cfc72014-10-02 10:34:54 -0700964 scattering_wait_period_.InSeconds());
965 } else {
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700966 prefs_->Delete(kPrefsWallClockScatteringWaitPeriod);
967 }
968}
969
970void PayloadState::LoadStagingWaitPeriod() {
971 SetStagingWaitPeriod(TimeDelta::FromSeconds(
972 GetPersistedValue(kPrefsWallClockStagingWaitPeriod, prefs_)));
973}
974
975void PayloadState::SetStagingWaitPeriod(TimeDelta wait_period) {
976 CHECK(prefs_);
977 staging_wait_period_ = wait_period;
978 LOG(INFO) << "Staging Wait Period (days) =" << staging_wait_period_.InDays();
979 if (staging_wait_period_.InSeconds() > 0) {
980 prefs_->SetInt64(kPrefsWallClockStagingWaitPeriod,
981 staging_wait_period_.InSeconds());
982 } else {
983 prefs_->Delete(kPrefsWallClockStagingWaitPeriod);
Gilad Arnold519cfc72014-10-02 10:34:54 -0700984 }
985}
986
David Zeuthencc6f9962013-04-18 11:57:24 -0700987void PayloadState::LoadUrlSwitchCount() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700988 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount, prefs_));
David Zeuthencc6f9962013-04-18 11:57:24 -0700989}
990
991void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
992 CHECK(prefs_);
993 url_switch_count_ = url_switch_count;
994 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
995 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
996}
997
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800998void PayloadState::LoadUrlFailureCount() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700999 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount, prefs_));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001000}
1001
1002void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
1003 CHECK(prefs_);
1004 url_failure_count_ = url_failure_count;
1005 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
1006 << ")'s Failure Count = " << url_failure_count_;
1007 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001008}
1009
Jay Srinivasan08262882012-12-28 19:29:43 -08001010void PayloadState::LoadBackoffExpiryTime() {
1011 CHECK(prefs_);
1012 int64_t stored_value;
1013 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
1014 return;
1015
1016 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
1017 return;
1018
1019 Time stored_time = Time::FromInternalValue(stored_value);
1020 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
1021 LOG(ERROR) << "Invalid backoff expiry time ("
1022 << utils::ToString(stored_time)
1023 << ") in persisted state. Resetting.";
1024 stored_time = Time();
1025 }
1026 SetBackoffExpiryTime(stored_time);
1027}
1028
1029void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
1030 CHECK(prefs_);
1031 backoff_expiry_time_ = new_time;
1032 LOG(INFO) << "Backoff Expiry Time = "
1033 << utils::ToString(backoff_expiry_time_);
1034 prefs_->SetInt64(kPrefsBackoffExpiryTime,
1035 backoff_expiry_time_.ToInternalValue());
1036}
1037
David Zeuthen9a017f22013-04-11 16:10:26 -07001038TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001039 Time end_time = update_timestamp_end_.is_null()
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001040 ? system_state_->clock()->GetWallclockTime()
1041 : update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001042 return end_time - update_timestamp_start_;
1043}
1044
1045void PayloadState::LoadUpdateTimestampStart() {
1046 int64_t stored_value;
1047 Time stored_time;
1048
1049 CHECK(prefs_);
1050
David Zeuthenf413fe52013-04-22 14:04:39 -07001051 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001052
1053 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1054 // The preference missing is not unexpected - in that case, just
1055 // use the current time as start time
1056 stored_time = now;
1057 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1058 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1059 stored_time = now;
1060 } else {
1061 stored_time = Time::FromInternalValue(stored_value);
1062 }
1063
1064 // Sanity check: If the time read from disk is in the future
1065 // (modulo some slack to account for possible NTP drift
1066 // adjustments), something is fishy and we should report and
1067 // reset.
1068 TimeDelta duration_according_to_stored_time = now - stored_time;
1069 if (duration_according_to_stored_time < -kDurationSlack) {
1070 LOG(ERROR) << "The UpdateTimestampStart value ("
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001071 << utils::ToString(stored_time) << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001072 << utils::FormatTimeDelta(duration_according_to_stored_time)
1073 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001074 stored_time = now;
1075 }
1076
1077 SetUpdateTimestampStart(stored_time);
1078}
1079
1080void PayloadState::SetUpdateTimestampStart(const Time& value) {
David Zeuthen9a017f22013-04-11 16:10:26 -07001081 update_timestamp_start_ = value;
Tianjie Xu90aaa102017-10-10 17:39:03 -07001082 metrics_utils::SetUpdateTimestampStart(value, prefs_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001083}
1084
1085void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1086 update_timestamp_end_ = value;
1087 LOG(INFO) << "Update Timestamp End = "
1088 << utils::ToString(update_timestamp_end_);
1089}
1090
1091TimeDelta PayloadState::GetUpdateDurationUptime() {
1092 return update_duration_uptime_;
1093}
1094
1095void PayloadState::LoadUpdateDurationUptime() {
1096 int64_t stored_value;
1097 TimeDelta stored_delta;
1098
1099 CHECK(prefs_);
1100
1101 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1102 // The preference missing is not unexpected - in that case, just
1103 // we'll use zero as the delta
1104 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1105 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1106 stored_delta = TimeDelta::FromSeconds(0);
1107 } else {
1108 stored_delta = TimeDelta::FromInternalValue(stored_value);
1109 }
1110
1111 // Sanity-check: Uptime can never be greater than the wall-clock
1112 // difference (modulo some slack). If it is, report and reset
1113 // to the wall-clock difference.
1114 TimeDelta diff = GetUpdateDuration() - stored_delta;
1115 if (diff < -kDurationSlack) {
1116 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001117 << utils::FormatTimeDelta(stored_delta)
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001118 << ") in persisted state is " << utils::FormatTimeDelta(diff)
David Zeuthen674c3182013-04-18 14:05:20 -07001119 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001120 stored_delta = update_duration_current_;
1121 }
1122
1123 SetUpdateDurationUptime(stored_delta);
1124}
1125
Chris Sosabe45bef2013-04-09 18:25:12 -07001126void PayloadState::LoadNumReboots() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001127 SetNumReboots(GetPersistedValue(kPrefsNumReboots, prefs_));
Chris Sosaaa18e162013-06-20 13:20:30 -07001128}
1129
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001130void PayloadState::LoadRollbackHappened() {
1131 CHECK(powerwash_safe_prefs_);
1132 bool rollback_happened = false;
1133 powerwash_safe_prefs_->GetBoolean(kPrefsRollbackHappened, &rollback_happened);
1134 SetRollbackHappened(rollback_happened);
1135}
1136
1137void PayloadState::SetRollbackHappened(bool rollback_happened) {
1138 CHECK(powerwash_safe_prefs_);
1139 LOG(INFO) << "Setting rollback-happened to " << rollback_happened << ".";
1140 rollback_happened_ = rollback_happened;
1141 if (rollback_happened) {
1142 powerwash_safe_prefs_->SetBoolean(kPrefsRollbackHappened,
1143 rollback_happened);
1144 } else {
1145 powerwash_safe_prefs_->Delete(kPrefsRollbackHappened);
1146 }
1147}
1148
Chris Sosaaa18e162013-06-20 13:20:30 -07001149void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001150 CHECK(powerwash_safe_prefs_);
1151 string rollback_version;
1152 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1153 &rollback_version)) {
1154 SetRollbackVersion(rollback_version);
1155 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001156}
1157
1158void PayloadState::SetRollbackVersion(const string& rollback_version) {
1159 CHECK(powerwash_safe_prefs_);
Andrewcc6ab9f2020-06-25 07:41:40 -07001160 LOG(INFO) << "Excluding version " << rollback_version;
Chris Sosaaa18e162013-06-20 13:20:30 -07001161 rollback_version_ = rollback_version;
1162 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001163}
1164
David Zeuthen9a017f22013-04-11 16:10:26 -07001165void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1166 const Time& timestamp,
1167 bool use_logging) {
1168 CHECK(prefs_);
1169 update_duration_uptime_ = value;
1170 update_duration_uptime_timestamp_ = timestamp;
1171 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1172 update_duration_uptime_.ToInternalValue());
1173 if (use_logging) {
1174 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001175 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001176 }
1177}
1178
1179void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001180 Time now = system_state_->clock()->GetMonotonicTime();
1181 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001182}
1183
1184void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001185 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001186 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
Colin Howes0e452c92018-11-02 13:18:44 -07001187
1188 if (uptime_since_last_update > TimeDelta::FromSeconds(kUptimeResolution)) {
1189 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1190 // We're frequently called so avoid logging this write
1191 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1192 }
David Zeuthen9a017f22013-04-11 16:10:26 -07001193}
1194
Jay Srinivasan19409b72013-04-12 19:23:36 -07001195string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1196 return prefix + "-from-" + utils::ToString(source);
1197}
1198
1199void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1200 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001201 SetCurrentBytesDownloaded(source, GetPersistedValue(key, prefs_), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001202}
1203
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001204void PayloadState::SetCurrentBytesDownloaded(DownloadSource source,
1205 uint64_t current_bytes_downloaded,
1206 bool log) {
Jay Srinivasan19409b72013-04-12 19:23:36 -07001207 CHECK(prefs_);
1208
1209 if (source >= kNumDownloadSources)
1210 return;
1211
1212 // Update the in-memory value.
1213 current_bytes_downloaded_[source] = current_bytes_downloaded;
1214
1215 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1216 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1217 LOG_IF(INFO, log) << "Current bytes downloaded for "
1218 << utils::ToString(source) << " = "
1219 << GetCurrentBytesDownloaded(source);
1220}
1221
1222void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1223 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001224 SetTotalBytesDownloaded(source, GetPersistedValue(key, prefs_), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001225}
1226
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001227void PayloadState::SetTotalBytesDownloaded(DownloadSource source,
1228 uint64_t total_bytes_downloaded,
1229 bool log) {
Jay Srinivasan19409b72013-04-12 19:23:36 -07001230 CHECK(prefs_);
1231
1232 if (source >= kNumDownloadSources)
1233 return;
1234
1235 // Update the in-memory value.
1236 total_bytes_downloaded_[source] = total_bytes_downloaded;
1237
1238 // Persist.
1239 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1240 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001241 LOG_IF(INFO, log) << "Total bytes downloaded for " << utils::ToString(source)
1242 << " = " << GetTotalBytesDownloaded(source);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001243}
1244
David Zeuthena573d6f2013-06-14 16:13:36 -07001245void PayloadState::LoadNumResponsesSeen() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001246 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen, prefs_));
David Zeuthena573d6f2013-06-14 16:13:36 -07001247}
1248
1249void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1250 CHECK(prefs_);
1251 num_responses_seen_ = num_responses_seen;
1252 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1253 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1254}
1255
Jay Srinivasan53173b92013-05-17 17:13:01 -07001256void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001257 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001258
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001259 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001260 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001261 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001262 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1263 } else {
1264 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1265 http_url_ok = true;
1266 }
1267
1268 candidate_urls_.clear();
Sen Jiang0affc2c2017-02-10 15:55:05 -08001269 for (const auto& package : response_.packages) {
1270 candidate_urls_.emplace_back();
1271 for (const string& candidate_url : package.payload_urls) {
1272 if (base::StartsWith(
1273 candidate_url, "http://", base::CompareCase::INSENSITIVE_ASCII) &&
1274 !http_url_ok) {
1275 continue;
1276 }
1277 candidate_urls_.back().push_back(candidate_url);
1278 LOG(INFO) << "Candidate Url" << (candidate_urls_.back().size() - 1)
1279 << ": " << candidate_url;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001280 }
Sen Jiang0affc2c2017-02-10 15:55:05 -08001281 LOG(INFO) << "Found " << candidate_urls_.back().size() << " candidate URLs "
1282 << "out of " << package.payload_urls.size()
1283 << " URLs supplied in package " << candidate_urls_.size() - 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001284 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001285}
1286
David Zeuthene4c58bf2013-06-18 17:26:50 -07001287void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001288 // Flush previous state from abnormal attempt failure, if any.
1289 ReportAndClearPersistedAttemptMetrics();
1290
Alex Deymo569c4242013-07-24 12:01:01 -07001291 // Avoid the UpdateEngineStarted actions if this is not the first time we
1292 // run the update engine since reboot.
1293 if (!system_state_->system_rebooted())
1294 return;
1295
Tianjie Xu90aaa102017-10-10 17:39:03 -07001296 // Report time_to_reboot if we booted into a new update.
1297 metrics_utils::LoadAndReportTimeToReboot(
1298 system_state_->metrics_reporter(), prefs_, system_state_->clock());
1299 prefs_->Delete(kPrefsSystemUpdatedMarker);
1300
Alex Deymo42432912013-07-12 20:21:15 -07001301 // Check if it is needed to send metrics about a failed reboot into a new
1302 // version.
1303 ReportFailedBootIfNeeded();
1304}
1305
1306void PayloadState::ReportFailedBootIfNeeded() {
1307 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1308 // payload was marked as ready immediately before the last reboot, and we
1309 // need to check if such payload successfully rebooted or not.
1310 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001311 int64_t installed_from = 0;
1312 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001313 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1314 return;
1315 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001316 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1317 // partition number. We are now using slot numbers (0 or 1) instead, so
1318 // the following comparison will not match if we are comparing an old
1319 // partition number against a new slot number, which is the correct outcome
1320 // since we successfully booted the new update in that case. If the boot
1321 // failed, we will read this value from the same version, so it will always
1322 // be compatible.
1323 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001324 // A reboot was pending, but the chromebook is again in the same
1325 // BootDevice where the update was installed from.
1326 int64_t target_attempt;
1327 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1328 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1329 "TargetVersionInstalledFrom was present.";
1330 target_attempt = 1;
1331 }
1332
1333 // Report the UMA metric of the current boot failure.
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001334 system_state_->metrics_reporter()->ReportFailedUpdateCount(
1335 target_attempt);
Alex Deymo42432912013-07-12 20:21:15 -07001336 } else {
1337 prefs_->Delete(kPrefsTargetVersionAttempt);
1338 prefs_->Delete(kPrefsTargetVersionUniqueId);
1339 }
1340 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1341 }
1342}
1343
1344void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1345 // Expect to boot into the new partition in the next reboot setting the
1346 // TargetVersion* flags in the Prefs.
1347 string stored_target_version_uid;
1348 string target_version_id;
1349 string target_partition;
1350 int64_t target_attempt;
1351
1352 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1353 prefs_->GetString(kPrefsTargetVersionUniqueId,
1354 &stored_target_version_uid) &&
1355 stored_target_version_uid == target_version_uid) {
1356 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1357 target_attempt = 0;
1358 } else {
1359 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1360 target_attempt = 0;
1361 }
1362 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1363
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001364 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001365 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001366}
1367
1368void PayloadState::ResetUpdateStatus() {
1369 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1370 // rebooted the next boot is not flagged as failed to rebooted into the
1371 // new applied payload.
1372 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1373
1374 // Also decrement the attempt number if it exists.
1375 int64_t target_attempt;
1376 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001377 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001378}
1379
David Zeuthendcba8092013-08-06 12:16:35 -07001380int PayloadState::GetP2PNumAttempts() {
1381 return p2p_num_attempts_;
1382}
1383
1384void PayloadState::SetP2PNumAttempts(int value) {
1385 p2p_num_attempts_ = value;
1386 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1387 CHECK(prefs_);
1388 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1389}
1390
1391void PayloadState::LoadP2PNumAttempts() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001392 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts, prefs_));
David Zeuthendcba8092013-08-06 12:16:35 -07001393}
1394
1395Time PayloadState::GetP2PFirstAttemptTimestamp() {
1396 return p2p_first_attempt_timestamp_;
1397}
1398
1399void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1400 p2p_first_attempt_timestamp_ = time;
1401 LOG(INFO) << "p2p First Attempt Timestamp = "
1402 << utils::ToString(p2p_first_attempt_timestamp_);
1403 CHECK(prefs_);
1404 int64_t stored_value = time.ToInternalValue();
1405 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1406}
1407
1408void PayloadState::LoadP2PFirstAttemptTimestamp() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001409 int64_t stored_value =
1410 GetPersistedValue(kPrefsP2PFirstAttemptTimestamp, prefs_);
David Zeuthendcba8092013-08-06 12:16:35 -07001411 Time stored_time = Time::FromInternalValue(stored_value);
1412 SetP2PFirstAttemptTimestamp(stored_time);
1413}
1414
1415void PayloadState::P2PNewAttempt() {
1416 CHECK(prefs_);
1417 // Set timestamp, if it hasn't been set already
1418 if (p2p_first_attempt_timestamp_.is_null()) {
1419 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1420 }
1421 // Increase number of attempts
1422 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1423}
1424
1425bool PayloadState::P2PAttemptAllowed() {
1426 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1427 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001428 << " which is greater than " << kMaxP2PAttempts
David Zeuthendcba8092013-08-06 12:16:35 -07001429 << " - disallowing p2p.";
1430 return false;
1431 }
1432
1433 if (!p2p_first_attempt_timestamp_.is_null()) {
1434 Time now = system_state_->clock()->GetWallclockTime();
1435 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1436 if (time_spent_attempting_p2p.InSeconds() < 0) {
1437 LOG(ERROR) << "Time spent attempting p2p is negative"
1438 << " - disallowing p2p.";
1439 return false;
1440 }
1441 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1442 LOG(INFO) << "Time spent attempting p2p is "
1443 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1444 << " which is greater than "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001445 << utils::FormatTimeDelta(
1446 TimeDelta::FromSeconds(kMaxP2PAttemptTimeSeconds))
David Zeuthendcba8092013-08-06 12:16:35 -07001447 << " - disallowing p2p.";
1448 return false;
1449 }
1450 }
1451
1452 return true;
1453}
1454
Sen Jiang0affc2c2017-02-10 15:55:05 -08001455int64_t PayloadState::GetPayloadSize() {
1456 int64_t payload_size = 0;
1457 for (const auto& package : response_.packages)
1458 payload_size += package.size;
1459 return payload_size;
1460}
1461
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001462} // namespace chromeos_update_engine