blob: a1a9d72ec6739928c165cd774362aa7f94bf2355 [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"
Alex Deymo38429cf2015-11-11 18:27:22 -080035#include "update_engine/metrics_utils.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070036#include "update_engine/omaha_request_params.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080037#include "update_engine/payload_consumer/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070038#include "update_engine/system_state.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080039
Jay Srinivasan08262882012-12-28 19:29:43 -080040using base::Time;
41using base::TimeDelta;
42using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080043using std::string;
44
45namespace chromeos_update_engine {
46
David Zeuthen9a017f22013-04-11 16:10:26 -070047const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
48
Jay Srinivasan08262882012-12-28 19:29:43 -080049// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070050static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080051
Jay Srinivasan08262882012-12-28 19:29:43 -080052// We want to randomize retry attempts after the backoff by +/- 6 hours.
53static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080054
Jay Srinivasan19409b72013-04-12 19:23:36 -070055PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070056 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070057 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070058 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070059 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070060 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070061 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070062 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070063 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070064 attempt_num_bytes_downloaded_(0),
65 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Shuqian Zhao29971732016-02-05 11:29:32 -080066 attempt_error_code_(ErrorCode::kSuccess),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070067 attempt_type_(AttemptType::kUpdate) {
68 for (int i = 0; i <= kNumDownloadSources; i++)
69 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070070}
71
72bool PayloadState::Initialize(SystemState* system_state) {
73 system_state_ = system_state;
74 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070075 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080076 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080077 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070078 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080079 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080080 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070081 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080082 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070083 LoadUpdateTimestampStart();
84 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
85 // being called before it. Don't reorder.
86 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070087 for (int i = 0; i < kNumDownloadSources; i++) {
88 DownloadSource source = static_cast<DownloadSource>(i);
89 LoadCurrentBytesDownloaded(source);
90 LoadTotalBytesDownloaded(source);
91 }
Chris Sosabe45bef2013-04-09 18:25:12 -070092 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070093 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070094 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070095 LoadP2PFirstAttemptTimestamp();
96 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080097 return true;
98}
99
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800100void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800101 // Always store the latest response.
102 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800103
Jay Srinivasan53173b92013-05-17 17:13:01 -0700104 // Compute the candidate URLs first as they are used to calculate the
105 // response signature so that a change in enterprise policy for
106 // HTTP downloads being enabled or not could be honored as soon as the
107 // next update check happens.
108 ComputeCandidateUrls();
109
Jay Srinivasan08262882012-12-28 19:29:43 -0800110 // Check if the "signature" of this response (i.e. the fields we care about)
111 // has changed.
112 string new_response_signature = CalculateResponseSignature();
113 bool has_response_changed = (response_signature_ != new_response_signature);
114
115 // If the response has changed, we should persist the new signature and
116 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800117 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800118 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700119 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800120 SetResponseSignature(new_response_signature);
121 ResetPersistedState();
122 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800123 }
124
Sen Jiang97eba342017-05-22 14:34:11 -0700125 // Always start from payload index 0, even for resume, to download partition
126 // info from previous payloads.
127 payload_index_ = 0;
128
Jay Srinivasan08262882012-12-28 19:29:43 -0800129 // This is the earliest point at which we can validate whether the URL index
130 // we loaded from the persisted state is a valid value. If the response
131 // hasn't changed but the URL index is invalid, it's indicative of some
132 // tampering of the persisted state.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800133 if (payload_index_ >= candidate_urls_.size() ||
134 url_index_ >= candidate_urls_[payload_index_].size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800135 LOG(INFO) << "Resetting all payload state as the url index seems to have "
136 "been tampered with";
137 ResetPersistedState();
138 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800139 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700140
141 // Update the current download source which depends on the latest value of
142 // the response.
143 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800144}
145
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700146void PayloadState::SetUsingP2PForDownloading(bool value) {
147 using_p2p_for_downloading_ = value;
148 // Update the current download source which depends on whether we are
149 // using p2p or not.
150 UpdateCurrentDownloadSource();
151}
152
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800153void PayloadState::DownloadComplete() {
154 LOG(INFO) << "Payload downloaded successfully";
155 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700156 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800157}
158
159void PayloadState::DownloadProgress(size_t count) {
160 if (count == 0)
161 return;
162
David Zeuthen9a017f22013-04-11 16:10:26 -0700163 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700164 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700165
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800166 // We've received non-zero bytes from a recent download operation. Since our
167 // URL failure count is meant to penalize a URL only for consecutive
168 // failures, downloading bytes successfully means we should reset the failure
169 // count (as we know at least that the URL is working). In future, we can
170 // design this to be more sophisticated to check for more intelligent failure
171 // patterns, but right now, even 1 byte downloaded will mark the URL to be
172 // good unless it hits 10 (or configured number of) consecutive failures
173 // again.
174
175 if (GetUrlFailureCount() == 0)
176 return;
177
178 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
179 << " to 0 as we received " << count << " bytes successfully";
180 SetUrlFailureCount(0);
181}
182
David Zeuthenafed4a12014-04-09 15:28:44 -0700183void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700184 // Flush previous state from abnormal attempt failure, if any.
185 ReportAndClearPersistedAttemptMetrics();
186
David Zeuthenafed4a12014-04-09 15:28:44 -0700187 attempt_type_ = attempt_type;
188
David Zeuthen33bae492014-02-25 16:16:18 -0800189 ClockInterface *clock = system_state_->clock();
190 attempt_start_time_boot_ = clock->GetBootTime();
191 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800192 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700193
194 metrics::ConnectionType type;
Sen Jiang255e22b2016-05-20 16:15:29 -0700195 ConnectionType network_connection_type;
196 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700197 ConnectionManagerInterface* connection_manager =
198 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700199 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700200 &tethering)) {
201 LOG(ERROR) << "Failed to determine connection type.";
202 type = metrics::ConnectionType::kUnknown;
203 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800204 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700205 }
206 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700207
208 if (attempt_type == AttemptType::kUpdate)
209 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800210}
211
Chris Sosabe45bef2013-04-09 18:25:12 -0700212void PayloadState::UpdateResumed() {
213 LOG(INFO) << "Resuming an update that was previously started.";
214 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700215 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700216}
217
Jay Srinivasan19409b72013-04-12 19:23:36 -0700218void PayloadState::UpdateRestarted() {
219 LOG(INFO) << "Starting a new update";
220 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700221 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700222 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700223}
224
David Zeuthen9a017f22013-04-11 16:10:26 -0700225void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700226 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700227 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700228 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800229
David Zeuthen96197df2014-04-16 12:22:39 -0700230 switch (attempt_type_) {
231 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700232 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700233 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700234 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700235 break;
236
237 case AttemptType::kRollback:
238 metrics::ReportRollbackMetrics(system_state_,
239 metrics::RollbackResult::kSuccess);
240 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700241 }
Shuqian Zhao29971732016-02-05 11:29:32 -0800242 attempt_error_code_ = ErrorCode::kSuccess;
David Zeuthena573d6f2013-06-14 16:13:36 -0700243
244 // Reset the number of responses seen since it counts from the last
245 // successful update, e.g. now.
246 SetNumResponsesSeen(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700247 SetPayloadIndex(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700248
249 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700250}
251
David Zeuthena99981f2013-04-29 13:42:47 -0700252void PayloadState::UpdateFailed(ErrorCode error) {
253 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800254 LOG(INFO) << "Updating payload state for error code: " << base_error
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800255 << " (" << utils::ErrorCodeToString(base_error) << ")";
Shuqian Zhaocd486362016-03-04 19:07:40 -0800256 attempt_error_code_ = base_error;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800257
Jay Srinivasan53173b92013-05-17 17:13:01 -0700258 if (candidate_urls_.size() == 0) {
259 // This means we got this error even before we got a valid Omaha response
260 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800261 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800262 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
263 return;
264 }
265
David Zeuthen96197df2014-04-16 12:22:39 -0700266 switch (attempt_type_) {
267 case AttemptType::kUpdate:
268 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700269 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700270 break;
271
272 case AttemptType::kRollback:
273 metrics::ReportRollbackMetrics(system_state_,
274 metrics::RollbackResult::kFailed);
275 break;
276 }
David Zeuthen33bae492014-02-25 16:16:18 -0800277
Shuqian Zhao29971732016-02-05 11:29:32 -0800278
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800279 switch (base_error) {
280 // Errors which are good indicators of a problem with a particular URL or
281 // the protocol used in the URL or entities in the communication channel
282 // (e.g. proxies). We should try the next available URL in the next update
283 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700284 case ErrorCode::kPayloadHashMismatchError:
285 case ErrorCode::kPayloadSizeMismatchError:
286 case ErrorCode::kDownloadPayloadVerificationError:
287 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
288 case ErrorCode::kSignedDeltaPayloadExpectedError:
289 case ErrorCode::kDownloadInvalidMetadataMagicString:
290 case ErrorCode::kDownloadSignatureMissingInManifest:
291 case ErrorCode::kDownloadManifestParseError:
292 case ErrorCode::kDownloadMetadataSignatureError:
293 case ErrorCode::kDownloadMetadataSignatureVerificationError:
294 case ErrorCode::kDownloadMetadataSignatureMismatch:
295 case ErrorCode::kDownloadOperationHashVerificationError:
296 case ErrorCode::kDownloadOperationExecutionError:
297 case ErrorCode::kDownloadOperationHashMismatch:
298 case ErrorCode::kDownloadInvalidMetadataSize:
299 case ErrorCode::kDownloadInvalidMetadataSignature:
300 case ErrorCode::kDownloadOperationHashMissingError:
301 case ErrorCode::kDownloadMetadataSignatureMissingError:
302 case ErrorCode::kPayloadMismatchedType:
303 case ErrorCode::kUnsupportedMajorPayloadVersion:
304 case ErrorCode::kUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800305 IncrementUrlIndex();
306 break;
307
308 // Errors which seem to be just transient network/communication related
309 // failures and do not indicate any inherent problem with the URL itself.
310 // So, we should keep the current URL but just increment the
311 // failure count to give it more chances. This way, while we maximize our
312 // chances of downloading from the URLs that appear earlier in the response
313 // (because download from a local server URL that appears earlier in a
314 // response is preferable than downloading from the next URL which could be
315 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700316
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700317 case ErrorCode::kError:
318 case ErrorCode::kDownloadTransferError:
319 case ErrorCode::kDownloadWriteError:
320 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700321 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800322 IncrementFailureCount();
323 break;
324
325 // Errors which are not specific to a URL and hence shouldn't result in
326 // the URL being penalized. This can happen in two cases:
327 // 1. We haven't started downloading anything: These errors don't cost us
328 // anything in terms of actual payload bytes, so we should just do the
329 // regular retries at the next update check.
330 // 2. We have successfully downloaded the payload: In this case, the
331 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800332 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800333 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700334 case ErrorCode::kOmahaRequestError:
335 case ErrorCode::kOmahaResponseHandlerError:
336 case ErrorCode::kPostinstallRunnerError:
337 case ErrorCode::kFilesystemCopierError:
338 case ErrorCode::kInstallDeviceOpenError:
339 case ErrorCode::kKernelDeviceOpenError:
340 case ErrorCode::kDownloadNewPartitionInfoError:
341 case ErrorCode::kNewRootfsVerificationError:
342 case ErrorCode::kNewKernelVerificationError:
343 case ErrorCode::kPostinstallBootedFromFirmwareB:
344 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
345 case ErrorCode::kOmahaRequestEmptyResponseError:
346 case ErrorCode::kOmahaRequestXMLParseError:
347 case ErrorCode::kOmahaResponseInvalid:
348 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
349 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700350 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700351 case ErrorCode::kOmahaUpdateDeferredForBackoff:
352 case ErrorCode::kPostinstallPowerwashError:
353 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400354 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700355 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800356 case ErrorCode::kUserCanceled:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800357 LOG(INFO) << "Not incrementing URL index or failure count for this error";
358 break;
359
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700360 case ErrorCode::kSuccess: // success code
361 case ErrorCode::kUmaReportedMax: // not an error code
362 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
363 case ErrorCode::kDevModeFlag: // not an error code
364 case ErrorCode::kResumedFlag: // not an error code
365 case ErrorCode::kTestImageFlag: // not an error code
366 case ErrorCode::kTestOmahaUrlFlag: // not an error code
367 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800368 // These shouldn't happen. Enumerating these explicitly here so that we
369 // can let the compiler warn about new error codes that are added to
370 // action_processor.h but not added here.
371 LOG(WARNING) << "Unexpected error code for UpdateFailed";
372 break;
373
374 // Note: Not adding a default here so as to let the compiler warn us of
375 // any new enums that were added in the .h but not listed in this switch.
376 }
377}
378
Jay Srinivasan08262882012-12-28 19:29:43 -0800379bool PayloadState::ShouldBackoffDownload() {
380 if (response_.disable_payload_backoff) {
381 LOG(INFO) << "Payload backoff logic is disabled. "
382 "Can proceed with the download";
383 return false;
384 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700385 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700386 LOG(INFO) << "Payload backoff logic is disabled because download "
387 << "will happen from local peer (via p2p).";
388 return false;
389 }
390 if (system_state_->request_params()->interactive()) {
391 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
392 return false;
393 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700394 for (const auto& package : response_.packages) {
395 if (package.is_delta) {
396 // If delta payloads fail, we want to fallback quickly to full payloads as
397 // they are more likely to succeed. Exponential backoffs would greatly
398 // slow down the fallback to full payloads. So we don't backoff for delta
399 // payloads.
400 LOG(INFO) << "No backoffs for delta payloads. "
401 << "Can proceed with the download";
402 return false;
403 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800404 }
405
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700406 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800407 // Backoffs are needed only for official builds. We do not want any delays
408 // or update failures due to backoffs during testing or development.
409 LOG(INFO) << "No backoffs for test/dev images. "
410 << "Can proceed with the download";
411 return false;
412 }
413
414 if (backoff_expiry_time_.is_null()) {
415 LOG(INFO) << "No backoff expiry time has been set. "
416 << "Can proceed with the download";
417 return false;
418 }
419
420 if (backoff_expiry_time_ < Time::Now()) {
421 LOG(INFO) << "The backoff expiry time ("
422 << utils::ToString(backoff_expiry_time_)
423 << ") has elapsed. Can proceed with the download";
424 return false;
425 }
426
427 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
428 << utils::ToString(backoff_expiry_time_);
429 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800430}
431
Chris Sosaaa18e162013-06-20 13:20:30 -0700432void PayloadState::Rollback() {
433 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700434 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700435}
436
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800437void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700438 // Update the payload attempt number for both payload types: full and delta.
439 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
440}
441
442void PayloadState::IncrementFullPayloadAttemptNumber() {
443 // Update the payload attempt number for full payloads and the backoff time.
Sen Jiangcdd52062017-05-18 15:33:10 -0700444 if (response_.packages[payload_index_].is_delta) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800445 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
446 return;
447 }
448
Alex Deymo29b51d92013-07-09 15:26:24 -0700449 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700450 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800451 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800452}
453
454void PayloadState::IncrementUrlIndex() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800455 size_t next_url_index = url_index_ + 1;
456 size_t max_url_size = 0;
457 for (const auto& urls : candidate_urls_)
458 max_url_size = std::max(max_url_size, urls.size());
459 if (next_url_index < max_url_size) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800460 LOG(INFO) << "Incrementing the URL index for next attempt";
461 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800462 } else {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800463 LOG(INFO) << "Resetting the current URL index (" << url_index_ << ") to "
464 << "0 as we only have " << max_url_size << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800465 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700466 IncrementPayloadAttemptNumber();
467 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800468 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800469
David Zeuthencc6f9962013-04-18 11:57:24 -0700470 // If we have multiple URLs, record that we just switched to another one
Sen Jiang0affc2c2017-02-10 15:55:05 -0800471 if (max_url_size > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700472 SetUrlSwitchCount(url_switch_count_ + 1);
473
Jay Srinivasan08262882012-12-28 19:29:43 -0800474 // Whenever we update the URL index, we should also clear the URL failure
475 // count so we can start over fresh for the new URL.
476 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800477}
478
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800479void PayloadState::IncrementFailureCount() {
480 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800481 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800482 LOG(INFO) << "Incrementing the URL failure count";
483 SetUrlFailureCount(next_url_failure_count);
484 } else {
485 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
486 << ". Trying next available URL";
487 IncrementUrlIndex();
488 }
489}
490
Jay Srinivasan08262882012-12-28 19:29:43 -0800491void PayloadState::UpdateBackoffExpiryTime() {
492 if (response_.disable_payload_backoff) {
493 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
494 SetBackoffExpiryTime(Time());
495 return;
496 }
497
Alex Deymo820cc702013-06-28 15:43:46 -0700498 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800499 SetBackoffExpiryTime(Time());
500 return;
501 }
502
503 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700504 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800505 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700506 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700507 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800508
509 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
510 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700511 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800512
513 // The number of days is the minimum of 2 raised to (payload_attempt_number
514 // - 1) or kMaxBackoffDays.
515 num_days = min(num_days << power, kMaxBackoffDays);
516
517 // We don't want all retries to happen exactly at the same time when
518 // retrying after backoff. So add some random minutes to fuzz.
519 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
520 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
521 TimeDelta::FromMinutes(fuzz_minutes);
522 LOG(INFO) << "Incrementing the backoff expiry time by "
523 << utils::FormatTimeDelta(next_backoff_interval);
524 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
525}
526
Jay Srinivasan19409b72013-04-12 19:23:36 -0700527void PayloadState::UpdateCurrentDownloadSource() {
528 current_download_source_ = kNumDownloadSources;
529
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700530 if (using_p2p_for_downloading_) {
531 current_download_source_ = kDownloadSourceHttpPeer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800532 } else if (payload_index_ < candidate_urls_.size() &&
533 candidate_urls_[payload_index_].size() != 0) {
534 const string& current_url = candidate_urls_[payload_index_][GetUrlIndex()];
535 if (base::StartsWith(
536 current_url, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700537 current_download_source_ = kDownloadSourceHttpsServer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800538 } else if (base::StartsWith(current_url,
539 "http://",
Alex Vakulenko0103c362016-01-20 07:56:15 -0800540 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700541 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800542 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700543 }
544
545 LOG(INFO) << "Current download source: "
546 << utils::ToString(current_download_source_);
547}
548
549void PayloadState::UpdateBytesDownloaded(size_t count) {
550 SetCurrentBytesDownloaded(
551 current_download_source_,
552 GetCurrentBytesDownloaded(current_download_source_) + count,
553 false);
554 SetTotalBytesDownloaded(
555 current_download_source_,
556 GetTotalBytesDownloaded(current_download_source_) + count,
557 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800558
559 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700560}
561
David Zeuthen33bae492014-02-25 16:16:18 -0800562PayloadType PayloadState::CalculatePayloadType() {
Sen Jiangcdd52062017-05-18 15:33:10 -0700563 for (const auto& package : response_.packages) {
564 if (package.is_delta) {
565 return kPayloadTypeDelta;
566 }
David Zeuthen33bae492014-02-25 16:16:18 -0800567 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700568 OmahaRequestParams* params = system_state_->request_params();
569 if (params->delta_okay()) {
570 return kPayloadTypeFull;
571 }
572 // Full payload, delta was not allowed by request.
573 return kPayloadTypeForcedFull;
David Zeuthen33bae492014-02-25 16:16:18 -0800574}
575
576// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
577// metrics if the attempt ends abnormally, e.g. if the update_engine
578// process crashes or the device is rebooted. See
579// http://crbug.com/357676
580void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
581 int attempt_number = GetPayloadAttemptNumber();
582
583 PayloadType payload_type = CalculatePayloadType();
584
Sen Jiang0affc2c2017-02-10 15:55:05 -0800585 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800586
587 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
588
589 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700590 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
591 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800592 attempt_start_time_monotonic_;
593
594 int64_t payload_download_speed_bps = 0;
595 int64_t usec = duration_uptime.InMicroseconds();
596 if (usec > 0) {
597 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
598 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
599 payload_download_speed_bps = static_cast<int64_t>(bps);
600 }
601
602 DownloadSource download_source = current_download_source_;
603
604 metrics::DownloadErrorCode payload_download_error_code =
605 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700606 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800607 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800608
609 // Add additional detail to AttemptResult
610 switch (attempt_result) {
611 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800612 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800613 break;
614
615 case metrics::AttemptResult::kInternalError:
616 internal_error_code = code;
617 break;
618
619 // Explicit fall-through for cases where we do not have additional
620 // detail. We avoid the default keyword to force people adding new
621 // AttemptResult values to visit this code and examine whether
622 // additional detail is needed.
623 case metrics::AttemptResult::kUpdateSucceeded:
624 case metrics::AttemptResult::kMetadataMalformed:
625 case metrics::AttemptResult::kOperationMalformed:
626 case metrics::AttemptResult::kOperationExecutionError:
627 case metrics::AttemptResult::kMetadataVerificationFailed:
628 case metrics::AttemptResult::kPayloadVerificationFailed:
629 case metrics::AttemptResult::kVerificationFailed:
630 case metrics::AttemptResult::kPostInstallFailed:
631 case metrics::AttemptResult::kAbnormalTermination:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800632 case metrics::AttemptResult::kUpdateCanceled:
David Zeuthen33bae492014-02-25 16:16:18 -0800633 case metrics::AttemptResult::kNumConstants:
634 case metrics::AttemptResult::kUnset:
635 break;
636 }
637
638 metrics::ReportUpdateAttemptMetrics(system_state_,
639 attempt_number,
640 payload_type,
641 duration,
642 duration_uptime,
643 payload_size,
644 payload_bytes_downloaded,
645 payload_download_speed_bps,
646 download_source,
647 attempt_result,
648 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700649 payload_download_error_code,
650 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800651}
652
David Zeuthen4e1d1492014-04-25 13:12:27 -0700653void PayloadState::PersistAttemptMetrics() {
654 // TODO(zeuthen): For now we only persist whether an attempt was in
655 // progress and not values/metrics related to the attempt. This
656 // means that when this happens, of all the UpdateEngine.Attempt.*
657 // metrics, only UpdateEngine.Attempt.Result is reported (with the
658 // value |kAbnormalTermination|). In the future we might want to
659 // persist more data so we can report other metrics in the
660 // UpdateEngine.Attempt.* namespace when this happens.
661 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
662}
663
664void PayloadState::ClearPersistedAttemptMetrics() {
665 prefs_->Delete(kPrefsAttemptInProgress);
666}
667
668void PayloadState::ReportAndClearPersistedAttemptMetrics() {
669 bool attempt_in_progress = false;
670 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
671 return;
672 if (!attempt_in_progress)
673 return;
674
675 metrics::ReportAbnormallyTerminatedUpdateAttemptMetrics(system_state_);
676
677 ClearPersistedAttemptMetrics();
678}
679
David Zeuthen33bae492014-02-25 16:16:18 -0800680void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700681 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800682
683 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800684 int64_t total_bytes_by_source[kNumDownloadSources];
685 int64_t successful_bytes = 0;
686 int64_t total_bytes = 0;
687 int64_t successful_mbs = 0;
688 int64_t total_mbs = 0;
689
Jay Srinivasan19409b72013-04-12 19:23:36 -0700690 for (int i = 0; i < kNumDownloadSources; i++) {
691 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800692 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700693
David Zeuthen44848602013-06-24 13:32:14 -0700694 // Only consider this download source (and send byte counts) as
695 // having been used if we downloaded a non-trivial amount of bytes
696 // (e.g. at least 1 MiB) that contributed to the final success of
697 // the update. Otherwise we're going to end up with a lot of
698 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700699
David Zeuthen33bae492014-02-25 16:16:18 -0800700 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800701 successful_bytes += bytes;
702 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700703 SetCurrentBytesDownloaded(source, 0, true);
704
David Zeuthen33bae492014-02-25 16:16:18 -0800705 bytes = GetTotalBytesDownloaded(source);
706 total_bytes_by_source[i] = bytes;
707 total_bytes += bytes;
708 total_mbs += bytes / kNumBytesInOneMiB;
709 SetTotalBytesDownloaded(source, 0, true);
710 }
711
712 int download_overhead_percentage = 0;
713 if (successful_bytes > 0) {
714 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
715 successful_bytes;
716 }
717
718 int url_switch_count = static_cast<int>(url_switch_count_);
719
720 int reboot_count = GetNumReboots();
721
722 SetNumReboots(0);
723
724 TimeDelta duration = GetUpdateDuration();
David Zeuthen33bae492014-02-25 16:16:18 -0800725
726 prefs_->Delete(kPrefsUpdateTimestampStart);
727 prefs_->Delete(kPrefsUpdateDurationUptime);
728
729 PayloadType payload_type = CalculatePayloadType();
730
Sen Jiang0affc2c2017-02-10 15:55:05 -0800731 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800732
733 int attempt_count = GetPayloadAttemptNumber();
734
735 int updates_abandoned_count = num_responses_seen_ - 1;
736
737 metrics::ReportSuccessfulUpdateMetrics(system_state_,
738 attempt_count,
739 updates_abandoned_count,
740 payload_type,
741 payload_size,
742 total_bytes_by_source,
743 download_overhead_percentage,
744 duration,
745 reboot_count,
746 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700747}
748
749void PayloadState::UpdateNumReboots() {
750 // We only update the reboot count when the system has been detected to have
751 // been rebooted.
752 if (!system_state_->system_rebooted()) {
753 return;
754 }
755
756 SetNumReboots(GetNumReboots() + 1);
757}
758
759void PayloadState::SetNumReboots(uint32_t num_reboots) {
760 CHECK(prefs_);
761 num_reboots_ = num_reboots;
762 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
763 LOG(INFO) << "Number of Reboots during current update attempt = "
764 << num_reboots_;
765}
766
Jay Srinivasan08262882012-12-28 19:29:43 -0800767void PayloadState::ResetPersistedState() {
768 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700769 SetFullPayloadAttemptNumber(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700770 SetPayloadIndex(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800771 SetUrlIndex(0);
772 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700773 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700774 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700775 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700776 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700777 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700778 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700779 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700780 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700781 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700782 SetScatteringWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700783}
784
785void PayloadState::ResetRollbackVersion() {
786 CHECK(powerwash_safe_prefs_);
787 rollback_version_ = "";
788 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700789}
790
791void PayloadState::ResetDownloadSourcesOnNewUpdate() {
792 for (int i = 0; i < kNumDownloadSources; i++) {
793 DownloadSource source = static_cast<DownloadSource>(i);
794 SetCurrentBytesDownloaded(source, 0, true);
795 // Note: Not resetting the TotalBytesDownloaded as we want that metric
796 // to count the bytes downloaded across various update attempts until
797 // we have successfully applied the update.
798 }
799}
800
Chris Sosab3dcdb32013-09-04 15:22:12 -0700801int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700802 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700803 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700804 return 0;
805
806 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700807 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700808 return 0;
809
810 if (stored_value < 0) {
811 LOG(ERROR) << key << ": Invalid value (" << stored_value
812 << ") in persisted state. Defaulting to 0";
813 return 0;
814 }
815
816 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800817}
818
819string PayloadState::CalculateResponseSignature() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800820 string response_sign;
821 for (size_t i = 0; i < response_.packages.size(); i++) {
822 const auto& package = response_.packages[i];
823 response_sign += base::StringPrintf(
824 "Payload %zu:\n"
825 " Size = %ju\n"
826 " Sha256 Hash = %s\n"
827 " Metadata Size = %ju\n"
828 " Metadata Signature = %s\n"
Sen Jiangcdd52062017-05-18 15:33:10 -0700829 " Is Delta = %d\n"
Sen Jiang0affc2c2017-02-10 15:55:05 -0800830 " NumURLs = %zu\n",
831 i,
832 static_cast<uintmax_t>(package.size),
833 package.hash.c_str(),
834 static_cast<uintmax_t>(package.metadata_size),
835 package.metadata_signature.c_str(),
Sen Jiangcdd52062017-05-18 15:33:10 -0700836 package.is_delta,
Sen Jiang0affc2c2017-02-10 15:55:05 -0800837 candidate_urls_[i].size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800838
Sen Jiang0affc2c2017-02-10 15:55:05 -0800839 for (size_t j = 0; j < candidate_urls_[i].size(); j++)
840 response_sign += base::StringPrintf(
841 " Candidate Url%zu = %s\n", j, candidate_urls_[i][j].c_str());
842 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800843
Alex Vakulenko75039d72014-03-25 12:36:28 -0700844 response_sign += base::StringPrintf(
Alex Vakulenko75039d72014-03-25 12:36:28 -0700845 "Max Failure Count Per Url = %d\n"
846 "Disable Payload Backoff = %d\n",
Alex Vakulenko75039d72014-03-25 12:36:28 -0700847 response_.max_failure_count_per_url,
848 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800849 return response_sign;
850}
851
852void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800853 CHECK(prefs_);
854 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800855 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
856 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
857 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800858 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800859}
860
Jay Srinivasan19409b72013-04-12 19:23:36 -0700861void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800862 CHECK(prefs_);
863 response_signature_ = response_signature;
864 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
865 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
866}
867
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800868void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700869 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800870}
871
Alex Deymo820cc702013-06-28 15:43:46 -0700872void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700873 SetFullPayloadAttemptNumber(GetPersistedValue(
874 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700875}
876
877void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800878 CHECK(prefs_);
879 payload_attempt_number_ = payload_attempt_number;
880 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
881 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
882}
883
Alex Deymo820cc702013-06-28 15:43:46 -0700884void PayloadState::SetFullPayloadAttemptNumber(
885 int full_payload_attempt_number) {
886 CHECK(prefs_);
887 full_payload_attempt_number_ = full_payload_attempt_number;
888 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
889 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
890 full_payload_attempt_number_);
891}
892
Sen Jiang5ae865b2017-04-18 14:24:40 -0700893void PayloadState::SetPayloadIndex(size_t payload_index) {
894 CHECK(prefs_);
895 payload_index_ = payload_index;
896 LOG(INFO) << "Payload Index = " << payload_index_;
897 prefs_->SetInt64(kPrefsUpdateStatePayloadIndex, payload_index_);
898}
899
900bool PayloadState::NextPayload() {
901 if (payload_index_ + 1 >= candidate_urls_.size())
902 return false;
903 SetPayloadIndex(payload_index_ + 1);
904 return true;
905}
906
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800907void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700908 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800909}
910
911void PayloadState::SetUrlIndex(uint32_t url_index) {
912 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800913 url_index_ = url_index;
914 LOG(INFO) << "Current URL Index = " << url_index_;
915 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700916
917 // Also update the download source, which is purely dependent on the
918 // current URL index alone.
919 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800920}
921
Gilad Arnold519cfc72014-10-02 10:34:54 -0700922void PayloadState::LoadScatteringWaitPeriod() {
923 SetScatteringWaitPeriod(
924 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
925}
926
Alex Deymof329b932014-10-30 01:37:48 -0700927void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700928 CHECK(prefs_);
929 scattering_wait_period_ = wait_period;
930 LOG(INFO) << "Scattering Wait Period (seconds) = "
931 << scattering_wait_period_.InSeconds();
932 if (scattering_wait_period_.InSeconds() > 0) {
933 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
934 scattering_wait_period_.InSeconds());
935 } else {
936 prefs_->Delete(kPrefsWallClockWaitPeriod);
937 }
938}
939
David Zeuthencc6f9962013-04-18 11:57:24 -0700940void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700941 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700942}
943
944void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
945 CHECK(prefs_);
946 url_switch_count_ = url_switch_count;
947 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
948 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
949}
950
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800951void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700952 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800953}
954
955void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
956 CHECK(prefs_);
957 url_failure_count_ = url_failure_count;
958 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
959 << ")'s Failure Count = " << url_failure_count_;
960 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800961}
962
Jay Srinivasan08262882012-12-28 19:29:43 -0800963void PayloadState::LoadBackoffExpiryTime() {
964 CHECK(prefs_);
965 int64_t stored_value;
966 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
967 return;
968
969 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
970 return;
971
972 Time stored_time = Time::FromInternalValue(stored_value);
973 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
974 LOG(ERROR) << "Invalid backoff expiry time ("
975 << utils::ToString(stored_time)
976 << ") in persisted state. Resetting.";
977 stored_time = Time();
978 }
979 SetBackoffExpiryTime(stored_time);
980}
981
982void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
983 CHECK(prefs_);
984 backoff_expiry_time_ = new_time;
985 LOG(INFO) << "Backoff Expiry Time = "
986 << utils::ToString(backoff_expiry_time_);
987 prefs_->SetInt64(kPrefsBackoffExpiryTime,
988 backoff_expiry_time_.ToInternalValue());
989}
990
David Zeuthen9a017f22013-04-11 16:10:26 -0700991TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700992 Time end_time = update_timestamp_end_.is_null()
993 ? system_state_->clock()->GetWallclockTime() :
994 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700995 return end_time - update_timestamp_start_;
996}
997
998void PayloadState::LoadUpdateTimestampStart() {
999 int64_t stored_value;
1000 Time stored_time;
1001
1002 CHECK(prefs_);
1003
David Zeuthenf413fe52013-04-22 14:04:39 -07001004 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001005
1006 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1007 // The preference missing is not unexpected - in that case, just
1008 // use the current time as start time
1009 stored_time = now;
1010 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1011 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1012 stored_time = now;
1013 } else {
1014 stored_time = Time::FromInternalValue(stored_value);
1015 }
1016
1017 // Sanity check: If the time read from disk is in the future
1018 // (modulo some slack to account for possible NTP drift
1019 // adjustments), something is fishy and we should report and
1020 // reset.
1021 TimeDelta duration_according_to_stored_time = now - stored_time;
1022 if (duration_according_to_stored_time < -kDurationSlack) {
1023 LOG(ERROR) << "The UpdateTimestampStart value ("
1024 << utils::ToString(stored_time)
1025 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001026 << utils::FormatTimeDelta(duration_according_to_stored_time)
1027 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001028 stored_time = now;
1029 }
1030
1031 SetUpdateTimestampStart(stored_time);
1032}
1033
1034void PayloadState::SetUpdateTimestampStart(const Time& value) {
1035 CHECK(prefs_);
1036 update_timestamp_start_ = value;
1037 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1038 update_timestamp_start_.ToInternalValue());
1039 LOG(INFO) << "Update Timestamp Start = "
1040 << utils::ToString(update_timestamp_start_);
1041}
1042
1043void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1044 update_timestamp_end_ = value;
1045 LOG(INFO) << "Update Timestamp End = "
1046 << utils::ToString(update_timestamp_end_);
1047}
1048
1049TimeDelta PayloadState::GetUpdateDurationUptime() {
1050 return update_duration_uptime_;
1051}
1052
1053void PayloadState::LoadUpdateDurationUptime() {
1054 int64_t stored_value;
1055 TimeDelta stored_delta;
1056
1057 CHECK(prefs_);
1058
1059 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1060 // The preference missing is not unexpected - in that case, just
1061 // we'll use zero as the delta
1062 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1063 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1064 stored_delta = TimeDelta::FromSeconds(0);
1065 } else {
1066 stored_delta = TimeDelta::FromInternalValue(stored_value);
1067 }
1068
1069 // Sanity-check: Uptime can never be greater than the wall-clock
1070 // difference (modulo some slack). If it is, report and reset
1071 // to the wall-clock difference.
1072 TimeDelta diff = GetUpdateDuration() - stored_delta;
1073 if (diff < -kDurationSlack) {
1074 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001075 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001076 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001077 << utils::FormatTimeDelta(diff)
1078 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001079 stored_delta = update_duration_current_;
1080 }
1081
1082 SetUpdateDurationUptime(stored_delta);
1083}
1084
Chris Sosabe45bef2013-04-09 18:25:12 -07001085void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001086 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001087}
1088
1089void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001090 CHECK(powerwash_safe_prefs_);
1091 string rollback_version;
1092 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1093 &rollback_version)) {
1094 SetRollbackVersion(rollback_version);
1095 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001096}
1097
1098void PayloadState::SetRollbackVersion(const string& rollback_version) {
1099 CHECK(powerwash_safe_prefs_);
1100 LOG(INFO) << "Blacklisting version "<< rollback_version;
1101 rollback_version_ = rollback_version;
1102 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001103}
1104
David Zeuthen9a017f22013-04-11 16:10:26 -07001105void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1106 const Time& timestamp,
1107 bool use_logging) {
1108 CHECK(prefs_);
1109 update_duration_uptime_ = value;
1110 update_duration_uptime_timestamp_ = timestamp;
1111 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1112 update_duration_uptime_.ToInternalValue());
1113 if (use_logging) {
1114 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001115 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001116 }
1117}
1118
1119void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001120 Time now = system_state_->clock()->GetMonotonicTime();
1121 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001122}
1123
1124void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001125 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001126 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1127 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1128 // We're frequently called so avoid logging this write
1129 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1130}
1131
Jay Srinivasan19409b72013-04-12 19:23:36 -07001132string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1133 return prefix + "-from-" + utils::ToString(source);
1134}
1135
1136void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1137 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001138 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001139}
1140
1141void PayloadState::SetCurrentBytesDownloaded(
1142 DownloadSource source,
1143 uint64_t current_bytes_downloaded,
1144 bool log) {
1145 CHECK(prefs_);
1146
1147 if (source >= kNumDownloadSources)
1148 return;
1149
1150 // Update the in-memory value.
1151 current_bytes_downloaded_[source] = current_bytes_downloaded;
1152
1153 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1154 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1155 LOG_IF(INFO, log) << "Current bytes downloaded for "
1156 << utils::ToString(source) << " = "
1157 << GetCurrentBytesDownloaded(source);
1158}
1159
1160void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1161 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001162 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001163}
1164
1165void PayloadState::SetTotalBytesDownloaded(
1166 DownloadSource source,
1167 uint64_t total_bytes_downloaded,
1168 bool log) {
1169 CHECK(prefs_);
1170
1171 if (source >= kNumDownloadSources)
1172 return;
1173
1174 // Update the in-memory value.
1175 total_bytes_downloaded_[source] = total_bytes_downloaded;
1176
1177 // Persist.
1178 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1179 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1180 LOG_IF(INFO, log) << "Total bytes downloaded for "
1181 << utils::ToString(source) << " = "
1182 << GetTotalBytesDownloaded(source);
1183}
1184
David Zeuthena573d6f2013-06-14 16:13:36 -07001185void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001186 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001187}
1188
1189void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1190 CHECK(prefs_);
1191 num_responses_seen_ = num_responses_seen;
1192 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1193 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1194}
1195
Jay Srinivasan53173b92013-05-17 17:13:01 -07001196void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001197 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001198
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001199 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001200 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001201 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001202 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1203 } else {
1204 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1205 http_url_ok = true;
1206 }
1207
1208 candidate_urls_.clear();
Sen Jiang0affc2c2017-02-10 15:55:05 -08001209 for (const auto& package : response_.packages) {
1210 candidate_urls_.emplace_back();
1211 for (const string& candidate_url : package.payload_urls) {
1212 if (base::StartsWith(
1213 candidate_url, "http://", base::CompareCase::INSENSITIVE_ASCII) &&
1214 !http_url_ok) {
1215 continue;
1216 }
1217 candidate_urls_.back().push_back(candidate_url);
1218 LOG(INFO) << "Candidate Url" << (candidate_urls_.back().size() - 1)
1219 << ": " << candidate_url;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001220 }
Sen Jiang0affc2c2017-02-10 15:55:05 -08001221 LOG(INFO) << "Found " << candidate_urls_.back().size() << " candidate URLs "
1222 << "out of " << package.payload_urls.size()
1223 << " URLs supplied in package " << candidate_urls_.size() - 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001224 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001225}
1226
David Zeuthene4c58bf2013-06-18 17:26:50 -07001227void PayloadState::CreateSystemUpdatedMarkerFile() {
1228 CHECK(prefs_);
1229 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1230 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1231}
1232
1233void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1234 // Send |time_to_reboot| as a UMA stat.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001235 string metric = metrics::kMetricTimeToRebootMinutes;
David Zeuthen33bae492014-02-25 16:16:18 -08001236 system_state_->metrics_lib()->SendToUMA(metric,
1237 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001238 0, // min: 0 minute
1239 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001240 kNumDefaultUmaBuckets);
1241 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1242 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001243}
1244
1245void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001246 // Flush previous state from abnormal attempt failure, if any.
1247 ReportAndClearPersistedAttemptMetrics();
1248
Alex Deymo569c4242013-07-24 12:01:01 -07001249 // Avoid the UpdateEngineStarted actions if this is not the first time we
1250 // run the update engine since reboot.
1251 if (!system_state_->system_rebooted())
1252 return;
1253
David Zeuthene4c58bf2013-06-18 17:26:50 -07001254 // Figure out if we just booted into a new update
1255 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1256 int64_t stored_value;
1257 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1258 Time system_updated_at = Time::FromInternalValue(stored_value);
1259 if (!system_updated_at.is_null()) {
1260 TimeDelta time_to_reboot =
1261 system_state_->clock()->GetWallclockTime() - system_updated_at;
1262 if (time_to_reboot.ToInternalValue() < 0) {
1263 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1264 << utils::ToString(system_updated_at);
1265 } else {
1266 BootedIntoUpdate(time_to_reboot);
1267 }
1268 }
1269 }
1270 prefs_->Delete(kPrefsSystemUpdatedMarker);
1271 }
Alex Deymo42432912013-07-12 20:21:15 -07001272 // Check if it is needed to send metrics about a failed reboot into a new
1273 // version.
1274 ReportFailedBootIfNeeded();
1275}
1276
1277void PayloadState::ReportFailedBootIfNeeded() {
1278 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1279 // payload was marked as ready immediately before the last reboot, and we
1280 // need to check if such payload successfully rebooted or not.
1281 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001282 int64_t installed_from = 0;
1283 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001284 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1285 return;
1286 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001287 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1288 // partition number. We are now using slot numbers (0 or 1) instead, so
1289 // the following comparison will not match if we are comparing an old
1290 // partition number against a new slot number, which is the correct outcome
1291 // since we successfully booted the new update in that case. If the boot
1292 // failed, we will read this value from the same version, so it will always
1293 // be compatible.
1294 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001295 // A reboot was pending, but the chromebook is again in the same
1296 // BootDevice where the update was installed from.
1297 int64_t target_attempt;
1298 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1299 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1300 "TargetVersionInstalledFrom was present.";
1301 target_attempt = 1;
1302 }
1303
1304 // Report the UMA metric of the current boot failure.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001305 string metric = metrics::kMetricFailedUpdateCount;
David Zeuthen33bae492014-02-25 16:16:18 -08001306 LOG(INFO) << "Uploading " << target_attempt
1307 << " (count) for metric " << metric;
1308 system_state_->metrics_lib()->SendToUMA(
1309 metric,
1310 target_attempt,
1311 1, // min value
1312 50, // max value
1313 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001314 } else {
1315 prefs_->Delete(kPrefsTargetVersionAttempt);
1316 prefs_->Delete(kPrefsTargetVersionUniqueId);
1317 }
1318 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1319 }
1320}
1321
1322void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1323 // Expect to boot into the new partition in the next reboot setting the
1324 // TargetVersion* flags in the Prefs.
1325 string stored_target_version_uid;
1326 string target_version_id;
1327 string target_partition;
1328 int64_t target_attempt;
1329
1330 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1331 prefs_->GetString(kPrefsTargetVersionUniqueId,
1332 &stored_target_version_uid) &&
1333 stored_target_version_uid == target_version_uid) {
1334 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1335 target_attempt = 0;
1336 } else {
1337 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1338 target_attempt = 0;
1339 }
1340 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1341
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001342 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001343 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001344}
1345
1346void PayloadState::ResetUpdateStatus() {
1347 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1348 // rebooted the next boot is not flagged as failed to rebooted into the
1349 // new applied payload.
1350 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1351
1352 // Also decrement the attempt number if it exists.
1353 int64_t target_attempt;
1354 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001355 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001356}
1357
David Zeuthendcba8092013-08-06 12:16:35 -07001358int PayloadState::GetP2PNumAttempts() {
1359 return p2p_num_attempts_;
1360}
1361
1362void PayloadState::SetP2PNumAttempts(int value) {
1363 p2p_num_attempts_ = value;
1364 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1365 CHECK(prefs_);
1366 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1367}
1368
1369void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001370 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001371}
1372
1373Time PayloadState::GetP2PFirstAttemptTimestamp() {
1374 return p2p_first_attempt_timestamp_;
1375}
1376
1377void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1378 p2p_first_attempt_timestamp_ = time;
1379 LOG(INFO) << "p2p First Attempt Timestamp = "
1380 << utils::ToString(p2p_first_attempt_timestamp_);
1381 CHECK(prefs_);
1382 int64_t stored_value = time.ToInternalValue();
1383 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1384}
1385
1386void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001387 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001388 Time stored_time = Time::FromInternalValue(stored_value);
1389 SetP2PFirstAttemptTimestamp(stored_time);
1390}
1391
1392void PayloadState::P2PNewAttempt() {
1393 CHECK(prefs_);
1394 // Set timestamp, if it hasn't been set already
1395 if (p2p_first_attempt_timestamp_.is_null()) {
1396 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1397 }
1398 // Increase number of attempts
1399 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1400}
1401
1402bool PayloadState::P2PAttemptAllowed() {
1403 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1404 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1405 << " which is greater than "
1406 << kMaxP2PAttempts
1407 << " - disallowing p2p.";
1408 return false;
1409 }
1410
1411 if (!p2p_first_attempt_timestamp_.is_null()) {
1412 Time now = system_state_->clock()->GetWallclockTime();
1413 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1414 if (time_spent_attempting_p2p.InSeconds() < 0) {
1415 LOG(ERROR) << "Time spent attempting p2p is negative"
1416 << " - disallowing p2p.";
1417 return false;
1418 }
1419 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1420 LOG(INFO) << "Time spent attempting p2p is "
1421 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1422 << " which is greater than "
1423 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1424 kMaxP2PAttemptTimeSeconds))
1425 << " - disallowing p2p.";
1426 return false;
1427 }
1428 }
1429
1430 return true;
1431}
1432
Sen Jiang0affc2c2017-02-10 15:55:05 -08001433int64_t PayloadState::GetPayloadSize() {
1434 int64_t payload_size = 0;
1435 for (const auto& package : response_.packages)
1436 payload_size += package.size;
1437 return payload_size;
1438}
1439
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001440} // namespace chromeos_update_engine