blob: 7c969b30487aee22fe880ade6d9a7d3a238e02a7 [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:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800307 IncrementUrlIndex();
308 break;
309
310 // Errors which seem to be just transient network/communication related
311 // failures and do not indicate any inherent problem with the URL itself.
312 // So, we should keep the current URL but just increment the
313 // failure count to give it more chances. This way, while we maximize our
314 // chances of downloading from the URLs that appear earlier in the response
315 // (because download from a local server URL that appears earlier in a
316 // response is preferable than downloading from the next URL which could be
317 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700318
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700319 case ErrorCode::kError:
320 case ErrorCode::kDownloadTransferError:
321 case ErrorCode::kDownloadWriteError:
322 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700323 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800324 IncrementFailureCount();
325 break;
326
327 // Errors which are not specific to a URL and hence shouldn't result in
328 // the URL being penalized. This can happen in two cases:
329 // 1. We haven't started downloading anything: These errors don't cost us
330 // anything in terms of actual payload bytes, so we should just do the
331 // regular retries at the next update check.
332 // 2. We have successfully downloaded the payload: In this case, the
333 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800334 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800335 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700336 case ErrorCode::kOmahaRequestError:
337 case ErrorCode::kOmahaResponseHandlerError:
338 case ErrorCode::kPostinstallRunnerError:
339 case ErrorCode::kFilesystemCopierError:
340 case ErrorCode::kInstallDeviceOpenError:
341 case ErrorCode::kKernelDeviceOpenError:
342 case ErrorCode::kDownloadNewPartitionInfoError:
343 case ErrorCode::kNewRootfsVerificationError:
344 case ErrorCode::kNewKernelVerificationError:
345 case ErrorCode::kPostinstallBootedFromFirmwareB:
346 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
347 case ErrorCode::kOmahaRequestEmptyResponseError:
348 case ErrorCode::kOmahaRequestXMLParseError:
349 case ErrorCode::kOmahaResponseInvalid:
350 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
351 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700352 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700353 case ErrorCode::kOmahaUpdateDeferredForBackoff:
354 case ErrorCode::kPostinstallPowerwashError:
355 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400356 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700357 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800358 case ErrorCode::kUserCanceled:
Weidong Guo421ff332017-04-17 10:08:38 -0700359 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
Sen Jiang02c49422017-10-31 15:14:11 -0700360 case ErrorCode::kUpdatedButNotActive:
Sen Jiang3978ddd2018-03-22 18:05:44 -0700361 case ErrorCode::kNoUpdate:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800362 LOG(INFO) << "Not incrementing URL index or failure count for this error";
363 break;
364
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700365 case ErrorCode::kSuccess: // success code
366 case ErrorCode::kUmaReportedMax: // not an error code
367 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
368 case ErrorCode::kDevModeFlag: // not an error code
369 case ErrorCode::kResumedFlag: // not an error code
370 case ErrorCode::kTestImageFlag: // not an error code
371 case ErrorCode::kTestOmahaUrlFlag: // not an error code
372 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800373 // These shouldn't happen. Enumerating these explicitly here so that we
374 // can let the compiler warn about new error codes that are added to
375 // action_processor.h but not added here.
376 LOG(WARNING) << "Unexpected error code for UpdateFailed";
377 break;
378
379 // Note: Not adding a default here so as to let the compiler warn us of
380 // any new enums that were added in the .h but not listed in this switch.
381 }
382}
383
Jay Srinivasan08262882012-12-28 19:29:43 -0800384bool PayloadState::ShouldBackoffDownload() {
385 if (response_.disable_payload_backoff) {
386 LOG(INFO) << "Payload backoff logic is disabled. "
387 "Can proceed with the download";
388 return false;
389 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700390 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700391 LOG(INFO) << "Payload backoff logic is disabled because download "
392 << "will happen from local peer (via p2p).";
393 return false;
394 }
395 if (system_state_->request_params()->interactive()) {
396 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
397 return false;
398 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700399 for (const auto& package : response_.packages) {
400 if (package.is_delta) {
401 // If delta payloads fail, we want to fallback quickly to full payloads as
402 // they are more likely to succeed. Exponential backoffs would greatly
403 // slow down the fallback to full payloads. So we don't backoff for delta
404 // payloads.
405 LOG(INFO) << "No backoffs for delta payloads. "
406 << "Can proceed with the download";
407 return false;
408 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800409 }
410
Amin Hassaniffb6d802018-03-30 11:43:57 -0700411 if (!system_state_->hardware()->IsOfficialBuild() &&
412 !prefs_->Exists(kPrefsNoIgnoreBackoff)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800413 // Backoffs are needed only for official builds. We do not want any delays
Amin Hassaniffb6d802018-03-30 11:43:57 -0700414 // or update failures due to backoffs during testing or development. Unless
415 // the |kPrefsNoIgnoreBackoff| is manually set.
Jay Srinivasan08262882012-12-28 19:29:43 -0800416 LOG(INFO) << "No backoffs for test/dev images. "
417 << "Can proceed with the download";
418 return false;
419 }
420
421 if (backoff_expiry_time_.is_null()) {
422 LOG(INFO) << "No backoff expiry time has been set. "
423 << "Can proceed with the download";
424 return false;
425 }
426
427 if (backoff_expiry_time_ < Time::Now()) {
428 LOG(INFO) << "The backoff expiry time ("
429 << utils::ToString(backoff_expiry_time_)
430 << ") has elapsed. Can proceed with the download";
431 return false;
432 }
433
434 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
435 << utils::ToString(backoff_expiry_time_);
436 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800437}
438
Chris Sosaaa18e162013-06-20 13:20:30 -0700439void PayloadState::Rollback() {
440 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700441 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700442}
443
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800444void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700445 // Update the payload attempt number for both payload types: full and delta.
446 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
447}
448
449void PayloadState::IncrementFullPayloadAttemptNumber() {
450 // Update the payload attempt number for full payloads and the backoff time.
Sen Jiangcdd52062017-05-18 15:33:10 -0700451 if (response_.packages[payload_index_].is_delta) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800452 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
453 return;
454 }
455
Alex Deymo29b51d92013-07-09 15:26:24 -0700456 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700457 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800458 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800459}
460
461void PayloadState::IncrementUrlIndex() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800462 size_t next_url_index = url_index_ + 1;
463 size_t max_url_size = 0;
464 for (const auto& urls : candidate_urls_)
465 max_url_size = std::max(max_url_size, urls.size());
466 if (next_url_index < max_url_size) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800467 LOG(INFO) << "Incrementing the URL index for next attempt";
468 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800469 } else {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800470 LOG(INFO) << "Resetting the current URL index (" << url_index_ << ") to "
471 << "0 as we only have " << max_url_size << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800472 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700473 IncrementPayloadAttemptNumber();
474 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800475 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800476
David Zeuthencc6f9962013-04-18 11:57:24 -0700477 // If we have multiple URLs, record that we just switched to another one
Sen Jiang0affc2c2017-02-10 15:55:05 -0800478 if (max_url_size > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700479 SetUrlSwitchCount(url_switch_count_ + 1);
480
Jay Srinivasan08262882012-12-28 19:29:43 -0800481 // Whenever we update the URL index, we should also clear the URL failure
482 // count so we can start over fresh for the new URL.
483 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800484}
485
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800486void PayloadState::IncrementFailureCount() {
487 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800488 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800489 LOG(INFO) << "Incrementing the URL failure count";
490 SetUrlFailureCount(next_url_failure_count);
491 } else {
492 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
493 << ". Trying next available URL";
494 IncrementUrlIndex();
495 }
496}
497
Jay Srinivasan08262882012-12-28 19:29:43 -0800498void PayloadState::UpdateBackoffExpiryTime() {
499 if (response_.disable_payload_backoff) {
500 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
501 SetBackoffExpiryTime(Time());
502 return;
503 }
504
Alex Deymo820cc702013-06-28 15:43:46 -0700505 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800506 SetBackoffExpiryTime(Time());
507 return;
508 }
509
510 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700511 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800512 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700513 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700514 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800515
516 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
517 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700518 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800519
520 // The number of days is the minimum of 2 raised to (payload_attempt_number
521 // - 1) or kMaxBackoffDays.
522 num_days = min(num_days << power, kMaxBackoffDays);
523
524 // We don't want all retries to happen exactly at the same time when
525 // retrying after backoff. So add some random minutes to fuzz.
526 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
527 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
528 TimeDelta::FromMinutes(fuzz_minutes);
529 LOG(INFO) << "Incrementing the backoff expiry time by "
530 << utils::FormatTimeDelta(next_backoff_interval);
531 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
532}
533
Jay Srinivasan19409b72013-04-12 19:23:36 -0700534void PayloadState::UpdateCurrentDownloadSource() {
535 current_download_source_ = kNumDownloadSources;
536
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700537 if (using_p2p_for_downloading_) {
538 current_download_source_ = kDownloadSourceHttpPeer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800539 } else if (payload_index_ < candidate_urls_.size() &&
540 candidate_urls_[payload_index_].size() != 0) {
541 const string& current_url = candidate_urls_[payload_index_][GetUrlIndex()];
542 if (base::StartsWith(
543 current_url, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700544 current_download_source_ = kDownloadSourceHttpsServer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800545 } else if (base::StartsWith(current_url,
546 "http://",
Alex Vakulenko0103c362016-01-20 07:56:15 -0800547 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700548 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800549 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700550 }
551
552 LOG(INFO) << "Current download source: "
553 << utils::ToString(current_download_source_);
554}
555
556void PayloadState::UpdateBytesDownloaded(size_t count) {
557 SetCurrentBytesDownloaded(
558 current_download_source_,
559 GetCurrentBytesDownloaded(current_download_source_) + count,
560 false);
561 SetTotalBytesDownloaded(
562 current_download_source_,
563 GetTotalBytesDownloaded(current_download_source_) + count,
564 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800565
566 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700567}
568
David Zeuthen33bae492014-02-25 16:16:18 -0800569PayloadType PayloadState::CalculatePayloadType() {
Sen Jiangcdd52062017-05-18 15:33:10 -0700570 for (const auto& package : response_.packages) {
571 if (package.is_delta) {
572 return kPayloadTypeDelta;
573 }
David Zeuthen33bae492014-02-25 16:16:18 -0800574 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700575 OmahaRequestParams* params = system_state_->request_params();
576 if (params->delta_okay()) {
577 return kPayloadTypeFull;
578 }
579 // Full payload, delta was not allowed by request.
580 return kPayloadTypeForcedFull;
David Zeuthen33bae492014-02-25 16:16:18 -0800581}
582
583// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
584// metrics if the attempt ends abnormally, e.g. if the update_engine
585// process crashes or the device is rebooted. See
586// http://crbug.com/357676
587void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
588 int attempt_number = GetPayloadAttemptNumber();
589
590 PayloadType payload_type = CalculatePayloadType();
591
Sen Jiang0affc2c2017-02-10 15:55:05 -0800592 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800593
594 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
595
596 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700597 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
598 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800599 attempt_start_time_monotonic_;
600
601 int64_t payload_download_speed_bps = 0;
602 int64_t usec = duration_uptime.InMicroseconds();
603 if (usec > 0) {
604 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
605 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
606 payload_download_speed_bps = static_cast<int64_t>(bps);
607 }
608
609 DownloadSource download_source = current_download_source_;
610
611 metrics::DownloadErrorCode payload_download_error_code =
612 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700613 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800614 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800615
616 // Add additional detail to AttemptResult
617 switch (attempt_result) {
618 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800619 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800620 break;
621
622 case metrics::AttemptResult::kInternalError:
623 internal_error_code = code;
624 break;
625
626 // Explicit fall-through for cases where we do not have additional
627 // detail. We avoid the default keyword to force people adding new
628 // AttemptResult values to visit this code and examine whether
629 // additional detail is needed.
630 case metrics::AttemptResult::kUpdateSucceeded:
631 case metrics::AttemptResult::kMetadataMalformed:
632 case metrics::AttemptResult::kOperationMalformed:
633 case metrics::AttemptResult::kOperationExecutionError:
634 case metrics::AttemptResult::kMetadataVerificationFailed:
635 case metrics::AttemptResult::kPayloadVerificationFailed:
636 case metrics::AttemptResult::kVerificationFailed:
637 case metrics::AttemptResult::kPostInstallFailed:
638 case metrics::AttemptResult::kAbnormalTermination:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800639 case metrics::AttemptResult::kUpdateCanceled:
Sen Jiang02c49422017-10-31 15:14:11 -0700640 case metrics::AttemptResult::kUpdateSucceededNotActive:
David Zeuthen33bae492014-02-25 16:16:18 -0800641 case metrics::AttemptResult::kNumConstants:
642 case metrics::AttemptResult::kUnset:
643 break;
644 }
645
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700646 system_state_->metrics_reporter()->ReportUpdateAttemptMetrics(
647 system_state_,
648 attempt_number,
649 payload_type,
650 duration,
651 duration_uptime,
652 payload_size,
Tianjie Xu1f93d092017-10-09 12:13:29 -0700653 attempt_result,
654 internal_error_code);
655
656 system_state_->metrics_reporter()->ReportUpdateAttemptDownloadMetrics(
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700657 payload_bytes_downloaded,
658 payload_download_speed_bps,
659 download_source,
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700660 payload_download_error_code,
661 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800662}
663
David Zeuthen4e1d1492014-04-25 13:12:27 -0700664void PayloadState::PersistAttemptMetrics() {
665 // TODO(zeuthen): For now we only persist whether an attempt was in
666 // progress and not values/metrics related to the attempt. This
667 // means that when this happens, of all the UpdateEngine.Attempt.*
668 // metrics, only UpdateEngine.Attempt.Result is reported (with the
669 // value |kAbnormalTermination|). In the future we might want to
670 // persist more data so we can report other metrics in the
671 // UpdateEngine.Attempt.* namespace when this happens.
672 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
673}
674
675void PayloadState::ClearPersistedAttemptMetrics() {
676 prefs_->Delete(kPrefsAttemptInProgress);
677}
678
679void PayloadState::ReportAndClearPersistedAttemptMetrics() {
680 bool attempt_in_progress = false;
681 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
682 return;
683 if (!attempt_in_progress)
684 return;
685
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700686 system_state_->metrics_reporter()
687 ->ReportAbnormallyTerminatedUpdateAttemptMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700688
689 ClearPersistedAttemptMetrics();
690}
691
David Zeuthen33bae492014-02-25 16:16:18 -0800692void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700693 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800694
695 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800696 int64_t total_bytes_by_source[kNumDownloadSources];
697 int64_t successful_bytes = 0;
698 int64_t total_bytes = 0;
699 int64_t successful_mbs = 0;
700 int64_t total_mbs = 0;
701
Jay Srinivasan19409b72013-04-12 19:23:36 -0700702 for (int i = 0; i < kNumDownloadSources; i++) {
703 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800704 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700705
David Zeuthen44848602013-06-24 13:32:14 -0700706 // Only consider this download source (and send byte counts) as
707 // having been used if we downloaded a non-trivial amount of bytes
708 // (e.g. at least 1 MiB) that contributed to the final success of
709 // the update. Otherwise we're going to end up with a lot of
710 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700711
David Zeuthen33bae492014-02-25 16:16:18 -0800712 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800713 successful_bytes += bytes;
714 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700715 SetCurrentBytesDownloaded(source, 0, true);
716
David Zeuthen33bae492014-02-25 16:16:18 -0800717 bytes = GetTotalBytesDownloaded(source);
718 total_bytes_by_source[i] = bytes;
719 total_bytes += bytes;
720 total_mbs += bytes / kNumBytesInOneMiB;
721 SetTotalBytesDownloaded(source, 0, true);
722 }
723
724 int download_overhead_percentage = 0;
725 if (successful_bytes > 0) {
726 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
727 successful_bytes;
728 }
729
730 int url_switch_count = static_cast<int>(url_switch_count_);
731
732 int reboot_count = GetNumReboots();
733
734 SetNumReboots(0);
735
736 TimeDelta duration = GetUpdateDuration();
David Zeuthen33bae492014-02-25 16:16:18 -0800737
738 prefs_->Delete(kPrefsUpdateTimestampStart);
739 prefs_->Delete(kPrefsUpdateDurationUptime);
740
741 PayloadType payload_type = CalculatePayloadType();
742
Sen Jiang0affc2c2017-02-10 15:55:05 -0800743 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800744
745 int attempt_count = GetPayloadAttemptNumber();
746
747 int updates_abandoned_count = num_responses_seen_ - 1;
748
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700749 system_state_->metrics_reporter()->ReportSuccessfulUpdateMetrics(
750 attempt_count,
751 updates_abandoned_count,
752 payload_type,
753 payload_size,
754 total_bytes_by_source,
755 download_overhead_percentage,
756 duration,
757 reboot_count,
758 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700759}
760
761void PayloadState::UpdateNumReboots() {
762 // We only update the reboot count when the system has been detected to have
763 // been rebooted.
764 if (!system_state_->system_rebooted()) {
765 return;
766 }
767
768 SetNumReboots(GetNumReboots() + 1);
769}
770
771void PayloadState::SetNumReboots(uint32_t num_reboots) {
Chris Sosabe45bef2013-04-09 18:25:12 -0700772 num_reboots_ = num_reboots;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700773 metrics_utils::SetNumReboots(num_reboots, prefs_);
Chris Sosabe45bef2013-04-09 18:25:12 -0700774}
775
Jay Srinivasan08262882012-12-28 19:29:43 -0800776void PayloadState::ResetPersistedState() {
777 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700778 SetFullPayloadAttemptNumber(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700779 SetPayloadIndex(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800780 SetUrlIndex(0);
781 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700782 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700783 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700784 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700785 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700786 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700787 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700788 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700789 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700790 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700791 SetScatteringWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700792}
793
794void PayloadState::ResetRollbackVersion() {
795 CHECK(powerwash_safe_prefs_);
796 rollback_version_ = "";
797 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700798}
799
800void PayloadState::ResetDownloadSourcesOnNewUpdate() {
801 for (int i = 0; i < kNumDownloadSources; i++) {
802 DownloadSource source = static_cast<DownloadSource>(i);
803 SetCurrentBytesDownloaded(source, 0, true);
804 // Note: Not resetting the TotalBytesDownloaded as we want that metric
805 // to count the bytes downloaded across various update attempts until
806 // we have successfully applied the update.
807 }
808}
809
Jay Srinivasan08262882012-12-28 19:29:43 -0800810string PayloadState::CalculateResponseSignature() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800811 string response_sign;
812 for (size_t i = 0; i < response_.packages.size(); i++) {
813 const auto& package = response_.packages[i];
814 response_sign += base::StringPrintf(
815 "Payload %zu:\n"
816 " Size = %ju\n"
817 " Sha256 Hash = %s\n"
818 " Metadata Size = %ju\n"
819 " Metadata Signature = %s\n"
Sen Jiangcdd52062017-05-18 15:33:10 -0700820 " Is Delta = %d\n"
Sen Jiang0affc2c2017-02-10 15:55:05 -0800821 " NumURLs = %zu\n",
822 i,
823 static_cast<uintmax_t>(package.size),
824 package.hash.c_str(),
825 static_cast<uintmax_t>(package.metadata_size),
826 package.metadata_signature.c_str(),
Sen Jiangcdd52062017-05-18 15:33:10 -0700827 package.is_delta,
Sen Jiang0affc2c2017-02-10 15:55:05 -0800828 candidate_urls_[i].size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800829
Sen Jiang0affc2c2017-02-10 15:55:05 -0800830 for (size_t j = 0; j < candidate_urls_[i].size(); j++)
831 response_sign += base::StringPrintf(
832 " Candidate Url%zu = %s\n", j, candidate_urls_[i][j].c_str());
833 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800834
Alex Vakulenko75039d72014-03-25 12:36:28 -0700835 response_sign += base::StringPrintf(
Alex Vakulenko75039d72014-03-25 12:36:28 -0700836 "Max Failure Count Per Url = %d\n"
837 "Disable Payload Backoff = %d\n",
Alex Vakulenko75039d72014-03-25 12:36:28 -0700838 response_.max_failure_count_per_url,
839 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800840 return response_sign;
841}
842
843void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800844 CHECK(prefs_);
845 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800846 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
847 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
848 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800849 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800850}
851
Jay Srinivasan19409b72013-04-12 19:23:36 -0700852void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800853 CHECK(prefs_);
854 response_signature_ = response_signature;
855 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
856 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
857}
858
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800859void PayloadState::LoadPayloadAttemptNumber() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700860 SetPayloadAttemptNumber(
861 GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800862}
863
Alex Deymo820cc702013-06-28 15:43:46 -0700864void PayloadState::LoadFullPayloadAttemptNumber() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700865 SetFullPayloadAttemptNumber(
866 GetPersistedValue(kPrefsFullPayloadAttemptNumber, prefs_));
Alex Deymo820cc702013-06-28 15:43:46 -0700867}
868
869void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800870 payload_attempt_number_ = payload_attempt_number;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700871 metrics_utils::SetPayloadAttemptNumber(payload_attempt_number, prefs_);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800872}
873
Alex Deymo820cc702013-06-28 15:43:46 -0700874void PayloadState::SetFullPayloadAttemptNumber(
875 int full_payload_attempt_number) {
876 CHECK(prefs_);
877 full_payload_attempt_number_ = full_payload_attempt_number;
878 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
879 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
880 full_payload_attempt_number_);
881}
882
Sen Jiang5ae865b2017-04-18 14:24:40 -0700883void PayloadState::SetPayloadIndex(size_t payload_index) {
884 CHECK(prefs_);
885 payload_index_ = payload_index;
886 LOG(INFO) << "Payload Index = " << payload_index_;
887 prefs_->SetInt64(kPrefsUpdateStatePayloadIndex, payload_index_);
888}
889
890bool PayloadState::NextPayload() {
891 if (payload_index_ + 1 >= candidate_urls_.size())
892 return false;
893 SetPayloadIndex(payload_index_ + 1);
894 return true;
895}
896
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800897void PayloadState::LoadUrlIndex() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700898 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex, prefs_));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800899}
900
901void PayloadState::SetUrlIndex(uint32_t url_index) {
902 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800903 url_index_ = url_index;
904 LOG(INFO) << "Current URL Index = " << url_index_;
905 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700906
907 // Also update the download source, which is purely dependent on the
908 // current URL index alone.
909 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800910}
911
Gilad Arnold519cfc72014-10-02 10:34:54 -0700912void PayloadState::LoadScatteringWaitPeriod() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700913 SetScatteringWaitPeriod(TimeDelta::FromSeconds(
914 GetPersistedValue(kPrefsWallClockWaitPeriod, prefs_)));
Gilad Arnold519cfc72014-10-02 10:34:54 -0700915}
916
Alex Deymof329b932014-10-30 01:37:48 -0700917void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700918 CHECK(prefs_);
919 scattering_wait_period_ = wait_period;
920 LOG(INFO) << "Scattering Wait Period (seconds) = "
921 << scattering_wait_period_.InSeconds();
922 if (scattering_wait_period_.InSeconds() > 0) {
923 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
924 scattering_wait_period_.InSeconds());
925 } else {
926 prefs_->Delete(kPrefsWallClockWaitPeriod);
927 }
928}
929
David Zeuthencc6f9962013-04-18 11:57:24 -0700930void PayloadState::LoadUrlSwitchCount() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700931 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount, prefs_));
David Zeuthencc6f9962013-04-18 11:57:24 -0700932}
933
934void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
935 CHECK(prefs_);
936 url_switch_count_ = url_switch_count;
937 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
938 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
939}
940
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800941void PayloadState::LoadUrlFailureCount() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700942 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount, prefs_));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800943}
944
945void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
946 CHECK(prefs_);
947 url_failure_count_ = url_failure_count;
948 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
949 << ")'s Failure Count = " << url_failure_count_;
950 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800951}
952
Jay Srinivasan08262882012-12-28 19:29:43 -0800953void PayloadState::LoadBackoffExpiryTime() {
954 CHECK(prefs_);
955 int64_t stored_value;
956 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
957 return;
958
959 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
960 return;
961
962 Time stored_time = Time::FromInternalValue(stored_value);
963 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
964 LOG(ERROR) << "Invalid backoff expiry time ("
965 << utils::ToString(stored_time)
966 << ") in persisted state. Resetting.";
967 stored_time = Time();
968 }
969 SetBackoffExpiryTime(stored_time);
970}
971
972void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
973 CHECK(prefs_);
974 backoff_expiry_time_ = new_time;
975 LOG(INFO) << "Backoff Expiry Time = "
976 << utils::ToString(backoff_expiry_time_);
977 prefs_->SetInt64(kPrefsBackoffExpiryTime,
978 backoff_expiry_time_.ToInternalValue());
979}
980
David Zeuthen9a017f22013-04-11 16:10:26 -0700981TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700982 Time end_time = update_timestamp_end_.is_null()
983 ? system_state_->clock()->GetWallclockTime() :
984 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700985 return end_time - update_timestamp_start_;
986}
987
988void PayloadState::LoadUpdateTimestampStart() {
989 int64_t stored_value;
990 Time stored_time;
991
992 CHECK(prefs_);
993
David Zeuthenf413fe52013-04-22 14:04:39 -0700994 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700995
996 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
997 // The preference missing is not unexpected - in that case, just
998 // use the current time as start time
999 stored_time = now;
1000 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1001 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1002 stored_time = now;
1003 } else {
1004 stored_time = Time::FromInternalValue(stored_value);
1005 }
1006
1007 // Sanity check: If the time read from disk is in the future
1008 // (modulo some slack to account for possible NTP drift
1009 // adjustments), something is fishy and we should report and
1010 // reset.
1011 TimeDelta duration_according_to_stored_time = now - stored_time;
1012 if (duration_according_to_stored_time < -kDurationSlack) {
1013 LOG(ERROR) << "The UpdateTimestampStart value ("
1014 << utils::ToString(stored_time)
1015 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001016 << utils::FormatTimeDelta(duration_according_to_stored_time)
1017 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001018 stored_time = now;
1019 }
1020
1021 SetUpdateTimestampStart(stored_time);
1022}
1023
1024void PayloadState::SetUpdateTimestampStart(const Time& value) {
David Zeuthen9a017f22013-04-11 16:10:26 -07001025 update_timestamp_start_ = value;
Tianjie Xu90aaa102017-10-10 17:39:03 -07001026 metrics_utils::SetUpdateTimestampStart(value, prefs_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001027}
1028
1029void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1030 update_timestamp_end_ = value;
1031 LOG(INFO) << "Update Timestamp End = "
1032 << utils::ToString(update_timestamp_end_);
1033}
1034
1035TimeDelta PayloadState::GetUpdateDurationUptime() {
1036 return update_duration_uptime_;
1037}
1038
1039void PayloadState::LoadUpdateDurationUptime() {
1040 int64_t stored_value;
1041 TimeDelta stored_delta;
1042
1043 CHECK(prefs_);
1044
1045 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1046 // The preference missing is not unexpected - in that case, just
1047 // we'll use zero as the delta
1048 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1049 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1050 stored_delta = TimeDelta::FromSeconds(0);
1051 } else {
1052 stored_delta = TimeDelta::FromInternalValue(stored_value);
1053 }
1054
1055 // Sanity-check: Uptime can never be greater than the wall-clock
1056 // difference (modulo some slack). If it is, report and reset
1057 // to the wall-clock difference.
1058 TimeDelta diff = GetUpdateDuration() - stored_delta;
1059 if (diff < -kDurationSlack) {
1060 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001061 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001062 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001063 << utils::FormatTimeDelta(diff)
1064 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001065 stored_delta = update_duration_current_;
1066 }
1067
1068 SetUpdateDurationUptime(stored_delta);
1069}
1070
Chris Sosabe45bef2013-04-09 18:25:12 -07001071void PayloadState::LoadNumReboots() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001072 SetNumReboots(GetPersistedValue(kPrefsNumReboots, prefs_));
Chris Sosaaa18e162013-06-20 13:20:30 -07001073}
1074
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001075void PayloadState::LoadRollbackHappened() {
1076 CHECK(powerwash_safe_prefs_);
1077 bool rollback_happened = false;
1078 powerwash_safe_prefs_->GetBoolean(kPrefsRollbackHappened, &rollback_happened);
1079 SetRollbackHappened(rollback_happened);
1080}
1081
1082void PayloadState::SetRollbackHappened(bool rollback_happened) {
1083 CHECK(powerwash_safe_prefs_);
1084 LOG(INFO) << "Setting rollback-happened to " << rollback_happened << ".";
1085 rollback_happened_ = rollback_happened;
1086 if (rollback_happened) {
1087 powerwash_safe_prefs_->SetBoolean(kPrefsRollbackHappened,
1088 rollback_happened);
1089 } else {
1090 powerwash_safe_prefs_->Delete(kPrefsRollbackHappened);
1091 }
1092}
1093
Chris Sosaaa18e162013-06-20 13:20:30 -07001094void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001095 CHECK(powerwash_safe_prefs_);
1096 string rollback_version;
1097 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1098 &rollback_version)) {
1099 SetRollbackVersion(rollback_version);
1100 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001101}
1102
1103void PayloadState::SetRollbackVersion(const string& rollback_version) {
1104 CHECK(powerwash_safe_prefs_);
1105 LOG(INFO) << "Blacklisting version "<< rollback_version;
1106 rollback_version_ = rollback_version;
1107 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001108}
1109
David Zeuthen9a017f22013-04-11 16:10:26 -07001110void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1111 const Time& timestamp,
1112 bool use_logging) {
1113 CHECK(prefs_);
1114 update_duration_uptime_ = value;
1115 update_duration_uptime_timestamp_ = timestamp;
1116 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1117 update_duration_uptime_.ToInternalValue());
1118 if (use_logging) {
1119 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001120 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001121 }
1122}
1123
1124void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001125 Time now = system_state_->clock()->GetMonotonicTime();
1126 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001127}
1128
1129void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001130 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001131 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1132 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1133 // We're frequently called so avoid logging this write
1134 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1135}
1136
Jay Srinivasan19409b72013-04-12 19:23:36 -07001137string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1138 return prefix + "-from-" + utils::ToString(source);
1139}
1140
1141void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1142 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001143 SetCurrentBytesDownloaded(source, GetPersistedValue(key, prefs_), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001144}
1145
1146void PayloadState::SetCurrentBytesDownloaded(
1147 DownloadSource source,
1148 uint64_t current_bytes_downloaded,
1149 bool log) {
1150 CHECK(prefs_);
1151
1152 if (source >= kNumDownloadSources)
1153 return;
1154
1155 // Update the in-memory value.
1156 current_bytes_downloaded_[source] = current_bytes_downloaded;
1157
1158 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1159 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1160 LOG_IF(INFO, log) << "Current bytes downloaded for "
1161 << utils::ToString(source) << " = "
1162 << GetCurrentBytesDownloaded(source);
1163}
1164
1165void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1166 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001167 SetTotalBytesDownloaded(source, GetPersistedValue(key, prefs_), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001168}
1169
1170void PayloadState::SetTotalBytesDownloaded(
1171 DownloadSource source,
1172 uint64_t total_bytes_downloaded,
1173 bool log) {
1174 CHECK(prefs_);
1175
1176 if (source >= kNumDownloadSources)
1177 return;
1178
1179 // Update the in-memory value.
1180 total_bytes_downloaded_[source] = total_bytes_downloaded;
1181
1182 // Persist.
1183 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1184 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1185 LOG_IF(INFO, log) << "Total bytes downloaded for "
1186 << utils::ToString(source) << " = "
1187 << GetTotalBytesDownloaded(source);
1188}
1189
David Zeuthena573d6f2013-06-14 16:13:36 -07001190void PayloadState::LoadNumResponsesSeen() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001191 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen, prefs_));
David Zeuthena573d6f2013-06-14 16:13:36 -07001192}
1193
1194void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1195 CHECK(prefs_);
1196 num_responses_seen_ = num_responses_seen;
1197 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1198 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1199}
1200
Jay Srinivasan53173b92013-05-17 17:13:01 -07001201void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001202 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001203
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001204 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001205 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001206 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001207 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1208 } else {
1209 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1210 http_url_ok = true;
1211 }
1212
1213 candidate_urls_.clear();
Sen Jiang0affc2c2017-02-10 15:55:05 -08001214 for (const auto& package : response_.packages) {
1215 candidate_urls_.emplace_back();
1216 for (const string& candidate_url : package.payload_urls) {
1217 if (base::StartsWith(
1218 candidate_url, "http://", base::CompareCase::INSENSITIVE_ASCII) &&
1219 !http_url_ok) {
1220 continue;
1221 }
1222 candidate_urls_.back().push_back(candidate_url);
1223 LOG(INFO) << "Candidate Url" << (candidate_urls_.back().size() - 1)
1224 << ": " << candidate_url;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001225 }
Sen Jiang0affc2c2017-02-10 15:55:05 -08001226 LOG(INFO) << "Found " << candidate_urls_.back().size() << " candidate URLs "
1227 << "out of " << package.payload_urls.size()
1228 << " URLs supplied in package " << candidate_urls_.size() - 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001229 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001230}
1231
David Zeuthene4c58bf2013-06-18 17:26:50 -07001232void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001233 // Flush previous state from abnormal attempt failure, if any.
1234 ReportAndClearPersistedAttemptMetrics();
1235
Alex Deymo569c4242013-07-24 12:01:01 -07001236 // Avoid the UpdateEngineStarted actions if this is not the first time we
1237 // run the update engine since reboot.
1238 if (!system_state_->system_rebooted())
1239 return;
1240
Tianjie Xu90aaa102017-10-10 17:39:03 -07001241 // Report time_to_reboot if we booted into a new update.
1242 metrics_utils::LoadAndReportTimeToReboot(
1243 system_state_->metrics_reporter(), prefs_, system_state_->clock());
1244 prefs_->Delete(kPrefsSystemUpdatedMarker);
1245
Alex Deymo42432912013-07-12 20:21:15 -07001246 // Check if it is needed to send metrics about a failed reboot into a new
1247 // version.
1248 ReportFailedBootIfNeeded();
1249}
1250
1251void PayloadState::ReportFailedBootIfNeeded() {
1252 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1253 // payload was marked as ready immediately before the last reboot, and we
1254 // need to check if such payload successfully rebooted or not.
1255 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001256 int64_t installed_from = 0;
1257 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001258 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1259 return;
1260 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001261 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1262 // partition number. We are now using slot numbers (0 or 1) instead, so
1263 // the following comparison will not match if we are comparing an old
1264 // partition number against a new slot number, which is the correct outcome
1265 // since we successfully booted the new update in that case. If the boot
1266 // failed, we will read this value from the same version, so it will always
1267 // be compatible.
1268 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001269 // A reboot was pending, but the chromebook is again in the same
1270 // BootDevice where the update was installed from.
1271 int64_t target_attempt;
1272 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1273 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1274 "TargetVersionInstalledFrom was present.";
1275 target_attempt = 1;
1276 }
1277
1278 // Report the UMA metric of the current boot failure.
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001279 system_state_->metrics_reporter()->ReportFailedUpdateCount(
1280 target_attempt);
Alex Deymo42432912013-07-12 20:21:15 -07001281 } else {
1282 prefs_->Delete(kPrefsTargetVersionAttempt);
1283 prefs_->Delete(kPrefsTargetVersionUniqueId);
1284 }
1285 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1286 }
1287}
1288
1289void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1290 // Expect to boot into the new partition in the next reboot setting the
1291 // TargetVersion* flags in the Prefs.
1292 string stored_target_version_uid;
1293 string target_version_id;
1294 string target_partition;
1295 int64_t target_attempt;
1296
1297 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1298 prefs_->GetString(kPrefsTargetVersionUniqueId,
1299 &stored_target_version_uid) &&
1300 stored_target_version_uid == target_version_uid) {
1301 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1302 target_attempt = 0;
1303 } else {
1304 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1305 target_attempt = 0;
1306 }
1307 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1308
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001309 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001310 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001311}
1312
1313void PayloadState::ResetUpdateStatus() {
1314 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1315 // rebooted the next boot is not flagged as failed to rebooted into the
1316 // new applied payload.
1317 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1318
1319 // Also decrement the attempt number if it exists.
1320 int64_t target_attempt;
1321 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001322 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001323}
1324
David Zeuthendcba8092013-08-06 12:16:35 -07001325int PayloadState::GetP2PNumAttempts() {
1326 return p2p_num_attempts_;
1327}
1328
1329void PayloadState::SetP2PNumAttempts(int value) {
1330 p2p_num_attempts_ = value;
1331 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1332 CHECK(prefs_);
1333 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1334}
1335
1336void PayloadState::LoadP2PNumAttempts() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001337 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts, prefs_));
David Zeuthendcba8092013-08-06 12:16:35 -07001338}
1339
1340Time PayloadState::GetP2PFirstAttemptTimestamp() {
1341 return p2p_first_attempt_timestamp_;
1342}
1343
1344void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1345 p2p_first_attempt_timestamp_ = time;
1346 LOG(INFO) << "p2p First Attempt Timestamp = "
1347 << utils::ToString(p2p_first_attempt_timestamp_);
1348 CHECK(prefs_);
1349 int64_t stored_value = time.ToInternalValue();
1350 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1351}
1352
1353void PayloadState::LoadP2PFirstAttemptTimestamp() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001354 int64_t stored_value =
1355 GetPersistedValue(kPrefsP2PFirstAttemptTimestamp, prefs_);
David Zeuthendcba8092013-08-06 12:16:35 -07001356 Time stored_time = Time::FromInternalValue(stored_value);
1357 SetP2PFirstAttemptTimestamp(stored_time);
1358}
1359
1360void PayloadState::P2PNewAttempt() {
1361 CHECK(prefs_);
1362 // Set timestamp, if it hasn't been set already
1363 if (p2p_first_attempt_timestamp_.is_null()) {
1364 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1365 }
1366 // Increase number of attempts
1367 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1368}
1369
1370bool PayloadState::P2PAttemptAllowed() {
1371 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1372 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1373 << " which is greater than "
1374 << kMaxP2PAttempts
1375 << " - disallowing p2p.";
1376 return false;
1377 }
1378
1379 if (!p2p_first_attempt_timestamp_.is_null()) {
1380 Time now = system_state_->clock()->GetWallclockTime();
1381 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1382 if (time_spent_attempting_p2p.InSeconds() < 0) {
1383 LOG(ERROR) << "Time spent attempting p2p is negative"
1384 << " - disallowing p2p.";
1385 return false;
1386 }
1387 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1388 LOG(INFO) << "Time spent attempting p2p is "
1389 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1390 << " which is greater than "
1391 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1392 kMaxP2PAttemptTimeSeconds))
1393 << " - disallowing p2p.";
1394 return false;
1395 }
1396 }
1397
1398 return true;
1399}
1400
Sen Jiang0affc2c2017-02-10 15:55:05 -08001401int64_t PayloadState::GetPayloadSize() {
1402 int64_t payload_size = 0;
1403 for (const auto& package : response_.packages)
1404 payload_size += package.size;
1405 return payload_size;
1406}
1407
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001408} // namespace chromeos_update_engine