blob: 9160ccd400dbb485fd6bf30ea1d4c7887b60feb2 [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>
Gilad Arnold1f847232014-04-07 12:07:49 -070025#include <policy/device_policy.h>
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080026
Alex Deymo39910dc2015-11-09 17:04:30 -080027#include "update_engine/common/clock.h"
28#include "update_engine/common/constants.h"
29#include "update_engine/common/hardware_interface.h"
30#include "update_engine/common/prefs.h"
31#include "update_engine/common/utils.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070032#include "update_engine/omaha_request_params.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080033#include "update_engine/payload_consumer/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070034#include "update_engine/system_state.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080035
Jay Srinivasan08262882012-12-28 19:29:43 -080036using base::Time;
37using base::TimeDelta;
38using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080039using std::string;
40
41namespace chromeos_update_engine {
42
David Zeuthen9a017f22013-04-11 16:10:26 -070043const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
44
Jay Srinivasan08262882012-12-28 19:29:43 -080045// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070046static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080047
Jay Srinivasan08262882012-12-28 19:29:43 -080048// We want to randomize retry attempts after the backoff by +/- 6 hours.
49static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080050
Jay Srinivasan19409b72013-04-12 19:23:36 -070051PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070052 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070053 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070054 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070055 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070056 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070057 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070058 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070059 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070060 attempt_num_bytes_downloaded_(0),
61 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070062 attempt_type_(AttemptType::kUpdate) {
63 for (int i = 0; i <= kNumDownloadSources; i++)
64 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070065}
66
67bool PayloadState::Initialize(SystemState* system_state) {
68 system_state_ = system_state;
69 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070070 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080071 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080072 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070073 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080074 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080075 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070076 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080077 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070078 LoadUpdateTimestampStart();
79 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
80 // being called before it. Don't reorder.
81 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070082 for (int i = 0; i < kNumDownloadSources; i++) {
83 DownloadSource source = static_cast<DownloadSource>(i);
84 LoadCurrentBytesDownloaded(source);
85 LoadTotalBytesDownloaded(source);
86 }
Chris Sosabe45bef2013-04-09 18:25:12 -070087 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070088 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070089 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070090 LoadP2PFirstAttemptTimestamp();
91 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080092 return true;
93}
94
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080095void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080096 // Always store the latest response.
97 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080098
Jay Srinivasan53173b92013-05-17 17:13:01 -070099 // Compute the candidate URLs first as they are used to calculate the
100 // response signature so that a change in enterprise policy for
101 // HTTP downloads being enabled or not could be honored as soon as the
102 // next update check happens.
103 ComputeCandidateUrls();
104
Jay Srinivasan08262882012-12-28 19:29:43 -0800105 // Check if the "signature" of this response (i.e. the fields we care about)
106 // has changed.
107 string new_response_signature = CalculateResponseSignature();
108 bool has_response_changed = (response_signature_ != new_response_signature);
109
110 // If the response has changed, we should persist the new signature and
111 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800112 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800113 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700114 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800115 SetResponseSignature(new_response_signature);
116 ResetPersistedState();
117 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800118 }
119
Jay Srinivasan08262882012-12-28 19:29:43 -0800120 // This is the earliest point at which we can validate whether the URL index
121 // we loaded from the persisted state is a valid value. If the response
122 // hasn't changed but the URL index is invalid, it's indicative of some
123 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700124 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800125 LOG(INFO) << "Resetting all payload state as the url index seems to have "
126 "been tampered with";
127 ResetPersistedState();
128 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800129 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700130
131 // Update the current download source which depends on the latest value of
132 // the response.
133 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800134}
135
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700136void PayloadState::SetUsingP2PForDownloading(bool value) {
137 using_p2p_for_downloading_ = value;
138 // Update the current download source which depends on whether we are
139 // using p2p or not.
140 UpdateCurrentDownloadSource();
141}
142
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800143void PayloadState::DownloadComplete() {
144 LOG(INFO) << "Payload downloaded successfully";
145 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700146 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800147}
148
149void PayloadState::DownloadProgress(size_t count) {
150 if (count == 0)
151 return;
152
David Zeuthen9a017f22013-04-11 16:10:26 -0700153 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700154 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700155
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800156 // We've received non-zero bytes from a recent download operation. Since our
157 // URL failure count is meant to penalize a URL only for consecutive
158 // failures, downloading bytes successfully means we should reset the failure
159 // count (as we know at least that the URL is working). In future, we can
160 // design this to be more sophisticated to check for more intelligent failure
161 // patterns, but right now, even 1 byte downloaded will mark the URL to be
162 // good unless it hits 10 (or configured number of) consecutive failures
163 // again.
164
165 if (GetUrlFailureCount() == 0)
166 return;
167
168 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
169 << " to 0 as we received " << count << " bytes successfully";
170 SetUrlFailureCount(0);
171}
172
David Zeuthenafed4a12014-04-09 15:28:44 -0700173void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700174 // Flush previous state from abnormal attempt failure, if any.
175 ReportAndClearPersistedAttemptMetrics();
176
David Zeuthenafed4a12014-04-09 15:28:44 -0700177 attempt_type_ = attempt_type;
178
David Zeuthen33bae492014-02-25 16:16:18 -0800179 ClockInterface *clock = system_state_->clock();
180 attempt_start_time_boot_ = clock->GetBootTime();
181 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800182 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700183
184 metrics::ConnectionType type;
185 NetworkConnectionType network_connection_type;
186 NetworkTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700187 ConnectionManagerInterface* connection_manager =
188 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700189 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700190 &tethering)) {
191 LOG(ERROR) << "Failed to determine connection type.";
192 type = metrics::ConnectionType::kUnknown;
193 } else {
194 type = utils::GetConnectionType(network_connection_type, tethering);
195 }
196 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700197
198 if (attempt_type == AttemptType::kUpdate)
199 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800200}
201
Chris Sosabe45bef2013-04-09 18:25:12 -0700202void PayloadState::UpdateResumed() {
203 LOG(INFO) << "Resuming an update that was previously started.";
204 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700205 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700206}
207
Jay Srinivasan19409b72013-04-12 19:23:36 -0700208void PayloadState::UpdateRestarted() {
209 LOG(INFO) << "Starting a new update";
210 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700211 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700212 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700213}
214
David Zeuthen9a017f22013-04-11 16:10:26 -0700215void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700216 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700217 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700218 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800219
David Zeuthen96197df2014-04-16 12:22:39 -0700220 switch (attempt_type_) {
221 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700222 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700223 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700224 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700225 break;
226
227 case AttemptType::kRollback:
228 metrics::ReportRollbackMetrics(system_state_,
229 metrics::RollbackResult::kSuccess);
230 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700231 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700232
233 // Reset the number of responses seen since it counts from the last
234 // successful update, e.g. now.
235 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700236
237 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700238}
239
David Zeuthena99981f2013-04-29 13:42:47 -0700240void PayloadState::UpdateFailed(ErrorCode error) {
241 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800242 LOG(INFO) << "Updating payload state for error code: " << base_error
243 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800244
Jay Srinivasan53173b92013-05-17 17:13:01 -0700245 if (candidate_urls_.size() == 0) {
246 // This means we got this error even before we got a valid Omaha response
247 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800248 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800249 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
250 return;
251 }
252
David Zeuthen96197df2014-04-16 12:22:39 -0700253 switch (attempt_type_) {
254 case AttemptType::kUpdate:
255 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700256 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700257 break;
258
259 case AttemptType::kRollback:
260 metrics::ReportRollbackMetrics(system_state_,
261 metrics::RollbackResult::kFailed);
262 break;
263 }
David Zeuthen33bae492014-02-25 16:16:18 -0800264
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800265 switch (base_error) {
266 // Errors which are good indicators of a problem with a particular URL or
267 // the protocol used in the URL or entities in the communication channel
268 // (e.g. proxies). We should try the next available URL in the next update
269 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700270 case ErrorCode::kPayloadHashMismatchError:
271 case ErrorCode::kPayloadSizeMismatchError:
272 case ErrorCode::kDownloadPayloadVerificationError:
273 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
274 case ErrorCode::kSignedDeltaPayloadExpectedError:
275 case ErrorCode::kDownloadInvalidMetadataMagicString:
276 case ErrorCode::kDownloadSignatureMissingInManifest:
277 case ErrorCode::kDownloadManifestParseError:
278 case ErrorCode::kDownloadMetadataSignatureError:
279 case ErrorCode::kDownloadMetadataSignatureVerificationError:
280 case ErrorCode::kDownloadMetadataSignatureMismatch:
281 case ErrorCode::kDownloadOperationHashVerificationError:
282 case ErrorCode::kDownloadOperationExecutionError:
283 case ErrorCode::kDownloadOperationHashMismatch:
284 case ErrorCode::kDownloadInvalidMetadataSize:
285 case ErrorCode::kDownloadInvalidMetadataSignature:
286 case ErrorCode::kDownloadOperationHashMissingError:
287 case ErrorCode::kDownloadMetadataSignatureMissingError:
288 case ErrorCode::kPayloadMismatchedType:
289 case ErrorCode::kUnsupportedMajorPayloadVersion:
290 case ErrorCode::kUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800291 IncrementUrlIndex();
292 break;
293
294 // Errors which seem to be just transient network/communication related
295 // failures and do not indicate any inherent problem with the URL itself.
296 // So, we should keep the current URL but just increment the
297 // failure count to give it more chances. This way, while we maximize our
298 // chances of downloading from the URLs that appear earlier in the response
299 // (because download from a local server URL that appears earlier in a
300 // response is preferable than downloading from the next URL which could be
301 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700302
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700303 case ErrorCode::kError:
304 case ErrorCode::kDownloadTransferError:
305 case ErrorCode::kDownloadWriteError:
306 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700307 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800308 IncrementFailureCount();
309 break;
310
311 // Errors which are not specific to a URL and hence shouldn't result in
312 // the URL being penalized. This can happen in two cases:
313 // 1. We haven't started downloading anything: These errors don't cost us
314 // anything in terms of actual payload bytes, so we should just do the
315 // regular retries at the next update check.
316 // 2. We have successfully downloaded the payload: In this case, the
317 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800318 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800319 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700320 case ErrorCode::kOmahaRequestError:
321 case ErrorCode::kOmahaResponseHandlerError:
322 case ErrorCode::kPostinstallRunnerError:
323 case ErrorCode::kFilesystemCopierError:
324 case ErrorCode::kInstallDeviceOpenError:
325 case ErrorCode::kKernelDeviceOpenError:
326 case ErrorCode::kDownloadNewPartitionInfoError:
327 case ErrorCode::kNewRootfsVerificationError:
328 case ErrorCode::kNewKernelVerificationError:
329 case ErrorCode::kPostinstallBootedFromFirmwareB:
330 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
331 case ErrorCode::kOmahaRequestEmptyResponseError:
332 case ErrorCode::kOmahaRequestXMLParseError:
333 case ErrorCode::kOmahaResponseInvalid:
334 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
335 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
336 case ErrorCode::kOmahaUpdateDeferredForBackoff:
337 case ErrorCode::kPostinstallPowerwashError:
338 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400339 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700340 case ErrorCode::kFilesystemVerifierError:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800341 LOG(INFO) << "Not incrementing URL index or failure count for this error";
342 break;
343
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700344 case ErrorCode::kSuccess: // success code
345 case ErrorCode::kUmaReportedMax: // not an error code
346 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
347 case ErrorCode::kDevModeFlag: // not an error code
348 case ErrorCode::kResumedFlag: // not an error code
349 case ErrorCode::kTestImageFlag: // not an error code
350 case ErrorCode::kTestOmahaUrlFlag: // not an error code
351 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800352 // These shouldn't happen. Enumerating these explicitly here so that we
353 // can let the compiler warn about new error codes that are added to
354 // action_processor.h but not added here.
355 LOG(WARNING) << "Unexpected error code for UpdateFailed";
356 break;
357
358 // Note: Not adding a default here so as to let the compiler warn us of
359 // any new enums that were added in the .h but not listed in this switch.
360 }
361}
362
Jay Srinivasan08262882012-12-28 19:29:43 -0800363bool PayloadState::ShouldBackoffDownload() {
364 if (response_.disable_payload_backoff) {
365 LOG(INFO) << "Payload backoff logic is disabled. "
366 "Can proceed with the download";
367 return false;
368 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700369 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700370 LOG(INFO) << "Payload backoff logic is disabled because download "
371 << "will happen from local peer (via p2p).";
372 return false;
373 }
374 if (system_state_->request_params()->interactive()) {
375 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
376 return false;
377 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800378 if (response_.is_delta_payload) {
379 // If delta payloads fail, we want to fallback quickly to full payloads as
380 // they are more likely to succeed. Exponential backoffs would greatly
381 // slow down the fallback to full payloads. So we don't backoff for delta
382 // payloads.
383 LOG(INFO) << "No backoffs for delta payloads. "
384 << "Can proceed with the download";
385 return false;
386 }
387
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700388 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800389 // Backoffs are needed only for official builds. We do not want any delays
390 // or update failures due to backoffs during testing or development.
391 LOG(INFO) << "No backoffs for test/dev images. "
392 << "Can proceed with the download";
393 return false;
394 }
395
396 if (backoff_expiry_time_.is_null()) {
397 LOG(INFO) << "No backoff expiry time has been set. "
398 << "Can proceed with the download";
399 return false;
400 }
401
402 if (backoff_expiry_time_ < Time::Now()) {
403 LOG(INFO) << "The backoff expiry time ("
404 << utils::ToString(backoff_expiry_time_)
405 << ") has elapsed. Can proceed with the download";
406 return false;
407 }
408
409 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
410 << utils::ToString(backoff_expiry_time_);
411 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800412}
413
Chris Sosaaa18e162013-06-20 13:20:30 -0700414void PayloadState::Rollback() {
415 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700416 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700417}
418
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800419void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700420 // Update the payload attempt number for both payload types: full and delta.
421 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
422}
423
424void PayloadState::IncrementFullPayloadAttemptNumber() {
425 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800426 if (response_.is_delta_payload) {
427 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
428 return;
429 }
430
Alex Deymo29b51d92013-07-09 15:26:24 -0700431 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700432 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800433 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800434}
435
436void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800437 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700438 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800439 LOG(INFO) << "Incrementing the URL index for next attempt";
440 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800441 } else {
442 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700443 << "0 as we only have " << candidate_urls_.size()
444 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800445 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700446 IncrementPayloadAttemptNumber();
447 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800448 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800449
David Zeuthencc6f9962013-04-18 11:57:24 -0700450 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700451 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700452 SetUrlSwitchCount(url_switch_count_ + 1);
453
Jay Srinivasan08262882012-12-28 19:29:43 -0800454 // Whenever we update the URL index, we should also clear the URL failure
455 // count so we can start over fresh for the new URL.
456 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800457}
458
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800459void PayloadState::IncrementFailureCount() {
460 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800461 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800462 LOG(INFO) << "Incrementing the URL failure count";
463 SetUrlFailureCount(next_url_failure_count);
464 } else {
465 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
466 << ". Trying next available URL";
467 IncrementUrlIndex();
468 }
469}
470
Jay Srinivasan08262882012-12-28 19:29:43 -0800471void PayloadState::UpdateBackoffExpiryTime() {
472 if (response_.disable_payload_backoff) {
473 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
474 SetBackoffExpiryTime(Time());
475 return;
476 }
477
Alex Deymo820cc702013-06-28 15:43:46 -0700478 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800479 SetBackoffExpiryTime(Time());
480 return;
481 }
482
483 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700484 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800485 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700486 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700487 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800488
489 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
490 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700491 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800492
493 // The number of days is the minimum of 2 raised to (payload_attempt_number
494 // - 1) or kMaxBackoffDays.
495 num_days = min(num_days << power, kMaxBackoffDays);
496
497 // We don't want all retries to happen exactly at the same time when
498 // retrying after backoff. So add some random minutes to fuzz.
499 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
500 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
501 TimeDelta::FromMinutes(fuzz_minutes);
502 LOG(INFO) << "Incrementing the backoff expiry time by "
503 << utils::FormatTimeDelta(next_backoff_interval);
504 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
505}
506
Jay Srinivasan19409b72013-04-12 19:23:36 -0700507void PayloadState::UpdateCurrentDownloadSource() {
508 current_download_source_ = kNumDownloadSources;
509
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700510 if (using_p2p_for_downloading_) {
511 current_download_source_ = kDownloadSourceHttpPeer;
512 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700513 string current_url = candidate_urls_[GetUrlIndex()];
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700514 if (base::StartsWithASCII(current_url, "https://", false))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700515 current_download_source_ = kDownloadSourceHttpsServer;
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700516 else if (base::StartsWithASCII(current_url, "http://", false))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700517 current_download_source_ = kDownloadSourceHttpServer;
518 }
519
520 LOG(INFO) << "Current download source: "
521 << utils::ToString(current_download_source_);
522}
523
524void PayloadState::UpdateBytesDownloaded(size_t count) {
525 SetCurrentBytesDownloaded(
526 current_download_source_,
527 GetCurrentBytesDownloaded(current_download_source_) + count,
528 false);
529 SetTotalBytesDownloaded(
530 current_download_source_,
531 GetTotalBytesDownloaded(current_download_source_) + count,
532 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800533
534 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700535}
536
David Zeuthen33bae492014-02-25 16:16:18 -0800537PayloadType PayloadState::CalculatePayloadType() {
538 PayloadType payload_type;
539 OmahaRequestParams* params = system_state_->request_params();
540 if (response_.is_delta_payload) {
541 payload_type = kPayloadTypeDelta;
542 } else if (params->delta_okay()) {
543 payload_type = kPayloadTypeFull;
544 } else { // Full payload, delta was not allowed by request.
545 payload_type = kPayloadTypeForcedFull;
546 }
547 return payload_type;
548}
549
550// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
551// metrics if the attempt ends abnormally, e.g. if the update_engine
552// process crashes or the device is rebooted. See
553// http://crbug.com/357676
554void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
555 int attempt_number = GetPayloadAttemptNumber();
556
557 PayloadType payload_type = CalculatePayloadType();
558
559 int64_t payload_size = response_.size;
560
561 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
562
563 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700564 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
565 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800566 attempt_start_time_monotonic_;
567
568 int64_t payload_download_speed_bps = 0;
569 int64_t usec = duration_uptime.InMicroseconds();
570 if (usec > 0) {
571 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
572 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
573 payload_download_speed_bps = static_cast<int64_t>(bps);
574 }
575
576 DownloadSource download_source = current_download_source_;
577
578 metrics::DownloadErrorCode payload_download_error_code =
579 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700580 ErrorCode internal_error_code = ErrorCode::kSuccess;
David Zeuthen33bae492014-02-25 16:16:18 -0800581 metrics::AttemptResult attempt_result = utils::GetAttemptResult(code);
582
583 // Add additional detail to AttemptResult
584 switch (attempt_result) {
585 case metrics::AttemptResult::kPayloadDownloadError:
586 payload_download_error_code = utils::GetDownloadErrorCode(code);
587 break;
588
589 case metrics::AttemptResult::kInternalError:
590 internal_error_code = code;
591 break;
592
593 // Explicit fall-through for cases where we do not have additional
594 // detail. We avoid the default keyword to force people adding new
595 // AttemptResult values to visit this code and examine whether
596 // additional detail is needed.
597 case metrics::AttemptResult::kUpdateSucceeded:
598 case metrics::AttemptResult::kMetadataMalformed:
599 case metrics::AttemptResult::kOperationMalformed:
600 case metrics::AttemptResult::kOperationExecutionError:
601 case metrics::AttemptResult::kMetadataVerificationFailed:
602 case metrics::AttemptResult::kPayloadVerificationFailed:
603 case metrics::AttemptResult::kVerificationFailed:
604 case metrics::AttemptResult::kPostInstallFailed:
605 case metrics::AttemptResult::kAbnormalTermination:
606 case metrics::AttemptResult::kNumConstants:
607 case metrics::AttemptResult::kUnset:
608 break;
609 }
610
611 metrics::ReportUpdateAttemptMetrics(system_state_,
612 attempt_number,
613 payload_type,
614 duration,
615 duration_uptime,
616 payload_size,
617 payload_bytes_downloaded,
618 payload_download_speed_bps,
619 download_source,
620 attempt_result,
621 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700622 payload_download_error_code,
623 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800624}
625
David Zeuthen4e1d1492014-04-25 13:12:27 -0700626void PayloadState::PersistAttemptMetrics() {
627 // TODO(zeuthen): For now we only persist whether an attempt was in
628 // progress and not values/metrics related to the attempt. This
629 // means that when this happens, of all the UpdateEngine.Attempt.*
630 // metrics, only UpdateEngine.Attempt.Result is reported (with the
631 // value |kAbnormalTermination|). In the future we might want to
632 // persist more data so we can report other metrics in the
633 // UpdateEngine.Attempt.* namespace when this happens.
634 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
635}
636
637void PayloadState::ClearPersistedAttemptMetrics() {
638 prefs_->Delete(kPrefsAttemptInProgress);
639}
640
641void PayloadState::ReportAndClearPersistedAttemptMetrics() {
642 bool attempt_in_progress = false;
643 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
644 return;
645 if (!attempt_in_progress)
646 return;
647
648 metrics::ReportAbnormallyTerminatedUpdateAttemptMetrics(system_state_);
649
650 ClearPersistedAttemptMetrics();
651}
652
David Zeuthen33bae492014-02-25 16:16:18 -0800653void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700654 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800655
656 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800657 int64_t total_bytes_by_source[kNumDownloadSources];
658 int64_t successful_bytes = 0;
659 int64_t total_bytes = 0;
660 int64_t successful_mbs = 0;
661 int64_t total_mbs = 0;
662
Jay Srinivasan19409b72013-04-12 19:23:36 -0700663 for (int i = 0; i < kNumDownloadSources; i++) {
664 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800665 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700666
David Zeuthen44848602013-06-24 13:32:14 -0700667 // Only consider this download source (and send byte counts) as
668 // having been used if we downloaded a non-trivial amount of bytes
669 // (e.g. at least 1 MiB) that contributed to the final success of
670 // the update. Otherwise we're going to end up with a lot of
671 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700672
David Zeuthen33bae492014-02-25 16:16:18 -0800673 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800674 successful_bytes += bytes;
675 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700676 SetCurrentBytesDownloaded(source, 0, true);
677
David Zeuthen33bae492014-02-25 16:16:18 -0800678 bytes = GetTotalBytesDownloaded(source);
679 total_bytes_by_source[i] = bytes;
680 total_bytes += bytes;
681 total_mbs += bytes / kNumBytesInOneMiB;
682 SetTotalBytesDownloaded(source, 0, true);
683 }
684
685 int download_overhead_percentage = 0;
686 if (successful_bytes > 0) {
687 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
688 successful_bytes;
689 }
690
691 int url_switch_count = static_cast<int>(url_switch_count_);
692
693 int reboot_count = GetNumReboots();
694
695 SetNumReboots(0);
696
697 TimeDelta duration = GetUpdateDuration();
David Zeuthen33bae492014-02-25 16:16:18 -0800698
699 prefs_->Delete(kPrefsUpdateTimestampStart);
700 prefs_->Delete(kPrefsUpdateDurationUptime);
701
702 PayloadType payload_type = CalculatePayloadType();
703
704 int64_t payload_size = response_.size;
705
706 int attempt_count = GetPayloadAttemptNumber();
707
708 int updates_abandoned_count = num_responses_seen_ - 1;
709
710 metrics::ReportSuccessfulUpdateMetrics(system_state_,
711 attempt_count,
712 updates_abandoned_count,
713 payload_type,
714 payload_size,
715 total_bytes_by_source,
716 download_overhead_percentage,
717 duration,
718 reboot_count,
719 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700720}
721
722void PayloadState::UpdateNumReboots() {
723 // We only update the reboot count when the system has been detected to have
724 // been rebooted.
725 if (!system_state_->system_rebooted()) {
726 return;
727 }
728
729 SetNumReboots(GetNumReboots() + 1);
730}
731
732void PayloadState::SetNumReboots(uint32_t num_reboots) {
733 CHECK(prefs_);
734 num_reboots_ = num_reboots;
735 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
736 LOG(INFO) << "Number of Reboots during current update attempt = "
737 << num_reboots_;
738}
739
Jay Srinivasan08262882012-12-28 19:29:43 -0800740void PayloadState::ResetPersistedState() {
741 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700742 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800743 SetUrlIndex(0);
744 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700745 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700746 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700747 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700748 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700749 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700750 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700751 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700752 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700753 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700754 SetScatteringWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700755}
756
757void PayloadState::ResetRollbackVersion() {
758 CHECK(powerwash_safe_prefs_);
759 rollback_version_ = "";
760 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700761}
762
763void PayloadState::ResetDownloadSourcesOnNewUpdate() {
764 for (int i = 0; i < kNumDownloadSources; i++) {
765 DownloadSource source = static_cast<DownloadSource>(i);
766 SetCurrentBytesDownloaded(source, 0, true);
767 // Note: Not resetting the TotalBytesDownloaded as we want that metric
768 // to count the bytes downloaded across various update attempts until
769 // we have successfully applied the update.
770 }
771}
772
Chris Sosab3dcdb32013-09-04 15:22:12 -0700773int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700774 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700775 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700776 return 0;
777
778 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700779 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700780 return 0;
781
782 if (stored_value < 0) {
783 LOG(ERROR) << key << ": Invalid value (" << stored_value
784 << ") in persisted state. Defaulting to 0";
785 return 0;
786 }
787
788 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800789}
790
791string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700792 string response_sign = base::StringPrintf(
793 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800794
Jay Srinivasan53173b92013-05-17 17:13:01 -0700795 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700796 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
797 static_cast<int>(i),
798 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800799
Alex Vakulenko75039d72014-03-25 12:36:28 -0700800 response_sign += base::StringPrintf(
801 "Payload Size = %ju\n"
802 "Payload Sha256 Hash = %s\n"
803 "Metadata Size = %ju\n"
804 "Metadata Signature = %s\n"
805 "Is Delta Payload = %d\n"
806 "Max Failure Count Per Url = %d\n"
807 "Disable Payload Backoff = %d\n",
808 static_cast<uintmax_t>(response_.size),
809 response_.hash.c_str(),
810 static_cast<uintmax_t>(response_.metadata_size),
811 response_.metadata_signature.c_str(),
812 response_.is_delta_payload,
813 response_.max_failure_count_per_url,
814 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800815 return response_sign;
816}
817
818void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800819 CHECK(prefs_);
820 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800821 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
822 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
823 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800824 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800825}
826
Jay Srinivasan19409b72013-04-12 19:23:36 -0700827void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800828 CHECK(prefs_);
829 response_signature_ = response_signature;
830 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
831 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
832}
833
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800834void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700835 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800836}
837
Alex Deymo820cc702013-06-28 15:43:46 -0700838void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700839 SetFullPayloadAttemptNumber(GetPersistedValue(
840 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700841}
842
843void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800844 CHECK(prefs_);
845 payload_attempt_number_ = payload_attempt_number;
846 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
847 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
848}
849
Alex Deymo820cc702013-06-28 15:43:46 -0700850void PayloadState::SetFullPayloadAttemptNumber(
851 int full_payload_attempt_number) {
852 CHECK(prefs_);
853 full_payload_attempt_number_ = full_payload_attempt_number;
854 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
855 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
856 full_payload_attempt_number_);
857}
858
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800859void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700860 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800861}
862
863void PayloadState::SetUrlIndex(uint32_t url_index) {
864 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800865 url_index_ = url_index;
866 LOG(INFO) << "Current URL Index = " << url_index_;
867 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700868
869 // Also update the download source, which is purely dependent on the
870 // current URL index alone.
871 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800872}
873
Gilad Arnold519cfc72014-10-02 10:34:54 -0700874void PayloadState::LoadScatteringWaitPeriod() {
875 SetScatteringWaitPeriod(
876 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
877}
878
Alex Deymof329b932014-10-30 01:37:48 -0700879void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700880 CHECK(prefs_);
881 scattering_wait_period_ = wait_period;
882 LOG(INFO) << "Scattering Wait Period (seconds) = "
883 << scattering_wait_period_.InSeconds();
884 if (scattering_wait_period_.InSeconds() > 0) {
885 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
886 scattering_wait_period_.InSeconds());
887 } else {
888 prefs_->Delete(kPrefsWallClockWaitPeriod);
889 }
890}
891
David Zeuthencc6f9962013-04-18 11:57:24 -0700892void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700893 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700894}
895
896void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
897 CHECK(prefs_);
898 url_switch_count_ = url_switch_count;
899 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
900 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
901}
902
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800903void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700904 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800905}
906
907void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
908 CHECK(prefs_);
909 url_failure_count_ = url_failure_count;
910 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
911 << ")'s Failure Count = " << url_failure_count_;
912 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800913}
914
Jay Srinivasan08262882012-12-28 19:29:43 -0800915void PayloadState::LoadBackoffExpiryTime() {
916 CHECK(prefs_);
917 int64_t stored_value;
918 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
919 return;
920
921 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
922 return;
923
924 Time stored_time = Time::FromInternalValue(stored_value);
925 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
926 LOG(ERROR) << "Invalid backoff expiry time ("
927 << utils::ToString(stored_time)
928 << ") in persisted state. Resetting.";
929 stored_time = Time();
930 }
931 SetBackoffExpiryTime(stored_time);
932}
933
934void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
935 CHECK(prefs_);
936 backoff_expiry_time_ = new_time;
937 LOG(INFO) << "Backoff Expiry Time = "
938 << utils::ToString(backoff_expiry_time_);
939 prefs_->SetInt64(kPrefsBackoffExpiryTime,
940 backoff_expiry_time_.ToInternalValue());
941}
942
David Zeuthen9a017f22013-04-11 16:10:26 -0700943TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700944 Time end_time = update_timestamp_end_.is_null()
945 ? system_state_->clock()->GetWallclockTime() :
946 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700947 return end_time - update_timestamp_start_;
948}
949
950void PayloadState::LoadUpdateTimestampStart() {
951 int64_t stored_value;
952 Time stored_time;
953
954 CHECK(prefs_);
955
David Zeuthenf413fe52013-04-22 14:04:39 -0700956 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700957
958 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
959 // The preference missing is not unexpected - in that case, just
960 // use the current time as start time
961 stored_time = now;
962 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
963 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
964 stored_time = now;
965 } else {
966 stored_time = Time::FromInternalValue(stored_value);
967 }
968
969 // Sanity check: If the time read from disk is in the future
970 // (modulo some slack to account for possible NTP drift
971 // adjustments), something is fishy and we should report and
972 // reset.
973 TimeDelta duration_according_to_stored_time = now - stored_time;
974 if (duration_according_to_stored_time < -kDurationSlack) {
975 LOG(ERROR) << "The UpdateTimestampStart value ("
976 << utils::ToString(stored_time)
977 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700978 << utils::FormatTimeDelta(duration_according_to_stored_time)
979 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700980 stored_time = now;
981 }
982
983 SetUpdateTimestampStart(stored_time);
984}
985
986void PayloadState::SetUpdateTimestampStart(const Time& value) {
987 CHECK(prefs_);
988 update_timestamp_start_ = value;
989 prefs_->SetInt64(kPrefsUpdateTimestampStart,
990 update_timestamp_start_.ToInternalValue());
991 LOG(INFO) << "Update Timestamp Start = "
992 << utils::ToString(update_timestamp_start_);
993}
994
995void PayloadState::SetUpdateTimestampEnd(const Time& value) {
996 update_timestamp_end_ = value;
997 LOG(INFO) << "Update Timestamp End = "
998 << utils::ToString(update_timestamp_end_);
999}
1000
1001TimeDelta PayloadState::GetUpdateDurationUptime() {
1002 return update_duration_uptime_;
1003}
1004
1005void PayloadState::LoadUpdateDurationUptime() {
1006 int64_t stored_value;
1007 TimeDelta stored_delta;
1008
1009 CHECK(prefs_);
1010
1011 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1012 // The preference missing is not unexpected - in that case, just
1013 // we'll use zero as the delta
1014 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1015 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1016 stored_delta = TimeDelta::FromSeconds(0);
1017 } else {
1018 stored_delta = TimeDelta::FromInternalValue(stored_value);
1019 }
1020
1021 // Sanity-check: Uptime can never be greater than the wall-clock
1022 // difference (modulo some slack). If it is, report and reset
1023 // to the wall-clock difference.
1024 TimeDelta diff = GetUpdateDuration() - stored_delta;
1025 if (diff < -kDurationSlack) {
1026 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001027 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001028 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001029 << utils::FormatTimeDelta(diff)
1030 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001031 stored_delta = update_duration_current_;
1032 }
1033
1034 SetUpdateDurationUptime(stored_delta);
1035}
1036
Chris Sosabe45bef2013-04-09 18:25:12 -07001037void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001038 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001039}
1040
1041void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001042 CHECK(powerwash_safe_prefs_);
1043 string rollback_version;
1044 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1045 &rollback_version)) {
1046 SetRollbackVersion(rollback_version);
1047 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001048}
1049
1050void PayloadState::SetRollbackVersion(const string& rollback_version) {
1051 CHECK(powerwash_safe_prefs_);
1052 LOG(INFO) << "Blacklisting version "<< rollback_version;
1053 rollback_version_ = rollback_version;
1054 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001055}
1056
David Zeuthen9a017f22013-04-11 16:10:26 -07001057void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1058 const Time& timestamp,
1059 bool use_logging) {
1060 CHECK(prefs_);
1061 update_duration_uptime_ = value;
1062 update_duration_uptime_timestamp_ = timestamp;
1063 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1064 update_duration_uptime_.ToInternalValue());
1065 if (use_logging) {
1066 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001067 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001068 }
1069}
1070
1071void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001072 Time now = system_state_->clock()->GetMonotonicTime();
1073 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001074}
1075
1076void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001077 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001078 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1079 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1080 // We're frequently called so avoid logging this write
1081 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1082}
1083
Jay Srinivasan19409b72013-04-12 19:23:36 -07001084string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1085 return prefix + "-from-" + utils::ToString(source);
1086}
1087
1088void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1089 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001090 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001091}
1092
1093void PayloadState::SetCurrentBytesDownloaded(
1094 DownloadSource source,
1095 uint64_t current_bytes_downloaded,
1096 bool log) {
1097 CHECK(prefs_);
1098
1099 if (source >= kNumDownloadSources)
1100 return;
1101
1102 // Update the in-memory value.
1103 current_bytes_downloaded_[source] = current_bytes_downloaded;
1104
1105 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1106 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1107 LOG_IF(INFO, log) << "Current bytes downloaded for "
1108 << utils::ToString(source) << " = "
1109 << GetCurrentBytesDownloaded(source);
1110}
1111
1112void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1113 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001114 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001115}
1116
1117void PayloadState::SetTotalBytesDownloaded(
1118 DownloadSource source,
1119 uint64_t total_bytes_downloaded,
1120 bool log) {
1121 CHECK(prefs_);
1122
1123 if (source >= kNumDownloadSources)
1124 return;
1125
1126 // Update the in-memory value.
1127 total_bytes_downloaded_[source] = total_bytes_downloaded;
1128
1129 // Persist.
1130 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1131 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1132 LOG_IF(INFO, log) << "Total bytes downloaded for "
1133 << utils::ToString(source) << " = "
1134 << GetTotalBytesDownloaded(source);
1135}
1136
David Zeuthena573d6f2013-06-14 16:13:36 -07001137void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001138 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001139}
1140
1141void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1142 CHECK(prefs_);
1143 num_responses_seen_ = num_responses_seen;
1144 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1145 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1146}
1147
Jay Srinivasan53173b92013-05-17 17:13:01 -07001148void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001149 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001150
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001151 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001152 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001153 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001154 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1155 } else {
1156 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1157 http_url_ok = true;
1158 }
1159
1160 candidate_urls_.clear();
1161 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1162 string candidate_url = response_.payload_urls[i];
Alex Vakulenko6a9d3492015-06-15 12:53:22 -07001163 if (base::StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1164 continue;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001165 candidate_urls_.push_back(candidate_url);
1166 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1167 << ": " << candidate_url;
1168 }
1169
1170 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1171 << "out of " << response_.payload_urls.size() << " URLs supplied";
1172}
1173
David Zeuthene4c58bf2013-06-18 17:26:50 -07001174void PayloadState::CreateSystemUpdatedMarkerFile() {
1175 CHECK(prefs_);
1176 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1177 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1178}
1179
1180void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1181 // Send |time_to_reboot| as a UMA stat.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001182 string metric = metrics::kMetricTimeToRebootMinutes;
David Zeuthen33bae492014-02-25 16:16:18 -08001183 system_state_->metrics_lib()->SendToUMA(metric,
1184 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001185 0, // min: 0 minute
1186 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001187 kNumDefaultUmaBuckets);
1188 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1189 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001190}
1191
1192void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001193 // Flush previous state from abnormal attempt failure, if any.
1194 ReportAndClearPersistedAttemptMetrics();
1195
Alex Deymo569c4242013-07-24 12:01:01 -07001196 // Avoid the UpdateEngineStarted actions if this is not the first time we
1197 // run the update engine since reboot.
1198 if (!system_state_->system_rebooted())
1199 return;
1200
David Zeuthene4c58bf2013-06-18 17:26:50 -07001201 // Figure out if we just booted into a new update
1202 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1203 int64_t stored_value;
1204 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1205 Time system_updated_at = Time::FromInternalValue(stored_value);
1206 if (!system_updated_at.is_null()) {
1207 TimeDelta time_to_reboot =
1208 system_state_->clock()->GetWallclockTime() - system_updated_at;
1209 if (time_to_reboot.ToInternalValue() < 0) {
1210 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1211 << utils::ToString(system_updated_at);
1212 } else {
1213 BootedIntoUpdate(time_to_reboot);
1214 }
1215 }
1216 }
1217 prefs_->Delete(kPrefsSystemUpdatedMarker);
1218 }
Alex Deymo42432912013-07-12 20:21:15 -07001219 // Check if it is needed to send metrics about a failed reboot into a new
1220 // version.
1221 ReportFailedBootIfNeeded();
1222}
1223
1224void PayloadState::ReportFailedBootIfNeeded() {
1225 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1226 // payload was marked as ready immediately before the last reboot, and we
1227 // need to check if such payload successfully rebooted or not.
1228 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001229 int64_t installed_from = 0;
1230 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001231 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1232 return;
1233 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001234 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1235 // partition number. We are now using slot numbers (0 or 1) instead, so
1236 // the following comparison will not match if we are comparing an old
1237 // partition number against a new slot number, which is the correct outcome
1238 // since we successfully booted the new update in that case. If the boot
1239 // failed, we will read this value from the same version, so it will always
1240 // be compatible.
1241 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001242 // A reboot was pending, but the chromebook is again in the same
1243 // BootDevice where the update was installed from.
1244 int64_t target_attempt;
1245 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1246 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1247 "TargetVersionInstalledFrom was present.";
1248 target_attempt = 1;
1249 }
1250
1251 // Report the UMA metric of the current boot failure.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001252 string metric = metrics::kMetricFailedUpdateCount;
David Zeuthen33bae492014-02-25 16:16:18 -08001253 LOG(INFO) << "Uploading " << target_attempt
1254 << " (count) for metric " << metric;
1255 system_state_->metrics_lib()->SendToUMA(
1256 metric,
1257 target_attempt,
1258 1, // min value
1259 50, // max value
1260 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001261 } else {
1262 prefs_->Delete(kPrefsTargetVersionAttempt);
1263 prefs_->Delete(kPrefsTargetVersionUniqueId);
1264 }
1265 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1266 }
1267}
1268
1269void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1270 // Expect to boot into the new partition in the next reboot setting the
1271 // TargetVersion* flags in the Prefs.
1272 string stored_target_version_uid;
1273 string target_version_id;
1274 string target_partition;
1275 int64_t target_attempt;
1276
1277 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1278 prefs_->GetString(kPrefsTargetVersionUniqueId,
1279 &stored_target_version_uid) &&
1280 stored_target_version_uid == target_version_uid) {
1281 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1282 target_attempt = 0;
1283 } else {
1284 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1285 target_attempt = 0;
1286 }
1287 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1288
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001289 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001290 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001291}
1292
1293void PayloadState::ResetUpdateStatus() {
1294 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1295 // rebooted the next boot is not flagged as failed to rebooted into the
1296 // new applied payload.
1297 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1298
1299 // Also decrement the attempt number if it exists.
1300 int64_t target_attempt;
1301 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001302 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001303}
1304
David Zeuthendcba8092013-08-06 12:16:35 -07001305int PayloadState::GetP2PNumAttempts() {
1306 return p2p_num_attempts_;
1307}
1308
1309void PayloadState::SetP2PNumAttempts(int value) {
1310 p2p_num_attempts_ = value;
1311 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1312 CHECK(prefs_);
1313 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1314}
1315
1316void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001317 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001318}
1319
1320Time PayloadState::GetP2PFirstAttemptTimestamp() {
1321 return p2p_first_attempt_timestamp_;
1322}
1323
1324void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1325 p2p_first_attempt_timestamp_ = time;
1326 LOG(INFO) << "p2p First Attempt Timestamp = "
1327 << utils::ToString(p2p_first_attempt_timestamp_);
1328 CHECK(prefs_);
1329 int64_t stored_value = time.ToInternalValue();
1330 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1331}
1332
1333void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001334 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001335 Time stored_time = Time::FromInternalValue(stored_value);
1336 SetP2PFirstAttemptTimestamp(stored_time);
1337}
1338
1339void PayloadState::P2PNewAttempt() {
1340 CHECK(prefs_);
1341 // Set timestamp, if it hasn't been set already
1342 if (p2p_first_attempt_timestamp_.is_null()) {
1343 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1344 }
1345 // Increase number of attempts
1346 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1347}
1348
1349bool PayloadState::P2PAttemptAllowed() {
1350 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1351 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1352 << " which is greater than "
1353 << kMaxP2PAttempts
1354 << " - disallowing p2p.";
1355 return false;
1356 }
1357
1358 if (!p2p_first_attempt_timestamp_.is_null()) {
1359 Time now = system_state_->clock()->GetWallclockTime();
1360 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1361 if (time_spent_attempting_p2p.InSeconds() < 0) {
1362 LOG(ERROR) << "Time spent attempting p2p is negative"
1363 << " - disallowing p2p.";
1364 return false;
1365 }
1366 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1367 LOG(INFO) << "Time spent attempting p2p is "
1368 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1369 << " which is greater than "
1370 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1371 kMaxP2PAttemptTimeSeconds))
1372 << " - disallowing p2p.";
1373 return false;
1374 }
1375 }
1376
1377 return true;
1378}
1379
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001380} // namespace chromeos_update_engine