blob: fcd4dab0606deb4064fbbd4b68fcfb2cdf63f4dc [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>
13#include <base/format_macros.h>
Gilad Arnold1f847232014-04-07 12:07:49 -070014#include <policy/device_policy.h>
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080015
David Zeuthenf413fe52013-04-22 14:04:39 -070016#include "update_engine/clock.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070017#include "update_engine/constants.h"
Alex Deymo42432912013-07-12 20:21:15 -070018#include "update_engine/hardware_interface.h"
19#include "update_engine/install_plan.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070020#include "update_engine/omaha_request_params.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070021#include "update_engine/prefs.h"
David Zeuthenb281f072014-04-02 10:20:19 -070022#include "update_engine/real_dbus_wrapper.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070023#include "update_engine/system_state.h"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080024#include "update_engine/utils.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080025
Jay Srinivasan08262882012-12-28 19:29:43 -080026using base::Time;
27using base::TimeDelta;
28using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080029using std::string;
30
31namespace chromeos_update_engine {
32
David Zeuthen9a017f22013-04-11 16:10:26 -070033const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
34
Jay Srinivasan08262882012-12-28 19:29:43 -080035// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070036static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080037
Jay Srinivasan08262882012-12-28 19:29:43 -080038// We want to randomize retry attempts after the backoff by +/- 6 hours.
39static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080040
Jay Srinivasan19409b72013-04-12 19:23:36 -070041PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070042 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070043 using_p2p_for_downloading_(false),
Jay Srinivasan19409b72013-04-12 19:23:36 -070044 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070045 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070046 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070047 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070048 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070049 p2p_num_attempts_(0),
50 attempt_num_bytes_downloaded_(0),
51 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070052 attempt_type_(AttemptType::kUpdate) {
53 for (int i = 0; i <= kNumDownloadSources; i++)
54 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070055}
56
57bool PayloadState::Initialize(SystemState* system_state) {
58 system_state_ = system_state;
59 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070060 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080061 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080062 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070063 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080064 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080065 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070066 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080067 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070068 LoadUpdateTimestampStart();
69 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
70 // being called before it. Don't reorder.
71 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070072 for (int i = 0; i < kNumDownloadSources; i++) {
73 DownloadSource source = static_cast<DownloadSource>(i);
74 LoadCurrentBytesDownloaded(source);
75 LoadTotalBytesDownloaded(source);
76 }
Chris Sosabe45bef2013-04-09 18:25:12 -070077 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070078 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070079 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070080 LoadP2PFirstAttemptTimestamp();
81 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080082 return true;
83}
84
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080085void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080086 // Always store the latest response.
87 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080088
Jay Srinivasan53173b92013-05-17 17:13:01 -070089 // Compute the candidate URLs first as they are used to calculate the
90 // response signature so that a change in enterprise policy for
91 // HTTP downloads being enabled or not could be honored as soon as the
92 // next update check happens.
93 ComputeCandidateUrls();
94
Jay Srinivasan08262882012-12-28 19:29:43 -080095 // Check if the "signature" of this response (i.e. the fields we care about)
96 // has changed.
97 string new_response_signature = CalculateResponseSignature();
98 bool has_response_changed = (response_signature_ != new_response_signature);
99
100 // If the response has changed, we should persist the new signature and
101 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800102 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800103 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700104 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800105 SetResponseSignature(new_response_signature);
106 ResetPersistedState();
Alex Deymob33b0f02013-08-08 21:10:02 -0700107 ReportUpdatesAbandonedEventCountMetric();
Jay Srinivasan08262882012-12-28 19:29:43 -0800108 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800109 }
110
Jay Srinivasan08262882012-12-28 19:29:43 -0800111 // This is the earliest point at which we can validate whether the URL index
112 // we loaded from the persisted state is a valid value. If the response
113 // hasn't changed but the URL index is invalid, it's indicative of some
114 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700115 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800116 LOG(INFO) << "Resetting all payload state as the url index seems to have "
117 "been tampered with";
118 ResetPersistedState();
119 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800120 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700121
122 // Update the current download source which depends on the latest value of
123 // the response.
124 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800125}
126
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700127void PayloadState::SetUsingP2PForDownloading(bool value) {
128 using_p2p_for_downloading_ = value;
129 // Update the current download source which depends on whether we are
130 // using p2p or not.
131 UpdateCurrentDownloadSource();
132}
133
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800134void PayloadState::DownloadComplete() {
135 LOG(INFO) << "Payload downloaded successfully";
136 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700137 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800138}
139
140void PayloadState::DownloadProgress(size_t count) {
141 if (count == 0)
142 return;
143
David Zeuthen9a017f22013-04-11 16:10:26 -0700144 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700145 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700146
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800147 // We've received non-zero bytes from a recent download operation. Since our
148 // URL failure count is meant to penalize a URL only for consecutive
149 // failures, downloading bytes successfully means we should reset the failure
150 // count (as we know at least that the URL is working). In future, we can
151 // design this to be more sophisticated to check for more intelligent failure
152 // patterns, but right now, even 1 byte downloaded will mark the URL to be
153 // good unless it hits 10 (or configured number of) consecutive failures
154 // again.
155
156 if (GetUrlFailureCount() == 0)
157 return;
158
159 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
160 << " to 0 as we received " << count << " bytes successfully";
161 SetUrlFailureCount(0);
162}
163
David Zeuthenafed4a12014-04-09 15:28:44 -0700164void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700165 // Flush previous state from abnormal attempt failure, if any.
166 ReportAndClearPersistedAttemptMetrics();
167
David Zeuthenafed4a12014-04-09 15:28:44 -0700168 attempt_type_ = attempt_type;
169
David Zeuthen33bae492014-02-25 16:16:18 -0800170 ClockInterface *clock = system_state_->clock();
171 attempt_start_time_boot_ = clock->GetBootTime();
172 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800173 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700174
175 metrics::ConnectionType type;
176 NetworkConnectionType network_connection_type;
177 NetworkTethering tethering;
178 RealDBusWrapper dbus_iface;
179 ConnectionManager* connection_manager = system_state_->connection_manager();
180 if (!connection_manager->GetConnectionProperties(&dbus_iface,
181 &network_connection_type,
182 &tethering)) {
183 LOG(ERROR) << "Failed to determine connection type.";
184 type = metrics::ConnectionType::kUnknown;
185 } else {
186 type = utils::GetConnectionType(network_connection_type, tethering);
187 }
188 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700189
190 if (attempt_type == AttemptType::kUpdate)
191 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800192}
193
Chris Sosabe45bef2013-04-09 18:25:12 -0700194void PayloadState::UpdateResumed() {
195 LOG(INFO) << "Resuming an update that was previously started.";
196 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700197 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700198}
199
Jay Srinivasan19409b72013-04-12 19:23:36 -0700200void PayloadState::UpdateRestarted() {
201 LOG(INFO) << "Starting a new update";
202 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700203 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700204 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700205}
206
David Zeuthen9a017f22013-04-11 16:10:26 -0700207void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700208 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700209 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700210 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800211
David Zeuthen96197df2014-04-16 12:22:39 -0700212 switch (attempt_type_) {
213 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700214 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700215 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700216 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700217 break;
218
219 case AttemptType::kRollback:
220 metrics::ReportRollbackMetrics(system_state_,
221 metrics::RollbackResult::kSuccess);
222 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700223 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700224
225 // Reset the number of responses seen since it counts from the last
226 // successful update, e.g. now.
227 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700228
229 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700230}
231
David Zeuthena99981f2013-04-29 13:42:47 -0700232void PayloadState::UpdateFailed(ErrorCode error) {
233 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800234 LOG(INFO) << "Updating payload state for error code: " << base_error
235 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800236
Jay Srinivasan53173b92013-05-17 17:13:01 -0700237 if (candidate_urls_.size() == 0) {
238 // This means we got this error even before we got a valid Omaha response
239 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800240 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800241 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
242 return;
243 }
244
David Zeuthen96197df2014-04-16 12:22:39 -0700245 switch (attempt_type_) {
246 case AttemptType::kUpdate:
247 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700248 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700249 break;
250
251 case AttemptType::kRollback:
252 metrics::ReportRollbackMetrics(system_state_,
253 metrics::RollbackResult::kFailed);
254 break;
255 }
David Zeuthen33bae492014-02-25 16:16:18 -0800256
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800257 switch (base_error) {
258 // Errors which are good indicators of a problem with a particular URL or
259 // the protocol used in the URL or entities in the communication channel
260 // (e.g. proxies). We should try the next available URL in the next update
261 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700262 case ErrorCode::kPayloadHashMismatchError:
263 case ErrorCode::kPayloadSizeMismatchError:
264 case ErrorCode::kDownloadPayloadVerificationError:
265 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
266 case ErrorCode::kSignedDeltaPayloadExpectedError:
267 case ErrorCode::kDownloadInvalidMetadataMagicString:
268 case ErrorCode::kDownloadSignatureMissingInManifest:
269 case ErrorCode::kDownloadManifestParseError:
270 case ErrorCode::kDownloadMetadataSignatureError:
271 case ErrorCode::kDownloadMetadataSignatureVerificationError:
272 case ErrorCode::kDownloadMetadataSignatureMismatch:
273 case ErrorCode::kDownloadOperationHashVerificationError:
274 case ErrorCode::kDownloadOperationExecutionError:
275 case ErrorCode::kDownloadOperationHashMismatch:
276 case ErrorCode::kDownloadInvalidMetadataSize:
277 case ErrorCode::kDownloadInvalidMetadataSignature:
278 case ErrorCode::kDownloadOperationHashMissingError:
279 case ErrorCode::kDownloadMetadataSignatureMissingError:
280 case ErrorCode::kPayloadMismatchedType:
281 case ErrorCode::kUnsupportedMajorPayloadVersion:
282 case ErrorCode::kUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800283 IncrementUrlIndex();
284 break;
285
286 // Errors which seem to be just transient network/communication related
287 // failures and do not indicate any inherent problem with the URL itself.
288 // So, we should keep the current URL but just increment the
289 // failure count to give it more chances. This way, while we maximize our
290 // chances of downloading from the URLs that appear earlier in the response
291 // (because download from a local server URL that appears earlier in a
292 // response is preferable than downloading from the next URL which could be
293 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700294
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700295 case ErrorCode::kError:
296 case ErrorCode::kDownloadTransferError:
297 case ErrorCode::kDownloadWriteError:
298 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700299 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800300 IncrementFailureCount();
301 break;
302
303 // Errors which are not specific to a URL and hence shouldn't result in
304 // the URL being penalized. This can happen in two cases:
305 // 1. We haven't started downloading anything: These errors don't cost us
306 // anything in terms of actual payload bytes, so we should just do the
307 // regular retries at the next update check.
308 // 2. We have successfully downloaded the payload: In this case, the
309 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800310 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800311 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700312 case ErrorCode::kOmahaRequestError:
313 case ErrorCode::kOmahaResponseHandlerError:
314 case ErrorCode::kPostinstallRunnerError:
315 case ErrorCode::kFilesystemCopierError:
316 case ErrorCode::kInstallDeviceOpenError:
317 case ErrorCode::kKernelDeviceOpenError:
318 case ErrorCode::kDownloadNewPartitionInfoError:
319 case ErrorCode::kNewRootfsVerificationError:
320 case ErrorCode::kNewKernelVerificationError:
321 case ErrorCode::kPostinstallBootedFromFirmwareB:
322 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
323 case ErrorCode::kOmahaRequestEmptyResponseError:
324 case ErrorCode::kOmahaRequestXMLParseError:
325 case ErrorCode::kOmahaResponseInvalid:
326 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
327 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
328 case ErrorCode::kOmahaUpdateDeferredForBackoff:
329 case ErrorCode::kPostinstallPowerwashError:
330 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400331 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800332 LOG(INFO) << "Not incrementing URL index or failure count for this error";
333 break;
334
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700335 case ErrorCode::kSuccess: // success code
336 case ErrorCode::kUmaReportedMax: // not an error code
337 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
338 case ErrorCode::kDevModeFlag: // not an error code
339 case ErrorCode::kResumedFlag: // not an error code
340 case ErrorCode::kTestImageFlag: // not an error code
341 case ErrorCode::kTestOmahaUrlFlag: // not an error code
342 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800343 // These shouldn't happen. Enumerating these explicitly here so that we
344 // can let the compiler warn about new error codes that are added to
345 // action_processor.h but not added here.
346 LOG(WARNING) << "Unexpected error code for UpdateFailed";
347 break;
348
349 // Note: Not adding a default here so as to let the compiler warn us of
350 // any new enums that were added in the .h but not listed in this switch.
351 }
352}
353
Jay Srinivasan08262882012-12-28 19:29:43 -0800354bool PayloadState::ShouldBackoffDownload() {
355 if (response_.disable_payload_backoff) {
356 LOG(INFO) << "Payload backoff logic is disabled. "
357 "Can proceed with the download";
358 return false;
359 }
Chris Sosa20f005c2013-09-05 13:53:08 -0700360 if (system_state_->request_params()->use_p2p_for_downloading() &&
361 !system_state_->request_params()->p2p_url().empty()) {
362 LOG(INFO) << "Payload backoff logic is disabled because download "
363 << "will happen from local peer (via p2p).";
364 return false;
365 }
366 if (system_state_->request_params()->interactive()) {
367 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
368 return false;
369 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800370 if (response_.is_delta_payload) {
371 // If delta payloads fail, we want to fallback quickly to full payloads as
372 // they are more likely to succeed. Exponential backoffs would greatly
373 // slow down the fallback to full payloads. So we don't backoff for delta
374 // payloads.
375 LOG(INFO) << "No backoffs for delta payloads. "
376 << "Can proceed with the download";
377 return false;
378 }
379
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700380 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800381 // Backoffs are needed only for official builds. We do not want any delays
382 // or update failures due to backoffs during testing or development.
383 LOG(INFO) << "No backoffs for test/dev images. "
384 << "Can proceed with the download";
385 return false;
386 }
387
388 if (backoff_expiry_time_.is_null()) {
389 LOG(INFO) << "No backoff expiry time has been set. "
390 << "Can proceed with the download";
391 return false;
392 }
393
394 if (backoff_expiry_time_ < Time::Now()) {
395 LOG(INFO) << "The backoff expiry time ("
396 << utils::ToString(backoff_expiry_time_)
397 << ") has elapsed. Can proceed with the download";
398 return false;
399 }
400
401 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
402 << utils::ToString(backoff_expiry_time_);
403 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800404}
405
Chris Sosaaa18e162013-06-20 13:20:30 -0700406void PayloadState::Rollback() {
407 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700408 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700409}
410
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800411void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700412 // Update the payload attempt number for both payload types: full and delta.
413 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Alex Deymo29b51d92013-07-09 15:26:24 -0700414
415 // Report the metric every time the value is incremented.
416 string metric = "Installer.PayloadAttemptNumber";
417 int value = GetPayloadAttemptNumber();
418
419 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
420 system_state_->metrics_lib()->SendToUMA(
421 metric,
422 value,
423 1, // min value
424 50, // max value
425 kNumDefaultUmaBuckets);
Alex Deymo820cc702013-06-28 15:43:46 -0700426}
427
428void PayloadState::IncrementFullPayloadAttemptNumber() {
429 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800430 if (response_.is_delta_payload) {
431 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
432 return;
433 }
434
Alex Deymo29b51d92013-07-09 15:26:24 -0700435 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700436 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800437 UpdateBackoffExpiryTime();
Alex Deymo29b51d92013-07-09 15:26:24 -0700438
439 // Report the metric every time the value is incremented.
440 string metric = "Installer.FullPayloadAttemptNumber";
441 int value = GetFullPayloadAttemptNumber();
442
443 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
444 system_state_->metrics_lib()->SendToUMA(
445 metric,
446 value,
447 1, // min value
448 50, // max value
449 kNumDefaultUmaBuckets);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800450}
451
452void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800453 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700454 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800455 LOG(INFO) << "Incrementing the URL index for next attempt";
456 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800457 } else {
458 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700459 << "0 as we only have " << candidate_urls_.size()
460 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800461 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700462 IncrementPayloadAttemptNumber();
463 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800464 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800465
David Zeuthencc6f9962013-04-18 11:57:24 -0700466 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700467 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700468 SetUrlSwitchCount(url_switch_count_ + 1);
469
Jay Srinivasan08262882012-12-28 19:29:43 -0800470 // Whenever we update the URL index, we should also clear the URL failure
471 // count so we can start over fresh for the new URL.
472 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800473}
474
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800475void PayloadState::IncrementFailureCount() {
476 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800477 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800478 LOG(INFO) << "Incrementing the URL failure count";
479 SetUrlFailureCount(next_url_failure_count);
480 } else {
481 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
482 << ". Trying next available URL";
483 IncrementUrlIndex();
484 }
485}
486
Jay Srinivasan08262882012-12-28 19:29:43 -0800487void PayloadState::UpdateBackoffExpiryTime() {
488 if (response_.disable_payload_backoff) {
489 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
490 SetBackoffExpiryTime(Time());
491 return;
492 }
493
Alex Deymo820cc702013-06-28 15:43:46 -0700494 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800495 SetBackoffExpiryTime(Time());
496 return;
497 }
498
499 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700500 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800501 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700502 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700503 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800504
505 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
506 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700507 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800508
509 // The number of days is the minimum of 2 raised to (payload_attempt_number
510 // - 1) or kMaxBackoffDays.
511 num_days = min(num_days << power, kMaxBackoffDays);
512
513 // We don't want all retries to happen exactly at the same time when
514 // retrying after backoff. So add some random minutes to fuzz.
515 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
516 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
517 TimeDelta::FromMinutes(fuzz_minutes);
518 LOG(INFO) << "Incrementing the backoff expiry time by "
519 << utils::FormatTimeDelta(next_backoff_interval);
520 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
521}
522
Jay Srinivasan19409b72013-04-12 19:23:36 -0700523void PayloadState::UpdateCurrentDownloadSource() {
524 current_download_source_ = kNumDownloadSources;
525
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700526 if (using_p2p_for_downloading_) {
527 current_download_source_ = kDownloadSourceHttpPeer;
528 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700529 string current_url = candidate_urls_[GetUrlIndex()];
Jay Srinivasan19409b72013-04-12 19:23:36 -0700530 if (StartsWithASCII(current_url, "https://", false))
531 current_download_source_ = kDownloadSourceHttpsServer;
532 else if (StartsWithASCII(current_url, "http://", false))
533 current_download_source_ = kDownloadSourceHttpServer;
534 }
535
536 LOG(INFO) << "Current download source: "
537 << utils::ToString(current_download_source_);
538}
539
540void PayloadState::UpdateBytesDownloaded(size_t count) {
541 SetCurrentBytesDownloaded(
542 current_download_source_,
543 GetCurrentBytesDownloaded(current_download_source_) + count,
544 false);
545 SetTotalBytesDownloaded(
546 current_download_source_,
547 GetTotalBytesDownloaded(current_download_source_) + count,
548 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800549
550 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700551}
552
David Zeuthen33bae492014-02-25 16:16:18 -0800553PayloadType PayloadState::CalculatePayloadType() {
554 PayloadType payload_type;
555 OmahaRequestParams* params = system_state_->request_params();
556 if (response_.is_delta_payload) {
557 payload_type = kPayloadTypeDelta;
558 } else if (params->delta_okay()) {
559 payload_type = kPayloadTypeFull;
560 } else { // Full payload, delta was not allowed by request.
561 payload_type = kPayloadTypeForcedFull;
562 }
563 return payload_type;
564}
565
566// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
567// metrics if the attempt ends abnormally, e.g. if the update_engine
568// process crashes or the device is rebooted. See
569// http://crbug.com/357676
570void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
571 int attempt_number = GetPayloadAttemptNumber();
572
573 PayloadType payload_type = CalculatePayloadType();
574
575 int64_t payload_size = response_.size;
576
577 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
578
579 ClockInterface *clock = system_state_->clock();
580 base::TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
581 base::TimeDelta duration_uptime = clock->GetMonotonicTime() -
582 attempt_start_time_monotonic_;
583
584 int64_t payload_download_speed_bps = 0;
585 int64_t usec = duration_uptime.InMicroseconds();
586 if (usec > 0) {
587 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
588 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
589 payload_download_speed_bps = static_cast<int64_t>(bps);
590 }
591
592 DownloadSource download_source = current_download_source_;
593
594 metrics::DownloadErrorCode payload_download_error_code =
595 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700596 ErrorCode internal_error_code = ErrorCode::kSuccess;
David Zeuthen33bae492014-02-25 16:16:18 -0800597 metrics::AttemptResult attempt_result = utils::GetAttemptResult(code);
598
599 // Add additional detail to AttemptResult
600 switch (attempt_result) {
601 case metrics::AttemptResult::kPayloadDownloadError:
602 payload_download_error_code = utils::GetDownloadErrorCode(code);
603 break;
604
605 case metrics::AttemptResult::kInternalError:
606 internal_error_code = code;
607 break;
608
609 // Explicit fall-through for cases where we do not have additional
610 // detail. We avoid the default keyword to force people adding new
611 // AttemptResult values to visit this code and examine whether
612 // additional detail is needed.
613 case metrics::AttemptResult::kUpdateSucceeded:
614 case metrics::AttemptResult::kMetadataMalformed:
615 case metrics::AttemptResult::kOperationMalformed:
616 case metrics::AttemptResult::kOperationExecutionError:
617 case metrics::AttemptResult::kMetadataVerificationFailed:
618 case metrics::AttemptResult::kPayloadVerificationFailed:
619 case metrics::AttemptResult::kVerificationFailed:
620 case metrics::AttemptResult::kPostInstallFailed:
621 case metrics::AttemptResult::kAbnormalTermination:
622 case metrics::AttemptResult::kNumConstants:
623 case metrics::AttemptResult::kUnset:
624 break;
625 }
626
627 metrics::ReportUpdateAttemptMetrics(system_state_,
628 attempt_number,
629 payload_type,
630 duration,
631 duration_uptime,
632 payload_size,
633 payload_bytes_downloaded,
634 payload_download_speed_bps,
635 download_source,
636 attempt_result,
637 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700638 payload_download_error_code,
639 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800640}
641
David Zeuthen4e1d1492014-04-25 13:12:27 -0700642void PayloadState::PersistAttemptMetrics() {
643 // TODO(zeuthen): For now we only persist whether an attempt was in
644 // progress and not values/metrics related to the attempt. This
645 // means that when this happens, of all the UpdateEngine.Attempt.*
646 // metrics, only UpdateEngine.Attempt.Result is reported (with the
647 // value |kAbnormalTermination|). In the future we might want to
648 // persist more data so we can report other metrics in the
649 // UpdateEngine.Attempt.* namespace when this happens.
650 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
651}
652
653void PayloadState::ClearPersistedAttemptMetrics() {
654 prefs_->Delete(kPrefsAttemptInProgress);
655}
656
657void PayloadState::ReportAndClearPersistedAttemptMetrics() {
658 bool attempt_in_progress = false;
659 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
660 return;
661 if (!attempt_in_progress)
662 return;
663
664 metrics::ReportAbnormallyTerminatedUpdateAttemptMetrics(system_state_);
665
666 ClearPersistedAttemptMetrics();
667}
668
David Zeuthen33bae492014-02-25 16:16:18 -0800669void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700670 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800671
672 // Report metrics collected from all known download sources to UMA.
673 int64_t successful_bytes_by_source[kNumDownloadSources];
674 int64_t total_bytes_by_source[kNumDownloadSources];
675 int64_t successful_bytes = 0;
676 int64_t total_bytes = 0;
677 int64_t successful_mbs = 0;
678 int64_t total_mbs = 0;
679
Jay Srinivasan19409b72013-04-12 19:23:36 -0700680 for (int i = 0; i < kNumDownloadSources; i++) {
681 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800682 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700683
David Zeuthen44848602013-06-24 13:32:14 -0700684 // Only consider this download source (and send byte counts) as
685 // having been used if we downloaded a non-trivial amount of bytes
686 // (e.g. at least 1 MiB) that contributed to the final success of
687 // the update. Otherwise we're going to end up with a lot of
688 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700689
David Zeuthen33bae492014-02-25 16:16:18 -0800690 bytes = GetCurrentBytesDownloaded(source);
691 successful_bytes_by_source[i] = bytes;
692 successful_bytes += bytes;
693 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700694 SetCurrentBytesDownloaded(source, 0, true);
695
David Zeuthen33bae492014-02-25 16:16:18 -0800696 bytes = GetTotalBytesDownloaded(source);
697 total_bytes_by_source[i] = bytes;
698 total_bytes += bytes;
699 total_mbs += bytes / kNumBytesInOneMiB;
700 SetTotalBytesDownloaded(source, 0, true);
701 }
702
703 int download_overhead_percentage = 0;
704 if (successful_bytes > 0) {
705 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
706 successful_bytes;
707 }
708
709 int url_switch_count = static_cast<int>(url_switch_count_);
710
711 int reboot_count = GetNumReboots();
712
713 SetNumReboots(0);
714
715 TimeDelta duration = GetUpdateDuration();
716 TimeDelta duration_uptime = GetUpdateDurationUptime();
717
718 prefs_->Delete(kPrefsUpdateTimestampStart);
719 prefs_->Delete(kPrefsUpdateDurationUptime);
720
721 PayloadType payload_type = CalculatePayloadType();
722
723 int64_t payload_size = response_.size;
724
725 int attempt_count = GetPayloadAttemptNumber();
726
727 int updates_abandoned_count = num_responses_seen_ - 1;
728
729 metrics::ReportSuccessfulUpdateMetrics(system_state_,
730 attempt_count,
731 updates_abandoned_count,
732 payload_type,
733 payload_size,
734 total_bytes_by_source,
735 download_overhead_percentage,
736 duration,
737 reboot_count,
738 url_switch_count);
739
740 // TODO(zeuthen): This is the old metric reporting code which is
741 // slated for removal soon. See http://crbug.com/355745 for details.
742
743 // The old metrics code is using MiB's instead of bytes to calculate
744 // the overhead which due to rounding makes the numbers slightly
745 // different.
746 download_overhead_percentage = 0;
747 if (successful_mbs > 0) {
748 download_overhead_percentage = (total_mbs - successful_mbs) * 100ULL /
749 successful_mbs;
750 }
751
752 int download_sources_used = 0;
753 for (int i = 0; i < kNumDownloadSources; i++) {
754 DownloadSource source = static_cast<DownloadSource>(i);
755 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
756 int64_t mbs;
757
758 // Only consider this download source (and send byte counts) as
759 // having been used if we downloaded a non-trivial amount of bytes
760 // (e.g. at least 1 MiB) that contributed to the final success of
761 // the update. Otherwise we're going to end up with a lot of
762 // zero-byte events in the histogram.
763
764 mbs = successful_bytes_by_source[i] / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700765 if (mbs > 0) {
David Zeuthen33bae492014-02-25 16:16:18 -0800766 metric = "Installer.SuccessfulMBsDownloadedFrom" +
767 utils::ToString(source);
David Zeuthen44848602013-06-24 13:32:14 -0700768 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
769 system_state_->metrics_lib()->SendToUMA(metric,
770 mbs,
771 0, // min
772 kMaxMiBs,
773 kNumDefaultUmaBuckets);
774 }
David Zeuthen33bae492014-02-25 16:16:18 -0800775
776 mbs = total_bytes_by_source[i] / kNumBytesInOneMiB;
777 if (mbs > 0) {
778 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
779 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
780 system_state_->metrics_lib()->SendToUMA(metric,
781 mbs,
782 0, // min
783 kMaxMiBs,
784 kNumDefaultUmaBuckets);
785 download_sources_used |= (1 << i);
786 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700787 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700788
789 metric = "Installer.DownloadSourcesUsed";
790 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
791 << " (bit flags) for metric " << metric;
792 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
793 system_state_->metrics_lib()->SendToUMA(metric,
794 download_sources_used,
795 0, // min
796 1 << kNumDownloadSources,
797 num_buckets);
798
David Zeuthen33bae492014-02-25 16:16:18 -0800799 metric = "Installer.DownloadOverheadPercentage";
800 LOG(INFO) << "Uploading " << download_overhead_percentage
801 << "% for metric " << metric;
802 system_state_->metrics_lib()->SendToUMA(metric,
803 download_overhead_percentage,
804 0, // min: 0% overhead
805 1000, // max: 1000% overhead
806 kNumDefaultUmaBuckets);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700807
David Zeuthen33bae492014-02-25 16:16:18 -0800808 metric = "Installer.UpdateURLSwitches";
809 LOG(INFO) << "Uploading " << url_switch_count
810 << " (count) for metric " << metric;
David Zeuthencc6f9962013-04-18 11:57:24 -0700811 system_state_->metrics_lib()->SendToUMA(
812 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800813 url_switch_count,
David Zeuthencc6f9962013-04-18 11:57:24 -0700814 0, // min value
815 100, // max value
816 kNumDefaultUmaBuckets);
David Zeuthencc6f9962013-04-18 11:57:24 -0700817
David Zeuthen33bae492014-02-25 16:16:18 -0800818 metric = "Installer.UpdateNumReboots";
819 LOG(INFO) << "Uploading reboot count of " << reboot_count << " for metric "
Chris Sosabe45bef2013-04-09 18:25:12 -0700820 << metric;
821 system_state_->metrics_lib()->SendToUMA(
822 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800823 reboot_count, // sample
824 0, // min = 0.
825 50, // max
Chris Sosabe45bef2013-04-09 18:25:12 -0700826 25); // buckets
David Zeuthen33bae492014-02-25 16:16:18 -0800827
828 metric = "Installer.UpdateDurationMinutes";
829 system_state_->metrics_lib()->SendToUMA(
830 metric,
831 static_cast<int>(duration.InMinutes()),
832 1, // min: 1 minute
833 365*24*60, // max: 1 year (approx)
834 kNumDefaultUmaBuckets);
835 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
836 << " for metric " << metric;
837
838 metric = "Installer.UpdateDurationUptimeMinutes";
839 system_state_->metrics_lib()->SendToUMA(
840 metric,
841 static_cast<int>(duration_uptime.InMinutes()),
842 1, // min: 1 minute
843 30*24*60, // max: 1 month (approx)
844 kNumDefaultUmaBuckets);
845 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
846 << " for metric " << metric;
847
848 metric = "Installer.PayloadFormat";
849 system_state_->metrics_lib()->SendEnumToUMA(
850 metric,
851 payload_type,
852 kNumPayloadTypes);
853 LOG(INFO) << "Uploading " << utils::ToString(payload_type)
854 << " for metric " << metric;
855
856 metric = "Installer.AttemptsCount.Total";
857 system_state_->metrics_lib()->SendToUMA(
858 metric,
859 attempt_count,
860 1, // min
861 50, // max
862 kNumDefaultUmaBuckets);
863 LOG(INFO) << "Uploading " << attempt_count
864 << " for metric " << metric;
865
866 metric = "Installer.UpdatesAbandonedCount";
867 LOG(INFO) << "Uploading " << updates_abandoned_count
868 << " (count) for metric " << metric;
869 system_state_->metrics_lib()->SendToUMA(
870 metric,
871 updates_abandoned_count,
872 0, // min value
873 100, // max value
874 kNumDefaultUmaBuckets);
Chris Sosabe45bef2013-04-09 18:25:12 -0700875}
876
877void PayloadState::UpdateNumReboots() {
878 // We only update the reboot count when the system has been detected to have
879 // been rebooted.
880 if (!system_state_->system_rebooted()) {
881 return;
882 }
883
884 SetNumReboots(GetNumReboots() + 1);
885}
886
887void PayloadState::SetNumReboots(uint32_t num_reboots) {
888 CHECK(prefs_);
889 num_reboots_ = num_reboots;
890 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
891 LOG(INFO) << "Number of Reboots during current update attempt = "
892 << num_reboots_;
893}
894
Jay Srinivasan08262882012-12-28 19:29:43 -0800895void PayloadState::ResetPersistedState() {
896 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700897 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800898 SetUrlIndex(0);
899 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700900 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700901 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700902 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700903 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700904 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700905 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700906 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700907 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700908 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Gilad Arnold519cfc72014-10-02 10:34:54 -0700909 SetScatteringWaitPeriod(base::TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700910}
911
912void PayloadState::ResetRollbackVersion() {
913 CHECK(powerwash_safe_prefs_);
914 rollback_version_ = "";
915 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700916}
917
918void PayloadState::ResetDownloadSourcesOnNewUpdate() {
919 for (int i = 0; i < kNumDownloadSources; i++) {
920 DownloadSource source = static_cast<DownloadSource>(i);
921 SetCurrentBytesDownloaded(source, 0, true);
922 // Note: Not resetting the TotalBytesDownloaded as we want that metric
923 // to count the bytes downloaded across various update attempts until
924 // we have successfully applied the update.
925 }
926}
927
Chris Sosab3dcdb32013-09-04 15:22:12 -0700928int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700929 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700930 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700931 return 0;
932
933 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700934 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700935 return 0;
936
937 if (stored_value < 0) {
938 LOG(ERROR) << key << ": Invalid value (" << stored_value
939 << ") in persisted state. Defaulting to 0";
940 return 0;
941 }
942
943 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800944}
945
946string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700947 string response_sign = base::StringPrintf(
948 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800949
Jay Srinivasan53173b92013-05-17 17:13:01 -0700950 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700951 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
952 static_cast<int>(i),
953 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800954
Alex Vakulenko75039d72014-03-25 12:36:28 -0700955 response_sign += base::StringPrintf(
956 "Payload Size = %ju\n"
957 "Payload Sha256 Hash = %s\n"
958 "Metadata Size = %ju\n"
959 "Metadata Signature = %s\n"
960 "Is Delta Payload = %d\n"
961 "Max Failure Count Per Url = %d\n"
962 "Disable Payload Backoff = %d\n",
963 static_cast<uintmax_t>(response_.size),
964 response_.hash.c_str(),
965 static_cast<uintmax_t>(response_.metadata_size),
966 response_.metadata_signature.c_str(),
967 response_.is_delta_payload,
968 response_.max_failure_count_per_url,
969 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800970 return response_sign;
971}
972
973void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800974 CHECK(prefs_);
975 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800976 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
977 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
978 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800979 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800980}
981
Jay Srinivasan19409b72013-04-12 19:23:36 -0700982void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800983 CHECK(prefs_);
984 response_signature_ = response_signature;
985 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
986 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
987}
988
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800989void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700990 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800991}
992
Alex Deymo820cc702013-06-28 15:43:46 -0700993void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700994 SetFullPayloadAttemptNumber(GetPersistedValue(
995 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700996}
997
998void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800999 CHECK(prefs_);
1000 payload_attempt_number_ = payload_attempt_number;
1001 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
1002 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
1003}
1004
Alex Deymo820cc702013-06-28 15:43:46 -07001005void PayloadState::SetFullPayloadAttemptNumber(
1006 int full_payload_attempt_number) {
1007 CHECK(prefs_);
1008 full_payload_attempt_number_ = full_payload_attempt_number;
1009 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
1010 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
1011 full_payload_attempt_number_);
1012}
1013
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001014void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001015 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001016}
1017
1018void PayloadState::SetUrlIndex(uint32_t url_index) {
1019 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001020 url_index_ = url_index;
1021 LOG(INFO) << "Current URL Index = " << url_index_;
1022 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001023
1024 // Also update the download source, which is purely dependent on the
1025 // current URL index alone.
1026 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001027}
1028
Gilad Arnold519cfc72014-10-02 10:34:54 -07001029void PayloadState::LoadScatteringWaitPeriod() {
1030 SetScatteringWaitPeriod(
1031 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
1032}
1033
1034void PayloadState::SetScatteringWaitPeriod(base::TimeDelta wait_period) {
1035 CHECK(prefs_);
1036 scattering_wait_period_ = wait_period;
1037 LOG(INFO) << "Scattering Wait Period (seconds) = "
1038 << scattering_wait_period_.InSeconds();
1039 if (scattering_wait_period_.InSeconds() > 0) {
1040 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
1041 scattering_wait_period_.InSeconds());
1042 } else {
1043 prefs_->Delete(kPrefsWallClockWaitPeriod);
1044 }
1045}
1046
David Zeuthencc6f9962013-04-18 11:57:24 -07001047void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001048 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -07001049}
1050
1051void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
1052 CHECK(prefs_);
1053 url_switch_count_ = url_switch_count;
1054 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
1055 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
1056}
1057
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001058void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001059 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001060}
1061
1062void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
1063 CHECK(prefs_);
1064 url_failure_count_ = url_failure_count;
1065 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
1066 << ")'s Failure Count = " << url_failure_count_;
1067 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001068}
1069
Jay Srinivasan08262882012-12-28 19:29:43 -08001070void PayloadState::LoadBackoffExpiryTime() {
1071 CHECK(prefs_);
1072 int64_t stored_value;
1073 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
1074 return;
1075
1076 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
1077 return;
1078
1079 Time stored_time = Time::FromInternalValue(stored_value);
1080 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
1081 LOG(ERROR) << "Invalid backoff expiry time ("
1082 << utils::ToString(stored_time)
1083 << ") in persisted state. Resetting.";
1084 stored_time = Time();
1085 }
1086 SetBackoffExpiryTime(stored_time);
1087}
1088
1089void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
1090 CHECK(prefs_);
1091 backoff_expiry_time_ = new_time;
1092 LOG(INFO) << "Backoff Expiry Time = "
1093 << utils::ToString(backoff_expiry_time_);
1094 prefs_->SetInt64(kPrefsBackoffExpiryTime,
1095 backoff_expiry_time_.ToInternalValue());
1096}
1097
David Zeuthen9a017f22013-04-11 16:10:26 -07001098TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001099 Time end_time = update_timestamp_end_.is_null()
1100 ? system_state_->clock()->GetWallclockTime() :
1101 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001102 return end_time - update_timestamp_start_;
1103}
1104
1105void PayloadState::LoadUpdateTimestampStart() {
1106 int64_t stored_value;
1107 Time stored_time;
1108
1109 CHECK(prefs_);
1110
David Zeuthenf413fe52013-04-22 14:04:39 -07001111 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001112
1113 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1114 // The preference missing is not unexpected - in that case, just
1115 // use the current time as start time
1116 stored_time = now;
1117 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1118 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1119 stored_time = now;
1120 } else {
1121 stored_time = Time::FromInternalValue(stored_value);
1122 }
1123
1124 // Sanity check: If the time read from disk is in the future
1125 // (modulo some slack to account for possible NTP drift
1126 // adjustments), something is fishy and we should report and
1127 // reset.
1128 TimeDelta duration_according_to_stored_time = now - stored_time;
1129 if (duration_according_to_stored_time < -kDurationSlack) {
1130 LOG(ERROR) << "The UpdateTimestampStart value ("
1131 << utils::ToString(stored_time)
1132 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001133 << utils::FormatTimeDelta(duration_according_to_stored_time)
1134 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001135 stored_time = now;
1136 }
1137
1138 SetUpdateTimestampStart(stored_time);
1139}
1140
1141void PayloadState::SetUpdateTimestampStart(const Time& value) {
1142 CHECK(prefs_);
1143 update_timestamp_start_ = value;
1144 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1145 update_timestamp_start_.ToInternalValue());
1146 LOG(INFO) << "Update Timestamp Start = "
1147 << utils::ToString(update_timestamp_start_);
1148}
1149
1150void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1151 update_timestamp_end_ = value;
1152 LOG(INFO) << "Update Timestamp End = "
1153 << utils::ToString(update_timestamp_end_);
1154}
1155
1156TimeDelta PayloadState::GetUpdateDurationUptime() {
1157 return update_duration_uptime_;
1158}
1159
1160void PayloadState::LoadUpdateDurationUptime() {
1161 int64_t stored_value;
1162 TimeDelta stored_delta;
1163
1164 CHECK(prefs_);
1165
1166 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1167 // The preference missing is not unexpected - in that case, just
1168 // we'll use zero as the delta
1169 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1170 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1171 stored_delta = TimeDelta::FromSeconds(0);
1172 } else {
1173 stored_delta = TimeDelta::FromInternalValue(stored_value);
1174 }
1175
1176 // Sanity-check: Uptime can never be greater than the wall-clock
1177 // difference (modulo some slack). If it is, report and reset
1178 // to the wall-clock difference.
1179 TimeDelta diff = GetUpdateDuration() - stored_delta;
1180 if (diff < -kDurationSlack) {
1181 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001182 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001183 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001184 << utils::FormatTimeDelta(diff)
1185 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001186 stored_delta = update_duration_current_;
1187 }
1188
1189 SetUpdateDurationUptime(stored_delta);
1190}
1191
Chris Sosabe45bef2013-04-09 18:25:12 -07001192void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001193 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001194}
1195
1196void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001197 CHECK(powerwash_safe_prefs_);
1198 string rollback_version;
1199 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1200 &rollback_version)) {
1201 SetRollbackVersion(rollback_version);
1202 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001203}
1204
1205void PayloadState::SetRollbackVersion(const string& rollback_version) {
1206 CHECK(powerwash_safe_prefs_);
1207 LOG(INFO) << "Blacklisting version "<< rollback_version;
1208 rollback_version_ = rollback_version;
1209 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001210}
1211
David Zeuthen9a017f22013-04-11 16:10:26 -07001212void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1213 const Time& timestamp,
1214 bool use_logging) {
1215 CHECK(prefs_);
1216 update_duration_uptime_ = value;
1217 update_duration_uptime_timestamp_ = timestamp;
1218 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1219 update_duration_uptime_.ToInternalValue());
1220 if (use_logging) {
1221 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001222 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001223 }
1224}
1225
1226void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001227 Time now = system_state_->clock()->GetMonotonicTime();
1228 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001229}
1230
1231void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001232 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001233 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1234 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1235 // We're frequently called so avoid logging this write
1236 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1237}
1238
Jay Srinivasan19409b72013-04-12 19:23:36 -07001239string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1240 return prefix + "-from-" + utils::ToString(source);
1241}
1242
1243void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1244 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001245 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001246}
1247
1248void PayloadState::SetCurrentBytesDownloaded(
1249 DownloadSource source,
1250 uint64_t current_bytes_downloaded,
1251 bool log) {
1252 CHECK(prefs_);
1253
1254 if (source >= kNumDownloadSources)
1255 return;
1256
1257 // Update the in-memory value.
1258 current_bytes_downloaded_[source] = current_bytes_downloaded;
1259
1260 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1261 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1262 LOG_IF(INFO, log) << "Current bytes downloaded for "
1263 << utils::ToString(source) << " = "
1264 << GetCurrentBytesDownloaded(source);
1265}
1266
1267void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1268 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001269 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001270}
1271
1272void PayloadState::SetTotalBytesDownloaded(
1273 DownloadSource source,
1274 uint64_t total_bytes_downloaded,
1275 bool log) {
1276 CHECK(prefs_);
1277
1278 if (source >= kNumDownloadSources)
1279 return;
1280
1281 // Update the in-memory value.
1282 total_bytes_downloaded_[source] = total_bytes_downloaded;
1283
1284 // Persist.
1285 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1286 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1287 LOG_IF(INFO, log) << "Total bytes downloaded for "
1288 << utils::ToString(source) << " = "
1289 << GetTotalBytesDownloaded(source);
1290}
1291
David Zeuthena573d6f2013-06-14 16:13:36 -07001292void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001293 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001294}
1295
1296void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1297 CHECK(prefs_);
1298 num_responses_seen_ = num_responses_seen;
1299 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1300 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1301}
1302
Alex Deymob33b0f02013-08-08 21:10:02 -07001303void PayloadState::ReportUpdatesAbandonedEventCountMetric() {
1304 string metric = "Installer.UpdatesAbandonedEventCount";
1305 int value = num_responses_seen_ - 1;
1306
1307 // Do not send an "abandoned" event when 0 payloads were abandoned since the
1308 // last successful update.
1309 if (value == 0)
1310 return;
1311
1312 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1313 system_state_->metrics_lib()->SendToUMA(
1314 metric,
1315 value,
1316 0, // min value
1317 100, // max value
1318 kNumDefaultUmaBuckets);
1319}
1320
Jay Srinivasan53173b92013-05-17 17:13:01 -07001321void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001322 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001323
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001324 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001325 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001326 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001327 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1328 } else {
1329 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1330 http_url_ok = true;
1331 }
1332
1333 candidate_urls_.clear();
1334 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1335 string candidate_url = response_.payload_urls[i];
1336 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1337 continue;
1338 candidate_urls_.push_back(candidate_url);
1339 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1340 << ": " << candidate_url;
1341 }
1342
1343 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1344 << "out of " << response_.payload_urls.size() << " URLs supplied";
1345}
1346
David Zeuthene4c58bf2013-06-18 17:26:50 -07001347void PayloadState::CreateSystemUpdatedMarkerFile() {
1348 CHECK(prefs_);
1349 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1350 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1351}
1352
1353void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1354 // Send |time_to_reboot| as a UMA stat.
1355 string metric = "Installer.TimeToRebootMinutes";
1356 system_state_->metrics_lib()->SendToUMA(metric,
1357 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001358 0, // min: 0 minute
1359 30*24*60, // max: 1 month (approx)
David Zeuthene4c58bf2013-06-18 17:26:50 -07001360 kNumDefaultUmaBuckets);
1361 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1362 << " for metric " << metric;
David Zeuthen33bae492014-02-25 16:16:18 -08001363
1364 metric = metrics::kMetricTimeToRebootMinutes;
1365 system_state_->metrics_lib()->SendToUMA(metric,
1366 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001367 0, // min: 0 minute
1368 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001369 kNumDefaultUmaBuckets);
1370 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1371 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001372}
1373
1374void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001375 // Flush previous state from abnormal attempt failure, if any.
1376 ReportAndClearPersistedAttemptMetrics();
1377
Alex Deymo569c4242013-07-24 12:01:01 -07001378 // Avoid the UpdateEngineStarted actions if this is not the first time we
1379 // run the update engine since reboot.
1380 if (!system_state_->system_rebooted())
1381 return;
1382
David Zeuthene4c58bf2013-06-18 17:26:50 -07001383 // Figure out if we just booted into a new update
1384 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1385 int64_t stored_value;
1386 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1387 Time system_updated_at = Time::FromInternalValue(stored_value);
1388 if (!system_updated_at.is_null()) {
1389 TimeDelta time_to_reboot =
1390 system_state_->clock()->GetWallclockTime() - system_updated_at;
1391 if (time_to_reboot.ToInternalValue() < 0) {
1392 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1393 << utils::ToString(system_updated_at);
1394 } else {
1395 BootedIntoUpdate(time_to_reboot);
1396 }
1397 }
1398 }
1399 prefs_->Delete(kPrefsSystemUpdatedMarker);
1400 }
Alex Deymo42432912013-07-12 20:21:15 -07001401 // Check if it is needed to send metrics about a failed reboot into a new
1402 // version.
1403 ReportFailedBootIfNeeded();
1404}
1405
1406void PayloadState::ReportFailedBootIfNeeded() {
1407 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1408 // payload was marked as ready immediately before the last reboot, and we
1409 // need to check if such payload successfully rebooted or not.
1410 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001411 int64_t installed_from = 0;
1412 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001413 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1414 return;
1415 }
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001416 if (static_cast<int>(installed_from) ==
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001417 utils::GetPartitionNumber(system_state_->hardware()->BootDevice())) {
Alex Deymo42432912013-07-12 20:21:15 -07001418 // A reboot was pending, but the chromebook is again in the same
1419 // BootDevice where the update was installed from.
1420 int64_t target_attempt;
1421 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1422 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1423 "TargetVersionInstalledFrom was present.";
1424 target_attempt = 1;
1425 }
1426
1427 // Report the UMA metric of the current boot failure.
1428 string metric = "Installer.RebootToNewPartitionAttempt";
1429
1430 LOG(INFO) << "Uploading " << target_attempt
1431 << " (count) for metric " << metric;
1432 system_state_->metrics_lib()->SendToUMA(
1433 metric,
1434 target_attempt,
1435 1, // min value
1436 50, // max value
1437 kNumDefaultUmaBuckets);
David Zeuthen33bae492014-02-25 16:16:18 -08001438
1439 metric = metrics::kMetricFailedUpdateCount;
1440 LOG(INFO) << "Uploading " << target_attempt
1441 << " (count) for metric " << metric;
1442 system_state_->metrics_lib()->SendToUMA(
1443 metric,
1444 target_attempt,
1445 1, // min value
1446 50, // max value
1447 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001448 } else {
1449 prefs_->Delete(kPrefsTargetVersionAttempt);
1450 prefs_->Delete(kPrefsTargetVersionUniqueId);
1451 }
1452 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1453 }
1454}
1455
1456void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1457 // Expect to boot into the new partition in the next reboot setting the
1458 // TargetVersion* flags in the Prefs.
1459 string stored_target_version_uid;
1460 string target_version_id;
1461 string target_partition;
1462 int64_t target_attempt;
1463
1464 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1465 prefs_->GetString(kPrefsTargetVersionUniqueId,
1466 &stored_target_version_uid) &&
1467 stored_target_version_uid == target_version_uid) {
1468 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1469 target_attempt = 0;
1470 } else {
1471 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1472 target_attempt = 0;
1473 }
1474 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1475
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001476 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
1477 utils::GetPartitionNumber(
Alex Deymo42432912013-07-12 20:21:15 -07001478 system_state_->hardware()->BootDevice()));
1479}
1480
1481void PayloadState::ResetUpdateStatus() {
1482 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1483 // rebooted the next boot is not flagged as failed to rebooted into the
1484 // new applied payload.
1485 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1486
1487 // Also decrement the attempt number if it exists.
1488 int64_t target_attempt;
1489 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1490 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt-1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001491}
1492
David Zeuthendcba8092013-08-06 12:16:35 -07001493int PayloadState::GetP2PNumAttempts() {
1494 return p2p_num_attempts_;
1495}
1496
1497void PayloadState::SetP2PNumAttempts(int value) {
1498 p2p_num_attempts_ = value;
1499 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1500 CHECK(prefs_);
1501 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1502}
1503
1504void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001505 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001506}
1507
1508Time PayloadState::GetP2PFirstAttemptTimestamp() {
1509 return p2p_first_attempt_timestamp_;
1510}
1511
1512void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1513 p2p_first_attempt_timestamp_ = time;
1514 LOG(INFO) << "p2p First Attempt Timestamp = "
1515 << utils::ToString(p2p_first_attempt_timestamp_);
1516 CHECK(prefs_);
1517 int64_t stored_value = time.ToInternalValue();
1518 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1519}
1520
1521void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001522 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001523 Time stored_time = Time::FromInternalValue(stored_value);
1524 SetP2PFirstAttemptTimestamp(stored_time);
1525}
1526
1527void PayloadState::P2PNewAttempt() {
1528 CHECK(prefs_);
1529 // Set timestamp, if it hasn't been set already
1530 if (p2p_first_attempt_timestamp_.is_null()) {
1531 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1532 }
1533 // Increase number of attempts
1534 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1535}
1536
1537bool PayloadState::P2PAttemptAllowed() {
1538 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1539 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1540 << " which is greater than "
1541 << kMaxP2PAttempts
1542 << " - disallowing p2p.";
1543 return false;
1544 }
1545
1546 if (!p2p_first_attempt_timestamp_.is_null()) {
1547 Time now = system_state_->clock()->GetWallclockTime();
1548 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1549 if (time_spent_attempting_p2p.InSeconds() < 0) {
1550 LOG(ERROR) << "Time spent attempting p2p is negative"
1551 << " - disallowing p2p.";
1552 return false;
1553 }
1554 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1555 LOG(INFO) << "Time spent attempting p2p is "
1556 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1557 << " which is greater than "
1558 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1559 kMaxP2PAttemptTimeSeconds))
1560 << " - disallowing p2p.";
1561 return false;
1562 }
1563 }
1564
1565 return true;
1566}
1567
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001568} // namespace chromeos_update_engine