blob: 87965d7fba283504f2bdf0cfab69df40ffbe4248 [file] [log] [blame]
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/payload_state.h"
6
Jay Srinivasan08262882012-12-28 19:29:43 -08007#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -07008#include <string>
Jay Srinivasan08262882012-12-28 19:29:43 -08009
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080010#include <base/logging.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070011#include <base/strings/string_util.h>
12#include <base/strings/stringprintf.h>
13#include <base/format_macros.h>
Gilad Arnold1f847232014-04-07 12:07:49 -070014#include <policy/device_policy.h>
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080015
David Zeuthenf413fe52013-04-22 14:04:39 -070016#include "update_engine/clock.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070017#include "update_engine/constants.h"
Alex Deymo42432912013-07-12 20:21:15 -070018#include "update_engine/hardware_interface.h"
19#include "update_engine/install_plan.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070020#include "update_engine/omaha_request_params.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070021#include "update_engine/prefs.h"
David Zeuthenb281f072014-04-02 10:20:19 -070022#include "update_engine/real_dbus_wrapper.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070023#include "update_engine/system_state.h"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080024#include "update_engine/utils.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080025
Jay Srinivasan08262882012-12-28 19:29:43 -080026using base::Time;
27using base::TimeDelta;
28using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080029using std::string;
30
31namespace chromeos_update_engine {
32
David Zeuthen9a017f22013-04-11 16:10:26 -070033const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
34
Jay Srinivasan08262882012-12-28 19:29:43 -080035// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070036static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080037
Jay Srinivasan08262882012-12-28 19:29:43 -080038// We want to randomize retry attempts after the backoff by +/- 6 hours.
39static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080040
Jay Srinivasan19409b72013-04-12 19:23:36 -070041PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070042 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070043 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070044 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070045 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070046 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070047 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070048 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070049 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070050 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 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700360 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700361 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();
Alex Deymof329b932014-10-30 01:37:48 -0700579 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
580 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800581 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;
Alex Deymof329b932014-10-30 01:37:48 -0700791 int num_buckets = min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700792 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
Alex Deymof329b932014-10-30 01:37:48 -0700908 SetScatteringWaitPeriod(TimeDelta());
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
Gilad Arnold519cfc72014-10-02 10:34:54 -07001028void PayloadState::LoadScatteringWaitPeriod() {
1029 SetScatteringWaitPeriod(
1030 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
1031}
1032
Alex Deymof329b932014-10-30 01:37:48 -07001033void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -07001034 CHECK(prefs_);
1035 scattering_wait_period_ = wait_period;
1036 LOG(INFO) << "Scattering Wait Period (seconds) = "
1037 << scattering_wait_period_.InSeconds();
1038 if (scattering_wait_period_.InSeconds() > 0) {
1039 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
1040 scattering_wait_period_.InSeconds());
1041 } else {
1042 prefs_->Delete(kPrefsWallClockWaitPeriod);
1043 }
1044}
1045
David Zeuthencc6f9962013-04-18 11:57:24 -07001046void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001047 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -07001048}
1049
1050void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
1051 CHECK(prefs_);
1052 url_switch_count_ = url_switch_count;
1053 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
1054 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
1055}
1056
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001057void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001058 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001059}
1060
1061void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
1062 CHECK(prefs_);
1063 url_failure_count_ = url_failure_count;
1064 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
1065 << ")'s Failure Count = " << url_failure_count_;
1066 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001067}
1068
Jay Srinivasan08262882012-12-28 19:29:43 -08001069void PayloadState::LoadBackoffExpiryTime() {
1070 CHECK(prefs_);
1071 int64_t stored_value;
1072 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
1073 return;
1074
1075 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
1076 return;
1077
1078 Time stored_time = Time::FromInternalValue(stored_value);
1079 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
1080 LOG(ERROR) << "Invalid backoff expiry time ("
1081 << utils::ToString(stored_time)
1082 << ") in persisted state. Resetting.";
1083 stored_time = Time();
1084 }
1085 SetBackoffExpiryTime(stored_time);
1086}
1087
1088void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
1089 CHECK(prefs_);
1090 backoff_expiry_time_ = new_time;
1091 LOG(INFO) << "Backoff Expiry Time = "
1092 << utils::ToString(backoff_expiry_time_);
1093 prefs_->SetInt64(kPrefsBackoffExpiryTime,
1094 backoff_expiry_time_.ToInternalValue());
1095}
1096
David Zeuthen9a017f22013-04-11 16:10:26 -07001097TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001098 Time end_time = update_timestamp_end_.is_null()
1099 ? system_state_->clock()->GetWallclockTime() :
1100 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001101 return end_time - update_timestamp_start_;
1102}
1103
1104void PayloadState::LoadUpdateTimestampStart() {
1105 int64_t stored_value;
1106 Time stored_time;
1107
1108 CHECK(prefs_);
1109
David Zeuthenf413fe52013-04-22 14:04:39 -07001110 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001111
1112 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1113 // The preference missing is not unexpected - in that case, just
1114 // use the current time as start time
1115 stored_time = now;
1116 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1117 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1118 stored_time = now;
1119 } else {
1120 stored_time = Time::FromInternalValue(stored_value);
1121 }
1122
1123 // Sanity check: If the time read from disk is in the future
1124 // (modulo some slack to account for possible NTP drift
1125 // adjustments), something is fishy and we should report and
1126 // reset.
1127 TimeDelta duration_according_to_stored_time = now - stored_time;
1128 if (duration_according_to_stored_time < -kDurationSlack) {
1129 LOG(ERROR) << "The UpdateTimestampStart value ("
1130 << utils::ToString(stored_time)
1131 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001132 << utils::FormatTimeDelta(duration_according_to_stored_time)
1133 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001134 stored_time = now;
1135 }
1136
1137 SetUpdateTimestampStart(stored_time);
1138}
1139
1140void PayloadState::SetUpdateTimestampStart(const Time& value) {
1141 CHECK(prefs_);
1142 update_timestamp_start_ = value;
1143 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1144 update_timestamp_start_.ToInternalValue());
1145 LOG(INFO) << "Update Timestamp Start = "
1146 << utils::ToString(update_timestamp_start_);
1147}
1148
1149void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1150 update_timestamp_end_ = value;
1151 LOG(INFO) << "Update Timestamp End = "
1152 << utils::ToString(update_timestamp_end_);
1153}
1154
1155TimeDelta PayloadState::GetUpdateDurationUptime() {
1156 return update_duration_uptime_;
1157}
1158
1159void PayloadState::LoadUpdateDurationUptime() {
1160 int64_t stored_value;
1161 TimeDelta stored_delta;
1162
1163 CHECK(prefs_);
1164
1165 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1166 // The preference missing is not unexpected - in that case, just
1167 // we'll use zero as the delta
1168 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1169 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1170 stored_delta = TimeDelta::FromSeconds(0);
1171 } else {
1172 stored_delta = TimeDelta::FromInternalValue(stored_value);
1173 }
1174
1175 // Sanity-check: Uptime can never be greater than the wall-clock
1176 // difference (modulo some slack). If it is, report and reset
1177 // to the wall-clock difference.
1178 TimeDelta diff = GetUpdateDuration() - stored_delta;
1179 if (diff < -kDurationSlack) {
1180 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001181 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001182 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001183 << utils::FormatTimeDelta(diff)
1184 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001185 stored_delta = update_duration_current_;
1186 }
1187
1188 SetUpdateDurationUptime(stored_delta);
1189}
1190
Chris Sosabe45bef2013-04-09 18:25:12 -07001191void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001192 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001193}
1194
1195void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001196 CHECK(powerwash_safe_prefs_);
1197 string rollback_version;
1198 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1199 &rollback_version)) {
1200 SetRollbackVersion(rollback_version);
1201 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001202}
1203
1204void PayloadState::SetRollbackVersion(const string& rollback_version) {
1205 CHECK(powerwash_safe_prefs_);
1206 LOG(INFO) << "Blacklisting version "<< rollback_version;
1207 rollback_version_ = rollback_version;
1208 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001209}
1210
David Zeuthen9a017f22013-04-11 16:10:26 -07001211void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1212 const Time& timestamp,
1213 bool use_logging) {
1214 CHECK(prefs_);
1215 update_duration_uptime_ = value;
1216 update_duration_uptime_timestamp_ = timestamp;
1217 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1218 update_duration_uptime_.ToInternalValue());
1219 if (use_logging) {
1220 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001221 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001222 }
1223}
1224
1225void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001226 Time now = system_state_->clock()->GetMonotonicTime();
1227 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001228}
1229
1230void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001231 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001232 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1233 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1234 // We're frequently called so avoid logging this write
1235 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1236}
1237
Jay Srinivasan19409b72013-04-12 19:23:36 -07001238string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1239 return prefix + "-from-" + utils::ToString(source);
1240}
1241
1242void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1243 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001244 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001245}
1246
1247void PayloadState::SetCurrentBytesDownloaded(
1248 DownloadSource source,
1249 uint64_t current_bytes_downloaded,
1250 bool log) {
1251 CHECK(prefs_);
1252
1253 if (source >= kNumDownloadSources)
1254 return;
1255
1256 // Update the in-memory value.
1257 current_bytes_downloaded_[source] = current_bytes_downloaded;
1258
1259 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1260 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1261 LOG_IF(INFO, log) << "Current bytes downloaded for "
1262 << utils::ToString(source) << " = "
1263 << GetCurrentBytesDownloaded(source);
1264}
1265
1266void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1267 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001268 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001269}
1270
1271void PayloadState::SetTotalBytesDownloaded(
1272 DownloadSource source,
1273 uint64_t total_bytes_downloaded,
1274 bool log) {
1275 CHECK(prefs_);
1276
1277 if (source >= kNumDownloadSources)
1278 return;
1279
1280 // Update the in-memory value.
1281 total_bytes_downloaded_[source] = total_bytes_downloaded;
1282
1283 // Persist.
1284 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1285 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1286 LOG_IF(INFO, log) << "Total bytes downloaded for "
1287 << utils::ToString(source) << " = "
1288 << GetTotalBytesDownloaded(source);
1289}
1290
David Zeuthena573d6f2013-06-14 16:13:36 -07001291void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001292 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001293}
1294
1295void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1296 CHECK(prefs_);
1297 num_responses_seen_ = num_responses_seen;
1298 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1299 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1300}
1301
Alex Deymob33b0f02013-08-08 21:10:02 -07001302void PayloadState::ReportUpdatesAbandonedEventCountMetric() {
1303 string metric = "Installer.UpdatesAbandonedEventCount";
1304 int value = num_responses_seen_ - 1;
1305
1306 // Do not send an "abandoned" event when 0 payloads were abandoned since the
1307 // last successful update.
1308 if (value == 0)
1309 return;
1310
1311 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1312 system_state_->metrics_lib()->SendToUMA(
1313 metric,
1314 value,
1315 0, // min value
1316 100, // max value
1317 kNumDefaultUmaBuckets);
1318}
1319
Jay Srinivasan53173b92013-05-17 17:13:01 -07001320void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001321 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001322
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001323 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001324 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001325 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001326 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1327 } else {
1328 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1329 http_url_ok = true;
1330 }
1331
1332 candidate_urls_.clear();
1333 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1334 string candidate_url = response_.payload_urls[i];
1335 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1336 continue;
1337 candidate_urls_.push_back(candidate_url);
1338 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1339 << ": " << candidate_url;
1340 }
1341
1342 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1343 << "out of " << response_.payload_urls.size() << " URLs supplied";
1344}
1345
David Zeuthene4c58bf2013-06-18 17:26:50 -07001346void PayloadState::CreateSystemUpdatedMarkerFile() {
1347 CHECK(prefs_);
1348 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1349 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1350}
1351
1352void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1353 // Send |time_to_reboot| as a UMA stat.
1354 string metric = "Installer.TimeToRebootMinutes";
1355 system_state_->metrics_lib()->SendToUMA(metric,
1356 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001357 0, // min: 0 minute
1358 30*24*60, // max: 1 month (approx)
David Zeuthene4c58bf2013-06-18 17:26:50 -07001359 kNumDefaultUmaBuckets);
1360 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1361 << " for metric " << metric;
David Zeuthen33bae492014-02-25 16:16:18 -08001362
1363 metric = metrics::kMetricTimeToRebootMinutes;
1364 system_state_->metrics_lib()->SendToUMA(metric,
1365 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001366 0, // min: 0 minute
1367 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001368 kNumDefaultUmaBuckets);
1369 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1370 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001371}
1372
1373void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001374 // Flush previous state from abnormal attempt failure, if any.
1375 ReportAndClearPersistedAttemptMetrics();
1376
Alex Deymo569c4242013-07-24 12:01:01 -07001377 // Avoid the UpdateEngineStarted actions if this is not the first time we
1378 // run the update engine since reboot.
1379 if (!system_state_->system_rebooted())
1380 return;
1381
David Zeuthene4c58bf2013-06-18 17:26:50 -07001382 // Figure out if we just booted into a new update
1383 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1384 int64_t stored_value;
1385 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1386 Time system_updated_at = Time::FromInternalValue(stored_value);
1387 if (!system_updated_at.is_null()) {
1388 TimeDelta time_to_reboot =
1389 system_state_->clock()->GetWallclockTime() - system_updated_at;
1390 if (time_to_reboot.ToInternalValue() < 0) {
1391 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1392 << utils::ToString(system_updated_at);
1393 } else {
1394 BootedIntoUpdate(time_to_reboot);
1395 }
1396 }
1397 }
1398 prefs_->Delete(kPrefsSystemUpdatedMarker);
1399 }
Alex Deymo42432912013-07-12 20:21:15 -07001400 // Check if it is needed to send metrics about a failed reboot into a new
1401 // version.
1402 ReportFailedBootIfNeeded();
1403}
1404
1405void PayloadState::ReportFailedBootIfNeeded() {
1406 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1407 // payload was marked as ready immediately before the last reboot, and we
1408 // need to check if such payload successfully rebooted or not.
1409 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001410 int64_t installed_from = 0;
1411 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001412 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1413 return;
1414 }
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001415 if (static_cast<int>(installed_from) ==
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001416 utils::GetPartitionNumber(system_state_->hardware()->BootDevice())) {
Alex Deymo42432912013-07-12 20:21:15 -07001417 // A reboot was pending, but the chromebook is again in the same
1418 // BootDevice where the update was installed from.
1419 int64_t target_attempt;
1420 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1421 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1422 "TargetVersionInstalledFrom was present.";
1423 target_attempt = 1;
1424 }
1425
1426 // Report the UMA metric of the current boot failure.
1427 string metric = "Installer.RebootToNewPartitionAttempt";
1428
1429 LOG(INFO) << "Uploading " << target_attempt
1430 << " (count) for metric " << metric;
1431 system_state_->metrics_lib()->SendToUMA(
1432 metric,
1433 target_attempt,
1434 1, // min value
1435 50, // max value
1436 kNumDefaultUmaBuckets);
David Zeuthen33bae492014-02-25 16:16:18 -08001437
1438 metric = metrics::kMetricFailedUpdateCount;
1439 LOG(INFO) << "Uploading " << target_attempt
1440 << " (count) for metric " << metric;
1441 system_state_->metrics_lib()->SendToUMA(
1442 metric,
1443 target_attempt,
1444 1, // min value
1445 50, // max value
1446 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001447 } else {
1448 prefs_->Delete(kPrefsTargetVersionAttempt);
1449 prefs_->Delete(kPrefsTargetVersionUniqueId);
1450 }
1451 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1452 }
1453}
1454
1455void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1456 // Expect to boot into the new partition in the next reboot setting the
1457 // TargetVersion* flags in the Prefs.
1458 string stored_target_version_uid;
1459 string target_version_id;
1460 string target_partition;
1461 int64_t target_attempt;
1462
1463 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1464 prefs_->GetString(kPrefsTargetVersionUniqueId,
1465 &stored_target_version_uid) &&
1466 stored_target_version_uid == target_version_uid) {
1467 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1468 target_attempt = 0;
1469 } else {
1470 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1471 target_attempt = 0;
1472 }
1473 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1474
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001475 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
1476 utils::GetPartitionNumber(
Alex Deymo42432912013-07-12 20:21:15 -07001477 system_state_->hardware()->BootDevice()));
1478}
1479
1480void PayloadState::ResetUpdateStatus() {
1481 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1482 // rebooted the next boot is not flagged as failed to rebooted into the
1483 // new applied payload.
1484 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1485
1486 // Also decrement the attempt number if it exists.
1487 int64_t target_attempt;
1488 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1489 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt-1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001490}
1491
David Zeuthendcba8092013-08-06 12:16:35 -07001492int PayloadState::GetP2PNumAttempts() {
1493 return p2p_num_attempts_;
1494}
1495
1496void PayloadState::SetP2PNumAttempts(int value) {
1497 p2p_num_attempts_ = value;
1498 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1499 CHECK(prefs_);
1500 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1501}
1502
1503void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001504 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001505}
1506
1507Time PayloadState::GetP2PFirstAttemptTimestamp() {
1508 return p2p_first_attempt_timestamp_;
1509}
1510
1511void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1512 p2p_first_attempt_timestamp_ = time;
1513 LOG(INFO) << "p2p First Attempt Timestamp = "
1514 << utils::ToString(p2p_first_attempt_timestamp_);
1515 CHECK(prefs_);
1516 int64_t stored_value = time.ToInternalValue();
1517 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1518}
1519
1520void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001521 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001522 Time stored_time = Time::FromInternalValue(stored_value);
1523 SetP2PFirstAttemptTimestamp(stored_time);
1524}
1525
1526void PayloadState::P2PNewAttempt() {
1527 CHECK(prefs_);
1528 // Set timestamp, if it hasn't been set already
1529 if (p2p_first_attempt_timestamp_.is_null()) {
1530 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1531 }
1532 // Increase number of attempts
1533 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1534}
1535
1536bool PayloadState::P2PAttemptAllowed() {
1537 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1538 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1539 << " which is greater than "
1540 << kMaxP2PAttempts
1541 << " - disallowing p2p.";
1542 return false;
1543 }
1544
1545 if (!p2p_first_attempt_timestamp_.is_null()) {
1546 Time now = system_state_->clock()->GetWallclockTime();
1547 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1548 if (time_spent_attempting_p2p.InSeconds() < 0) {
1549 LOG(ERROR) << "Time spent attempting p2p is negative"
1550 << " - disallowing p2p.";
1551 return false;
1552 }
1553 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1554 LOG(INFO) << "Time spent attempting p2p is "
1555 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1556 << " which is greater than "
1557 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1558 kMaxP2PAttemptTimeSeconds))
1559 << " - disallowing p2p.";
1560 return false;
1561 }
1562 }
1563
1564 return true;
1565}
1566
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001567} // namespace chromeos_update_engine