blob: 4b5b5fd2072dadb123f51b99fef6b3e40c3e73ba [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080016
17#include "update_engine/payload_state.h"
18
Jay Srinivasan08262882012-12-28 19:29:43 -080019#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070020#include <string>
Jay Srinivasan08262882012-12-28 19:29:43 -080021
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080022#include <base/logging.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070023#include <base/strings/string_util.h>
24#include <base/strings/stringprintf.h>
Alex Deymoa2591792015-11-17 00:39:40 -030025#include <metrics/metrics_library.h>
Gilad Arnold1f847232014-04-07 12:07:49 -070026#include <policy/device_policy.h>
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080027
Alex Deymo39910dc2015-11-09 17:04:30 -080028#include "update_engine/common/clock.h"
29#include "update_engine/common/constants.h"
Alex Deymoe88e9fe2016-02-03 16:38:00 -080030#include "update_engine/common/error_code_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080031#include "update_engine/common/hardware_interface.h"
32#include "update_engine/common/prefs.h"
33#include "update_engine/common/utils.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080034#include "update_engine/metrics_utils.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070035#include "update_engine/omaha_request_params.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080036#include "update_engine/payload_consumer/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070037#include "update_engine/system_state.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080038
Jay Srinivasan08262882012-12-28 19:29:43 -080039using base::Time;
40using base::TimeDelta;
41using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080042using std::string;
43
44namespace chromeos_update_engine {
45
David Zeuthen9a017f22013-04-11 16:10:26 -070046const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
47
Jay Srinivasan08262882012-12-28 19:29:43 -080048// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070049static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080050
Jay Srinivasan08262882012-12-28 19:29:43 -080051// We want to randomize retry attempts after the backoff by +/- 6 hours.
52static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080053
Jay Srinivasan19409b72013-04-12 19:23:36 -070054PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070055 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070056 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070057 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070058 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070059 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070060 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070061 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070062 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070063 attempt_num_bytes_downloaded_(0),
64 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070065 attempt_type_(AttemptType::kUpdate) {
66 for (int i = 0; i <= kNumDownloadSources; i++)
67 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070068}
69
70bool PayloadState::Initialize(SystemState* system_state) {
71 system_state_ = system_state;
72 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070073 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080074 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080075 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070076 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080077 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080078 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070079 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080080 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070081 LoadUpdateTimestampStart();
82 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
83 // being called before it. Don't reorder.
84 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070085 for (int i = 0; i < kNumDownloadSources; i++) {
86 DownloadSource source = static_cast<DownloadSource>(i);
87 LoadCurrentBytesDownloaded(source);
88 LoadTotalBytesDownloaded(source);
89 }
Chris Sosabe45bef2013-04-09 18:25:12 -070090 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070091 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070092 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070093 LoadP2PFirstAttemptTimestamp();
94 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080095 return true;
96}
97
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080098void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080099 // Always store the latest response.
100 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800101
Jay Srinivasan53173b92013-05-17 17:13:01 -0700102 // Compute the candidate URLs first as they are used to calculate the
103 // response signature so that a change in enterprise policy for
104 // HTTP downloads being enabled or not could be honored as soon as the
105 // next update check happens.
106 ComputeCandidateUrls();
107
Jay Srinivasan08262882012-12-28 19:29:43 -0800108 // Check if the "signature" of this response (i.e. the fields we care about)
109 // has changed.
110 string new_response_signature = CalculateResponseSignature();
111 bool has_response_changed = (response_signature_ != new_response_signature);
112
113 // If the response has changed, we should persist the new signature and
114 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800115 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800116 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700117 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800118 SetResponseSignature(new_response_signature);
119 ResetPersistedState();
120 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800121 }
122
Jay Srinivasan08262882012-12-28 19:29:43 -0800123 // This is the earliest point at which we can validate whether the URL index
124 // we loaded from the persisted state is a valid value. If the response
125 // hasn't changed but the URL index is invalid, it's indicative of some
126 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700127 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800128 LOG(INFO) << "Resetting all payload state as the url index seems to have "
129 "been tampered with";
130 ResetPersistedState();
131 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800132 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700133
134 // Update the current download source which depends on the latest value of
135 // the response.
136 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800137}
138
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700139void PayloadState::SetUsingP2PForDownloading(bool value) {
140 using_p2p_for_downloading_ = value;
141 // Update the current download source which depends on whether we are
142 // using p2p or not.
143 UpdateCurrentDownloadSource();
144}
145
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800146void PayloadState::DownloadComplete() {
147 LOG(INFO) << "Payload downloaded successfully";
148 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700149 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800150}
151
152void PayloadState::DownloadProgress(size_t count) {
153 if (count == 0)
154 return;
155
David Zeuthen9a017f22013-04-11 16:10:26 -0700156 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700157 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700158
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800159 // We've received non-zero bytes from a recent download operation. Since our
160 // URL failure count is meant to penalize a URL only for consecutive
161 // failures, downloading bytes successfully means we should reset the failure
162 // count (as we know at least that the URL is working). In future, we can
163 // design this to be more sophisticated to check for more intelligent failure
164 // patterns, but right now, even 1 byte downloaded will mark the URL to be
165 // good unless it hits 10 (or configured number of) consecutive failures
166 // again.
167
168 if (GetUrlFailureCount() == 0)
169 return;
170
171 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
172 << " to 0 as we received " << count << " bytes successfully";
173 SetUrlFailureCount(0);
174}
175
David Zeuthenafed4a12014-04-09 15:28:44 -0700176void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700177 // Flush previous state from abnormal attempt failure, if any.
178 ReportAndClearPersistedAttemptMetrics();
179
David Zeuthenafed4a12014-04-09 15:28:44 -0700180 attempt_type_ = attempt_type;
181
David Zeuthen33bae492014-02-25 16:16:18 -0800182 ClockInterface *clock = system_state_->clock();
183 attempt_start_time_boot_ = clock->GetBootTime();
184 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800185 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700186
187 metrics::ConnectionType type;
188 NetworkConnectionType network_connection_type;
189 NetworkTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700190 ConnectionManagerInterface* connection_manager =
191 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700192 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700193 &tethering)) {
194 LOG(ERROR) << "Failed to determine connection type.";
195 type = metrics::ConnectionType::kUnknown;
196 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800197 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700198 }
199 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700200
201 if (attempt_type == AttemptType::kUpdate)
202 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800203}
204
Chris Sosabe45bef2013-04-09 18:25:12 -0700205void PayloadState::UpdateResumed() {
206 LOG(INFO) << "Resuming an update that was previously started.";
207 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700208 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700209}
210
Jay Srinivasan19409b72013-04-12 19:23:36 -0700211void PayloadState::UpdateRestarted() {
212 LOG(INFO) << "Starting a new update";
213 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700214 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700215 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700216}
217
David Zeuthen9a017f22013-04-11 16:10:26 -0700218void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700219 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700220 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700221 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800222
David Zeuthen96197df2014-04-16 12:22:39 -0700223 switch (attempt_type_) {
224 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700225 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700226 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700227 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700228 break;
229
230 case AttemptType::kRollback:
231 metrics::ReportRollbackMetrics(system_state_,
232 metrics::RollbackResult::kSuccess);
233 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700234 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700235
236 // Reset the number of responses seen since it counts from the last
237 // successful update, e.g. now.
238 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700239
240 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700241}
242
David Zeuthena99981f2013-04-29 13:42:47 -0700243void PayloadState::UpdateFailed(ErrorCode error) {
244 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800245 LOG(INFO) << "Updating payload state for error code: " << base_error
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800246 << " (" << utils::ErrorCodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800247
Jay Srinivasan53173b92013-05-17 17:13:01 -0700248 if (candidate_urls_.size() == 0) {
249 // This means we got this error even before we got a valid Omaha response
250 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800251 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800252 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
253 return;
254 }
255
David Zeuthen96197df2014-04-16 12:22:39 -0700256 switch (attempt_type_) {
257 case AttemptType::kUpdate:
258 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700259 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700260 break;
261
262 case AttemptType::kRollback:
263 metrics::ReportRollbackMetrics(system_state_,
264 metrics::RollbackResult::kFailed);
265 break;
266 }
David Zeuthen33bae492014-02-25 16:16:18 -0800267
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800268 switch (base_error) {
269 // Errors which are good indicators of a problem with a particular URL or
270 // the protocol used in the URL or entities in the communication channel
271 // (e.g. proxies). We should try the next available URL in the next update
272 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700273 case ErrorCode::kPayloadHashMismatchError:
274 case ErrorCode::kPayloadSizeMismatchError:
275 case ErrorCode::kDownloadPayloadVerificationError:
276 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
277 case ErrorCode::kSignedDeltaPayloadExpectedError:
278 case ErrorCode::kDownloadInvalidMetadataMagicString:
279 case ErrorCode::kDownloadSignatureMissingInManifest:
280 case ErrorCode::kDownloadManifestParseError:
281 case ErrorCode::kDownloadMetadataSignatureError:
282 case ErrorCode::kDownloadMetadataSignatureVerificationError:
283 case ErrorCode::kDownloadMetadataSignatureMismatch:
284 case ErrorCode::kDownloadOperationHashVerificationError:
285 case ErrorCode::kDownloadOperationExecutionError:
286 case ErrorCode::kDownloadOperationHashMismatch:
287 case ErrorCode::kDownloadInvalidMetadataSize:
288 case ErrorCode::kDownloadInvalidMetadataSignature:
289 case ErrorCode::kDownloadOperationHashMissingError:
290 case ErrorCode::kDownloadMetadataSignatureMissingError:
291 case ErrorCode::kPayloadMismatchedType:
292 case ErrorCode::kUnsupportedMajorPayloadVersion:
293 case ErrorCode::kUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800294 IncrementUrlIndex();
295 break;
296
297 // Errors which seem to be just transient network/communication related
298 // failures and do not indicate any inherent problem with the URL itself.
299 // So, we should keep the current URL but just increment the
300 // failure count to give it more chances. This way, while we maximize our
301 // chances of downloading from the URLs that appear earlier in the response
302 // (because download from a local server URL that appears earlier in a
303 // response is preferable than downloading from the next URL which could be
304 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700305
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700306 case ErrorCode::kError:
307 case ErrorCode::kDownloadTransferError:
308 case ErrorCode::kDownloadWriteError:
309 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700310 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800311 IncrementFailureCount();
312 break;
313
314 // Errors which are not specific to a URL and hence shouldn't result in
315 // the URL being penalized. This can happen in two cases:
316 // 1. We haven't started downloading anything: These errors don't cost us
317 // anything in terms of actual payload bytes, so we should just do the
318 // regular retries at the next update check.
319 // 2. We have successfully downloaded the payload: In this case, the
320 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800321 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800322 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700323 case ErrorCode::kOmahaRequestError:
324 case ErrorCode::kOmahaResponseHandlerError:
325 case ErrorCode::kPostinstallRunnerError:
326 case ErrorCode::kFilesystemCopierError:
327 case ErrorCode::kInstallDeviceOpenError:
328 case ErrorCode::kKernelDeviceOpenError:
329 case ErrorCode::kDownloadNewPartitionInfoError:
330 case ErrorCode::kNewRootfsVerificationError:
331 case ErrorCode::kNewKernelVerificationError:
332 case ErrorCode::kPostinstallBootedFromFirmwareB:
333 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
334 case ErrorCode::kOmahaRequestEmptyResponseError:
335 case ErrorCode::kOmahaRequestXMLParseError:
336 case ErrorCode::kOmahaResponseInvalid:
337 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
338 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
339 case ErrorCode::kOmahaUpdateDeferredForBackoff:
340 case ErrorCode::kPostinstallPowerwashError:
341 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400342 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700343 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800344 case ErrorCode::kUserCanceled:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800345 LOG(INFO) << "Not incrementing URL index or failure count for this error";
346 break;
347
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700348 case ErrorCode::kSuccess: // success code
349 case ErrorCode::kUmaReportedMax: // not an error code
350 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
351 case ErrorCode::kDevModeFlag: // not an error code
352 case ErrorCode::kResumedFlag: // not an error code
353 case ErrorCode::kTestImageFlag: // not an error code
354 case ErrorCode::kTestOmahaUrlFlag: // not an error code
355 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800356 // These shouldn't happen. Enumerating these explicitly here so that we
357 // can let the compiler warn about new error codes that are added to
358 // action_processor.h but not added here.
359 LOG(WARNING) << "Unexpected error code for UpdateFailed";
360 break;
361
362 // Note: Not adding a default here so as to let the compiler warn us of
363 // any new enums that were added in the .h but not listed in this switch.
364 }
365}
366
Jay Srinivasan08262882012-12-28 19:29:43 -0800367bool PayloadState::ShouldBackoffDownload() {
368 if (response_.disable_payload_backoff) {
369 LOG(INFO) << "Payload backoff logic is disabled. "
370 "Can proceed with the download";
371 return false;
372 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700373 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700374 LOG(INFO) << "Payload backoff logic is disabled because download "
375 << "will happen from local peer (via p2p).";
376 return false;
377 }
378 if (system_state_->request_params()->interactive()) {
379 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
380 return false;
381 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800382 if (response_.is_delta_payload) {
383 // If delta payloads fail, we want to fallback quickly to full payloads as
384 // they are more likely to succeed. Exponential backoffs would greatly
385 // slow down the fallback to full payloads. So we don't backoff for delta
386 // payloads.
387 LOG(INFO) << "No backoffs for delta payloads. "
388 << "Can proceed with the download";
389 return false;
390 }
391
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700392 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800393 // Backoffs are needed only for official builds. We do not want any delays
394 // or update failures due to backoffs during testing or development.
395 LOG(INFO) << "No backoffs for test/dev images. "
396 << "Can proceed with the download";
397 return false;
398 }
399
400 if (backoff_expiry_time_.is_null()) {
401 LOG(INFO) << "No backoff expiry time has been set. "
402 << "Can proceed with the download";
403 return false;
404 }
405
406 if (backoff_expiry_time_ < Time::Now()) {
407 LOG(INFO) << "The backoff expiry time ("
408 << utils::ToString(backoff_expiry_time_)
409 << ") has elapsed. Can proceed with the download";
410 return false;
411 }
412
413 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
414 << utils::ToString(backoff_expiry_time_);
415 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800416}
417
Chris Sosaaa18e162013-06-20 13:20:30 -0700418void PayloadState::Rollback() {
419 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700420 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700421}
422
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800423void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700424 // Update the payload attempt number for both payload types: full and delta.
425 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
426}
427
428void PayloadState::IncrementFullPayloadAttemptNumber() {
429 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800430 if (response_.is_delta_payload) {
431 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
432 return;
433 }
434
Alex Deymo29b51d92013-07-09 15:26:24 -0700435 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700436 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800437 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800438}
439
440void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800441 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700442 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800443 LOG(INFO) << "Incrementing the URL index for next attempt";
444 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800445 } else {
446 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700447 << "0 as we only have " << candidate_urls_.size()
448 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800449 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700450 IncrementPayloadAttemptNumber();
451 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800452 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800453
David Zeuthencc6f9962013-04-18 11:57:24 -0700454 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700455 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700456 SetUrlSwitchCount(url_switch_count_ + 1);
457
Jay Srinivasan08262882012-12-28 19:29:43 -0800458 // Whenever we update the URL index, we should also clear the URL failure
459 // count so we can start over fresh for the new URL.
460 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800461}
462
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800463void PayloadState::IncrementFailureCount() {
464 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800465 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800466 LOG(INFO) << "Incrementing the URL failure count";
467 SetUrlFailureCount(next_url_failure_count);
468 } else {
469 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
470 << ". Trying next available URL";
471 IncrementUrlIndex();
472 }
473}
474
Jay Srinivasan08262882012-12-28 19:29:43 -0800475void PayloadState::UpdateBackoffExpiryTime() {
476 if (response_.disable_payload_backoff) {
477 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
478 SetBackoffExpiryTime(Time());
479 return;
480 }
481
Alex Deymo820cc702013-06-28 15:43:46 -0700482 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800483 SetBackoffExpiryTime(Time());
484 return;
485 }
486
487 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700488 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800489 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700490 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700491 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800492
493 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
494 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700495 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800496
497 // The number of days is the minimum of 2 raised to (payload_attempt_number
498 // - 1) or kMaxBackoffDays.
499 num_days = min(num_days << power, kMaxBackoffDays);
500
501 // We don't want all retries to happen exactly at the same time when
502 // retrying after backoff. So add some random minutes to fuzz.
503 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
504 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
505 TimeDelta::FromMinutes(fuzz_minutes);
506 LOG(INFO) << "Incrementing the backoff expiry time by "
507 << utils::FormatTimeDelta(next_backoff_interval);
508 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
509}
510
Jay Srinivasan19409b72013-04-12 19:23:36 -0700511void PayloadState::UpdateCurrentDownloadSource() {
512 current_download_source_ = kNumDownloadSources;
513
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700514 if (using_p2p_for_downloading_) {
515 current_download_source_ = kDownloadSourceHttpPeer;
516 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700517 string current_url = candidate_urls_[GetUrlIndex()];
Alex Vakulenko0103c362016-01-20 07:56:15 -0800518 if (base::StartsWith(current_url, "https://",
519 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700520 current_download_source_ = kDownloadSourceHttpsServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800521 } else if (base::StartsWith(current_url, "http://",
522 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700523 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800524 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700525 }
526
527 LOG(INFO) << "Current download source: "
528 << utils::ToString(current_download_source_);
529}
530
531void PayloadState::UpdateBytesDownloaded(size_t count) {
532 SetCurrentBytesDownloaded(
533 current_download_source_,
534 GetCurrentBytesDownloaded(current_download_source_) + count,
535 false);
536 SetTotalBytesDownloaded(
537 current_download_source_,
538 GetTotalBytesDownloaded(current_download_source_) + count,
539 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800540
541 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700542}
543
David Zeuthen33bae492014-02-25 16:16:18 -0800544PayloadType PayloadState::CalculatePayloadType() {
545 PayloadType payload_type;
546 OmahaRequestParams* params = system_state_->request_params();
547 if (response_.is_delta_payload) {
548 payload_type = kPayloadTypeDelta;
549 } else if (params->delta_okay()) {
550 payload_type = kPayloadTypeFull;
551 } else { // Full payload, delta was not allowed by request.
552 payload_type = kPayloadTypeForcedFull;
553 }
554 return payload_type;
555}
556
557// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
558// metrics if the attempt ends abnormally, e.g. if the update_engine
559// process crashes or the device is rebooted. See
560// http://crbug.com/357676
561void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
562 int attempt_number = GetPayloadAttemptNumber();
563
564 PayloadType payload_type = CalculatePayloadType();
565
566 int64_t payload_size = response_.size;
567
568 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
569
570 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700571 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
572 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800573 attempt_start_time_monotonic_;
574
575 int64_t payload_download_speed_bps = 0;
576 int64_t usec = duration_uptime.InMicroseconds();
577 if (usec > 0) {
578 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
579 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
580 payload_download_speed_bps = static_cast<int64_t>(bps);
581 }
582
583 DownloadSource download_source = current_download_source_;
584
585 metrics::DownloadErrorCode payload_download_error_code =
586 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700587 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800588 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800589
590 // Add additional detail to AttemptResult
591 switch (attempt_result) {
592 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800593 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800594 break;
595
596 case metrics::AttemptResult::kInternalError:
597 internal_error_code = code;
598 break;
599
600 // Explicit fall-through for cases where we do not have additional
601 // detail. We avoid the default keyword to force people adding new
602 // AttemptResult values to visit this code and examine whether
603 // additional detail is needed.
604 case metrics::AttemptResult::kUpdateSucceeded:
605 case metrics::AttemptResult::kMetadataMalformed:
606 case metrics::AttemptResult::kOperationMalformed:
607 case metrics::AttemptResult::kOperationExecutionError:
608 case metrics::AttemptResult::kMetadataVerificationFailed:
609 case metrics::AttemptResult::kPayloadVerificationFailed:
610 case metrics::AttemptResult::kVerificationFailed:
611 case metrics::AttemptResult::kPostInstallFailed:
612 case metrics::AttemptResult::kAbnormalTermination:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800613 case metrics::AttemptResult::kUpdateCanceled:
David Zeuthen33bae492014-02-25 16:16:18 -0800614 case metrics::AttemptResult::kNumConstants:
615 case metrics::AttemptResult::kUnset:
616 break;
617 }
618
619 metrics::ReportUpdateAttemptMetrics(system_state_,
620 attempt_number,
621 payload_type,
622 duration,
623 duration_uptime,
624 payload_size,
625 payload_bytes_downloaded,
626 payload_download_speed_bps,
627 download_source,
628 attempt_result,
629 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700630 payload_download_error_code,
631 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800632}
633
David Zeuthen4e1d1492014-04-25 13:12:27 -0700634void PayloadState::PersistAttemptMetrics() {
635 // TODO(zeuthen): For now we only persist whether an attempt was in
636 // progress and not values/metrics related to the attempt. This
637 // means that when this happens, of all the UpdateEngine.Attempt.*
638 // metrics, only UpdateEngine.Attempt.Result is reported (with the
639 // value |kAbnormalTermination|). In the future we might want to
640 // persist more data so we can report other metrics in the
641 // UpdateEngine.Attempt.* namespace when this happens.
642 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
643}
644
645void PayloadState::ClearPersistedAttemptMetrics() {
646 prefs_->Delete(kPrefsAttemptInProgress);
647}
648
649void PayloadState::ReportAndClearPersistedAttemptMetrics() {
650 bool attempt_in_progress = false;
651 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
652 return;
653 if (!attempt_in_progress)
654 return;
655
656 metrics::ReportAbnormallyTerminatedUpdateAttemptMetrics(system_state_);
657
658 ClearPersistedAttemptMetrics();
659}
660
David Zeuthen33bae492014-02-25 16:16:18 -0800661void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700662 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800663
664 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800665 int64_t total_bytes_by_source[kNumDownloadSources];
666 int64_t successful_bytes = 0;
667 int64_t total_bytes = 0;
668 int64_t successful_mbs = 0;
669 int64_t total_mbs = 0;
670
Jay Srinivasan19409b72013-04-12 19:23:36 -0700671 for (int i = 0; i < kNumDownloadSources; i++) {
672 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800673 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700674
David Zeuthen44848602013-06-24 13:32:14 -0700675 // Only consider this download source (and send byte counts) as
676 // having been used if we downloaded a non-trivial amount of bytes
677 // (e.g. at least 1 MiB) that contributed to the final success of
678 // the update. Otherwise we're going to end up with a lot of
679 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700680
David Zeuthen33bae492014-02-25 16:16:18 -0800681 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800682 successful_bytes += bytes;
683 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700684 SetCurrentBytesDownloaded(source, 0, true);
685
David Zeuthen33bae492014-02-25 16:16:18 -0800686 bytes = GetTotalBytesDownloaded(source);
687 total_bytes_by_source[i] = bytes;
688 total_bytes += bytes;
689 total_mbs += bytes / kNumBytesInOneMiB;
690 SetTotalBytesDownloaded(source, 0, true);
691 }
692
693 int download_overhead_percentage = 0;
694 if (successful_bytes > 0) {
695 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
696 successful_bytes;
697 }
698
699 int url_switch_count = static_cast<int>(url_switch_count_);
700
701 int reboot_count = GetNumReboots();
702
703 SetNumReboots(0);
704
705 TimeDelta duration = GetUpdateDuration();
David Zeuthen33bae492014-02-25 16:16:18 -0800706
707 prefs_->Delete(kPrefsUpdateTimestampStart);
708 prefs_->Delete(kPrefsUpdateDurationUptime);
709
710 PayloadType payload_type = CalculatePayloadType();
711
712 int64_t payload_size = response_.size;
713
714 int attempt_count = GetPayloadAttemptNumber();
715
716 int updates_abandoned_count = num_responses_seen_ - 1;
717
718 metrics::ReportSuccessfulUpdateMetrics(system_state_,
719 attempt_count,
720 updates_abandoned_count,
721 payload_type,
722 payload_size,
723 total_bytes_by_source,
724 download_overhead_percentage,
725 duration,
726 reboot_count,
727 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700728}
729
730void PayloadState::UpdateNumReboots() {
731 // We only update the reboot count when the system has been detected to have
732 // been rebooted.
733 if (!system_state_->system_rebooted()) {
734 return;
735 }
736
737 SetNumReboots(GetNumReboots() + 1);
738}
739
740void PayloadState::SetNumReboots(uint32_t num_reboots) {
741 CHECK(prefs_);
742 num_reboots_ = num_reboots;
743 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
744 LOG(INFO) << "Number of Reboots during current update attempt = "
745 << num_reboots_;
746}
747
Jay Srinivasan08262882012-12-28 19:29:43 -0800748void PayloadState::ResetPersistedState() {
749 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700750 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800751 SetUrlIndex(0);
752 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700753 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700754 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700755 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700756 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700757 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700758 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700759 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700760 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700761 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700762 SetScatteringWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700763}
764
765void PayloadState::ResetRollbackVersion() {
766 CHECK(powerwash_safe_prefs_);
767 rollback_version_ = "";
768 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700769}
770
771void PayloadState::ResetDownloadSourcesOnNewUpdate() {
772 for (int i = 0; i < kNumDownloadSources; i++) {
773 DownloadSource source = static_cast<DownloadSource>(i);
774 SetCurrentBytesDownloaded(source, 0, true);
775 // Note: Not resetting the TotalBytesDownloaded as we want that metric
776 // to count the bytes downloaded across various update attempts until
777 // we have successfully applied the update.
778 }
779}
780
Chris Sosab3dcdb32013-09-04 15:22:12 -0700781int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700782 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700783 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700784 return 0;
785
786 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700787 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700788 return 0;
789
790 if (stored_value < 0) {
791 LOG(ERROR) << key << ": Invalid value (" << stored_value
792 << ") in persisted state. Defaulting to 0";
793 return 0;
794 }
795
796 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800797}
798
799string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700800 string response_sign = base::StringPrintf(
801 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800802
Jay Srinivasan53173b92013-05-17 17:13:01 -0700803 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700804 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
805 static_cast<int>(i),
806 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800807
Alex Vakulenko75039d72014-03-25 12:36:28 -0700808 response_sign += base::StringPrintf(
809 "Payload Size = %ju\n"
810 "Payload Sha256 Hash = %s\n"
811 "Metadata Size = %ju\n"
812 "Metadata Signature = %s\n"
813 "Is Delta Payload = %d\n"
814 "Max Failure Count Per Url = %d\n"
815 "Disable Payload Backoff = %d\n",
816 static_cast<uintmax_t>(response_.size),
817 response_.hash.c_str(),
818 static_cast<uintmax_t>(response_.metadata_size),
819 response_.metadata_signature.c_str(),
820 response_.is_delta_payload,
821 response_.max_failure_count_per_url,
822 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800823 return response_sign;
824}
825
826void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800827 CHECK(prefs_);
828 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800829 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
830 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
831 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800832 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800833}
834
Jay Srinivasan19409b72013-04-12 19:23:36 -0700835void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800836 CHECK(prefs_);
837 response_signature_ = response_signature;
838 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
839 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
840}
841
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800842void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700843 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800844}
845
Alex Deymo820cc702013-06-28 15:43:46 -0700846void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700847 SetFullPayloadAttemptNumber(GetPersistedValue(
848 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700849}
850
851void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800852 CHECK(prefs_);
853 payload_attempt_number_ = payload_attempt_number;
854 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
855 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
856}
857
Alex Deymo820cc702013-06-28 15:43:46 -0700858void PayloadState::SetFullPayloadAttemptNumber(
859 int full_payload_attempt_number) {
860 CHECK(prefs_);
861 full_payload_attempt_number_ = full_payload_attempt_number;
862 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
863 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
864 full_payload_attempt_number_);
865}
866
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800867void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700868 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800869}
870
871void PayloadState::SetUrlIndex(uint32_t url_index) {
872 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800873 url_index_ = url_index;
874 LOG(INFO) << "Current URL Index = " << url_index_;
875 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700876
877 // Also update the download source, which is purely dependent on the
878 // current URL index alone.
879 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800880}
881
Gilad Arnold519cfc72014-10-02 10:34:54 -0700882void PayloadState::LoadScatteringWaitPeriod() {
883 SetScatteringWaitPeriod(
884 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
885}
886
Alex Deymof329b932014-10-30 01:37:48 -0700887void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700888 CHECK(prefs_);
889 scattering_wait_period_ = wait_period;
890 LOG(INFO) << "Scattering Wait Period (seconds) = "
891 << scattering_wait_period_.InSeconds();
892 if (scattering_wait_period_.InSeconds() > 0) {
893 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
894 scattering_wait_period_.InSeconds());
895 } else {
896 prefs_->Delete(kPrefsWallClockWaitPeriod);
897 }
898}
899
David Zeuthencc6f9962013-04-18 11:57:24 -0700900void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700901 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700902}
903
904void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
905 CHECK(prefs_);
906 url_switch_count_ = url_switch_count;
907 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
908 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
909}
910
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800911void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700912 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800913}
914
915void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
916 CHECK(prefs_);
917 url_failure_count_ = url_failure_count;
918 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
919 << ")'s Failure Count = " << url_failure_count_;
920 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800921}
922
Jay Srinivasan08262882012-12-28 19:29:43 -0800923void PayloadState::LoadBackoffExpiryTime() {
924 CHECK(prefs_);
925 int64_t stored_value;
926 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
927 return;
928
929 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
930 return;
931
932 Time stored_time = Time::FromInternalValue(stored_value);
933 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
934 LOG(ERROR) << "Invalid backoff expiry time ("
935 << utils::ToString(stored_time)
936 << ") in persisted state. Resetting.";
937 stored_time = Time();
938 }
939 SetBackoffExpiryTime(stored_time);
940}
941
942void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
943 CHECK(prefs_);
944 backoff_expiry_time_ = new_time;
945 LOG(INFO) << "Backoff Expiry Time = "
946 << utils::ToString(backoff_expiry_time_);
947 prefs_->SetInt64(kPrefsBackoffExpiryTime,
948 backoff_expiry_time_.ToInternalValue());
949}
950
David Zeuthen9a017f22013-04-11 16:10:26 -0700951TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700952 Time end_time = update_timestamp_end_.is_null()
953 ? system_state_->clock()->GetWallclockTime() :
954 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700955 return end_time - update_timestamp_start_;
956}
957
958void PayloadState::LoadUpdateTimestampStart() {
959 int64_t stored_value;
960 Time stored_time;
961
962 CHECK(prefs_);
963
David Zeuthenf413fe52013-04-22 14:04:39 -0700964 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700965
966 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
967 // The preference missing is not unexpected - in that case, just
968 // use the current time as start time
969 stored_time = now;
970 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
971 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
972 stored_time = now;
973 } else {
974 stored_time = Time::FromInternalValue(stored_value);
975 }
976
977 // Sanity check: If the time read from disk is in the future
978 // (modulo some slack to account for possible NTP drift
979 // adjustments), something is fishy and we should report and
980 // reset.
981 TimeDelta duration_according_to_stored_time = now - stored_time;
982 if (duration_according_to_stored_time < -kDurationSlack) {
983 LOG(ERROR) << "The UpdateTimestampStart value ("
984 << utils::ToString(stored_time)
985 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700986 << utils::FormatTimeDelta(duration_according_to_stored_time)
987 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700988 stored_time = now;
989 }
990
991 SetUpdateTimestampStart(stored_time);
992}
993
994void PayloadState::SetUpdateTimestampStart(const Time& value) {
995 CHECK(prefs_);
996 update_timestamp_start_ = value;
997 prefs_->SetInt64(kPrefsUpdateTimestampStart,
998 update_timestamp_start_.ToInternalValue());
999 LOG(INFO) << "Update Timestamp Start = "
1000 << utils::ToString(update_timestamp_start_);
1001}
1002
1003void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1004 update_timestamp_end_ = value;
1005 LOG(INFO) << "Update Timestamp End = "
1006 << utils::ToString(update_timestamp_end_);
1007}
1008
1009TimeDelta PayloadState::GetUpdateDurationUptime() {
1010 return update_duration_uptime_;
1011}
1012
1013void PayloadState::LoadUpdateDurationUptime() {
1014 int64_t stored_value;
1015 TimeDelta stored_delta;
1016
1017 CHECK(prefs_);
1018
1019 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1020 // The preference missing is not unexpected - in that case, just
1021 // we'll use zero as the delta
1022 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1023 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1024 stored_delta = TimeDelta::FromSeconds(0);
1025 } else {
1026 stored_delta = TimeDelta::FromInternalValue(stored_value);
1027 }
1028
1029 // Sanity-check: Uptime can never be greater than the wall-clock
1030 // difference (modulo some slack). If it is, report and reset
1031 // to the wall-clock difference.
1032 TimeDelta diff = GetUpdateDuration() - stored_delta;
1033 if (diff < -kDurationSlack) {
1034 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001035 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001036 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001037 << utils::FormatTimeDelta(diff)
1038 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001039 stored_delta = update_duration_current_;
1040 }
1041
1042 SetUpdateDurationUptime(stored_delta);
1043}
1044
Chris Sosabe45bef2013-04-09 18:25:12 -07001045void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001046 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001047}
1048
1049void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001050 CHECK(powerwash_safe_prefs_);
1051 string rollback_version;
1052 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1053 &rollback_version)) {
1054 SetRollbackVersion(rollback_version);
1055 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001056}
1057
1058void PayloadState::SetRollbackVersion(const string& rollback_version) {
1059 CHECK(powerwash_safe_prefs_);
1060 LOG(INFO) << "Blacklisting version "<< rollback_version;
1061 rollback_version_ = rollback_version;
1062 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001063}
1064
David Zeuthen9a017f22013-04-11 16:10:26 -07001065void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1066 const Time& timestamp,
1067 bool use_logging) {
1068 CHECK(prefs_);
1069 update_duration_uptime_ = value;
1070 update_duration_uptime_timestamp_ = timestamp;
1071 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1072 update_duration_uptime_.ToInternalValue());
1073 if (use_logging) {
1074 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001075 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001076 }
1077}
1078
1079void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001080 Time now = system_state_->clock()->GetMonotonicTime();
1081 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001082}
1083
1084void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001085 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001086 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1087 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1088 // We're frequently called so avoid logging this write
1089 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1090}
1091
Jay Srinivasan19409b72013-04-12 19:23:36 -07001092string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1093 return prefix + "-from-" + utils::ToString(source);
1094}
1095
1096void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1097 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001098 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001099}
1100
1101void PayloadState::SetCurrentBytesDownloaded(
1102 DownloadSource source,
1103 uint64_t current_bytes_downloaded,
1104 bool log) {
1105 CHECK(prefs_);
1106
1107 if (source >= kNumDownloadSources)
1108 return;
1109
1110 // Update the in-memory value.
1111 current_bytes_downloaded_[source] = current_bytes_downloaded;
1112
1113 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1114 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1115 LOG_IF(INFO, log) << "Current bytes downloaded for "
1116 << utils::ToString(source) << " = "
1117 << GetCurrentBytesDownloaded(source);
1118}
1119
1120void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1121 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001122 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001123}
1124
1125void PayloadState::SetTotalBytesDownloaded(
1126 DownloadSource source,
1127 uint64_t total_bytes_downloaded,
1128 bool log) {
1129 CHECK(prefs_);
1130
1131 if (source >= kNumDownloadSources)
1132 return;
1133
1134 // Update the in-memory value.
1135 total_bytes_downloaded_[source] = total_bytes_downloaded;
1136
1137 // Persist.
1138 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1139 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1140 LOG_IF(INFO, log) << "Total bytes downloaded for "
1141 << utils::ToString(source) << " = "
1142 << GetTotalBytesDownloaded(source);
1143}
1144
David Zeuthena573d6f2013-06-14 16:13:36 -07001145void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001146 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001147}
1148
1149void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1150 CHECK(prefs_);
1151 num_responses_seen_ = num_responses_seen;
1152 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1153 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1154}
1155
Jay Srinivasan53173b92013-05-17 17:13:01 -07001156void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001157 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001158
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001159 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001160 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001161 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001162 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1163 } else {
1164 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1165 http_url_ok = true;
1166 }
1167
1168 candidate_urls_.clear();
1169 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1170 string candidate_url = response_.payload_urls[i];
Alex Vakulenko0103c362016-01-20 07:56:15 -08001171 if (base::StartsWith(candidate_url, "http://",
1172 base::CompareCase::INSENSITIVE_ASCII) &&
1173 !http_url_ok) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -07001174 continue;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001175 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001176 candidate_urls_.push_back(candidate_url);
1177 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1178 << ": " << candidate_url;
1179 }
1180
1181 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1182 << "out of " << response_.payload_urls.size() << " URLs supplied";
1183}
1184
David Zeuthene4c58bf2013-06-18 17:26:50 -07001185void PayloadState::CreateSystemUpdatedMarkerFile() {
1186 CHECK(prefs_);
1187 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1188 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1189}
1190
1191void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1192 // Send |time_to_reboot| as a UMA stat.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001193 string metric = metrics::kMetricTimeToRebootMinutes;
David Zeuthen33bae492014-02-25 16:16:18 -08001194 system_state_->metrics_lib()->SendToUMA(metric,
1195 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001196 0, // min: 0 minute
1197 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001198 kNumDefaultUmaBuckets);
1199 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1200 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001201}
1202
1203void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001204 // Flush previous state from abnormal attempt failure, if any.
1205 ReportAndClearPersistedAttemptMetrics();
1206
Alex Deymo569c4242013-07-24 12:01:01 -07001207 // Avoid the UpdateEngineStarted actions if this is not the first time we
1208 // run the update engine since reboot.
1209 if (!system_state_->system_rebooted())
1210 return;
1211
David Zeuthene4c58bf2013-06-18 17:26:50 -07001212 // Figure out if we just booted into a new update
1213 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1214 int64_t stored_value;
1215 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1216 Time system_updated_at = Time::FromInternalValue(stored_value);
1217 if (!system_updated_at.is_null()) {
1218 TimeDelta time_to_reboot =
1219 system_state_->clock()->GetWallclockTime() - system_updated_at;
1220 if (time_to_reboot.ToInternalValue() < 0) {
1221 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1222 << utils::ToString(system_updated_at);
1223 } else {
1224 BootedIntoUpdate(time_to_reboot);
1225 }
1226 }
1227 }
1228 prefs_->Delete(kPrefsSystemUpdatedMarker);
1229 }
Alex Deymo42432912013-07-12 20:21:15 -07001230 // Check if it is needed to send metrics about a failed reboot into a new
1231 // version.
1232 ReportFailedBootIfNeeded();
1233}
1234
1235void PayloadState::ReportFailedBootIfNeeded() {
1236 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1237 // payload was marked as ready immediately before the last reboot, and we
1238 // need to check if such payload successfully rebooted or not.
1239 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001240 int64_t installed_from = 0;
1241 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001242 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1243 return;
1244 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001245 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1246 // partition number. We are now using slot numbers (0 or 1) instead, so
1247 // the following comparison will not match if we are comparing an old
1248 // partition number against a new slot number, which is the correct outcome
1249 // since we successfully booted the new update in that case. If the boot
1250 // failed, we will read this value from the same version, so it will always
1251 // be compatible.
1252 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001253 // A reboot was pending, but the chromebook is again in the same
1254 // BootDevice where the update was installed from.
1255 int64_t target_attempt;
1256 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1257 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1258 "TargetVersionInstalledFrom was present.";
1259 target_attempt = 1;
1260 }
1261
1262 // Report the UMA metric of the current boot failure.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001263 string metric = metrics::kMetricFailedUpdateCount;
David Zeuthen33bae492014-02-25 16:16:18 -08001264 LOG(INFO) << "Uploading " << target_attempt
1265 << " (count) for metric " << metric;
1266 system_state_->metrics_lib()->SendToUMA(
1267 metric,
1268 target_attempt,
1269 1, // min value
1270 50, // max value
1271 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001272 } else {
1273 prefs_->Delete(kPrefsTargetVersionAttempt);
1274 prefs_->Delete(kPrefsTargetVersionUniqueId);
1275 }
1276 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1277 }
1278}
1279
1280void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1281 // Expect to boot into the new partition in the next reboot setting the
1282 // TargetVersion* flags in the Prefs.
1283 string stored_target_version_uid;
1284 string target_version_id;
1285 string target_partition;
1286 int64_t target_attempt;
1287
1288 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1289 prefs_->GetString(kPrefsTargetVersionUniqueId,
1290 &stored_target_version_uid) &&
1291 stored_target_version_uid == target_version_uid) {
1292 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1293 target_attempt = 0;
1294 } else {
1295 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1296 target_attempt = 0;
1297 }
1298 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1299
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001300 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001301 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001302}
1303
1304void PayloadState::ResetUpdateStatus() {
1305 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1306 // rebooted the next boot is not flagged as failed to rebooted into the
1307 // new applied payload.
1308 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1309
1310 // Also decrement the attempt number if it exists.
1311 int64_t target_attempt;
1312 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001313 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001314}
1315
David Zeuthendcba8092013-08-06 12:16:35 -07001316int PayloadState::GetP2PNumAttempts() {
1317 return p2p_num_attempts_;
1318}
1319
1320void PayloadState::SetP2PNumAttempts(int value) {
1321 p2p_num_attempts_ = value;
1322 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1323 CHECK(prefs_);
1324 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1325}
1326
1327void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001328 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001329}
1330
1331Time PayloadState::GetP2PFirstAttemptTimestamp() {
1332 return p2p_first_attempt_timestamp_;
1333}
1334
1335void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1336 p2p_first_attempt_timestamp_ = time;
1337 LOG(INFO) << "p2p First Attempt Timestamp = "
1338 << utils::ToString(p2p_first_attempt_timestamp_);
1339 CHECK(prefs_);
1340 int64_t stored_value = time.ToInternalValue();
1341 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1342}
1343
1344void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001345 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001346 Time stored_time = Time::FromInternalValue(stored_value);
1347 SetP2PFirstAttemptTimestamp(stored_time);
1348}
1349
1350void PayloadState::P2PNewAttempt() {
1351 CHECK(prefs_);
1352 // Set timestamp, if it hasn't been set already
1353 if (p2p_first_attempt_timestamp_.is_null()) {
1354 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1355 }
1356 // Increase number of attempts
1357 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1358}
1359
1360bool PayloadState::P2PAttemptAllowed() {
1361 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1362 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1363 << " which is greater than "
1364 << kMaxP2PAttempts
1365 << " - disallowing p2p.";
1366 return false;
1367 }
1368
1369 if (!p2p_first_attempt_timestamp_.is_null()) {
1370 Time now = system_state_->clock()->GetWallclockTime();
1371 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1372 if (time_spent_attempting_p2p.InSeconds() < 0) {
1373 LOG(ERROR) << "Time spent attempting p2p is negative"
1374 << " - disallowing p2p.";
1375 return false;
1376 }
1377 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1378 LOG(INFO) << "Time spent attempting p2p is "
1379 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1380 << " which is greater than "
1381 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1382 kMaxP2PAttemptTimeSeconds))
1383 << " - disallowing p2p.";
1384 return false;
1385 }
1386 }
1387
1388 return true;
1389}
1390
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001391} // namespace chromeos_update_engine