blob: 6b7b0fb7df50d21f9df0c69dfbb08daedbe15141 [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"
Alex Deymo38429cf2015-11-11 18:27:22 -080032#include "update_engine/metrics_utils.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070033#include "update_engine/omaha_request_params.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080034#include "update_engine/payload_consumer/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070035#include "update_engine/system_state.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080036
Jay Srinivasan08262882012-12-28 19:29:43 -080037using base::Time;
38using base::TimeDelta;
39using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080040using std::string;
41
42namespace chromeos_update_engine {
43
David Zeuthen9a017f22013-04-11 16:10:26 -070044const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
45
Jay Srinivasan08262882012-12-28 19:29:43 -080046// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070047static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080048
Jay Srinivasan08262882012-12-28 19:29:43 -080049// We want to randomize retry attempts after the backoff by +/- 6 hours.
50static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080051
Jay Srinivasan19409b72013-04-12 19:23:36 -070052PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070053 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070054 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070055 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070056 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070057 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070058 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070059 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070060 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070061 attempt_num_bytes_downloaded_(0),
62 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070063 attempt_type_(AttemptType::kUpdate) {
64 for (int i = 0; i <= kNumDownloadSources; i++)
65 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070066}
67
68bool PayloadState::Initialize(SystemState* system_state) {
69 system_state_ = system_state;
70 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070071 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080072 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080073 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070074 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080075 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080076 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070077 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080078 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070079 LoadUpdateTimestampStart();
80 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
81 // being called before it. Don't reorder.
82 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070083 for (int i = 0; i < kNumDownloadSources; i++) {
84 DownloadSource source = static_cast<DownloadSource>(i);
85 LoadCurrentBytesDownloaded(source);
86 LoadTotalBytesDownloaded(source);
87 }
Chris Sosabe45bef2013-04-09 18:25:12 -070088 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070089 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070090 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070091 LoadP2PFirstAttemptTimestamp();
92 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080093 return true;
94}
95
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080096void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080097 // Always store the latest response.
98 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080099
Jay Srinivasan53173b92013-05-17 17:13:01 -0700100 // Compute the candidate URLs first as they are used to calculate the
101 // response signature so that a change in enterprise policy for
102 // HTTP downloads being enabled or not could be honored as soon as the
103 // next update check happens.
104 ComputeCandidateUrls();
105
Jay Srinivasan08262882012-12-28 19:29:43 -0800106 // Check if the "signature" of this response (i.e. the fields we care about)
107 // has changed.
108 string new_response_signature = CalculateResponseSignature();
109 bool has_response_changed = (response_signature_ != new_response_signature);
110
111 // If the response has changed, we should persist the new signature and
112 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800113 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800114 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700115 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800116 SetResponseSignature(new_response_signature);
117 ResetPersistedState();
118 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800119 }
120
Jay Srinivasan08262882012-12-28 19:29:43 -0800121 // This is the earliest point at which we can validate whether the URL index
122 // we loaded from the persisted state is a valid value. If the response
123 // hasn't changed but the URL index is invalid, it's indicative of some
124 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700125 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800126 LOG(INFO) << "Resetting all payload state as the url index seems to have "
127 "been tampered with";
128 ResetPersistedState();
129 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800130 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700131
132 // Update the current download source which depends on the latest value of
133 // the response.
134 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800135}
136
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700137void PayloadState::SetUsingP2PForDownloading(bool value) {
138 using_p2p_for_downloading_ = value;
139 // Update the current download source which depends on whether we are
140 // using p2p or not.
141 UpdateCurrentDownloadSource();
142}
143
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800144void PayloadState::DownloadComplete() {
145 LOG(INFO) << "Payload downloaded successfully";
146 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700147 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800148}
149
150void PayloadState::DownloadProgress(size_t count) {
151 if (count == 0)
152 return;
153
David Zeuthen9a017f22013-04-11 16:10:26 -0700154 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700155 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700156
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800157 // We've received non-zero bytes from a recent download operation. Since our
158 // URL failure count is meant to penalize a URL only for consecutive
159 // failures, downloading bytes successfully means we should reset the failure
160 // count (as we know at least that the URL is working). In future, we can
161 // design this to be more sophisticated to check for more intelligent failure
162 // patterns, but right now, even 1 byte downloaded will mark the URL to be
163 // good unless it hits 10 (or configured number of) consecutive failures
164 // again.
165
166 if (GetUrlFailureCount() == 0)
167 return;
168
169 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
170 << " to 0 as we received " << count << " bytes successfully";
171 SetUrlFailureCount(0);
172}
173
David Zeuthenafed4a12014-04-09 15:28:44 -0700174void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700175 // Flush previous state from abnormal attempt failure, if any.
176 ReportAndClearPersistedAttemptMetrics();
177
David Zeuthenafed4a12014-04-09 15:28:44 -0700178 attempt_type_ = attempt_type;
179
David Zeuthen33bae492014-02-25 16:16:18 -0800180 ClockInterface *clock = system_state_->clock();
181 attempt_start_time_boot_ = clock->GetBootTime();
182 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800183 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700184
185 metrics::ConnectionType type;
186 NetworkConnectionType network_connection_type;
187 NetworkTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700188 ConnectionManagerInterface* connection_manager =
189 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700190 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700191 &tethering)) {
192 LOG(ERROR) << "Failed to determine connection type.";
193 type = metrics::ConnectionType::kUnknown;
194 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800195 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700196 }
197 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700198
199 if (attempt_type == AttemptType::kUpdate)
200 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800201}
202
Chris Sosabe45bef2013-04-09 18:25:12 -0700203void PayloadState::UpdateResumed() {
204 LOG(INFO) << "Resuming an update that was previously started.";
205 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700206 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700207}
208
Jay Srinivasan19409b72013-04-12 19:23:36 -0700209void PayloadState::UpdateRestarted() {
210 LOG(INFO) << "Starting a new update";
211 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700212 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700213 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700214}
215
David Zeuthen9a017f22013-04-11 16:10:26 -0700216void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700217 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700218 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700219 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800220
David Zeuthen96197df2014-04-16 12:22:39 -0700221 switch (attempt_type_) {
222 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700223 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700224 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700225 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700226 break;
227
228 case AttemptType::kRollback:
229 metrics::ReportRollbackMetrics(system_state_,
230 metrics::RollbackResult::kSuccess);
231 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700232 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700233
234 // Reset the number of responses seen since it counts from the last
235 // successful update, e.g. now.
236 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700237
238 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700239}
240
David Zeuthena99981f2013-04-29 13:42:47 -0700241void PayloadState::UpdateFailed(ErrorCode error) {
242 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800243 LOG(INFO) << "Updating payload state for error code: " << base_error
244 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800245
Jay Srinivasan53173b92013-05-17 17:13:01 -0700246 if (candidate_urls_.size() == 0) {
247 // This means we got this error even before we got a valid Omaha response
248 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800249 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800250 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
251 return;
252 }
253
David Zeuthen96197df2014-04-16 12:22:39 -0700254 switch (attempt_type_) {
255 case AttemptType::kUpdate:
256 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700257 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700258 break;
259
260 case AttemptType::kRollback:
261 metrics::ReportRollbackMetrics(system_state_,
262 metrics::RollbackResult::kFailed);
263 break;
264 }
David Zeuthen33bae492014-02-25 16:16:18 -0800265
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800266 switch (base_error) {
267 // Errors which are good indicators of a problem with a particular URL or
268 // the protocol used in the URL or entities in the communication channel
269 // (e.g. proxies). We should try the next available URL in the next update
270 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700271 case ErrorCode::kPayloadHashMismatchError:
272 case ErrorCode::kPayloadSizeMismatchError:
273 case ErrorCode::kDownloadPayloadVerificationError:
274 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
275 case ErrorCode::kSignedDeltaPayloadExpectedError:
276 case ErrorCode::kDownloadInvalidMetadataMagicString:
277 case ErrorCode::kDownloadSignatureMissingInManifest:
278 case ErrorCode::kDownloadManifestParseError:
279 case ErrorCode::kDownloadMetadataSignatureError:
280 case ErrorCode::kDownloadMetadataSignatureVerificationError:
281 case ErrorCode::kDownloadMetadataSignatureMismatch:
282 case ErrorCode::kDownloadOperationHashVerificationError:
283 case ErrorCode::kDownloadOperationExecutionError:
284 case ErrorCode::kDownloadOperationHashMismatch:
285 case ErrorCode::kDownloadInvalidMetadataSize:
286 case ErrorCode::kDownloadInvalidMetadataSignature:
287 case ErrorCode::kDownloadOperationHashMissingError:
288 case ErrorCode::kDownloadMetadataSignatureMissingError:
289 case ErrorCode::kPayloadMismatchedType:
290 case ErrorCode::kUnsupportedMajorPayloadVersion:
291 case ErrorCode::kUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800292 IncrementUrlIndex();
293 break;
294
295 // Errors which seem to be just transient network/communication related
296 // failures and do not indicate any inherent problem with the URL itself.
297 // So, we should keep the current URL but just increment the
298 // failure count to give it more chances. This way, while we maximize our
299 // chances of downloading from the URLs that appear earlier in the response
300 // (because download from a local server URL that appears earlier in a
301 // response is preferable than downloading from the next URL which could be
302 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700303
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700304 case ErrorCode::kError:
305 case ErrorCode::kDownloadTransferError:
306 case ErrorCode::kDownloadWriteError:
307 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700308 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800309 IncrementFailureCount();
310 break;
311
312 // Errors which are not specific to a URL and hence shouldn't result in
313 // the URL being penalized. This can happen in two cases:
314 // 1. We haven't started downloading anything: These errors don't cost us
315 // anything in terms of actual payload bytes, so we should just do the
316 // regular retries at the next update check.
317 // 2. We have successfully downloaded the payload: In this case, the
318 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800319 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800320 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700321 case ErrorCode::kOmahaRequestError:
322 case ErrorCode::kOmahaResponseHandlerError:
323 case ErrorCode::kPostinstallRunnerError:
324 case ErrorCode::kFilesystemCopierError:
325 case ErrorCode::kInstallDeviceOpenError:
326 case ErrorCode::kKernelDeviceOpenError:
327 case ErrorCode::kDownloadNewPartitionInfoError:
328 case ErrorCode::kNewRootfsVerificationError:
329 case ErrorCode::kNewKernelVerificationError:
330 case ErrorCode::kPostinstallBootedFromFirmwareB:
331 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
332 case ErrorCode::kOmahaRequestEmptyResponseError:
333 case ErrorCode::kOmahaRequestXMLParseError:
334 case ErrorCode::kOmahaResponseInvalid:
335 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
336 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
337 case ErrorCode::kOmahaUpdateDeferredForBackoff:
338 case ErrorCode::kPostinstallPowerwashError:
339 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400340 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700341 case ErrorCode::kFilesystemVerifierError:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800342 LOG(INFO) << "Not incrementing URL index or failure count for this error";
343 break;
344
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700345 case ErrorCode::kSuccess: // success code
346 case ErrorCode::kUmaReportedMax: // not an error code
347 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
348 case ErrorCode::kDevModeFlag: // not an error code
349 case ErrorCode::kResumedFlag: // not an error code
350 case ErrorCode::kTestImageFlag: // not an error code
351 case ErrorCode::kTestOmahaUrlFlag: // not an error code
352 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800353 // These shouldn't happen. Enumerating these explicitly here so that we
354 // can let the compiler warn about new error codes that are added to
355 // action_processor.h but not added here.
356 LOG(WARNING) << "Unexpected error code for UpdateFailed";
357 break;
358
359 // Note: Not adding a default here so as to let the compiler warn us of
360 // any new enums that were added in the .h but not listed in this switch.
361 }
362}
363
Jay Srinivasan08262882012-12-28 19:29:43 -0800364bool PayloadState::ShouldBackoffDownload() {
365 if (response_.disable_payload_backoff) {
366 LOG(INFO) << "Payload backoff logic is disabled. "
367 "Can proceed with the download";
368 return false;
369 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700370 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700371 LOG(INFO) << "Payload backoff logic is disabled because download "
372 << "will happen from local peer (via p2p).";
373 return false;
374 }
375 if (system_state_->request_params()->interactive()) {
376 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
377 return false;
378 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800379 if (response_.is_delta_payload) {
380 // If delta payloads fail, we want to fallback quickly to full payloads as
381 // they are more likely to succeed. Exponential backoffs would greatly
382 // slow down the fallback to full payloads. So we don't backoff for delta
383 // payloads.
384 LOG(INFO) << "No backoffs for delta payloads. "
385 << "Can proceed with the download";
386 return false;
387 }
388
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700389 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800390 // Backoffs are needed only for official builds. We do not want any delays
391 // or update failures due to backoffs during testing or development.
392 LOG(INFO) << "No backoffs for test/dev images. "
393 << "Can proceed with the download";
394 return false;
395 }
396
397 if (backoff_expiry_time_.is_null()) {
398 LOG(INFO) << "No backoff expiry time has been set. "
399 << "Can proceed with the download";
400 return false;
401 }
402
403 if (backoff_expiry_time_ < Time::Now()) {
404 LOG(INFO) << "The backoff expiry time ("
405 << utils::ToString(backoff_expiry_time_)
406 << ") has elapsed. Can proceed with the download";
407 return false;
408 }
409
410 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
411 << utils::ToString(backoff_expiry_time_);
412 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800413}
414
Chris Sosaaa18e162013-06-20 13:20:30 -0700415void PayloadState::Rollback() {
416 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700417 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700418}
419
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800420void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700421 // Update the payload attempt number for both payload types: full and delta.
422 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
423}
424
425void PayloadState::IncrementFullPayloadAttemptNumber() {
426 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800427 if (response_.is_delta_payload) {
428 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
429 return;
430 }
431
Alex Deymo29b51d92013-07-09 15:26:24 -0700432 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700433 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800434 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800435}
436
437void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800438 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700439 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800440 LOG(INFO) << "Incrementing the URL index for next attempt";
441 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800442 } else {
443 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700444 << "0 as we only have " << candidate_urls_.size()
445 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800446 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700447 IncrementPayloadAttemptNumber();
448 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800449 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800450
David Zeuthencc6f9962013-04-18 11:57:24 -0700451 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700452 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700453 SetUrlSwitchCount(url_switch_count_ + 1);
454
Jay Srinivasan08262882012-12-28 19:29:43 -0800455 // Whenever we update the URL index, we should also clear the URL failure
456 // count so we can start over fresh for the new URL.
457 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800458}
459
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800460void PayloadState::IncrementFailureCount() {
461 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800462 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800463 LOG(INFO) << "Incrementing the URL failure count";
464 SetUrlFailureCount(next_url_failure_count);
465 } else {
466 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
467 << ". Trying next available URL";
468 IncrementUrlIndex();
469 }
470}
471
Jay Srinivasan08262882012-12-28 19:29:43 -0800472void PayloadState::UpdateBackoffExpiryTime() {
473 if (response_.disable_payload_backoff) {
474 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
475 SetBackoffExpiryTime(Time());
476 return;
477 }
478
Alex Deymo820cc702013-06-28 15:43:46 -0700479 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800480 SetBackoffExpiryTime(Time());
481 return;
482 }
483
484 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700485 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800486 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700487 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700488 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800489
490 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
491 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700492 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800493
494 // The number of days is the minimum of 2 raised to (payload_attempt_number
495 // - 1) or kMaxBackoffDays.
496 num_days = min(num_days << power, kMaxBackoffDays);
497
498 // We don't want all retries to happen exactly at the same time when
499 // retrying after backoff. So add some random minutes to fuzz.
500 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
501 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
502 TimeDelta::FromMinutes(fuzz_minutes);
503 LOG(INFO) << "Incrementing the backoff expiry time by "
504 << utils::FormatTimeDelta(next_backoff_interval);
505 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
506}
507
Jay Srinivasan19409b72013-04-12 19:23:36 -0700508void PayloadState::UpdateCurrentDownloadSource() {
509 current_download_source_ = kNumDownloadSources;
510
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700511 if (using_p2p_for_downloading_) {
512 current_download_source_ = kDownloadSourceHttpPeer;
513 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700514 string current_url = candidate_urls_[GetUrlIndex()];
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700515 if (base::StartsWithASCII(current_url, "https://", false))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700516 current_download_source_ = kDownloadSourceHttpsServer;
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700517 else if (base::StartsWithASCII(current_url, "http://", false))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700518 current_download_source_ = kDownloadSourceHttpServer;
519 }
520
521 LOG(INFO) << "Current download source: "
522 << utils::ToString(current_download_source_);
523}
524
525void PayloadState::UpdateBytesDownloaded(size_t count) {
526 SetCurrentBytesDownloaded(
527 current_download_source_,
528 GetCurrentBytesDownloaded(current_download_source_) + count,
529 false);
530 SetTotalBytesDownloaded(
531 current_download_source_,
532 GetTotalBytesDownloaded(current_download_source_) + count,
533 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800534
535 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700536}
537
David Zeuthen33bae492014-02-25 16:16:18 -0800538PayloadType PayloadState::CalculatePayloadType() {
539 PayloadType payload_type;
540 OmahaRequestParams* params = system_state_->request_params();
541 if (response_.is_delta_payload) {
542 payload_type = kPayloadTypeDelta;
543 } else if (params->delta_okay()) {
544 payload_type = kPayloadTypeFull;
545 } else { // Full payload, delta was not allowed by request.
546 payload_type = kPayloadTypeForcedFull;
547 }
548 return payload_type;
549}
550
551// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
552// metrics if the attempt ends abnormally, e.g. if the update_engine
553// process crashes or the device is rebooted. See
554// http://crbug.com/357676
555void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
556 int attempt_number = GetPayloadAttemptNumber();
557
558 PayloadType payload_type = CalculatePayloadType();
559
560 int64_t payload_size = response_.size;
561
562 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
563
564 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700565 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
566 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800567 attempt_start_time_monotonic_;
568
569 int64_t payload_download_speed_bps = 0;
570 int64_t usec = duration_uptime.InMicroseconds();
571 if (usec > 0) {
572 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
573 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
574 payload_download_speed_bps = static_cast<int64_t>(bps);
575 }
576
577 DownloadSource download_source = current_download_source_;
578
579 metrics::DownloadErrorCode payload_download_error_code =
580 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700581 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800582 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800583
584 // Add additional detail to AttemptResult
585 switch (attempt_result) {
586 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800587 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800588 break;
589
590 case metrics::AttemptResult::kInternalError:
591 internal_error_code = code;
592 break;
593
594 // Explicit fall-through for cases where we do not have additional
595 // detail. We avoid the default keyword to force people adding new
596 // AttemptResult values to visit this code and examine whether
597 // additional detail is needed.
598 case metrics::AttemptResult::kUpdateSucceeded:
599 case metrics::AttemptResult::kMetadataMalformed:
600 case metrics::AttemptResult::kOperationMalformed:
601 case metrics::AttemptResult::kOperationExecutionError:
602 case metrics::AttemptResult::kMetadataVerificationFailed:
603 case metrics::AttemptResult::kPayloadVerificationFailed:
604 case metrics::AttemptResult::kVerificationFailed:
605 case metrics::AttemptResult::kPostInstallFailed:
606 case metrics::AttemptResult::kAbnormalTermination:
607 case metrics::AttemptResult::kNumConstants:
608 case metrics::AttemptResult::kUnset:
609 break;
610 }
611
612 metrics::ReportUpdateAttemptMetrics(system_state_,
613 attempt_number,
614 payload_type,
615 duration,
616 duration_uptime,
617 payload_size,
618 payload_bytes_downloaded,
619 payload_download_speed_bps,
620 download_source,
621 attempt_result,
622 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700623 payload_download_error_code,
624 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800625}
626
David Zeuthen4e1d1492014-04-25 13:12:27 -0700627void PayloadState::PersistAttemptMetrics() {
628 // TODO(zeuthen): For now we only persist whether an attempt was in
629 // progress and not values/metrics related to the attempt. This
630 // means that when this happens, of all the UpdateEngine.Attempt.*
631 // metrics, only UpdateEngine.Attempt.Result is reported (with the
632 // value |kAbnormalTermination|). In the future we might want to
633 // persist more data so we can report other metrics in the
634 // UpdateEngine.Attempt.* namespace when this happens.
635 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
636}
637
638void PayloadState::ClearPersistedAttemptMetrics() {
639 prefs_->Delete(kPrefsAttemptInProgress);
640}
641
642void PayloadState::ReportAndClearPersistedAttemptMetrics() {
643 bool attempt_in_progress = false;
644 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
645 return;
646 if (!attempt_in_progress)
647 return;
648
649 metrics::ReportAbnormallyTerminatedUpdateAttemptMetrics(system_state_);
650
651 ClearPersistedAttemptMetrics();
652}
653
David Zeuthen33bae492014-02-25 16:16:18 -0800654void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700655 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800656
657 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800658 int64_t total_bytes_by_source[kNumDownloadSources];
659 int64_t successful_bytes = 0;
660 int64_t total_bytes = 0;
661 int64_t successful_mbs = 0;
662 int64_t total_mbs = 0;
663
Jay Srinivasan19409b72013-04-12 19:23:36 -0700664 for (int i = 0; i < kNumDownloadSources; i++) {
665 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800666 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700667
David Zeuthen44848602013-06-24 13:32:14 -0700668 // Only consider this download source (and send byte counts) as
669 // having been used if we downloaded a non-trivial amount of bytes
670 // (e.g. at least 1 MiB) that contributed to the final success of
671 // the update. Otherwise we're going to end up with a lot of
672 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700673
David Zeuthen33bae492014-02-25 16:16:18 -0800674 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800675 successful_bytes += bytes;
676 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700677 SetCurrentBytesDownloaded(source, 0, true);
678
David Zeuthen33bae492014-02-25 16:16:18 -0800679 bytes = GetTotalBytesDownloaded(source);
680 total_bytes_by_source[i] = bytes;
681 total_bytes += bytes;
682 total_mbs += bytes / kNumBytesInOneMiB;
683 SetTotalBytesDownloaded(source, 0, true);
684 }
685
686 int download_overhead_percentage = 0;
687 if (successful_bytes > 0) {
688 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
689 successful_bytes;
690 }
691
692 int url_switch_count = static_cast<int>(url_switch_count_);
693
694 int reboot_count = GetNumReboots();
695
696 SetNumReboots(0);
697
698 TimeDelta duration = GetUpdateDuration();
David Zeuthen33bae492014-02-25 16:16:18 -0800699
700 prefs_->Delete(kPrefsUpdateTimestampStart);
701 prefs_->Delete(kPrefsUpdateDurationUptime);
702
703 PayloadType payload_type = CalculatePayloadType();
704
705 int64_t payload_size = response_.size;
706
707 int attempt_count = GetPayloadAttemptNumber();
708
709 int updates_abandoned_count = num_responses_seen_ - 1;
710
711 metrics::ReportSuccessfulUpdateMetrics(system_state_,
712 attempt_count,
713 updates_abandoned_count,
714 payload_type,
715 payload_size,
716 total_bytes_by_source,
717 download_overhead_percentage,
718 duration,
719 reboot_count,
720 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700721}
722
723void PayloadState::UpdateNumReboots() {
724 // We only update the reboot count when the system has been detected to have
725 // been rebooted.
726 if (!system_state_->system_rebooted()) {
727 return;
728 }
729
730 SetNumReboots(GetNumReboots() + 1);
731}
732
733void PayloadState::SetNumReboots(uint32_t num_reboots) {
734 CHECK(prefs_);
735 num_reboots_ = num_reboots;
736 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
737 LOG(INFO) << "Number of Reboots during current update attempt = "
738 << num_reboots_;
739}
740
Jay Srinivasan08262882012-12-28 19:29:43 -0800741void PayloadState::ResetPersistedState() {
742 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700743 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800744 SetUrlIndex(0);
745 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700746 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700747 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700748 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700749 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700750 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700751 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700752 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700753 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700754 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700755 SetScatteringWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700756}
757
758void PayloadState::ResetRollbackVersion() {
759 CHECK(powerwash_safe_prefs_);
760 rollback_version_ = "";
761 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700762}
763
764void PayloadState::ResetDownloadSourcesOnNewUpdate() {
765 for (int i = 0; i < kNumDownloadSources; i++) {
766 DownloadSource source = static_cast<DownloadSource>(i);
767 SetCurrentBytesDownloaded(source, 0, true);
768 // Note: Not resetting the TotalBytesDownloaded as we want that metric
769 // to count the bytes downloaded across various update attempts until
770 // we have successfully applied the update.
771 }
772}
773
Chris Sosab3dcdb32013-09-04 15:22:12 -0700774int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700775 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700776 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700777 return 0;
778
779 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700780 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700781 return 0;
782
783 if (stored_value < 0) {
784 LOG(ERROR) << key << ": Invalid value (" << stored_value
785 << ") in persisted state. Defaulting to 0";
786 return 0;
787 }
788
789 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800790}
791
792string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700793 string response_sign = base::StringPrintf(
794 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800795
Jay Srinivasan53173b92013-05-17 17:13:01 -0700796 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700797 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
798 static_cast<int>(i),
799 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800800
Alex Vakulenko75039d72014-03-25 12:36:28 -0700801 response_sign += base::StringPrintf(
802 "Payload Size = %ju\n"
803 "Payload Sha256 Hash = %s\n"
804 "Metadata Size = %ju\n"
805 "Metadata Signature = %s\n"
806 "Is Delta Payload = %d\n"
807 "Max Failure Count Per Url = %d\n"
808 "Disable Payload Backoff = %d\n",
809 static_cast<uintmax_t>(response_.size),
810 response_.hash.c_str(),
811 static_cast<uintmax_t>(response_.metadata_size),
812 response_.metadata_signature.c_str(),
813 response_.is_delta_payload,
814 response_.max_failure_count_per_url,
815 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800816 return response_sign;
817}
818
819void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800820 CHECK(prefs_);
821 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800822 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
823 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
824 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800825 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800826}
827
Jay Srinivasan19409b72013-04-12 19:23:36 -0700828void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800829 CHECK(prefs_);
830 response_signature_ = response_signature;
831 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
832 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
833}
834
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800835void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700836 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800837}
838
Alex Deymo820cc702013-06-28 15:43:46 -0700839void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700840 SetFullPayloadAttemptNumber(GetPersistedValue(
841 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700842}
843
844void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800845 CHECK(prefs_);
846 payload_attempt_number_ = payload_attempt_number;
847 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
848 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
849}
850
Alex Deymo820cc702013-06-28 15:43:46 -0700851void PayloadState::SetFullPayloadAttemptNumber(
852 int full_payload_attempt_number) {
853 CHECK(prefs_);
854 full_payload_attempt_number_ = full_payload_attempt_number;
855 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
856 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
857 full_payload_attempt_number_);
858}
859
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800860void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700861 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800862}
863
864void PayloadState::SetUrlIndex(uint32_t url_index) {
865 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800866 url_index_ = url_index;
867 LOG(INFO) << "Current URL Index = " << url_index_;
868 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700869
870 // Also update the download source, which is purely dependent on the
871 // current URL index alone.
872 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800873}
874
Gilad Arnold519cfc72014-10-02 10:34:54 -0700875void PayloadState::LoadScatteringWaitPeriod() {
876 SetScatteringWaitPeriod(
877 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
878}
879
Alex Deymof329b932014-10-30 01:37:48 -0700880void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700881 CHECK(prefs_);
882 scattering_wait_period_ = wait_period;
883 LOG(INFO) << "Scattering Wait Period (seconds) = "
884 << scattering_wait_period_.InSeconds();
885 if (scattering_wait_period_.InSeconds() > 0) {
886 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
887 scattering_wait_period_.InSeconds());
888 } else {
889 prefs_->Delete(kPrefsWallClockWaitPeriod);
890 }
891}
892
David Zeuthencc6f9962013-04-18 11:57:24 -0700893void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700894 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700895}
896
897void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
898 CHECK(prefs_);
899 url_switch_count_ = url_switch_count;
900 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
901 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
902}
903
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800904void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700905 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800906}
907
908void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
909 CHECK(prefs_);
910 url_failure_count_ = url_failure_count;
911 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
912 << ")'s Failure Count = " << url_failure_count_;
913 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800914}
915
Jay Srinivasan08262882012-12-28 19:29:43 -0800916void PayloadState::LoadBackoffExpiryTime() {
917 CHECK(prefs_);
918 int64_t stored_value;
919 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
920 return;
921
922 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
923 return;
924
925 Time stored_time = Time::FromInternalValue(stored_value);
926 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
927 LOG(ERROR) << "Invalid backoff expiry time ("
928 << utils::ToString(stored_time)
929 << ") in persisted state. Resetting.";
930 stored_time = Time();
931 }
932 SetBackoffExpiryTime(stored_time);
933}
934
935void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
936 CHECK(prefs_);
937 backoff_expiry_time_ = new_time;
938 LOG(INFO) << "Backoff Expiry Time = "
939 << utils::ToString(backoff_expiry_time_);
940 prefs_->SetInt64(kPrefsBackoffExpiryTime,
941 backoff_expiry_time_.ToInternalValue());
942}
943
David Zeuthen9a017f22013-04-11 16:10:26 -0700944TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700945 Time end_time = update_timestamp_end_.is_null()
946 ? system_state_->clock()->GetWallclockTime() :
947 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700948 return end_time - update_timestamp_start_;
949}
950
951void PayloadState::LoadUpdateTimestampStart() {
952 int64_t stored_value;
953 Time stored_time;
954
955 CHECK(prefs_);
956
David Zeuthenf413fe52013-04-22 14:04:39 -0700957 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700958
959 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
960 // The preference missing is not unexpected - in that case, just
961 // use the current time as start time
962 stored_time = now;
963 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
964 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
965 stored_time = now;
966 } else {
967 stored_time = Time::FromInternalValue(stored_value);
968 }
969
970 // Sanity check: If the time read from disk is in the future
971 // (modulo some slack to account for possible NTP drift
972 // adjustments), something is fishy and we should report and
973 // reset.
974 TimeDelta duration_according_to_stored_time = now - stored_time;
975 if (duration_according_to_stored_time < -kDurationSlack) {
976 LOG(ERROR) << "The UpdateTimestampStart value ("
977 << utils::ToString(stored_time)
978 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700979 << utils::FormatTimeDelta(duration_according_to_stored_time)
980 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700981 stored_time = now;
982 }
983
984 SetUpdateTimestampStart(stored_time);
985}
986
987void PayloadState::SetUpdateTimestampStart(const Time& value) {
988 CHECK(prefs_);
989 update_timestamp_start_ = value;
990 prefs_->SetInt64(kPrefsUpdateTimestampStart,
991 update_timestamp_start_.ToInternalValue());
992 LOG(INFO) << "Update Timestamp Start = "
993 << utils::ToString(update_timestamp_start_);
994}
995
996void PayloadState::SetUpdateTimestampEnd(const Time& value) {
997 update_timestamp_end_ = value;
998 LOG(INFO) << "Update Timestamp End = "
999 << utils::ToString(update_timestamp_end_);
1000}
1001
1002TimeDelta PayloadState::GetUpdateDurationUptime() {
1003 return update_duration_uptime_;
1004}
1005
1006void PayloadState::LoadUpdateDurationUptime() {
1007 int64_t stored_value;
1008 TimeDelta stored_delta;
1009
1010 CHECK(prefs_);
1011
1012 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1013 // The preference missing is not unexpected - in that case, just
1014 // we'll use zero as the delta
1015 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1016 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1017 stored_delta = TimeDelta::FromSeconds(0);
1018 } else {
1019 stored_delta = TimeDelta::FromInternalValue(stored_value);
1020 }
1021
1022 // Sanity-check: Uptime can never be greater than the wall-clock
1023 // difference (modulo some slack). If it is, report and reset
1024 // to the wall-clock difference.
1025 TimeDelta diff = GetUpdateDuration() - stored_delta;
1026 if (diff < -kDurationSlack) {
1027 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001028 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001029 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001030 << utils::FormatTimeDelta(diff)
1031 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001032 stored_delta = update_duration_current_;
1033 }
1034
1035 SetUpdateDurationUptime(stored_delta);
1036}
1037
Chris Sosabe45bef2013-04-09 18:25:12 -07001038void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001039 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001040}
1041
1042void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001043 CHECK(powerwash_safe_prefs_);
1044 string rollback_version;
1045 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1046 &rollback_version)) {
1047 SetRollbackVersion(rollback_version);
1048 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001049}
1050
1051void PayloadState::SetRollbackVersion(const string& rollback_version) {
1052 CHECK(powerwash_safe_prefs_);
1053 LOG(INFO) << "Blacklisting version "<< rollback_version;
1054 rollback_version_ = rollback_version;
1055 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001056}
1057
David Zeuthen9a017f22013-04-11 16:10:26 -07001058void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1059 const Time& timestamp,
1060 bool use_logging) {
1061 CHECK(prefs_);
1062 update_duration_uptime_ = value;
1063 update_duration_uptime_timestamp_ = timestamp;
1064 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1065 update_duration_uptime_.ToInternalValue());
1066 if (use_logging) {
1067 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001068 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001069 }
1070}
1071
1072void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001073 Time now = system_state_->clock()->GetMonotonicTime();
1074 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001075}
1076
1077void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001078 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001079 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1080 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1081 // We're frequently called so avoid logging this write
1082 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1083}
1084
Jay Srinivasan19409b72013-04-12 19:23:36 -07001085string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1086 return prefix + "-from-" + utils::ToString(source);
1087}
1088
1089void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1090 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001091 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001092}
1093
1094void PayloadState::SetCurrentBytesDownloaded(
1095 DownloadSource source,
1096 uint64_t current_bytes_downloaded,
1097 bool log) {
1098 CHECK(prefs_);
1099
1100 if (source >= kNumDownloadSources)
1101 return;
1102
1103 // Update the in-memory value.
1104 current_bytes_downloaded_[source] = current_bytes_downloaded;
1105
1106 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1107 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1108 LOG_IF(INFO, log) << "Current bytes downloaded for "
1109 << utils::ToString(source) << " = "
1110 << GetCurrentBytesDownloaded(source);
1111}
1112
1113void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1114 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001115 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001116}
1117
1118void PayloadState::SetTotalBytesDownloaded(
1119 DownloadSource source,
1120 uint64_t total_bytes_downloaded,
1121 bool log) {
1122 CHECK(prefs_);
1123
1124 if (source >= kNumDownloadSources)
1125 return;
1126
1127 // Update the in-memory value.
1128 total_bytes_downloaded_[source] = total_bytes_downloaded;
1129
1130 // Persist.
1131 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1132 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1133 LOG_IF(INFO, log) << "Total bytes downloaded for "
1134 << utils::ToString(source) << " = "
1135 << GetTotalBytesDownloaded(source);
1136}
1137
David Zeuthena573d6f2013-06-14 16:13:36 -07001138void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001139 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001140}
1141
1142void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1143 CHECK(prefs_);
1144 num_responses_seen_ = num_responses_seen;
1145 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1146 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1147}
1148
Jay Srinivasan53173b92013-05-17 17:13:01 -07001149void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001150 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001151
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001152 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001153 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001154 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001155 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1156 } else {
1157 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1158 http_url_ok = true;
1159 }
1160
1161 candidate_urls_.clear();
1162 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1163 string candidate_url = response_.payload_urls[i];
Alex Vakulenko6a9d3492015-06-15 12:53:22 -07001164 if (base::StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1165 continue;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001166 candidate_urls_.push_back(candidate_url);
1167 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1168 << ": " << candidate_url;
1169 }
1170
1171 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1172 << "out of " << response_.payload_urls.size() << " URLs supplied";
1173}
1174
David Zeuthene4c58bf2013-06-18 17:26:50 -07001175void PayloadState::CreateSystemUpdatedMarkerFile() {
1176 CHECK(prefs_);
1177 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1178 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1179}
1180
1181void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1182 // Send |time_to_reboot| as a UMA stat.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001183 string metric = metrics::kMetricTimeToRebootMinutes;
David Zeuthen33bae492014-02-25 16:16:18 -08001184 system_state_->metrics_lib()->SendToUMA(metric,
1185 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001186 0, // min: 0 minute
1187 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001188 kNumDefaultUmaBuckets);
1189 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1190 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001191}
1192
1193void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001194 // Flush previous state from abnormal attempt failure, if any.
1195 ReportAndClearPersistedAttemptMetrics();
1196
Alex Deymo569c4242013-07-24 12:01:01 -07001197 // Avoid the UpdateEngineStarted actions if this is not the first time we
1198 // run the update engine since reboot.
1199 if (!system_state_->system_rebooted())
1200 return;
1201
David Zeuthene4c58bf2013-06-18 17:26:50 -07001202 // Figure out if we just booted into a new update
1203 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1204 int64_t stored_value;
1205 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1206 Time system_updated_at = Time::FromInternalValue(stored_value);
1207 if (!system_updated_at.is_null()) {
1208 TimeDelta time_to_reboot =
1209 system_state_->clock()->GetWallclockTime() - system_updated_at;
1210 if (time_to_reboot.ToInternalValue() < 0) {
1211 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1212 << utils::ToString(system_updated_at);
1213 } else {
1214 BootedIntoUpdate(time_to_reboot);
1215 }
1216 }
1217 }
1218 prefs_->Delete(kPrefsSystemUpdatedMarker);
1219 }
Alex Deymo42432912013-07-12 20:21:15 -07001220 // Check if it is needed to send metrics about a failed reboot into a new
1221 // version.
1222 ReportFailedBootIfNeeded();
1223}
1224
1225void PayloadState::ReportFailedBootIfNeeded() {
1226 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1227 // payload was marked as ready immediately before the last reboot, and we
1228 // need to check if such payload successfully rebooted or not.
1229 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001230 int64_t installed_from = 0;
1231 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001232 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1233 return;
1234 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001235 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1236 // partition number. We are now using slot numbers (0 or 1) instead, so
1237 // the following comparison will not match if we are comparing an old
1238 // partition number against a new slot number, which is the correct outcome
1239 // since we successfully booted the new update in that case. If the boot
1240 // failed, we will read this value from the same version, so it will always
1241 // be compatible.
1242 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001243 // A reboot was pending, but the chromebook is again in the same
1244 // BootDevice where the update was installed from.
1245 int64_t target_attempt;
1246 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1247 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1248 "TargetVersionInstalledFrom was present.";
1249 target_attempt = 1;
1250 }
1251
1252 // Report the UMA metric of the current boot failure.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001253 string metric = metrics::kMetricFailedUpdateCount;
David Zeuthen33bae492014-02-25 16:16:18 -08001254 LOG(INFO) << "Uploading " << target_attempt
1255 << " (count) for metric " << metric;
1256 system_state_->metrics_lib()->SendToUMA(
1257 metric,
1258 target_attempt,
1259 1, // min value
1260 50, // max value
1261 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001262 } else {
1263 prefs_->Delete(kPrefsTargetVersionAttempt);
1264 prefs_->Delete(kPrefsTargetVersionUniqueId);
1265 }
1266 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1267 }
1268}
1269
1270void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1271 // Expect to boot into the new partition in the next reboot setting the
1272 // TargetVersion* flags in the Prefs.
1273 string stored_target_version_uid;
1274 string target_version_id;
1275 string target_partition;
1276 int64_t target_attempt;
1277
1278 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1279 prefs_->GetString(kPrefsTargetVersionUniqueId,
1280 &stored_target_version_uid) &&
1281 stored_target_version_uid == target_version_uid) {
1282 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1283 target_attempt = 0;
1284 } else {
1285 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1286 target_attempt = 0;
1287 }
1288 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1289
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001290 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001291 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001292}
1293
1294void PayloadState::ResetUpdateStatus() {
1295 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1296 // rebooted the next boot is not flagged as failed to rebooted into the
1297 // new applied payload.
1298 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1299
1300 // Also decrement the attempt number if it exists.
1301 int64_t target_attempt;
1302 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001303 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001304}
1305
David Zeuthendcba8092013-08-06 12:16:35 -07001306int PayloadState::GetP2PNumAttempts() {
1307 return p2p_num_attempts_;
1308}
1309
1310void PayloadState::SetP2PNumAttempts(int value) {
1311 p2p_num_attempts_ = value;
1312 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1313 CHECK(prefs_);
1314 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1315}
1316
1317void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001318 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001319}
1320
1321Time PayloadState::GetP2PFirstAttemptTimestamp() {
1322 return p2p_first_attempt_timestamp_;
1323}
1324
1325void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1326 p2p_first_attempt_timestamp_ = time;
1327 LOG(INFO) << "p2p First Attempt Timestamp = "
1328 << utils::ToString(p2p_first_attempt_timestamp_);
1329 CHECK(prefs_);
1330 int64_t stored_value = time.ToInternalValue();
1331 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1332}
1333
1334void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001335 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001336 Time stored_time = Time::FromInternalValue(stored_value);
1337 SetP2PFirstAttemptTimestamp(stored_time);
1338}
1339
1340void PayloadState::P2PNewAttempt() {
1341 CHECK(prefs_);
1342 // Set timestamp, if it hasn't been set already
1343 if (p2p_first_attempt_timestamp_.is_null()) {
1344 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1345 }
1346 // Increase number of attempts
1347 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1348}
1349
1350bool PayloadState::P2PAttemptAllowed() {
1351 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1352 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1353 << " which is greater than "
1354 << kMaxP2PAttempts
1355 << " - disallowing p2p.";
1356 return false;
1357 }
1358
1359 if (!p2p_first_attempt_timestamp_.is_null()) {
1360 Time now = system_state_->clock()->GetWallclockTime();
1361 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1362 if (time_spent_attempting_p2p.InSeconds() < 0) {
1363 LOG(ERROR) << "Time spent attempting p2p is negative"
1364 << " - disallowing p2p.";
1365 return false;
1366 }
1367 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1368 LOG(INFO) << "Time spent attempting p2p is "
1369 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1370 << " which is greater than "
1371 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1372 kMaxP2PAttemptTimeSeconds))
1373 << " - disallowing p2p.";
1374 return false;
1375 }
1376 }
1377
1378 return true;
1379}
1380
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001381} // namespace chromeos_update_engine