blob: 23ff3e2fc2a365ca88784cde765dcc0c0d5be68f [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"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080040
Jay Srinivasan08262882012-12-28 19:29:43 -080041using base::Time;
42using base::TimeDelta;
43using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080044using std::string;
45
46namespace chromeos_update_engine {
47
Tianjie Xu90aaa102017-10-10 17:39:03 -070048using metrics_utils::GetPersistedValue;
49
David Zeuthen9a017f22013-04-11 16:10:26 -070050const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
51
Jay Srinivasan08262882012-12-28 19:29:43 -080052// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070053static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080054
Jay Srinivasan08262882012-12-28 19:29:43 -080055// We want to randomize retry attempts after the backoff by +/- 6 hours.
56static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080057
Colin Howes0e452c92018-11-02 13:18:44 -070058// Limit persisting current update duration uptime to once per second
59static const uint64_t kUptimeResolution = 1;
60
Jay Srinivasan19409b72013-04-12 19:23:36 -070061PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070062 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070063 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070064 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070065 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070066 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070067 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070068 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070069 url_switch_count_(0),
Marton Hunyadye58bddb2018-04-10 20:27:26 +020070 rollback_happened_(false),
David Zeuthenafed4a12014-04-09 15:28:44 -070071 attempt_num_bytes_downloaded_(0),
72 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070073 attempt_type_(AttemptType::kUpdate) {
74 for (int i = 0; i <= kNumDownloadSources; i++)
75 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070076}
77
78bool PayloadState::Initialize(SystemState* system_state) {
79 system_state_ = system_state;
80 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070081 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080082 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080083 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070084 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080085 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080086 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070087 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080088 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070089 LoadUpdateTimestampStart();
90 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
91 // being called before it. Don't reorder.
92 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070093 for (int i = 0; i < kNumDownloadSources; i++) {
94 DownloadSource source = static_cast<DownloadSource>(i);
95 LoadCurrentBytesDownloaded(source);
96 LoadTotalBytesDownloaded(source);
97 }
Chris Sosabe45bef2013-04-09 18:25:12 -070098 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070099 LoadNumResponsesSeen();
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200100 LoadRollbackHappened();
Chris Sosaaa18e162013-06-20 13:20:30 -0700101 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700102 LoadP2PFirstAttemptTimestamp();
103 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800104 return true;
105}
106
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800107void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800108 // Always store the latest response.
109 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800110
Jay Srinivasan53173b92013-05-17 17:13:01 -0700111 // Compute the candidate URLs first as they are used to calculate the
112 // response signature so that a change in enterprise policy for
113 // HTTP downloads being enabled or not could be honored as soon as the
114 // next update check happens.
115 ComputeCandidateUrls();
116
Jay Srinivasan08262882012-12-28 19:29:43 -0800117 // Check if the "signature" of this response (i.e. the fields we care about)
118 // has changed.
119 string new_response_signature = CalculateResponseSignature();
120 bool has_response_changed = (response_signature_ != new_response_signature);
121
122 // If the response has changed, we should persist the new signature and
123 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800124 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800125 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700126 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800127 SetResponseSignature(new_response_signature);
128 ResetPersistedState();
129 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800130 }
131
Sen Jiang97eba342017-05-22 14:34:11 -0700132 // Always start from payload index 0, even for resume, to download partition
133 // info from previous payloads.
134 payload_index_ = 0;
135
Jay Srinivasan08262882012-12-28 19:29:43 -0800136 // This is the earliest point at which we can validate whether the URL index
137 // we loaded from the persisted state is a valid value. If the response
138 // hasn't changed but the URL index is invalid, it's indicative of some
139 // tampering of the persisted state.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800140 if (payload_index_ >= candidate_urls_.size() ||
141 url_index_ >= candidate_urls_[payload_index_].size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800142 LOG(INFO) << "Resetting all payload state as the url index seems to have "
143 "been tampered with";
144 ResetPersistedState();
145 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800146 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700147
148 // Update the current download source which depends on the latest value of
149 // the response.
150 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800151}
152
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700153void PayloadState::SetUsingP2PForDownloading(bool value) {
154 using_p2p_for_downloading_ = value;
155 // Update the current download source which depends on whether we are
156 // using p2p or not.
157 UpdateCurrentDownloadSource();
158}
159
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800160void PayloadState::DownloadComplete() {
161 LOG(INFO) << "Payload downloaded successfully";
162 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700163 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800164}
165
166void PayloadState::DownloadProgress(size_t count) {
167 if (count == 0)
168 return;
169
David Zeuthen9a017f22013-04-11 16:10:26 -0700170 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700171 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700172
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800173 // We've received non-zero bytes from a recent download operation. Since our
174 // URL failure count is meant to penalize a URL only for consecutive
175 // failures, downloading bytes successfully means we should reset the failure
176 // count (as we know at least that the URL is working). In future, we can
177 // design this to be more sophisticated to check for more intelligent failure
178 // patterns, but right now, even 1 byte downloaded will mark the URL to be
179 // good unless it hits 10 (or configured number of) consecutive failures
180 // again.
181
182 if (GetUrlFailureCount() == 0)
183 return;
184
185 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
186 << " to 0 as we received " << count << " bytes successfully";
187 SetUrlFailureCount(0);
188}
189
David Zeuthenafed4a12014-04-09 15:28:44 -0700190void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700191 // Flush previous state from abnormal attempt failure, if any.
192 ReportAndClearPersistedAttemptMetrics();
193
David Zeuthenafed4a12014-04-09 15:28:44 -0700194 attempt_type_ = attempt_type;
195
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800196 ClockInterface* clock = system_state_->clock();
David Zeuthen33bae492014-02-25 16:16:18 -0800197 attempt_start_time_boot_ = clock->GetBootTime();
198 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800199 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700200
201 metrics::ConnectionType type;
Sen Jiang255e22b2016-05-20 16:15:29 -0700202 ConnectionType network_connection_type;
203 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700204 ConnectionManagerInterface* connection_manager =
205 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700206 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700207 &tethering)) {
208 LOG(ERROR) << "Failed to determine connection type.";
209 type = metrics::ConnectionType::kUnknown;
210 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800211 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700212 }
213 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700214
215 if (attempt_type == AttemptType::kUpdate)
216 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800217}
218
Chris Sosabe45bef2013-04-09 18:25:12 -0700219void PayloadState::UpdateResumed() {
220 LOG(INFO) << "Resuming an update that was previously started.";
221 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700222 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700223}
224
Jay Srinivasan19409b72013-04-12 19:23:36 -0700225void PayloadState::UpdateRestarted() {
226 LOG(INFO) << "Starting a new update";
227 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700228 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700229 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700230}
231
David Zeuthen9a017f22013-04-11 16:10:26 -0700232void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700233 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700234 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700235 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800236
David Zeuthen96197df2014-04-16 12:22:39 -0700237 switch (attempt_type_) {
238 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700239 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700240 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700241 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700242 break;
243
244 case AttemptType::kRollback:
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700245 system_state_->metrics_reporter()->ReportRollbackMetrics(
246 metrics::RollbackResult::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700247 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700248 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700249
250 // Reset the number of responses seen since it counts from the last
251 // successful update, e.g. now.
252 SetNumResponsesSeen(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700253 SetPayloadIndex(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700254
Tianjie Xu90aaa102017-10-10 17:39:03 -0700255 metrics_utils::SetSystemUpdatedMarker(system_state_->clock(), prefs_);
David Zeuthen9a017f22013-04-11 16:10:26 -0700256}
257
David Zeuthena99981f2013-04-29 13:42:47 -0700258void PayloadState::UpdateFailed(ErrorCode error) {
259 ErrorCode base_error = utils::GetBaseErrorCode(error);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800260 LOG(INFO) << "Updating payload state for error code: " << base_error << " ("
261 << utils::ErrorCodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800262
Jay Srinivasan53173b92013-05-17 17:13:01 -0700263 if (candidate_urls_.size() == 0) {
264 // This means we got this error even before we got a valid Omaha response
265 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800266 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800267 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
268 return;
269 }
270
David Zeuthen96197df2014-04-16 12:22:39 -0700271 switch (attempt_type_) {
272 case AttemptType::kUpdate:
273 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700274 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700275 break;
276
277 case AttemptType::kRollback:
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700278 system_state_->metrics_reporter()->ReportRollbackMetrics(
279 metrics::RollbackResult::kFailed);
David Zeuthen96197df2014-04-16 12:22:39 -0700280 break;
281 }
David Zeuthen33bae492014-02-25 16:16:18 -0800282
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800283 switch (base_error) {
284 // Errors which are good indicators of a problem with a particular URL or
285 // the protocol used in the URL or entities in the communication channel
286 // (e.g. proxies). We should try the next available URL in the next update
287 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700288 case ErrorCode::kPayloadHashMismatchError:
289 case ErrorCode::kPayloadSizeMismatchError:
290 case ErrorCode::kDownloadPayloadVerificationError:
291 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
292 case ErrorCode::kSignedDeltaPayloadExpectedError:
293 case ErrorCode::kDownloadInvalidMetadataMagicString:
294 case ErrorCode::kDownloadSignatureMissingInManifest:
295 case ErrorCode::kDownloadManifestParseError:
296 case ErrorCode::kDownloadMetadataSignatureError:
297 case ErrorCode::kDownloadMetadataSignatureVerificationError:
298 case ErrorCode::kDownloadMetadataSignatureMismatch:
299 case ErrorCode::kDownloadOperationHashVerificationError:
300 case ErrorCode::kDownloadOperationExecutionError:
301 case ErrorCode::kDownloadOperationHashMismatch:
302 case ErrorCode::kDownloadInvalidMetadataSize:
303 case ErrorCode::kDownloadInvalidMetadataSignature:
304 case ErrorCode::kDownloadOperationHashMissingError:
305 case ErrorCode::kDownloadMetadataSignatureMissingError:
306 case ErrorCode::kPayloadMismatchedType:
307 case ErrorCode::kUnsupportedMajorPayloadVersion:
308 case ErrorCode::kUnsupportedMinorPayloadVersion:
Sen Jiang8e768e92017-06-28 17:13:19 -0700309 case ErrorCode::kPayloadTimestampError:
Sen Jiang57f91802017-11-14 17:42:13 -0800310 case ErrorCode::kVerityCalculationError:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800311 IncrementUrlIndex();
312 break;
313
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800314 // Errors which seem to be just transient network/communication related
315 // failures and do not indicate any inherent problem with the URL itself.
316 // So, we should keep the current URL but just increment the
317 // failure count to give it more chances. This way, while we maximize our
318 // chances of downloading from the URLs that appear earlier in the
319 // response (because download from a local server URL that appears earlier
320 // in a response is preferable than downloading from the next URL which
321 // could be a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700322
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700323 case ErrorCode::kError:
324 case ErrorCode::kDownloadTransferError:
325 case ErrorCode::kDownloadWriteError:
326 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700327 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800328 IncrementFailureCount();
329 break;
330
331 // Errors which are not specific to a URL and hence shouldn't result in
332 // the URL being penalized. This can happen in two cases:
333 // 1. We haven't started downloading anything: These errors don't cost us
334 // anything in terms of actual payload bytes, so we should just do the
335 // regular retries at the next update check.
336 // 2. We have successfully downloaded the payload: In this case, the
337 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800338 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800339 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700340 case ErrorCode::kOmahaRequestError:
341 case ErrorCode::kOmahaResponseHandlerError:
342 case ErrorCode::kPostinstallRunnerError:
343 case ErrorCode::kFilesystemCopierError:
344 case ErrorCode::kInstallDeviceOpenError:
345 case ErrorCode::kKernelDeviceOpenError:
346 case ErrorCode::kDownloadNewPartitionInfoError:
347 case ErrorCode::kNewRootfsVerificationError:
348 case ErrorCode::kNewKernelVerificationError:
349 case ErrorCode::kPostinstallBootedFromFirmwareB:
350 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
351 case ErrorCode::kOmahaRequestEmptyResponseError:
352 case ErrorCode::kOmahaRequestXMLParseError:
353 case ErrorCode::kOmahaResponseInvalid:
354 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
355 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700356 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700357 case ErrorCode::kOmahaUpdateDeferredForBackoff:
358 case ErrorCode::kPostinstallPowerwashError:
359 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400360 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700361 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800362 case ErrorCode::kUserCanceled:
Weidong Guo421ff332017-04-17 10:08:38 -0700363 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
Sen Jiangfe522822017-10-31 15:14:11 -0700364 case ErrorCode::kUpdatedButNotActive:
Sen Jiang89e24c12018-03-22 18:05:44 -0700365 case ErrorCode::kNoUpdate:
Marton Hunyady199152d2018-05-07 19:08:48 +0200366 case ErrorCode::kRollbackNotPossible:
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700367 case ErrorCode::kFirstActiveOmahaPingSentPersistenceError:
Yifan Hongf6c805a2019-12-13 11:50:43 -0800368 case ErrorCode::kInternalLibCurlError:
369 case ErrorCode::kUnresolvedHostError:
370 case ErrorCode::kUnresolvedHostRecovered:
Yifan Hong46e37d42019-12-13 12:01:42 -0800371 case ErrorCode::kNotEnoughSpace:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800372 LOG(INFO) << "Not incrementing URL index or failure count for this error";
373 break;
374
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800375 case ErrorCode::kSuccess: // success code
376 case ErrorCode::kUmaReportedMax: // not an error code
377 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
378 case ErrorCode::kDevModeFlag: // not an error code
379 case ErrorCode::kResumedFlag: // not an error code
380 case ErrorCode::kTestImageFlag: // not an error code
381 case ErrorCode::kTestOmahaUrlFlag: // not an error code
382 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800383 // These shouldn't happen. Enumerating these explicitly here so that we
384 // can let the compiler warn about new error codes that are added to
385 // action_processor.h but not added here.
386 LOG(WARNING) << "Unexpected error code for UpdateFailed";
387 break;
388
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800389 // Note: Not adding a default here so as to let the compiler warn us of
390 // any new enums that were added in the .h but not listed in this switch.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800391 }
392}
393
Jay Srinivasan08262882012-12-28 19:29:43 -0800394bool PayloadState::ShouldBackoffDownload() {
395 if (response_.disable_payload_backoff) {
396 LOG(INFO) << "Payload backoff logic is disabled. "
397 "Can proceed with the download";
398 return false;
399 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700400 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700401 LOG(INFO) << "Payload backoff logic is disabled because download "
402 << "will happen from local peer (via p2p).";
403 return false;
404 }
405 if (system_state_->request_params()->interactive()) {
406 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
407 return false;
408 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700409 for (const auto& package : response_.packages) {
410 if (package.is_delta) {
411 // If delta payloads fail, we want to fallback quickly to full payloads as
412 // they are more likely to succeed. Exponential backoffs would greatly
413 // slow down the fallback to full payloads. So we don't backoff for delta
414 // payloads.
415 LOG(INFO) << "No backoffs for delta payloads. "
416 << "Can proceed with the download";
417 return false;
418 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800419 }
420
Amin Hassaniffb6d802018-03-30 11:43:57 -0700421 if (!system_state_->hardware()->IsOfficialBuild() &&
422 !prefs_->Exists(kPrefsNoIgnoreBackoff)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800423 // Backoffs are needed only for official builds. We do not want any delays
Amin Hassaniffb6d802018-03-30 11:43:57 -0700424 // or update failures due to backoffs during testing or development. Unless
425 // the |kPrefsNoIgnoreBackoff| is manually set.
Jay Srinivasan08262882012-12-28 19:29:43 -0800426 LOG(INFO) << "No backoffs for test/dev images. "
427 << "Can proceed with the download";
428 return false;
429 }
430
431 if (backoff_expiry_time_.is_null()) {
432 LOG(INFO) << "No backoff expiry time has been set. "
433 << "Can proceed with the download";
434 return false;
435 }
436
437 if (backoff_expiry_time_ < Time::Now()) {
438 LOG(INFO) << "The backoff expiry time ("
439 << utils::ToString(backoff_expiry_time_)
440 << ") has elapsed. Can proceed with the download";
441 return false;
442 }
443
444 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
445 << utils::ToString(backoff_expiry_time_);
446 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800447}
448
Chris Sosaaa18e162013-06-20 13:20:30 -0700449void PayloadState::Rollback() {
450 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700451 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700452}
453
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800454void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700455 // Update the payload attempt number for both payload types: full and delta.
456 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
457}
458
459void PayloadState::IncrementFullPayloadAttemptNumber() {
460 // Update the payload attempt number for full payloads and the backoff time.
Sen Jiangcdd52062017-05-18 15:33:10 -0700461 if (response_.packages[payload_index_].is_delta) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800462 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
463 return;
464 }
465
Alex Deymo29b51d92013-07-09 15:26:24 -0700466 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700467 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800468 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800469}
470
471void PayloadState::IncrementUrlIndex() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800472 size_t next_url_index = url_index_ + 1;
473 size_t max_url_size = 0;
474 for (const auto& urls : candidate_urls_)
475 max_url_size = std::max(max_url_size, urls.size());
476 if (next_url_index < max_url_size) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800477 LOG(INFO) << "Incrementing the URL index for next attempt";
478 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800479 } else {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800480 LOG(INFO) << "Resetting the current URL index (" << url_index_ << ") to "
481 << "0 as we only have " << max_url_size << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800482 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700483 IncrementPayloadAttemptNumber();
484 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800485 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800486
David Zeuthencc6f9962013-04-18 11:57:24 -0700487 // If we have multiple URLs, record that we just switched to another one
Sen Jiang0affc2c2017-02-10 15:55:05 -0800488 if (max_url_size > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700489 SetUrlSwitchCount(url_switch_count_ + 1);
490
Jay Srinivasan08262882012-12-28 19:29:43 -0800491 // Whenever we update the URL index, we should also clear the URL failure
492 // count so we can start over fresh for the new URL.
493 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800494}
495
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800496void PayloadState::IncrementFailureCount() {
497 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800498 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800499 LOG(INFO) << "Incrementing the URL failure count";
500 SetUrlFailureCount(next_url_failure_count);
501 } else {
502 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
503 << ". Trying next available URL";
504 IncrementUrlIndex();
505 }
506}
507
Jay Srinivasan08262882012-12-28 19:29:43 -0800508void PayloadState::UpdateBackoffExpiryTime() {
509 if (response_.disable_payload_backoff) {
510 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
511 SetBackoffExpiryTime(Time());
512 return;
513 }
514
Alex Deymo820cc702013-06-28 15:43:46 -0700515 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800516 SetBackoffExpiryTime(Time());
517 return;
518 }
519
520 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700521 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800522 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700523 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700524 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800525
526 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
527 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700528 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800529
530 // The number of days is the minimum of 2 raised to (payload_attempt_number
531 // - 1) or kMaxBackoffDays.
532 num_days = min(num_days << power, kMaxBackoffDays);
533
534 // We don't want all retries to happen exactly at the same time when
535 // retrying after backoff. So add some random minutes to fuzz.
536 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800537 TimeDelta next_backoff_interval =
538 TimeDelta::FromDays(num_days) + TimeDelta::FromMinutes(fuzz_minutes);
Jay Srinivasan08262882012-12-28 19:29:43 -0800539 LOG(INFO) << "Incrementing the backoff expiry time by "
540 << utils::FormatTimeDelta(next_backoff_interval);
541 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
542}
543
Jay Srinivasan19409b72013-04-12 19:23:36 -0700544void PayloadState::UpdateCurrentDownloadSource() {
545 current_download_source_ = kNumDownloadSources;
546
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700547 if (using_p2p_for_downloading_) {
548 current_download_source_ = kDownloadSourceHttpPeer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800549 } else if (payload_index_ < candidate_urls_.size() &&
550 candidate_urls_[payload_index_].size() != 0) {
551 const string& current_url = candidate_urls_[payload_index_][GetUrlIndex()];
552 if (base::StartsWith(
553 current_url, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700554 current_download_source_ = kDownloadSourceHttpsServer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800555 } else if (base::StartsWith(current_url,
556 "http://",
Alex Vakulenko0103c362016-01-20 07:56:15 -0800557 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700558 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800559 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700560 }
561
562 LOG(INFO) << "Current download source: "
563 << utils::ToString(current_download_source_);
564}
565
566void PayloadState::UpdateBytesDownloaded(size_t count) {
567 SetCurrentBytesDownloaded(
568 current_download_source_,
569 GetCurrentBytesDownloaded(current_download_source_) + count,
570 false);
571 SetTotalBytesDownloaded(
572 current_download_source_,
573 GetTotalBytesDownloaded(current_download_source_) + count,
574 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800575
576 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700577}
578
David Zeuthen33bae492014-02-25 16:16:18 -0800579PayloadType PayloadState::CalculatePayloadType() {
Sen Jiangcdd52062017-05-18 15:33:10 -0700580 for (const auto& package : response_.packages) {
581 if (package.is_delta) {
582 return kPayloadTypeDelta;
583 }
David Zeuthen33bae492014-02-25 16:16:18 -0800584 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700585 OmahaRequestParams* params = system_state_->request_params();
586 if (params->delta_okay()) {
587 return kPayloadTypeFull;
588 }
589 // Full payload, delta was not allowed by request.
590 return kPayloadTypeForcedFull;
David Zeuthen33bae492014-02-25 16:16:18 -0800591}
592
593// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
594// metrics if the attempt ends abnormally, e.g. if the update_engine
595// process crashes or the device is rebooted. See
596// http://crbug.com/357676
597void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
598 int attempt_number = GetPayloadAttemptNumber();
599
600 PayloadType payload_type = CalculatePayloadType();
601
Sen Jiang0affc2c2017-02-10 15:55:05 -0800602 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800603
604 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
605
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800606 ClockInterface* clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700607 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800608 TimeDelta duration_uptime =
609 clock->GetMonotonicTime() - attempt_start_time_monotonic_;
David Zeuthen33bae492014-02-25 16:16:18 -0800610
611 int64_t payload_download_speed_bps = 0;
612 int64_t usec = duration_uptime.InMicroseconds();
613 if (usec > 0) {
614 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
615 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
616 payload_download_speed_bps = static_cast<int64_t>(bps);
617 }
618
619 DownloadSource download_source = current_download_source_;
620
621 metrics::DownloadErrorCode payload_download_error_code =
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800622 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700623 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800624 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800625
626 // Add additional detail to AttemptResult
627 switch (attempt_result) {
628 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800629 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800630 break;
631
632 case metrics::AttemptResult::kInternalError:
633 internal_error_code = code;
634 break;
635
636 // Explicit fall-through for cases where we do not have additional
637 // detail. We avoid the default keyword to force people adding new
638 // AttemptResult values to visit this code and examine whether
639 // additional detail is needed.
640 case metrics::AttemptResult::kUpdateSucceeded:
641 case metrics::AttemptResult::kMetadataMalformed:
642 case metrics::AttemptResult::kOperationMalformed:
643 case metrics::AttemptResult::kOperationExecutionError:
644 case metrics::AttemptResult::kMetadataVerificationFailed:
645 case metrics::AttemptResult::kPayloadVerificationFailed:
646 case metrics::AttemptResult::kVerificationFailed:
647 case metrics::AttemptResult::kPostInstallFailed:
648 case metrics::AttemptResult::kAbnormalTermination:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800649 case metrics::AttemptResult::kUpdateCanceled:
Sen Jiangfe522822017-10-31 15:14:11 -0700650 case metrics::AttemptResult::kUpdateSucceededNotActive:
David Zeuthen33bae492014-02-25 16:16:18 -0800651 case metrics::AttemptResult::kNumConstants:
652 case metrics::AttemptResult::kUnset:
653 break;
654 }
655
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700656 system_state_->metrics_reporter()->ReportUpdateAttemptMetrics(
657 system_state_,
658 attempt_number,
659 payload_type,
660 duration,
661 duration_uptime,
662 payload_size,
Tianjie Xu1f93d092017-10-09 12:13:29 -0700663 attempt_result,
664 internal_error_code);
665
666 system_state_->metrics_reporter()->ReportUpdateAttemptDownloadMetrics(
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700667 payload_bytes_downloaded,
668 payload_download_speed_bps,
669 download_source,
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700670 payload_download_error_code,
671 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800672}
673
David Zeuthen4e1d1492014-04-25 13:12:27 -0700674void PayloadState::PersistAttemptMetrics() {
675 // TODO(zeuthen): For now we only persist whether an attempt was in
676 // progress and not values/metrics related to the attempt. This
677 // means that when this happens, of all the UpdateEngine.Attempt.*
678 // metrics, only UpdateEngine.Attempt.Result is reported (with the
679 // value |kAbnormalTermination|). In the future we might want to
680 // persist more data so we can report other metrics in the
681 // UpdateEngine.Attempt.* namespace when this happens.
682 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
683}
684
685void PayloadState::ClearPersistedAttemptMetrics() {
686 prefs_->Delete(kPrefsAttemptInProgress);
687}
688
689void PayloadState::ReportAndClearPersistedAttemptMetrics() {
690 bool attempt_in_progress = false;
691 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
692 return;
693 if (!attempt_in_progress)
694 return;
695
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700696 system_state_->metrics_reporter()
697 ->ReportAbnormallyTerminatedUpdateAttemptMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700698
699 ClearPersistedAttemptMetrics();
700}
701
David Zeuthen33bae492014-02-25 16:16:18 -0800702void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700703 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800704
705 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800706 int64_t total_bytes_by_source[kNumDownloadSources];
707 int64_t successful_bytes = 0;
708 int64_t total_bytes = 0;
709 int64_t successful_mbs = 0;
710 int64_t total_mbs = 0;
711
Jay Srinivasan19409b72013-04-12 19:23:36 -0700712 for (int i = 0; i < kNumDownloadSources; i++) {
713 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800714 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700715
David Zeuthen44848602013-06-24 13:32:14 -0700716 // Only consider this download source (and send byte counts) as
717 // having been used if we downloaded a non-trivial amount of bytes
718 // (e.g. at least 1 MiB) that contributed to the final success of
719 // the update. Otherwise we're going to end up with a lot of
720 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700721
David Zeuthen33bae492014-02-25 16:16:18 -0800722 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800723 successful_bytes += bytes;
724 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700725 SetCurrentBytesDownloaded(source, 0, true);
726
David Zeuthen33bae492014-02-25 16:16:18 -0800727 bytes = GetTotalBytesDownloaded(source);
728 total_bytes_by_source[i] = bytes;
729 total_bytes += bytes;
730 total_mbs += bytes / kNumBytesInOneMiB;
731 SetTotalBytesDownloaded(source, 0, true);
732 }
733
734 int download_overhead_percentage = 0;
735 if (successful_bytes > 0) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800736 download_overhead_percentage =
737 (total_bytes - successful_bytes) * 100ULL / successful_bytes;
David Zeuthen33bae492014-02-25 16:16:18 -0800738 }
739
740 int url_switch_count = static_cast<int>(url_switch_count_);
741
742 int reboot_count = GetNumReboots();
743
744 SetNumReboots(0);
745
746 TimeDelta duration = GetUpdateDuration();
Sen Jiang8712e962018-05-08 12:12:28 -0700747 TimeDelta duration_uptime = GetUpdateDurationUptime();
David Zeuthen33bae492014-02-25 16:16:18 -0800748
749 prefs_->Delete(kPrefsUpdateTimestampStart);
750 prefs_->Delete(kPrefsUpdateDurationUptime);
751
752 PayloadType payload_type = CalculatePayloadType();
753
Sen Jiang0affc2c2017-02-10 15:55:05 -0800754 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800755
756 int attempt_count = GetPayloadAttemptNumber();
757
758 int updates_abandoned_count = num_responses_seen_ - 1;
759
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700760 system_state_->metrics_reporter()->ReportSuccessfulUpdateMetrics(
761 attempt_count,
762 updates_abandoned_count,
763 payload_type,
764 payload_size,
765 total_bytes_by_source,
766 download_overhead_percentage,
767 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700768 duration_uptime,
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700769 reboot_count,
770 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700771}
772
773void PayloadState::UpdateNumReboots() {
774 // We only update the reboot count when the system has been detected to have
775 // been rebooted.
776 if (!system_state_->system_rebooted()) {
777 return;
778 }
779
780 SetNumReboots(GetNumReboots() + 1);
781}
782
783void PayloadState::SetNumReboots(uint32_t num_reboots) {
Chris Sosabe45bef2013-04-09 18:25:12 -0700784 num_reboots_ = num_reboots;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700785 metrics_utils::SetNumReboots(num_reboots, prefs_);
Chris Sosabe45bef2013-04-09 18:25:12 -0700786}
787
Jay Srinivasan08262882012-12-28 19:29:43 -0800788void PayloadState::ResetPersistedState() {
789 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700790 SetFullPayloadAttemptNumber(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700791 SetPayloadIndex(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800792 SetUrlIndex(0);
793 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700794 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700795 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700796 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700797 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700798 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700799 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700800 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700801 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700802 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700803 SetScatteringWaitPeriod(TimeDelta());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700804 SetStagingWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700805}
806
807void PayloadState::ResetRollbackVersion() {
808 CHECK(powerwash_safe_prefs_);
809 rollback_version_ = "";
810 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700811}
812
813void PayloadState::ResetDownloadSourcesOnNewUpdate() {
814 for (int i = 0; i < kNumDownloadSources; i++) {
815 DownloadSource source = static_cast<DownloadSource>(i);
816 SetCurrentBytesDownloaded(source, 0, true);
817 // Note: Not resetting the TotalBytesDownloaded as we want that metric
818 // to count the bytes downloaded across various update attempts until
819 // we have successfully applied the update.
820 }
821}
822
Jay Srinivasan08262882012-12-28 19:29:43 -0800823string PayloadState::CalculateResponseSignature() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800824 string response_sign;
825 for (size_t i = 0; i < response_.packages.size(); i++) {
826 const auto& package = response_.packages[i];
827 response_sign += base::StringPrintf(
828 "Payload %zu:\n"
829 " Size = %ju\n"
830 " Sha256 Hash = %s\n"
831 " Metadata Size = %ju\n"
832 " Metadata Signature = %s\n"
Sen Jiangcdd52062017-05-18 15:33:10 -0700833 " Is Delta = %d\n"
Sen Jiang0affc2c2017-02-10 15:55:05 -0800834 " NumURLs = %zu\n",
835 i,
836 static_cast<uintmax_t>(package.size),
837 package.hash.c_str(),
838 static_cast<uintmax_t>(package.metadata_size),
839 package.metadata_signature.c_str(),
Sen Jiangcdd52062017-05-18 15:33:10 -0700840 package.is_delta,
Sen Jiang0affc2c2017-02-10 15:55:05 -0800841 candidate_urls_[i].size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800842
Sen Jiang0affc2c2017-02-10 15:55:05 -0800843 for (size_t j = 0; j < candidate_urls_[i].size(); j++)
844 response_sign += base::StringPrintf(
845 " Candidate Url%zu = %s\n", j, candidate_urls_[i][j].c_str());
846 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800847
Alex Vakulenko75039d72014-03-25 12:36:28 -0700848 response_sign += base::StringPrintf(
Alex Vakulenko75039d72014-03-25 12:36:28 -0700849 "Max Failure Count Per Url = %d\n"
850 "Disable Payload Backoff = %d\n",
Alex Vakulenko75039d72014-03-25 12:36:28 -0700851 response_.max_failure_count_per_url,
852 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800853 return response_sign;
854}
855
856void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800857 CHECK(prefs_);
858 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800859 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
860 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
861 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800862 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800863}
864
Jay Srinivasan19409b72013-04-12 19:23:36 -0700865void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800866 CHECK(prefs_);
867 response_signature_ = response_signature;
868 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
869 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
870}
871
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800872void PayloadState::LoadPayloadAttemptNumber() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700873 SetPayloadAttemptNumber(
874 GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800875}
876
Alex Deymo820cc702013-06-28 15:43:46 -0700877void PayloadState::LoadFullPayloadAttemptNumber() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700878 SetFullPayloadAttemptNumber(
879 GetPersistedValue(kPrefsFullPayloadAttemptNumber, prefs_));
Alex Deymo820cc702013-06-28 15:43:46 -0700880}
881
882void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800883 payload_attempt_number_ = payload_attempt_number;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700884 metrics_utils::SetPayloadAttemptNumber(payload_attempt_number, prefs_);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800885}
886
Alex Deymo820cc702013-06-28 15:43:46 -0700887void PayloadState::SetFullPayloadAttemptNumber(
888 int full_payload_attempt_number) {
889 CHECK(prefs_);
890 full_payload_attempt_number_ = full_payload_attempt_number;
891 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
892 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800893 full_payload_attempt_number_);
Alex Deymo820cc702013-06-28 15:43:46 -0700894}
895
Sen Jiang5ae865b2017-04-18 14:24:40 -0700896void PayloadState::SetPayloadIndex(size_t payload_index) {
897 CHECK(prefs_);
898 payload_index_ = payload_index;
899 LOG(INFO) << "Payload Index = " << payload_index_;
900 prefs_->SetInt64(kPrefsUpdateStatePayloadIndex, payload_index_);
901}
902
903bool PayloadState::NextPayload() {
904 if (payload_index_ + 1 >= candidate_urls_.size())
905 return false;
906 SetPayloadIndex(payload_index_ + 1);
907 return true;
908}
909
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800910void PayloadState::LoadUrlIndex() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700911 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex, prefs_));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800912}
913
914void PayloadState::SetUrlIndex(uint32_t url_index) {
915 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800916 url_index_ = url_index;
917 LOG(INFO) << "Current URL Index = " << url_index_;
918 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700919
920 // Also update the download source, which is purely dependent on the
921 // current URL index alone.
922 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800923}
924
Gilad Arnold519cfc72014-10-02 10:34:54 -0700925void PayloadState::LoadScatteringWaitPeriod() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700926 SetScatteringWaitPeriod(TimeDelta::FromSeconds(
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700927 GetPersistedValue(kPrefsWallClockScatteringWaitPeriod, prefs_)));
Gilad Arnold519cfc72014-10-02 10:34:54 -0700928}
929
Alex Deymof329b932014-10-30 01:37:48 -0700930void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700931 CHECK(prefs_);
932 scattering_wait_period_ = wait_period;
933 LOG(INFO) << "Scattering Wait Period (seconds) = "
934 << scattering_wait_period_.InSeconds();
935 if (scattering_wait_period_.InSeconds() > 0) {
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700936 prefs_->SetInt64(kPrefsWallClockScatteringWaitPeriod,
Gilad Arnold519cfc72014-10-02 10:34:54 -0700937 scattering_wait_period_.InSeconds());
938 } else {
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700939 prefs_->Delete(kPrefsWallClockScatteringWaitPeriod);
940 }
941}
942
943void PayloadState::LoadStagingWaitPeriod() {
944 SetStagingWaitPeriod(TimeDelta::FromSeconds(
945 GetPersistedValue(kPrefsWallClockStagingWaitPeriod, prefs_)));
946}
947
948void PayloadState::SetStagingWaitPeriod(TimeDelta wait_period) {
949 CHECK(prefs_);
950 staging_wait_period_ = wait_period;
951 LOG(INFO) << "Staging Wait Period (days) =" << staging_wait_period_.InDays();
952 if (staging_wait_period_.InSeconds() > 0) {
953 prefs_->SetInt64(kPrefsWallClockStagingWaitPeriod,
954 staging_wait_period_.InSeconds());
955 } else {
956 prefs_->Delete(kPrefsWallClockStagingWaitPeriod);
Gilad Arnold519cfc72014-10-02 10:34:54 -0700957 }
958}
959
David Zeuthencc6f9962013-04-18 11:57:24 -0700960void PayloadState::LoadUrlSwitchCount() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700961 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount, prefs_));
David Zeuthencc6f9962013-04-18 11:57:24 -0700962}
963
964void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
965 CHECK(prefs_);
966 url_switch_count_ = url_switch_count;
967 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
968 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
969}
970
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800971void PayloadState::LoadUrlFailureCount() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700972 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount, prefs_));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800973}
974
975void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
976 CHECK(prefs_);
977 url_failure_count_ = url_failure_count;
978 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
979 << ")'s Failure Count = " << url_failure_count_;
980 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800981}
982
Jay Srinivasan08262882012-12-28 19:29:43 -0800983void PayloadState::LoadBackoffExpiryTime() {
984 CHECK(prefs_);
985 int64_t stored_value;
986 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
987 return;
988
989 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
990 return;
991
992 Time stored_time = Time::FromInternalValue(stored_value);
993 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
994 LOG(ERROR) << "Invalid backoff expiry time ("
995 << utils::ToString(stored_time)
996 << ") in persisted state. Resetting.";
997 stored_time = Time();
998 }
999 SetBackoffExpiryTime(stored_time);
1000}
1001
1002void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
1003 CHECK(prefs_);
1004 backoff_expiry_time_ = new_time;
1005 LOG(INFO) << "Backoff Expiry Time = "
1006 << utils::ToString(backoff_expiry_time_);
1007 prefs_->SetInt64(kPrefsBackoffExpiryTime,
1008 backoff_expiry_time_.ToInternalValue());
1009}
1010
David Zeuthen9a017f22013-04-11 16:10:26 -07001011TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001012 Time end_time = update_timestamp_end_.is_null()
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001013 ? system_state_->clock()->GetWallclockTime()
1014 : update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001015 return end_time - update_timestamp_start_;
1016}
1017
1018void PayloadState::LoadUpdateTimestampStart() {
1019 int64_t stored_value;
1020 Time stored_time;
1021
1022 CHECK(prefs_);
1023
David Zeuthenf413fe52013-04-22 14:04:39 -07001024 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001025
1026 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1027 // The preference missing is not unexpected - in that case, just
1028 // use the current time as start time
1029 stored_time = now;
1030 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1031 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1032 stored_time = now;
1033 } else {
1034 stored_time = Time::FromInternalValue(stored_value);
1035 }
1036
1037 // Sanity check: If the time read from disk is in the future
1038 // (modulo some slack to account for possible NTP drift
1039 // adjustments), something is fishy and we should report and
1040 // reset.
1041 TimeDelta duration_according_to_stored_time = now - stored_time;
1042 if (duration_according_to_stored_time < -kDurationSlack) {
1043 LOG(ERROR) << "The UpdateTimestampStart value ("
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001044 << utils::ToString(stored_time) << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001045 << utils::FormatTimeDelta(duration_according_to_stored_time)
1046 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001047 stored_time = now;
1048 }
1049
1050 SetUpdateTimestampStart(stored_time);
1051}
1052
1053void PayloadState::SetUpdateTimestampStart(const Time& value) {
David Zeuthen9a017f22013-04-11 16:10:26 -07001054 update_timestamp_start_ = value;
Tianjie Xu90aaa102017-10-10 17:39:03 -07001055 metrics_utils::SetUpdateTimestampStart(value, prefs_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001056}
1057
1058void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1059 update_timestamp_end_ = value;
1060 LOG(INFO) << "Update Timestamp End = "
1061 << utils::ToString(update_timestamp_end_);
1062}
1063
1064TimeDelta PayloadState::GetUpdateDurationUptime() {
1065 return update_duration_uptime_;
1066}
1067
1068void PayloadState::LoadUpdateDurationUptime() {
1069 int64_t stored_value;
1070 TimeDelta stored_delta;
1071
1072 CHECK(prefs_);
1073
1074 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1075 // The preference missing is not unexpected - in that case, just
1076 // we'll use zero as the delta
1077 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1078 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1079 stored_delta = TimeDelta::FromSeconds(0);
1080 } else {
1081 stored_delta = TimeDelta::FromInternalValue(stored_value);
1082 }
1083
1084 // Sanity-check: Uptime can never be greater than the wall-clock
1085 // difference (modulo some slack). If it is, report and reset
1086 // to the wall-clock difference.
1087 TimeDelta diff = GetUpdateDuration() - stored_delta;
1088 if (diff < -kDurationSlack) {
1089 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001090 << utils::FormatTimeDelta(stored_delta)
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001091 << ") in persisted state is " << utils::FormatTimeDelta(diff)
David Zeuthen674c3182013-04-18 14:05:20 -07001092 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001093 stored_delta = update_duration_current_;
1094 }
1095
1096 SetUpdateDurationUptime(stored_delta);
1097}
1098
Chris Sosabe45bef2013-04-09 18:25:12 -07001099void PayloadState::LoadNumReboots() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001100 SetNumReboots(GetPersistedValue(kPrefsNumReboots, prefs_));
Chris Sosaaa18e162013-06-20 13:20:30 -07001101}
1102
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001103void PayloadState::LoadRollbackHappened() {
1104 CHECK(powerwash_safe_prefs_);
1105 bool rollback_happened = false;
1106 powerwash_safe_prefs_->GetBoolean(kPrefsRollbackHappened, &rollback_happened);
1107 SetRollbackHappened(rollback_happened);
1108}
1109
1110void PayloadState::SetRollbackHappened(bool rollback_happened) {
1111 CHECK(powerwash_safe_prefs_);
1112 LOG(INFO) << "Setting rollback-happened to " << rollback_happened << ".";
1113 rollback_happened_ = rollback_happened;
1114 if (rollback_happened) {
1115 powerwash_safe_prefs_->SetBoolean(kPrefsRollbackHappened,
1116 rollback_happened);
1117 } else {
1118 powerwash_safe_prefs_->Delete(kPrefsRollbackHappened);
1119 }
1120}
1121
Chris Sosaaa18e162013-06-20 13:20:30 -07001122void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001123 CHECK(powerwash_safe_prefs_);
1124 string rollback_version;
1125 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1126 &rollback_version)) {
1127 SetRollbackVersion(rollback_version);
1128 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001129}
1130
1131void PayloadState::SetRollbackVersion(const string& rollback_version) {
1132 CHECK(powerwash_safe_prefs_);
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001133 LOG(INFO) << "Blacklisting version " << rollback_version;
Chris Sosaaa18e162013-06-20 13:20:30 -07001134 rollback_version_ = rollback_version;
1135 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001136}
1137
David Zeuthen9a017f22013-04-11 16:10:26 -07001138void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1139 const Time& timestamp,
1140 bool use_logging) {
1141 CHECK(prefs_);
1142 update_duration_uptime_ = value;
1143 update_duration_uptime_timestamp_ = timestamp;
1144 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1145 update_duration_uptime_.ToInternalValue());
1146 if (use_logging) {
1147 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001148 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001149 }
1150}
1151
1152void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001153 Time now = system_state_->clock()->GetMonotonicTime();
1154 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001155}
1156
1157void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001158 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001159 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
Colin Howes0e452c92018-11-02 13:18:44 -07001160
1161 if (uptime_since_last_update > TimeDelta::FromSeconds(kUptimeResolution)) {
1162 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1163 // We're frequently called so avoid logging this write
1164 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1165 }
David Zeuthen9a017f22013-04-11 16:10:26 -07001166}
1167
Jay Srinivasan19409b72013-04-12 19:23:36 -07001168string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1169 return prefix + "-from-" + utils::ToString(source);
1170}
1171
1172void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1173 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001174 SetCurrentBytesDownloaded(source, GetPersistedValue(key, prefs_), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001175}
1176
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001177void PayloadState::SetCurrentBytesDownloaded(DownloadSource source,
1178 uint64_t current_bytes_downloaded,
1179 bool log) {
Jay Srinivasan19409b72013-04-12 19:23:36 -07001180 CHECK(prefs_);
1181
1182 if (source >= kNumDownloadSources)
1183 return;
1184
1185 // Update the in-memory value.
1186 current_bytes_downloaded_[source] = current_bytes_downloaded;
1187
1188 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1189 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1190 LOG_IF(INFO, log) << "Current bytes downloaded for "
1191 << utils::ToString(source) << " = "
1192 << GetCurrentBytesDownloaded(source);
1193}
1194
1195void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1196 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001197 SetTotalBytesDownloaded(source, GetPersistedValue(key, prefs_), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001198}
1199
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001200void PayloadState::SetTotalBytesDownloaded(DownloadSource source,
1201 uint64_t total_bytes_downloaded,
1202 bool log) {
Jay Srinivasan19409b72013-04-12 19:23:36 -07001203 CHECK(prefs_);
1204
1205 if (source >= kNumDownloadSources)
1206 return;
1207
1208 // Update the in-memory value.
1209 total_bytes_downloaded_[source] = total_bytes_downloaded;
1210
1211 // Persist.
1212 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1213 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001214 LOG_IF(INFO, log) << "Total bytes downloaded for " << utils::ToString(source)
1215 << " = " << GetTotalBytesDownloaded(source);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001216}
1217
David Zeuthena573d6f2013-06-14 16:13:36 -07001218void PayloadState::LoadNumResponsesSeen() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001219 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen, prefs_));
David Zeuthena573d6f2013-06-14 16:13:36 -07001220}
1221
1222void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1223 CHECK(prefs_);
1224 num_responses_seen_ = num_responses_seen;
1225 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1226 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1227}
1228
Jay Srinivasan53173b92013-05-17 17:13:01 -07001229void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001230 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001231
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001232 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001233 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001234 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001235 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1236 } else {
1237 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1238 http_url_ok = true;
1239 }
1240
1241 candidate_urls_.clear();
Sen Jiang0affc2c2017-02-10 15:55:05 -08001242 for (const auto& package : response_.packages) {
1243 candidate_urls_.emplace_back();
1244 for (const string& candidate_url : package.payload_urls) {
1245 if (base::StartsWith(
1246 candidate_url, "http://", base::CompareCase::INSENSITIVE_ASCII) &&
1247 !http_url_ok) {
1248 continue;
1249 }
1250 candidate_urls_.back().push_back(candidate_url);
1251 LOG(INFO) << "Candidate Url" << (candidate_urls_.back().size() - 1)
1252 << ": " << candidate_url;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001253 }
Sen Jiang0affc2c2017-02-10 15:55:05 -08001254 LOG(INFO) << "Found " << candidate_urls_.back().size() << " candidate URLs "
1255 << "out of " << package.payload_urls.size()
1256 << " URLs supplied in package " << candidate_urls_.size() - 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001257 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001258}
1259
David Zeuthene4c58bf2013-06-18 17:26:50 -07001260void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001261 // Flush previous state from abnormal attempt failure, if any.
1262 ReportAndClearPersistedAttemptMetrics();
1263
Alex Deymo569c4242013-07-24 12:01:01 -07001264 // Avoid the UpdateEngineStarted actions if this is not the first time we
1265 // run the update engine since reboot.
1266 if (!system_state_->system_rebooted())
1267 return;
1268
Tianjie Xu90aaa102017-10-10 17:39:03 -07001269 // Report time_to_reboot if we booted into a new update.
1270 metrics_utils::LoadAndReportTimeToReboot(
1271 system_state_->metrics_reporter(), prefs_, system_state_->clock());
1272 prefs_->Delete(kPrefsSystemUpdatedMarker);
1273
Alex Deymo42432912013-07-12 20:21:15 -07001274 // Check if it is needed to send metrics about a failed reboot into a new
1275 // version.
1276 ReportFailedBootIfNeeded();
1277}
1278
1279void PayloadState::ReportFailedBootIfNeeded() {
1280 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1281 // payload was marked as ready immediately before the last reboot, and we
1282 // need to check if such payload successfully rebooted or not.
1283 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001284 int64_t installed_from = 0;
1285 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001286 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1287 return;
1288 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001289 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1290 // partition number. We are now using slot numbers (0 or 1) instead, so
1291 // the following comparison will not match if we are comparing an old
1292 // partition number against a new slot number, which is the correct outcome
1293 // since we successfully booted the new update in that case. If the boot
1294 // failed, we will read this value from the same version, so it will always
1295 // be compatible.
1296 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001297 // A reboot was pending, but the chromebook is again in the same
1298 // BootDevice where the update was installed from.
1299 int64_t target_attempt;
1300 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1301 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1302 "TargetVersionInstalledFrom was present.";
1303 target_attempt = 1;
1304 }
1305
1306 // Report the UMA metric of the current boot failure.
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001307 system_state_->metrics_reporter()->ReportFailedUpdateCount(
1308 target_attempt);
Alex Deymo42432912013-07-12 20:21:15 -07001309 } else {
1310 prefs_->Delete(kPrefsTargetVersionAttempt);
1311 prefs_->Delete(kPrefsTargetVersionUniqueId);
1312 }
1313 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1314 }
1315}
1316
1317void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1318 // Expect to boot into the new partition in the next reboot setting the
1319 // TargetVersion* flags in the Prefs.
1320 string stored_target_version_uid;
1321 string target_version_id;
1322 string target_partition;
1323 int64_t target_attempt;
1324
1325 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1326 prefs_->GetString(kPrefsTargetVersionUniqueId,
1327 &stored_target_version_uid) &&
1328 stored_target_version_uid == target_version_uid) {
1329 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1330 target_attempt = 0;
1331 } else {
1332 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1333 target_attempt = 0;
1334 }
1335 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1336
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001337 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001338 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001339}
1340
1341void PayloadState::ResetUpdateStatus() {
1342 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1343 // rebooted the next boot is not flagged as failed to rebooted into the
1344 // new applied payload.
1345 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1346
1347 // Also decrement the attempt number if it exists.
1348 int64_t target_attempt;
1349 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001350 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001351}
1352
David Zeuthendcba8092013-08-06 12:16:35 -07001353int PayloadState::GetP2PNumAttempts() {
1354 return p2p_num_attempts_;
1355}
1356
1357void PayloadState::SetP2PNumAttempts(int value) {
1358 p2p_num_attempts_ = value;
1359 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1360 CHECK(prefs_);
1361 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1362}
1363
1364void PayloadState::LoadP2PNumAttempts() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001365 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts, prefs_));
David Zeuthendcba8092013-08-06 12:16:35 -07001366}
1367
1368Time PayloadState::GetP2PFirstAttemptTimestamp() {
1369 return p2p_first_attempt_timestamp_;
1370}
1371
1372void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1373 p2p_first_attempt_timestamp_ = time;
1374 LOG(INFO) << "p2p First Attempt Timestamp = "
1375 << utils::ToString(p2p_first_attempt_timestamp_);
1376 CHECK(prefs_);
1377 int64_t stored_value = time.ToInternalValue();
1378 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1379}
1380
1381void PayloadState::LoadP2PFirstAttemptTimestamp() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001382 int64_t stored_value =
1383 GetPersistedValue(kPrefsP2PFirstAttemptTimestamp, prefs_);
David Zeuthendcba8092013-08-06 12:16:35 -07001384 Time stored_time = Time::FromInternalValue(stored_value);
1385 SetP2PFirstAttemptTimestamp(stored_time);
1386}
1387
1388void PayloadState::P2PNewAttempt() {
1389 CHECK(prefs_);
1390 // Set timestamp, if it hasn't been set already
1391 if (p2p_first_attempt_timestamp_.is_null()) {
1392 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1393 }
1394 // Increase number of attempts
1395 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1396}
1397
1398bool PayloadState::P2PAttemptAllowed() {
1399 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1400 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001401 << " which is greater than " << kMaxP2PAttempts
David Zeuthendcba8092013-08-06 12:16:35 -07001402 << " - disallowing p2p.";
1403 return false;
1404 }
1405
1406 if (!p2p_first_attempt_timestamp_.is_null()) {
1407 Time now = system_state_->clock()->GetWallclockTime();
1408 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1409 if (time_spent_attempting_p2p.InSeconds() < 0) {
1410 LOG(ERROR) << "Time spent attempting p2p is negative"
1411 << " - disallowing p2p.";
1412 return false;
1413 }
1414 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1415 LOG(INFO) << "Time spent attempting p2p is "
1416 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1417 << " which is greater than "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001418 << utils::FormatTimeDelta(
1419 TimeDelta::FromSeconds(kMaxP2PAttemptTimeSeconds))
David Zeuthendcba8092013-08-06 12:16:35 -07001420 << " - disallowing p2p.";
1421 return false;
1422 }
1423 }
1424
1425 return true;
1426}
1427
Sen Jiang0affc2c2017-02-10 15:55:05 -08001428int64_t PayloadState::GetPayloadSize() {
1429 int64_t payload_size = 0;
1430 for (const auto& package : response_.packages)
1431 payload_size += package.size;
1432 return payload_size;
1433}
1434
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001435} // namespace chromeos_update_engine