blob: 38a36f94bbf6d2a0e8ea5b63dc45869a275ab76b [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080016
17#include "update_engine/payload_state.h"
18
Jay Srinivasan08262882012-12-28 19:29:43 -080019#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070020#include <string>
Jay Srinivasan08262882012-12-28 19:29:43 -080021
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080022#include <base/logging.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070023#include <base/strings/string_util.h>
24#include <base/strings/stringprintf.h>
Alex Deymoa2591792015-11-17 00:39:40 -030025#include <metrics/metrics_library.h>
Gilad Arnold1f847232014-04-07 12:07:49 -070026#include <policy/device_policy.h>
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080027
Alex Deymo39910dc2015-11-09 17:04:30 -080028#include "update_engine/common/clock.h"
29#include "update_engine/common/constants.h"
30#include "update_engine/common/hardware_interface.h"
31#include "update_engine/common/prefs.h"
32#include "update_engine/common/utils.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080033#include "update_engine/metrics_utils.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070034#include "update_engine/omaha_request_params.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080035#include "update_engine/payload_consumer/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070036#include "update_engine/system_state.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080037
Jay Srinivasan08262882012-12-28 19:29:43 -080038using base::Time;
39using base::TimeDelta;
40using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080041using std::string;
42
43namespace chromeos_update_engine {
44
David Zeuthen9a017f22013-04-11 16:10:26 -070045const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
46
Jay Srinivasan08262882012-12-28 19:29:43 -080047// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070048static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080049
Jay Srinivasan08262882012-12-28 19:29:43 -080050// We want to randomize retry attempts after the backoff by +/- 6 hours.
51static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080052
Jay Srinivasan19409b72013-04-12 19:23:36 -070053PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070054 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070055 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070056 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070057 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070058 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070059 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070060 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070061 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070062 attempt_num_bytes_downloaded_(0),
63 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070064 attempt_type_(AttemptType::kUpdate) {
65 for (int i = 0; i <= kNumDownloadSources; i++)
66 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070067}
68
69bool PayloadState::Initialize(SystemState* system_state) {
70 system_state_ = system_state;
71 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070072 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080073 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080074 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070075 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080076 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080077 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070078 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080079 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070080 LoadUpdateTimestampStart();
81 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
82 // being called before it. Don't reorder.
83 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070084 for (int i = 0; i < kNumDownloadSources; i++) {
85 DownloadSource source = static_cast<DownloadSource>(i);
86 LoadCurrentBytesDownloaded(source);
87 LoadTotalBytesDownloaded(source);
88 }
Chris Sosabe45bef2013-04-09 18:25:12 -070089 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070090 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070091 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070092 LoadP2PFirstAttemptTimestamp();
93 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080094 return true;
95}
96
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080097void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080098 // Always store the latest response.
99 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800100
Jay Srinivasan53173b92013-05-17 17:13:01 -0700101 // Compute the candidate URLs first as they are used to calculate the
102 // response signature so that a change in enterprise policy for
103 // HTTP downloads being enabled or not could be honored as soon as the
104 // next update check happens.
105 ComputeCandidateUrls();
106
Jay Srinivasan08262882012-12-28 19:29:43 -0800107 // Check if the "signature" of this response (i.e. the fields we care about)
108 // has changed.
109 string new_response_signature = CalculateResponseSignature();
110 bool has_response_changed = (response_signature_ != new_response_signature);
111
112 // If the response has changed, we should persist the new signature and
113 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800114 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800115 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700116 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800117 SetResponseSignature(new_response_signature);
118 ResetPersistedState();
119 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800120 }
121
Jay Srinivasan08262882012-12-28 19:29:43 -0800122 // This is the earliest point at which we can validate whether the URL index
123 // we loaded from the persisted state is a valid value. If the response
124 // hasn't changed but the URL index is invalid, it's indicative of some
125 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700126 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800127 LOG(INFO) << "Resetting all payload state as the url index seems to have "
128 "been tampered with";
129 ResetPersistedState();
130 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800131 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700132
133 // Update the current download source which depends on the latest value of
134 // the response.
135 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800136}
137
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700138void PayloadState::SetUsingP2PForDownloading(bool value) {
139 using_p2p_for_downloading_ = value;
140 // Update the current download source which depends on whether we are
141 // using p2p or not.
142 UpdateCurrentDownloadSource();
143}
144
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800145void PayloadState::DownloadComplete() {
146 LOG(INFO) << "Payload downloaded successfully";
147 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700148 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800149}
150
151void PayloadState::DownloadProgress(size_t count) {
152 if (count == 0)
153 return;
154
David Zeuthen9a017f22013-04-11 16:10:26 -0700155 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700156 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700157
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800158 // We've received non-zero bytes from a recent download operation. Since our
159 // URL failure count is meant to penalize a URL only for consecutive
160 // failures, downloading bytes successfully means we should reset the failure
161 // count (as we know at least that the URL is working). In future, we can
162 // design this to be more sophisticated to check for more intelligent failure
163 // patterns, but right now, even 1 byte downloaded will mark the URL to be
164 // good unless it hits 10 (or configured number of) consecutive failures
165 // again.
166
167 if (GetUrlFailureCount() == 0)
168 return;
169
170 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
171 << " to 0 as we received " << count << " bytes successfully";
172 SetUrlFailureCount(0);
173}
174
David Zeuthenafed4a12014-04-09 15:28:44 -0700175void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700176 // Flush previous state from abnormal attempt failure, if any.
177 ReportAndClearPersistedAttemptMetrics();
178
David Zeuthenafed4a12014-04-09 15:28:44 -0700179 attempt_type_ = attempt_type;
180
David Zeuthen33bae492014-02-25 16:16:18 -0800181 ClockInterface *clock = system_state_->clock();
182 attempt_start_time_boot_ = clock->GetBootTime();
183 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800184 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700185
186 metrics::ConnectionType type;
187 NetworkConnectionType network_connection_type;
188 NetworkTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700189 ConnectionManagerInterface* connection_manager =
190 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700191 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700192 &tethering)) {
193 LOG(ERROR) << "Failed to determine connection type.";
194 type = metrics::ConnectionType::kUnknown;
195 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800196 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700197 }
198 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700199
200 if (attempt_type == AttemptType::kUpdate)
201 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800202}
203
Chris Sosabe45bef2013-04-09 18:25:12 -0700204void PayloadState::UpdateResumed() {
205 LOG(INFO) << "Resuming an update that was previously started.";
206 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700207 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700208}
209
Jay Srinivasan19409b72013-04-12 19:23:36 -0700210void PayloadState::UpdateRestarted() {
211 LOG(INFO) << "Starting a new update";
212 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700213 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700214 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700215}
216
David Zeuthen9a017f22013-04-11 16:10:26 -0700217void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700218 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700219 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700220 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800221
David Zeuthen96197df2014-04-16 12:22:39 -0700222 switch (attempt_type_) {
223 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700224 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700225 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700226 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700227 break;
228
229 case AttemptType::kRollback:
230 metrics::ReportRollbackMetrics(system_state_,
231 metrics::RollbackResult::kSuccess);
232 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700233 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700234
235 // Reset the number of responses seen since it counts from the last
236 // successful update, e.g. now.
237 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700238
239 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700240}
241
David Zeuthena99981f2013-04-29 13:42:47 -0700242void PayloadState::UpdateFailed(ErrorCode error) {
243 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800244 LOG(INFO) << "Updating payload state for error code: " << base_error
245 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800246
Jay Srinivasan53173b92013-05-17 17:13:01 -0700247 if (candidate_urls_.size() == 0) {
248 // This means we got this error even before we got a valid Omaha response
249 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800250 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800251 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
252 return;
253 }
254
David Zeuthen96197df2014-04-16 12:22:39 -0700255 switch (attempt_type_) {
256 case AttemptType::kUpdate:
257 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700258 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700259 break;
260
261 case AttemptType::kRollback:
262 metrics::ReportRollbackMetrics(system_state_,
263 metrics::RollbackResult::kFailed);
264 break;
265 }
David Zeuthen33bae492014-02-25 16:16:18 -0800266
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800267 switch (base_error) {
268 // Errors which are good indicators of a problem with a particular URL or
269 // the protocol used in the URL or entities in the communication channel
270 // (e.g. proxies). We should try the next available URL in the next update
271 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700272 case ErrorCode::kPayloadHashMismatchError:
273 case ErrorCode::kPayloadSizeMismatchError:
274 case ErrorCode::kDownloadPayloadVerificationError:
275 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
276 case ErrorCode::kSignedDeltaPayloadExpectedError:
277 case ErrorCode::kDownloadInvalidMetadataMagicString:
278 case ErrorCode::kDownloadSignatureMissingInManifest:
279 case ErrorCode::kDownloadManifestParseError:
280 case ErrorCode::kDownloadMetadataSignatureError:
281 case ErrorCode::kDownloadMetadataSignatureVerificationError:
282 case ErrorCode::kDownloadMetadataSignatureMismatch:
283 case ErrorCode::kDownloadOperationHashVerificationError:
284 case ErrorCode::kDownloadOperationExecutionError:
285 case ErrorCode::kDownloadOperationHashMismatch:
286 case ErrorCode::kDownloadInvalidMetadataSize:
287 case ErrorCode::kDownloadInvalidMetadataSignature:
288 case ErrorCode::kDownloadOperationHashMissingError:
289 case ErrorCode::kDownloadMetadataSignatureMissingError:
290 case ErrorCode::kPayloadMismatchedType:
291 case ErrorCode::kUnsupportedMajorPayloadVersion:
292 case ErrorCode::kUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800293 IncrementUrlIndex();
294 break;
295
296 // Errors which seem to be just transient network/communication related
297 // failures and do not indicate any inherent problem with the URL itself.
298 // So, we should keep the current URL but just increment the
299 // failure count to give it more chances. This way, while we maximize our
300 // chances of downloading from the URLs that appear earlier in the response
301 // (because download from a local server URL that appears earlier in a
302 // response is preferable than downloading from the next URL which could be
303 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700304
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700305 case ErrorCode::kError:
306 case ErrorCode::kDownloadTransferError:
307 case ErrorCode::kDownloadWriteError:
308 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700309 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800310 IncrementFailureCount();
311 break;
312
313 // Errors which are not specific to a URL and hence shouldn't result in
314 // the URL being penalized. This can happen in two cases:
315 // 1. We haven't started downloading anything: These errors don't cost us
316 // anything in terms of actual payload bytes, so we should just do the
317 // regular retries at the next update check.
318 // 2. We have successfully downloaded the payload: In this case, the
319 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800320 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800321 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700322 case ErrorCode::kOmahaRequestError:
323 case ErrorCode::kOmahaResponseHandlerError:
324 case ErrorCode::kPostinstallRunnerError:
325 case ErrorCode::kFilesystemCopierError:
326 case ErrorCode::kInstallDeviceOpenError:
327 case ErrorCode::kKernelDeviceOpenError:
328 case ErrorCode::kDownloadNewPartitionInfoError:
329 case ErrorCode::kNewRootfsVerificationError:
330 case ErrorCode::kNewKernelVerificationError:
331 case ErrorCode::kPostinstallBootedFromFirmwareB:
332 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
333 case ErrorCode::kOmahaRequestEmptyResponseError:
334 case ErrorCode::kOmahaRequestXMLParseError:
335 case ErrorCode::kOmahaResponseInvalid:
336 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
337 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
338 case ErrorCode::kOmahaUpdateDeferredForBackoff:
339 case ErrorCode::kPostinstallPowerwashError:
340 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400341 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700342 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800343 case ErrorCode::kUserCanceled:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800344 LOG(INFO) << "Not incrementing URL index or failure count for this error";
345 break;
346
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700347 case ErrorCode::kSuccess: // success code
348 case ErrorCode::kUmaReportedMax: // not an error code
349 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
350 case ErrorCode::kDevModeFlag: // not an error code
351 case ErrorCode::kResumedFlag: // not an error code
352 case ErrorCode::kTestImageFlag: // not an error code
353 case ErrorCode::kTestOmahaUrlFlag: // not an error code
354 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800355 // These shouldn't happen. Enumerating these explicitly here so that we
356 // can let the compiler warn about new error codes that are added to
357 // action_processor.h but not added here.
358 LOG(WARNING) << "Unexpected error code for UpdateFailed";
359 break;
360
361 // Note: Not adding a default here so as to let the compiler warn us of
362 // any new enums that were added in the .h but not listed in this switch.
363 }
364}
365
Jay Srinivasan08262882012-12-28 19:29:43 -0800366bool PayloadState::ShouldBackoffDownload() {
367 if (response_.disable_payload_backoff) {
368 LOG(INFO) << "Payload backoff logic is disabled. "
369 "Can proceed with the download";
370 return false;
371 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700372 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700373 LOG(INFO) << "Payload backoff logic is disabled because download "
374 << "will happen from local peer (via p2p).";
375 return false;
376 }
377 if (system_state_->request_params()->interactive()) {
378 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
379 return false;
380 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800381 if (response_.is_delta_payload) {
382 // If delta payloads fail, we want to fallback quickly to full payloads as
383 // they are more likely to succeed. Exponential backoffs would greatly
384 // slow down the fallback to full payloads. So we don't backoff for delta
385 // payloads.
386 LOG(INFO) << "No backoffs for delta payloads. "
387 << "Can proceed with the download";
388 return false;
389 }
390
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700391 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800392 // Backoffs are needed only for official builds. We do not want any delays
393 // or update failures due to backoffs during testing or development.
394 LOG(INFO) << "No backoffs for test/dev images. "
395 << "Can proceed with the download";
396 return false;
397 }
398
399 if (backoff_expiry_time_.is_null()) {
400 LOG(INFO) << "No backoff expiry time has been set. "
401 << "Can proceed with the download";
402 return false;
403 }
404
405 if (backoff_expiry_time_ < Time::Now()) {
406 LOG(INFO) << "The backoff expiry time ("
407 << utils::ToString(backoff_expiry_time_)
408 << ") has elapsed. Can proceed with the download";
409 return false;
410 }
411
412 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
413 << utils::ToString(backoff_expiry_time_);
414 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800415}
416
Chris Sosaaa18e162013-06-20 13:20:30 -0700417void PayloadState::Rollback() {
418 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700419 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700420}
421
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800422void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700423 // Update the payload attempt number for both payload types: full and delta.
424 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
425}
426
427void PayloadState::IncrementFullPayloadAttemptNumber() {
428 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800429 if (response_.is_delta_payload) {
430 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
431 return;
432 }
433
Alex Deymo29b51d92013-07-09 15:26:24 -0700434 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700435 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800436 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800437}
438
439void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800440 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700441 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800442 LOG(INFO) << "Incrementing the URL index for next attempt";
443 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800444 } else {
445 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700446 << "0 as we only have " << candidate_urls_.size()
447 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800448 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700449 IncrementPayloadAttemptNumber();
450 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800451 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800452
David Zeuthencc6f9962013-04-18 11:57:24 -0700453 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700454 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700455 SetUrlSwitchCount(url_switch_count_ + 1);
456
Jay Srinivasan08262882012-12-28 19:29:43 -0800457 // Whenever we update the URL index, we should also clear the URL failure
458 // count so we can start over fresh for the new URL.
459 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800460}
461
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800462void PayloadState::IncrementFailureCount() {
463 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800464 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800465 LOG(INFO) << "Incrementing the URL failure count";
466 SetUrlFailureCount(next_url_failure_count);
467 } else {
468 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
469 << ". Trying next available URL";
470 IncrementUrlIndex();
471 }
472}
473
Jay Srinivasan08262882012-12-28 19:29:43 -0800474void PayloadState::UpdateBackoffExpiryTime() {
475 if (response_.disable_payload_backoff) {
476 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
477 SetBackoffExpiryTime(Time());
478 return;
479 }
480
Alex Deymo820cc702013-06-28 15:43:46 -0700481 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800482 SetBackoffExpiryTime(Time());
483 return;
484 }
485
486 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700487 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800488 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700489 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700490 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800491
492 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
493 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700494 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800495
496 // The number of days is the minimum of 2 raised to (payload_attempt_number
497 // - 1) or kMaxBackoffDays.
498 num_days = min(num_days << power, kMaxBackoffDays);
499
500 // We don't want all retries to happen exactly at the same time when
501 // retrying after backoff. So add some random minutes to fuzz.
502 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
503 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
504 TimeDelta::FromMinutes(fuzz_minutes);
505 LOG(INFO) << "Incrementing the backoff expiry time by "
506 << utils::FormatTimeDelta(next_backoff_interval);
507 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
508}
509
Jay Srinivasan19409b72013-04-12 19:23:36 -0700510void PayloadState::UpdateCurrentDownloadSource() {
511 current_download_source_ = kNumDownloadSources;
512
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700513 if (using_p2p_for_downloading_) {
514 current_download_source_ = kDownloadSourceHttpPeer;
515 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700516 string current_url = candidate_urls_[GetUrlIndex()];
Alex Vakulenko0103c362016-01-20 07:56:15 -0800517 if (base::StartsWith(current_url, "https://",
518 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700519 current_download_source_ = kDownloadSourceHttpsServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800520 } else if (base::StartsWith(current_url, "http://",
521 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700522 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800523 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700524 }
525
526 LOG(INFO) << "Current download source: "
527 << utils::ToString(current_download_source_);
528}
529
530void PayloadState::UpdateBytesDownloaded(size_t count) {
531 SetCurrentBytesDownloaded(
532 current_download_source_,
533 GetCurrentBytesDownloaded(current_download_source_) + count,
534 false);
535 SetTotalBytesDownloaded(
536 current_download_source_,
537 GetTotalBytesDownloaded(current_download_source_) + count,
538 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800539
540 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700541}
542
David Zeuthen33bae492014-02-25 16:16:18 -0800543PayloadType PayloadState::CalculatePayloadType() {
544 PayloadType payload_type;
545 OmahaRequestParams* params = system_state_->request_params();
546 if (response_.is_delta_payload) {
547 payload_type = kPayloadTypeDelta;
548 } else if (params->delta_okay()) {
549 payload_type = kPayloadTypeFull;
550 } else { // Full payload, delta was not allowed by request.
551 payload_type = kPayloadTypeForcedFull;
552 }
553 return payload_type;
554}
555
556// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
557// metrics if the attempt ends abnormally, e.g. if the update_engine
558// process crashes or the device is rebooted. See
559// http://crbug.com/357676
560void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
561 int attempt_number = GetPayloadAttemptNumber();
562
563 PayloadType payload_type = CalculatePayloadType();
564
565 int64_t payload_size = response_.size;
566
567 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
568
569 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700570 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
571 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800572 attempt_start_time_monotonic_;
573
574 int64_t payload_download_speed_bps = 0;
575 int64_t usec = duration_uptime.InMicroseconds();
576 if (usec > 0) {
577 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
578 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
579 payload_download_speed_bps = static_cast<int64_t>(bps);
580 }
581
582 DownloadSource download_source = current_download_source_;
583
584 metrics::DownloadErrorCode payload_download_error_code =
585 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700586 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800587 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800588
589 // Add additional detail to AttemptResult
590 switch (attempt_result) {
591 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800592 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800593 break;
594
595 case metrics::AttemptResult::kInternalError:
596 internal_error_code = code;
597 break;
598
599 // Explicit fall-through for cases where we do not have additional
600 // detail. We avoid the default keyword to force people adding new
601 // AttemptResult values to visit this code and examine whether
602 // additional detail is needed.
603 case metrics::AttemptResult::kUpdateSucceeded:
604 case metrics::AttemptResult::kMetadataMalformed:
605 case metrics::AttemptResult::kOperationMalformed:
606 case metrics::AttemptResult::kOperationExecutionError:
607 case metrics::AttemptResult::kMetadataVerificationFailed:
608 case metrics::AttemptResult::kPayloadVerificationFailed:
609 case metrics::AttemptResult::kVerificationFailed:
610 case metrics::AttemptResult::kPostInstallFailed:
611 case metrics::AttemptResult::kAbnormalTermination:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800612 case metrics::AttemptResult::kUpdateCanceled:
David Zeuthen33bae492014-02-25 16:16:18 -0800613 case metrics::AttemptResult::kNumConstants:
614 case metrics::AttemptResult::kUnset:
615 break;
616 }
617
618 metrics::ReportUpdateAttemptMetrics(system_state_,
619 attempt_number,
620 payload_type,
621 duration,
622 duration_uptime,
623 payload_size,
624 payload_bytes_downloaded,
625 payload_download_speed_bps,
626 download_source,
627 attempt_result,
628 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700629 payload_download_error_code,
630 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800631}
632
David Zeuthen4e1d1492014-04-25 13:12:27 -0700633void PayloadState::PersistAttemptMetrics() {
634 // TODO(zeuthen): For now we only persist whether an attempt was in
635 // progress and not values/metrics related to the attempt. This
636 // means that when this happens, of all the UpdateEngine.Attempt.*
637 // metrics, only UpdateEngine.Attempt.Result is reported (with the
638 // value |kAbnormalTermination|). In the future we might want to
639 // persist more data so we can report other metrics in the
640 // UpdateEngine.Attempt.* namespace when this happens.
641 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
642}
643
644void PayloadState::ClearPersistedAttemptMetrics() {
645 prefs_->Delete(kPrefsAttemptInProgress);
646}
647
648void PayloadState::ReportAndClearPersistedAttemptMetrics() {
649 bool attempt_in_progress = false;
650 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
651 return;
652 if (!attempt_in_progress)
653 return;
654
655 metrics::ReportAbnormallyTerminatedUpdateAttemptMetrics(system_state_);
656
657 ClearPersistedAttemptMetrics();
658}
659
David Zeuthen33bae492014-02-25 16:16:18 -0800660void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700661 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800662
663 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800664 int64_t total_bytes_by_source[kNumDownloadSources];
665 int64_t successful_bytes = 0;
666 int64_t total_bytes = 0;
667 int64_t successful_mbs = 0;
668 int64_t total_mbs = 0;
669
Jay Srinivasan19409b72013-04-12 19:23:36 -0700670 for (int i = 0; i < kNumDownloadSources; i++) {
671 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800672 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700673
David Zeuthen44848602013-06-24 13:32:14 -0700674 // Only consider this download source (and send byte counts) as
675 // having been used if we downloaded a non-trivial amount of bytes
676 // (e.g. at least 1 MiB) that contributed to the final success of
677 // the update. Otherwise we're going to end up with a lot of
678 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700679
David Zeuthen33bae492014-02-25 16:16:18 -0800680 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800681 successful_bytes += bytes;
682 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700683 SetCurrentBytesDownloaded(source, 0, true);
684
David Zeuthen33bae492014-02-25 16:16:18 -0800685 bytes = GetTotalBytesDownloaded(source);
686 total_bytes_by_source[i] = bytes;
687 total_bytes += bytes;
688 total_mbs += bytes / kNumBytesInOneMiB;
689 SetTotalBytesDownloaded(source, 0, true);
690 }
691
692 int download_overhead_percentage = 0;
693 if (successful_bytes > 0) {
694 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
695 successful_bytes;
696 }
697
698 int url_switch_count = static_cast<int>(url_switch_count_);
699
700 int reboot_count = GetNumReboots();
701
702 SetNumReboots(0);
703
704 TimeDelta duration = GetUpdateDuration();
David Zeuthen33bae492014-02-25 16:16:18 -0800705
706 prefs_->Delete(kPrefsUpdateTimestampStart);
707 prefs_->Delete(kPrefsUpdateDurationUptime);
708
709 PayloadType payload_type = CalculatePayloadType();
710
711 int64_t payload_size = response_.size;
712
713 int attempt_count = GetPayloadAttemptNumber();
714
715 int updates_abandoned_count = num_responses_seen_ - 1;
716
717 metrics::ReportSuccessfulUpdateMetrics(system_state_,
718 attempt_count,
719 updates_abandoned_count,
720 payload_type,
721 payload_size,
722 total_bytes_by_source,
723 download_overhead_percentage,
724 duration,
725 reboot_count,
726 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700727}
728
729void PayloadState::UpdateNumReboots() {
730 // We only update the reboot count when the system has been detected to have
731 // been rebooted.
732 if (!system_state_->system_rebooted()) {
733 return;
734 }
735
736 SetNumReboots(GetNumReboots() + 1);
737}
738
739void PayloadState::SetNumReboots(uint32_t num_reboots) {
740 CHECK(prefs_);
741 num_reboots_ = num_reboots;
742 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
743 LOG(INFO) << "Number of Reboots during current update attempt = "
744 << num_reboots_;
745}
746
Jay Srinivasan08262882012-12-28 19:29:43 -0800747void PayloadState::ResetPersistedState() {
748 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700749 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800750 SetUrlIndex(0);
751 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700752 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700753 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700754 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700755 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700756 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700757 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700758 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700759 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700760 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700761 SetScatteringWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700762}
763
764void PayloadState::ResetRollbackVersion() {
765 CHECK(powerwash_safe_prefs_);
766 rollback_version_ = "";
767 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700768}
769
770void PayloadState::ResetDownloadSourcesOnNewUpdate() {
771 for (int i = 0; i < kNumDownloadSources; i++) {
772 DownloadSource source = static_cast<DownloadSource>(i);
773 SetCurrentBytesDownloaded(source, 0, true);
774 // Note: Not resetting the TotalBytesDownloaded as we want that metric
775 // to count the bytes downloaded across various update attempts until
776 // we have successfully applied the update.
777 }
778}
779
Chris Sosab3dcdb32013-09-04 15:22:12 -0700780int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700781 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700782 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700783 return 0;
784
785 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700786 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700787 return 0;
788
789 if (stored_value < 0) {
790 LOG(ERROR) << key << ": Invalid value (" << stored_value
791 << ") in persisted state. Defaulting to 0";
792 return 0;
793 }
794
795 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800796}
797
798string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700799 string response_sign = base::StringPrintf(
800 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800801
Jay Srinivasan53173b92013-05-17 17:13:01 -0700802 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700803 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
804 static_cast<int>(i),
805 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800806
Alex Vakulenko75039d72014-03-25 12:36:28 -0700807 response_sign += base::StringPrintf(
808 "Payload Size = %ju\n"
809 "Payload Sha256 Hash = %s\n"
810 "Metadata Size = %ju\n"
811 "Metadata Signature = %s\n"
812 "Is Delta Payload = %d\n"
813 "Max Failure Count Per Url = %d\n"
814 "Disable Payload Backoff = %d\n",
815 static_cast<uintmax_t>(response_.size),
816 response_.hash.c_str(),
817 static_cast<uintmax_t>(response_.metadata_size),
818 response_.metadata_signature.c_str(),
819 response_.is_delta_payload,
820 response_.max_failure_count_per_url,
821 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800822 return response_sign;
823}
824
825void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800826 CHECK(prefs_);
827 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800828 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
829 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
830 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800831 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800832}
833
Jay Srinivasan19409b72013-04-12 19:23:36 -0700834void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800835 CHECK(prefs_);
836 response_signature_ = response_signature;
837 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
838 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
839}
840
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800841void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700842 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800843}
844
Alex Deymo820cc702013-06-28 15:43:46 -0700845void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700846 SetFullPayloadAttemptNumber(GetPersistedValue(
847 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700848}
849
850void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800851 CHECK(prefs_);
852 payload_attempt_number_ = payload_attempt_number;
853 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
854 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
855}
856
Alex Deymo820cc702013-06-28 15:43:46 -0700857void PayloadState::SetFullPayloadAttemptNumber(
858 int full_payload_attempt_number) {
859 CHECK(prefs_);
860 full_payload_attempt_number_ = full_payload_attempt_number;
861 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
862 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
863 full_payload_attempt_number_);
864}
865
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800866void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700867 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800868}
869
870void PayloadState::SetUrlIndex(uint32_t url_index) {
871 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800872 url_index_ = url_index;
873 LOG(INFO) << "Current URL Index = " << url_index_;
874 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700875
876 // Also update the download source, which is purely dependent on the
877 // current URL index alone.
878 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800879}
880
Gilad Arnold519cfc72014-10-02 10:34:54 -0700881void PayloadState::LoadScatteringWaitPeriod() {
882 SetScatteringWaitPeriod(
883 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
884}
885
Alex Deymof329b932014-10-30 01:37:48 -0700886void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700887 CHECK(prefs_);
888 scattering_wait_period_ = wait_period;
889 LOG(INFO) << "Scattering Wait Period (seconds) = "
890 << scattering_wait_period_.InSeconds();
891 if (scattering_wait_period_.InSeconds() > 0) {
892 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
893 scattering_wait_period_.InSeconds());
894 } else {
895 prefs_->Delete(kPrefsWallClockWaitPeriod);
896 }
897}
898
David Zeuthencc6f9962013-04-18 11:57:24 -0700899void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700900 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700901}
902
903void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
904 CHECK(prefs_);
905 url_switch_count_ = url_switch_count;
906 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
907 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
908}
909
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800910void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700911 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800912}
913
914void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
915 CHECK(prefs_);
916 url_failure_count_ = url_failure_count;
917 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
918 << ")'s Failure Count = " << url_failure_count_;
919 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800920}
921
Jay Srinivasan08262882012-12-28 19:29:43 -0800922void PayloadState::LoadBackoffExpiryTime() {
923 CHECK(prefs_);
924 int64_t stored_value;
925 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
926 return;
927
928 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
929 return;
930
931 Time stored_time = Time::FromInternalValue(stored_value);
932 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
933 LOG(ERROR) << "Invalid backoff expiry time ("
934 << utils::ToString(stored_time)
935 << ") in persisted state. Resetting.";
936 stored_time = Time();
937 }
938 SetBackoffExpiryTime(stored_time);
939}
940
941void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
942 CHECK(prefs_);
943 backoff_expiry_time_ = new_time;
944 LOG(INFO) << "Backoff Expiry Time = "
945 << utils::ToString(backoff_expiry_time_);
946 prefs_->SetInt64(kPrefsBackoffExpiryTime,
947 backoff_expiry_time_.ToInternalValue());
948}
949
David Zeuthen9a017f22013-04-11 16:10:26 -0700950TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700951 Time end_time = update_timestamp_end_.is_null()
952 ? system_state_->clock()->GetWallclockTime() :
953 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700954 return end_time - update_timestamp_start_;
955}
956
957void PayloadState::LoadUpdateTimestampStart() {
958 int64_t stored_value;
959 Time stored_time;
960
961 CHECK(prefs_);
962
David Zeuthenf413fe52013-04-22 14:04:39 -0700963 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700964
965 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
966 // The preference missing is not unexpected - in that case, just
967 // use the current time as start time
968 stored_time = now;
969 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
970 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
971 stored_time = now;
972 } else {
973 stored_time = Time::FromInternalValue(stored_value);
974 }
975
976 // Sanity check: If the time read from disk is in the future
977 // (modulo some slack to account for possible NTP drift
978 // adjustments), something is fishy and we should report and
979 // reset.
980 TimeDelta duration_according_to_stored_time = now - stored_time;
981 if (duration_according_to_stored_time < -kDurationSlack) {
982 LOG(ERROR) << "The UpdateTimestampStart value ("
983 << utils::ToString(stored_time)
984 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700985 << utils::FormatTimeDelta(duration_according_to_stored_time)
986 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700987 stored_time = now;
988 }
989
990 SetUpdateTimestampStart(stored_time);
991}
992
993void PayloadState::SetUpdateTimestampStart(const Time& value) {
994 CHECK(prefs_);
995 update_timestamp_start_ = value;
996 prefs_->SetInt64(kPrefsUpdateTimestampStart,
997 update_timestamp_start_.ToInternalValue());
998 LOG(INFO) << "Update Timestamp Start = "
999 << utils::ToString(update_timestamp_start_);
1000}
1001
1002void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1003 update_timestamp_end_ = value;
1004 LOG(INFO) << "Update Timestamp End = "
1005 << utils::ToString(update_timestamp_end_);
1006}
1007
1008TimeDelta PayloadState::GetUpdateDurationUptime() {
1009 return update_duration_uptime_;
1010}
1011
1012void PayloadState::LoadUpdateDurationUptime() {
1013 int64_t stored_value;
1014 TimeDelta stored_delta;
1015
1016 CHECK(prefs_);
1017
1018 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1019 // The preference missing is not unexpected - in that case, just
1020 // we'll use zero as the delta
1021 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1022 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1023 stored_delta = TimeDelta::FromSeconds(0);
1024 } else {
1025 stored_delta = TimeDelta::FromInternalValue(stored_value);
1026 }
1027
1028 // Sanity-check: Uptime can never be greater than the wall-clock
1029 // difference (modulo some slack). If it is, report and reset
1030 // to the wall-clock difference.
1031 TimeDelta diff = GetUpdateDuration() - stored_delta;
1032 if (diff < -kDurationSlack) {
1033 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001034 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001035 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001036 << utils::FormatTimeDelta(diff)
1037 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001038 stored_delta = update_duration_current_;
1039 }
1040
1041 SetUpdateDurationUptime(stored_delta);
1042}
1043
Chris Sosabe45bef2013-04-09 18:25:12 -07001044void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001045 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001046}
1047
1048void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001049 CHECK(powerwash_safe_prefs_);
1050 string rollback_version;
1051 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1052 &rollback_version)) {
1053 SetRollbackVersion(rollback_version);
1054 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001055}
1056
1057void PayloadState::SetRollbackVersion(const string& rollback_version) {
1058 CHECK(powerwash_safe_prefs_);
1059 LOG(INFO) << "Blacklisting version "<< rollback_version;
1060 rollback_version_ = rollback_version;
1061 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001062}
1063
David Zeuthen9a017f22013-04-11 16:10:26 -07001064void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1065 const Time& timestamp,
1066 bool use_logging) {
1067 CHECK(prefs_);
1068 update_duration_uptime_ = value;
1069 update_duration_uptime_timestamp_ = timestamp;
1070 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1071 update_duration_uptime_.ToInternalValue());
1072 if (use_logging) {
1073 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001074 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001075 }
1076}
1077
1078void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001079 Time now = system_state_->clock()->GetMonotonicTime();
1080 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001081}
1082
1083void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001084 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001085 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1086 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1087 // We're frequently called so avoid logging this write
1088 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1089}
1090
Jay Srinivasan19409b72013-04-12 19:23:36 -07001091string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1092 return prefix + "-from-" + utils::ToString(source);
1093}
1094
1095void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1096 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001097 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001098}
1099
1100void PayloadState::SetCurrentBytesDownloaded(
1101 DownloadSource source,
1102 uint64_t current_bytes_downloaded,
1103 bool log) {
1104 CHECK(prefs_);
1105
1106 if (source >= kNumDownloadSources)
1107 return;
1108
1109 // Update the in-memory value.
1110 current_bytes_downloaded_[source] = current_bytes_downloaded;
1111
1112 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1113 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1114 LOG_IF(INFO, log) << "Current bytes downloaded for "
1115 << utils::ToString(source) << " = "
1116 << GetCurrentBytesDownloaded(source);
1117}
1118
1119void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1120 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001121 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001122}
1123
1124void PayloadState::SetTotalBytesDownloaded(
1125 DownloadSource source,
1126 uint64_t total_bytes_downloaded,
1127 bool log) {
1128 CHECK(prefs_);
1129
1130 if (source >= kNumDownloadSources)
1131 return;
1132
1133 // Update the in-memory value.
1134 total_bytes_downloaded_[source] = total_bytes_downloaded;
1135
1136 // Persist.
1137 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1138 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1139 LOG_IF(INFO, log) << "Total bytes downloaded for "
1140 << utils::ToString(source) << " = "
1141 << GetTotalBytesDownloaded(source);
1142}
1143
David Zeuthena573d6f2013-06-14 16:13:36 -07001144void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001145 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001146}
1147
1148void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1149 CHECK(prefs_);
1150 num_responses_seen_ = num_responses_seen;
1151 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1152 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1153}
1154
Jay Srinivasan53173b92013-05-17 17:13:01 -07001155void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001156 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001157
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001158 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001159 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001160 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001161 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1162 } else {
1163 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1164 http_url_ok = true;
1165 }
1166
1167 candidate_urls_.clear();
1168 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1169 string candidate_url = response_.payload_urls[i];
Alex Vakulenko0103c362016-01-20 07:56:15 -08001170 if (base::StartsWith(candidate_url, "http://",
1171 base::CompareCase::INSENSITIVE_ASCII) &&
1172 !http_url_ok) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -07001173 continue;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001174 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001175 candidate_urls_.push_back(candidate_url);
1176 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1177 << ": " << candidate_url;
1178 }
1179
1180 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1181 << "out of " << response_.payload_urls.size() << " URLs supplied";
1182}
1183
David Zeuthene4c58bf2013-06-18 17:26:50 -07001184void PayloadState::CreateSystemUpdatedMarkerFile() {
1185 CHECK(prefs_);
1186 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1187 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1188}
1189
1190void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1191 // Send |time_to_reboot| as a UMA stat.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001192 string metric = metrics::kMetricTimeToRebootMinutes;
David Zeuthen33bae492014-02-25 16:16:18 -08001193 system_state_->metrics_lib()->SendToUMA(metric,
1194 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001195 0, // min: 0 minute
1196 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001197 kNumDefaultUmaBuckets);
1198 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1199 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001200}
1201
1202void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001203 // Flush previous state from abnormal attempt failure, if any.
1204 ReportAndClearPersistedAttemptMetrics();
1205
Alex Deymo569c4242013-07-24 12:01:01 -07001206 // Avoid the UpdateEngineStarted actions if this is not the first time we
1207 // run the update engine since reboot.
1208 if (!system_state_->system_rebooted())
1209 return;
1210
David Zeuthene4c58bf2013-06-18 17:26:50 -07001211 // Figure out if we just booted into a new update
1212 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1213 int64_t stored_value;
1214 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1215 Time system_updated_at = Time::FromInternalValue(stored_value);
1216 if (!system_updated_at.is_null()) {
1217 TimeDelta time_to_reboot =
1218 system_state_->clock()->GetWallclockTime() - system_updated_at;
1219 if (time_to_reboot.ToInternalValue() < 0) {
1220 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1221 << utils::ToString(system_updated_at);
1222 } else {
1223 BootedIntoUpdate(time_to_reboot);
1224 }
1225 }
1226 }
1227 prefs_->Delete(kPrefsSystemUpdatedMarker);
1228 }
Alex Deymo42432912013-07-12 20:21:15 -07001229 // Check if it is needed to send metrics about a failed reboot into a new
1230 // version.
1231 ReportFailedBootIfNeeded();
1232}
1233
1234void PayloadState::ReportFailedBootIfNeeded() {
1235 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1236 // payload was marked as ready immediately before the last reboot, and we
1237 // need to check if such payload successfully rebooted or not.
1238 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001239 int64_t installed_from = 0;
1240 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001241 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1242 return;
1243 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001244 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1245 // partition number. We are now using slot numbers (0 or 1) instead, so
1246 // the following comparison will not match if we are comparing an old
1247 // partition number against a new slot number, which is the correct outcome
1248 // since we successfully booted the new update in that case. If the boot
1249 // failed, we will read this value from the same version, so it will always
1250 // be compatible.
1251 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001252 // A reboot was pending, but the chromebook is again in the same
1253 // BootDevice where the update was installed from.
1254 int64_t target_attempt;
1255 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1256 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1257 "TargetVersionInstalledFrom was present.";
1258 target_attempt = 1;
1259 }
1260
1261 // Report the UMA metric of the current boot failure.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001262 string metric = metrics::kMetricFailedUpdateCount;
David Zeuthen33bae492014-02-25 16:16:18 -08001263 LOG(INFO) << "Uploading " << target_attempt
1264 << " (count) for metric " << metric;
1265 system_state_->metrics_lib()->SendToUMA(
1266 metric,
1267 target_attempt,
1268 1, // min value
1269 50, // max value
1270 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001271 } else {
1272 prefs_->Delete(kPrefsTargetVersionAttempt);
1273 prefs_->Delete(kPrefsTargetVersionUniqueId);
1274 }
1275 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1276 }
1277}
1278
1279void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1280 // Expect to boot into the new partition in the next reboot setting the
1281 // TargetVersion* flags in the Prefs.
1282 string stored_target_version_uid;
1283 string target_version_id;
1284 string target_partition;
1285 int64_t target_attempt;
1286
1287 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1288 prefs_->GetString(kPrefsTargetVersionUniqueId,
1289 &stored_target_version_uid) &&
1290 stored_target_version_uid == target_version_uid) {
1291 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1292 target_attempt = 0;
1293 } else {
1294 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1295 target_attempt = 0;
1296 }
1297 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1298
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001299 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001300 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001301}
1302
1303void PayloadState::ResetUpdateStatus() {
1304 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1305 // rebooted the next boot is not flagged as failed to rebooted into the
1306 // new applied payload.
1307 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1308
1309 // Also decrement the attempt number if it exists.
1310 int64_t target_attempt;
1311 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001312 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001313}
1314
David Zeuthendcba8092013-08-06 12:16:35 -07001315int PayloadState::GetP2PNumAttempts() {
1316 return p2p_num_attempts_;
1317}
1318
1319void PayloadState::SetP2PNumAttempts(int value) {
1320 p2p_num_attempts_ = value;
1321 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1322 CHECK(prefs_);
1323 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1324}
1325
1326void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001327 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001328}
1329
1330Time PayloadState::GetP2PFirstAttemptTimestamp() {
1331 return p2p_first_attempt_timestamp_;
1332}
1333
1334void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1335 p2p_first_attempt_timestamp_ = time;
1336 LOG(INFO) << "p2p First Attempt Timestamp = "
1337 << utils::ToString(p2p_first_attempt_timestamp_);
1338 CHECK(prefs_);
1339 int64_t stored_value = time.ToInternalValue();
1340 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1341}
1342
1343void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001344 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001345 Time stored_time = Time::FromInternalValue(stored_value);
1346 SetP2PFirstAttemptTimestamp(stored_time);
1347}
1348
1349void PayloadState::P2PNewAttempt() {
1350 CHECK(prefs_);
1351 // Set timestamp, if it hasn't been set already
1352 if (p2p_first_attempt_timestamp_.is_null()) {
1353 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1354 }
1355 // Increase number of attempts
1356 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1357}
1358
1359bool PayloadState::P2PAttemptAllowed() {
1360 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1361 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1362 << " which is greater than "
1363 << kMaxP2PAttempts
1364 << " - disallowing p2p.";
1365 return false;
1366 }
1367
1368 if (!p2p_first_attempt_timestamp_.is_null()) {
1369 Time now = system_state_->clock()->GetWallclockTime();
1370 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1371 if (time_spent_attempting_p2p.InSeconds() < 0) {
1372 LOG(ERROR) << "Time spent attempting p2p is negative"
1373 << " - disallowing p2p.";
1374 return false;
1375 }
1376 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1377 LOG(INFO) << "Time spent attempting p2p is "
1378 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1379 << " which is greater than "
1380 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1381 kMaxP2PAttemptTimeSeconds))
1382 << " - disallowing p2p.";
1383 return false;
1384 }
1385 }
1386
1387 return true;
1388}
1389
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001390} // namespace chromeos_update_engine