blob: c17623816c750346c52d3983c5d6a922b2d68496 [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>
8
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08009#include <base/logging.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070010#include <base/strings/string_util.h>
11#include <base/strings/stringprintf.h>
12#include <base/format_macros.h>
Gilad Arnold1f847232014-04-07 12:07:49 -070013#include <policy/device_policy.h>
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080014
David Zeuthenf413fe52013-04-22 14:04:39 -070015#include "update_engine/clock.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070016#include "update_engine/constants.h"
Alex Deymo42432912013-07-12 20:21:15 -070017#include "update_engine/hardware_interface.h"
18#include "update_engine/install_plan.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070019#include "update_engine/omaha_request_params.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070020#include "update_engine/prefs.h"
David Zeuthenb281f072014-04-02 10:20:19 -070021#include "update_engine/real_dbus_wrapper.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070022#include "update_engine/system_state.h"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080023#include "update_engine/utils.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080024
Jay Srinivasan08262882012-12-28 19:29:43 -080025using base::Time;
26using base::TimeDelta;
27using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080028using std::string;
29
30namespace chromeos_update_engine {
31
David Zeuthen9a017f22013-04-11 16:10:26 -070032const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
33
Jay Srinivasan08262882012-12-28 19:29:43 -080034// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070035static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080036
Jay Srinivasan08262882012-12-28 19:29:43 -080037// We want to randomize retry attempts after the backoff by +/- 6 hours.
38static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080039
Jay Srinivasan19409b72013-04-12 19:23:36 -070040PayloadState::PayloadState()
41 : prefs_(NULL),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070042 using_p2p_for_downloading_(false),
Jay Srinivasan19409b72013-04-12 19:23:36 -070043 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070044 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070045 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070046 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070047 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070048 p2p_num_attempts_(0),
49 attempt_num_bytes_downloaded_(0),
50 attempt_connection_type_(metrics::ConnectionType::kUnknown),
51 attempt_type_(AttemptType::kUpdate)
52{
Jay Srinivasan19409b72013-04-12 19:23:36 -070053 for (int i = 0; i <= kNumDownloadSources; i++)
54 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
55}
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) {
165 attempt_type_ = attempt_type;
166
David Zeuthen33bae492014-02-25 16:16:18 -0800167 ClockInterface *clock = system_state_->clock();
168 attempt_start_time_boot_ = clock->GetBootTime();
169 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800170 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700171
172 metrics::ConnectionType type;
173 NetworkConnectionType network_connection_type;
174 NetworkTethering tethering;
175 RealDBusWrapper dbus_iface;
176 ConnectionManager* connection_manager = system_state_->connection_manager();
177 if (!connection_manager->GetConnectionProperties(&dbus_iface,
178 &network_connection_type,
179 &tethering)) {
180 LOG(ERROR) << "Failed to determine connection type.";
181 type = metrics::ConnectionType::kUnknown;
182 } else {
183 type = utils::GetConnectionType(network_connection_type, tethering);
184 }
185 attempt_connection_type_ = type;
David Zeuthen33bae492014-02-25 16:16:18 -0800186}
187
Chris Sosabe45bef2013-04-09 18:25:12 -0700188void PayloadState::UpdateResumed() {
189 LOG(INFO) << "Resuming an update that was previously started.";
190 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700191 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700192}
193
Jay Srinivasan19409b72013-04-12 19:23:36 -0700194void PayloadState::UpdateRestarted() {
195 LOG(INFO) << "Starting a new update";
196 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700197 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700198 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700199}
200
David Zeuthen9a017f22013-04-11 16:10:26 -0700201void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700202 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700203 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700204 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800205
David Zeuthen96197df2014-04-16 12:22:39 -0700206 switch (attempt_type_) {
207 case AttemptType::kUpdate:
208 CollectAndReportAttemptMetrics(kErrorCodeSuccess);
209 CollectAndReportSuccessfulUpdateMetrics();
210 break;
211
212 case AttemptType::kRollback:
213 metrics::ReportRollbackMetrics(system_state_,
214 metrics::RollbackResult::kSuccess);
215 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700216 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700217
218 // Reset the number of responses seen since it counts from the last
219 // successful update, e.g. now.
220 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700221
222 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700223}
224
David Zeuthena99981f2013-04-29 13:42:47 -0700225void PayloadState::UpdateFailed(ErrorCode error) {
226 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800227 LOG(INFO) << "Updating payload state for error code: " << base_error
228 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800229
Jay Srinivasan53173b92013-05-17 17:13:01 -0700230 if (candidate_urls_.size() == 0) {
231 // This means we got this error even before we got a valid Omaha response
232 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800233 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800234 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
235 return;
236 }
237
David Zeuthen96197df2014-04-16 12:22:39 -0700238 switch (attempt_type_) {
239 case AttemptType::kUpdate:
240 CollectAndReportAttemptMetrics(base_error);
241 break;
242
243 case AttemptType::kRollback:
244 metrics::ReportRollbackMetrics(system_state_,
245 metrics::RollbackResult::kFailed);
246 break;
247 }
David Zeuthen33bae492014-02-25 16:16:18 -0800248
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800249 switch (base_error) {
250 // Errors which are good indicators of a problem with a particular URL or
251 // the protocol used in the URL or entities in the communication channel
252 // (e.g. proxies). We should try the next available URL in the next update
253 // check to quickly recover from these errors.
David Zeuthena99981f2013-04-29 13:42:47 -0700254 case kErrorCodePayloadHashMismatchError:
255 case kErrorCodePayloadSizeMismatchError:
256 case kErrorCodeDownloadPayloadVerificationError:
257 case kErrorCodeDownloadPayloadPubKeyVerificationError:
258 case kErrorCodeSignedDeltaPayloadExpectedError:
259 case kErrorCodeDownloadInvalidMetadataMagicString:
260 case kErrorCodeDownloadSignatureMissingInManifest:
261 case kErrorCodeDownloadManifestParseError:
262 case kErrorCodeDownloadMetadataSignatureError:
263 case kErrorCodeDownloadMetadataSignatureVerificationError:
264 case kErrorCodeDownloadMetadataSignatureMismatch:
265 case kErrorCodeDownloadOperationHashVerificationError:
266 case kErrorCodeDownloadOperationExecutionError:
267 case kErrorCodeDownloadOperationHashMismatch:
268 case kErrorCodeDownloadInvalidMetadataSize:
269 case kErrorCodeDownloadInvalidMetadataSignature:
270 case kErrorCodeDownloadOperationHashMissingError:
271 case kErrorCodeDownloadMetadataSignatureMissingError:
Gilad Arnold21504f02013-05-24 08:51:22 -0700272 case kErrorCodePayloadMismatchedType:
Don Garrett4d039442013-10-28 18:40:06 -0700273 case kErrorCodeUnsupportedMajorPayloadVersion:
274 case kErrorCodeUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800275 IncrementUrlIndex();
276 break;
277
278 // Errors which seem to be just transient network/communication related
279 // failures and do not indicate any inherent problem with the URL itself.
280 // So, we should keep the current URL but just increment the
281 // failure count to give it more chances. This way, while we maximize our
282 // chances of downloading from the URLs that appear earlier in the response
283 // (because download from a local server URL that appears earlier in a
284 // response is preferable than downloading from the next URL which could be
285 // a internet URL and thus could be more expensive).
David Zeuthena99981f2013-04-29 13:42:47 -0700286 case kErrorCodeError:
287 case kErrorCodeDownloadTransferError:
288 case kErrorCodeDownloadWriteError:
289 case kErrorCodeDownloadStateInitializationError:
290 case kErrorCodeOmahaErrorInHTTPResponse: // Aggregate code for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800291 IncrementFailureCount();
292 break;
293
294 // Errors which are not specific to a URL and hence shouldn't result in
295 // the URL being penalized. This can happen in two cases:
296 // 1. We haven't started downloading anything: These errors don't cost us
297 // anything in terms of actual payload bytes, so we should just do the
298 // regular retries at the next update check.
299 // 2. We have successfully downloaded the payload: In this case, the
300 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800301 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800302 // In either case, there's no need to update URL index or failure count.
David Zeuthena99981f2013-04-29 13:42:47 -0700303 case kErrorCodeOmahaRequestError:
304 case kErrorCodeOmahaResponseHandlerError:
305 case kErrorCodePostinstallRunnerError:
306 case kErrorCodeFilesystemCopierError:
307 case kErrorCodeInstallDeviceOpenError:
308 case kErrorCodeKernelDeviceOpenError:
309 case kErrorCodeDownloadNewPartitionInfoError:
310 case kErrorCodeNewRootfsVerificationError:
311 case kErrorCodeNewKernelVerificationError:
312 case kErrorCodePostinstallBootedFromFirmwareB:
Don Garrett81018e02013-07-30 18:46:31 -0700313 case kErrorCodePostinstallFirmwareRONotUpdatable:
David Zeuthena99981f2013-04-29 13:42:47 -0700314 case kErrorCodeOmahaRequestEmptyResponseError:
315 case kErrorCodeOmahaRequestXMLParseError:
316 case kErrorCodeOmahaResponseInvalid:
317 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
318 case kErrorCodeOmahaUpdateDeferredPerPolicy:
319 case kErrorCodeOmahaUpdateDeferredForBackoff:
320 case kErrorCodePostinstallPowerwashError:
321 case kErrorCodeUpdateCanceledByChannelChange:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800322 LOG(INFO) << "Not incrementing URL index or failure count for this error";
323 break;
324
David Zeuthena99981f2013-04-29 13:42:47 -0700325 case kErrorCodeSuccess: // success code
David Zeuthena99981f2013-04-29 13:42:47 -0700326 case kErrorCodeUmaReportedMax: // not an error code
327 case kErrorCodeOmahaRequestHTTPResponseBase: // aggregated already
328 case kErrorCodeDevModeFlag: // not an error code
329 case kErrorCodeResumedFlag: // not an error code
330 case kErrorCodeTestImageFlag: // not an error code
331 case kErrorCodeTestOmahaUrlFlag: // not an error code
332 case kErrorCodeSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800333 // These shouldn't happen. Enumerating these explicitly here so that we
334 // can let the compiler warn about new error codes that are added to
335 // action_processor.h but not added here.
336 LOG(WARNING) << "Unexpected error code for UpdateFailed";
337 break;
338
339 // Note: Not adding a default here so as to let the compiler warn us of
340 // any new enums that were added in the .h but not listed in this switch.
341 }
342}
343
Jay Srinivasan08262882012-12-28 19:29:43 -0800344bool PayloadState::ShouldBackoffDownload() {
345 if (response_.disable_payload_backoff) {
346 LOG(INFO) << "Payload backoff logic is disabled. "
347 "Can proceed with the download";
348 return false;
349 }
Chris Sosa20f005c2013-09-05 13:53:08 -0700350 if (system_state_->request_params()->use_p2p_for_downloading() &&
351 !system_state_->request_params()->p2p_url().empty()) {
352 LOG(INFO) << "Payload backoff logic is disabled because download "
353 << "will happen from local peer (via p2p).";
354 return false;
355 }
356 if (system_state_->request_params()->interactive()) {
357 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
358 return false;
359 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800360 if (response_.is_delta_payload) {
361 // If delta payloads fail, we want to fallback quickly to full payloads as
362 // they are more likely to succeed. Exponential backoffs would greatly
363 // slow down the fallback to full payloads. So we don't backoff for delta
364 // payloads.
365 LOG(INFO) << "No backoffs for delta payloads. "
366 << "Can proceed with the download";
367 return false;
368 }
369
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700370 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800371 // Backoffs are needed only for official builds. We do not want any delays
372 // or update failures due to backoffs during testing or development.
373 LOG(INFO) << "No backoffs for test/dev images. "
374 << "Can proceed with the download";
375 return false;
376 }
377
378 if (backoff_expiry_time_.is_null()) {
379 LOG(INFO) << "No backoff expiry time has been set. "
380 << "Can proceed with the download";
381 return false;
382 }
383
384 if (backoff_expiry_time_ < Time::Now()) {
385 LOG(INFO) << "The backoff expiry time ("
386 << utils::ToString(backoff_expiry_time_)
387 << ") has elapsed. Can proceed with the download";
388 return false;
389 }
390
391 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
392 << utils::ToString(backoff_expiry_time_);
393 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800394}
395
Chris Sosaaa18e162013-06-20 13:20:30 -0700396void PayloadState::Rollback() {
397 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700398 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700399}
400
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800401void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700402 // Update the payload attempt number for both payload types: full and delta.
403 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Alex Deymo29b51d92013-07-09 15:26:24 -0700404
405 // Report the metric every time the value is incremented.
406 string metric = "Installer.PayloadAttemptNumber";
407 int value = GetPayloadAttemptNumber();
408
409 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
410 system_state_->metrics_lib()->SendToUMA(
411 metric,
412 value,
413 1, // min value
414 50, // max value
415 kNumDefaultUmaBuckets);
Alex Deymo820cc702013-06-28 15:43:46 -0700416}
417
418void PayloadState::IncrementFullPayloadAttemptNumber() {
419 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800420 if (response_.is_delta_payload) {
421 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
422 return;
423 }
424
Alex Deymo29b51d92013-07-09 15:26:24 -0700425 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700426 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800427 UpdateBackoffExpiryTime();
Alex Deymo29b51d92013-07-09 15:26:24 -0700428
429 // Report the metric every time the value is incremented.
430 string metric = "Installer.FullPayloadAttemptNumber";
431 int value = GetFullPayloadAttemptNumber();
432
433 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
434 system_state_->metrics_lib()->SendToUMA(
435 metric,
436 value,
437 1, // min value
438 50, // max value
439 kNumDefaultUmaBuckets);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800440}
441
442void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800443 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700444 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800445 LOG(INFO) << "Incrementing the URL index for next attempt";
446 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800447 } else {
448 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700449 << "0 as we only have " << candidate_urls_.size()
450 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800451 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700452 IncrementPayloadAttemptNumber();
453 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800454 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800455
David Zeuthencc6f9962013-04-18 11:57:24 -0700456 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700457 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700458 SetUrlSwitchCount(url_switch_count_ + 1);
459
Jay Srinivasan08262882012-12-28 19:29:43 -0800460 // Whenever we update the URL index, we should also clear the URL failure
461 // count so we can start over fresh for the new URL.
462 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800463}
464
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800465void PayloadState::IncrementFailureCount() {
466 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800467 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800468 LOG(INFO) << "Incrementing the URL failure count";
469 SetUrlFailureCount(next_url_failure_count);
470 } else {
471 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
472 << ". Trying next available URL";
473 IncrementUrlIndex();
474 }
475}
476
Jay Srinivasan08262882012-12-28 19:29:43 -0800477void PayloadState::UpdateBackoffExpiryTime() {
478 if (response_.disable_payload_backoff) {
479 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
480 SetBackoffExpiryTime(Time());
481 return;
482 }
483
Alex Deymo820cc702013-06-28 15:43:46 -0700484 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800485 SetBackoffExpiryTime(Time());
486 return;
487 }
488
489 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700490 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800491 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Deymo820cc702013-06-28 15:43:46 -0700492 int num_days = 1; // the value to be shifted.
493 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800494
495 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
496 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700497 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800498
499 // The number of days is the minimum of 2 raised to (payload_attempt_number
500 // - 1) or kMaxBackoffDays.
501 num_days = min(num_days << power, kMaxBackoffDays);
502
503 // We don't want all retries to happen exactly at the same time when
504 // retrying after backoff. So add some random minutes to fuzz.
505 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
506 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
507 TimeDelta::FromMinutes(fuzz_minutes);
508 LOG(INFO) << "Incrementing the backoff expiry time by "
509 << utils::FormatTimeDelta(next_backoff_interval);
510 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
511}
512
Jay Srinivasan19409b72013-04-12 19:23:36 -0700513void PayloadState::UpdateCurrentDownloadSource() {
514 current_download_source_ = kNumDownloadSources;
515
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700516 if (using_p2p_for_downloading_) {
517 current_download_source_ = kDownloadSourceHttpPeer;
518 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700519 string current_url = candidate_urls_[GetUrlIndex()];
Jay Srinivasan19409b72013-04-12 19:23:36 -0700520 if (StartsWithASCII(current_url, "https://", false))
521 current_download_source_ = kDownloadSourceHttpsServer;
522 else if (StartsWithASCII(current_url, "http://", false))
523 current_download_source_ = kDownloadSourceHttpServer;
524 }
525
526 LOG(INFO) << "Current download source: "
527 << utils::ToString(current_download_source_);
528}
529
530void PayloadState::UpdateBytesDownloaded(size_t count) {
531 SetCurrentBytesDownloaded(
532 current_download_source_,
533 GetCurrentBytesDownloaded(current_download_source_) + count,
534 false);
535 SetTotalBytesDownloaded(
536 current_download_source_,
537 GetTotalBytesDownloaded(current_download_source_) + count,
538 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800539
540 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700541}
542
David Zeuthen33bae492014-02-25 16:16:18 -0800543PayloadType PayloadState::CalculatePayloadType() {
544 PayloadType payload_type;
545 OmahaRequestParams* params = system_state_->request_params();
546 if (response_.is_delta_payload) {
547 payload_type = kPayloadTypeDelta;
548 } else if (params->delta_okay()) {
549 payload_type = kPayloadTypeFull;
550 } else { // Full payload, delta was not allowed by request.
551 payload_type = kPayloadTypeForcedFull;
552 }
553 return payload_type;
554}
555
556// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
557// metrics if the attempt ends abnormally, e.g. if the update_engine
558// process crashes or the device is rebooted. See
559// http://crbug.com/357676
560void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
561 int attempt_number = GetPayloadAttemptNumber();
562
563 PayloadType payload_type = CalculatePayloadType();
564
565 int64_t payload_size = response_.size;
566
567 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
568
569 ClockInterface *clock = system_state_->clock();
570 base::TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
571 base::TimeDelta duration_uptime = clock->GetMonotonicTime() -
572 attempt_start_time_monotonic_;
573
574 int64_t payload_download_speed_bps = 0;
575 int64_t usec = duration_uptime.InMicroseconds();
576 if (usec > 0) {
577 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
578 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
579 payload_download_speed_bps = static_cast<int64_t>(bps);
580 }
581
582 DownloadSource download_source = current_download_source_;
583
584 metrics::DownloadErrorCode payload_download_error_code =
585 metrics::DownloadErrorCode::kUnset;
586 ErrorCode internal_error_code = kErrorCodeSuccess;
587 metrics::AttemptResult attempt_result = utils::GetAttemptResult(code);
588
589 // Add additional detail to AttemptResult
590 switch (attempt_result) {
591 case metrics::AttemptResult::kPayloadDownloadError:
592 payload_download_error_code = utils::GetDownloadErrorCode(code);
593 break;
594
595 case metrics::AttemptResult::kInternalError:
596 internal_error_code = code;
597 break;
598
599 // Explicit fall-through for cases where we do not have additional
600 // detail. We avoid the default keyword to force people adding new
601 // AttemptResult values to visit this code and examine whether
602 // additional detail is needed.
603 case metrics::AttemptResult::kUpdateSucceeded:
604 case metrics::AttemptResult::kMetadataMalformed:
605 case metrics::AttemptResult::kOperationMalformed:
606 case metrics::AttemptResult::kOperationExecutionError:
607 case metrics::AttemptResult::kMetadataVerificationFailed:
608 case metrics::AttemptResult::kPayloadVerificationFailed:
609 case metrics::AttemptResult::kVerificationFailed:
610 case metrics::AttemptResult::kPostInstallFailed:
611 case metrics::AttemptResult::kAbnormalTermination:
612 case metrics::AttemptResult::kNumConstants:
613 case metrics::AttemptResult::kUnset:
614 break;
615 }
616
617 metrics::ReportUpdateAttemptMetrics(system_state_,
618 attempt_number,
619 payload_type,
620 duration,
621 duration_uptime,
622 payload_size,
623 payload_bytes_downloaded,
624 payload_download_speed_bps,
625 download_source,
626 attempt_result,
627 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700628 payload_download_error_code,
629 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800630}
631
632void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700633 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800634
635 // Report metrics collected from all known download sources to UMA.
636 int64_t successful_bytes_by_source[kNumDownloadSources];
637 int64_t total_bytes_by_source[kNumDownloadSources];
638 int64_t successful_bytes = 0;
639 int64_t total_bytes = 0;
640 int64_t successful_mbs = 0;
641 int64_t total_mbs = 0;
642
Jay Srinivasan19409b72013-04-12 19:23:36 -0700643 for (int i = 0; i < kNumDownloadSources; i++) {
644 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800645 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700646
David Zeuthen44848602013-06-24 13:32:14 -0700647 // Only consider this download source (and send byte counts) as
648 // having been used if we downloaded a non-trivial amount of bytes
649 // (e.g. at least 1 MiB) that contributed to the final success of
650 // the update. Otherwise we're going to end up with a lot of
651 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700652
David Zeuthen33bae492014-02-25 16:16:18 -0800653 bytes = GetCurrentBytesDownloaded(source);
654 successful_bytes_by_source[i] = bytes;
655 successful_bytes += bytes;
656 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700657 SetCurrentBytesDownloaded(source, 0, true);
658
David Zeuthen33bae492014-02-25 16:16:18 -0800659 bytes = GetTotalBytesDownloaded(source);
660 total_bytes_by_source[i] = bytes;
661 total_bytes += bytes;
662 total_mbs += bytes / kNumBytesInOneMiB;
663 SetTotalBytesDownloaded(source, 0, true);
664 }
665
666 int download_overhead_percentage = 0;
667 if (successful_bytes > 0) {
668 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
669 successful_bytes;
670 }
671
672 int url_switch_count = static_cast<int>(url_switch_count_);
673
674 int reboot_count = GetNumReboots();
675
676 SetNumReboots(0);
677
678 TimeDelta duration = GetUpdateDuration();
679 TimeDelta duration_uptime = GetUpdateDurationUptime();
680
681 prefs_->Delete(kPrefsUpdateTimestampStart);
682 prefs_->Delete(kPrefsUpdateDurationUptime);
683
684 PayloadType payload_type = CalculatePayloadType();
685
686 int64_t payload_size = response_.size;
687
688 int attempt_count = GetPayloadAttemptNumber();
689
690 int updates_abandoned_count = num_responses_seen_ - 1;
691
692 metrics::ReportSuccessfulUpdateMetrics(system_state_,
693 attempt_count,
694 updates_abandoned_count,
695 payload_type,
696 payload_size,
697 total_bytes_by_source,
698 download_overhead_percentage,
699 duration,
700 reboot_count,
701 url_switch_count);
702
703 // TODO(zeuthen): This is the old metric reporting code which is
704 // slated for removal soon. See http://crbug.com/355745 for details.
705
706 // The old metrics code is using MiB's instead of bytes to calculate
707 // the overhead which due to rounding makes the numbers slightly
708 // different.
709 download_overhead_percentage = 0;
710 if (successful_mbs > 0) {
711 download_overhead_percentage = (total_mbs - successful_mbs) * 100ULL /
712 successful_mbs;
713 }
714
715 int download_sources_used = 0;
716 for (int i = 0; i < kNumDownloadSources; i++) {
717 DownloadSource source = static_cast<DownloadSource>(i);
718 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
719 int64_t mbs;
720
721 // Only consider this download source (and send byte counts) as
722 // having been used if we downloaded a non-trivial amount of bytes
723 // (e.g. at least 1 MiB) that contributed to the final success of
724 // the update. Otherwise we're going to end up with a lot of
725 // zero-byte events in the histogram.
726
727 mbs = successful_bytes_by_source[i] / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700728 if (mbs > 0) {
David Zeuthen33bae492014-02-25 16:16:18 -0800729 metric = "Installer.SuccessfulMBsDownloadedFrom" +
730 utils::ToString(source);
David Zeuthen44848602013-06-24 13:32:14 -0700731 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
732 system_state_->metrics_lib()->SendToUMA(metric,
733 mbs,
734 0, // min
735 kMaxMiBs,
736 kNumDefaultUmaBuckets);
737 }
David Zeuthen33bae492014-02-25 16:16:18 -0800738
739 mbs = total_bytes_by_source[i] / kNumBytesInOneMiB;
740 if (mbs > 0) {
741 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
742 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
743 system_state_->metrics_lib()->SendToUMA(metric,
744 mbs,
745 0, // min
746 kMaxMiBs,
747 kNumDefaultUmaBuckets);
748 download_sources_used |= (1 << i);
749 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700750 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700751
752 metric = "Installer.DownloadSourcesUsed";
753 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
754 << " (bit flags) for metric " << metric;
755 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
756 system_state_->metrics_lib()->SendToUMA(metric,
757 download_sources_used,
758 0, // min
759 1 << kNumDownloadSources,
760 num_buckets);
761
David Zeuthen33bae492014-02-25 16:16:18 -0800762 metric = "Installer.DownloadOverheadPercentage";
763 LOG(INFO) << "Uploading " << download_overhead_percentage
764 << "% for metric " << metric;
765 system_state_->metrics_lib()->SendToUMA(metric,
766 download_overhead_percentage,
767 0, // min: 0% overhead
768 1000, // max: 1000% overhead
769 kNumDefaultUmaBuckets);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700770
David Zeuthen33bae492014-02-25 16:16:18 -0800771 metric = "Installer.UpdateURLSwitches";
772 LOG(INFO) << "Uploading " << url_switch_count
773 << " (count) for metric " << metric;
David Zeuthencc6f9962013-04-18 11:57:24 -0700774 system_state_->metrics_lib()->SendToUMA(
775 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800776 url_switch_count,
David Zeuthencc6f9962013-04-18 11:57:24 -0700777 0, // min value
778 100, // max value
779 kNumDefaultUmaBuckets);
David Zeuthencc6f9962013-04-18 11:57:24 -0700780
David Zeuthen33bae492014-02-25 16:16:18 -0800781 metric = "Installer.UpdateNumReboots";
782 LOG(INFO) << "Uploading reboot count of " << reboot_count << " for metric "
Chris Sosabe45bef2013-04-09 18:25:12 -0700783 << metric;
784 system_state_->metrics_lib()->SendToUMA(
785 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800786 reboot_count, // sample
787 0, // min = 0.
788 50, // max
Chris Sosabe45bef2013-04-09 18:25:12 -0700789 25); // buckets
David Zeuthen33bae492014-02-25 16:16:18 -0800790
791 metric = "Installer.UpdateDurationMinutes";
792 system_state_->metrics_lib()->SendToUMA(
793 metric,
794 static_cast<int>(duration.InMinutes()),
795 1, // min: 1 minute
796 365*24*60, // max: 1 year (approx)
797 kNumDefaultUmaBuckets);
798 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
799 << " for metric " << metric;
800
801 metric = "Installer.UpdateDurationUptimeMinutes";
802 system_state_->metrics_lib()->SendToUMA(
803 metric,
804 static_cast<int>(duration_uptime.InMinutes()),
805 1, // min: 1 minute
806 30*24*60, // max: 1 month (approx)
807 kNumDefaultUmaBuckets);
808 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
809 << " for metric " << metric;
810
811 metric = "Installer.PayloadFormat";
812 system_state_->metrics_lib()->SendEnumToUMA(
813 metric,
814 payload_type,
815 kNumPayloadTypes);
816 LOG(INFO) << "Uploading " << utils::ToString(payload_type)
817 << " for metric " << metric;
818
819 metric = "Installer.AttemptsCount.Total";
820 system_state_->metrics_lib()->SendToUMA(
821 metric,
822 attempt_count,
823 1, // min
824 50, // max
825 kNumDefaultUmaBuckets);
826 LOG(INFO) << "Uploading " << attempt_count
827 << " for metric " << metric;
828
829 metric = "Installer.UpdatesAbandonedCount";
830 LOG(INFO) << "Uploading " << updates_abandoned_count
831 << " (count) for metric " << metric;
832 system_state_->metrics_lib()->SendToUMA(
833 metric,
834 updates_abandoned_count,
835 0, // min value
836 100, // max value
837 kNumDefaultUmaBuckets);
Chris Sosabe45bef2013-04-09 18:25:12 -0700838}
839
840void PayloadState::UpdateNumReboots() {
841 // We only update the reboot count when the system has been detected to have
842 // been rebooted.
843 if (!system_state_->system_rebooted()) {
844 return;
845 }
846
847 SetNumReboots(GetNumReboots() + 1);
848}
849
850void PayloadState::SetNumReboots(uint32_t num_reboots) {
851 CHECK(prefs_);
852 num_reboots_ = num_reboots;
853 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
854 LOG(INFO) << "Number of Reboots during current update attempt = "
855 << num_reboots_;
856}
857
Jay Srinivasan08262882012-12-28 19:29:43 -0800858void PayloadState::ResetPersistedState() {
859 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700860 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800861 SetUrlIndex(0);
862 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700863 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800864 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700865 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
David Zeuthen9a017f22013-04-11 16:10:26 -0700866 SetUpdateTimestampEnd(Time()); // Set to null time
867 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700868 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700869 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700870 SetP2PNumAttempts(0);
871 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Chris Sosaaa18e162013-06-20 13:20:30 -0700872}
873
874void PayloadState::ResetRollbackVersion() {
875 CHECK(powerwash_safe_prefs_);
876 rollback_version_ = "";
877 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700878}
879
880void PayloadState::ResetDownloadSourcesOnNewUpdate() {
881 for (int i = 0; i < kNumDownloadSources; i++) {
882 DownloadSource source = static_cast<DownloadSource>(i);
883 SetCurrentBytesDownloaded(source, 0, true);
884 // Note: Not resetting the TotalBytesDownloaded as we want that metric
885 // to count the bytes downloaded across various update attempts until
886 // we have successfully applied the update.
887 }
888}
889
Chris Sosab3dcdb32013-09-04 15:22:12 -0700890int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700891 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700892 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700893 return 0;
894
895 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700896 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700897 return 0;
898
899 if (stored_value < 0) {
900 LOG(ERROR) << key << ": Invalid value (" << stored_value
901 << ") in persisted state. Defaulting to 0";
902 return 0;
903 }
904
905 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800906}
907
908string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700909 string response_sign = base::StringPrintf(
910 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800911
Jay Srinivasan53173b92013-05-17 17:13:01 -0700912 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700913 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
914 static_cast<int>(i),
915 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800916
Alex Vakulenko75039d72014-03-25 12:36:28 -0700917 response_sign += base::StringPrintf(
918 "Payload Size = %ju\n"
919 "Payload Sha256 Hash = %s\n"
920 "Metadata Size = %ju\n"
921 "Metadata Signature = %s\n"
922 "Is Delta Payload = %d\n"
923 "Max Failure Count Per Url = %d\n"
924 "Disable Payload Backoff = %d\n",
925 static_cast<uintmax_t>(response_.size),
926 response_.hash.c_str(),
927 static_cast<uintmax_t>(response_.metadata_size),
928 response_.metadata_signature.c_str(),
929 response_.is_delta_payload,
930 response_.max_failure_count_per_url,
931 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800932 return response_sign;
933}
934
935void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800936 CHECK(prefs_);
937 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800938 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
939 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
940 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800941 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800942}
943
Jay Srinivasan19409b72013-04-12 19:23:36 -0700944void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800945 CHECK(prefs_);
946 response_signature_ = response_signature;
947 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
948 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
949}
950
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800951void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700952 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800953}
954
Alex Deymo820cc702013-06-28 15:43:46 -0700955void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700956 SetFullPayloadAttemptNumber(GetPersistedValue(
957 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700958}
959
960void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800961 CHECK(prefs_);
962 payload_attempt_number_ = payload_attempt_number;
963 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
964 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
965}
966
Alex Deymo820cc702013-06-28 15:43:46 -0700967void PayloadState::SetFullPayloadAttemptNumber(
968 int full_payload_attempt_number) {
969 CHECK(prefs_);
970 full_payload_attempt_number_ = full_payload_attempt_number;
971 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
972 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
973 full_payload_attempt_number_);
974}
975
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800976void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700977 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800978}
979
980void PayloadState::SetUrlIndex(uint32_t url_index) {
981 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800982 url_index_ = url_index;
983 LOG(INFO) << "Current URL Index = " << url_index_;
984 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700985
986 // Also update the download source, which is purely dependent on the
987 // current URL index alone.
988 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800989}
990
David Zeuthencc6f9962013-04-18 11:57:24 -0700991void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700992 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700993}
994
995void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
996 CHECK(prefs_);
997 url_switch_count_ = url_switch_count;
998 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
999 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
1000}
1001
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001002void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001003 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001004}
1005
1006void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
1007 CHECK(prefs_);
1008 url_failure_count_ = url_failure_count;
1009 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
1010 << ")'s Failure Count = " << url_failure_count_;
1011 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001012}
1013
Jay Srinivasan08262882012-12-28 19:29:43 -08001014void PayloadState::LoadBackoffExpiryTime() {
1015 CHECK(prefs_);
1016 int64_t stored_value;
1017 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
1018 return;
1019
1020 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
1021 return;
1022
1023 Time stored_time = Time::FromInternalValue(stored_value);
1024 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
1025 LOG(ERROR) << "Invalid backoff expiry time ("
1026 << utils::ToString(stored_time)
1027 << ") in persisted state. Resetting.";
1028 stored_time = Time();
1029 }
1030 SetBackoffExpiryTime(stored_time);
1031}
1032
1033void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
1034 CHECK(prefs_);
1035 backoff_expiry_time_ = new_time;
1036 LOG(INFO) << "Backoff Expiry Time = "
1037 << utils::ToString(backoff_expiry_time_);
1038 prefs_->SetInt64(kPrefsBackoffExpiryTime,
1039 backoff_expiry_time_.ToInternalValue());
1040}
1041
David Zeuthen9a017f22013-04-11 16:10:26 -07001042TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001043 Time end_time = update_timestamp_end_.is_null()
1044 ? system_state_->clock()->GetWallclockTime() :
1045 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001046 return end_time - update_timestamp_start_;
1047}
1048
1049void PayloadState::LoadUpdateTimestampStart() {
1050 int64_t stored_value;
1051 Time stored_time;
1052
1053 CHECK(prefs_);
1054
David Zeuthenf413fe52013-04-22 14:04:39 -07001055 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001056
1057 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1058 // The preference missing is not unexpected - in that case, just
1059 // use the current time as start time
1060 stored_time = now;
1061 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1062 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1063 stored_time = now;
1064 } else {
1065 stored_time = Time::FromInternalValue(stored_value);
1066 }
1067
1068 // Sanity check: If the time read from disk is in the future
1069 // (modulo some slack to account for possible NTP drift
1070 // adjustments), something is fishy and we should report and
1071 // reset.
1072 TimeDelta duration_according_to_stored_time = now - stored_time;
1073 if (duration_according_to_stored_time < -kDurationSlack) {
1074 LOG(ERROR) << "The UpdateTimestampStart value ("
1075 << utils::ToString(stored_time)
1076 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001077 << utils::FormatTimeDelta(duration_according_to_stored_time)
1078 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001079 stored_time = now;
1080 }
1081
1082 SetUpdateTimestampStart(stored_time);
1083}
1084
1085void PayloadState::SetUpdateTimestampStart(const Time& value) {
1086 CHECK(prefs_);
1087 update_timestamp_start_ = value;
1088 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1089 update_timestamp_start_.ToInternalValue());
1090 LOG(INFO) << "Update Timestamp Start = "
1091 << utils::ToString(update_timestamp_start_);
1092}
1093
1094void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1095 update_timestamp_end_ = value;
1096 LOG(INFO) << "Update Timestamp End = "
1097 << utils::ToString(update_timestamp_end_);
1098}
1099
1100TimeDelta PayloadState::GetUpdateDurationUptime() {
1101 return update_duration_uptime_;
1102}
1103
1104void PayloadState::LoadUpdateDurationUptime() {
1105 int64_t stored_value;
1106 TimeDelta stored_delta;
1107
1108 CHECK(prefs_);
1109
1110 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1111 // The preference missing is not unexpected - in that case, just
1112 // we'll use zero as the delta
1113 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1114 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1115 stored_delta = TimeDelta::FromSeconds(0);
1116 } else {
1117 stored_delta = TimeDelta::FromInternalValue(stored_value);
1118 }
1119
1120 // Sanity-check: Uptime can never be greater than the wall-clock
1121 // difference (modulo some slack). If it is, report and reset
1122 // to the wall-clock difference.
1123 TimeDelta diff = GetUpdateDuration() - stored_delta;
1124 if (diff < -kDurationSlack) {
1125 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001126 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001127 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001128 << utils::FormatTimeDelta(diff)
1129 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001130 stored_delta = update_duration_current_;
1131 }
1132
1133 SetUpdateDurationUptime(stored_delta);
1134}
1135
Chris Sosabe45bef2013-04-09 18:25:12 -07001136void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001137 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001138}
1139
1140void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001141 CHECK(powerwash_safe_prefs_);
1142 string rollback_version;
1143 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1144 &rollback_version)) {
1145 SetRollbackVersion(rollback_version);
1146 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001147}
1148
1149void PayloadState::SetRollbackVersion(const string& rollback_version) {
1150 CHECK(powerwash_safe_prefs_);
1151 LOG(INFO) << "Blacklisting version "<< rollback_version;
1152 rollback_version_ = rollback_version;
1153 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001154}
1155
David Zeuthen9a017f22013-04-11 16:10:26 -07001156void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1157 const Time& timestamp,
1158 bool use_logging) {
1159 CHECK(prefs_);
1160 update_duration_uptime_ = value;
1161 update_duration_uptime_timestamp_ = timestamp;
1162 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1163 update_duration_uptime_.ToInternalValue());
1164 if (use_logging) {
1165 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001166 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001167 }
1168}
1169
1170void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001171 Time now = system_state_->clock()->GetMonotonicTime();
1172 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001173}
1174
1175void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001176 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001177 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1178 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1179 // We're frequently called so avoid logging this write
1180 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1181}
1182
Jay Srinivasan19409b72013-04-12 19:23:36 -07001183string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1184 return prefix + "-from-" + utils::ToString(source);
1185}
1186
1187void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1188 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001189 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001190}
1191
1192void PayloadState::SetCurrentBytesDownloaded(
1193 DownloadSource source,
1194 uint64_t current_bytes_downloaded,
1195 bool log) {
1196 CHECK(prefs_);
1197
1198 if (source >= kNumDownloadSources)
1199 return;
1200
1201 // Update the in-memory value.
1202 current_bytes_downloaded_[source] = current_bytes_downloaded;
1203
1204 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1205 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1206 LOG_IF(INFO, log) << "Current bytes downloaded for "
1207 << utils::ToString(source) << " = "
1208 << GetCurrentBytesDownloaded(source);
1209}
1210
1211void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1212 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001213 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001214}
1215
1216void PayloadState::SetTotalBytesDownloaded(
1217 DownloadSource source,
1218 uint64_t total_bytes_downloaded,
1219 bool log) {
1220 CHECK(prefs_);
1221
1222 if (source >= kNumDownloadSources)
1223 return;
1224
1225 // Update the in-memory value.
1226 total_bytes_downloaded_[source] = total_bytes_downloaded;
1227
1228 // Persist.
1229 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1230 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1231 LOG_IF(INFO, log) << "Total bytes downloaded for "
1232 << utils::ToString(source) << " = "
1233 << GetTotalBytesDownloaded(source);
1234}
1235
David Zeuthena573d6f2013-06-14 16:13:36 -07001236void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001237 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001238}
1239
1240void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1241 CHECK(prefs_);
1242 num_responses_seen_ = num_responses_seen;
1243 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1244 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1245}
1246
Alex Deymob33b0f02013-08-08 21:10:02 -07001247void PayloadState::ReportUpdatesAbandonedEventCountMetric() {
1248 string metric = "Installer.UpdatesAbandonedEventCount";
1249 int value = num_responses_seen_ - 1;
1250
1251 // Do not send an "abandoned" event when 0 payloads were abandoned since the
1252 // last successful update.
1253 if (value == 0)
1254 return;
1255
1256 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1257 system_state_->metrics_lib()->SendToUMA(
1258 metric,
1259 value,
1260 0, // min value
1261 100, // max value
1262 kNumDefaultUmaBuckets);
1263}
1264
Jay Srinivasan53173b92013-05-17 17:13:01 -07001265void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001266 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001267
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001268 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001269 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001270 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001271 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1272 } else {
1273 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1274 http_url_ok = true;
1275 }
1276
1277 candidate_urls_.clear();
1278 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1279 string candidate_url = response_.payload_urls[i];
1280 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1281 continue;
1282 candidate_urls_.push_back(candidate_url);
1283 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1284 << ": " << candidate_url;
1285 }
1286
1287 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1288 << "out of " << response_.payload_urls.size() << " URLs supplied";
1289}
1290
David Zeuthene4c58bf2013-06-18 17:26:50 -07001291void PayloadState::CreateSystemUpdatedMarkerFile() {
1292 CHECK(prefs_);
1293 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1294 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1295}
1296
1297void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1298 // Send |time_to_reboot| as a UMA stat.
1299 string metric = "Installer.TimeToRebootMinutes";
1300 system_state_->metrics_lib()->SendToUMA(metric,
1301 time_to_reboot.InMinutes(),
1302 0, // min: 0 minute
1303 30*24*60, // max: 1 month (approx)
1304 kNumDefaultUmaBuckets);
1305 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1306 << " for metric " << metric;
David Zeuthen33bae492014-02-25 16:16:18 -08001307
1308 metric = metrics::kMetricTimeToRebootMinutes;
1309 system_state_->metrics_lib()->SendToUMA(metric,
1310 time_to_reboot.InMinutes(),
1311 0, // min: 0 minute
1312 30*24*60, // max: 1 month (approx)
1313 kNumDefaultUmaBuckets);
1314 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1315 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001316}
1317
1318void PayloadState::UpdateEngineStarted() {
Alex Deymo569c4242013-07-24 12:01:01 -07001319 // Avoid the UpdateEngineStarted actions if this is not the first time we
1320 // run the update engine since reboot.
1321 if (!system_state_->system_rebooted())
1322 return;
1323
David Zeuthene4c58bf2013-06-18 17:26:50 -07001324 // Figure out if we just booted into a new update
1325 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1326 int64_t stored_value;
1327 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1328 Time system_updated_at = Time::FromInternalValue(stored_value);
1329 if (!system_updated_at.is_null()) {
1330 TimeDelta time_to_reboot =
1331 system_state_->clock()->GetWallclockTime() - system_updated_at;
1332 if (time_to_reboot.ToInternalValue() < 0) {
1333 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1334 << utils::ToString(system_updated_at);
1335 } else {
1336 BootedIntoUpdate(time_to_reboot);
1337 }
1338 }
1339 }
1340 prefs_->Delete(kPrefsSystemUpdatedMarker);
1341 }
Alex Deymo42432912013-07-12 20:21:15 -07001342 // Check if it is needed to send metrics about a failed reboot into a new
1343 // version.
1344 ReportFailedBootIfNeeded();
1345}
1346
1347void PayloadState::ReportFailedBootIfNeeded() {
1348 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1349 // payload was marked as ready immediately before the last reboot, and we
1350 // need to check if such payload successfully rebooted or not.
1351 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001352 int64_t installed_from = 0;
1353 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001354 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1355 return;
1356 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001357 if (int(installed_from) ==
1358 utils::GetPartitionNumber(system_state_->hardware()->BootDevice())) {
Alex Deymo42432912013-07-12 20:21:15 -07001359 // A reboot was pending, but the chromebook is again in the same
1360 // BootDevice where the update was installed from.
1361 int64_t target_attempt;
1362 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1363 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1364 "TargetVersionInstalledFrom was present.";
1365 target_attempt = 1;
1366 }
1367
1368 // Report the UMA metric of the current boot failure.
1369 string metric = "Installer.RebootToNewPartitionAttempt";
1370
1371 LOG(INFO) << "Uploading " << target_attempt
1372 << " (count) for metric " << metric;
1373 system_state_->metrics_lib()->SendToUMA(
1374 metric,
1375 target_attempt,
1376 1, // min value
1377 50, // max value
1378 kNumDefaultUmaBuckets);
David Zeuthen33bae492014-02-25 16:16:18 -08001379
1380 metric = metrics::kMetricFailedUpdateCount;
1381 LOG(INFO) << "Uploading " << target_attempt
1382 << " (count) for metric " << metric;
1383 system_state_->metrics_lib()->SendToUMA(
1384 metric,
1385 target_attempt,
1386 1, // min value
1387 50, // max value
1388 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001389 } else {
1390 prefs_->Delete(kPrefsTargetVersionAttempt);
1391 prefs_->Delete(kPrefsTargetVersionUniqueId);
1392 }
1393 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1394 }
1395}
1396
1397void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1398 // Expect to boot into the new partition in the next reboot setting the
1399 // TargetVersion* flags in the Prefs.
1400 string stored_target_version_uid;
1401 string target_version_id;
1402 string target_partition;
1403 int64_t target_attempt;
1404
1405 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1406 prefs_->GetString(kPrefsTargetVersionUniqueId,
1407 &stored_target_version_uid) &&
1408 stored_target_version_uid == target_version_uid) {
1409 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1410 target_attempt = 0;
1411 } else {
1412 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1413 target_attempt = 0;
1414 }
1415 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1416
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001417 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
1418 utils::GetPartitionNumber(
Alex Deymo42432912013-07-12 20:21:15 -07001419 system_state_->hardware()->BootDevice()));
1420}
1421
1422void PayloadState::ResetUpdateStatus() {
1423 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1424 // rebooted the next boot is not flagged as failed to rebooted into the
1425 // new applied payload.
1426 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1427
1428 // Also decrement the attempt number if it exists.
1429 int64_t target_attempt;
1430 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1431 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt-1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001432}
1433
David Zeuthendcba8092013-08-06 12:16:35 -07001434int PayloadState::GetP2PNumAttempts() {
1435 return p2p_num_attempts_;
1436}
1437
1438void PayloadState::SetP2PNumAttempts(int value) {
1439 p2p_num_attempts_ = value;
1440 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1441 CHECK(prefs_);
1442 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1443}
1444
1445void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001446 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001447}
1448
1449Time PayloadState::GetP2PFirstAttemptTimestamp() {
1450 return p2p_first_attempt_timestamp_;
1451}
1452
1453void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1454 p2p_first_attempt_timestamp_ = time;
1455 LOG(INFO) << "p2p First Attempt Timestamp = "
1456 << utils::ToString(p2p_first_attempt_timestamp_);
1457 CHECK(prefs_);
1458 int64_t stored_value = time.ToInternalValue();
1459 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1460}
1461
1462void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001463 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001464 Time stored_time = Time::FromInternalValue(stored_value);
1465 SetP2PFirstAttemptTimestamp(stored_time);
1466}
1467
1468void PayloadState::P2PNewAttempt() {
1469 CHECK(prefs_);
1470 // Set timestamp, if it hasn't been set already
1471 if (p2p_first_attempt_timestamp_.is_null()) {
1472 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1473 }
1474 // Increase number of attempts
1475 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1476}
1477
1478bool PayloadState::P2PAttemptAllowed() {
1479 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1480 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1481 << " which is greater than "
1482 << kMaxP2PAttempts
1483 << " - disallowing p2p.";
1484 return false;
1485 }
1486
1487 if (!p2p_first_attempt_timestamp_.is_null()) {
1488 Time now = system_state_->clock()->GetWallclockTime();
1489 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1490 if (time_spent_attempting_p2p.InSeconds() < 0) {
1491 LOG(ERROR) << "Time spent attempting p2p is negative"
1492 << " - disallowing p2p.";
1493 return false;
1494 }
1495 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1496 LOG(INFO) << "Time spent attempting p2p is "
1497 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1498 << " which is greater than "
1499 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1500 kMaxP2PAttemptTimeSeconds))
1501 << " - disallowing p2p.";
1502 return false;
1503 }
1504 }
1505
1506 return true;
1507}
1508
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001509} // namespace chromeos_update_engine