blob: 8594f28ed5d331050c13b759d532e075b25c968a [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"
30#include "update_engine/common/hardware_interface.h"
31#include "update_engine/common/prefs.h"
32#include "update_engine/common/utils.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080033#include "update_engine/metrics_utils.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070034#include "update_engine/omaha_request_params.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080035#include "update_engine/payload_consumer/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070036#include "update_engine/system_state.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080037
Jay Srinivasan08262882012-12-28 19:29:43 -080038using base::Time;
39using base::TimeDelta;
40using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080041using std::string;
42
43namespace chromeos_update_engine {
44
David Zeuthen9a017f22013-04-11 16:10:26 -070045const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
46
Jay Srinivasan08262882012-12-28 19:29:43 -080047// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070048static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080049
Jay Srinivasan08262882012-12-28 19:29:43 -080050// We want to randomize retry attempts after the backoff by +/- 6 hours.
51static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080052
Jay Srinivasan19409b72013-04-12 19:23:36 -070053PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070054 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070055 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070056 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070057 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070058 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070059 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070060 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070061 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070062 attempt_num_bytes_downloaded_(0),
63 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070064 attempt_type_(AttemptType::kUpdate) {
65 for (int i = 0; i <= kNumDownloadSources; i++)
66 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070067}
68
69bool PayloadState::Initialize(SystemState* system_state) {
70 system_state_ = system_state;
71 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070072 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080073 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080074 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070075 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080076 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080077 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070078 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080079 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070080 LoadUpdateTimestampStart();
81 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
82 // being called before it. Don't reorder.
83 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070084 for (int i = 0; i < kNumDownloadSources; i++) {
85 DownloadSource source = static_cast<DownloadSource>(i);
86 LoadCurrentBytesDownloaded(source);
87 LoadTotalBytesDownloaded(source);
88 }
Chris Sosabe45bef2013-04-09 18:25:12 -070089 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070090 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070091 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070092 LoadP2PFirstAttemptTimestamp();
93 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080094 return true;
95}
96
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080097void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080098 // Always store the latest response.
99 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800100
Jay Srinivasan53173b92013-05-17 17:13:01 -0700101 // Compute the candidate URLs first as they are used to calculate the
102 // response signature so that a change in enterprise policy for
103 // HTTP downloads being enabled or not could be honored as soon as the
104 // next update check happens.
105 ComputeCandidateUrls();
106
Jay Srinivasan08262882012-12-28 19:29:43 -0800107 // Check if the "signature" of this response (i.e. the fields we care about)
108 // has changed.
109 string new_response_signature = CalculateResponseSignature();
110 bool has_response_changed = (response_signature_ != new_response_signature);
111
112 // If the response has changed, we should persist the new signature and
113 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800114 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800115 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700116 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800117 SetResponseSignature(new_response_signature);
118 ResetPersistedState();
119 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800120 }
121
Jay Srinivasan08262882012-12-28 19:29:43 -0800122 // This is the earliest point at which we can validate whether the URL index
123 // we loaded from the persisted state is a valid value. If the response
124 // hasn't changed but the URL index is invalid, it's indicative of some
125 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700126 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800127 LOG(INFO) << "Resetting all payload state as the url index seems to have "
128 "been tampered with";
129 ResetPersistedState();
130 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800131 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700132
133 // Update the current download source which depends on the latest value of
134 // the response.
135 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800136}
137
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700138void PayloadState::SetUsingP2PForDownloading(bool value) {
139 using_p2p_for_downloading_ = value;
140 // Update the current download source which depends on whether we are
141 // using p2p or not.
142 UpdateCurrentDownloadSource();
143}
144
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800145void PayloadState::DownloadComplete() {
146 LOG(INFO) << "Payload downloaded successfully";
147 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700148 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800149}
150
151void PayloadState::DownloadProgress(size_t count) {
152 if (count == 0)
153 return;
154
David Zeuthen9a017f22013-04-11 16:10:26 -0700155 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700156 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700157
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800158 // We've received non-zero bytes from a recent download operation. Since our
159 // URL failure count is meant to penalize a URL only for consecutive
160 // failures, downloading bytes successfully means we should reset the failure
161 // count (as we know at least that the URL is working). In future, we can
162 // design this to be more sophisticated to check for more intelligent failure
163 // patterns, but right now, even 1 byte downloaded will mark the URL to be
164 // good unless it hits 10 (or configured number of) consecutive failures
165 // again.
166
167 if (GetUrlFailureCount() == 0)
168 return;
169
170 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
171 << " to 0 as we received " << count << " bytes successfully";
172 SetUrlFailureCount(0);
173}
174
David Zeuthenafed4a12014-04-09 15:28:44 -0700175void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700176 // Flush previous state from abnormal attempt failure, if any.
177 ReportAndClearPersistedAttemptMetrics();
178
David Zeuthenafed4a12014-04-09 15:28:44 -0700179 attempt_type_ = attempt_type;
180
David Zeuthen33bae492014-02-25 16:16:18 -0800181 ClockInterface *clock = system_state_->clock();
182 attempt_start_time_boot_ = clock->GetBootTime();
183 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800184 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700185
186 metrics::ConnectionType type;
187 NetworkConnectionType network_connection_type;
188 NetworkTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700189 ConnectionManagerInterface* connection_manager =
190 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700191 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700192 &tethering)) {
193 LOG(ERROR) << "Failed to determine connection type.";
194 type = metrics::ConnectionType::kUnknown;
195 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800196 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700197 }
198 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700199
200 if (attempt_type == AttemptType::kUpdate)
201 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800202}
203
Chris Sosabe45bef2013-04-09 18:25:12 -0700204void PayloadState::UpdateResumed() {
205 LOG(INFO) << "Resuming an update that was previously started.";
206 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700207 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700208}
209
Jay Srinivasan19409b72013-04-12 19:23:36 -0700210void PayloadState::UpdateRestarted() {
211 LOG(INFO) << "Starting a new update";
212 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700213 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700214 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700215}
216
David Zeuthen9a017f22013-04-11 16:10:26 -0700217void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700218 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700219 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700220 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800221
David Zeuthen96197df2014-04-16 12:22:39 -0700222 switch (attempt_type_) {
223 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700224 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700225 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700226 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700227 break;
228
229 case AttemptType::kRollback:
230 metrics::ReportRollbackMetrics(system_state_,
231 metrics::RollbackResult::kSuccess);
232 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700233 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700234
235 // Reset the number of responses seen since it counts from the last
236 // successful update, e.g. now.
237 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700238
239 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700240}
241
David Zeuthena99981f2013-04-29 13:42:47 -0700242void PayloadState::UpdateFailed(ErrorCode error) {
243 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800244 LOG(INFO) << "Updating payload state for error code: " << base_error
245 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800246
Jay Srinivasan53173b92013-05-17 17:13:01 -0700247 if (candidate_urls_.size() == 0) {
248 // This means we got this error even before we got a valid Omaha response
249 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800250 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800251 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
252 return;
253 }
254
David Zeuthen96197df2014-04-16 12:22:39 -0700255 switch (attempt_type_) {
256 case AttemptType::kUpdate:
257 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700258 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700259 break;
260
261 case AttemptType::kRollback:
262 metrics::ReportRollbackMetrics(system_state_,
263 metrics::RollbackResult::kFailed);
264 break;
265 }
David Zeuthen33bae492014-02-25 16:16:18 -0800266
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800267 switch (base_error) {
268 // Errors which are good indicators of a problem with a particular URL or
269 // the protocol used in the URL or entities in the communication channel
270 // (e.g. proxies). We should try the next available URL in the next update
271 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700272 case ErrorCode::kPayloadHashMismatchError:
273 case ErrorCode::kPayloadSizeMismatchError:
274 case ErrorCode::kDownloadPayloadVerificationError:
275 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
276 case ErrorCode::kSignedDeltaPayloadExpectedError:
277 case ErrorCode::kDownloadInvalidMetadataMagicString:
278 case ErrorCode::kDownloadSignatureMissingInManifest:
279 case ErrorCode::kDownloadManifestParseError:
280 case ErrorCode::kDownloadMetadataSignatureError:
281 case ErrorCode::kDownloadMetadataSignatureVerificationError:
282 case ErrorCode::kDownloadMetadataSignatureMismatch:
283 case ErrorCode::kDownloadOperationHashVerificationError:
284 case ErrorCode::kDownloadOperationExecutionError:
285 case ErrorCode::kDownloadOperationHashMismatch:
286 case ErrorCode::kDownloadInvalidMetadataSize:
287 case ErrorCode::kDownloadInvalidMetadataSignature:
288 case ErrorCode::kDownloadOperationHashMissingError:
289 case ErrorCode::kDownloadMetadataSignatureMissingError:
290 case ErrorCode::kPayloadMismatchedType:
291 case ErrorCode::kUnsupportedMajorPayloadVersion:
292 case ErrorCode::kUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800293 IncrementUrlIndex();
294 break;
295
296 // Errors which seem to be just transient network/communication related
297 // failures and do not indicate any inherent problem with the URL itself.
298 // So, we should keep the current URL but just increment the
299 // failure count to give it more chances. This way, while we maximize our
300 // chances of downloading from the URLs that appear earlier in the response
301 // (because download from a local server URL that appears earlier in a
302 // response is preferable than downloading from the next URL which could be
303 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700304
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700305 case ErrorCode::kError:
306 case ErrorCode::kDownloadTransferError:
307 case ErrorCode::kDownloadWriteError:
308 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700309 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800310 IncrementFailureCount();
311 break;
312
313 // Errors which are not specific to a URL and hence shouldn't result in
314 // the URL being penalized. This can happen in two cases:
315 // 1. We haven't started downloading anything: These errors don't cost us
316 // anything in terms of actual payload bytes, so we should just do the
317 // regular retries at the next update check.
318 // 2. We have successfully downloaded the payload: In this case, the
319 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800320 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800321 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700322 case ErrorCode::kOmahaRequestError:
323 case ErrorCode::kOmahaResponseHandlerError:
324 case ErrorCode::kPostinstallRunnerError:
325 case ErrorCode::kFilesystemCopierError:
326 case ErrorCode::kInstallDeviceOpenError:
327 case ErrorCode::kKernelDeviceOpenError:
328 case ErrorCode::kDownloadNewPartitionInfoError:
329 case ErrorCode::kNewRootfsVerificationError:
330 case ErrorCode::kNewKernelVerificationError:
331 case ErrorCode::kPostinstallBootedFromFirmwareB:
332 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
333 case ErrorCode::kOmahaRequestEmptyResponseError:
334 case ErrorCode::kOmahaRequestXMLParseError:
335 case ErrorCode::kOmahaResponseInvalid:
336 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
337 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
338 case ErrorCode::kOmahaUpdateDeferredForBackoff:
339 case ErrorCode::kPostinstallPowerwashError:
340 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400341 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700342 case ErrorCode::kFilesystemVerifierError:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800343 LOG(INFO) << "Not incrementing URL index or failure count for this error";
344 break;
345
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700346 case ErrorCode::kSuccess: // success code
347 case ErrorCode::kUmaReportedMax: // not an error code
348 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
349 case ErrorCode::kDevModeFlag: // not an error code
350 case ErrorCode::kResumedFlag: // not an error code
351 case ErrorCode::kTestImageFlag: // not an error code
352 case ErrorCode::kTestOmahaUrlFlag: // not an error code
353 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800354 // These shouldn't happen. Enumerating these explicitly here so that we
355 // can let the compiler warn about new error codes that are added to
356 // action_processor.h but not added here.
357 LOG(WARNING) << "Unexpected error code for UpdateFailed";
358 break;
359
360 // Note: Not adding a default here so as to let the compiler warn us of
361 // any new enums that were added in the .h but not listed in this switch.
362 }
363}
364
Jay Srinivasan08262882012-12-28 19:29:43 -0800365bool PayloadState::ShouldBackoffDownload() {
366 if (response_.disable_payload_backoff) {
367 LOG(INFO) << "Payload backoff logic is disabled. "
368 "Can proceed with the download";
369 return false;
370 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700371 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700372 LOG(INFO) << "Payload backoff logic is disabled because download "
373 << "will happen from local peer (via p2p).";
374 return false;
375 }
376 if (system_state_->request_params()->interactive()) {
377 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
378 return false;
379 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800380 if (response_.is_delta_payload) {
381 // If delta payloads fail, we want to fallback quickly to full payloads as
382 // they are more likely to succeed. Exponential backoffs would greatly
383 // slow down the fallback to full payloads. So we don't backoff for delta
384 // payloads.
385 LOG(INFO) << "No backoffs for delta payloads. "
386 << "Can proceed with the download";
387 return false;
388 }
389
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700390 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800391 // Backoffs are needed only for official builds. We do not want any delays
392 // or update failures due to backoffs during testing or development.
393 LOG(INFO) << "No backoffs for test/dev images. "
394 << "Can proceed with the download";
395 return false;
396 }
397
398 if (backoff_expiry_time_.is_null()) {
399 LOG(INFO) << "No backoff expiry time has been set. "
400 << "Can proceed with the download";
401 return false;
402 }
403
404 if (backoff_expiry_time_ < Time::Now()) {
405 LOG(INFO) << "The backoff expiry time ("
406 << utils::ToString(backoff_expiry_time_)
407 << ") has elapsed. Can proceed with the download";
408 return false;
409 }
410
411 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
412 << utils::ToString(backoff_expiry_time_);
413 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800414}
415
Chris Sosaaa18e162013-06-20 13:20:30 -0700416void PayloadState::Rollback() {
417 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700418 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700419}
420
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800421void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700422 // Update the payload attempt number for both payload types: full and delta.
423 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
424}
425
426void PayloadState::IncrementFullPayloadAttemptNumber() {
427 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800428 if (response_.is_delta_payload) {
429 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
430 return;
431 }
432
Alex Deymo29b51d92013-07-09 15:26:24 -0700433 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700434 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800435 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800436}
437
438void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800439 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700440 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800441 LOG(INFO) << "Incrementing the URL index for next attempt";
442 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800443 } else {
444 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700445 << "0 as we only have " << candidate_urls_.size()
446 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800447 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700448 IncrementPayloadAttemptNumber();
449 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800450 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800451
David Zeuthencc6f9962013-04-18 11:57:24 -0700452 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700453 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700454 SetUrlSwitchCount(url_switch_count_ + 1);
455
Jay Srinivasan08262882012-12-28 19:29:43 -0800456 // Whenever we update the URL index, we should also clear the URL failure
457 // count so we can start over fresh for the new URL.
458 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800459}
460
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800461void PayloadState::IncrementFailureCount() {
462 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800463 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800464 LOG(INFO) << "Incrementing the URL failure count";
465 SetUrlFailureCount(next_url_failure_count);
466 } else {
467 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
468 << ". Trying next available URL";
469 IncrementUrlIndex();
470 }
471}
472
Jay Srinivasan08262882012-12-28 19:29:43 -0800473void PayloadState::UpdateBackoffExpiryTime() {
474 if (response_.disable_payload_backoff) {
475 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
476 SetBackoffExpiryTime(Time());
477 return;
478 }
479
Alex Deymo820cc702013-06-28 15:43:46 -0700480 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800481 SetBackoffExpiryTime(Time());
482 return;
483 }
484
485 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700486 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800487 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700488 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700489 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800490
491 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
492 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700493 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800494
495 // The number of days is the minimum of 2 raised to (payload_attempt_number
496 // - 1) or kMaxBackoffDays.
497 num_days = min(num_days << power, kMaxBackoffDays);
498
499 // We don't want all retries to happen exactly at the same time when
500 // retrying after backoff. So add some random minutes to fuzz.
501 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
502 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
503 TimeDelta::FromMinutes(fuzz_minutes);
504 LOG(INFO) << "Incrementing the backoff expiry time by "
505 << utils::FormatTimeDelta(next_backoff_interval);
506 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
507}
508
Jay Srinivasan19409b72013-04-12 19:23:36 -0700509void PayloadState::UpdateCurrentDownloadSource() {
510 current_download_source_ = kNumDownloadSources;
511
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700512 if (using_p2p_for_downloading_) {
513 current_download_source_ = kDownloadSourceHttpPeer;
514 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700515 string current_url = candidate_urls_[GetUrlIndex()];
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700516 if (base::StartsWithASCII(current_url, "https://", false))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700517 current_download_source_ = kDownloadSourceHttpsServer;
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700518 else if (base::StartsWithASCII(current_url, "http://", false))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700519 current_download_source_ = kDownloadSourceHttpServer;
520 }
521
522 LOG(INFO) << "Current download source: "
523 << utils::ToString(current_download_source_);
524}
525
526void PayloadState::UpdateBytesDownloaded(size_t count) {
527 SetCurrentBytesDownloaded(
528 current_download_source_,
529 GetCurrentBytesDownloaded(current_download_source_) + count,
530 false);
531 SetTotalBytesDownloaded(
532 current_download_source_,
533 GetTotalBytesDownloaded(current_download_source_) + count,
534 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800535
536 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700537}
538
David Zeuthen33bae492014-02-25 16:16:18 -0800539PayloadType PayloadState::CalculatePayloadType() {
540 PayloadType payload_type;
541 OmahaRequestParams* params = system_state_->request_params();
542 if (response_.is_delta_payload) {
543 payload_type = kPayloadTypeDelta;
544 } else if (params->delta_okay()) {
545 payload_type = kPayloadTypeFull;
546 } else { // Full payload, delta was not allowed by request.
547 payload_type = kPayloadTypeForcedFull;
548 }
549 return payload_type;
550}
551
552// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
553// metrics if the attempt ends abnormally, e.g. if the update_engine
554// process crashes or the device is rebooted. See
555// http://crbug.com/357676
556void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
557 int attempt_number = GetPayloadAttemptNumber();
558
559 PayloadType payload_type = CalculatePayloadType();
560
561 int64_t payload_size = response_.size;
562
563 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
564
565 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700566 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
567 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800568 attempt_start_time_monotonic_;
569
570 int64_t payload_download_speed_bps = 0;
571 int64_t usec = duration_uptime.InMicroseconds();
572 if (usec > 0) {
573 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
574 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
575 payload_download_speed_bps = static_cast<int64_t>(bps);
576 }
577
578 DownloadSource download_source = current_download_source_;
579
580 metrics::DownloadErrorCode payload_download_error_code =
581 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700582 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800583 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800584
585 // Add additional detail to AttemptResult
586 switch (attempt_result) {
587 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800588 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800589 break;
590
591 case metrics::AttemptResult::kInternalError:
592 internal_error_code = code;
593 break;
594
595 // Explicit fall-through for cases where we do not have additional
596 // detail. We avoid the default keyword to force people adding new
597 // AttemptResult values to visit this code and examine whether
598 // additional detail is needed.
599 case metrics::AttemptResult::kUpdateSucceeded:
600 case metrics::AttemptResult::kMetadataMalformed:
601 case metrics::AttemptResult::kOperationMalformed:
602 case metrics::AttemptResult::kOperationExecutionError:
603 case metrics::AttemptResult::kMetadataVerificationFailed:
604 case metrics::AttemptResult::kPayloadVerificationFailed:
605 case metrics::AttemptResult::kVerificationFailed:
606 case metrics::AttemptResult::kPostInstallFailed:
607 case metrics::AttemptResult::kAbnormalTermination:
608 case metrics::AttemptResult::kNumConstants:
609 case metrics::AttemptResult::kUnset:
610 break;
611 }
612
613 metrics::ReportUpdateAttemptMetrics(system_state_,
614 attempt_number,
615 payload_type,
616 duration,
617 duration_uptime,
618 payload_size,
619 payload_bytes_downloaded,
620 payload_download_speed_bps,
621 download_source,
622 attempt_result,
623 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700624 payload_download_error_code,
625 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800626}
627
David Zeuthen4e1d1492014-04-25 13:12:27 -0700628void PayloadState::PersistAttemptMetrics() {
629 // TODO(zeuthen): For now we only persist whether an attempt was in
630 // progress and not values/metrics related to the attempt. This
631 // means that when this happens, of all the UpdateEngine.Attempt.*
632 // metrics, only UpdateEngine.Attempt.Result is reported (with the
633 // value |kAbnormalTermination|). In the future we might want to
634 // persist more data so we can report other metrics in the
635 // UpdateEngine.Attempt.* namespace when this happens.
636 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
637}
638
639void PayloadState::ClearPersistedAttemptMetrics() {
640 prefs_->Delete(kPrefsAttemptInProgress);
641}
642
643void PayloadState::ReportAndClearPersistedAttemptMetrics() {
644 bool attempt_in_progress = false;
645 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
646 return;
647 if (!attempt_in_progress)
648 return;
649
650 metrics::ReportAbnormallyTerminatedUpdateAttemptMetrics(system_state_);
651
652 ClearPersistedAttemptMetrics();
653}
654
David Zeuthen33bae492014-02-25 16:16:18 -0800655void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700656 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800657
658 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800659 int64_t total_bytes_by_source[kNumDownloadSources];
660 int64_t successful_bytes = 0;
661 int64_t total_bytes = 0;
662 int64_t successful_mbs = 0;
663 int64_t total_mbs = 0;
664
Jay Srinivasan19409b72013-04-12 19:23:36 -0700665 for (int i = 0; i < kNumDownloadSources; i++) {
666 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800667 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700668
David Zeuthen44848602013-06-24 13:32:14 -0700669 // Only consider this download source (and send byte counts) as
670 // having been used if we downloaded a non-trivial amount of bytes
671 // (e.g. at least 1 MiB) that contributed to the final success of
672 // the update. Otherwise we're going to end up with a lot of
673 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700674
David Zeuthen33bae492014-02-25 16:16:18 -0800675 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800676 successful_bytes += bytes;
677 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700678 SetCurrentBytesDownloaded(source, 0, true);
679
David Zeuthen33bae492014-02-25 16:16:18 -0800680 bytes = GetTotalBytesDownloaded(source);
681 total_bytes_by_source[i] = bytes;
682 total_bytes += bytes;
683 total_mbs += bytes / kNumBytesInOneMiB;
684 SetTotalBytesDownloaded(source, 0, true);
685 }
686
687 int download_overhead_percentage = 0;
688 if (successful_bytes > 0) {
689 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
690 successful_bytes;
691 }
692
693 int url_switch_count = static_cast<int>(url_switch_count_);
694
695 int reboot_count = GetNumReboots();
696
697 SetNumReboots(0);
698
699 TimeDelta duration = GetUpdateDuration();
David Zeuthen33bae492014-02-25 16:16:18 -0800700
701 prefs_->Delete(kPrefsUpdateTimestampStart);
702 prefs_->Delete(kPrefsUpdateDurationUptime);
703
704 PayloadType payload_type = CalculatePayloadType();
705
706 int64_t payload_size = response_.size;
707
708 int attempt_count = GetPayloadAttemptNumber();
709
710 int updates_abandoned_count = num_responses_seen_ - 1;
711
712 metrics::ReportSuccessfulUpdateMetrics(system_state_,
713 attempt_count,
714 updates_abandoned_count,
715 payload_type,
716 payload_size,
717 total_bytes_by_source,
718 download_overhead_percentage,
719 duration,
720 reboot_count,
721 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700722}
723
724void PayloadState::UpdateNumReboots() {
725 // We only update the reboot count when the system has been detected to have
726 // been rebooted.
727 if (!system_state_->system_rebooted()) {
728 return;
729 }
730
731 SetNumReboots(GetNumReboots() + 1);
732}
733
734void PayloadState::SetNumReboots(uint32_t num_reboots) {
735 CHECK(prefs_);
736 num_reboots_ = num_reboots;
737 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
738 LOG(INFO) << "Number of Reboots during current update attempt = "
739 << num_reboots_;
740}
741
Jay Srinivasan08262882012-12-28 19:29:43 -0800742void PayloadState::ResetPersistedState() {
743 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700744 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800745 SetUrlIndex(0);
746 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700747 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700748 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700749 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700750 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700751 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700752 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700753 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700754 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700755 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700756 SetScatteringWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700757}
758
759void PayloadState::ResetRollbackVersion() {
760 CHECK(powerwash_safe_prefs_);
761 rollback_version_ = "";
762 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700763}
764
765void PayloadState::ResetDownloadSourcesOnNewUpdate() {
766 for (int i = 0; i < kNumDownloadSources; i++) {
767 DownloadSource source = static_cast<DownloadSource>(i);
768 SetCurrentBytesDownloaded(source, 0, true);
769 // Note: Not resetting the TotalBytesDownloaded as we want that metric
770 // to count the bytes downloaded across various update attempts until
771 // we have successfully applied the update.
772 }
773}
774
Chris Sosab3dcdb32013-09-04 15:22:12 -0700775int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700776 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700777 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700778 return 0;
779
780 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700781 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700782 return 0;
783
784 if (stored_value < 0) {
785 LOG(ERROR) << key << ": Invalid value (" << stored_value
786 << ") in persisted state. Defaulting to 0";
787 return 0;
788 }
789
790 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800791}
792
793string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700794 string response_sign = base::StringPrintf(
795 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800796
Jay Srinivasan53173b92013-05-17 17:13:01 -0700797 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700798 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
799 static_cast<int>(i),
800 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800801
Alex Vakulenko75039d72014-03-25 12:36:28 -0700802 response_sign += base::StringPrintf(
803 "Payload Size = %ju\n"
804 "Payload Sha256 Hash = %s\n"
805 "Metadata Size = %ju\n"
806 "Metadata Signature = %s\n"
807 "Is Delta Payload = %d\n"
808 "Max Failure Count Per Url = %d\n"
809 "Disable Payload Backoff = %d\n",
810 static_cast<uintmax_t>(response_.size),
811 response_.hash.c_str(),
812 static_cast<uintmax_t>(response_.metadata_size),
813 response_.metadata_signature.c_str(),
814 response_.is_delta_payload,
815 response_.max_failure_count_per_url,
816 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800817 return response_sign;
818}
819
820void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800821 CHECK(prefs_);
822 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800823 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
824 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
825 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800826 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800827}
828
Jay Srinivasan19409b72013-04-12 19:23:36 -0700829void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800830 CHECK(prefs_);
831 response_signature_ = response_signature;
832 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
833 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
834}
835
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800836void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700837 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800838}
839
Alex Deymo820cc702013-06-28 15:43:46 -0700840void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700841 SetFullPayloadAttemptNumber(GetPersistedValue(
842 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700843}
844
845void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800846 CHECK(prefs_);
847 payload_attempt_number_ = payload_attempt_number;
848 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
849 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
850}
851
Alex Deymo820cc702013-06-28 15:43:46 -0700852void PayloadState::SetFullPayloadAttemptNumber(
853 int full_payload_attempt_number) {
854 CHECK(prefs_);
855 full_payload_attempt_number_ = full_payload_attempt_number;
856 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
857 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
858 full_payload_attempt_number_);
859}
860
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800861void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700862 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800863}
864
865void PayloadState::SetUrlIndex(uint32_t url_index) {
866 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800867 url_index_ = url_index;
868 LOG(INFO) << "Current URL Index = " << url_index_;
869 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700870
871 // Also update the download source, which is purely dependent on the
872 // current URL index alone.
873 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800874}
875
Gilad Arnold519cfc72014-10-02 10:34:54 -0700876void PayloadState::LoadScatteringWaitPeriod() {
877 SetScatteringWaitPeriod(
878 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
879}
880
Alex Deymof329b932014-10-30 01:37:48 -0700881void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700882 CHECK(prefs_);
883 scattering_wait_period_ = wait_period;
884 LOG(INFO) << "Scattering Wait Period (seconds) = "
885 << scattering_wait_period_.InSeconds();
886 if (scattering_wait_period_.InSeconds() > 0) {
887 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
888 scattering_wait_period_.InSeconds());
889 } else {
890 prefs_->Delete(kPrefsWallClockWaitPeriod);
891 }
892}
893
David Zeuthencc6f9962013-04-18 11:57:24 -0700894void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700895 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700896}
897
898void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
899 CHECK(prefs_);
900 url_switch_count_ = url_switch_count;
901 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
902 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
903}
904
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800905void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700906 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800907}
908
909void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
910 CHECK(prefs_);
911 url_failure_count_ = url_failure_count;
912 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
913 << ")'s Failure Count = " << url_failure_count_;
914 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800915}
916
Jay Srinivasan08262882012-12-28 19:29:43 -0800917void PayloadState::LoadBackoffExpiryTime() {
918 CHECK(prefs_);
919 int64_t stored_value;
920 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
921 return;
922
923 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
924 return;
925
926 Time stored_time = Time::FromInternalValue(stored_value);
927 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
928 LOG(ERROR) << "Invalid backoff expiry time ("
929 << utils::ToString(stored_time)
930 << ") in persisted state. Resetting.";
931 stored_time = Time();
932 }
933 SetBackoffExpiryTime(stored_time);
934}
935
936void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
937 CHECK(prefs_);
938 backoff_expiry_time_ = new_time;
939 LOG(INFO) << "Backoff Expiry Time = "
940 << utils::ToString(backoff_expiry_time_);
941 prefs_->SetInt64(kPrefsBackoffExpiryTime,
942 backoff_expiry_time_.ToInternalValue());
943}
944
David Zeuthen9a017f22013-04-11 16:10:26 -0700945TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700946 Time end_time = update_timestamp_end_.is_null()
947 ? system_state_->clock()->GetWallclockTime() :
948 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700949 return end_time - update_timestamp_start_;
950}
951
952void PayloadState::LoadUpdateTimestampStart() {
953 int64_t stored_value;
954 Time stored_time;
955
956 CHECK(prefs_);
957
David Zeuthenf413fe52013-04-22 14:04:39 -0700958 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700959
960 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
961 // The preference missing is not unexpected - in that case, just
962 // use the current time as start time
963 stored_time = now;
964 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
965 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
966 stored_time = now;
967 } else {
968 stored_time = Time::FromInternalValue(stored_value);
969 }
970
971 // Sanity check: If the time read from disk is in the future
972 // (modulo some slack to account for possible NTP drift
973 // adjustments), something is fishy and we should report and
974 // reset.
975 TimeDelta duration_according_to_stored_time = now - stored_time;
976 if (duration_according_to_stored_time < -kDurationSlack) {
977 LOG(ERROR) << "The UpdateTimestampStart value ("
978 << utils::ToString(stored_time)
979 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700980 << utils::FormatTimeDelta(duration_according_to_stored_time)
981 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700982 stored_time = now;
983 }
984
985 SetUpdateTimestampStart(stored_time);
986}
987
988void PayloadState::SetUpdateTimestampStart(const Time& value) {
989 CHECK(prefs_);
990 update_timestamp_start_ = value;
991 prefs_->SetInt64(kPrefsUpdateTimestampStart,
992 update_timestamp_start_.ToInternalValue());
993 LOG(INFO) << "Update Timestamp Start = "
994 << utils::ToString(update_timestamp_start_);
995}
996
997void PayloadState::SetUpdateTimestampEnd(const Time& value) {
998 update_timestamp_end_ = value;
999 LOG(INFO) << "Update Timestamp End = "
1000 << utils::ToString(update_timestamp_end_);
1001}
1002
1003TimeDelta PayloadState::GetUpdateDurationUptime() {
1004 return update_duration_uptime_;
1005}
1006
1007void PayloadState::LoadUpdateDurationUptime() {
1008 int64_t stored_value;
1009 TimeDelta stored_delta;
1010
1011 CHECK(prefs_);
1012
1013 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1014 // The preference missing is not unexpected - in that case, just
1015 // we'll use zero as the delta
1016 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1017 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1018 stored_delta = TimeDelta::FromSeconds(0);
1019 } else {
1020 stored_delta = TimeDelta::FromInternalValue(stored_value);
1021 }
1022
1023 // Sanity-check: Uptime can never be greater than the wall-clock
1024 // difference (modulo some slack). If it is, report and reset
1025 // to the wall-clock difference.
1026 TimeDelta diff = GetUpdateDuration() - stored_delta;
1027 if (diff < -kDurationSlack) {
1028 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001029 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001030 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001031 << utils::FormatTimeDelta(diff)
1032 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001033 stored_delta = update_duration_current_;
1034 }
1035
1036 SetUpdateDurationUptime(stored_delta);
1037}
1038
Chris Sosabe45bef2013-04-09 18:25:12 -07001039void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001040 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001041}
1042
1043void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001044 CHECK(powerwash_safe_prefs_);
1045 string rollback_version;
1046 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1047 &rollback_version)) {
1048 SetRollbackVersion(rollback_version);
1049 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001050}
1051
1052void PayloadState::SetRollbackVersion(const string& rollback_version) {
1053 CHECK(powerwash_safe_prefs_);
1054 LOG(INFO) << "Blacklisting version "<< rollback_version;
1055 rollback_version_ = rollback_version;
1056 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001057}
1058
David Zeuthen9a017f22013-04-11 16:10:26 -07001059void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1060 const Time& timestamp,
1061 bool use_logging) {
1062 CHECK(prefs_);
1063 update_duration_uptime_ = value;
1064 update_duration_uptime_timestamp_ = timestamp;
1065 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1066 update_duration_uptime_.ToInternalValue());
1067 if (use_logging) {
1068 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001069 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001070 }
1071}
1072
1073void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001074 Time now = system_state_->clock()->GetMonotonicTime();
1075 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001076}
1077
1078void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001079 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001080 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1081 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1082 // We're frequently called so avoid logging this write
1083 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1084}
1085
Jay Srinivasan19409b72013-04-12 19:23:36 -07001086string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1087 return prefix + "-from-" + utils::ToString(source);
1088}
1089
1090void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1091 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001092 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001093}
1094
1095void PayloadState::SetCurrentBytesDownloaded(
1096 DownloadSource source,
1097 uint64_t current_bytes_downloaded,
1098 bool log) {
1099 CHECK(prefs_);
1100
1101 if (source >= kNumDownloadSources)
1102 return;
1103
1104 // Update the in-memory value.
1105 current_bytes_downloaded_[source] = current_bytes_downloaded;
1106
1107 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1108 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1109 LOG_IF(INFO, log) << "Current bytes downloaded for "
1110 << utils::ToString(source) << " = "
1111 << GetCurrentBytesDownloaded(source);
1112}
1113
1114void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1115 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001116 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001117}
1118
1119void PayloadState::SetTotalBytesDownloaded(
1120 DownloadSource source,
1121 uint64_t total_bytes_downloaded,
1122 bool log) {
1123 CHECK(prefs_);
1124
1125 if (source >= kNumDownloadSources)
1126 return;
1127
1128 // Update the in-memory value.
1129 total_bytes_downloaded_[source] = total_bytes_downloaded;
1130
1131 // Persist.
1132 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1133 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1134 LOG_IF(INFO, log) << "Total bytes downloaded for "
1135 << utils::ToString(source) << " = "
1136 << GetTotalBytesDownloaded(source);
1137}
1138
David Zeuthena573d6f2013-06-14 16:13:36 -07001139void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001140 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001141}
1142
1143void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1144 CHECK(prefs_);
1145 num_responses_seen_ = num_responses_seen;
1146 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1147 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1148}
1149
Jay Srinivasan53173b92013-05-17 17:13:01 -07001150void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001151 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001152
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001153 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001154 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001155 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001156 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1157 } else {
1158 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1159 http_url_ok = true;
1160 }
1161
1162 candidate_urls_.clear();
1163 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1164 string candidate_url = response_.payload_urls[i];
Alex Vakulenko6a9d3492015-06-15 12:53:22 -07001165 if (base::StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1166 continue;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001167 candidate_urls_.push_back(candidate_url);
1168 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1169 << ": " << candidate_url;
1170 }
1171
1172 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1173 << "out of " << response_.payload_urls.size() << " URLs supplied";
1174}
1175
David Zeuthene4c58bf2013-06-18 17:26:50 -07001176void PayloadState::CreateSystemUpdatedMarkerFile() {
1177 CHECK(prefs_);
1178 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1179 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1180}
1181
1182void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1183 // Send |time_to_reboot| as a UMA stat.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001184 string metric = metrics::kMetricTimeToRebootMinutes;
David Zeuthen33bae492014-02-25 16:16:18 -08001185 system_state_->metrics_lib()->SendToUMA(metric,
1186 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001187 0, // min: 0 minute
1188 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001189 kNumDefaultUmaBuckets);
1190 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1191 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001192}
1193
1194void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001195 // Flush previous state from abnormal attempt failure, if any.
1196 ReportAndClearPersistedAttemptMetrics();
1197
Alex Deymo569c4242013-07-24 12:01:01 -07001198 // Avoid the UpdateEngineStarted actions if this is not the first time we
1199 // run the update engine since reboot.
1200 if (!system_state_->system_rebooted())
1201 return;
1202
David Zeuthene4c58bf2013-06-18 17:26:50 -07001203 // Figure out if we just booted into a new update
1204 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1205 int64_t stored_value;
1206 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1207 Time system_updated_at = Time::FromInternalValue(stored_value);
1208 if (!system_updated_at.is_null()) {
1209 TimeDelta time_to_reboot =
1210 system_state_->clock()->GetWallclockTime() - system_updated_at;
1211 if (time_to_reboot.ToInternalValue() < 0) {
1212 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1213 << utils::ToString(system_updated_at);
1214 } else {
1215 BootedIntoUpdate(time_to_reboot);
1216 }
1217 }
1218 }
1219 prefs_->Delete(kPrefsSystemUpdatedMarker);
1220 }
Alex Deymo42432912013-07-12 20:21:15 -07001221 // Check if it is needed to send metrics about a failed reboot into a new
1222 // version.
1223 ReportFailedBootIfNeeded();
1224}
1225
1226void PayloadState::ReportFailedBootIfNeeded() {
1227 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1228 // payload was marked as ready immediately before the last reboot, and we
1229 // need to check if such payload successfully rebooted or not.
1230 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001231 int64_t installed_from = 0;
1232 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001233 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1234 return;
1235 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001236 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1237 // partition number. We are now using slot numbers (0 or 1) instead, so
1238 // the following comparison will not match if we are comparing an old
1239 // partition number against a new slot number, which is the correct outcome
1240 // since we successfully booted the new update in that case. If the boot
1241 // failed, we will read this value from the same version, so it will always
1242 // be compatible.
1243 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001244 // A reboot was pending, but the chromebook is again in the same
1245 // BootDevice where the update was installed from.
1246 int64_t target_attempt;
1247 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1248 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1249 "TargetVersionInstalledFrom was present.";
1250 target_attempt = 1;
1251 }
1252
1253 // Report the UMA metric of the current boot failure.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001254 string metric = metrics::kMetricFailedUpdateCount;
David Zeuthen33bae492014-02-25 16:16:18 -08001255 LOG(INFO) << "Uploading " << target_attempt
1256 << " (count) for metric " << metric;
1257 system_state_->metrics_lib()->SendToUMA(
1258 metric,
1259 target_attempt,
1260 1, // min value
1261 50, // max value
1262 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001263 } else {
1264 prefs_->Delete(kPrefsTargetVersionAttempt);
1265 prefs_->Delete(kPrefsTargetVersionUniqueId);
1266 }
1267 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1268 }
1269}
1270
1271void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1272 // Expect to boot into the new partition in the next reboot setting the
1273 // TargetVersion* flags in the Prefs.
1274 string stored_target_version_uid;
1275 string target_version_id;
1276 string target_partition;
1277 int64_t target_attempt;
1278
1279 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1280 prefs_->GetString(kPrefsTargetVersionUniqueId,
1281 &stored_target_version_uid) &&
1282 stored_target_version_uid == target_version_uid) {
1283 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1284 target_attempt = 0;
1285 } else {
1286 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1287 target_attempt = 0;
1288 }
1289 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1290
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001291 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001292 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001293}
1294
1295void PayloadState::ResetUpdateStatus() {
1296 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1297 // rebooted the next boot is not flagged as failed to rebooted into the
1298 // new applied payload.
1299 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1300
1301 // Also decrement the attempt number if it exists.
1302 int64_t target_attempt;
1303 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001304 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001305}
1306
David Zeuthendcba8092013-08-06 12:16:35 -07001307int PayloadState::GetP2PNumAttempts() {
1308 return p2p_num_attempts_;
1309}
1310
1311void PayloadState::SetP2PNumAttempts(int value) {
1312 p2p_num_attempts_ = value;
1313 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1314 CHECK(prefs_);
1315 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1316}
1317
1318void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001319 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001320}
1321
1322Time PayloadState::GetP2PFirstAttemptTimestamp() {
1323 return p2p_first_attempt_timestamp_;
1324}
1325
1326void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1327 p2p_first_attempt_timestamp_ = time;
1328 LOG(INFO) << "p2p First Attempt Timestamp = "
1329 << utils::ToString(p2p_first_attempt_timestamp_);
1330 CHECK(prefs_);
1331 int64_t stored_value = time.ToInternalValue();
1332 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1333}
1334
1335void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001336 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001337 Time stored_time = Time::FromInternalValue(stored_value);
1338 SetP2PFirstAttemptTimestamp(stored_time);
1339}
1340
1341void PayloadState::P2PNewAttempt() {
1342 CHECK(prefs_);
1343 // Set timestamp, if it hasn't been set already
1344 if (p2p_first_attempt_timestamp_.is_null()) {
1345 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1346 }
1347 // Increase number of attempts
1348 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1349}
1350
1351bool PayloadState::P2PAttemptAllowed() {
1352 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1353 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1354 << " which is greater than "
1355 << kMaxP2PAttempts
1356 << " - disallowing p2p.";
1357 return false;
1358 }
1359
1360 if (!p2p_first_attempt_timestamp_.is_null()) {
1361 Time now = system_state_->clock()->GetWallclockTime();
1362 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1363 if (time_spent_attempting_p2p.InSeconds() < 0) {
1364 LOG(ERROR) << "Time spent attempting p2p is negative"
1365 << " - disallowing p2p.";
1366 return false;
1367 }
1368 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1369 LOG(INFO) << "Time spent attempting p2p is "
1370 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1371 << " which is greater than "
1372 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1373 kMaxP2PAttemptTimeSeconds))
1374 << " - disallowing p2p.";
1375 return false;
1376 }
1377 }
1378
1379 return true;
1380}
1381
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001382} // namespace chromeos_update_engine