blob: 72144ef787a961fa5a3b13b0c10b6b00e850eca6 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080016
17#include "update_engine/payload_state.h"
18
Jay Srinivasan08262882012-12-28 19:29:43 -080019#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070020#include <string>
Jay Srinivasan08262882012-12-28 19:29:43 -080021
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080022#include <base/logging.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070023#include <base/strings/string_util.h>
24#include <base/strings/stringprintf.h>
Alex Deymoa2591792015-11-17 00:39:40 -030025#include <metrics/metrics_library.h>
Gilad Arnold1f847232014-04-07 12:07:49 -070026#include <policy/device_policy.h>
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080027
Alex Deymo39910dc2015-11-09 17:04:30 -080028#include "update_engine/common/clock.h"
29#include "update_engine/common/constants.h"
Alex Deymoe88e9fe2016-02-03 16:38:00 -080030#include "update_engine/common/error_code_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080031#include "update_engine/common/hardware_interface.h"
32#include "update_engine/common/prefs.h"
33#include "update_engine/common/utils.h"
Sen Jiang255e22b2016-05-20 16:15:29 -070034#include "update_engine/connection_manager_interface.h"
Tianjie Xu282aa1f2017-09-05 13:42:45 -070035#include "update_engine/metrics_reporter_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080036#include "update_engine/metrics_utils.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070037#include "update_engine/omaha_request_params.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080038#include "update_engine/payload_consumer/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070039#include "update_engine/system_state.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080040
Jay Srinivasan08262882012-12-28 19:29:43 -080041using base::Time;
42using base::TimeDelta;
43using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080044using std::string;
45
46namespace chromeos_update_engine {
47
Tianjie Xu90aaa102017-10-10 17:39:03 -070048using metrics_utils::GetPersistedValue;
49
David Zeuthen9a017f22013-04-11 16:10:26 -070050const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
51
Jay Srinivasan08262882012-12-28 19:29:43 -080052// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070053static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080054
Jay Srinivasan08262882012-12-28 19:29:43 -080055// We want to randomize retry attempts after the backoff by +/- 6 hours.
56static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080057
Colin Howes0e452c92018-11-02 13:18:44 -070058// Limit persisting current update duration uptime to once per second
59static const uint64_t kUptimeResolution = 1;
60
Jay Srinivasan19409b72013-04-12 19:23:36 -070061PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070062 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070063 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070064 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070065 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070066 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070067 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070068 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070069 url_switch_count_(0),
Marton Hunyadye58bddb2018-04-10 20:27:26 +020070 rollback_happened_(false),
David Zeuthenafed4a12014-04-09 15:28:44 -070071 attempt_num_bytes_downloaded_(0),
72 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070073 attempt_type_(AttemptType::kUpdate) {
74 for (int i = 0; i <= kNumDownloadSources; i++)
75 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070076}
77
78bool PayloadState::Initialize(SystemState* system_state) {
79 system_state_ = system_state;
80 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070081 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080082 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080083 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070084 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080085 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080086 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070087 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080088 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070089 LoadUpdateTimestampStart();
90 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
91 // being called before it. Don't reorder.
92 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070093 for (int i = 0; i < kNumDownloadSources; i++) {
94 DownloadSource source = static_cast<DownloadSource>(i);
95 LoadCurrentBytesDownloaded(source);
96 LoadTotalBytesDownloaded(source);
97 }
Chris Sosabe45bef2013-04-09 18:25:12 -070098 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070099 LoadNumResponsesSeen();
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200100 LoadRollbackHappened();
Chris Sosaaa18e162013-06-20 13:20:30 -0700101 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700102 LoadP2PFirstAttemptTimestamp();
103 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800104 return true;
105}
106
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800107void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800108 // Always store the latest response.
109 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800110
Jay Srinivasan53173b92013-05-17 17:13:01 -0700111 // Compute the candidate URLs first as they are used to calculate the
112 // response signature so that a change in enterprise policy for
113 // HTTP downloads being enabled or not could be honored as soon as the
114 // next update check happens.
115 ComputeCandidateUrls();
116
Jay Srinivasan08262882012-12-28 19:29:43 -0800117 // Check if the "signature" of this response (i.e. the fields we care about)
118 // has changed.
119 string new_response_signature = CalculateResponseSignature();
120 bool has_response_changed = (response_signature_ != new_response_signature);
121
122 // If the response has changed, we should persist the new signature and
123 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800124 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800125 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700126 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800127 SetResponseSignature(new_response_signature);
128 ResetPersistedState();
129 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800130 }
131
Sen Jiang97eba342017-05-22 14:34:11 -0700132 // Always start from payload index 0, even for resume, to download partition
133 // info from previous payloads.
134 payload_index_ = 0;
135
Jay Srinivasan08262882012-12-28 19:29:43 -0800136 // This is the earliest point at which we can validate whether the URL index
137 // we loaded from the persisted state is a valid value. If the response
138 // hasn't changed but the URL index is invalid, it's indicative of some
139 // tampering of the persisted state.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800140 if (payload_index_ >= candidate_urls_.size() ||
141 url_index_ >= candidate_urls_[payload_index_].size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800142 LOG(INFO) << "Resetting all payload state as the url index seems to have "
143 "been tampered with";
144 ResetPersistedState();
145 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800146 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700147
148 // Update the current download source which depends on the latest value of
149 // the response.
150 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800151}
152
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700153void PayloadState::SetUsingP2PForDownloading(bool value) {
154 using_p2p_for_downloading_ = value;
155 // Update the current download source which depends on whether we are
156 // using p2p or not.
157 UpdateCurrentDownloadSource();
158}
159
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800160void PayloadState::DownloadComplete() {
161 LOG(INFO) << "Payload downloaded successfully";
162 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700163 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800164}
165
166void PayloadState::DownloadProgress(size_t count) {
167 if (count == 0)
168 return;
169
David Zeuthen9a017f22013-04-11 16:10:26 -0700170 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700171 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700172
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800173 // We've received non-zero bytes from a recent download operation. Since our
174 // URL failure count is meant to penalize a URL only for consecutive
175 // failures, downloading bytes successfully means we should reset the failure
176 // count (as we know at least that the URL is working). In future, we can
177 // design this to be more sophisticated to check for more intelligent failure
178 // patterns, but right now, even 1 byte downloaded will mark the URL to be
179 // good unless it hits 10 (or configured number of) consecutive failures
180 // again.
181
182 if (GetUrlFailureCount() == 0)
183 return;
184
185 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
186 << " to 0 as we received " << count << " bytes successfully";
187 SetUrlFailureCount(0);
188}
189
David Zeuthenafed4a12014-04-09 15:28:44 -0700190void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700191 // Flush previous state from abnormal attempt failure, if any.
192 ReportAndClearPersistedAttemptMetrics();
193
David Zeuthenafed4a12014-04-09 15:28:44 -0700194 attempt_type_ = attempt_type;
195
David Zeuthen33bae492014-02-25 16:16:18 -0800196 ClockInterface *clock = system_state_->clock();
197 attempt_start_time_boot_ = clock->GetBootTime();
198 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800199 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700200
201 metrics::ConnectionType type;
Sen Jiang255e22b2016-05-20 16:15:29 -0700202 ConnectionType network_connection_type;
203 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700204 ConnectionManagerInterface* connection_manager =
205 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700206 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700207 &tethering)) {
208 LOG(ERROR) << "Failed to determine connection type.";
209 type = metrics::ConnectionType::kUnknown;
210 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800211 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700212 }
213 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700214
215 if (attempt_type == AttemptType::kUpdate)
216 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800217}
218
Chris Sosabe45bef2013-04-09 18:25:12 -0700219void PayloadState::UpdateResumed() {
220 LOG(INFO) << "Resuming an update that was previously started.";
221 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700222 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700223}
224
Jay Srinivasan19409b72013-04-12 19:23:36 -0700225void PayloadState::UpdateRestarted() {
226 LOG(INFO) << "Starting a new update";
227 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700228 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700229 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700230}
231
David Zeuthen9a017f22013-04-11 16:10:26 -0700232void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700233 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700234 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700235 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800236
David Zeuthen96197df2014-04-16 12:22:39 -0700237 switch (attempt_type_) {
238 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700239 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700240 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700241 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700242 break;
243
244 case AttemptType::kRollback:
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700245 system_state_->metrics_reporter()->ReportRollbackMetrics(
246 metrics::RollbackResult::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700247 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700248 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700249
250 // Reset the number of responses seen since it counts from the last
251 // successful update, e.g. now.
252 SetNumResponsesSeen(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700253 SetPayloadIndex(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700254
Tianjie Xu90aaa102017-10-10 17:39:03 -0700255 metrics_utils::SetSystemUpdatedMarker(system_state_->clock(), prefs_);
David Zeuthen9a017f22013-04-11 16:10:26 -0700256}
257
David Zeuthena99981f2013-04-29 13:42:47 -0700258void PayloadState::UpdateFailed(ErrorCode error) {
259 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800260 LOG(INFO) << "Updating payload state for error code: " << base_error
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800261 << " (" << utils::ErrorCodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800262
Jay Srinivasan53173b92013-05-17 17:13:01 -0700263 if (candidate_urls_.size() == 0) {
264 // This means we got this error even before we got a valid Omaha response
265 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800266 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800267 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
268 return;
269 }
270
David Zeuthen96197df2014-04-16 12:22:39 -0700271 switch (attempt_type_) {
272 case AttemptType::kUpdate:
273 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700274 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700275 break;
276
277 case AttemptType::kRollback:
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700278 system_state_->metrics_reporter()->ReportRollbackMetrics(
279 metrics::RollbackResult::kFailed);
David Zeuthen96197df2014-04-16 12:22:39 -0700280 break;
281 }
David Zeuthen33bae492014-02-25 16:16:18 -0800282
Shuqian Zhao29971732016-02-05 11:29:32 -0800283
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800284 switch (base_error) {
285 // Errors which are good indicators of a problem with a particular URL or
286 // the protocol used in the URL or entities in the communication channel
287 // (e.g. proxies). We should try the next available URL in the next update
288 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700289 case ErrorCode::kPayloadHashMismatchError:
290 case ErrorCode::kPayloadSizeMismatchError:
291 case ErrorCode::kDownloadPayloadVerificationError:
292 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
293 case ErrorCode::kSignedDeltaPayloadExpectedError:
294 case ErrorCode::kDownloadInvalidMetadataMagicString:
295 case ErrorCode::kDownloadSignatureMissingInManifest:
296 case ErrorCode::kDownloadManifestParseError:
297 case ErrorCode::kDownloadMetadataSignatureError:
298 case ErrorCode::kDownloadMetadataSignatureVerificationError:
299 case ErrorCode::kDownloadMetadataSignatureMismatch:
300 case ErrorCode::kDownloadOperationHashVerificationError:
301 case ErrorCode::kDownloadOperationExecutionError:
302 case ErrorCode::kDownloadOperationHashMismatch:
303 case ErrorCode::kDownloadInvalidMetadataSize:
304 case ErrorCode::kDownloadInvalidMetadataSignature:
305 case ErrorCode::kDownloadOperationHashMissingError:
306 case ErrorCode::kDownloadMetadataSignatureMissingError:
307 case ErrorCode::kPayloadMismatchedType:
308 case ErrorCode::kUnsupportedMajorPayloadVersion:
309 case ErrorCode::kUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800310 IncrementUrlIndex();
311 break;
312
313 // Errors which seem to be just transient network/communication related
314 // failures and do not indicate any inherent problem with the URL itself.
315 // So, we should keep the current URL but just increment the
316 // failure count to give it more chances. This way, while we maximize our
317 // chances of downloading from the URLs that appear earlier in the response
318 // (because download from a local server URL that appears earlier in a
319 // response is preferable than downloading from the next URL which could be
320 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700321
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700322 case ErrorCode::kError:
323 case ErrorCode::kDownloadTransferError:
324 case ErrorCode::kDownloadWriteError:
325 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700326 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800327 IncrementFailureCount();
328 break;
329
330 // Errors which are not specific to a URL and hence shouldn't result in
331 // the URL being penalized. This can happen in two cases:
332 // 1. We haven't started downloading anything: These errors don't cost us
333 // anything in terms of actual payload bytes, so we should just do the
334 // regular retries at the next update check.
335 // 2. We have successfully downloaded the payload: In this case, the
336 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800337 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800338 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700339 case ErrorCode::kOmahaRequestError:
340 case ErrorCode::kOmahaResponseHandlerError:
341 case ErrorCode::kPostinstallRunnerError:
342 case ErrorCode::kFilesystemCopierError:
343 case ErrorCode::kInstallDeviceOpenError:
344 case ErrorCode::kKernelDeviceOpenError:
345 case ErrorCode::kDownloadNewPartitionInfoError:
346 case ErrorCode::kNewRootfsVerificationError:
347 case ErrorCode::kNewKernelVerificationError:
348 case ErrorCode::kPostinstallBootedFromFirmwareB:
349 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
350 case ErrorCode::kOmahaRequestEmptyResponseError:
351 case ErrorCode::kOmahaRequestXMLParseError:
352 case ErrorCode::kOmahaResponseInvalid:
353 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
354 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700355 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700356 case ErrorCode::kOmahaUpdateDeferredForBackoff:
357 case ErrorCode::kPostinstallPowerwashError:
358 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400359 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700360 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800361 case ErrorCode::kUserCanceled:
Weidong Guo421ff332017-04-17 10:08:38 -0700362 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
Sen Jiang02c49422017-10-31 15:14:11 -0700363 case ErrorCode::kUpdatedButNotActive:
Sen Jiang3978ddd2018-03-22 18:05:44 -0700364 case ErrorCode::kNoUpdate:
Marton Hunyady199152d2018-05-07 19:08:48 +0200365 case ErrorCode::kRollbackNotPossible:
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700366 case ErrorCode::kFirstActiveOmahaPingSentPersistenceError:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800367 LOG(INFO) << "Not incrementing URL index or failure count for this error";
368 break;
369
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700370 case ErrorCode::kSuccess: // success code
371 case ErrorCode::kUmaReportedMax: // not an error code
372 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
373 case ErrorCode::kDevModeFlag: // not an error code
374 case ErrorCode::kResumedFlag: // not an error code
375 case ErrorCode::kTestImageFlag: // not an error code
376 case ErrorCode::kTestOmahaUrlFlag: // not an error code
377 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800378 // These shouldn't happen. Enumerating these explicitly here so that we
379 // can let the compiler warn about new error codes that are added to
380 // action_processor.h but not added here.
381 LOG(WARNING) << "Unexpected error code for UpdateFailed";
382 break;
383
384 // Note: Not adding a default here so as to let the compiler warn us of
385 // any new enums that were added in the .h but not listed in this switch.
386 }
387}
388
Jay Srinivasan08262882012-12-28 19:29:43 -0800389bool PayloadState::ShouldBackoffDownload() {
390 if (response_.disable_payload_backoff) {
391 LOG(INFO) << "Payload backoff logic is disabled. "
392 "Can proceed with the download";
393 return false;
394 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700395 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700396 LOG(INFO) << "Payload backoff logic is disabled because download "
397 << "will happen from local peer (via p2p).";
398 return false;
399 }
400 if (system_state_->request_params()->interactive()) {
401 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
402 return false;
403 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700404 for (const auto& package : response_.packages) {
405 if (package.is_delta) {
406 // If delta payloads fail, we want to fallback quickly to full payloads as
407 // they are more likely to succeed. Exponential backoffs would greatly
408 // slow down the fallback to full payloads. So we don't backoff for delta
409 // payloads.
410 LOG(INFO) << "No backoffs for delta payloads. "
411 << "Can proceed with the download";
412 return false;
413 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800414 }
415
Amin Hassaniffb6d802018-03-30 11:43:57 -0700416 if (!system_state_->hardware()->IsOfficialBuild() &&
417 !prefs_->Exists(kPrefsNoIgnoreBackoff)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800418 // Backoffs are needed only for official builds. We do not want any delays
Amin Hassaniffb6d802018-03-30 11:43:57 -0700419 // or update failures due to backoffs during testing or development. Unless
420 // the |kPrefsNoIgnoreBackoff| is manually set.
Jay Srinivasan08262882012-12-28 19:29:43 -0800421 LOG(INFO) << "No backoffs for test/dev images. "
422 << "Can proceed with the download";
423 return false;
424 }
425
426 if (backoff_expiry_time_.is_null()) {
427 LOG(INFO) << "No backoff expiry time has been set. "
428 << "Can proceed with the download";
429 return false;
430 }
431
432 if (backoff_expiry_time_ < Time::Now()) {
433 LOG(INFO) << "The backoff expiry time ("
434 << utils::ToString(backoff_expiry_time_)
435 << ") has elapsed. Can proceed with the download";
436 return false;
437 }
438
439 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
440 << utils::ToString(backoff_expiry_time_);
441 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800442}
443
Chris Sosaaa18e162013-06-20 13:20:30 -0700444void PayloadState::Rollback() {
445 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700446 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700447}
448
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800449void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700450 // Update the payload attempt number for both payload types: full and delta.
451 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
452}
453
454void PayloadState::IncrementFullPayloadAttemptNumber() {
455 // Update the payload attempt number for full payloads and the backoff time.
Sen Jiangcdd52062017-05-18 15:33:10 -0700456 if (response_.packages[payload_index_].is_delta) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800457 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
458 return;
459 }
460
Alex Deymo29b51d92013-07-09 15:26:24 -0700461 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700462 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800463 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800464}
465
466void PayloadState::IncrementUrlIndex() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800467 size_t next_url_index = url_index_ + 1;
468 size_t max_url_size = 0;
469 for (const auto& urls : candidate_urls_)
470 max_url_size = std::max(max_url_size, urls.size());
471 if (next_url_index < max_url_size) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800472 LOG(INFO) << "Incrementing the URL index for next attempt";
473 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800474 } else {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800475 LOG(INFO) << "Resetting the current URL index (" << url_index_ << ") to "
476 << "0 as we only have " << max_url_size << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800477 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700478 IncrementPayloadAttemptNumber();
479 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800480 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800481
David Zeuthencc6f9962013-04-18 11:57:24 -0700482 // If we have multiple URLs, record that we just switched to another one
Sen Jiang0affc2c2017-02-10 15:55:05 -0800483 if (max_url_size > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700484 SetUrlSwitchCount(url_switch_count_ + 1);
485
Jay Srinivasan08262882012-12-28 19:29:43 -0800486 // Whenever we update the URL index, we should also clear the URL failure
487 // count so we can start over fresh for the new URL.
488 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800489}
490
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800491void PayloadState::IncrementFailureCount() {
492 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800493 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800494 LOG(INFO) << "Incrementing the URL failure count";
495 SetUrlFailureCount(next_url_failure_count);
496 } else {
497 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
498 << ". Trying next available URL";
499 IncrementUrlIndex();
500 }
501}
502
Jay Srinivasan08262882012-12-28 19:29:43 -0800503void PayloadState::UpdateBackoffExpiryTime() {
504 if (response_.disable_payload_backoff) {
505 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
506 SetBackoffExpiryTime(Time());
507 return;
508 }
509
Alex Deymo820cc702013-06-28 15:43:46 -0700510 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800511 SetBackoffExpiryTime(Time());
512 return;
513 }
514
515 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700516 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800517 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700518 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700519 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800520
521 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
522 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700523 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800524
525 // The number of days is the minimum of 2 raised to (payload_attempt_number
526 // - 1) or kMaxBackoffDays.
527 num_days = min(num_days << power, kMaxBackoffDays);
528
529 // We don't want all retries to happen exactly at the same time when
530 // retrying after backoff. So add some random minutes to fuzz.
531 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
532 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
533 TimeDelta::FromMinutes(fuzz_minutes);
534 LOG(INFO) << "Incrementing the backoff expiry time by "
535 << utils::FormatTimeDelta(next_backoff_interval);
536 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
537}
538
Jay Srinivasan19409b72013-04-12 19:23:36 -0700539void PayloadState::UpdateCurrentDownloadSource() {
540 current_download_source_ = kNumDownloadSources;
541
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700542 if (using_p2p_for_downloading_) {
543 current_download_source_ = kDownloadSourceHttpPeer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800544 } else if (payload_index_ < candidate_urls_.size() &&
545 candidate_urls_[payload_index_].size() != 0) {
546 const string& current_url = candidate_urls_[payload_index_][GetUrlIndex()];
547 if (base::StartsWith(
548 current_url, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700549 current_download_source_ = kDownloadSourceHttpsServer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800550 } else if (base::StartsWith(current_url,
551 "http://",
Alex Vakulenko0103c362016-01-20 07:56:15 -0800552 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700553 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800554 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700555 }
556
557 LOG(INFO) << "Current download source: "
558 << utils::ToString(current_download_source_);
559}
560
561void PayloadState::UpdateBytesDownloaded(size_t count) {
562 SetCurrentBytesDownloaded(
563 current_download_source_,
564 GetCurrentBytesDownloaded(current_download_source_) + count,
565 false);
566 SetTotalBytesDownloaded(
567 current_download_source_,
568 GetTotalBytesDownloaded(current_download_source_) + count,
569 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800570
571 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700572}
573
David Zeuthen33bae492014-02-25 16:16:18 -0800574PayloadType PayloadState::CalculatePayloadType() {
Sen Jiangcdd52062017-05-18 15:33:10 -0700575 for (const auto& package : response_.packages) {
576 if (package.is_delta) {
577 return kPayloadTypeDelta;
578 }
David Zeuthen33bae492014-02-25 16:16:18 -0800579 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700580 OmahaRequestParams* params = system_state_->request_params();
581 if (params->delta_okay()) {
582 return kPayloadTypeFull;
583 }
584 // Full payload, delta was not allowed by request.
585 return kPayloadTypeForcedFull;
David Zeuthen33bae492014-02-25 16:16:18 -0800586}
587
588// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
589// metrics if the attempt ends abnormally, e.g. if the update_engine
590// process crashes or the device is rebooted. See
591// http://crbug.com/357676
592void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
593 int attempt_number = GetPayloadAttemptNumber();
594
595 PayloadType payload_type = CalculatePayloadType();
596
Sen Jiang0affc2c2017-02-10 15:55:05 -0800597 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800598
599 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
600
601 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700602 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
603 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800604 attempt_start_time_monotonic_;
605
606 int64_t payload_download_speed_bps = 0;
607 int64_t usec = duration_uptime.InMicroseconds();
608 if (usec > 0) {
609 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
610 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
611 payload_download_speed_bps = static_cast<int64_t>(bps);
612 }
613
614 DownloadSource download_source = current_download_source_;
615
616 metrics::DownloadErrorCode payload_download_error_code =
617 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700618 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800619 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800620
621 // Add additional detail to AttemptResult
622 switch (attempt_result) {
623 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800624 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800625 break;
626
627 case metrics::AttemptResult::kInternalError:
628 internal_error_code = code;
629 break;
630
631 // Explicit fall-through for cases where we do not have additional
632 // detail. We avoid the default keyword to force people adding new
633 // AttemptResult values to visit this code and examine whether
634 // additional detail is needed.
635 case metrics::AttemptResult::kUpdateSucceeded:
636 case metrics::AttemptResult::kMetadataMalformed:
637 case metrics::AttemptResult::kOperationMalformed:
638 case metrics::AttemptResult::kOperationExecutionError:
639 case metrics::AttemptResult::kMetadataVerificationFailed:
640 case metrics::AttemptResult::kPayloadVerificationFailed:
641 case metrics::AttemptResult::kVerificationFailed:
642 case metrics::AttemptResult::kPostInstallFailed:
643 case metrics::AttemptResult::kAbnormalTermination:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800644 case metrics::AttemptResult::kUpdateCanceled:
Sen Jiang02c49422017-10-31 15:14:11 -0700645 case metrics::AttemptResult::kUpdateSucceededNotActive:
David Zeuthen33bae492014-02-25 16:16:18 -0800646 case metrics::AttemptResult::kNumConstants:
647 case metrics::AttemptResult::kUnset:
648 break;
649 }
650
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700651 system_state_->metrics_reporter()->ReportUpdateAttemptMetrics(
652 system_state_,
653 attempt_number,
654 payload_type,
655 duration,
656 duration_uptime,
657 payload_size,
Tianjie Xu1f93d092017-10-09 12:13:29 -0700658 attempt_result,
659 internal_error_code);
660
661 system_state_->metrics_reporter()->ReportUpdateAttemptDownloadMetrics(
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700662 payload_bytes_downloaded,
663 payload_download_speed_bps,
664 download_source,
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700665 payload_download_error_code,
666 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800667}
668
David Zeuthen4e1d1492014-04-25 13:12:27 -0700669void PayloadState::PersistAttemptMetrics() {
670 // TODO(zeuthen): For now we only persist whether an attempt was in
671 // progress and not values/metrics related to the attempt. This
672 // means that when this happens, of all the UpdateEngine.Attempt.*
673 // metrics, only UpdateEngine.Attempt.Result is reported (with the
674 // value |kAbnormalTermination|). In the future we might want to
675 // persist more data so we can report other metrics in the
676 // UpdateEngine.Attempt.* namespace when this happens.
677 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
678}
679
680void PayloadState::ClearPersistedAttemptMetrics() {
681 prefs_->Delete(kPrefsAttemptInProgress);
682}
683
684void PayloadState::ReportAndClearPersistedAttemptMetrics() {
685 bool attempt_in_progress = false;
686 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
687 return;
688 if (!attempt_in_progress)
689 return;
690
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700691 system_state_->metrics_reporter()
692 ->ReportAbnormallyTerminatedUpdateAttemptMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700693
694 ClearPersistedAttemptMetrics();
695}
696
David Zeuthen33bae492014-02-25 16:16:18 -0800697void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700698 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800699
700 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800701 int64_t total_bytes_by_source[kNumDownloadSources];
702 int64_t successful_bytes = 0;
703 int64_t total_bytes = 0;
704 int64_t successful_mbs = 0;
705 int64_t total_mbs = 0;
706
Jay Srinivasan19409b72013-04-12 19:23:36 -0700707 for (int i = 0; i < kNumDownloadSources; i++) {
708 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800709 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700710
David Zeuthen44848602013-06-24 13:32:14 -0700711 // Only consider this download source (and send byte counts) as
712 // having been used if we downloaded a non-trivial amount of bytes
713 // (e.g. at least 1 MiB) that contributed to the final success of
714 // the update. Otherwise we're going to end up with a lot of
715 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700716
David Zeuthen33bae492014-02-25 16:16:18 -0800717 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800718 successful_bytes += bytes;
719 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700720 SetCurrentBytesDownloaded(source, 0, true);
721
David Zeuthen33bae492014-02-25 16:16:18 -0800722 bytes = GetTotalBytesDownloaded(source);
723 total_bytes_by_source[i] = bytes;
724 total_bytes += bytes;
725 total_mbs += bytes / kNumBytesInOneMiB;
726 SetTotalBytesDownloaded(source, 0, true);
727 }
728
729 int download_overhead_percentage = 0;
730 if (successful_bytes > 0) {
731 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
732 successful_bytes;
733 }
734
735 int url_switch_count = static_cast<int>(url_switch_count_);
736
737 int reboot_count = GetNumReboots();
738
739 SetNumReboots(0);
740
741 TimeDelta duration = GetUpdateDuration();
Sen Jiang8712e962018-05-08 12:12:28 -0700742 TimeDelta duration_uptime = GetUpdateDurationUptime();
David Zeuthen33bae492014-02-25 16:16:18 -0800743
744 prefs_->Delete(kPrefsUpdateTimestampStart);
745 prefs_->Delete(kPrefsUpdateDurationUptime);
746
747 PayloadType payload_type = CalculatePayloadType();
748
Sen Jiang0affc2c2017-02-10 15:55:05 -0800749 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800750
751 int attempt_count = GetPayloadAttemptNumber();
752
753 int updates_abandoned_count = num_responses_seen_ - 1;
754
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700755 system_state_->metrics_reporter()->ReportSuccessfulUpdateMetrics(
756 attempt_count,
757 updates_abandoned_count,
758 payload_type,
759 payload_size,
760 total_bytes_by_source,
761 download_overhead_percentage,
762 duration,
Sen Jiang8712e962018-05-08 12:12:28 -0700763 duration_uptime,
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700764 reboot_count,
765 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700766}
767
768void PayloadState::UpdateNumReboots() {
769 // We only update the reboot count when the system has been detected to have
770 // been rebooted.
771 if (!system_state_->system_rebooted()) {
772 return;
773 }
774
775 SetNumReboots(GetNumReboots() + 1);
776}
777
778void PayloadState::SetNumReboots(uint32_t num_reboots) {
Chris Sosabe45bef2013-04-09 18:25:12 -0700779 num_reboots_ = num_reboots;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700780 metrics_utils::SetNumReboots(num_reboots, prefs_);
Chris Sosabe45bef2013-04-09 18:25:12 -0700781}
782
Jay Srinivasan08262882012-12-28 19:29:43 -0800783void PayloadState::ResetPersistedState() {
784 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700785 SetFullPayloadAttemptNumber(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700786 SetPayloadIndex(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800787 SetUrlIndex(0);
788 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700789 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700790 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700791 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700792 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700793 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700794 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700795 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700796 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700797 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700798 SetScatteringWaitPeriod(TimeDelta());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700799 SetStagingWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700800}
801
802void PayloadState::ResetRollbackVersion() {
803 CHECK(powerwash_safe_prefs_);
804 rollback_version_ = "";
805 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700806}
807
808void PayloadState::ResetDownloadSourcesOnNewUpdate() {
809 for (int i = 0; i < kNumDownloadSources; i++) {
810 DownloadSource source = static_cast<DownloadSource>(i);
811 SetCurrentBytesDownloaded(source, 0, true);
812 // Note: Not resetting the TotalBytesDownloaded as we want that metric
813 // to count the bytes downloaded across various update attempts until
814 // we have successfully applied the update.
815 }
816}
817
Jay Srinivasan08262882012-12-28 19:29:43 -0800818string PayloadState::CalculateResponseSignature() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800819 string response_sign;
820 for (size_t i = 0; i < response_.packages.size(); i++) {
821 const auto& package = response_.packages[i];
822 response_sign += base::StringPrintf(
823 "Payload %zu:\n"
824 " Size = %ju\n"
825 " Sha256 Hash = %s\n"
826 " Metadata Size = %ju\n"
827 " Metadata Signature = %s\n"
Sen Jiangcdd52062017-05-18 15:33:10 -0700828 " Is Delta = %d\n"
Sen Jiang0affc2c2017-02-10 15:55:05 -0800829 " NumURLs = %zu\n",
830 i,
831 static_cast<uintmax_t>(package.size),
832 package.hash.c_str(),
833 static_cast<uintmax_t>(package.metadata_size),
834 package.metadata_signature.c_str(),
Sen Jiangcdd52062017-05-18 15:33:10 -0700835 package.is_delta,
Sen Jiang0affc2c2017-02-10 15:55:05 -0800836 candidate_urls_[i].size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800837
Sen Jiang0affc2c2017-02-10 15:55:05 -0800838 for (size_t j = 0; j < candidate_urls_[i].size(); j++)
839 response_sign += base::StringPrintf(
840 " Candidate Url%zu = %s\n", j, candidate_urls_[i][j].c_str());
841 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800842
Alex Vakulenko75039d72014-03-25 12:36:28 -0700843 response_sign += base::StringPrintf(
Alex Vakulenko75039d72014-03-25 12:36:28 -0700844 "Max Failure Count Per Url = %d\n"
845 "Disable Payload Backoff = %d\n",
Alex Vakulenko75039d72014-03-25 12:36:28 -0700846 response_.max_failure_count_per_url,
847 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800848 return response_sign;
849}
850
851void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800852 CHECK(prefs_);
853 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800854 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
855 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
856 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800857 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800858}
859
Jay Srinivasan19409b72013-04-12 19:23:36 -0700860void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800861 CHECK(prefs_);
862 response_signature_ = response_signature;
863 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
864 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
865}
866
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800867void PayloadState::LoadPayloadAttemptNumber() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700868 SetPayloadAttemptNumber(
869 GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800870}
871
Alex Deymo820cc702013-06-28 15:43:46 -0700872void PayloadState::LoadFullPayloadAttemptNumber() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700873 SetFullPayloadAttemptNumber(
874 GetPersistedValue(kPrefsFullPayloadAttemptNumber, prefs_));
Alex Deymo820cc702013-06-28 15:43:46 -0700875}
876
877void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800878 payload_attempt_number_ = payload_attempt_number;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700879 metrics_utils::SetPayloadAttemptNumber(payload_attempt_number, prefs_);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800880}
881
Alex Deymo820cc702013-06-28 15:43:46 -0700882void PayloadState::SetFullPayloadAttemptNumber(
883 int full_payload_attempt_number) {
884 CHECK(prefs_);
885 full_payload_attempt_number_ = full_payload_attempt_number;
886 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
887 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
888 full_payload_attempt_number_);
889}
890
Sen Jiang5ae865b2017-04-18 14:24:40 -0700891void PayloadState::SetPayloadIndex(size_t payload_index) {
892 CHECK(prefs_);
893 payload_index_ = payload_index;
894 LOG(INFO) << "Payload Index = " << payload_index_;
895 prefs_->SetInt64(kPrefsUpdateStatePayloadIndex, payload_index_);
896}
897
898bool PayloadState::NextPayload() {
899 if (payload_index_ + 1 >= candidate_urls_.size())
900 return false;
901 SetPayloadIndex(payload_index_ + 1);
902 return true;
903}
904
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800905void PayloadState::LoadUrlIndex() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700906 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex, prefs_));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800907}
908
909void PayloadState::SetUrlIndex(uint32_t url_index) {
910 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800911 url_index_ = url_index;
912 LOG(INFO) << "Current URL Index = " << url_index_;
913 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700914
915 // Also update the download source, which is purely dependent on the
916 // current URL index alone.
917 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800918}
919
Gilad Arnold519cfc72014-10-02 10:34:54 -0700920void PayloadState::LoadScatteringWaitPeriod() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700921 SetScatteringWaitPeriod(TimeDelta::FromSeconds(
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700922 GetPersistedValue(kPrefsWallClockScatteringWaitPeriod, prefs_)));
Gilad Arnold519cfc72014-10-02 10:34:54 -0700923}
924
Alex Deymof329b932014-10-30 01:37:48 -0700925void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700926 CHECK(prefs_);
927 scattering_wait_period_ = wait_period;
928 LOG(INFO) << "Scattering Wait Period (seconds) = "
929 << scattering_wait_period_.InSeconds();
930 if (scattering_wait_period_.InSeconds() > 0) {
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700931 prefs_->SetInt64(kPrefsWallClockScatteringWaitPeriod,
Gilad Arnold519cfc72014-10-02 10:34:54 -0700932 scattering_wait_period_.InSeconds());
933 } else {
Adolfo Victoriad3a1e352018-07-16 11:40:47 -0700934 prefs_->Delete(kPrefsWallClockScatteringWaitPeriod);
935 }
936}
937
938void PayloadState::LoadStagingWaitPeriod() {
939 SetStagingWaitPeriod(TimeDelta::FromSeconds(
940 GetPersistedValue(kPrefsWallClockStagingWaitPeriod, prefs_)));
941}
942
943void PayloadState::SetStagingWaitPeriod(TimeDelta wait_period) {
944 CHECK(prefs_);
945 staging_wait_period_ = wait_period;
946 LOG(INFO) << "Staging Wait Period (days) =" << staging_wait_period_.InDays();
947 if (staging_wait_period_.InSeconds() > 0) {
948 prefs_->SetInt64(kPrefsWallClockStagingWaitPeriod,
949 staging_wait_period_.InSeconds());
950 } else {
951 prefs_->Delete(kPrefsWallClockStagingWaitPeriod);
Gilad Arnold519cfc72014-10-02 10:34:54 -0700952 }
953}
954
David Zeuthencc6f9962013-04-18 11:57:24 -0700955void PayloadState::LoadUrlSwitchCount() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700956 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount, prefs_));
David Zeuthencc6f9962013-04-18 11:57:24 -0700957}
958
959void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
960 CHECK(prefs_);
961 url_switch_count_ = url_switch_count;
962 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
963 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
964}
965
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800966void PayloadState::LoadUrlFailureCount() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700967 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount, prefs_));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800968}
969
970void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
971 CHECK(prefs_);
972 url_failure_count_ = url_failure_count;
973 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
974 << ")'s Failure Count = " << url_failure_count_;
975 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800976}
977
Jay Srinivasan08262882012-12-28 19:29:43 -0800978void PayloadState::LoadBackoffExpiryTime() {
979 CHECK(prefs_);
980 int64_t stored_value;
981 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
982 return;
983
984 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
985 return;
986
987 Time stored_time = Time::FromInternalValue(stored_value);
988 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
989 LOG(ERROR) << "Invalid backoff expiry time ("
990 << utils::ToString(stored_time)
991 << ") in persisted state. Resetting.";
992 stored_time = Time();
993 }
994 SetBackoffExpiryTime(stored_time);
995}
996
997void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
998 CHECK(prefs_);
999 backoff_expiry_time_ = new_time;
1000 LOG(INFO) << "Backoff Expiry Time = "
1001 << utils::ToString(backoff_expiry_time_);
1002 prefs_->SetInt64(kPrefsBackoffExpiryTime,
1003 backoff_expiry_time_.ToInternalValue());
1004}
1005
David Zeuthen9a017f22013-04-11 16:10:26 -07001006TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001007 Time end_time = update_timestamp_end_.is_null()
1008 ? system_state_->clock()->GetWallclockTime() :
1009 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001010 return end_time - update_timestamp_start_;
1011}
1012
1013void PayloadState::LoadUpdateTimestampStart() {
1014 int64_t stored_value;
1015 Time stored_time;
1016
1017 CHECK(prefs_);
1018
David Zeuthenf413fe52013-04-22 14:04:39 -07001019 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001020
1021 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1022 // The preference missing is not unexpected - in that case, just
1023 // use the current time as start time
1024 stored_time = now;
1025 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1026 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1027 stored_time = now;
1028 } else {
1029 stored_time = Time::FromInternalValue(stored_value);
1030 }
1031
1032 // Sanity check: If the time read from disk is in the future
1033 // (modulo some slack to account for possible NTP drift
1034 // adjustments), something is fishy and we should report and
1035 // reset.
1036 TimeDelta duration_according_to_stored_time = now - stored_time;
1037 if (duration_according_to_stored_time < -kDurationSlack) {
1038 LOG(ERROR) << "The UpdateTimestampStart value ("
1039 << utils::ToString(stored_time)
1040 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001041 << utils::FormatTimeDelta(duration_according_to_stored_time)
1042 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001043 stored_time = now;
1044 }
1045
1046 SetUpdateTimestampStart(stored_time);
1047}
1048
1049void PayloadState::SetUpdateTimestampStart(const Time& value) {
David Zeuthen9a017f22013-04-11 16:10:26 -07001050 update_timestamp_start_ = value;
Tianjie Xu90aaa102017-10-10 17:39:03 -07001051 metrics_utils::SetUpdateTimestampStart(value, prefs_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001052}
1053
1054void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1055 update_timestamp_end_ = value;
1056 LOG(INFO) << "Update Timestamp End = "
1057 << utils::ToString(update_timestamp_end_);
1058}
1059
1060TimeDelta PayloadState::GetUpdateDurationUptime() {
1061 return update_duration_uptime_;
1062}
1063
1064void PayloadState::LoadUpdateDurationUptime() {
1065 int64_t stored_value;
1066 TimeDelta stored_delta;
1067
1068 CHECK(prefs_);
1069
1070 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1071 // The preference missing is not unexpected - in that case, just
1072 // we'll use zero as the delta
1073 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1074 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1075 stored_delta = TimeDelta::FromSeconds(0);
1076 } else {
1077 stored_delta = TimeDelta::FromInternalValue(stored_value);
1078 }
1079
1080 // Sanity-check: Uptime can never be greater than the wall-clock
1081 // difference (modulo some slack). If it is, report and reset
1082 // to the wall-clock difference.
1083 TimeDelta diff = GetUpdateDuration() - stored_delta;
1084 if (diff < -kDurationSlack) {
1085 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001086 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001087 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001088 << utils::FormatTimeDelta(diff)
1089 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001090 stored_delta = update_duration_current_;
1091 }
1092
1093 SetUpdateDurationUptime(stored_delta);
1094}
1095
Chris Sosabe45bef2013-04-09 18:25:12 -07001096void PayloadState::LoadNumReboots() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001097 SetNumReboots(GetPersistedValue(kPrefsNumReboots, prefs_));
Chris Sosaaa18e162013-06-20 13:20:30 -07001098}
1099
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001100void PayloadState::LoadRollbackHappened() {
1101 CHECK(powerwash_safe_prefs_);
1102 bool rollback_happened = false;
1103 powerwash_safe_prefs_->GetBoolean(kPrefsRollbackHappened, &rollback_happened);
1104 SetRollbackHappened(rollback_happened);
1105}
1106
1107void PayloadState::SetRollbackHappened(bool rollback_happened) {
1108 CHECK(powerwash_safe_prefs_);
1109 LOG(INFO) << "Setting rollback-happened to " << rollback_happened << ".";
1110 rollback_happened_ = rollback_happened;
1111 if (rollback_happened) {
1112 powerwash_safe_prefs_->SetBoolean(kPrefsRollbackHappened,
1113 rollback_happened);
1114 } else {
1115 powerwash_safe_prefs_->Delete(kPrefsRollbackHappened);
1116 }
1117}
1118
Chris Sosaaa18e162013-06-20 13:20:30 -07001119void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001120 CHECK(powerwash_safe_prefs_);
1121 string rollback_version;
1122 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1123 &rollback_version)) {
1124 SetRollbackVersion(rollback_version);
1125 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001126}
1127
1128void PayloadState::SetRollbackVersion(const string& rollback_version) {
1129 CHECK(powerwash_safe_prefs_);
1130 LOG(INFO) << "Blacklisting version "<< rollback_version;
1131 rollback_version_ = rollback_version;
1132 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001133}
1134
David Zeuthen9a017f22013-04-11 16:10:26 -07001135void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1136 const Time& timestamp,
1137 bool use_logging) {
1138 CHECK(prefs_);
1139 update_duration_uptime_ = value;
1140 update_duration_uptime_timestamp_ = timestamp;
1141 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1142 update_duration_uptime_.ToInternalValue());
1143 if (use_logging) {
1144 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001145 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001146 }
1147}
1148
1149void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001150 Time now = system_state_->clock()->GetMonotonicTime();
1151 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001152}
1153
1154void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001155 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001156 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
Colin Howes0e452c92018-11-02 13:18:44 -07001157
1158 if (uptime_since_last_update > TimeDelta::FromSeconds(kUptimeResolution)) {
1159 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1160 // We're frequently called so avoid logging this write
1161 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1162 }
David Zeuthen9a017f22013-04-11 16:10:26 -07001163}
1164
Jay Srinivasan19409b72013-04-12 19:23:36 -07001165string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1166 return prefix + "-from-" + utils::ToString(source);
1167}
1168
1169void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1170 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001171 SetCurrentBytesDownloaded(source, GetPersistedValue(key, prefs_), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001172}
1173
1174void PayloadState::SetCurrentBytesDownloaded(
1175 DownloadSource source,
1176 uint64_t current_bytes_downloaded,
1177 bool log) {
1178 CHECK(prefs_);
1179
1180 if (source >= kNumDownloadSources)
1181 return;
1182
1183 // Update the in-memory value.
1184 current_bytes_downloaded_[source] = current_bytes_downloaded;
1185
1186 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1187 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1188 LOG_IF(INFO, log) << "Current bytes downloaded for "
1189 << utils::ToString(source) << " = "
1190 << GetCurrentBytesDownloaded(source);
1191}
1192
1193void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1194 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001195 SetTotalBytesDownloaded(source, GetPersistedValue(key, prefs_), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001196}
1197
1198void PayloadState::SetTotalBytesDownloaded(
1199 DownloadSource source,
1200 uint64_t total_bytes_downloaded,
1201 bool log) {
1202 CHECK(prefs_);
1203
1204 if (source >= kNumDownloadSources)
1205 return;
1206
1207 // Update the in-memory value.
1208 total_bytes_downloaded_[source] = total_bytes_downloaded;
1209
1210 // Persist.
1211 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1212 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1213 LOG_IF(INFO, log) << "Total bytes downloaded for "
1214 << utils::ToString(source) << " = "
1215 << GetTotalBytesDownloaded(source);
1216}
1217
David Zeuthena573d6f2013-06-14 16:13:36 -07001218void PayloadState::LoadNumResponsesSeen() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001219 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen, prefs_));
David Zeuthena573d6f2013-06-14 16:13:36 -07001220}
1221
1222void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1223 CHECK(prefs_);
1224 num_responses_seen_ = num_responses_seen;
1225 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1226 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1227}
1228
Jay Srinivasan53173b92013-05-17 17:13:01 -07001229void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001230 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001231
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001232 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001233 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001234 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001235 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1236 } else {
1237 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1238 http_url_ok = true;
1239 }
1240
1241 candidate_urls_.clear();
Sen Jiang0affc2c2017-02-10 15:55:05 -08001242 for (const auto& package : response_.packages) {
1243 candidate_urls_.emplace_back();
1244 for (const string& candidate_url : package.payload_urls) {
1245 if (base::StartsWith(
1246 candidate_url, "http://", base::CompareCase::INSENSITIVE_ASCII) &&
1247 !http_url_ok) {
1248 continue;
1249 }
1250 candidate_urls_.back().push_back(candidate_url);
1251 LOG(INFO) << "Candidate Url" << (candidate_urls_.back().size() - 1)
1252 << ": " << candidate_url;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001253 }
Sen Jiang0affc2c2017-02-10 15:55:05 -08001254 LOG(INFO) << "Found " << candidate_urls_.back().size() << " candidate URLs "
1255 << "out of " << package.payload_urls.size()
1256 << " URLs supplied in package " << candidate_urls_.size() - 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001257 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001258}
1259
David Zeuthene4c58bf2013-06-18 17:26:50 -07001260void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001261 // Flush previous state from abnormal attempt failure, if any.
1262 ReportAndClearPersistedAttemptMetrics();
1263
Alex Deymo569c4242013-07-24 12:01:01 -07001264 // Avoid the UpdateEngineStarted actions if this is not the first time we
1265 // run the update engine since reboot.
1266 if (!system_state_->system_rebooted())
1267 return;
1268
Tianjie Xu90aaa102017-10-10 17:39:03 -07001269 // Report time_to_reboot if we booted into a new update.
1270 metrics_utils::LoadAndReportTimeToReboot(
1271 system_state_->metrics_reporter(), prefs_, system_state_->clock());
1272 prefs_->Delete(kPrefsSystemUpdatedMarker);
1273
Alex Deymo42432912013-07-12 20:21:15 -07001274 // Check if it is needed to send metrics about a failed reboot into a new
1275 // version.
1276 ReportFailedBootIfNeeded();
1277}
1278
1279void PayloadState::ReportFailedBootIfNeeded() {
1280 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1281 // payload was marked as ready immediately before the last reboot, and we
1282 // need to check if such payload successfully rebooted or not.
1283 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001284 int64_t installed_from = 0;
1285 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001286 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1287 return;
1288 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001289 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1290 // partition number. We are now using slot numbers (0 or 1) instead, so
1291 // the following comparison will not match if we are comparing an old
1292 // partition number against a new slot number, which is the correct outcome
1293 // since we successfully booted the new update in that case. If the boot
1294 // failed, we will read this value from the same version, so it will always
1295 // be compatible.
1296 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001297 // A reboot was pending, but the chromebook is again in the same
1298 // BootDevice where the update was installed from.
1299 int64_t target_attempt;
1300 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1301 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1302 "TargetVersionInstalledFrom was present.";
1303 target_attempt = 1;
1304 }
1305
1306 // Report the UMA metric of the current boot failure.
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001307 system_state_->metrics_reporter()->ReportFailedUpdateCount(
1308 target_attempt);
Alex Deymo42432912013-07-12 20:21:15 -07001309 } else {
1310 prefs_->Delete(kPrefsTargetVersionAttempt);
1311 prefs_->Delete(kPrefsTargetVersionUniqueId);
1312 }
1313 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1314 }
1315}
1316
1317void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1318 // Expect to boot into the new partition in the next reboot setting the
1319 // TargetVersion* flags in the Prefs.
1320 string stored_target_version_uid;
1321 string target_version_id;
1322 string target_partition;
1323 int64_t target_attempt;
1324
1325 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1326 prefs_->GetString(kPrefsTargetVersionUniqueId,
1327 &stored_target_version_uid) &&
1328 stored_target_version_uid == target_version_uid) {
1329 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1330 target_attempt = 0;
1331 } else {
1332 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1333 target_attempt = 0;
1334 }
1335 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1336
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001337 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001338 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001339}
1340
1341void PayloadState::ResetUpdateStatus() {
1342 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1343 // rebooted the next boot is not flagged as failed to rebooted into the
1344 // new applied payload.
1345 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1346
1347 // Also decrement the attempt number if it exists.
1348 int64_t target_attempt;
1349 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001350 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001351}
1352
David Zeuthendcba8092013-08-06 12:16:35 -07001353int PayloadState::GetP2PNumAttempts() {
1354 return p2p_num_attempts_;
1355}
1356
1357void PayloadState::SetP2PNumAttempts(int value) {
1358 p2p_num_attempts_ = value;
1359 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1360 CHECK(prefs_);
1361 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1362}
1363
1364void PayloadState::LoadP2PNumAttempts() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001365 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts, prefs_));
David Zeuthendcba8092013-08-06 12:16:35 -07001366}
1367
1368Time PayloadState::GetP2PFirstAttemptTimestamp() {
1369 return p2p_first_attempt_timestamp_;
1370}
1371
1372void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1373 p2p_first_attempt_timestamp_ = time;
1374 LOG(INFO) << "p2p First Attempt Timestamp = "
1375 << utils::ToString(p2p_first_attempt_timestamp_);
1376 CHECK(prefs_);
1377 int64_t stored_value = time.ToInternalValue();
1378 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1379}
1380
1381void PayloadState::LoadP2PFirstAttemptTimestamp() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001382 int64_t stored_value =
1383 GetPersistedValue(kPrefsP2PFirstAttemptTimestamp, prefs_);
David Zeuthendcba8092013-08-06 12:16:35 -07001384 Time stored_time = Time::FromInternalValue(stored_value);
1385 SetP2PFirstAttemptTimestamp(stored_time);
1386}
1387
1388void PayloadState::P2PNewAttempt() {
1389 CHECK(prefs_);
1390 // Set timestamp, if it hasn't been set already
1391 if (p2p_first_attempt_timestamp_.is_null()) {
1392 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1393 }
1394 // Increase number of attempts
1395 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1396}
1397
1398bool PayloadState::P2PAttemptAllowed() {
1399 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1400 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1401 << " which is greater than "
1402 << kMaxP2PAttempts
1403 << " - disallowing p2p.";
1404 return false;
1405 }
1406
1407 if (!p2p_first_attempt_timestamp_.is_null()) {
1408 Time now = system_state_->clock()->GetWallclockTime();
1409 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1410 if (time_spent_attempting_p2p.InSeconds() < 0) {
1411 LOG(ERROR) << "Time spent attempting p2p is negative"
1412 << " - disallowing p2p.";
1413 return false;
1414 }
1415 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1416 LOG(INFO) << "Time spent attempting p2p is "
1417 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1418 << " which is greater than "
1419 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1420 kMaxP2PAttemptTimeSeconds))
1421 << " - disallowing p2p.";
1422 return false;
1423 }
1424 }
1425
1426 return true;
1427}
1428
Sen Jiang0affc2c2017-02-10 15:55:05 -08001429int64_t PayloadState::GetPayloadSize() {
1430 int64_t payload_size = 0;
1431 for (const auto& package : response_.packages)
1432 payload_size += package.size;
1433 return payload_size;
1434}
1435
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001436} // namespace chromeos_update_engine