blob: aa4c73c5df0cddfc45edac66d9ae2d4c24ff3e48 [file] [log] [blame]
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/payload_state.h"
6
Jay Srinivasan08262882012-12-28 19:29:43 -08007#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -07008#include <string>
Jay Srinivasan08262882012-12-28 19:29:43 -08009
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080010#include <base/logging.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070011#include <base/strings/string_util.h>
12#include <base/strings/stringprintf.h>
Gilad Arnold1f847232014-04-07 12:07:49 -070013#include <policy/device_policy.h>
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080014
David Zeuthenf413fe52013-04-22 14:04:39 -070015#include "update_engine/clock.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070016#include "update_engine/constants.h"
Alex Deymo42432912013-07-12 20:21:15 -070017#include "update_engine/hardware_interface.h"
18#include "update_engine/install_plan.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070019#include "update_engine/omaha_request_params.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070020#include "update_engine/prefs.h"
21#include "update_engine/system_state.h"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080022#include "update_engine/utils.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080023
Jay Srinivasan08262882012-12-28 19:29:43 -080024using base::Time;
25using base::TimeDelta;
26using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080027using std::string;
28
29namespace chromeos_update_engine {
30
David Zeuthen9a017f22013-04-11 16:10:26 -070031const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
32
Jay Srinivasan08262882012-12-28 19:29:43 -080033// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070034static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080035
Jay Srinivasan08262882012-12-28 19:29:43 -080036// We want to randomize retry attempts after the backoff by +/- 6 hours.
37static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080038
Jay Srinivasan19409b72013-04-12 19:23:36 -070039PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070040 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070041 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070042 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070043 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070044 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070045 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070046 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070047 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070048 attempt_num_bytes_downloaded_(0),
49 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070050 attempt_type_(AttemptType::kUpdate) {
51 for (int i = 0; i <= kNumDownloadSources; i++)
52 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070053}
54
55bool PayloadState::Initialize(SystemState* system_state) {
56 system_state_ = system_state;
57 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070058 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080059 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080060 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070061 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080062 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080063 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070064 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080065 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070066 LoadUpdateTimestampStart();
67 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
68 // being called before it. Don't reorder.
69 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070070 for (int i = 0; i < kNumDownloadSources; i++) {
71 DownloadSource source = static_cast<DownloadSource>(i);
72 LoadCurrentBytesDownloaded(source);
73 LoadTotalBytesDownloaded(source);
74 }
Chris Sosabe45bef2013-04-09 18:25:12 -070075 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070076 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070077 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070078 LoadP2PFirstAttemptTimestamp();
79 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080080 return true;
81}
82
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080083void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080084 // Always store the latest response.
85 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080086
Jay Srinivasan53173b92013-05-17 17:13:01 -070087 // Compute the candidate URLs first as they are used to calculate the
88 // response signature so that a change in enterprise policy for
89 // HTTP downloads being enabled or not could be honored as soon as the
90 // next update check happens.
91 ComputeCandidateUrls();
92
Jay Srinivasan08262882012-12-28 19:29:43 -080093 // Check if the "signature" of this response (i.e. the fields we care about)
94 // has changed.
95 string new_response_signature = CalculateResponseSignature();
96 bool has_response_changed = (response_signature_ != new_response_signature);
97
98 // If the response has changed, we should persist the new signature and
99 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800100 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800101 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700102 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800103 SetResponseSignature(new_response_signature);
104 ResetPersistedState();
Alex Deymob33b0f02013-08-08 21:10:02 -0700105 ReportUpdatesAbandonedEventCountMetric();
Jay Srinivasan08262882012-12-28 19:29:43 -0800106 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800107 }
108
Jay Srinivasan08262882012-12-28 19:29:43 -0800109 // This is the earliest point at which we can validate whether the URL index
110 // we loaded from the persisted state is a valid value. If the response
111 // hasn't changed but the URL index is invalid, it's indicative of some
112 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700113 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800114 LOG(INFO) << "Resetting all payload state as the url index seems to have "
115 "been tampered with";
116 ResetPersistedState();
117 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800118 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700119
120 // Update the current download source which depends on the latest value of
121 // the response.
122 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800123}
124
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700125void PayloadState::SetUsingP2PForDownloading(bool value) {
126 using_p2p_for_downloading_ = value;
127 // Update the current download source which depends on whether we are
128 // using p2p or not.
129 UpdateCurrentDownloadSource();
130}
131
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800132void PayloadState::DownloadComplete() {
133 LOG(INFO) << "Payload downloaded successfully";
134 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700135 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800136}
137
138void PayloadState::DownloadProgress(size_t count) {
139 if (count == 0)
140 return;
141
David Zeuthen9a017f22013-04-11 16:10:26 -0700142 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700143 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700144
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800145 // We've received non-zero bytes from a recent download operation. Since our
146 // URL failure count is meant to penalize a URL only for consecutive
147 // failures, downloading bytes successfully means we should reset the failure
148 // count (as we know at least that the URL is working). In future, we can
149 // design this to be more sophisticated to check for more intelligent failure
150 // patterns, but right now, even 1 byte downloaded will mark the URL to be
151 // good unless it hits 10 (or configured number of) consecutive failures
152 // again.
153
154 if (GetUrlFailureCount() == 0)
155 return;
156
157 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
158 << " to 0 as we received " << count << " bytes successfully";
159 SetUrlFailureCount(0);
160}
161
David Zeuthenafed4a12014-04-09 15:28:44 -0700162void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700163 // Flush previous state from abnormal attempt failure, if any.
164 ReportAndClearPersistedAttemptMetrics();
165
David Zeuthenafed4a12014-04-09 15:28:44 -0700166 attempt_type_ = attempt_type;
167
David Zeuthen33bae492014-02-25 16:16:18 -0800168 ClockInterface *clock = system_state_->clock();
169 attempt_start_time_boot_ = clock->GetBootTime();
170 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800171 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700172
173 metrics::ConnectionType type;
174 NetworkConnectionType network_connection_type;
175 NetworkTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700176 ConnectionManagerInterface* connection_manager =
177 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700178 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700179 &tethering)) {
180 LOG(ERROR) << "Failed to determine connection type.";
181 type = metrics::ConnectionType::kUnknown;
182 } else {
183 type = utils::GetConnectionType(network_connection_type, tethering);
184 }
185 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700186
187 if (attempt_type == AttemptType::kUpdate)
188 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800189}
190
Chris Sosabe45bef2013-04-09 18:25:12 -0700191void PayloadState::UpdateResumed() {
192 LOG(INFO) << "Resuming an update that was previously started.";
193 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700194 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700195}
196
Jay Srinivasan19409b72013-04-12 19:23:36 -0700197void PayloadState::UpdateRestarted() {
198 LOG(INFO) << "Starting a new update";
199 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700200 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700201 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700202}
203
David Zeuthen9a017f22013-04-11 16:10:26 -0700204void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700205 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700206 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700207 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800208
David Zeuthen96197df2014-04-16 12:22:39 -0700209 switch (attempt_type_) {
210 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700211 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700212 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700213 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700214 break;
215
216 case AttemptType::kRollback:
217 metrics::ReportRollbackMetrics(system_state_,
218 metrics::RollbackResult::kSuccess);
219 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700220 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700221
222 // Reset the number of responses seen since it counts from the last
223 // successful update, e.g. now.
224 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700225
226 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700227}
228
David Zeuthena99981f2013-04-29 13:42:47 -0700229void PayloadState::UpdateFailed(ErrorCode error) {
230 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800231 LOG(INFO) << "Updating payload state for error code: " << base_error
232 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800233
Jay Srinivasan53173b92013-05-17 17:13:01 -0700234 if (candidate_urls_.size() == 0) {
235 // This means we got this error even before we got a valid Omaha response
236 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800237 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800238 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
239 return;
240 }
241
David Zeuthen96197df2014-04-16 12:22:39 -0700242 switch (attempt_type_) {
243 case AttemptType::kUpdate:
244 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700245 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700246 break;
247
248 case AttemptType::kRollback:
249 metrics::ReportRollbackMetrics(system_state_,
250 metrics::RollbackResult::kFailed);
251 break;
252 }
David Zeuthen33bae492014-02-25 16:16:18 -0800253
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800254 switch (base_error) {
255 // Errors which are good indicators of a problem with a particular URL or
256 // the protocol used in the URL or entities in the communication channel
257 // (e.g. proxies). We should try the next available URL in the next update
258 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700259 case ErrorCode::kPayloadHashMismatchError:
260 case ErrorCode::kPayloadSizeMismatchError:
261 case ErrorCode::kDownloadPayloadVerificationError:
262 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
263 case ErrorCode::kSignedDeltaPayloadExpectedError:
264 case ErrorCode::kDownloadInvalidMetadataMagicString:
265 case ErrorCode::kDownloadSignatureMissingInManifest:
266 case ErrorCode::kDownloadManifestParseError:
267 case ErrorCode::kDownloadMetadataSignatureError:
268 case ErrorCode::kDownloadMetadataSignatureVerificationError:
269 case ErrorCode::kDownloadMetadataSignatureMismatch:
270 case ErrorCode::kDownloadOperationHashVerificationError:
271 case ErrorCode::kDownloadOperationExecutionError:
272 case ErrorCode::kDownloadOperationHashMismatch:
273 case ErrorCode::kDownloadInvalidMetadataSize:
274 case ErrorCode::kDownloadInvalidMetadataSignature:
275 case ErrorCode::kDownloadOperationHashMissingError:
276 case ErrorCode::kDownloadMetadataSignatureMissingError:
277 case ErrorCode::kPayloadMismatchedType:
278 case ErrorCode::kUnsupportedMajorPayloadVersion:
279 case ErrorCode::kUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800280 IncrementUrlIndex();
281 break;
282
283 // Errors which seem to be just transient network/communication related
284 // failures and do not indicate any inherent problem with the URL itself.
285 // So, we should keep the current URL but just increment the
286 // failure count to give it more chances. This way, while we maximize our
287 // chances of downloading from the URLs that appear earlier in the response
288 // (because download from a local server URL that appears earlier in a
289 // response is preferable than downloading from the next URL which could be
290 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700291
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700292 case ErrorCode::kError:
293 case ErrorCode::kDownloadTransferError:
294 case ErrorCode::kDownloadWriteError:
295 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700296 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800297 IncrementFailureCount();
298 break;
299
300 // Errors which are not specific to a URL and hence shouldn't result in
301 // the URL being penalized. This can happen in two cases:
302 // 1. We haven't started downloading anything: These errors don't cost us
303 // anything in terms of actual payload bytes, so we should just do the
304 // regular retries at the next update check.
305 // 2. We have successfully downloaded the payload: In this case, the
306 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800307 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800308 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700309 case ErrorCode::kOmahaRequestError:
310 case ErrorCode::kOmahaResponseHandlerError:
311 case ErrorCode::kPostinstallRunnerError:
312 case ErrorCode::kFilesystemCopierError:
313 case ErrorCode::kInstallDeviceOpenError:
314 case ErrorCode::kKernelDeviceOpenError:
315 case ErrorCode::kDownloadNewPartitionInfoError:
316 case ErrorCode::kNewRootfsVerificationError:
317 case ErrorCode::kNewKernelVerificationError:
318 case ErrorCode::kPostinstallBootedFromFirmwareB:
319 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
320 case ErrorCode::kOmahaRequestEmptyResponseError:
321 case ErrorCode::kOmahaRequestXMLParseError:
322 case ErrorCode::kOmahaResponseInvalid:
323 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
324 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
325 case ErrorCode::kOmahaUpdateDeferredForBackoff:
326 case ErrorCode::kPostinstallPowerwashError:
327 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400328 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700329 case ErrorCode::kFilesystemVerifierError:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800330 LOG(INFO) << "Not incrementing URL index or failure count for this error";
331 break;
332
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700333 case ErrorCode::kSuccess: // success code
334 case ErrorCode::kUmaReportedMax: // not an error code
335 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
336 case ErrorCode::kDevModeFlag: // not an error code
337 case ErrorCode::kResumedFlag: // not an error code
338 case ErrorCode::kTestImageFlag: // not an error code
339 case ErrorCode::kTestOmahaUrlFlag: // not an error code
340 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800341 // These shouldn't happen. Enumerating these explicitly here so that we
342 // can let the compiler warn about new error codes that are added to
343 // action_processor.h but not added here.
344 LOG(WARNING) << "Unexpected error code for UpdateFailed";
345 break;
346
347 // Note: Not adding a default here so as to let the compiler warn us of
348 // any new enums that were added in the .h but not listed in this switch.
349 }
350}
351
Jay Srinivasan08262882012-12-28 19:29:43 -0800352bool PayloadState::ShouldBackoffDownload() {
353 if (response_.disable_payload_backoff) {
354 LOG(INFO) << "Payload backoff logic is disabled. "
355 "Can proceed with the download";
356 return false;
357 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700358 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700359 LOG(INFO) << "Payload backoff logic is disabled because download "
360 << "will happen from local peer (via p2p).";
361 return false;
362 }
363 if (system_state_->request_params()->interactive()) {
364 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
365 return false;
366 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800367 if (response_.is_delta_payload) {
368 // If delta payloads fail, we want to fallback quickly to full payloads as
369 // they are more likely to succeed. Exponential backoffs would greatly
370 // slow down the fallback to full payloads. So we don't backoff for delta
371 // payloads.
372 LOG(INFO) << "No backoffs for delta payloads. "
373 << "Can proceed with the download";
374 return false;
375 }
376
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700377 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800378 // Backoffs are needed only for official builds. We do not want any delays
379 // or update failures due to backoffs during testing or development.
380 LOG(INFO) << "No backoffs for test/dev images. "
381 << "Can proceed with the download";
382 return false;
383 }
384
385 if (backoff_expiry_time_.is_null()) {
386 LOG(INFO) << "No backoff expiry time has been set. "
387 << "Can proceed with the download";
388 return false;
389 }
390
391 if (backoff_expiry_time_ < Time::Now()) {
392 LOG(INFO) << "The backoff expiry time ("
393 << utils::ToString(backoff_expiry_time_)
394 << ") has elapsed. Can proceed with the download";
395 return false;
396 }
397
398 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
399 << utils::ToString(backoff_expiry_time_);
400 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800401}
402
Chris Sosaaa18e162013-06-20 13:20:30 -0700403void PayloadState::Rollback() {
404 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700405 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700406}
407
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800408void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700409 // Update the payload attempt number for both payload types: full and delta.
410 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Alex Deymo29b51d92013-07-09 15:26:24 -0700411
412 // Report the metric every time the value is incremented.
413 string metric = "Installer.PayloadAttemptNumber";
414 int value = GetPayloadAttemptNumber();
415
416 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
417 system_state_->metrics_lib()->SendToUMA(
418 metric,
419 value,
420 1, // min value
421 50, // max value
422 kNumDefaultUmaBuckets);
Alex Deymo820cc702013-06-28 15:43:46 -0700423}
424
425void PayloadState::IncrementFullPayloadAttemptNumber() {
426 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800427 if (response_.is_delta_payload) {
428 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
429 return;
430 }
431
Alex Deymo29b51d92013-07-09 15:26:24 -0700432 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700433 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800434 UpdateBackoffExpiryTime();
Alex Deymo29b51d92013-07-09 15:26:24 -0700435
436 // Report the metric every time the value is incremented.
437 string metric = "Installer.FullPayloadAttemptNumber";
438 int value = GetFullPayloadAttemptNumber();
439
440 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
441 system_state_->metrics_lib()->SendToUMA(
442 metric,
443 value,
444 1, // min value
445 50, // max value
446 kNumDefaultUmaBuckets);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800447}
448
449void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800450 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700451 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800452 LOG(INFO) << "Incrementing the URL index for next attempt";
453 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800454 } else {
455 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700456 << "0 as we only have " << candidate_urls_.size()
457 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800458 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700459 IncrementPayloadAttemptNumber();
460 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800461 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800462
David Zeuthencc6f9962013-04-18 11:57:24 -0700463 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700464 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700465 SetUrlSwitchCount(url_switch_count_ + 1);
466
Jay Srinivasan08262882012-12-28 19:29:43 -0800467 // Whenever we update the URL index, we should also clear the URL failure
468 // count so we can start over fresh for the new URL.
469 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800470}
471
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800472void PayloadState::IncrementFailureCount() {
473 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800474 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800475 LOG(INFO) << "Incrementing the URL failure count";
476 SetUrlFailureCount(next_url_failure_count);
477 } else {
478 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
479 << ". Trying next available URL";
480 IncrementUrlIndex();
481 }
482}
483
Jay Srinivasan08262882012-12-28 19:29:43 -0800484void PayloadState::UpdateBackoffExpiryTime() {
485 if (response_.disable_payload_backoff) {
486 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
487 SetBackoffExpiryTime(Time());
488 return;
489 }
490
Alex Deymo820cc702013-06-28 15:43:46 -0700491 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800492 SetBackoffExpiryTime(Time());
493 return;
494 }
495
496 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700497 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800498 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700499 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700500 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800501
502 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
503 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700504 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800505
506 // The number of days is the minimum of 2 raised to (payload_attempt_number
507 // - 1) or kMaxBackoffDays.
508 num_days = min(num_days << power, kMaxBackoffDays);
509
510 // We don't want all retries to happen exactly at the same time when
511 // retrying after backoff. So add some random minutes to fuzz.
512 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
513 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
514 TimeDelta::FromMinutes(fuzz_minutes);
515 LOG(INFO) << "Incrementing the backoff expiry time by "
516 << utils::FormatTimeDelta(next_backoff_interval);
517 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
518}
519
Jay Srinivasan19409b72013-04-12 19:23:36 -0700520void PayloadState::UpdateCurrentDownloadSource() {
521 current_download_source_ = kNumDownloadSources;
522
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700523 if (using_p2p_for_downloading_) {
524 current_download_source_ = kDownloadSourceHttpPeer;
525 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700526 string current_url = candidate_urls_[GetUrlIndex()];
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700527 if (base::StartsWithASCII(current_url, "https://", false))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700528 current_download_source_ = kDownloadSourceHttpsServer;
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700529 else if (base::StartsWithASCII(current_url, "http://", false))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700530 current_download_source_ = kDownloadSourceHttpServer;
531 }
532
533 LOG(INFO) << "Current download source: "
534 << utils::ToString(current_download_source_);
535}
536
537void PayloadState::UpdateBytesDownloaded(size_t count) {
538 SetCurrentBytesDownloaded(
539 current_download_source_,
540 GetCurrentBytesDownloaded(current_download_source_) + count,
541 false);
542 SetTotalBytesDownloaded(
543 current_download_source_,
544 GetTotalBytesDownloaded(current_download_source_) + count,
545 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800546
547 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700548}
549
David Zeuthen33bae492014-02-25 16:16:18 -0800550PayloadType PayloadState::CalculatePayloadType() {
551 PayloadType payload_type;
552 OmahaRequestParams* params = system_state_->request_params();
553 if (response_.is_delta_payload) {
554 payload_type = kPayloadTypeDelta;
555 } else if (params->delta_okay()) {
556 payload_type = kPayloadTypeFull;
557 } else { // Full payload, delta was not allowed by request.
558 payload_type = kPayloadTypeForcedFull;
559 }
560 return payload_type;
561}
562
563// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
564// metrics if the attempt ends abnormally, e.g. if the update_engine
565// process crashes or the device is rebooted. See
566// http://crbug.com/357676
567void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
568 int attempt_number = GetPayloadAttemptNumber();
569
570 PayloadType payload_type = CalculatePayloadType();
571
572 int64_t payload_size = response_.size;
573
574 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
575
576 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700577 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
578 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800579 attempt_start_time_monotonic_;
580
581 int64_t payload_download_speed_bps = 0;
582 int64_t usec = duration_uptime.InMicroseconds();
583 if (usec > 0) {
584 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
585 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
586 payload_download_speed_bps = static_cast<int64_t>(bps);
587 }
588
589 DownloadSource download_source = current_download_source_;
590
591 metrics::DownloadErrorCode payload_download_error_code =
592 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700593 ErrorCode internal_error_code = ErrorCode::kSuccess;
David Zeuthen33bae492014-02-25 16:16:18 -0800594 metrics::AttemptResult attempt_result = utils::GetAttemptResult(code);
595
596 // Add additional detail to AttemptResult
597 switch (attempt_result) {
598 case metrics::AttemptResult::kPayloadDownloadError:
599 payload_download_error_code = utils::GetDownloadErrorCode(code);
600 break;
601
602 case metrics::AttemptResult::kInternalError:
603 internal_error_code = code;
604 break;
605
606 // Explicit fall-through for cases where we do not have additional
607 // detail. We avoid the default keyword to force people adding new
608 // AttemptResult values to visit this code and examine whether
609 // additional detail is needed.
610 case metrics::AttemptResult::kUpdateSucceeded:
611 case metrics::AttemptResult::kMetadataMalformed:
612 case metrics::AttemptResult::kOperationMalformed:
613 case metrics::AttemptResult::kOperationExecutionError:
614 case metrics::AttemptResult::kMetadataVerificationFailed:
615 case metrics::AttemptResult::kPayloadVerificationFailed:
616 case metrics::AttemptResult::kVerificationFailed:
617 case metrics::AttemptResult::kPostInstallFailed:
618 case metrics::AttemptResult::kAbnormalTermination:
619 case metrics::AttemptResult::kNumConstants:
620 case metrics::AttemptResult::kUnset:
621 break;
622 }
623
624 metrics::ReportUpdateAttemptMetrics(system_state_,
625 attempt_number,
626 payload_type,
627 duration,
628 duration_uptime,
629 payload_size,
630 payload_bytes_downloaded,
631 payload_download_speed_bps,
632 download_source,
633 attempt_result,
634 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700635 payload_download_error_code,
636 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800637}
638
David Zeuthen4e1d1492014-04-25 13:12:27 -0700639void PayloadState::PersistAttemptMetrics() {
640 // TODO(zeuthen): For now we only persist whether an attempt was in
641 // progress and not values/metrics related to the attempt. This
642 // means that when this happens, of all the UpdateEngine.Attempt.*
643 // metrics, only UpdateEngine.Attempt.Result is reported (with the
644 // value |kAbnormalTermination|). In the future we might want to
645 // persist more data so we can report other metrics in the
646 // UpdateEngine.Attempt.* namespace when this happens.
647 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
648}
649
650void PayloadState::ClearPersistedAttemptMetrics() {
651 prefs_->Delete(kPrefsAttemptInProgress);
652}
653
654void PayloadState::ReportAndClearPersistedAttemptMetrics() {
655 bool attempt_in_progress = false;
656 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
657 return;
658 if (!attempt_in_progress)
659 return;
660
661 metrics::ReportAbnormallyTerminatedUpdateAttemptMetrics(system_state_);
662
663 ClearPersistedAttemptMetrics();
664}
665
David Zeuthen33bae492014-02-25 16:16:18 -0800666void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700667 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800668
669 // Report metrics collected from all known download sources to UMA.
670 int64_t successful_bytes_by_source[kNumDownloadSources];
671 int64_t total_bytes_by_source[kNumDownloadSources];
672 int64_t successful_bytes = 0;
673 int64_t total_bytes = 0;
674 int64_t successful_mbs = 0;
675 int64_t total_mbs = 0;
676
Jay Srinivasan19409b72013-04-12 19:23:36 -0700677 for (int i = 0; i < kNumDownloadSources; i++) {
678 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800679 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700680
David Zeuthen44848602013-06-24 13:32:14 -0700681 // Only consider this download source (and send byte counts) as
682 // having been used if we downloaded a non-trivial amount of bytes
683 // (e.g. at least 1 MiB) that contributed to the final success of
684 // the update. Otherwise we're going to end up with a lot of
685 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700686
David Zeuthen33bae492014-02-25 16:16:18 -0800687 bytes = GetCurrentBytesDownloaded(source);
688 successful_bytes_by_source[i] = bytes;
689 successful_bytes += bytes;
690 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700691 SetCurrentBytesDownloaded(source, 0, true);
692
David Zeuthen33bae492014-02-25 16:16:18 -0800693 bytes = GetTotalBytesDownloaded(source);
694 total_bytes_by_source[i] = bytes;
695 total_bytes += bytes;
696 total_mbs += bytes / kNumBytesInOneMiB;
697 SetTotalBytesDownloaded(source, 0, true);
698 }
699
700 int download_overhead_percentage = 0;
701 if (successful_bytes > 0) {
702 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
703 successful_bytes;
704 }
705
706 int url_switch_count = static_cast<int>(url_switch_count_);
707
708 int reboot_count = GetNumReboots();
709
710 SetNumReboots(0);
711
712 TimeDelta duration = GetUpdateDuration();
713 TimeDelta duration_uptime = GetUpdateDurationUptime();
714
715 prefs_->Delete(kPrefsUpdateTimestampStart);
716 prefs_->Delete(kPrefsUpdateDurationUptime);
717
718 PayloadType payload_type = CalculatePayloadType();
719
720 int64_t payload_size = response_.size;
721
722 int attempt_count = GetPayloadAttemptNumber();
723
724 int updates_abandoned_count = num_responses_seen_ - 1;
725
726 metrics::ReportSuccessfulUpdateMetrics(system_state_,
727 attempt_count,
728 updates_abandoned_count,
729 payload_type,
730 payload_size,
731 total_bytes_by_source,
732 download_overhead_percentage,
733 duration,
734 reboot_count,
735 url_switch_count);
736
737 // TODO(zeuthen): This is the old metric reporting code which is
738 // slated for removal soon. See http://crbug.com/355745 for details.
739
740 // The old metrics code is using MiB's instead of bytes to calculate
741 // the overhead which due to rounding makes the numbers slightly
742 // different.
743 download_overhead_percentage = 0;
744 if (successful_mbs > 0) {
745 download_overhead_percentage = (total_mbs - successful_mbs) * 100ULL /
746 successful_mbs;
747 }
748
749 int download_sources_used = 0;
750 for (int i = 0; i < kNumDownloadSources; i++) {
751 DownloadSource source = static_cast<DownloadSource>(i);
752 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
753 int64_t mbs;
754
755 // Only consider this download source (and send byte counts) as
756 // having been used if we downloaded a non-trivial amount of bytes
757 // (e.g. at least 1 MiB) that contributed to the final success of
758 // the update. Otherwise we're going to end up with a lot of
759 // zero-byte events in the histogram.
760
761 mbs = successful_bytes_by_source[i] / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700762 if (mbs > 0) {
David Zeuthen33bae492014-02-25 16:16:18 -0800763 metric = "Installer.SuccessfulMBsDownloadedFrom" +
764 utils::ToString(source);
David Zeuthen44848602013-06-24 13:32:14 -0700765 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
766 system_state_->metrics_lib()->SendToUMA(metric,
767 mbs,
768 0, // min
769 kMaxMiBs,
770 kNumDefaultUmaBuckets);
771 }
David Zeuthen33bae492014-02-25 16:16:18 -0800772
773 mbs = total_bytes_by_source[i] / kNumBytesInOneMiB;
774 if (mbs > 0) {
775 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
776 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
777 system_state_->metrics_lib()->SendToUMA(metric,
778 mbs,
779 0, // min
780 kMaxMiBs,
781 kNumDefaultUmaBuckets);
782 download_sources_used |= (1 << i);
783 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700784 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700785
786 metric = "Installer.DownloadSourcesUsed";
787 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
788 << " (bit flags) for metric " << metric;
Alex Deymof329b932014-10-30 01:37:48 -0700789 int num_buckets = min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700790 system_state_->metrics_lib()->SendToUMA(metric,
791 download_sources_used,
792 0, // min
793 1 << kNumDownloadSources,
794 num_buckets);
795
David Zeuthen33bae492014-02-25 16:16:18 -0800796 metric = "Installer.DownloadOverheadPercentage";
797 LOG(INFO) << "Uploading " << download_overhead_percentage
798 << "% for metric " << metric;
799 system_state_->metrics_lib()->SendToUMA(metric,
800 download_overhead_percentage,
801 0, // min: 0% overhead
802 1000, // max: 1000% overhead
803 kNumDefaultUmaBuckets);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700804
David Zeuthen33bae492014-02-25 16:16:18 -0800805 metric = "Installer.UpdateURLSwitches";
806 LOG(INFO) << "Uploading " << url_switch_count
807 << " (count) for metric " << metric;
David Zeuthencc6f9962013-04-18 11:57:24 -0700808 system_state_->metrics_lib()->SendToUMA(
809 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800810 url_switch_count,
David Zeuthencc6f9962013-04-18 11:57:24 -0700811 0, // min value
812 100, // max value
813 kNumDefaultUmaBuckets);
David Zeuthencc6f9962013-04-18 11:57:24 -0700814
David Zeuthen33bae492014-02-25 16:16:18 -0800815 metric = "Installer.UpdateNumReboots";
816 LOG(INFO) << "Uploading reboot count of " << reboot_count << " for metric "
Chris Sosabe45bef2013-04-09 18:25:12 -0700817 << metric;
818 system_state_->metrics_lib()->SendToUMA(
819 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800820 reboot_count, // sample
821 0, // min = 0.
822 50, // max
Chris Sosabe45bef2013-04-09 18:25:12 -0700823 25); // buckets
David Zeuthen33bae492014-02-25 16:16:18 -0800824
825 metric = "Installer.UpdateDurationMinutes";
826 system_state_->metrics_lib()->SendToUMA(
827 metric,
828 static_cast<int>(duration.InMinutes()),
829 1, // min: 1 minute
830 365*24*60, // max: 1 year (approx)
831 kNumDefaultUmaBuckets);
832 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
833 << " for metric " << metric;
834
835 metric = "Installer.UpdateDurationUptimeMinutes";
836 system_state_->metrics_lib()->SendToUMA(
837 metric,
838 static_cast<int>(duration_uptime.InMinutes()),
839 1, // min: 1 minute
840 30*24*60, // max: 1 month (approx)
841 kNumDefaultUmaBuckets);
842 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
843 << " for metric " << metric;
844
845 metric = "Installer.PayloadFormat";
846 system_state_->metrics_lib()->SendEnumToUMA(
847 metric,
848 payload_type,
849 kNumPayloadTypes);
850 LOG(INFO) << "Uploading " << utils::ToString(payload_type)
851 << " for metric " << metric;
852
853 metric = "Installer.AttemptsCount.Total";
854 system_state_->metrics_lib()->SendToUMA(
855 metric,
856 attempt_count,
857 1, // min
858 50, // max
859 kNumDefaultUmaBuckets);
860 LOG(INFO) << "Uploading " << attempt_count
861 << " for metric " << metric;
862
863 metric = "Installer.UpdatesAbandonedCount";
864 LOG(INFO) << "Uploading " << updates_abandoned_count
865 << " (count) for metric " << metric;
866 system_state_->metrics_lib()->SendToUMA(
867 metric,
868 updates_abandoned_count,
869 0, // min value
870 100, // max value
871 kNumDefaultUmaBuckets);
Chris Sosabe45bef2013-04-09 18:25:12 -0700872}
873
874void PayloadState::UpdateNumReboots() {
875 // We only update the reboot count when the system has been detected to have
876 // been rebooted.
877 if (!system_state_->system_rebooted()) {
878 return;
879 }
880
881 SetNumReboots(GetNumReboots() + 1);
882}
883
884void PayloadState::SetNumReboots(uint32_t num_reboots) {
885 CHECK(prefs_);
886 num_reboots_ = num_reboots;
887 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
888 LOG(INFO) << "Number of Reboots during current update attempt = "
889 << num_reboots_;
890}
891
Jay Srinivasan08262882012-12-28 19:29:43 -0800892void PayloadState::ResetPersistedState() {
893 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700894 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800895 SetUrlIndex(0);
896 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700897 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700898 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700899 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700900 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700901 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700902 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700903 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700904 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700905 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700906 SetScatteringWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700907}
908
909void PayloadState::ResetRollbackVersion() {
910 CHECK(powerwash_safe_prefs_);
911 rollback_version_ = "";
912 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700913}
914
915void PayloadState::ResetDownloadSourcesOnNewUpdate() {
916 for (int i = 0; i < kNumDownloadSources; i++) {
917 DownloadSource source = static_cast<DownloadSource>(i);
918 SetCurrentBytesDownloaded(source, 0, true);
919 // Note: Not resetting the TotalBytesDownloaded as we want that metric
920 // to count the bytes downloaded across various update attempts until
921 // we have successfully applied the update.
922 }
923}
924
Chris Sosab3dcdb32013-09-04 15:22:12 -0700925int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700926 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700927 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700928 return 0;
929
930 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700931 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700932 return 0;
933
934 if (stored_value < 0) {
935 LOG(ERROR) << key << ": Invalid value (" << stored_value
936 << ") in persisted state. Defaulting to 0";
937 return 0;
938 }
939
940 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800941}
942
943string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700944 string response_sign = base::StringPrintf(
945 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800946
Jay Srinivasan53173b92013-05-17 17:13:01 -0700947 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700948 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
949 static_cast<int>(i),
950 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800951
Alex Vakulenko75039d72014-03-25 12:36:28 -0700952 response_sign += base::StringPrintf(
953 "Payload Size = %ju\n"
954 "Payload Sha256 Hash = %s\n"
955 "Metadata Size = %ju\n"
956 "Metadata Signature = %s\n"
957 "Is Delta Payload = %d\n"
958 "Max Failure Count Per Url = %d\n"
959 "Disable Payload Backoff = %d\n",
960 static_cast<uintmax_t>(response_.size),
961 response_.hash.c_str(),
962 static_cast<uintmax_t>(response_.metadata_size),
963 response_.metadata_signature.c_str(),
964 response_.is_delta_payload,
965 response_.max_failure_count_per_url,
966 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800967 return response_sign;
968}
969
970void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800971 CHECK(prefs_);
972 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800973 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
974 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
975 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800976 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800977}
978
Jay Srinivasan19409b72013-04-12 19:23:36 -0700979void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800980 CHECK(prefs_);
981 response_signature_ = response_signature;
982 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
983 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
984}
985
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800986void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700987 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800988}
989
Alex Deymo820cc702013-06-28 15:43:46 -0700990void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700991 SetFullPayloadAttemptNumber(GetPersistedValue(
992 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700993}
994
995void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800996 CHECK(prefs_);
997 payload_attempt_number_ = payload_attempt_number;
998 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
999 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
1000}
1001
Alex Deymo820cc702013-06-28 15:43:46 -07001002void PayloadState::SetFullPayloadAttemptNumber(
1003 int full_payload_attempt_number) {
1004 CHECK(prefs_);
1005 full_payload_attempt_number_ = full_payload_attempt_number;
1006 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
1007 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
1008 full_payload_attempt_number_);
1009}
1010
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001011void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001012 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001013}
1014
1015void PayloadState::SetUrlIndex(uint32_t url_index) {
1016 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001017 url_index_ = url_index;
1018 LOG(INFO) << "Current URL Index = " << url_index_;
1019 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001020
1021 // Also update the download source, which is purely dependent on the
1022 // current URL index alone.
1023 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001024}
1025
Gilad Arnold519cfc72014-10-02 10:34:54 -07001026void PayloadState::LoadScatteringWaitPeriod() {
1027 SetScatteringWaitPeriod(
1028 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
1029}
1030
Alex Deymof329b932014-10-30 01:37:48 -07001031void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -07001032 CHECK(prefs_);
1033 scattering_wait_period_ = wait_period;
1034 LOG(INFO) << "Scattering Wait Period (seconds) = "
1035 << scattering_wait_period_.InSeconds();
1036 if (scattering_wait_period_.InSeconds() > 0) {
1037 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
1038 scattering_wait_period_.InSeconds());
1039 } else {
1040 prefs_->Delete(kPrefsWallClockWaitPeriod);
1041 }
1042}
1043
David Zeuthencc6f9962013-04-18 11:57:24 -07001044void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001045 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -07001046}
1047
1048void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
1049 CHECK(prefs_);
1050 url_switch_count_ = url_switch_count;
1051 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
1052 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
1053}
1054
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001055void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001056 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001057}
1058
1059void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
1060 CHECK(prefs_);
1061 url_failure_count_ = url_failure_count;
1062 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
1063 << ")'s Failure Count = " << url_failure_count_;
1064 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001065}
1066
Jay Srinivasan08262882012-12-28 19:29:43 -08001067void PayloadState::LoadBackoffExpiryTime() {
1068 CHECK(prefs_);
1069 int64_t stored_value;
1070 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
1071 return;
1072
1073 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
1074 return;
1075
1076 Time stored_time = Time::FromInternalValue(stored_value);
1077 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
1078 LOG(ERROR) << "Invalid backoff expiry time ("
1079 << utils::ToString(stored_time)
1080 << ") in persisted state. Resetting.";
1081 stored_time = Time();
1082 }
1083 SetBackoffExpiryTime(stored_time);
1084}
1085
1086void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
1087 CHECK(prefs_);
1088 backoff_expiry_time_ = new_time;
1089 LOG(INFO) << "Backoff Expiry Time = "
1090 << utils::ToString(backoff_expiry_time_);
1091 prefs_->SetInt64(kPrefsBackoffExpiryTime,
1092 backoff_expiry_time_.ToInternalValue());
1093}
1094
David Zeuthen9a017f22013-04-11 16:10:26 -07001095TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001096 Time end_time = update_timestamp_end_.is_null()
1097 ? system_state_->clock()->GetWallclockTime() :
1098 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001099 return end_time - update_timestamp_start_;
1100}
1101
1102void PayloadState::LoadUpdateTimestampStart() {
1103 int64_t stored_value;
1104 Time stored_time;
1105
1106 CHECK(prefs_);
1107
David Zeuthenf413fe52013-04-22 14:04:39 -07001108 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001109
1110 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1111 // The preference missing is not unexpected - in that case, just
1112 // use the current time as start time
1113 stored_time = now;
1114 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1115 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1116 stored_time = now;
1117 } else {
1118 stored_time = Time::FromInternalValue(stored_value);
1119 }
1120
1121 // Sanity check: If the time read from disk is in the future
1122 // (modulo some slack to account for possible NTP drift
1123 // adjustments), something is fishy and we should report and
1124 // reset.
1125 TimeDelta duration_according_to_stored_time = now - stored_time;
1126 if (duration_according_to_stored_time < -kDurationSlack) {
1127 LOG(ERROR) << "The UpdateTimestampStart value ("
1128 << utils::ToString(stored_time)
1129 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001130 << utils::FormatTimeDelta(duration_according_to_stored_time)
1131 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001132 stored_time = now;
1133 }
1134
1135 SetUpdateTimestampStart(stored_time);
1136}
1137
1138void PayloadState::SetUpdateTimestampStart(const Time& value) {
1139 CHECK(prefs_);
1140 update_timestamp_start_ = value;
1141 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1142 update_timestamp_start_.ToInternalValue());
1143 LOG(INFO) << "Update Timestamp Start = "
1144 << utils::ToString(update_timestamp_start_);
1145}
1146
1147void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1148 update_timestamp_end_ = value;
1149 LOG(INFO) << "Update Timestamp End = "
1150 << utils::ToString(update_timestamp_end_);
1151}
1152
1153TimeDelta PayloadState::GetUpdateDurationUptime() {
1154 return update_duration_uptime_;
1155}
1156
1157void PayloadState::LoadUpdateDurationUptime() {
1158 int64_t stored_value;
1159 TimeDelta stored_delta;
1160
1161 CHECK(prefs_);
1162
1163 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1164 // The preference missing is not unexpected - in that case, just
1165 // we'll use zero as the delta
1166 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1167 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1168 stored_delta = TimeDelta::FromSeconds(0);
1169 } else {
1170 stored_delta = TimeDelta::FromInternalValue(stored_value);
1171 }
1172
1173 // Sanity-check: Uptime can never be greater than the wall-clock
1174 // difference (modulo some slack). If it is, report and reset
1175 // to the wall-clock difference.
1176 TimeDelta diff = GetUpdateDuration() - stored_delta;
1177 if (diff < -kDurationSlack) {
1178 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001179 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001180 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001181 << utils::FormatTimeDelta(diff)
1182 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001183 stored_delta = update_duration_current_;
1184 }
1185
1186 SetUpdateDurationUptime(stored_delta);
1187}
1188
Chris Sosabe45bef2013-04-09 18:25:12 -07001189void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001190 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001191}
1192
1193void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001194 CHECK(powerwash_safe_prefs_);
1195 string rollback_version;
1196 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1197 &rollback_version)) {
1198 SetRollbackVersion(rollback_version);
1199 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001200}
1201
1202void PayloadState::SetRollbackVersion(const string& rollback_version) {
1203 CHECK(powerwash_safe_prefs_);
1204 LOG(INFO) << "Blacklisting version "<< rollback_version;
1205 rollback_version_ = rollback_version;
1206 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001207}
1208
David Zeuthen9a017f22013-04-11 16:10:26 -07001209void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1210 const Time& timestamp,
1211 bool use_logging) {
1212 CHECK(prefs_);
1213 update_duration_uptime_ = value;
1214 update_duration_uptime_timestamp_ = timestamp;
1215 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1216 update_duration_uptime_.ToInternalValue());
1217 if (use_logging) {
1218 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001219 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001220 }
1221}
1222
1223void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001224 Time now = system_state_->clock()->GetMonotonicTime();
1225 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001226}
1227
1228void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001229 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001230 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1231 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1232 // We're frequently called so avoid logging this write
1233 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1234}
1235
Jay Srinivasan19409b72013-04-12 19:23:36 -07001236string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1237 return prefix + "-from-" + utils::ToString(source);
1238}
1239
1240void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1241 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001242 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001243}
1244
1245void PayloadState::SetCurrentBytesDownloaded(
1246 DownloadSource source,
1247 uint64_t current_bytes_downloaded,
1248 bool log) {
1249 CHECK(prefs_);
1250
1251 if (source >= kNumDownloadSources)
1252 return;
1253
1254 // Update the in-memory value.
1255 current_bytes_downloaded_[source] = current_bytes_downloaded;
1256
1257 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1258 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1259 LOG_IF(INFO, log) << "Current bytes downloaded for "
1260 << utils::ToString(source) << " = "
1261 << GetCurrentBytesDownloaded(source);
1262}
1263
1264void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1265 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001266 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001267}
1268
1269void PayloadState::SetTotalBytesDownloaded(
1270 DownloadSource source,
1271 uint64_t total_bytes_downloaded,
1272 bool log) {
1273 CHECK(prefs_);
1274
1275 if (source >= kNumDownloadSources)
1276 return;
1277
1278 // Update the in-memory value.
1279 total_bytes_downloaded_[source] = total_bytes_downloaded;
1280
1281 // Persist.
1282 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1283 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1284 LOG_IF(INFO, log) << "Total bytes downloaded for "
1285 << utils::ToString(source) << " = "
1286 << GetTotalBytesDownloaded(source);
1287}
1288
David Zeuthena573d6f2013-06-14 16:13:36 -07001289void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001290 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001291}
1292
1293void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1294 CHECK(prefs_);
1295 num_responses_seen_ = num_responses_seen;
1296 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1297 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1298}
1299
Alex Deymob33b0f02013-08-08 21:10:02 -07001300void PayloadState::ReportUpdatesAbandonedEventCountMetric() {
1301 string metric = "Installer.UpdatesAbandonedEventCount";
1302 int value = num_responses_seen_ - 1;
1303
1304 // Do not send an "abandoned" event when 0 payloads were abandoned since the
1305 // last successful update.
1306 if (value == 0)
1307 return;
1308
1309 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1310 system_state_->metrics_lib()->SendToUMA(
1311 metric,
1312 value,
1313 0, // min value
1314 100, // max value
1315 kNumDefaultUmaBuckets);
1316}
1317
Jay Srinivasan53173b92013-05-17 17:13:01 -07001318void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001319 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001320
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001321 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001322 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001323 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001324 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1325 } else {
1326 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1327 http_url_ok = true;
1328 }
1329
1330 candidate_urls_.clear();
1331 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1332 string candidate_url = response_.payload_urls[i];
Alex Vakulenko6a9d3492015-06-15 12:53:22 -07001333 if (base::StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1334 continue;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001335 candidate_urls_.push_back(candidate_url);
1336 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1337 << ": " << candidate_url;
1338 }
1339
1340 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1341 << "out of " << response_.payload_urls.size() << " URLs supplied";
1342}
1343
David Zeuthene4c58bf2013-06-18 17:26:50 -07001344void PayloadState::CreateSystemUpdatedMarkerFile() {
1345 CHECK(prefs_);
1346 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1347 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1348}
1349
1350void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1351 // Send |time_to_reboot| as a UMA stat.
1352 string metric = "Installer.TimeToRebootMinutes";
1353 system_state_->metrics_lib()->SendToUMA(metric,
1354 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001355 0, // min: 0 minute
1356 30*24*60, // max: 1 month (approx)
David Zeuthene4c58bf2013-06-18 17:26:50 -07001357 kNumDefaultUmaBuckets);
1358 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1359 << " for metric " << metric;
David Zeuthen33bae492014-02-25 16:16:18 -08001360
1361 metric = metrics::kMetricTimeToRebootMinutes;
1362 system_state_->metrics_lib()->SendToUMA(metric,
1363 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001364 0, // min: 0 minute
1365 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001366 kNumDefaultUmaBuckets);
1367 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1368 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001369}
1370
1371void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001372 // Flush previous state from abnormal attempt failure, if any.
1373 ReportAndClearPersistedAttemptMetrics();
1374
Alex Deymo569c4242013-07-24 12:01:01 -07001375 // Avoid the UpdateEngineStarted actions if this is not the first time we
1376 // run the update engine since reboot.
1377 if (!system_state_->system_rebooted())
1378 return;
1379
David Zeuthene4c58bf2013-06-18 17:26:50 -07001380 // Figure out if we just booted into a new update
1381 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1382 int64_t stored_value;
1383 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1384 Time system_updated_at = Time::FromInternalValue(stored_value);
1385 if (!system_updated_at.is_null()) {
1386 TimeDelta time_to_reboot =
1387 system_state_->clock()->GetWallclockTime() - system_updated_at;
1388 if (time_to_reboot.ToInternalValue() < 0) {
1389 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1390 << utils::ToString(system_updated_at);
1391 } else {
1392 BootedIntoUpdate(time_to_reboot);
1393 }
1394 }
1395 }
1396 prefs_->Delete(kPrefsSystemUpdatedMarker);
1397 }
Alex Deymo42432912013-07-12 20:21:15 -07001398 // Check if it is needed to send metrics about a failed reboot into a new
1399 // version.
1400 ReportFailedBootIfNeeded();
1401}
1402
1403void PayloadState::ReportFailedBootIfNeeded() {
1404 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1405 // payload was marked as ready immediately before the last reboot, and we
1406 // need to check if such payload successfully rebooted or not.
1407 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001408 int64_t installed_from = 0;
1409 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001410 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1411 return;
1412 }
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001413 if (static_cast<int>(installed_from) ==
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001414 utils::GetPartitionNumber(system_state_->hardware()->BootDevice())) {
Alex Deymo42432912013-07-12 20:21:15 -07001415 // A reboot was pending, but the chromebook is again in the same
1416 // BootDevice where the update was installed from.
1417 int64_t target_attempt;
1418 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1419 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1420 "TargetVersionInstalledFrom was present.";
1421 target_attempt = 1;
1422 }
1423
1424 // Report the UMA metric of the current boot failure.
1425 string metric = "Installer.RebootToNewPartitionAttempt";
1426
1427 LOG(INFO) << "Uploading " << target_attempt
1428 << " (count) for metric " << metric;
1429 system_state_->metrics_lib()->SendToUMA(
1430 metric,
1431 target_attempt,
1432 1, // min value
1433 50, // max value
1434 kNumDefaultUmaBuckets);
David Zeuthen33bae492014-02-25 16:16:18 -08001435
1436 metric = metrics::kMetricFailedUpdateCount;
1437 LOG(INFO) << "Uploading " << target_attempt
1438 << " (count) for metric " << metric;
1439 system_state_->metrics_lib()->SendToUMA(
1440 metric,
1441 target_attempt,
1442 1, // min value
1443 50, // max value
1444 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001445 } else {
1446 prefs_->Delete(kPrefsTargetVersionAttempt);
1447 prefs_->Delete(kPrefsTargetVersionUniqueId);
1448 }
1449 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1450 }
1451}
1452
1453void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1454 // Expect to boot into the new partition in the next reboot setting the
1455 // TargetVersion* flags in the Prefs.
1456 string stored_target_version_uid;
1457 string target_version_id;
1458 string target_partition;
1459 int64_t target_attempt;
1460
1461 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1462 prefs_->GetString(kPrefsTargetVersionUniqueId,
1463 &stored_target_version_uid) &&
1464 stored_target_version_uid == target_version_uid) {
1465 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1466 target_attempt = 0;
1467 } else {
1468 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1469 target_attempt = 0;
1470 }
1471 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1472
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001473 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
1474 utils::GetPartitionNumber(
Alex Deymo42432912013-07-12 20:21:15 -07001475 system_state_->hardware()->BootDevice()));
1476}
1477
1478void PayloadState::ResetUpdateStatus() {
1479 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1480 // rebooted the next boot is not flagged as failed to rebooted into the
1481 // new applied payload.
1482 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1483
1484 // Also decrement the attempt number if it exists.
1485 int64_t target_attempt;
1486 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1487 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt-1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001488}
1489
David Zeuthendcba8092013-08-06 12:16:35 -07001490int PayloadState::GetP2PNumAttempts() {
1491 return p2p_num_attempts_;
1492}
1493
1494void PayloadState::SetP2PNumAttempts(int value) {
1495 p2p_num_attempts_ = value;
1496 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1497 CHECK(prefs_);
1498 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1499}
1500
1501void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001502 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001503}
1504
1505Time PayloadState::GetP2PFirstAttemptTimestamp() {
1506 return p2p_first_attempt_timestamp_;
1507}
1508
1509void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1510 p2p_first_attempt_timestamp_ = time;
1511 LOG(INFO) << "p2p First Attempt Timestamp = "
1512 << utils::ToString(p2p_first_attempt_timestamp_);
1513 CHECK(prefs_);
1514 int64_t stored_value = time.ToInternalValue();
1515 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1516}
1517
1518void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001519 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001520 Time stored_time = Time::FromInternalValue(stored_value);
1521 SetP2PFirstAttemptTimestamp(stored_time);
1522}
1523
1524void PayloadState::P2PNewAttempt() {
1525 CHECK(prefs_);
1526 // Set timestamp, if it hasn't been set already
1527 if (p2p_first_attempt_timestamp_.is_null()) {
1528 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1529 }
1530 // Increase number of attempts
1531 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1532}
1533
1534bool PayloadState::P2PAttemptAllowed() {
1535 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1536 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1537 << " which is greater than "
1538 << kMaxP2PAttempts
1539 << " - disallowing p2p.";
1540 return false;
1541 }
1542
1543 if (!p2p_first_attempt_timestamp_.is_null()) {
1544 Time now = system_state_->clock()->GetWallclockTime();
1545 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1546 if (time_spent_attempting_p2p.InSeconds() < 0) {
1547 LOG(ERROR) << "Time spent attempting p2p is negative"
1548 << " - disallowing p2p.";
1549 return false;
1550 }
1551 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1552 LOG(INFO) << "Time spent attempting p2p is "
1553 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1554 << " which is greater than "
1555 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1556 kMaxP2PAttemptTimeSeconds))
1557 << " - disallowing p2p.";
1558 return false;
1559 }
1560 }
1561
1562 return true;
1563}
1564
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001565} // namespace chromeos_update_engine