blob: a98154640e1c58ed206dae86987a789315277dfc [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()
42 : prefs_(NULL),
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:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800331 LOG(INFO) << "Not incrementing URL index or failure count for this error";
332 break;
333
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700334 case ErrorCode::kSuccess: // success code
335 case ErrorCode::kUmaReportedMax: // not an error code
336 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
337 case ErrorCode::kDevModeFlag: // not an error code
338 case ErrorCode::kResumedFlag: // not an error code
339 case ErrorCode::kTestImageFlag: // not an error code
340 case ErrorCode::kTestOmahaUrlFlag: // not an error code
341 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800342 // These shouldn't happen. Enumerating these explicitly here so that we
343 // can let the compiler warn about new error codes that are added to
344 // action_processor.h but not added here.
345 LOG(WARNING) << "Unexpected error code for UpdateFailed";
346 break;
347
348 // Note: Not adding a default here so as to let the compiler warn us of
349 // any new enums that were added in the .h but not listed in this switch.
350 }
351}
352
Jay Srinivasan08262882012-12-28 19:29:43 -0800353bool PayloadState::ShouldBackoffDownload() {
354 if (response_.disable_payload_backoff) {
355 LOG(INFO) << "Payload backoff logic is disabled. "
356 "Can proceed with the download";
357 return false;
358 }
Chris Sosa20f005c2013-09-05 13:53:08 -0700359 if (system_state_->request_params()->use_p2p_for_downloading() &&
360 !system_state_->request_params()->p2p_url().empty()) {
361 LOG(INFO) << "Payload backoff logic is disabled because download "
362 << "will happen from local peer (via p2p).";
363 return false;
364 }
365 if (system_state_->request_params()->interactive()) {
366 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
367 return false;
368 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800369 if (response_.is_delta_payload) {
370 // If delta payloads fail, we want to fallback quickly to full payloads as
371 // they are more likely to succeed. Exponential backoffs would greatly
372 // slow down the fallback to full payloads. So we don't backoff for delta
373 // payloads.
374 LOG(INFO) << "No backoffs for delta payloads. "
375 << "Can proceed with the download";
376 return false;
377 }
378
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700379 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800380 // Backoffs are needed only for official builds. We do not want any delays
381 // or update failures due to backoffs during testing or development.
382 LOG(INFO) << "No backoffs for test/dev images. "
383 << "Can proceed with the download";
384 return false;
385 }
386
387 if (backoff_expiry_time_.is_null()) {
388 LOG(INFO) << "No backoff expiry time has been set. "
389 << "Can proceed with the download";
390 return false;
391 }
392
393 if (backoff_expiry_time_ < Time::Now()) {
394 LOG(INFO) << "The backoff expiry time ("
395 << utils::ToString(backoff_expiry_time_)
396 << ") has elapsed. Can proceed with the download";
397 return false;
398 }
399
400 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
401 << utils::ToString(backoff_expiry_time_);
402 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800403}
404
Chris Sosaaa18e162013-06-20 13:20:30 -0700405void PayloadState::Rollback() {
406 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700407 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700408}
409
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800410void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700411 // Update the payload attempt number for both payload types: full and delta.
412 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Alex Deymo29b51d92013-07-09 15:26:24 -0700413
414 // Report the metric every time the value is incremented.
415 string metric = "Installer.PayloadAttemptNumber";
416 int value = GetPayloadAttemptNumber();
417
418 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
419 system_state_->metrics_lib()->SendToUMA(
420 metric,
421 value,
422 1, // min value
423 50, // max value
424 kNumDefaultUmaBuckets);
Alex Deymo820cc702013-06-28 15:43:46 -0700425}
426
427void PayloadState::IncrementFullPayloadAttemptNumber() {
428 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800429 if (response_.is_delta_payload) {
430 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
431 return;
432 }
433
Alex Deymo29b51d92013-07-09 15:26:24 -0700434 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700435 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800436 UpdateBackoffExpiryTime();
Alex Deymo29b51d92013-07-09 15:26:24 -0700437
438 // Report the metric every time the value is incremented.
439 string metric = "Installer.FullPayloadAttemptNumber";
440 int value = GetFullPayloadAttemptNumber();
441
442 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
443 system_state_->metrics_lib()->SendToUMA(
444 metric,
445 value,
446 1, // min value
447 50, // max value
448 kNumDefaultUmaBuckets);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800449}
450
451void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800452 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700453 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800454 LOG(INFO) << "Incrementing the URL index for next attempt";
455 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800456 } else {
457 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700458 << "0 as we only have " << candidate_urls_.size()
459 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800460 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700461 IncrementPayloadAttemptNumber();
462 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800463 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800464
David Zeuthencc6f9962013-04-18 11:57:24 -0700465 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700466 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700467 SetUrlSwitchCount(url_switch_count_ + 1);
468
Jay Srinivasan08262882012-12-28 19:29:43 -0800469 // Whenever we update the URL index, we should also clear the URL failure
470 // count so we can start over fresh for the new URL.
471 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800472}
473
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800474void PayloadState::IncrementFailureCount() {
475 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800476 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800477 LOG(INFO) << "Incrementing the URL failure count";
478 SetUrlFailureCount(next_url_failure_count);
479 } else {
480 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
481 << ". Trying next available URL";
482 IncrementUrlIndex();
483 }
484}
485
Jay Srinivasan08262882012-12-28 19:29:43 -0800486void PayloadState::UpdateBackoffExpiryTime() {
487 if (response_.disable_payload_backoff) {
488 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
489 SetBackoffExpiryTime(Time());
490 return;
491 }
492
Alex Deymo820cc702013-06-28 15:43:46 -0700493 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800494 SetBackoffExpiryTime(Time());
495 return;
496 }
497
498 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700499 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800500 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700501 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700502 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800503
504 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
505 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700506 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800507
508 // The number of days is the minimum of 2 raised to (payload_attempt_number
509 // - 1) or kMaxBackoffDays.
510 num_days = min(num_days << power, kMaxBackoffDays);
511
512 // We don't want all retries to happen exactly at the same time when
513 // retrying after backoff. So add some random minutes to fuzz.
514 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
515 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
516 TimeDelta::FromMinutes(fuzz_minutes);
517 LOG(INFO) << "Incrementing the backoff expiry time by "
518 << utils::FormatTimeDelta(next_backoff_interval);
519 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
520}
521
Jay Srinivasan19409b72013-04-12 19:23:36 -0700522void PayloadState::UpdateCurrentDownloadSource() {
523 current_download_source_ = kNumDownloadSources;
524
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700525 if (using_p2p_for_downloading_) {
526 current_download_source_ = kDownloadSourceHttpPeer;
527 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700528 string current_url = candidate_urls_[GetUrlIndex()];
Jay Srinivasan19409b72013-04-12 19:23:36 -0700529 if (StartsWithASCII(current_url, "https://", false))
530 current_download_source_ = kDownloadSourceHttpsServer;
531 else if (StartsWithASCII(current_url, "http://", false))
532 current_download_source_ = kDownloadSourceHttpServer;
533 }
534
535 LOG(INFO) << "Current download source: "
536 << utils::ToString(current_download_source_);
537}
538
539void PayloadState::UpdateBytesDownloaded(size_t count) {
540 SetCurrentBytesDownloaded(
541 current_download_source_,
542 GetCurrentBytesDownloaded(current_download_source_) + count,
543 false);
544 SetTotalBytesDownloaded(
545 current_download_source_,
546 GetTotalBytesDownloaded(current_download_source_) + count,
547 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800548
549 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700550}
551
David Zeuthen33bae492014-02-25 16:16:18 -0800552PayloadType PayloadState::CalculatePayloadType() {
553 PayloadType payload_type;
554 OmahaRequestParams* params = system_state_->request_params();
555 if (response_.is_delta_payload) {
556 payload_type = kPayloadTypeDelta;
557 } else if (params->delta_okay()) {
558 payload_type = kPayloadTypeFull;
559 } else { // Full payload, delta was not allowed by request.
560 payload_type = kPayloadTypeForcedFull;
561 }
562 return payload_type;
563}
564
565// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
566// metrics if the attempt ends abnormally, e.g. if the update_engine
567// process crashes or the device is rebooted. See
568// http://crbug.com/357676
569void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
570 int attempt_number = GetPayloadAttemptNumber();
571
572 PayloadType payload_type = CalculatePayloadType();
573
574 int64_t payload_size = response_.size;
575
576 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
577
578 ClockInterface *clock = system_state_->clock();
579 base::TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
580 base::TimeDelta duration_uptime = clock->GetMonotonicTime() -
581 attempt_start_time_monotonic_;
582
583 int64_t payload_download_speed_bps = 0;
584 int64_t usec = duration_uptime.InMicroseconds();
585 if (usec > 0) {
586 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
587 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
588 payload_download_speed_bps = static_cast<int64_t>(bps);
589 }
590
591 DownloadSource download_source = current_download_source_;
592
593 metrics::DownloadErrorCode payload_download_error_code =
594 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700595 ErrorCode internal_error_code = ErrorCode::kSuccess;
David Zeuthen33bae492014-02-25 16:16:18 -0800596 metrics::AttemptResult attempt_result = utils::GetAttemptResult(code);
597
598 // Add additional detail to AttemptResult
599 switch (attempt_result) {
600 case metrics::AttemptResult::kPayloadDownloadError:
601 payload_download_error_code = utils::GetDownloadErrorCode(code);
602 break;
603
604 case metrics::AttemptResult::kInternalError:
605 internal_error_code = code;
606 break;
607
608 // Explicit fall-through for cases where we do not have additional
609 // detail. We avoid the default keyword to force people adding new
610 // AttemptResult values to visit this code and examine whether
611 // additional detail is needed.
612 case metrics::AttemptResult::kUpdateSucceeded:
613 case metrics::AttemptResult::kMetadataMalformed:
614 case metrics::AttemptResult::kOperationMalformed:
615 case metrics::AttemptResult::kOperationExecutionError:
616 case metrics::AttemptResult::kMetadataVerificationFailed:
617 case metrics::AttemptResult::kPayloadVerificationFailed:
618 case metrics::AttemptResult::kVerificationFailed:
619 case metrics::AttemptResult::kPostInstallFailed:
620 case metrics::AttemptResult::kAbnormalTermination:
621 case metrics::AttemptResult::kNumConstants:
622 case metrics::AttemptResult::kUnset:
623 break;
624 }
625
626 metrics::ReportUpdateAttemptMetrics(system_state_,
627 attempt_number,
628 payload_type,
629 duration,
630 duration_uptime,
631 payload_size,
632 payload_bytes_downloaded,
633 payload_download_speed_bps,
634 download_source,
635 attempt_result,
636 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700637 payload_download_error_code,
638 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800639}
640
David Zeuthen4e1d1492014-04-25 13:12:27 -0700641void PayloadState::PersistAttemptMetrics() {
642 // TODO(zeuthen): For now we only persist whether an attempt was in
643 // progress and not values/metrics related to the attempt. This
644 // means that when this happens, of all the UpdateEngine.Attempt.*
645 // metrics, only UpdateEngine.Attempt.Result is reported (with the
646 // value |kAbnormalTermination|). In the future we might want to
647 // persist more data so we can report other metrics in the
648 // UpdateEngine.Attempt.* namespace when this happens.
649 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
650}
651
652void PayloadState::ClearPersistedAttemptMetrics() {
653 prefs_->Delete(kPrefsAttemptInProgress);
654}
655
656void PayloadState::ReportAndClearPersistedAttemptMetrics() {
657 bool attempt_in_progress = false;
658 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
659 return;
660 if (!attempt_in_progress)
661 return;
662
663 metrics::ReportAbnormallyTerminatedUpdateAttemptMetrics(system_state_);
664
665 ClearPersistedAttemptMetrics();
666}
667
David Zeuthen33bae492014-02-25 16:16:18 -0800668void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700669 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800670
671 // Report metrics collected from all known download sources to UMA.
672 int64_t successful_bytes_by_source[kNumDownloadSources];
673 int64_t total_bytes_by_source[kNumDownloadSources];
674 int64_t successful_bytes = 0;
675 int64_t total_bytes = 0;
676 int64_t successful_mbs = 0;
677 int64_t total_mbs = 0;
678
Jay Srinivasan19409b72013-04-12 19:23:36 -0700679 for (int i = 0; i < kNumDownloadSources; i++) {
680 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800681 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700682
David Zeuthen44848602013-06-24 13:32:14 -0700683 // Only consider this download source (and send byte counts) as
684 // having been used if we downloaded a non-trivial amount of bytes
685 // (e.g. at least 1 MiB) that contributed to the final success of
686 // the update. Otherwise we're going to end up with a lot of
687 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700688
David Zeuthen33bae492014-02-25 16:16:18 -0800689 bytes = GetCurrentBytesDownloaded(source);
690 successful_bytes_by_source[i] = bytes;
691 successful_bytes += bytes;
692 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700693 SetCurrentBytesDownloaded(source, 0, true);
694
David Zeuthen33bae492014-02-25 16:16:18 -0800695 bytes = GetTotalBytesDownloaded(source);
696 total_bytes_by_source[i] = bytes;
697 total_bytes += bytes;
698 total_mbs += bytes / kNumBytesInOneMiB;
699 SetTotalBytesDownloaded(source, 0, true);
700 }
701
702 int download_overhead_percentage = 0;
703 if (successful_bytes > 0) {
704 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
705 successful_bytes;
706 }
707
708 int url_switch_count = static_cast<int>(url_switch_count_);
709
710 int reboot_count = GetNumReboots();
711
712 SetNumReboots(0);
713
714 TimeDelta duration = GetUpdateDuration();
715 TimeDelta duration_uptime = GetUpdateDurationUptime();
716
717 prefs_->Delete(kPrefsUpdateTimestampStart);
718 prefs_->Delete(kPrefsUpdateDurationUptime);
719
720 PayloadType payload_type = CalculatePayloadType();
721
722 int64_t payload_size = response_.size;
723
724 int attempt_count = GetPayloadAttemptNumber();
725
726 int updates_abandoned_count = num_responses_seen_ - 1;
727
728 metrics::ReportSuccessfulUpdateMetrics(system_state_,
729 attempt_count,
730 updates_abandoned_count,
731 payload_type,
732 payload_size,
733 total_bytes_by_source,
734 download_overhead_percentage,
735 duration,
736 reboot_count,
737 url_switch_count);
738
739 // TODO(zeuthen): This is the old metric reporting code which is
740 // slated for removal soon. See http://crbug.com/355745 for details.
741
742 // The old metrics code is using MiB's instead of bytes to calculate
743 // the overhead which due to rounding makes the numbers slightly
744 // different.
745 download_overhead_percentage = 0;
746 if (successful_mbs > 0) {
747 download_overhead_percentage = (total_mbs - successful_mbs) * 100ULL /
748 successful_mbs;
749 }
750
751 int download_sources_used = 0;
752 for (int i = 0; i < kNumDownloadSources; i++) {
753 DownloadSource source = static_cast<DownloadSource>(i);
754 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
755 int64_t mbs;
756
757 // Only consider this download source (and send byte counts) as
758 // having been used if we downloaded a non-trivial amount of bytes
759 // (e.g. at least 1 MiB) that contributed to the final success of
760 // the update. Otherwise we're going to end up with a lot of
761 // zero-byte events in the histogram.
762
763 mbs = successful_bytes_by_source[i] / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700764 if (mbs > 0) {
David Zeuthen33bae492014-02-25 16:16:18 -0800765 metric = "Installer.SuccessfulMBsDownloadedFrom" +
766 utils::ToString(source);
David Zeuthen44848602013-06-24 13:32:14 -0700767 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
768 system_state_->metrics_lib()->SendToUMA(metric,
769 mbs,
770 0, // min
771 kMaxMiBs,
772 kNumDefaultUmaBuckets);
773 }
David Zeuthen33bae492014-02-25 16:16:18 -0800774
775 mbs = total_bytes_by_source[i] / kNumBytesInOneMiB;
776 if (mbs > 0) {
777 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
778 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
779 system_state_->metrics_lib()->SendToUMA(metric,
780 mbs,
781 0, // min
782 kMaxMiBs,
783 kNumDefaultUmaBuckets);
784 download_sources_used |= (1 << i);
785 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700786 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700787
788 metric = "Installer.DownloadSourcesUsed";
789 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
790 << " (bit flags) for metric " << metric;
791 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
792 system_state_->metrics_lib()->SendToUMA(metric,
793 download_sources_used,
794 0, // min
795 1 << kNumDownloadSources,
796 num_buckets);
797
David Zeuthen33bae492014-02-25 16:16:18 -0800798 metric = "Installer.DownloadOverheadPercentage";
799 LOG(INFO) << "Uploading " << download_overhead_percentage
800 << "% for metric " << metric;
801 system_state_->metrics_lib()->SendToUMA(metric,
802 download_overhead_percentage,
803 0, // min: 0% overhead
804 1000, // max: 1000% overhead
805 kNumDefaultUmaBuckets);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700806
David Zeuthen33bae492014-02-25 16:16:18 -0800807 metric = "Installer.UpdateURLSwitches";
808 LOG(INFO) << "Uploading " << url_switch_count
809 << " (count) for metric " << metric;
David Zeuthencc6f9962013-04-18 11:57:24 -0700810 system_state_->metrics_lib()->SendToUMA(
811 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800812 url_switch_count,
David Zeuthencc6f9962013-04-18 11:57:24 -0700813 0, // min value
814 100, // max value
815 kNumDefaultUmaBuckets);
David Zeuthencc6f9962013-04-18 11:57:24 -0700816
David Zeuthen33bae492014-02-25 16:16:18 -0800817 metric = "Installer.UpdateNumReboots";
818 LOG(INFO) << "Uploading reboot count of " << reboot_count << " for metric "
Chris Sosabe45bef2013-04-09 18:25:12 -0700819 << metric;
820 system_state_->metrics_lib()->SendToUMA(
821 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800822 reboot_count, // sample
823 0, // min = 0.
824 50, // max
Chris Sosabe45bef2013-04-09 18:25:12 -0700825 25); // buckets
David Zeuthen33bae492014-02-25 16:16:18 -0800826
827 metric = "Installer.UpdateDurationMinutes";
828 system_state_->metrics_lib()->SendToUMA(
829 metric,
830 static_cast<int>(duration.InMinutes()),
831 1, // min: 1 minute
832 365*24*60, // max: 1 year (approx)
833 kNumDefaultUmaBuckets);
834 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
835 << " for metric " << metric;
836
837 metric = "Installer.UpdateDurationUptimeMinutes";
838 system_state_->metrics_lib()->SendToUMA(
839 metric,
840 static_cast<int>(duration_uptime.InMinutes()),
841 1, // min: 1 minute
842 30*24*60, // max: 1 month (approx)
843 kNumDefaultUmaBuckets);
844 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
845 << " for metric " << metric;
846
847 metric = "Installer.PayloadFormat";
848 system_state_->metrics_lib()->SendEnumToUMA(
849 metric,
850 payload_type,
851 kNumPayloadTypes);
852 LOG(INFO) << "Uploading " << utils::ToString(payload_type)
853 << " for metric " << metric;
854
855 metric = "Installer.AttemptsCount.Total";
856 system_state_->metrics_lib()->SendToUMA(
857 metric,
858 attempt_count,
859 1, // min
860 50, // max
861 kNumDefaultUmaBuckets);
862 LOG(INFO) << "Uploading " << attempt_count
863 << " for metric " << metric;
864
865 metric = "Installer.UpdatesAbandonedCount";
866 LOG(INFO) << "Uploading " << updates_abandoned_count
867 << " (count) for metric " << metric;
868 system_state_->metrics_lib()->SendToUMA(
869 metric,
870 updates_abandoned_count,
871 0, // min value
872 100, // max value
873 kNumDefaultUmaBuckets);
Chris Sosabe45bef2013-04-09 18:25:12 -0700874}
875
876void PayloadState::UpdateNumReboots() {
877 // We only update the reboot count when the system has been detected to have
878 // been rebooted.
879 if (!system_state_->system_rebooted()) {
880 return;
881 }
882
883 SetNumReboots(GetNumReboots() + 1);
884}
885
886void PayloadState::SetNumReboots(uint32_t num_reboots) {
887 CHECK(prefs_);
888 num_reboots_ = num_reboots;
889 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
890 LOG(INFO) << "Number of Reboots during current update attempt = "
891 << num_reboots_;
892}
893
Jay Srinivasan08262882012-12-28 19:29:43 -0800894void PayloadState::ResetPersistedState() {
895 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700896 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800897 SetUrlIndex(0);
898 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700899 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700900 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700901 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700902 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700903 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700904 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700905 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700906 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700907 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Chris Sosaaa18e162013-06-20 13:20:30 -0700908}
909
910void PayloadState::ResetRollbackVersion() {
911 CHECK(powerwash_safe_prefs_);
912 rollback_version_ = "";
913 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700914}
915
916void PayloadState::ResetDownloadSourcesOnNewUpdate() {
917 for (int i = 0; i < kNumDownloadSources; i++) {
918 DownloadSource source = static_cast<DownloadSource>(i);
919 SetCurrentBytesDownloaded(source, 0, true);
920 // Note: Not resetting the TotalBytesDownloaded as we want that metric
921 // to count the bytes downloaded across various update attempts until
922 // we have successfully applied the update.
923 }
924}
925
Chris Sosab3dcdb32013-09-04 15:22:12 -0700926int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700927 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700928 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700929 return 0;
930
931 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700932 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700933 return 0;
934
935 if (stored_value < 0) {
936 LOG(ERROR) << key << ": Invalid value (" << stored_value
937 << ") in persisted state. Defaulting to 0";
938 return 0;
939 }
940
941 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800942}
943
944string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700945 string response_sign = base::StringPrintf(
946 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800947
Jay Srinivasan53173b92013-05-17 17:13:01 -0700948 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700949 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
950 static_cast<int>(i),
951 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800952
Alex Vakulenko75039d72014-03-25 12:36:28 -0700953 response_sign += base::StringPrintf(
954 "Payload Size = %ju\n"
955 "Payload Sha256 Hash = %s\n"
956 "Metadata Size = %ju\n"
957 "Metadata Signature = %s\n"
958 "Is Delta Payload = %d\n"
959 "Max Failure Count Per Url = %d\n"
960 "Disable Payload Backoff = %d\n",
961 static_cast<uintmax_t>(response_.size),
962 response_.hash.c_str(),
963 static_cast<uintmax_t>(response_.metadata_size),
964 response_.metadata_signature.c_str(),
965 response_.is_delta_payload,
966 response_.max_failure_count_per_url,
967 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800968 return response_sign;
969}
970
971void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800972 CHECK(prefs_);
973 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800974 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
975 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
976 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800977 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800978}
979
Jay Srinivasan19409b72013-04-12 19:23:36 -0700980void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800981 CHECK(prefs_);
982 response_signature_ = response_signature;
983 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
984 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
985}
986
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800987void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700988 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800989}
990
Alex Deymo820cc702013-06-28 15:43:46 -0700991void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700992 SetFullPayloadAttemptNumber(GetPersistedValue(
993 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700994}
995
996void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800997 CHECK(prefs_);
998 payload_attempt_number_ = payload_attempt_number;
999 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
1000 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
1001}
1002
Alex Deymo820cc702013-06-28 15:43:46 -07001003void PayloadState::SetFullPayloadAttemptNumber(
1004 int full_payload_attempt_number) {
1005 CHECK(prefs_);
1006 full_payload_attempt_number_ = full_payload_attempt_number;
1007 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
1008 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
1009 full_payload_attempt_number_);
1010}
1011
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001012void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001013 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001014}
1015
1016void PayloadState::SetUrlIndex(uint32_t url_index) {
1017 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001018 url_index_ = url_index;
1019 LOG(INFO) << "Current URL Index = " << url_index_;
1020 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001021
1022 // Also update the download source, which is purely dependent on the
1023 // current URL index alone.
1024 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001025}
1026
David Zeuthencc6f9962013-04-18 11:57:24 -07001027void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001028 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -07001029}
1030
1031void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
1032 CHECK(prefs_);
1033 url_switch_count_ = url_switch_count;
1034 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
1035 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
1036}
1037
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001038void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001039 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001040}
1041
1042void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
1043 CHECK(prefs_);
1044 url_failure_count_ = url_failure_count;
1045 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
1046 << ")'s Failure Count = " << url_failure_count_;
1047 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001048}
1049
Jay Srinivasan08262882012-12-28 19:29:43 -08001050void PayloadState::LoadBackoffExpiryTime() {
1051 CHECK(prefs_);
1052 int64_t stored_value;
1053 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
1054 return;
1055
1056 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
1057 return;
1058
1059 Time stored_time = Time::FromInternalValue(stored_value);
1060 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
1061 LOG(ERROR) << "Invalid backoff expiry time ("
1062 << utils::ToString(stored_time)
1063 << ") in persisted state. Resetting.";
1064 stored_time = Time();
1065 }
1066 SetBackoffExpiryTime(stored_time);
1067}
1068
1069void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
1070 CHECK(prefs_);
1071 backoff_expiry_time_ = new_time;
1072 LOG(INFO) << "Backoff Expiry Time = "
1073 << utils::ToString(backoff_expiry_time_);
1074 prefs_->SetInt64(kPrefsBackoffExpiryTime,
1075 backoff_expiry_time_.ToInternalValue());
1076}
1077
David Zeuthen9a017f22013-04-11 16:10:26 -07001078TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001079 Time end_time = update_timestamp_end_.is_null()
1080 ? system_state_->clock()->GetWallclockTime() :
1081 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001082 return end_time - update_timestamp_start_;
1083}
1084
1085void PayloadState::LoadUpdateTimestampStart() {
1086 int64_t stored_value;
1087 Time stored_time;
1088
1089 CHECK(prefs_);
1090
David Zeuthenf413fe52013-04-22 14:04:39 -07001091 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001092
1093 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1094 // The preference missing is not unexpected - in that case, just
1095 // use the current time as start time
1096 stored_time = now;
1097 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1098 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1099 stored_time = now;
1100 } else {
1101 stored_time = Time::FromInternalValue(stored_value);
1102 }
1103
1104 // Sanity check: If the time read from disk is in the future
1105 // (modulo some slack to account for possible NTP drift
1106 // adjustments), something is fishy and we should report and
1107 // reset.
1108 TimeDelta duration_according_to_stored_time = now - stored_time;
1109 if (duration_according_to_stored_time < -kDurationSlack) {
1110 LOG(ERROR) << "The UpdateTimestampStart value ("
1111 << utils::ToString(stored_time)
1112 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001113 << utils::FormatTimeDelta(duration_according_to_stored_time)
1114 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001115 stored_time = now;
1116 }
1117
1118 SetUpdateTimestampStart(stored_time);
1119}
1120
1121void PayloadState::SetUpdateTimestampStart(const Time& value) {
1122 CHECK(prefs_);
1123 update_timestamp_start_ = value;
1124 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1125 update_timestamp_start_.ToInternalValue());
1126 LOG(INFO) << "Update Timestamp Start = "
1127 << utils::ToString(update_timestamp_start_);
1128}
1129
1130void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1131 update_timestamp_end_ = value;
1132 LOG(INFO) << "Update Timestamp End = "
1133 << utils::ToString(update_timestamp_end_);
1134}
1135
1136TimeDelta PayloadState::GetUpdateDurationUptime() {
1137 return update_duration_uptime_;
1138}
1139
1140void PayloadState::LoadUpdateDurationUptime() {
1141 int64_t stored_value;
1142 TimeDelta stored_delta;
1143
1144 CHECK(prefs_);
1145
1146 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1147 // The preference missing is not unexpected - in that case, just
1148 // we'll use zero as the delta
1149 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1150 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1151 stored_delta = TimeDelta::FromSeconds(0);
1152 } else {
1153 stored_delta = TimeDelta::FromInternalValue(stored_value);
1154 }
1155
1156 // Sanity-check: Uptime can never be greater than the wall-clock
1157 // difference (modulo some slack). If it is, report and reset
1158 // to the wall-clock difference.
1159 TimeDelta diff = GetUpdateDuration() - stored_delta;
1160 if (diff < -kDurationSlack) {
1161 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001162 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001163 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001164 << utils::FormatTimeDelta(diff)
1165 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001166 stored_delta = update_duration_current_;
1167 }
1168
1169 SetUpdateDurationUptime(stored_delta);
1170}
1171
Chris Sosabe45bef2013-04-09 18:25:12 -07001172void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001173 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001174}
1175
1176void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001177 CHECK(powerwash_safe_prefs_);
1178 string rollback_version;
1179 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1180 &rollback_version)) {
1181 SetRollbackVersion(rollback_version);
1182 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001183}
1184
1185void PayloadState::SetRollbackVersion(const string& rollback_version) {
1186 CHECK(powerwash_safe_prefs_);
1187 LOG(INFO) << "Blacklisting version "<< rollback_version;
1188 rollback_version_ = rollback_version;
1189 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001190}
1191
David Zeuthen9a017f22013-04-11 16:10:26 -07001192void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1193 const Time& timestamp,
1194 bool use_logging) {
1195 CHECK(prefs_);
1196 update_duration_uptime_ = value;
1197 update_duration_uptime_timestamp_ = timestamp;
1198 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1199 update_duration_uptime_.ToInternalValue());
1200 if (use_logging) {
1201 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001202 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001203 }
1204}
1205
1206void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001207 Time now = system_state_->clock()->GetMonotonicTime();
1208 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001209}
1210
1211void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001212 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001213 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1214 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1215 // We're frequently called so avoid logging this write
1216 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1217}
1218
Jay Srinivasan19409b72013-04-12 19:23:36 -07001219string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1220 return prefix + "-from-" + utils::ToString(source);
1221}
1222
1223void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1224 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001225 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001226}
1227
1228void PayloadState::SetCurrentBytesDownloaded(
1229 DownloadSource source,
1230 uint64_t current_bytes_downloaded,
1231 bool log) {
1232 CHECK(prefs_);
1233
1234 if (source >= kNumDownloadSources)
1235 return;
1236
1237 // Update the in-memory value.
1238 current_bytes_downloaded_[source] = current_bytes_downloaded;
1239
1240 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1241 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1242 LOG_IF(INFO, log) << "Current bytes downloaded for "
1243 << utils::ToString(source) << " = "
1244 << GetCurrentBytesDownloaded(source);
1245}
1246
1247void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1248 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001249 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001250}
1251
1252void PayloadState::SetTotalBytesDownloaded(
1253 DownloadSource source,
1254 uint64_t total_bytes_downloaded,
1255 bool log) {
1256 CHECK(prefs_);
1257
1258 if (source >= kNumDownloadSources)
1259 return;
1260
1261 // Update the in-memory value.
1262 total_bytes_downloaded_[source] = total_bytes_downloaded;
1263
1264 // Persist.
1265 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1266 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1267 LOG_IF(INFO, log) << "Total bytes downloaded for "
1268 << utils::ToString(source) << " = "
1269 << GetTotalBytesDownloaded(source);
1270}
1271
David Zeuthena573d6f2013-06-14 16:13:36 -07001272void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001273 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001274}
1275
1276void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1277 CHECK(prefs_);
1278 num_responses_seen_ = num_responses_seen;
1279 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1280 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1281}
1282
Alex Deymob33b0f02013-08-08 21:10:02 -07001283void PayloadState::ReportUpdatesAbandonedEventCountMetric() {
1284 string metric = "Installer.UpdatesAbandonedEventCount";
1285 int value = num_responses_seen_ - 1;
1286
1287 // Do not send an "abandoned" event when 0 payloads were abandoned since the
1288 // last successful update.
1289 if (value == 0)
1290 return;
1291
1292 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1293 system_state_->metrics_lib()->SendToUMA(
1294 metric,
1295 value,
1296 0, // min value
1297 100, // max value
1298 kNumDefaultUmaBuckets);
1299}
1300
Jay Srinivasan53173b92013-05-17 17:13:01 -07001301void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001302 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001303
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001304 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001305 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001306 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001307 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1308 } else {
1309 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1310 http_url_ok = true;
1311 }
1312
1313 candidate_urls_.clear();
1314 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1315 string candidate_url = response_.payload_urls[i];
1316 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1317 continue;
1318 candidate_urls_.push_back(candidate_url);
1319 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1320 << ": " << candidate_url;
1321 }
1322
1323 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1324 << "out of " << response_.payload_urls.size() << " URLs supplied";
1325}
1326
David Zeuthene4c58bf2013-06-18 17:26:50 -07001327void PayloadState::CreateSystemUpdatedMarkerFile() {
1328 CHECK(prefs_);
1329 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1330 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1331}
1332
1333void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1334 // Send |time_to_reboot| as a UMA stat.
1335 string metric = "Installer.TimeToRebootMinutes";
1336 system_state_->metrics_lib()->SendToUMA(metric,
1337 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001338 0, // min: 0 minute
1339 30*24*60, // max: 1 month (approx)
David Zeuthene4c58bf2013-06-18 17:26:50 -07001340 kNumDefaultUmaBuckets);
1341 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1342 << " for metric " << metric;
David Zeuthen33bae492014-02-25 16:16:18 -08001343
1344 metric = metrics::kMetricTimeToRebootMinutes;
1345 system_state_->metrics_lib()->SendToUMA(metric,
1346 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001347 0, // min: 0 minute
1348 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001349 kNumDefaultUmaBuckets);
1350 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1351 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001352}
1353
1354void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001355 // Flush previous state from abnormal attempt failure, if any.
1356 ReportAndClearPersistedAttemptMetrics();
1357
Alex Deymo569c4242013-07-24 12:01:01 -07001358 // Avoid the UpdateEngineStarted actions if this is not the first time we
1359 // run the update engine since reboot.
1360 if (!system_state_->system_rebooted())
1361 return;
1362
David Zeuthene4c58bf2013-06-18 17:26:50 -07001363 // Figure out if we just booted into a new update
1364 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1365 int64_t stored_value;
1366 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1367 Time system_updated_at = Time::FromInternalValue(stored_value);
1368 if (!system_updated_at.is_null()) {
1369 TimeDelta time_to_reboot =
1370 system_state_->clock()->GetWallclockTime() - system_updated_at;
1371 if (time_to_reboot.ToInternalValue() < 0) {
1372 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1373 << utils::ToString(system_updated_at);
1374 } else {
1375 BootedIntoUpdate(time_to_reboot);
1376 }
1377 }
1378 }
1379 prefs_->Delete(kPrefsSystemUpdatedMarker);
1380 }
Alex Deymo42432912013-07-12 20:21:15 -07001381 // Check if it is needed to send metrics about a failed reboot into a new
1382 // version.
1383 ReportFailedBootIfNeeded();
1384}
1385
1386void PayloadState::ReportFailedBootIfNeeded() {
1387 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1388 // payload was marked as ready immediately before the last reboot, and we
1389 // need to check if such payload successfully rebooted or not.
1390 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001391 int64_t installed_from = 0;
1392 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001393 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1394 return;
1395 }
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001396 if (static_cast<int>(installed_from) ==
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001397 utils::GetPartitionNumber(system_state_->hardware()->BootDevice())) {
Alex Deymo42432912013-07-12 20:21:15 -07001398 // A reboot was pending, but the chromebook is again in the same
1399 // BootDevice where the update was installed from.
1400 int64_t target_attempt;
1401 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1402 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1403 "TargetVersionInstalledFrom was present.";
1404 target_attempt = 1;
1405 }
1406
1407 // Report the UMA metric of the current boot failure.
1408 string metric = "Installer.RebootToNewPartitionAttempt";
1409
1410 LOG(INFO) << "Uploading " << target_attempt
1411 << " (count) for metric " << metric;
1412 system_state_->metrics_lib()->SendToUMA(
1413 metric,
1414 target_attempt,
1415 1, // min value
1416 50, // max value
1417 kNumDefaultUmaBuckets);
David Zeuthen33bae492014-02-25 16:16:18 -08001418
1419 metric = metrics::kMetricFailedUpdateCount;
1420 LOG(INFO) << "Uploading " << target_attempt
1421 << " (count) for metric " << metric;
1422 system_state_->metrics_lib()->SendToUMA(
1423 metric,
1424 target_attempt,
1425 1, // min value
1426 50, // max value
1427 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001428 } else {
1429 prefs_->Delete(kPrefsTargetVersionAttempt);
1430 prefs_->Delete(kPrefsTargetVersionUniqueId);
1431 }
1432 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1433 }
1434}
1435
1436void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1437 // Expect to boot into the new partition in the next reboot setting the
1438 // TargetVersion* flags in the Prefs.
1439 string stored_target_version_uid;
1440 string target_version_id;
1441 string target_partition;
1442 int64_t target_attempt;
1443
1444 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1445 prefs_->GetString(kPrefsTargetVersionUniqueId,
1446 &stored_target_version_uid) &&
1447 stored_target_version_uid == target_version_uid) {
1448 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1449 target_attempt = 0;
1450 } else {
1451 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1452 target_attempt = 0;
1453 }
1454 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1455
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001456 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
1457 utils::GetPartitionNumber(
Alex Deymo42432912013-07-12 20:21:15 -07001458 system_state_->hardware()->BootDevice()));
1459}
1460
1461void PayloadState::ResetUpdateStatus() {
1462 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1463 // rebooted the next boot is not flagged as failed to rebooted into the
1464 // new applied payload.
1465 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1466
1467 // Also decrement the attempt number if it exists.
1468 int64_t target_attempt;
1469 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1470 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt-1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001471}
1472
David Zeuthendcba8092013-08-06 12:16:35 -07001473int PayloadState::GetP2PNumAttempts() {
1474 return p2p_num_attempts_;
1475}
1476
1477void PayloadState::SetP2PNumAttempts(int value) {
1478 p2p_num_attempts_ = value;
1479 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1480 CHECK(prefs_);
1481 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1482}
1483
1484void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001485 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001486}
1487
1488Time PayloadState::GetP2PFirstAttemptTimestamp() {
1489 return p2p_first_attempt_timestamp_;
1490}
1491
1492void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1493 p2p_first_attempt_timestamp_ = time;
1494 LOG(INFO) << "p2p First Attempt Timestamp = "
1495 << utils::ToString(p2p_first_attempt_timestamp_);
1496 CHECK(prefs_);
1497 int64_t stored_value = time.ToInternalValue();
1498 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1499}
1500
1501void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001502 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001503 Time stored_time = Time::FromInternalValue(stored_value);
1504 SetP2PFirstAttemptTimestamp(stored_time);
1505}
1506
1507void PayloadState::P2PNewAttempt() {
1508 CHECK(prefs_);
1509 // Set timestamp, if it hasn't been set already
1510 if (p2p_first_attempt_timestamp_.is_null()) {
1511 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1512 }
1513 // Increase number of attempts
1514 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1515}
1516
1517bool PayloadState::P2PAttemptAllowed() {
1518 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1519 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1520 << " which is greater than "
1521 << kMaxP2PAttempts
1522 << " - disallowing p2p.";
1523 return false;
1524 }
1525
1526 if (!p2p_first_attempt_timestamp_.is_null()) {
1527 Time now = system_state_->clock()->GetWallclockTime();
1528 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1529 if (time_spent_attempting_p2p.InSeconds() < 0) {
1530 LOG(ERROR) << "Time spent attempting p2p is negative"
1531 << " - disallowing p2p.";
1532 return false;
1533 }
1534 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1535 LOG(INFO) << "Time spent attempting p2p is "
1536 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1537 << " which is greater than "
1538 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1539 kMaxP2PAttemptTimeSeconds))
1540 << " - disallowing p2p.";
1541 return false;
1542 }
1543 }
1544
1545 return true;
1546}
1547
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001548} // namespace chromeos_update_engine