blob: 1dd2ee6b761830938d45885ad6158f254cb26818 [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:
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
Chris Sosaaa18e162013-06-20 13:20:30 -0700909}
910
911void PayloadState::ResetRollbackVersion() {
912 CHECK(powerwash_safe_prefs_);
913 rollback_version_ = "";
914 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700915}
916
917void PayloadState::ResetDownloadSourcesOnNewUpdate() {
918 for (int i = 0; i < kNumDownloadSources; i++) {
919 DownloadSource source = static_cast<DownloadSource>(i);
920 SetCurrentBytesDownloaded(source, 0, true);
921 // Note: Not resetting the TotalBytesDownloaded as we want that metric
922 // to count the bytes downloaded across various update attempts until
923 // we have successfully applied the update.
924 }
925}
926
Chris Sosab3dcdb32013-09-04 15:22:12 -0700927int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700928 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700929 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700930 return 0;
931
932 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700933 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700934 return 0;
935
936 if (stored_value < 0) {
937 LOG(ERROR) << key << ": Invalid value (" << stored_value
938 << ") in persisted state. Defaulting to 0";
939 return 0;
940 }
941
942 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800943}
944
945string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700946 string response_sign = base::StringPrintf(
947 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800948
Jay Srinivasan53173b92013-05-17 17:13:01 -0700949 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700950 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
951 static_cast<int>(i),
952 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800953
Alex Vakulenko75039d72014-03-25 12:36:28 -0700954 response_sign += base::StringPrintf(
955 "Payload Size = %ju\n"
956 "Payload Sha256 Hash = %s\n"
957 "Metadata Size = %ju\n"
958 "Metadata Signature = %s\n"
959 "Is Delta Payload = %d\n"
960 "Max Failure Count Per Url = %d\n"
961 "Disable Payload Backoff = %d\n",
962 static_cast<uintmax_t>(response_.size),
963 response_.hash.c_str(),
964 static_cast<uintmax_t>(response_.metadata_size),
965 response_.metadata_signature.c_str(),
966 response_.is_delta_payload,
967 response_.max_failure_count_per_url,
968 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800969 return response_sign;
970}
971
972void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800973 CHECK(prefs_);
974 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800975 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
976 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
977 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800978 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800979}
980
Jay Srinivasan19409b72013-04-12 19:23:36 -0700981void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800982 CHECK(prefs_);
983 response_signature_ = response_signature;
984 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
985 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
986}
987
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800988void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700989 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800990}
991
Alex Deymo820cc702013-06-28 15:43:46 -0700992void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700993 SetFullPayloadAttemptNumber(GetPersistedValue(
994 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700995}
996
997void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800998 CHECK(prefs_);
999 payload_attempt_number_ = payload_attempt_number;
1000 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
1001 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
1002}
1003
Alex Deymo820cc702013-06-28 15:43:46 -07001004void PayloadState::SetFullPayloadAttemptNumber(
1005 int full_payload_attempt_number) {
1006 CHECK(prefs_);
1007 full_payload_attempt_number_ = full_payload_attempt_number;
1008 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
1009 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
1010 full_payload_attempt_number_);
1011}
1012
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001013void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001014 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001015}
1016
1017void PayloadState::SetUrlIndex(uint32_t url_index) {
1018 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001019 url_index_ = url_index;
1020 LOG(INFO) << "Current URL Index = " << url_index_;
1021 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001022
1023 // Also update the download source, which is purely dependent on the
1024 // current URL index alone.
1025 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001026}
1027
David Zeuthencc6f9962013-04-18 11:57:24 -07001028void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001029 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -07001030}
1031
1032void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
1033 CHECK(prefs_);
1034 url_switch_count_ = url_switch_count;
1035 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
1036 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
1037}
1038
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001039void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001040 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001041}
1042
1043void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
1044 CHECK(prefs_);
1045 url_failure_count_ = url_failure_count;
1046 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
1047 << ")'s Failure Count = " << url_failure_count_;
1048 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001049}
1050
Jay Srinivasan08262882012-12-28 19:29:43 -08001051void PayloadState::LoadBackoffExpiryTime() {
1052 CHECK(prefs_);
1053 int64_t stored_value;
1054 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
1055 return;
1056
1057 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
1058 return;
1059
1060 Time stored_time = Time::FromInternalValue(stored_value);
1061 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
1062 LOG(ERROR) << "Invalid backoff expiry time ("
1063 << utils::ToString(stored_time)
1064 << ") in persisted state. Resetting.";
1065 stored_time = Time();
1066 }
1067 SetBackoffExpiryTime(stored_time);
1068}
1069
1070void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
1071 CHECK(prefs_);
1072 backoff_expiry_time_ = new_time;
1073 LOG(INFO) << "Backoff Expiry Time = "
1074 << utils::ToString(backoff_expiry_time_);
1075 prefs_->SetInt64(kPrefsBackoffExpiryTime,
1076 backoff_expiry_time_.ToInternalValue());
1077}
1078
David Zeuthen9a017f22013-04-11 16:10:26 -07001079TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001080 Time end_time = update_timestamp_end_.is_null()
1081 ? system_state_->clock()->GetWallclockTime() :
1082 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001083 return end_time - update_timestamp_start_;
1084}
1085
1086void PayloadState::LoadUpdateTimestampStart() {
1087 int64_t stored_value;
1088 Time stored_time;
1089
1090 CHECK(prefs_);
1091
David Zeuthenf413fe52013-04-22 14:04:39 -07001092 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001093
1094 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1095 // The preference missing is not unexpected - in that case, just
1096 // use the current time as start time
1097 stored_time = now;
1098 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1099 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1100 stored_time = now;
1101 } else {
1102 stored_time = Time::FromInternalValue(stored_value);
1103 }
1104
1105 // Sanity check: If the time read from disk is in the future
1106 // (modulo some slack to account for possible NTP drift
1107 // adjustments), something is fishy and we should report and
1108 // reset.
1109 TimeDelta duration_according_to_stored_time = now - stored_time;
1110 if (duration_according_to_stored_time < -kDurationSlack) {
1111 LOG(ERROR) << "The UpdateTimestampStart value ("
1112 << utils::ToString(stored_time)
1113 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001114 << utils::FormatTimeDelta(duration_according_to_stored_time)
1115 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001116 stored_time = now;
1117 }
1118
1119 SetUpdateTimestampStart(stored_time);
1120}
1121
1122void PayloadState::SetUpdateTimestampStart(const Time& value) {
1123 CHECK(prefs_);
1124 update_timestamp_start_ = value;
1125 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1126 update_timestamp_start_.ToInternalValue());
1127 LOG(INFO) << "Update Timestamp Start = "
1128 << utils::ToString(update_timestamp_start_);
1129}
1130
1131void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1132 update_timestamp_end_ = value;
1133 LOG(INFO) << "Update Timestamp End = "
1134 << utils::ToString(update_timestamp_end_);
1135}
1136
1137TimeDelta PayloadState::GetUpdateDurationUptime() {
1138 return update_duration_uptime_;
1139}
1140
1141void PayloadState::LoadUpdateDurationUptime() {
1142 int64_t stored_value;
1143 TimeDelta stored_delta;
1144
1145 CHECK(prefs_);
1146
1147 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1148 // The preference missing is not unexpected - in that case, just
1149 // we'll use zero as the delta
1150 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1151 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1152 stored_delta = TimeDelta::FromSeconds(0);
1153 } else {
1154 stored_delta = TimeDelta::FromInternalValue(stored_value);
1155 }
1156
1157 // Sanity-check: Uptime can never be greater than the wall-clock
1158 // difference (modulo some slack). If it is, report and reset
1159 // to the wall-clock difference.
1160 TimeDelta diff = GetUpdateDuration() - stored_delta;
1161 if (diff < -kDurationSlack) {
1162 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001163 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001164 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001165 << utils::FormatTimeDelta(diff)
1166 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001167 stored_delta = update_duration_current_;
1168 }
1169
1170 SetUpdateDurationUptime(stored_delta);
1171}
1172
Chris Sosabe45bef2013-04-09 18:25:12 -07001173void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001174 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001175}
1176
1177void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001178 CHECK(powerwash_safe_prefs_);
1179 string rollback_version;
1180 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1181 &rollback_version)) {
1182 SetRollbackVersion(rollback_version);
1183 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001184}
1185
1186void PayloadState::SetRollbackVersion(const string& rollback_version) {
1187 CHECK(powerwash_safe_prefs_);
1188 LOG(INFO) << "Blacklisting version "<< rollback_version;
1189 rollback_version_ = rollback_version;
1190 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001191}
1192
David Zeuthen9a017f22013-04-11 16:10:26 -07001193void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1194 const Time& timestamp,
1195 bool use_logging) {
1196 CHECK(prefs_);
1197 update_duration_uptime_ = value;
1198 update_duration_uptime_timestamp_ = timestamp;
1199 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1200 update_duration_uptime_.ToInternalValue());
1201 if (use_logging) {
1202 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001203 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001204 }
1205}
1206
1207void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001208 Time now = system_state_->clock()->GetMonotonicTime();
1209 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001210}
1211
1212void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001213 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001214 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1215 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1216 // We're frequently called so avoid logging this write
1217 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1218}
1219
Jay Srinivasan19409b72013-04-12 19:23:36 -07001220string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1221 return prefix + "-from-" + utils::ToString(source);
1222}
1223
1224void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1225 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001226 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001227}
1228
1229void PayloadState::SetCurrentBytesDownloaded(
1230 DownloadSource source,
1231 uint64_t current_bytes_downloaded,
1232 bool log) {
1233 CHECK(prefs_);
1234
1235 if (source >= kNumDownloadSources)
1236 return;
1237
1238 // Update the in-memory value.
1239 current_bytes_downloaded_[source] = current_bytes_downloaded;
1240
1241 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1242 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1243 LOG_IF(INFO, log) << "Current bytes downloaded for "
1244 << utils::ToString(source) << " = "
1245 << GetCurrentBytesDownloaded(source);
1246}
1247
1248void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1249 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001250 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001251}
1252
1253void PayloadState::SetTotalBytesDownloaded(
1254 DownloadSource source,
1255 uint64_t total_bytes_downloaded,
1256 bool log) {
1257 CHECK(prefs_);
1258
1259 if (source >= kNumDownloadSources)
1260 return;
1261
1262 // Update the in-memory value.
1263 total_bytes_downloaded_[source] = total_bytes_downloaded;
1264
1265 // Persist.
1266 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1267 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1268 LOG_IF(INFO, log) << "Total bytes downloaded for "
1269 << utils::ToString(source) << " = "
1270 << GetTotalBytesDownloaded(source);
1271}
1272
David Zeuthena573d6f2013-06-14 16:13:36 -07001273void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001274 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001275}
1276
1277void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1278 CHECK(prefs_);
1279 num_responses_seen_ = num_responses_seen;
1280 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1281 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1282}
1283
Alex Deymob33b0f02013-08-08 21:10:02 -07001284void PayloadState::ReportUpdatesAbandonedEventCountMetric() {
1285 string metric = "Installer.UpdatesAbandonedEventCount";
1286 int value = num_responses_seen_ - 1;
1287
1288 // Do not send an "abandoned" event when 0 payloads were abandoned since the
1289 // last successful update.
1290 if (value == 0)
1291 return;
1292
1293 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1294 system_state_->metrics_lib()->SendToUMA(
1295 metric,
1296 value,
1297 0, // min value
1298 100, // max value
1299 kNumDefaultUmaBuckets);
1300}
1301
Jay Srinivasan53173b92013-05-17 17:13:01 -07001302void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001303 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001304
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001305 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001306 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001307 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001308 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1309 } else {
1310 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1311 http_url_ok = true;
1312 }
1313
1314 candidate_urls_.clear();
1315 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1316 string candidate_url = response_.payload_urls[i];
1317 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1318 continue;
1319 candidate_urls_.push_back(candidate_url);
1320 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1321 << ": " << candidate_url;
1322 }
1323
1324 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1325 << "out of " << response_.payload_urls.size() << " URLs supplied";
1326}
1327
David Zeuthene4c58bf2013-06-18 17:26:50 -07001328void PayloadState::CreateSystemUpdatedMarkerFile() {
1329 CHECK(prefs_);
1330 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1331 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1332}
1333
1334void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1335 // Send |time_to_reboot| as a UMA stat.
1336 string metric = "Installer.TimeToRebootMinutes";
1337 system_state_->metrics_lib()->SendToUMA(metric,
1338 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001339 0, // min: 0 minute
1340 30*24*60, // max: 1 month (approx)
David Zeuthene4c58bf2013-06-18 17:26:50 -07001341 kNumDefaultUmaBuckets);
1342 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1343 << " for metric " << metric;
David Zeuthen33bae492014-02-25 16:16:18 -08001344
1345 metric = metrics::kMetricTimeToRebootMinutes;
1346 system_state_->metrics_lib()->SendToUMA(metric,
1347 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001348 0, // min: 0 minute
1349 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001350 kNumDefaultUmaBuckets);
1351 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1352 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001353}
1354
1355void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001356 // Flush previous state from abnormal attempt failure, if any.
1357 ReportAndClearPersistedAttemptMetrics();
1358
Alex Deymo569c4242013-07-24 12:01:01 -07001359 // Avoid the UpdateEngineStarted actions if this is not the first time we
1360 // run the update engine since reboot.
1361 if (!system_state_->system_rebooted())
1362 return;
1363
David Zeuthene4c58bf2013-06-18 17:26:50 -07001364 // Figure out if we just booted into a new update
1365 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1366 int64_t stored_value;
1367 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1368 Time system_updated_at = Time::FromInternalValue(stored_value);
1369 if (!system_updated_at.is_null()) {
1370 TimeDelta time_to_reboot =
1371 system_state_->clock()->GetWallclockTime() - system_updated_at;
1372 if (time_to_reboot.ToInternalValue() < 0) {
1373 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1374 << utils::ToString(system_updated_at);
1375 } else {
1376 BootedIntoUpdate(time_to_reboot);
1377 }
1378 }
1379 }
1380 prefs_->Delete(kPrefsSystemUpdatedMarker);
1381 }
Alex Deymo42432912013-07-12 20:21:15 -07001382 // Check if it is needed to send metrics about a failed reboot into a new
1383 // version.
1384 ReportFailedBootIfNeeded();
1385}
1386
1387void PayloadState::ReportFailedBootIfNeeded() {
1388 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1389 // payload was marked as ready immediately before the last reboot, and we
1390 // need to check if such payload successfully rebooted or not.
1391 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001392 int64_t installed_from = 0;
1393 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001394 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1395 return;
1396 }
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001397 if (static_cast<int>(installed_from) ==
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001398 utils::GetPartitionNumber(system_state_->hardware()->BootDevice())) {
Alex Deymo42432912013-07-12 20:21:15 -07001399 // A reboot was pending, but the chromebook is again in the same
1400 // BootDevice where the update was installed from.
1401 int64_t target_attempt;
1402 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1403 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1404 "TargetVersionInstalledFrom was present.";
1405 target_attempt = 1;
1406 }
1407
1408 // Report the UMA metric of the current boot failure.
1409 string metric = "Installer.RebootToNewPartitionAttempt";
1410
1411 LOG(INFO) << "Uploading " << target_attempt
1412 << " (count) for metric " << metric;
1413 system_state_->metrics_lib()->SendToUMA(
1414 metric,
1415 target_attempt,
1416 1, // min value
1417 50, // max value
1418 kNumDefaultUmaBuckets);
David Zeuthen33bae492014-02-25 16:16:18 -08001419
1420 metric = metrics::kMetricFailedUpdateCount;
1421 LOG(INFO) << "Uploading " << target_attempt
1422 << " (count) for metric " << metric;
1423 system_state_->metrics_lib()->SendToUMA(
1424 metric,
1425 target_attempt,
1426 1, // min value
1427 50, // max value
1428 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001429 } else {
1430 prefs_->Delete(kPrefsTargetVersionAttempt);
1431 prefs_->Delete(kPrefsTargetVersionUniqueId);
1432 }
1433 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1434 }
1435}
1436
1437void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1438 // Expect to boot into the new partition in the next reboot setting the
1439 // TargetVersion* flags in the Prefs.
1440 string stored_target_version_uid;
1441 string target_version_id;
1442 string target_partition;
1443 int64_t target_attempt;
1444
1445 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1446 prefs_->GetString(kPrefsTargetVersionUniqueId,
1447 &stored_target_version_uid) &&
1448 stored_target_version_uid == target_version_uid) {
1449 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1450 target_attempt = 0;
1451 } else {
1452 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1453 target_attempt = 0;
1454 }
1455 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1456
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001457 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
1458 utils::GetPartitionNumber(
Alex Deymo42432912013-07-12 20:21:15 -07001459 system_state_->hardware()->BootDevice()));
1460}
1461
1462void PayloadState::ResetUpdateStatus() {
1463 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1464 // rebooted the next boot is not flagged as failed to rebooted into the
1465 // new applied payload.
1466 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1467
1468 // Also decrement the attempt number if it exists.
1469 int64_t target_attempt;
1470 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1471 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt-1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001472}
1473
David Zeuthendcba8092013-08-06 12:16:35 -07001474int PayloadState::GetP2PNumAttempts() {
1475 return p2p_num_attempts_;
1476}
1477
1478void PayloadState::SetP2PNumAttempts(int value) {
1479 p2p_num_attempts_ = value;
1480 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1481 CHECK(prefs_);
1482 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1483}
1484
1485void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001486 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001487}
1488
1489Time PayloadState::GetP2PFirstAttemptTimestamp() {
1490 return p2p_first_attempt_timestamp_;
1491}
1492
1493void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1494 p2p_first_attempt_timestamp_ = time;
1495 LOG(INFO) << "p2p First Attempt Timestamp = "
1496 << utils::ToString(p2p_first_attempt_timestamp_);
1497 CHECK(prefs_);
1498 int64_t stored_value = time.ToInternalValue();
1499 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1500}
1501
1502void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001503 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001504 Time stored_time = Time::FromInternalValue(stored_value);
1505 SetP2PFirstAttemptTimestamp(stored_time);
1506}
1507
1508void PayloadState::P2PNewAttempt() {
1509 CHECK(prefs_);
1510 // Set timestamp, if it hasn't been set already
1511 if (p2p_first_attempt_timestamp_.is_null()) {
1512 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1513 }
1514 // Increase number of attempts
1515 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1516}
1517
1518bool PayloadState::P2PAttemptAllowed() {
1519 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1520 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1521 << " which is greater than "
1522 << kMaxP2PAttempts
1523 << " - disallowing p2p.";
1524 return false;
1525 }
1526
1527 if (!p2p_first_attempt_timestamp_.is_null()) {
1528 Time now = system_state_->clock()->GetWallclockTime();
1529 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1530 if (time_spent_attempting_p2p.InSeconds() < 0) {
1531 LOG(ERROR) << "Time spent attempting p2p is negative"
1532 << " - disallowing p2p.";
1533 return false;
1534 }
1535 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1536 LOG(INFO) << "Time spent attempting p2p is "
1537 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1538 << " which is greater than "
1539 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1540 kMaxP2PAttemptTimeSeconds))
1541 << " - disallowing p2p.";
1542 return false;
1543 }
1544 }
1545
1546 return true;
1547}
1548
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001549} // namespace chromeos_update_engine