blob: d7ccee5e433d3a21f033869f55dab7e2847ef349 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080016
17#include "update_engine/payload_state.h"
18
Jay Srinivasan08262882012-12-28 19:29:43 -080019#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070020#include <string>
Jay Srinivasan08262882012-12-28 19:29:43 -080021
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080022#include <base/logging.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070023#include <base/strings/string_util.h>
24#include <base/strings/stringprintf.h>
Alex Deymoa2591792015-11-17 00:39:40 -030025#include <metrics/metrics_library.h>
Gilad Arnold1f847232014-04-07 12:07:49 -070026#include <policy/device_policy.h>
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080027
Alex Deymo39910dc2015-11-09 17:04:30 -080028#include "update_engine/common/clock.h"
29#include "update_engine/common/constants.h"
30#include "update_engine/common/hardware_interface.h"
31#include "update_engine/common/prefs.h"
32#include "update_engine/common/utils.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080033#include "update_engine/metrics_utils.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070034#include "update_engine/omaha_request_params.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080035#include "update_engine/payload_consumer/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070036#include "update_engine/system_state.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080037
Jay Srinivasan08262882012-12-28 19:29:43 -080038using base::Time;
39using base::TimeDelta;
40using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080041using std::string;
42
43namespace chromeos_update_engine {
44
David Zeuthen9a017f22013-04-11 16:10:26 -070045const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
46
Jay Srinivasan08262882012-12-28 19:29:43 -080047// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070048static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080049
Jay Srinivasan08262882012-12-28 19:29:43 -080050// We want to randomize retry attempts after the backoff by +/- 6 hours.
51static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080052
Jay Srinivasan19409b72013-04-12 19:23:36 -070053PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070054 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070055 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070056 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070057 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070058 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070059 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070060 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070061 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070062 attempt_num_bytes_downloaded_(0),
63 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070064 attempt_type_(AttemptType::kUpdate) {
65 for (int i = 0; i <= kNumDownloadSources; i++)
66 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070067}
68
69bool PayloadState::Initialize(SystemState* system_state) {
70 system_state_ = system_state;
71 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070072 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080073 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080074 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070075 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080076 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080077 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070078 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080079 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070080 LoadUpdateTimestampStart();
81 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
82 // being called before it. Don't reorder.
83 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070084 for (int i = 0; i < kNumDownloadSources; i++) {
85 DownloadSource source = static_cast<DownloadSource>(i);
86 LoadCurrentBytesDownloaded(source);
87 LoadTotalBytesDownloaded(source);
88 }
Chris Sosabe45bef2013-04-09 18:25:12 -070089 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070090 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070091 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070092 LoadP2PFirstAttemptTimestamp();
93 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080094 return true;
95}
96
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080097void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080098 // Always store the latest response.
99 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800100
Jay Srinivasan53173b92013-05-17 17:13:01 -0700101 // Compute the candidate URLs first as they are used to calculate the
102 // response signature so that a change in enterprise policy for
103 // HTTP downloads being enabled or not could be honored as soon as the
104 // next update check happens.
105 ComputeCandidateUrls();
106
Jay Srinivasan08262882012-12-28 19:29:43 -0800107 // Check if the "signature" of this response (i.e. the fields we care about)
108 // has changed.
109 string new_response_signature = CalculateResponseSignature();
110 bool has_response_changed = (response_signature_ != new_response_signature);
111
112 // If the response has changed, we should persist the new signature and
113 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800114 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800115 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700116 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800117 SetResponseSignature(new_response_signature);
118 ResetPersistedState();
119 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800120 }
121
Jay Srinivasan08262882012-12-28 19:29:43 -0800122 // This is the earliest point at which we can validate whether the URL index
123 // we loaded from the persisted state is a valid value. If the response
124 // hasn't changed but the URL index is invalid, it's indicative of some
125 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700126 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800127 LOG(INFO) << "Resetting all payload state as the url index seems to have "
128 "been tampered with";
129 ResetPersistedState();
130 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800131 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700132
133 // Update the current download source which depends on the latest value of
134 // the response.
135 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800136}
137
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700138void PayloadState::SetUsingP2PForDownloading(bool value) {
139 using_p2p_for_downloading_ = value;
140 // Update the current download source which depends on whether we are
141 // using p2p or not.
142 UpdateCurrentDownloadSource();
143}
144
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800145void PayloadState::DownloadComplete() {
146 LOG(INFO) << "Payload downloaded successfully";
147 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700148 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800149}
150
151void PayloadState::DownloadProgress(size_t count) {
152 if (count == 0)
153 return;
154
David Zeuthen9a017f22013-04-11 16:10:26 -0700155 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700156 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700157
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800158 // We've received non-zero bytes from a recent download operation. Since our
159 // URL failure count is meant to penalize a URL only for consecutive
160 // failures, downloading bytes successfully means we should reset the failure
161 // count (as we know at least that the URL is working). In future, we can
162 // design this to be more sophisticated to check for more intelligent failure
163 // patterns, but right now, even 1 byte downloaded will mark the URL to be
164 // good unless it hits 10 (or configured number of) consecutive failures
165 // again.
166
167 if (GetUrlFailureCount() == 0)
168 return;
169
170 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
171 << " to 0 as we received " << count << " bytes successfully";
172 SetUrlFailureCount(0);
173}
174
David Zeuthenafed4a12014-04-09 15:28:44 -0700175void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700176 // Flush previous state from abnormal attempt failure, if any.
177 ReportAndClearPersistedAttemptMetrics();
178
David Zeuthenafed4a12014-04-09 15:28:44 -0700179 attempt_type_ = attempt_type;
180
David Zeuthen33bae492014-02-25 16:16:18 -0800181 ClockInterface *clock = system_state_->clock();
182 attempt_start_time_boot_ = clock->GetBootTime();
183 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800184 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700185
186 metrics::ConnectionType type;
187 NetworkConnectionType network_connection_type;
188 NetworkTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700189 ConnectionManagerInterface* connection_manager =
190 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700191 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700192 &tethering)) {
193 LOG(ERROR) << "Failed to determine connection type.";
194 type = metrics::ConnectionType::kUnknown;
195 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800196 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700197 }
198 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700199
200 if (attempt_type == AttemptType::kUpdate)
201 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800202}
203
Chris Sosabe45bef2013-04-09 18:25:12 -0700204void PayloadState::UpdateResumed() {
205 LOG(INFO) << "Resuming an update that was previously started.";
206 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700207 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700208}
209
Jay Srinivasan19409b72013-04-12 19:23:36 -0700210void PayloadState::UpdateRestarted() {
211 LOG(INFO) << "Starting a new update";
212 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700213 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700214 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700215}
216
David Zeuthen9a017f22013-04-11 16:10:26 -0700217void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700218 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700219 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700220 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800221
David Zeuthen96197df2014-04-16 12:22:39 -0700222 switch (attempt_type_) {
223 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700224 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700225 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700226 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700227 break;
228
229 case AttemptType::kRollback:
230 metrics::ReportRollbackMetrics(system_state_,
231 metrics::RollbackResult::kSuccess);
232 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700233 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700234
235 // Reset the number of responses seen since it counts from the last
236 // successful update, e.g. now.
237 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700238
239 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700240}
241
David Zeuthena99981f2013-04-29 13:42:47 -0700242void PayloadState::UpdateFailed(ErrorCode error) {
243 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800244 LOG(INFO) << "Updating payload state for error code: " << base_error
245 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800246
Jay Srinivasan53173b92013-05-17 17:13:01 -0700247 if (candidate_urls_.size() == 0) {
248 // This means we got this error even before we got a valid Omaha response
249 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800250 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800251 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
252 return;
253 }
254
David Zeuthen96197df2014-04-16 12:22:39 -0700255 switch (attempt_type_) {
256 case AttemptType::kUpdate:
257 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700258 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700259 break;
260
261 case AttemptType::kRollback:
262 metrics::ReportRollbackMetrics(system_state_,
263 metrics::RollbackResult::kFailed);
264 break;
265 }
David Zeuthen33bae492014-02-25 16:16:18 -0800266
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800267 switch (base_error) {
268 // Errors which are good indicators of a problem with a particular URL or
269 // the protocol used in the URL or entities in the communication channel
270 // (e.g. proxies). We should try the next available URL in the next update
271 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700272 case ErrorCode::kPayloadHashMismatchError:
273 case ErrorCode::kPayloadSizeMismatchError:
274 case ErrorCode::kDownloadPayloadVerificationError:
275 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
276 case ErrorCode::kSignedDeltaPayloadExpectedError:
277 case ErrorCode::kDownloadInvalidMetadataMagicString:
278 case ErrorCode::kDownloadSignatureMissingInManifest:
279 case ErrorCode::kDownloadManifestParseError:
280 case ErrorCode::kDownloadMetadataSignatureError:
281 case ErrorCode::kDownloadMetadataSignatureVerificationError:
282 case ErrorCode::kDownloadMetadataSignatureMismatch:
283 case ErrorCode::kDownloadOperationHashVerificationError:
284 case ErrorCode::kDownloadOperationExecutionError:
285 case ErrorCode::kDownloadOperationHashMismatch:
286 case ErrorCode::kDownloadInvalidMetadataSize:
287 case ErrorCode::kDownloadInvalidMetadataSignature:
288 case ErrorCode::kDownloadOperationHashMissingError:
289 case ErrorCode::kDownloadMetadataSignatureMissingError:
290 case ErrorCode::kPayloadMismatchedType:
291 case ErrorCode::kUnsupportedMajorPayloadVersion:
292 case ErrorCode::kUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800293 IncrementUrlIndex();
294 break;
295
296 // Errors which seem to be just transient network/communication related
297 // failures and do not indicate any inherent problem with the URL itself.
298 // So, we should keep the current URL but just increment the
299 // failure count to give it more chances. This way, while we maximize our
300 // chances of downloading from the URLs that appear earlier in the response
301 // (because download from a local server URL that appears earlier in a
302 // response is preferable than downloading from the next URL which could be
303 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700304
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700305 case ErrorCode::kError:
306 case ErrorCode::kDownloadTransferError:
307 case ErrorCode::kDownloadWriteError:
308 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700309 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800310 IncrementFailureCount();
311 break;
312
313 // Errors which are not specific to a URL and hence shouldn't result in
314 // the URL being penalized. This can happen in two cases:
315 // 1. We haven't started downloading anything: These errors don't cost us
316 // anything in terms of actual payload bytes, so we should just do the
317 // regular retries at the next update check.
318 // 2. We have successfully downloaded the payload: In this case, the
319 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800320 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800321 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700322 case ErrorCode::kOmahaRequestError:
323 case ErrorCode::kOmahaResponseHandlerError:
324 case ErrorCode::kPostinstallRunnerError:
325 case ErrorCode::kFilesystemCopierError:
326 case ErrorCode::kInstallDeviceOpenError:
327 case ErrorCode::kKernelDeviceOpenError:
328 case ErrorCode::kDownloadNewPartitionInfoError:
329 case ErrorCode::kNewRootfsVerificationError:
330 case ErrorCode::kNewKernelVerificationError:
331 case ErrorCode::kPostinstallBootedFromFirmwareB:
332 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
333 case ErrorCode::kOmahaRequestEmptyResponseError:
334 case ErrorCode::kOmahaRequestXMLParseError:
335 case ErrorCode::kOmahaResponseInvalid:
336 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
337 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
338 case ErrorCode::kOmahaUpdateDeferredForBackoff:
339 case ErrorCode::kPostinstallPowerwashError:
340 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400341 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700342 case ErrorCode::kFilesystemVerifierError:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800343 LOG(INFO) << "Not incrementing URL index or failure count for this error";
344 break;
345
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700346 case ErrorCode::kSuccess: // success code
347 case ErrorCode::kUmaReportedMax: // not an error code
348 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
349 case ErrorCode::kDevModeFlag: // not an error code
350 case ErrorCode::kResumedFlag: // not an error code
351 case ErrorCode::kTestImageFlag: // not an error code
352 case ErrorCode::kTestOmahaUrlFlag: // not an error code
353 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800354 // These shouldn't happen. Enumerating these explicitly here so that we
355 // can let the compiler warn about new error codes that are added to
356 // action_processor.h but not added here.
357 LOG(WARNING) << "Unexpected error code for UpdateFailed";
358 break;
359
360 // Note: Not adding a default here so as to let the compiler warn us of
361 // any new enums that were added in the .h but not listed in this switch.
362 }
363}
364
Jay Srinivasan08262882012-12-28 19:29:43 -0800365bool PayloadState::ShouldBackoffDownload() {
366 if (response_.disable_payload_backoff) {
367 LOG(INFO) << "Payload backoff logic is disabled. "
368 "Can proceed with the download";
369 return false;
370 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700371 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700372 LOG(INFO) << "Payload backoff logic is disabled because download "
373 << "will happen from local peer (via p2p).";
374 return false;
375 }
376 if (system_state_->request_params()->interactive()) {
377 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
378 return false;
379 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800380 if (response_.is_delta_payload) {
381 // If delta payloads fail, we want to fallback quickly to full payloads as
382 // they are more likely to succeed. Exponential backoffs would greatly
383 // slow down the fallback to full payloads. So we don't backoff for delta
384 // payloads.
385 LOG(INFO) << "No backoffs for delta payloads. "
386 << "Can proceed with the download";
387 return false;
388 }
389
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700390 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800391 // Backoffs are needed only for official builds. We do not want any delays
392 // or update failures due to backoffs during testing or development.
393 LOG(INFO) << "No backoffs for test/dev images. "
394 << "Can proceed with the download";
395 return false;
396 }
397
398 if (backoff_expiry_time_.is_null()) {
399 LOG(INFO) << "No backoff expiry time has been set. "
400 << "Can proceed with the download";
401 return false;
402 }
403
404 if (backoff_expiry_time_ < Time::Now()) {
405 LOG(INFO) << "The backoff expiry time ("
406 << utils::ToString(backoff_expiry_time_)
407 << ") has elapsed. Can proceed with the download";
408 return false;
409 }
410
411 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
412 << utils::ToString(backoff_expiry_time_);
413 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800414}
415
Chris Sosaaa18e162013-06-20 13:20:30 -0700416void PayloadState::Rollback() {
417 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700418 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700419}
420
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800421void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700422 // Update the payload attempt number for both payload types: full and delta.
423 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
424}
425
426void PayloadState::IncrementFullPayloadAttemptNumber() {
427 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800428 if (response_.is_delta_payload) {
429 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
430 return;
431 }
432
Alex Deymo29b51d92013-07-09 15:26:24 -0700433 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700434 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800435 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800436}
437
438void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800439 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700440 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800441 LOG(INFO) << "Incrementing the URL index for next attempt";
442 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800443 } else {
444 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700445 << "0 as we only have " << candidate_urls_.size()
446 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800447 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700448 IncrementPayloadAttemptNumber();
449 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800450 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800451
David Zeuthencc6f9962013-04-18 11:57:24 -0700452 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700453 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700454 SetUrlSwitchCount(url_switch_count_ + 1);
455
Jay Srinivasan08262882012-12-28 19:29:43 -0800456 // Whenever we update the URL index, we should also clear the URL failure
457 // count so we can start over fresh for the new URL.
458 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800459}
460
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800461void PayloadState::IncrementFailureCount() {
462 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800463 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800464 LOG(INFO) << "Incrementing the URL failure count";
465 SetUrlFailureCount(next_url_failure_count);
466 } else {
467 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
468 << ". Trying next available URL";
469 IncrementUrlIndex();
470 }
471}
472
Jay Srinivasan08262882012-12-28 19:29:43 -0800473void PayloadState::UpdateBackoffExpiryTime() {
474 if (response_.disable_payload_backoff) {
475 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
476 SetBackoffExpiryTime(Time());
477 return;
478 }
479
Alex Deymo820cc702013-06-28 15:43:46 -0700480 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800481 SetBackoffExpiryTime(Time());
482 return;
483 }
484
485 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700486 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800487 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700488 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700489 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800490
491 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
492 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700493 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800494
495 // The number of days is the minimum of 2 raised to (payload_attempt_number
496 // - 1) or kMaxBackoffDays.
497 num_days = min(num_days << power, kMaxBackoffDays);
498
499 // We don't want all retries to happen exactly at the same time when
500 // retrying after backoff. So add some random minutes to fuzz.
501 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
502 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
503 TimeDelta::FromMinutes(fuzz_minutes);
504 LOG(INFO) << "Incrementing the backoff expiry time by "
505 << utils::FormatTimeDelta(next_backoff_interval);
506 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
507}
508
Jay Srinivasan19409b72013-04-12 19:23:36 -0700509void PayloadState::UpdateCurrentDownloadSource() {
510 current_download_source_ = kNumDownloadSources;
511
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700512 if (using_p2p_for_downloading_) {
513 current_download_source_ = kDownloadSourceHttpPeer;
514 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700515 string current_url = candidate_urls_[GetUrlIndex()];
Alex Vakulenko0103c362016-01-20 07:56:15 -0800516 if (base::StartsWith(current_url, "https://",
517 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700518 current_download_source_ = kDownloadSourceHttpsServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800519 } else if (base::StartsWith(current_url, "http://",
520 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700521 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800522 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700523 }
524
525 LOG(INFO) << "Current download source: "
526 << utils::ToString(current_download_source_);
527}
528
529void PayloadState::UpdateBytesDownloaded(size_t count) {
530 SetCurrentBytesDownloaded(
531 current_download_source_,
532 GetCurrentBytesDownloaded(current_download_source_) + count,
533 false);
534 SetTotalBytesDownloaded(
535 current_download_source_,
536 GetTotalBytesDownloaded(current_download_source_) + count,
537 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800538
539 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700540}
541
David Zeuthen33bae492014-02-25 16:16:18 -0800542PayloadType PayloadState::CalculatePayloadType() {
543 PayloadType payload_type;
544 OmahaRequestParams* params = system_state_->request_params();
545 if (response_.is_delta_payload) {
546 payload_type = kPayloadTypeDelta;
547 } else if (params->delta_okay()) {
548 payload_type = kPayloadTypeFull;
549 } else { // Full payload, delta was not allowed by request.
550 payload_type = kPayloadTypeForcedFull;
551 }
552 return payload_type;
553}
554
555// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
556// metrics if the attempt ends abnormally, e.g. if the update_engine
557// process crashes or the device is rebooted. See
558// http://crbug.com/357676
559void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
560 int attempt_number = GetPayloadAttemptNumber();
561
562 PayloadType payload_type = CalculatePayloadType();
563
564 int64_t payload_size = response_.size;
565
566 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
567
568 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700569 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
570 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800571 attempt_start_time_monotonic_;
572
573 int64_t payload_download_speed_bps = 0;
574 int64_t usec = duration_uptime.InMicroseconds();
575 if (usec > 0) {
576 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
577 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
578 payload_download_speed_bps = static_cast<int64_t>(bps);
579 }
580
581 DownloadSource download_source = current_download_source_;
582
583 metrics::DownloadErrorCode payload_download_error_code =
584 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700585 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800586 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800587
588 // Add additional detail to AttemptResult
589 switch (attempt_result) {
590 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800591 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800592 break;
593
594 case metrics::AttemptResult::kInternalError:
595 internal_error_code = code;
596 break;
597
598 // Explicit fall-through for cases where we do not have additional
599 // detail. We avoid the default keyword to force people adding new
600 // AttemptResult values to visit this code and examine whether
601 // additional detail is needed.
602 case metrics::AttemptResult::kUpdateSucceeded:
603 case metrics::AttemptResult::kMetadataMalformed:
604 case metrics::AttemptResult::kOperationMalformed:
605 case metrics::AttemptResult::kOperationExecutionError:
606 case metrics::AttemptResult::kMetadataVerificationFailed:
607 case metrics::AttemptResult::kPayloadVerificationFailed:
608 case metrics::AttemptResult::kVerificationFailed:
609 case metrics::AttemptResult::kPostInstallFailed:
610 case metrics::AttemptResult::kAbnormalTermination:
611 case metrics::AttemptResult::kNumConstants:
612 case metrics::AttemptResult::kUnset:
613 break;
614 }
615
616 metrics::ReportUpdateAttemptMetrics(system_state_,
617 attempt_number,
618 payload_type,
619 duration,
620 duration_uptime,
621 payload_size,
622 payload_bytes_downloaded,
623 payload_download_speed_bps,
624 download_source,
625 attempt_result,
626 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700627 payload_download_error_code,
628 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800629}
630
David Zeuthen4e1d1492014-04-25 13:12:27 -0700631void PayloadState::PersistAttemptMetrics() {
632 // TODO(zeuthen): For now we only persist whether an attempt was in
633 // progress and not values/metrics related to the attempt. This
634 // means that when this happens, of all the UpdateEngine.Attempt.*
635 // metrics, only UpdateEngine.Attempt.Result is reported (with the
636 // value |kAbnormalTermination|). In the future we might want to
637 // persist more data so we can report other metrics in the
638 // UpdateEngine.Attempt.* namespace when this happens.
639 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
640}
641
642void PayloadState::ClearPersistedAttemptMetrics() {
643 prefs_->Delete(kPrefsAttemptInProgress);
644}
645
646void PayloadState::ReportAndClearPersistedAttemptMetrics() {
647 bool attempt_in_progress = false;
648 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
649 return;
650 if (!attempt_in_progress)
651 return;
652
653 metrics::ReportAbnormallyTerminatedUpdateAttemptMetrics(system_state_);
654
655 ClearPersistedAttemptMetrics();
656}
657
David Zeuthen33bae492014-02-25 16:16:18 -0800658void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700659 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800660
661 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800662 int64_t total_bytes_by_source[kNumDownloadSources];
663 int64_t successful_bytes = 0;
664 int64_t total_bytes = 0;
665 int64_t successful_mbs = 0;
666 int64_t total_mbs = 0;
667
Jay Srinivasan19409b72013-04-12 19:23:36 -0700668 for (int i = 0; i < kNumDownloadSources; i++) {
669 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800670 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700671
David Zeuthen44848602013-06-24 13:32:14 -0700672 // Only consider this download source (and send byte counts) as
673 // having been used if we downloaded a non-trivial amount of bytes
674 // (e.g. at least 1 MiB) that contributed to the final success of
675 // the update. Otherwise we're going to end up with a lot of
676 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700677
David Zeuthen33bae492014-02-25 16:16:18 -0800678 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800679 successful_bytes += bytes;
680 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700681 SetCurrentBytesDownloaded(source, 0, true);
682
David Zeuthen33bae492014-02-25 16:16:18 -0800683 bytes = GetTotalBytesDownloaded(source);
684 total_bytes_by_source[i] = bytes;
685 total_bytes += bytes;
686 total_mbs += bytes / kNumBytesInOneMiB;
687 SetTotalBytesDownloaded(source, 0, true);
688 }
689
690 int download_overhead_percentage = 0;
691 if (successful_bytes > 0) {
692 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
693 successful_bytes;
694 }
695
696 int url_switch_count = static_cast<int>(url_switch_count_);
697
698 int reboot_count = GetNumReboots();
699
700 SetNumReboots(0);
701
702 TimeDelta duration = GetUpdateDuration();
David Zeuthen33bae492014-02-25 16:16:18 -0800703
704 prefs_->Delete(kPrefsUpdateTimestampStart);
705 prefs_->Delete(kPrefsUpdateDurationUptime);
706
707 PayloadType payload_type = CalculatePayloadType();
708
709 int64_t payload_size = response_.size;
710
711 int attempt_count = GetPayloadAttemptNumber();
712
713 int updates_abandoned_count = num_responses_seen_ - 1;
714
715 metrics::ReportSuccessfulUpdateMetrics(system_state_,
716 attempt_count,
717 updates_abandoned_count,
718 payload_type,
719 payload_size,
720 total_bytes_by_source,
721 download_overhead_percentage,
722 duration,
723 reboot_count,
724 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700725}
726
727void PayloadState::UpdateNumReboots() {
728 // We only update the reboot count when the system has been detected to have
729 // been rebooted.
730 if (!system_state_->system_rebooted()) {
731 return;
732 }
733
734 SetNumReboots(GetNumReboots() + 1);
735}
736
737void PayloadState::SetNumReboots(uint32_t num_reboots) {
738 CHECK(prefs_);
739 num_reboots_ = num_reboots;
740 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
741 LOG(INFO) << "Number of Reboots during current update attempt = "
742 << num_reboots_;
743}
744
Jay Srinivasan08262882012-12-28 19:29:43 -0800745void PayloadState::ResetPersistedState() {
746 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700747 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800748 SetUrlIndex(0);
749 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700750 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700751 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700752 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700753 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700754 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700755 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700756 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700757 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700758 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700759 SetScatteringWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700760}
761
762void PayloadState::ResetRollbackVersion() {
763 CHECK(powerwash_safe_prefs_);
764 rollback_version_ = "";
765 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700766}
767
768void PayloadState::ResetDownloadSourcesOnNewUpdate() {
769 for (int i = 0; i < kNumDownloadSources; i++) {
770 DownloadSource source = static_cast<DownloadSource>(i);
771 SetCurrentBytesDownloaded(source, 0, true);
772 // Note: Not resetting the TotalBytesDownloaded as we want that metric
773 // to count the bytes downloaded across various update attempts until
774 // we have successfully applied the update.
775 }
776}
777
Chris Sosab3dcdb32013-09-04 15:22:12 -0700778int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700779 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700780 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700781 return 0;
782
783 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700784 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700785 return 0;
786
787 if (stored_value < 0) {
788 LOG(ERROR) << key << ": Invalid value (" << stored_value
789 << ") in persisted state. Defaulting to 0";
790 return 0;
791 }
792
793 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800794}
795
796string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700797 string response_sign = base::StringPrintf(
798 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800799
Jay Srinivasan53173b92013-05-17 17:13:01 -0700800 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700801 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
802 static_cast<int>(i),
803 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800804
Alex Vakulenko75039d72014-03-25 12:36:28 -0700805 response_sign += base::StringPrintf(
806 "Payload Size = %ju\n"
807 "Payload Sha256 Hash = %s\n"
808 "Metadata Size = %ju\n"
809 "Metadata Signature = %s\n"
810 "Is Delta Payload = %d\n"
811 "Max Failure Count Per Url = %d\n"
812 "Disable Payload Backoff = %d\n",
813 static_cast<uintmax_t>(response_.size),
814 response_.hash.c_str(),
815 static_cast<uintmax_t>(response_.metadata_size),
816 response_.metadata_signature.c_str(),
817 response_.is_delta_payload,
818 response_.max_failure_count_per_url,
819 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800820 return response_sign;
821}
822
823void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800824 CHECK(prefs_);
825 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800826 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
827 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
828 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800829 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800830}
831
Jay Srinivasan19409b72013-04-12 19:23:36 -0700832void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800833 CHECK(prefs_);
834 response_signature_ = response_signature;
835 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
836 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
837}
838
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800839void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700840 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800841}
842
Alex Deymo820cc702013-06-28 15:43:46 -0700843void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700844 SetFullPayloadAttemptNumber(GetPersistedValue(
845 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700846}
847
848void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800849 CHECK(prefs_);
850 payload_attempt_number_ = payload_attempt_number;
851 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
852 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
853}
854
Alex Deymo820cc702013-06-28 15:43:46 -0700855void PayloadState::SetFullPayloadAttemptNumber(
856 int full_payload_attempt_number) {
857 CHECK(prefs_);
858 full_payload_attempt_number_ = full_payload_attempt_number;
859 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
860 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
861 full_payload_attempt_number_);
862}
863
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800864void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700865 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800866}
867
868void PayloadState::SetUrlIndex(uint32_t url_index) {
869 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800870 url_index_ = url_index;
871 LOG(INFO) << "Current URL Index = " << url_index_;
872 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700873
874 // Also update the download source, which is purely dependent on the
875 // current URL index alone.
876 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800877}
878
Gilad Arnold519cfc72014-10-02 10:34:54 -0700879void PayloadState::LoadScatteringWaitPeriod() {
880 SetScatteringWaitPeriod(
881 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
882}
883
Alex Deymof329b932014-10-30 01:37:48 -0700884void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700885 CHECK(prefs_);
886 scattering_wait_period_ = wait_period;
887 LOG(INFO) << "Scattering Wait Period (seconds) = "
888 << scattering_wait_period_.InSeconds();
889 if (scattering_wait_period_.InSeconds() > 0) {
890 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
891 scattering_wait_period_.InSeconds());
892 } else {
893 prefs_->Delete(kPrefsWallClockWaitPeriod);
894 }
895}
896
David Zeuthencc6f9962013-04-18 11:57:24 -0700897void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700898 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700899}
900
901void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
902 CHECK(prefs_);
903 url_switch_count_ = url_switch_count;
904 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
905 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
906}
907
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800908void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700909 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800910}
911
912void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
913 CHECK(prefs_);
914 url_failure_count_ = url_failure_count;
915 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
916 << ")'s Failure Count = " << url_failure_count_;
917 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800918}
919
Jay Srinivasan08262882012-12-28 19:29:43 -0800920void PayloadState::LoadBackoffExpiryTime() {
921 CHECK(prefs_);
922 int64_t stored_value;
923 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
924 return;
925
926 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
927 return;
928
929 Time stored_time = Time::FromInternalValue(stored_value);
930 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
931 LOG(ERROR) << "Invalid backoff expiry time ("
932 << utils::ToString(stored_time)
933 << ") in persisted state. Resetting.";
934 stored_time = Time();
935 }
936 SetBackoffExpiryTime(stored_time);
937}
938
939void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
940 CHECK(prefs_);
941 backoff_expiry_time_ = new_time;
942 LOG(INFO) << "Backoff Expiry Time = "
943 << utils::ToString(backoff_expiry_time_);
944 prefs_->SetInt64(kPrefsBackoffExpiryTime,
945 backoff_expiry_time_.ToInternalValue());
946}
947
David Zeuthen9a017f22013-04-11 16:10:26 -0700948TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700949 Time end_time = update_timestamp_end_.is_null()
950 ? system_state_->clock()->GetWallclockTime() :
951 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700952 return end_time - update_timestamp_start_;
953}
954
955void PayloadState::LoadUpdateTimestampStart() {
956 int64_t stored_value;
957 Time stored_time;
958
959 CHECK(prefs_);
960
David Zeuthenf413fe52013-04-22 14:04:39 -0700961 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700962
963 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
964 // The preference missing is not unexpected - in that case, just
965 // use the current time as start time
966 stored_time = now;
967 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
968 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
969 stored_time = now;
970 } else {
971 stored_time = Time::FromInternalValue(stored_value);
972 }
973
974 // Sanity check: If the time read from disk is in the future
975 // (modulo some slack to account for possible NTP drift
976 // adjustments), something is fishy and we should report and
977 // reset.
978 TimeDelta duration_according_to_stored_time = now - stored_time;
979 if (duration_according_to_stored_time < -kDurationSlack) {
980 LOG(ERROR) << "The UpdateTimestampStart value ("
981 << utils::ToString(stored_time)
982 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700983 << utils::FormatTimeDelta(duration_according_to_stored_time)
984 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700985 stored_time = now;
986 }
987
988 SetUpdateTimestampStart(stored_time);
989}
990
991void PayloadState::SetUpdateTimestampStart(const Time& value) {
992 CHECK(prefs_);
993 update_timestamp_start_ = value;
994 prefs_->SetInt64(kPrefsUpdateTimestampStart,
995 update_timestamp_start_.ToInternalValue());
996 LOG(INFO) << "Update Timestamp Start = "
997 << utils::ToString(update_timestamp_start_);
998}
999
1000void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1001 update_timestamp_end_ = value;
1002 LOG(INFO) << "Update Timestamp End = "
1003 << utils::ToString(update_timestamp_end_);
1004}
1005
1006TimeDelta PayloadState::GetUpdateDurationUptime() {
1007 return update_duration_uptime_;
1008}
1009
1010void PayloadState::LoadUpdateDurationUptime() {
1011 int64_t stored_value;
1012 TimeDelta stored_delta;
1013
1014 CHECK(prefs_);
1015
1016 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1017 // The preference missing is not unexpected - in that case, just
1018 // we'll use zero as the delta
1019 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1020 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1021 stored_delta = TimeDelta::FromSeconds(0);
1022 } else {
1023 stored_delta = TimeDelta::FromInternalValue(stored_value);
1024 }
1025
1026 // Sanity-check: Uptime can never be greater than the wall-clock
1027 // difference (modulo some slack). If it is, report and reset
1028 // to the wall-clock difference.
1029 TimeDelta diff = GetUpdateDuration() - stored_delta;
1030 if (diff < -kDurationSlack) {
1031 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001032 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001033 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001034 << utils::FormatTimeDelta(diff)
1035 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001036 stored_delta = update_duration_current_;
1037 }
1038
1039 SetUpdateDurationUptime(stored_delta);
1040}
1041
Chris Sosabe45bef2013-04-09 18:25:12 -07001042void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001043 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001044}
1045
1046void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001047 CHECK(powerwash_safe_prefs_);
1048 string rollback_version;
1049 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1050 &rollback_version)) {
1051 SetRollbackVersion(rollback_version);
1052 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001053}
1054
1055void PayloadState::SetRollbackVersion(const string& rollback_version) {
1056 CHECK(powerwash_safe_prefs_);
1057 LOG(INFO) << "Blacklisting version "<< rollback_version;
1058 rollback_version_ = rollback_version;
1059 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001060}
1061
David Zeuthen9a017f22013-04-11 16:10:26 -07001062void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1063 const Time& timestamp,
1064 bool use_logging) {
1065 CHECK(prefs_);
1066 update_duration_uptime_ = value;
1067 update_duration_uptime_timestamp_ = timestamp;
1068 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1069 update_duration_uptime_.ToInternalValue());
1070 if (use_logging) {
1071 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001072 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001073 }
1074}
1075
1076void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001077 Time now = system_state_->clock()->GetMonotonicTime();
1078 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001079}
1080
1081void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001082 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001083 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1084 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1085 // We're frequently called so avoid logging this write
1086 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1087}
1088
Jay Srinivasan19409b72013-04-12 19:23:36 -07001089string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1090 return prefix + "-from-" + utils::ToString(source);
1091}
1092
1093void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1094 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001095 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001096}
1097
1098void PayloadState::SetCurrentBytesDownloaded(
1099 DownloadSource source,
1100 uint64_t current_bytes_downloaded,
1101 bool log) {
1102 CHECK(prefs_);
1103
1104 if (source >= kNumDownloadSources)
1105 return;
1106
1107 // Update the in-memory value.
1108 current_bytes_downloaded_[source] = current_bytes_downloaded;
1109
1110 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1111 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1112 LOG_IF(INFO, log) << "Current bytes downloaded for "
1113 << utils::ToString(source) << " = "
1114 << GetCurrentBytesDownloaded(source);
1115}
1116
1117void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1118 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001119 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001120}
1121
1122void PayloadState::SetTotalBytesDownloaded(
1123 DownloadSource source,
1124 uint64_t total_bytes_downloaded,
1125 bool log) {
1126 CHECK(prefs_);
1127
1128 if (source >= kNumDownloadSources)
1129 return;
1130
1131 // Update the in-memory value.
1132 total_bytes_downloaded_[source] = total_bytes_downloaded;
1133
1134 // Persist.
1135 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1136 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1137 LOG_IF(INFO, log) << "Total bytes downloaded for "
1138 << utils::ToString(source) << " = "
1139 << GetTotalBytesDownloaded(source);
1140}
1141
David Zeuthena573d6f2013-06-14 16:13:36 -07001142void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001143 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001144}
1145
1146void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1147 CHECK(prefs_);
1148 num_responses_seen_ = num_responses_seen;
1149 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1150 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1151}
1152
Jay Srinivasan53173b92013-05-17 17:13:01 -07001153void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001154 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001155
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001156 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001157 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001158 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001159 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1160 } else {
1161 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1162 http_url_ok = true;
1163 }
1164
1165 candidate_urls_.clear();
1166 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1167 string candidate_url = response_.payload_urls[i];
Alex Vakulenko0103c362016-01-20 07:56:15 -08001168 if (base::StartsWith(candidate_url, "http://",
1169 base::CompareCase::INSENSITIVE_ASCII) &&
1170 !http_url_ok) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -07001171 continue;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001172 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001173 candidate_urls_.push_back(candidate_url);
1174 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1175 << ": " << candidate_url;
1176 }
1177
1178 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1179 << "out of " << response_.payload_urls.size() << " URLs supplied";
1180}
1181
David Zeuthene4c58bf2013-06-18 17:26:50 -07001182void PayloadState::CreateSystemUpdatedMarkerFile() {
1183 CHECK(prefs_);
1184 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1185 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1186}
1187
1188void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1189 // Send |time_to_reboot| as a UMA stat.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001190 string metric = metrics::kMetricTimeToRebootMinutes;
David Zeuthen33bae492014-02-25 16:16:18 -08001191 system_state_->metrics_lib()->SendToUMA(metric,
1192 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001193 0, // min: 0 minute
1194 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001195 kNumDefaultUmaBuckets);
1196 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1197 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001198}
1199
1200void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001201 // Flush previous state from abnormal attempt failure, if any.
1202 ReportAndClearPersistedAttemptMetrics();
1203
Alex Deymo569c4242013-07-24 12:01:01 -07001204 // Avoid the UpdateEngineStarted actions if this is not the first time we
1205 // run the update engine since reboot.
1206 if (!system_state_->system_rebooted())
1207 return;
1208
David Zeuthene4c58bf2013-06-18 17:26:50 -07001209 // Figure out if we just booted into a new update
1210 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1211 int64_t stored_value;
1212 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1213 Time system_updated_at = Time::FromInternalValue(stored_value);
1214 if (!system_updated_at.is_null()) {
1215 TimeDelta time_to_reboot =
1216 system_state_->clock()->GetWallclockTime() - system_updated_at;
1217 if (time_to_reboot.ToInternalValue() < 0) {
1218 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1219 << utils::ToString(system_updated_at);
1220 } else {
1221 BootedIntoUpdate(time_to_reboot);
1222 }
1223 }
1224 }
1225 prefs_->Delete(kPrefsSystemUpdatedMarker);
1226 }
Alex Deymo42432912013-07-12 20:21:15 -07001227 // Check if it is needed to send metrics about a failed reboot into a new
1228 // version.
1229 ReportFailedBootIfNeeded();
1230}
1231
1232void PayloadState::ReportFailedBootIfNeeded() {
1233 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1234 // payload was marked as ready immediately before the last reboot, and we
1235 // need to check if such payload successfully rebooted or not.
1236 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001237 int64_t installed_from = 0;
1238 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001239 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1240 return;
1241 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001242 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1243 // partition number. We are now using slot numbers (0 or 1) instead, so
1244 // the following comparison will not match if we are comparing an old
1245 // partition number against a new slot number, which is the correct outcome
1246 // since we successfully booted the new update in that case. If the boot
1247 // failed, we will read this value from the same version, so it will always
1248 // be compatible.
1249 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001250 // A reboot was pending, but the chromebook is again in the same
1251 // BootDevice where the update was installed from.
1252 int64_t target_attempt;
1253 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1254 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1255 "TargetVersionInstalledFrom was present.";
1256 target_attempt = 1;
1257 }
1258
1259 // Report the UMA metric of the current boot failure.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001260 string metric = metrics::kMetricFailedUpdateCount;
David Zeuthen33bae492014-02-25 16:16:18 -08001261 LOG(INFO) << "Uploading " << target_attempt
1262 << " (count) for metric " << metric;
1263 system_state_->metrics_lib()->SendToUMA(
1264 metric,
1265 target_attempt,
1266 1, // min value
1267 50, // max value
1268 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001269 } else {
1270 prefs_->Delete(kPrefsTargetVersionAttempt);
1271 prefs_->Delete(kPrefsTargetVersionUniqueId);
1272 }
1273 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1274 }
1275}
1276
1277void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1278 // Expect to boot into the new partition in the next reboot setting the
1279 // TargetVersion* flags in the Prefs.
1280 string stored_target_version_uid;
1281 string target_version_id;
1282 string target_partition;
1283 int64_t target_attempt;
1284
1285 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1286 prefs_->GetString(kPrefsTargetVersionUniqueId,
1287 &stored_target_version_uid) &&
1288 stored_target_version_uid == target_version_uid) {
1289 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1290 target_attempt = 0;
1291 } else {
1292 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1293 target_attempt = 0;
1294 }
1295 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1296
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001297 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001298 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001299}
1300
1301void PayloadState::ResetUpdateStatus() {
1302 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1303 // rebooted the next boot is not flagged as failed to rebooted into the
1304 // new applied payload.
1305 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1306
1307 // Also decrement the attempt number if it exists.
1308 int64_t target_attempt;
1309 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001310 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001311}
1312
David Zeuthendcba8092013-08-06 12:16:35 -07001313int PayloadState::GetP2PNumAttempts() {
1314 return p2p_num_attempts_;
1315}
1316
1317void PayloadState::SetP2PNumAttempts(int value) {
1318 p2p_num_attempts_ = value;
1319 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1320 CHECK(prefs_);
1321 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1322}
1323
1324void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001325 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001326}
1327
1328Time PayloadState::GetP2PFirstAttemptTimestamp() {
1329 return p2p_first_attempt_timestamp_;
1330}
1331
1332void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1333 p2p_first_attempt_timestamp_ = time;
1334 LOG(INFO) << "p2p First Attempt Timestamp = "
1335 << utils::ToString(p2p_first_attempt_timestamp_);
1336 CHECK(prefs_);
1337 int64_t stored_value = time.ToInternalValue();
1338 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1339}
1340
1341void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001342 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001343 Time stored_time = Time::FromInternalValue(stored_value);
1344 SetP2PFirstAttemptTimestamp(stored_time);
1345}
1346
1347void PayloadState::P2PNewAttempt() {
1348 CHECK(prefs_);
1349 // Set timestamp, if it hasn't been set already
1350 if (p2p_first_attempt_timestamp_.is_null()) {
1351 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1352 }
1353 // Increase number of attempts
1354 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1355}
1356
1357bool PayloadState::P2PAttemptAllowed() {
1358 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1359 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1360 << " which is greater than "
1361 << kMaxP2PAttempts
1362 << " - disallowing p2p.";
1363 return false;
1364 }
1365
1366 if (!p2p_first_attempt_timestamp_.is_null()) {
1367 Time now = system_state_->clock()->GetWallclockTime();
1368 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1369 if (time_spent_attempting_p2p.InSeconds() < 0) {
1370 LOG(ERROR) << "Time spent attempting p2p is negative"
1371 << " - disallowing p2p.";
1372 return false;
1373 }
1374 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1375 LOG(INFO) << "Time spent attempting p2p is "
1376 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1377 << " which is greater than "
1378 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1379 kMaxP2PAttemptTimeSeconds))
1380 << " - disallowing p2p.";
1381 return false;
1382 }
1383 }
1384
1385 return true;
1386}
1387
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001388} // namespace chromeos_update_engine