blob: 36f120a51a91b878bda16565286e44d36e0b1901 [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
Jay Srinivasan19409b72013-04-12 19:23:36 -070058PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070059 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070060 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070061 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070062 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070063 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070064 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070065 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070066 url_switch_count_(0),
Marton Hunyadye58bddb2018-04-10 20:27:26 +020067 rollback_happened_(false),
David Zeuthenafed4a12014-04-09 15:28:44 -070068 attempt_num_bytes_downloaded_(0),
69 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070070 attempt_type_(AttemptType::kUpdate) {
71 for (int i = 0; i <= kNumDownloadSources; i++)
72 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070073}
74
75bool PayloadState::Initialize(SystemState* system_state) {
76 system_state_ = system_state;
77 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070078 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080079 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080080 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070081 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080082 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080083 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070084 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080085 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070086 LoadUpdateTimestampStart();
87 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
88 // being called before it. Don't reorder.
89 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070090 for (int i = 0; i < kNumDownloadSources; i++) {
91 DownloadSource source = static_cast<DownloadSource>(i);
92 LoadCurrentBytesDownloaded(source);
93 LoadTotalBytesDownloaded(source);
94 }
Chris Sosabe45bef2013-04-09 18:25:12 -070095 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070096 LoadNumResponsesSeen();
Marton Hunyadye58bddb2018-04-10 20:27:26 +020097 LoadRollbackHappened();
Chris Sosaaa18e162013-06-20 13:20:30 -070098 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070099 LoadP2PFirstAttemptTimestamp();
100 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800101 return true;
102}
103
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800104void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800105 // Always store the latest response.
106 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800107
Jay Srinivasan53173b92013-05-17 17:13:01 -0700108 // Compute the candidate URLs first as they are used to calculate the
109 // response signature so that a change in enterprise policy for
110 // HTTP downloads being enabled or not could be honored as soon as the
111 // next update check happens.
112 ComputeCandidateUrls();
113
Jay Srinivasan08262882012-12-28 19:29:43 -0800114 // Check if the "signature" of this response (i.e. the fields we care about)
115 // has changed.
116 string new_response_signature = CalculateResponseSignature();
117 bool has_response_changed = (response_signature_ != new_response_signature);
118
119 // If the response has changed, we should persist the new signature and
120 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800121 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800122 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700123 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800124 SetResponseSignature(new_response_signature);
125 ResetPersistedState();
126 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800127 }
128
Sen Jiang97eba342017-05-22 14:34:11 -0700129 // Always start from payload index 0, even for resume, to download partition
130 // info from previous payloads.
131 payload_index_ = 0;
132
Jay Srinivasan08262882012-12-28 19:29:43 -0800133 // This is the earliest point at which we can validate whether the URL index
134 // we loaded from the persisted state is a valid value. If the response
135 // hasn't changed but the URL index is invalid, it's indicative of some
136 // tampering of the persisted state.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800137 if (payload_index_ >= candidate_urls_.size() ||
138 url_index_ >= candidate_urls_[payload_index_].size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800139 LOG(INFO) << "Resetting all payload state as the url index seems to have "
140 "been tampered with";
141 ResetPersistedState();
142 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800143 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700144
145 // Update the current download source which depends on the latest value of
146 // the response.
147 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800148}
149
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700150void PayloadState::SetUsingP2PForDownloading(bool value) {
151 using_p2p_for_downloading_ = value;
152 // Update the current download source which depends on whether we are
153 // using p2p or not.
154 UpdateCurrentDownloadSource();
155}
156
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800157void PayloadState::DownloadComplete() {
158 LOG(INFO) << "Payload downloaded successfully";
159 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700160 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800161}
162
163void PayloadState::DownloadProgress(size_t count) {
164 if (count == 0)
165 return;
166
David Zeuthen9a017f22013-04-11 16:10:26 -0700167 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700168 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700169
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800170 // We've received non-zero bytes from a recent download operation. Since our
171 // URL failure count is meant to penalize a URL only for consecutive
172 // failures, downloading bytes successfully means we should reset the failure
173 // count (as we know at least that the URL is working). In future, we can
174 // design this to be more sophisticated to check for more intelligent failure
175 // patterns, but right now, even 1 byte downloaded will mark the URL to be
176 // good unless it hits 10 (or configured number of) consecutive failures
177 // again.
178
179 if (GetUrlFailureCount() == 0)
180 return;
181
182 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
183 << " to 0 as we received " << count << " bytes successfully";
184 SetUrlFailureCount(0);
185}
186
David Zeuthenafed4a12014-04-09 15:28:44 -0700187void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700188 // Flush previous state from abnormal attempt failure, if any.
189 ReportAndClearPersistedAttemptMetrics();
190
David Zeuthenafed4a12014-04-09 15:28:44 -0700191 attempt_type_ = attempt_type;
192
David Zeuthen33bae492014-02-25 16:16:18 -0800193 ClockInterface *clock = system_state_->clock();
194 attempt_start_time_boot_ = clock->GetBootTime();
195 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800196 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700197
198 metrics::ConnectionType type;
Sen Jiang255e22b2016-05-20 16:15:29 -0700199 ConnectionType network_connection_type;
200 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700201 ConnectionManagerInterface* connection_manager =
202 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700203 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700204 &tethering)) {
205 LOG(ERROR) << "Failed to determine connection type.";
206 type = metrics::ConnectionType::kUnknown;
207 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800208 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700209 }
210 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700211
212 if (attempt_type == AttemptType::kUpdate)
213 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800214}
215
Chris Sosabe45bef2013-04-09 18:25:12 -0700216void PayloadState::UpdateResumed() {
217 LOG(INFO) << "Resuming an update that was previously started.";
218 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700219 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700220}
221
Jay Srinivasan19409b72013-04-12 19:23:36 -0700222void PayloadState::UpdateRestarted() {
223 LOG(INFO) << "Starting a new update";
224 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700225 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700226 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700227}
228
David Zeuthen9a017f22013-04-11 16:10:26 -0700229void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700230 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700231 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700232 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800233
David Zeuthen96197df2014-04-16 12:22:39 -0700234 switch (attempt_type_) {
235 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700236 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700237 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700238 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700239 break;
240
241 case AttemptType::kRollback:
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700242 system_state_->metrics_reporter()->ReportRollbackMetrics(
243 metrics::RollbackResult::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700244 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700245 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700246
247 // Reset the number of responses seen since it counts from the last
248 // successful update, e.g. now.
249 SetNumResponsesSeen(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700250 SetPayloadIndex(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700251
Tianjie Xu90aaa102017-10-10 17:39:03 -0700252 metrics_utils::SetSystemUpdatedMarker(system_state_->clock(), prefs_);
David Zeuthen9a017f22013-04-11 16:10:26 -0700253}
254
David Zeuthena99981f2013-04-29 13:42:47 -0700255void PayloadState::UpdateFailed(ErrorCode error) {
256 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800257 LOG(INFO) << "Updating payload state for error code: " << base_error
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800258 << " (" << utils::ErrorCodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800259
Jay Srinivasan53173b92013-05-17 17:13:01 -0700260 if (candidate_urls_.size() == 0) {
261 // This means we got this error even before we got a valid Omaha response
262 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800263 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800264 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
265 return;
266 }
267
David Zeuthen96197df2014-04-16 12:22:39 -0700268 switch (attempt_type_) {
269 case AttemptType::kUpdate:
270 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700271 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700272 break;
273
274 case AttemptType::kRollback:
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700275 system_state_->metrics_reporter()->ReportRollbackMetrics(
276 metrics::RollbackResult::kFailed);
David Zeuthen96197df2014-04-16 12:22:39 -0700277 break;
278 }
David Zeuthen33bae492014-02-25 16:16:18 -0800279
Shuqian Zhao29971732016-02-05 11:29:32 -0800280
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800281 switch (base_error) {
282 // Errors which are good indicators of a problem with a particular URL or
283 // the protocol used in the URL or entities in the communication channel
284 // (e.g. proxies). We should try the next available URL in the next update
285 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700286 case ErrorCode::kPayloadHashMismatchError:
287 case ErrorCode::kPayloadSizeMismatchError:
288 case ErrorCode::kDownloadPayloadVerificationError:
289 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
290 case ErrorCode::kSignedDeltaPayloadExpectedError:
291 case ErrorCode::kDownloadInvalidMetadataMagicString:
292 case ErrorCode::kDownloadSignatureMissingInManifest:
293 case ErrorCode::kDownloadManifestParseError:
294 case ErrorCode::kDownloadMetadataSignatureError:
295 case ErrorCode::kDownloadMetadataSignatureVerificationError:
296 case ErrorCode::kDownloadMetadataSignatureMismatch:
297 case ErrorCode::kDownloadOperationHashVerificationError:
298 case ErrorCode::kDownloadOperationExecutionError:
299 case ErrorCode::kDownloadOperationHashMismatch:
300 case ErrorCode::kDownloadInvalidMetadataSize:
301 case ErrorCode::kDownloadInvalidMetadataSignature:
302 case ErrorCode::kDownloadOperationHashMissingError:
303 case ErrorCode::kDownloadMetadataSignatureMissingError:
304 case ErrorCode::kPayloadMismatchedType:
305 case ErrorCode::kUnsupportedMajorPayloadVersion:
306 case ErrorCode::kUnsupportedMinorPayloadVersion:
Sen Jiang8e768e92017-06-28 17:13:19 -0700307 case ErrorCode::kPayloadTimestampError:
Sen Jiang57f91802017-11-14 17:42:13 -0800308 case ErrorCode::kVerityCalculationError:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800309 IncrementUrlIndex();
310 break;
311
312 // Errors which seem to be just transient network/communication related
313 // failures and do not indicate any inherent problem with the URL itself.
314 // So, we should keep the current URL but just increment the
315 // failure count to give it more chances. This way, while we maximize our
316 // chances of downloading from the URLs that appear earlier in the response
317 // (because download from a local server URL that appears earlier in a
318 // response is preferable than downloading from the next URL which could be
319 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700320
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700321 case ErrorCode::kError:
322 case ErrorCode::kDownloadTransferError:
323 case ErrorCode::kDownloadWriteError:
324 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700325 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800326 IncrementFailureCount();
327 break;
328
329 // Errors which are not specific to a URL and hence shouldn't result in
330 // the URL being penalized. This can happen in two cases:
331 // 1. We haven't started downloading anything: These errors don't cost us
332 // anything in terms of actual payload bytes, so we should just do the
333 // regular retries at the next update check.
334 // 2. We have successfully downloaded the payload: In this case, the
335 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800336 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800337 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700338 case ErrorCode::kOmahaRequestError:
339 case ErrorCode::kOmahaResponseHandlerError:
340 case ErrorCode::kPostinstallRunnerError:
341 case ErrorCode::kFilesystemCopierError:
342 case ErrorCode::kInstallDeviceOpenError:
343 case ErrorCode::kKernelDeviceOpenError:
344 case ErrorCode::kDownloadNewPartitionInfoError:
345 case ErrorCode::kNewRootfsVerificationError:
346 case ErrorCode::kNewKernelVerificationError:
347 case ErrorCode::kPostinstallBootedFromFirmwareB:
348 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
349 case ErrorCode::kOmahaRequestEmptyResponseError:
350 case ErrorCode::kOmahaRequestXMLParseError:
351 case ErrorCode::kOmahaResponseInvalid:
352 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
353 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700354 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700355 case ErrorCode::kOmahaUpdateDeferredForBackoff:
356 case ErrorCode::kPostinstallPowerwashError:
357 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400358 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700359 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800360 case ErrorCode::kUserCanceled:
Weidong Guo421ff332017-04-17 10:08:38 -0700361 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
Sen Jiangfe522822017-10-31 15:14:11 -0700362 case ErrorCode::kUpdatedButNotActive:
Sen Jiang89e24c12018-03-22 18:05:44 -0700363 case ErrorCode::kNoUpdate:
Marton Hunyady199152d2018-05-07 19:08:48 +0200364 case ErrorCode::kRollbackNotPossible:
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700365 case ErrorCode::kFirstActiveOmahaPingSentPersistenceError:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800366 LOG(INFO) << "Not incrementing URL index or failure count for this error";
367 break;
368
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700369 case ErrorCode::kSuccess: // success code
370 case ErrorCode::kUmaReportedMax: // not an error code
371 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
372 case ErrorCode::kDevModeFlag: // not an error code
373 case ErrorCode::kResumedFlag: // not an error code
374 case ErrorCode::kTestImageFlag: // not an error code
375 case ErrorCode::kTestOmahaUrlFlag: // not an error code
376 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800377 // These shouldn't happen. Enumerating these explicitly here so that we
378 // can let the compiler warn about new error codes that are added to
379 // action_processor.h but not added here.
380 LOG(WARNING) << "Unexpected error code for UpdateFailed";
381 break;
382
383 // Note: Not adding a default here so as to let the compiler warn us of
384 // any new enums that were added in the .h but not listed in this switch.
385 }
386}
387
Jay Srinivasan08262882012-12-28 19:29:43 -0800388bool PayloadState::ShouldBackoffDownload() {
389 if (response_.disable_payload_backoff) {
390 LOG(INFO) << "Payload backoff logic is disabled. "
391 "Can proceed with the download";
392 return false;
393 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700394 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700395 LOG(INFO) << "Payload backoff logic is disabled because download "
396 << "will happen from local peer (via p2p).";
397 return false;
398 }
399 if (system_state_->request_params()->interactive()) {
400 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
401 return false;
402 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700403 for (const auto& package : response_.packages) {
404 if (package.is_delta) {
405 // If delta payloads fail, we want to fallback quickly to full payloads as
406 // they are more likely to succeed. Exponential backoffs would greatly
407 // slow down the fallback to full payloads. So we don't backoff for delta
408 // payloads.
409 LOG(INFO) << "No backoffs for delta payloads. "
410 << "Can proceed with the download";
411 return false;
412 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800413 }
414
Amin Hassaniffb6d802018-03-30 11:43:57 -0700415 if (!system_state_->hardware()->IsOfficialBuild() &&
416 !prefs_->Exists(kPrefsNoIgnoreBackoff)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800417 // Backoffs are needed only for official builds. We do not want any delays
Amin Hassaniffb6d802018-03-30 11:43:57 -0700418 // or update failures due to backoffs during testing or development. Unless
419 // the |kPrefsNoIgnoreBackoff| is manually set.
Jay Srinivasan08262882012-12-28 19:29:43 -0800420 LOG(INFO) << "No backoffs for test/dev images. "
421 << "Can proceed with the download";
422 return false;
423 }
424
425 if (backoff_expiry_time_.is_null()) {
426 LOG(INFO) << "No backoff expiry time has been set. "
427 << "Can proceed with the download";
428 return false;
429 }
430
431 if (backoff_expiry_time_ < Time::Now()) {
432 LOG(INFO) << "The backoff expiry time ("
433 << utils::ToString(backoff_expiry_time_)
434 << ") has elapsed. Can proceed with the download";
435 return false;
436 }
437
438 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
439 << utils::ToString(backoff_expiry_time_);
440 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800441}
442
Chris Sosaaa18e162013-06-20 13:20:30 -0700443void PayloadState::Rollback() {
444 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700445 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700446}
447
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800448void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700449 // Update the payload attempt number for both payload types: full and delta.
450 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
451}
452
453void PayloadState::IncrementFullPayloadAttemptNumber() {
454 // Update the payload attempt number for full payloads and the backoff time.
Sen Jiangcdd52062017-05-18 15:33:10 -0700455 if (response_.packages[payload_index_].is_delta) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800456 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
457 return;
458 }
459
Alex Deymo29b51d92013-07-09 15:26:24 -0700460 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700461 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800462 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800463}
464
465void PayloadState::IncrementUrlIndex() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800466 size_t next_url_index = url_index_ + 1;
467 size_t max_url_size = 0;
468 for (const auto& urls : candidate_urls_)
469 max_url_size = std::max(max_url_size, urls.size());
470 if (next_url_index < max_url_size) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800471 LOG(INFO) << "Incrementing the URL index for next attempt";
472 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800473 } else {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800474 LOG(INFO) << "Resetting the current URL index (" << url_index_ << ") to "
475 << "0 as we only have " << max_url_size << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800476 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700477 IncrementPayloadAttemptNumber();
478 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800479 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800480
David Zeuthencc6f9962013-04-18 11:57:24 -0700481 // If we have multiple URLs, record that we just switched to another one
Sen Jiang0affc2c2017-02-10 15:55:05 -0800482 if (max_url_size > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700483 SetUrlSwitchCount(url_switch_count_ + 1);
484
Jay Srinivasan08262882012-12-28 19:29:43 -0800485 // Whenever we update the URL index, we should also clear the URL failure
486 // count so we can start over fresh for the new URL.
487 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800488}
489
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800490void PayloadState::IncrementFailureCount() {
491 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800492 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800493 LOG(INFO) << "Incrementing the URL failure count";
494 SetUrlFailureCount(next_url_failure_count);
495 } else {
496 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
497 << ". Trying next available URL";
498 IncrementUrlIndex();
499 }
500}
501
Jay Srinivasan08262882012-12-28 19:29:43 -0800502void PayloadState::UpdateBackoffExpiryTime() {
503 if (response_.disable_payload_backoff) {
504 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
505 SetBackoffExpiryTime(Time());
506 return;
507 }
508
Alex Deymo820cc702013-06-28 15:43:46 -0700509 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800510 SetBackoffExpiryTime(Time());
511 return;
512 }
513
514 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700515 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800516 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700517 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700518 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800519
520 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
521 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700522 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800523
524 // The number of days is the minimum of 2 raised to (payload_attempt_number
525 // - 1) or kMaxBackoffDays.
526 num_days = min(num_days << power, kMaxBackoffDays);
527
528 // We don't want all retries to happen exactly at the same time when
529 // retrying after backoff. So add some random minutes to fuzz.
530 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
531 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
532 TimeDelta::FromMinutes(fuzz_minutes);
533 LOG(INFO) << "Incrementing the backoff expiry time by "
534 << utils::FormatTimeDelta(next_backoff_interval);
535 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
536}
537
Jay Srinivasan19409b72013-04-12 19:23:36 -0700538void PayloadState::UpdateCurrentDownloadSource() {
539 current_download_source_ = kNumDownloadSources;
540
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700541 if (using_p2p_for_downloading_) {
542 current_download_source_ = kDownloadSourceHttpPeer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800543 } else if (payload_index_ < candidate_urls_.size() &&
544 candidate_urls_[payload_index_].size() != 0) {
545 const string& current_url = candidate_urls_[payload_index_][GetUrlIndex()];
546 if (base::StartsWith(
547 current_url, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700548 current_download_source_ = kDownloadSourceHttpsServer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800549 } else if (base::StartsWith(current_url,
550 "http://",
Alex Vakulenko0103c362016-01-20 07:56:15 -0800551 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700552 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800553 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700554 }
555
556 LOG(INFO) << "Current download source: "
557 << utils::ToString(current_download_source_);
558}
559
560void PayloadState::UpdateBytesDownloaded(size_t count) {
561 SetCurrentBytesDownloaded(
562 current_download_source_,
563 GetCurrentBytesDownloaded(current_download_source_) + count,
564 false);
565 SetTotalBytesDownloaded(
566 current_download_source_,
567 GetTotalBytesDownloaded(current_download_source_) + count,
568 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800569
570 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700571}
572
David Zeuthen33bae492014-02-25 16:16:18 -0800573PayloadType PayloadState::CalculatePayloadType() {
Sen Jiangcdd52062017-05-18 15:33:10 -0700574 for (const auto& package : response_.packages) {
575 if (package.is_delta) {
576 return kPayloadTypeDelta;
577 }
David Zeuthen33bae492014-02-25 16:16:18 -0800578 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700579 OmahaRequestParams* params = system_state_->request_params();
580 if (params->delta_okay()) {
581 return kPayloadTypeFull;
582 }
583 // Full payload, delta was not allowed by request.
584 return kPayloadTypeForcedFull;
David Zeuthen33bae492014-02-25 16:16:18 -0800585}
586
587// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
588// metrics if the attempt ends abnormally, e.g. if the update_engine
589// process crashes or the device is rebooted. See
590// http://crbug.com/357676
591void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
592 int attempt_number = GetPayloadAttemptNumber();
593
594 PayloadType payload_type = CalculatePayloadType();
595
Sen Jiang0affc2c2017-02-10 15:55:05 -0800596 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800597
598 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
599
600 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700601 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
602 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800603 attempt_start_time_monotonic_;
604
605 int64_t payload_download_speed_bps = 0;
606 int64_t usec = duration_uptime.InMicroseconds();
607 if (usec > 0) {
608 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
609 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
610 payload_download_speed_bps = static_cast<int64_t>(bps);
611 }
612
613 DownloadSource download_source = current_download_source_;
614
615 metrics::DownloadErrorCode payload_download_error_code =
616 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700617 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800618 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800619
620 // Add additional detail to AttemptResult
621 switch (attempt_result) {
622 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800623 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800624 break;
625
626 case metrics::AttemptResult::kInternalError:
627 internal_error_code = code;
628 break;
629
630 // Explicit fall-through for cases where we do not have additional
631 // detail. We avoid the default keyword to force people adding new
632 // AttemptResult values to visit this code and examine whether
633 // additional detail is needed.
634 case metrics::AttemptResult::kUpdateSucceeded:
635 case metrics::AttemptResult::kMetadataMalformed:
636 case metrics::AttemptResult::kOperationMalformed:
637 case metrics::AttemptResult::kOperationExecutionError:
638 case metrics::AttemptResult::kMetadataVerificationFailed:
639 case metrics::AttemptResult::kPayloadVerificationFailed:
640 case metrics::AttemptResult::kVerificationFailed:
641 case metrics::AttemptResult::kPostInstallFailed:
642 case metrics::AttemptResult::kAbnormalTermination:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800643 case metrics::AttemptResult::kUpdateCanceled:
Sen Jiangfe522822017-10-31 15:14:11 -0700644 case metrics::AttemptResult::kUpdateSucceededNotActive:
David Zeuthen33bae492014-02-25 16:16:18 -0800645 case metrics::AttemptResult::kNumConstants:
646 case metrics::AttemptResult::kUnset:
647 break;
648 }
649
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700650 system_state_->metrics_reporter()->ReportUpdateAttemptMetrics(
651 system_state_,
652 attempt_number,
653 payload_type,
654 duration,
655 duration_uptime,
656 payload_size,
Tianjie Xu1f93d092017-10-09 12:13:29 -0700657 attempt_result,
658 internal_error_code);
659
660 system_state_->metrics_reporter()->ReportUpdateAttemptDownloadMetrics(
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700661 payload_bytes_downloaded,
662 payload_download_speed_bps,
663 download_source,
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700664 payload_download_error_code,
665 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800666}
667
David Zeuthen4e1d1492014-04-25 13:12:27 -0700668void PayloadState::PersistAttemptMetrics() {
669 // TODO(zeuthen): For now we only persist whether an attempt was in
670 // progress and not values/metrics related to the attempt. This
671 // means that when this happens, of all the UpdateEngine.Attempt.*
672 // metrics, only UpdateEngine.Attempt.Result is reported (with the
673 // value |kAbnormalTermination|). In the future we might want to
674 // persist more data so we can report other metrics in the
675 // UpdateEngine.Attempt.* namespace when this happens.
676 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
677}
678
679void PayloadState::ClearPersistedAttemptMetrics() {
680 prefs_->Delete(kPrefsAttemptInProgress);
681}
682
683void PayloadState::ReportAndClearPersistedAttemptMetrics() {
684 bool attempt_in_progress = false;
685 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
686 return;
687 if (!attempt_in_progress)
688 return;
689
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700690 system_state_->metrics_reporter()
691 ->ReportAbnormallyTerminatedUpdateAttemptMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700692
693 ClearPersistedAttemptMetrics();
694}
695
David Zeuthen33bae492014-02-25 16:16:18 -0800696void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700697 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800698
699 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800700 int64_t total_bytes_by_source[kNumDownloadSources];
701 int64_t successful_bytes = 0;
702 int64_t total_bytes = 0;
703 int64_t successful_mbs = 0;
704 int64_t total_mbs = 0;
705
Jay Srinivasan19409b72013-04-12 19:23:36 -0700706 for (int i = 0; i < kNumDownloadSources; i++) {
707 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800708 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700709
David Zeuthen44848602013-06-24 13:32:14 -0700710 // Only consider this download source (and send byte counts) as
711 // having been used if we downloaded a non-trivial amount of bytes
712 // (e.g. at least 1 MiB) that contributed to the final success of
713 // the update. Otherwise we're going to end up with a lot of
714 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700715
David Zeuthen33bae492014-02-25 16:16:18 -0800716 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800717 successful_bytes += bytes;
718 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700719 SetCurrentBytesDownloaded(source, 0, true);
720
David Zeuthen33bae492014-02-25 16:16:18 -0800721 bytes = GetTotalBytesDownloaded(source);
722 total_bytes_by_source[i] = bytes;
723 total_bytes += bytes;
724 total_mbs += bytes / kNumBytesInOneMiB;
725 SetTotalBytesDownloaded(source, 0, true);
726 }
727
728 int download_overhead_percentage = 0;
729 if (successful_bytes > 0) {
730 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
731 successful_bytes;
732 }
733
734 int url_switch_count = static_cast<int>(url_switch_count_);
735
736 int reboot_count = GetNumReboots();
737
738 SetNumReboots(0);
739
740 TimeDelta duration = GetUpdateDuration();
Sen Jiang8712e962018-05-08 12:12:28 -0700741 TimeDelta duration_uptime = GetUpdateDurationUptime();
David Zeuthen33bae492014-02-25 16:16:18 -0800742
743 prefs_->Delete(kPrefsUpdateTimestampStart);
744 prefs_->Delete(kPrefsUpdateDurationUptime);
745
746 PayloadType payload_type = CalculatePayloadType();
747
Sen Jiang0affc2c2017-02-10 15:55:05 -0800748 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800749
750 int attempt_count = GetPayloadAttemptNumber();
751
752 int updates_abandoned_count = num_responses_seen_ - 1;
753
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700754 system_state_->metrics_reporter()->ReportSuccessfulUpdateMetrics(
755 attempt_count,
756 updates_abandoned_count,
757 payload_type,
758 payload_size,
759 total_bytes_by_source,
760 download_overhead_percentage,
761 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700762 duration_uptime,
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700763 reboot_count,
764 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700765}
766
767void PayloadState::UpdateNumReboots() {
768 // We only update the reboot count when the system has been detected to have
769 // been rebooted.
770 if (!system_state_->system_rebooted()) {
771 return;
772 }
773
774 SetNumReboots(GetNumReboots() + 1);
775}
776
777void PayloadState::SetNumReboots(uint32_t num_reboots) {
Chris Sosabe45bef2013-04-09 18:25:12 -0700778 num_reboots_ = num_reboots;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700779 metrics_utils::SetNumReboots(num_reboots, prefs_);
Chris Sosabe45bef2013-04-09 18:25:12 -0700780}
781
Jay Srinivasan08262882012-12-28 19:29:43 -0800782void PayloadState::ResetPersistedState() {
783 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700784 SetFullPayloadAttemptNumber(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700785 SetPayloadIndex(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800786 SetUrlIndex(0);
787 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700788 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700789 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700790 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700791 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700792 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700793 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700794 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700795 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700796 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700797 SetScatteringWaitPeriod(TimeDelta());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700798 SetStagingWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700799}
800
801void PayloadState::ResetRollbackVersion() {
802 CHECK(powerwash_safe_prefs_);
803 rollback_version_ = "";
804 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700805}
806
807void PayloadState::ResetDownloadSourcesOnNewUpdate() {
808 for (int i = 0; i < kNumDownloadSources; i++) {
809 DownloadSource source = static_cast<DownloadSource>(i);
810 SetCurrentBytesDownloaded(source, 0, true);
811 // Note: Not resetting the TotalBytesDownloaded as we want that metric
812 // to count the bytes downloaded across various update attempts until
813 // we have successfully applied the update.
814 }
815}
816
Jay Srinivasan08262882012-12-28 19:29:43 -0800817string PayloadState::CalculateResponseSignature() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800818 string response_sign;
819 for (size_t i = 0; i < response_.packages.size(); i++) {
820 const auto& package = response_.packages[i];
821 response_sign += base::StringPrintf(
822 "Payload %zu:\n"
823 " Size = %ju\n"
824 " Sha256 Hash = %s\n"
825 " Metadata Size = %ju\n"
826 " Metadata Signature = %s\n"
Sen Jiangcdd52062017-05-18 15:33:10 -0700827 " Is Delta = %d\n"
Sen Jiang0affc2c2017-02-10 15:55:05 -0800828 " NumURLs = %zu\n",
829 i,
830 static_cast<uintmax_t>(package.size),
831 package.hash.c_str(),
832 static_cast<uintmax_t>(package.metadata_size),
833 package.metadata_signature.c_str(),
Sen Jiangcdd52062017-05-18 15:33:10 -0700834 package.is_delta,
Sen Jiang0affc2c2017-02-10 15:55:05 -0800835 candidate_urls_[i].size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800836
Sen Jiang0affc2c2017-02-10 15:55:05 -0800837 for (size_t j = 0; j < candidate_urls_[i].size(); j++)
838 response_sign += base::StringPrintf(
839 " Candidate Url%zu = %s\n", j, candidate_urls_[i][j].c_str());
840 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800841
Alex Vakulenko75039d72014-03-25 12:36:28 -0700842 response_sign += base::StringPrintf(
Alex Vakulenko75039d72014-03-25 12:36:28 -0700843 "Max Failure Count Per Url = %d\n"
844 "Disable Payload Backoff = %d\n",
Alex Vakulenko75039d72014-03-25 12:36:28 -0700845 response_.max_failure_count_per_url,
846 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800847 return response_sign;
848}
849
850void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800851 CHECK(prefs_);
852 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800853 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
854 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
855 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800856 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800857}
858
Jay Srinivasan19409b72013-04-12 19:23:36 -0700859void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800860 CHECK(prefs_);
861 response_signature_ = response_signature;
862 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
863 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
864}
865
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800866void PayloadState::LoadPayloadAttemptNumber() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700867 SetPayloadAttemptNumber(
868 GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800869}
870
Alex Deymo820cc702013-06-28 15:43:46 -0700871void PayloadState::LoadFullPayloadAttemptNumber() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700872 SetFullPayloadAttemptNumber(
873 GetPersistedValue(kPrefsFullPayloadAttemptNumber, prefs_));
Alex Deymo820cc702013-06-28 15:43:46 -0700874}
875
876void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800877 payload_attempt_number_ = payload_attempt_number;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700878 metrics_utils::SetPayloadAttemptNumber(payload_attempt_number, prefs_);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800879}
880
Alex Deymo820cc702013-06-28 15:43:46 -0700881void PayloadState::SetFullPayloadAttemptNumber(
882 int full_payload_attempt_number) {
883 CHECK(prefs_);
884 full_payload_attempt_number_ = full_payload_attempt_number;
885 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
886 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
887 full_payload_attempt_number_);
888}
889
Sen Jiang5ae865b2017-04-18 14:24:40 -0700890void PayloadState::SetPayloadIndex(size_t payload_index) {
891 CHECK(prefs_);
892 payload_index_ = payload_index;
893 LOG(INFO) << "Payload Index = " << payload_index_;
894 prefs_->SetInt64(kPrefsUpdateStatePayloadIndex, payload_index_);
895}
896
897bool PayloadState::NextPayload() {
898 if (payload_index_ + 1 >= candidate_urls_.size())
899 return false;
900 SetPayloadIndex(payload_index_ + 1);
901 return true;
902}
903
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800904void PayloadState::LoadUrlIndex() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700905 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex, prefs_));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800906}
907
908void PayloadState::SetUrlIndex(uint32_t url_index) {
909 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800910 url_index_ = url_index;
911 LOG(INFO) << "Current URL Index = " << url_index_;
912 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700913
914 // Also update the download source, which is purely dependent on the
915 // current URL index alone.
916 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800917}
918
Gilad Arnold519cfc72014-10-02 10:34:54 -0700919void PayloadState::LoadScatteringWaitPeriod() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700920 SetScatteringWaitPeriod(TimeDelta::FromSeconds(
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700921 GetPersistedValue(kPrefsWallClockScatteringWaitPeriod, prefs_)));
Gilad Arnold519cfc72014-10-02 10:34:54 -0700922}
923
Alex Deymof329b932014-10-30 01:37:48 -0700924void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700925 CHECK(prefs_);
926 scattering_wait_period_ = wait_period;
927 LOG(INFO) << "Scattering Wait Period (seconds) = "
928 << scattering_wait_period_.InSeconds();
929 if (scattering_wait_period_.InSeconds() > 0) {
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700930 prefs_->SetInt64(kPrefsWallClockScatteringWaitPeriod,
Gilad Arnold519cfc72014-10-02 10:34:54 -0700931 scattering_wait_period_.InSeconds());
932 } else {
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700933 prefs_->Delete(kPrefsWallClockScatteringWaitPeriod);
934 }
935}
936
937void PayloadState::LoadStagingWaitPeriod() {
938 SetStagingWaitPeriod(TimeDelta::FromSeconds(
939 GetPersistedValue(kPrefsWallClockStagingWaitPeriod, prefs_)));
940}
941
942void PayloadState::SetStagingWaitPeriod(TimeDelta wait_period) {
943 CHECK(prefs_);
944 staging_wait_period_ = wait_period;
945 LOG(INFO) << "Staging Wait Period (days) =" << staging_wait_period_.InDays();
946 if (staging_wait_period_.InSeconds() > 0) {
947 prefs_->SetInt64(kPrefsWallClockStagingWaitPeriod,
948 staging_wait_period_.InSeconds());
949 } else {
950 prefs_->Delete(kPrefsWallClockStagingWaitPeriod);
Gilad Arnold519cfc72014-10-02 10:34:54 -0700951 }
952}
953
David Zeuthencc6f9962013-04-18 11:57:24 -0700954void PayloadState::LoadUrlSwitchCount() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700955 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount, prefs_));
David Zeuthencc6f9962013-04-18 11:57:24 -0700956}
957
958void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
959 CHECK(prefs_);
960 url_switch_count_ = url_switch_count;
961 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
962 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
963}
964
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800965void PayloadState::LoadUrlFailureCount() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700966 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount, prefs_));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800967}
968
969void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
970 CHECK(prefs_);
971 url_failure_count_ = url_failure_count;
972 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
973 << ")'s Failure Count = " << url_failure_count_;
974 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800975}
976
Jay Srinivasan08262882012-12-28 19:29:43 -0800977void PayloadState::LoadBackoffExpiryTime() {
978 CHECK(prefs_);
979 int64_t stored_value;
980 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
981 return;
982
983 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
984 return;
985
986 Time stored_time = Time::FromInternalValue(stored_value);
987 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
988 LOG(ERROR) << "Invalid backoff expiry time ("
989 << utils::ToString(stored_time)
990 << ") in persisted state. Resetting.";
991 stored_time = Time();
992 }
993 SetBackoffExpiryTime(stored_time);
994}
995
996void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
997 CHECK(prefs_);
998 backoff_expiry_time_ = new_time;
999 LOG(INFO) << "Backoff Expiry Time = "
1000 << utils::ToString(backoff_expiry_time_);
1001 prefs_->SetInt64(kPrefsBackoffExpiryTime,
1002 backoff_expiry_time_.ToInternalValue());
1003}
1004
David Zeuthen9a017f22013-04-11 16:10:26 -07001005TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001006 Time end_time = update_timestamp_end_.is_null()
1007 ? system_state_->clock()->GetWallclockTime() :
1008 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001009 return end_time - update_timestamp_start_;
1010}
1011
1012void PayloadState::LoadUpdateTimestampStart() {
1013 int64_t stored_value;
1014 Time stored_time;
1015
1016 CHECK(prefs_);
1017
David Zeuthenf413fe52013-04-22 14:04:39 -07001018 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001019
1020 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1021 // The preference missing is not unexpected - in that case, just
1022 // use the current time as start time
1023 stored_time = now;
1024 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1025 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1026 stored_time = now;
1027 } else {
1028 stored_time = Time::FromInternalValue(stored_value);
1029 }
1030
1031 // Sanity check: If the time read from disk is in the future
1032 // (modulo some slack to account for possible NTP drift
1033 // adjustments), something is fishy and we should report and
1034 // reset.
1035 TimeDelta duration_according_to_stored_time = now - stored_time;
1036 if (duration_according_to_stored_time < -kDurationSlack) {
1037 LOG(ERROR) << "The UpdateTimestampStart value ("
1038 << utils::ToString(stored_time)
1039 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001040 << utils::FormatTimeDelta(duration_according_to_stored_time)
1041 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001042 stored_time = now;
1043 }
1044
1045 SetUpdateTimestampStart(stored_time);
1046}
1047
1048void PayloadState::SetUpdateTimestampStart(const Time& value) {
David Zeuthen9a017f22013-04-11 16:10:26 -07001049 update_timestamp_start_ = value;
Tianjie Xu90aaa102017-10-10 17:39:03 -07001050 metrics_utils::SetUpdateTimestampStart(value, prefs_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001051}
1052
1053void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1054 update_timestamp_end_ = value;
1055 LOG(INFO) << "Update Timestamp End = "
1056 << utils::ToString(update_timestamp_end_);
1057}
1058
1059TimeDelta PayloadState::GetUpdateDurationUptime() {
1060 return update_duration_uptime_;
1061}
1062
1063void PayloadState::LoadUpdateDurationUptime() {
1064 int64_t stored_value;
1065 TimeDelta stored_delta;
1066
1067 CHECK(prefs_);
1068
1069 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1070 // The preference missing is not unexpected - in that case, just
1071 // we'll use zero as the delta
1072 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1073 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1074 stored_delta = TimeDelta::FromSeconds(0);
1075 } else {
1076 stored_delta = TimeDelta::FromInternalValue(stored_value);
1077 }
1078
1079 // Sanity-check: Uptime can never be greater than the wall-clock
1080 // difference (modulo some slack). If it is, report and reset
1081 // to the wall-clock difference.
1082 TimeDelta diff = GetUpdateDuration() - stored_delta;
1083 if (diff < -kDurationSlack) {
1084 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001085 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001086 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001087 << utils::FormatTimeDelta(diff)
1088 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001089 stored_delta = update_duration_current_;
1090 }
1091
1092 SetUpdateDurationUptime(stored_delta);
1093}
1094
Chris Sosabe45bef2013-04-09 18:25:12 -07001095void PayloadState::LoadNumReboots() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001096 SetNumReboots(GetPersistedValue(kPrefsNumReboots, prefs_));
Chris Sosaaa18e162013-06-20 13:20:30 -07001097}
1098
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001099void PayloadState::LoadRollbackHappened() {
1100 CHECK(powerwash_safe_prefs_);
1101 bool rollback_happened = false;
1102 powerwash_safe_prefs_->GetBoolean(kPrefsRollbackHappened, &rollback_happened);
1103 SetRollbackHappened(rollback_happened);
1104}
1105
1106void PayloadState::SetRollbackHappened(bool rollback_happened) {
1107 CHECK(powerwash_safe_prefs_);
1108 LOG(INFO) << "Setting rollback-happened to " << rollback_happened << ".";
1109 rollback_happened_ = rollback_happened;
1110 if (rollback_happened) {
1111 powerwash_safe_prefs_->SetBoolean(kPrefsRollbackHappened,
1112 rollback_happened);
1113 } else {
1114 powerwash_safe_prefs_->Delete(kPrefsRollbackHappened);
1115 }
1116}
1117
Chris Sosaaa18e162013-06-20 13:20:30 -07001118void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001119 CHECK(powerwash_safe_prefs_);
1120 string rollback_version;
1121 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1122 &rollback_version)) {
1123 SetRollbackVersion(rollback_version);
1124 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001125}
1126
1127void PayloadState::SetRollbackVersion(const string& rollback_version) {
1128 CHECK(powerwash_safe_prefs_);
1129 LOG(INFO) << "Blacklisting version "<< rollback_version;
1130 rollback_version_ = rollback_version;
1131 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001132}
1133
David Zeuthen9a017f22013-04-11 16:10:26 -07001134void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1135 const Time& timestamp,
1136 bool use_logging) {
1137 CHECK(prefs_);
1138 update_duration_uptime_ = value;
1139 update_duration_uptime_timestamp_ = timestamp;
1140 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1141 update_duration_uptime_.ToInternalValue());
1142 if (use_logging) {
1143 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001144 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001145 }
1146}
1147
1148void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001149 Time now = system_state_->clock()->GetMonotonicTime();
1150 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001151}
1152
1153void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001154 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001155 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1156 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1157 // We're frequently called so avoid logging this write
1158 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1159}
1160
Jay Srinivasan19409b72013-04-12 19:23:36 -07001161string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1162 return prefix + "-from-" + utils::ToString(source);
1163}
1164
1165void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1166 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001167 SetCurrentBytesDownloaded(source, GetPersistedValue(key, prefs_), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001168}
1169
1170void PayloadState::SetCurrentBytesDownloaded(
1171 DownloadSource source,
1172 uint64_t current_bytes_downloaded,
1173 bool log) {
1174 CHECK(prefs_);
1175
1176 if (source >= kNumDownloadSources)
1177 return;
1178
1179 // Update the in-memory value.
1180 current_bytes_downloaded_[source] = current_bytes_downloaded;
1181
1182 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1183 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1184 LOG_IF(INFO, log) << "Current bytes downloaded for "
1185 << utils::ToString(source) << " = "
1186 << GetCurrentBytesDownloaded(source);
1187}
1188
1189void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1190 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001191 SetTotalBytesDownloaded(source, GetPersistedValue(key, prefs_), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001192}
1193
1194void PayloadState::SetTotalBytesDownloaded(
1195 DownloadSource source,
1196 uint64_t total_bytes_downloaded,
1197 bool log) {
1198 CHECK(prefs_);
1199
1200 if (source >= kNumDownloadSources)
1201 return;
1202
1203 // Update the in-memory value.
1204 total_bytes_downloaded_[source] = total_bytes_downloaded;
1205
1206 // Persist.
1207 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1208 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1209 LOG_IF(INFO, log) << "Total bytes downloaded for "
1210 << utils::ToString(source) << " = "
1211 << GetTotalBytesDownloaded(source);
1212}
1213
David Zeuthena573d6f2013-06-14 16:13:36 -07001214void PayloadState::LoadNumResponsesSeen() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001215 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen, prefs_));
David Zeuthena573d6f2013-06-14 16:13:36 -07001216}
1217
1218void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1219 CHECK(prefs_);
1220 num_responses_seen_ = num_responses_seen;
1221 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1222 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1223}
1224
Jay Srinivasan53173b92013-05-17 17:13:01 -07001225void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001226 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001227
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001228 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001229 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001230 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001231 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1232 } else {
1233 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1234 http_url_ok = true;
1235 }
1236
1237 candidate_urls_.clear();
Sen Jiang0affc2c2017-02-10 15:55:05 -08001238 for (const auto& package : response_.packages) {
1239 candidate_urls_.emplace_back();
1240 for (const string& candidate_url : package.payload_urls) {
1241 if (base::StartsWith(
1242 candidate_url, "http://", base::CompareCase::INSENSITIVE_ASCII) &&
1243 !http_url_ok) {
1244 continue;
1245 }
1246 candidate_urls_.back().push_back(candidate_url);
1247 LOG(INFO) << "Candidate Url" << (candidate_urls_.back().size() - 1)
1248 << ": " << candidate_url;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001249 }
Sen Jiang0affc2c2017-02-10 15:55:05 -08001250 LOG(INFO) << "Found " << candidate_urls_.back().size() << " candidate URLs "
1251 << "out of " << package.payload_urls.size()
1252 << " URLs supplied in package " << candidate_urls_.size() - 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001253 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001254}
1255
David Zeuthene4c58bf2013-06-18 17:26:50 -07001256void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001257 // Flush previous state from abnormal attempt failure, if any.
1258 ReportAndClearPersistedAttemptMetrics();
1259
Alex Deymo569c4242013-07-24 12:01:01 -07001260 // Avoid the UpdateEngineStarted actions if this is not the first time we
1261 // run the update engine since reboot.
1262 if (!system_state_->system_rebooted())
1263 return;
1264
Tianjie Xu90aaa102017-10-10 17:39:03 -07001265 // Report time_to_reboot if we booted into a new update.
1266 metrics_utils::LoadAndReportTimeToReboot(
1267 system_state_->metrics_reporter(), prefs_, system_state_->clock());
1268 prefs_->Delete(kPrefsSystemUpdatedMarker);
1269
Alex Deymo42432912013-07-12 20:21:15 -07001270 // Check if it is needed to send metrics about a failed reboot into a new
1271 // version.
1272 ReportFailedBootIfNeeded();
1273}
1274
1275void PayloadState::ReportFailedBootIfNeeded() {
1276 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1277 // payload was marked as ready immediately before the last reboot, and we
1278 // need to check if such payload successfully rebooted or not.
1279 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001280 int64_t installed_from = 0;
1281 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001282 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1283 return;
1284 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001285 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1286 // partition number. We are now using slot numbers (0 or 1) instead, so
1287 // the following comparison will not match if we are comparing an old
1288 // partition number against a new slot number, which is the correct outcome
1289 // since we successfully booted the new update in that case. If the boot
1290 // failed, we will read this value from the same version, so it will always
1291 // be compatible.
1292 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001293 // A reboot was pending, but the chromebook is again in the same
1294 // BootDevice where the update was installed from.
1295 int64_t target_attempt;
1296 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1297 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1298 "TargetVersionInstalledFrom was present.";
1299 target_attempt = 1;
1300 }
1301
1302 // Report the UMA metric of the current boot failure.
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001303 system_state_->metrics_reporter()->ReportFailedUpdateCount(
1304 target_attempt);
Alex Deymo42432912013-07-12 20:21:15 -07001305 } else {
1306 prefs_->Delete(kPrefsTargetVersionAttempt);
1307 prefs_->Delete(kPrefsTargetVersionUniqueId);
1308 }
1309 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1310 }
1311}
1312
1313void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1314 // Expect to boot into the new partition in the next reboot setting the
1315 // TargetVersion* flags in the Prefs.
1316 string stored_target_version_uid;
1317 string target_version_id;
1318 string target_partition;
1319 int64_t target_attempt;
1320
1321 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1322 prefs_->GetString(kPrefsTargetVersionUniqueId,
1323 &stored_target_version_uid) &&
1324 stored_target_version_uid == target_version_uid) {
1325 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1326 target_attempt = 0;
1327 } else {
1328 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1329 target_attempt = 0;
1330 }
1331 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1332
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001333 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001334 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001335}
1336
1337void PayloadState::ResetUpdateStatus() {
1338 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1339 // rebooted the next boot is not flagged as failed to rebooted into the
1340 // new applied payload.
1341 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1342
1343 // Also decrement the attempt number if it exists.
1344 int64_t target_attempt;
1345 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001346 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001347}
1348
David Zeuthendcba8092013-08-06 12:16:35 -07001349int PayloadState::GetP2PNumAttempts() {
1350 return p2p_num_attempts_;
1351}
1352
1353void PayloadState::SetP2PNumAttempts(int value) {
1354 p2p_num_attempts_ = value;
1355 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1356 CHECK(prefs_);
1357 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1358}
1359
1360void PayloadState::LoadP2PNumAttempts() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001361 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts, prefs_));
David Zeuthendcba8092013-08-06 12:16:35 -07001362}
1363
1364Time PayloadState::GetP2PFirstAttemptTimestamp() {
1365 return p2p_first_attempt_timestamp_;
1366}
1367
1368void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1369 p2p_first_attempt_timestamp_ = time;
1370 LOG(INFO) << "p2p First Attempt Timestamp = "
1371 << utils::ToString(p2p_first_attempt_timestamp_);
1372 CHECK(prefs_);
1373 int64_t stored_value = time.ToInternalValue();
1374 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1375}
1376
1377void PayloadState::LoadP2PFirstAttemptTimestamp() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001378 int64_t stored_value =
1379 GetPersistedValue(kPrefsP2PFirstAttemptTimestamp, prefs_);
David Zeuthendcba8092013-08-06 12:16:35 -07001380 Time stored_time = Time::FromInternalValue(stored_value);
1381 SetP2PFirstAttemptTimestamp(stored_time);
1382}
1383
1384void PayloadState::P2PNewAttempt() {
1385 CHECK(prefs_);
1386 // Set timestamp, if it hasn't been set already
1387 if (p2p_first_attempt_timestamp_.is_null()) {
1388 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1389 }
1390 // Increase number of attempts
1391 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1392}
1393
1394bool PayloadState::P2PAttemptAllowed() {
1395 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1396 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1397 << " which is greater than "
1398 << kMaxP2PAttempts
1399 << " - disallowing p2p.";
1400 return false;
1401 }
1402
1403 if (!p2p_first_attempt_timestamp_.is_null()) {
1404 Time now = system_state_->clock()->GetWallclockTime();
1405 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1406 if (time_spent_attempting_p2p.InSeconds() < 0) {
1407 LOG(ERROR) << "Time spent attempting p2p is negative"
1408 << " - disallowing p2p.";
1409 return false;
1410 }
1411 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1412 LOG(INFO) << "Time spent attempting p2p is "
1413 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1414 << " which is greater than "
1415 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1416 kMaxP2PAttemptTimeSeconds))
1417 << " - disallowing p2p.";
1418 return false;
1419 }
1420 }
1421
1422 return true;
1423}
1424
Sen Jiang0affc2c2017-02-10 15:55:05 -08001425int64_t PayloadState::GetPayloadSize() {
1426 int64_t payload_size = 0;
1427 for (const auto& package : response_.packages)
1428 payload_size += package.size;
1429 return payload_size;
1430}
1431
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001432} // namespace chromeos_update_engine