blob: 4c8efa0e2b92cd38c570dfdfc2565a95db6c060e [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 Zeuthenafed4a12014-04-09 15:28:44 -0700206 // Only report metrics on an update, not on a rollback.
207 if (attempt_type_ == AttemptType::kUpdate) {
208 CollectAndReportAttemptMetrics(kErrorCodeSuccess);
209 CollectAndReportSuccessfulUpdateMetrics();
210 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700211
212 // Reset the number of responses seen since it counts from the last
213 // successful update, e.g. now.
214 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700215
216 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700217}
218
David Zeuthena99981f2013-04-29 13:42:47 -0700219void PayloadState::UpdateFailed(ErrorCode error) {
220 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800221 LOG(INFO) << "Updating payload state for error code: " << base_error
222 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800223
Jay Srinivasan53173b92013-05-17 17:13:01 -0700224 if (candidate_urls_.size() == 0) {
225 // This means we got this error even before we got a valid Omaha response
226 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800227 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800228 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
229 return;
230 }
231
David Zeuthenafed4a12014-04-09 15:28:44 -0700232 // Only report metrics on an update, not on a rollback.
233 if (attempt_type_ == AttemptType::kUpdate)
234 CollectAndReportAttemptMetrics(base_error);
David Zeuthen33bae492014-02-25 16:16:18 -0800235
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800236 switch (base_error) {
237 // Errors which are good indicators of a problem with a particular URL or
238 // the protocol used in the URL or entities in the communication channel
239 // (e.g. proxies). We should try the next available URL in the next update
240 // check to quickly recover from these errors.
David Zeuthena99981f2013-04-29 13:42:47 -0700241 case kErrorCodePayloadHashMismatchError:
242 case kErrorCodePayloadSizeMismatchError:
243 case kErrorCodeDownloadPayloadVerificationError:
244 case kErrorCodeDownloadPayloadPubKeyVerificationError:
245 case kErrorCodeSignedDeltaPayloadExpectedError:
246 case kErrorCodeDownloadInvalidMetadataMagicString:
247 case kErrorCodeDownloadSignatureMissingInManifest:
248 case kErrorCodeDownloadManifestParseError:
249 case kErrorCodeDownloadMetadataSignatureError:
250 case kErrorCodeDownloadMetadataSignatureVerificationError:
251 case kErrorCodeDownloadMetadataSignatureMismatch:
252 case kErrorCodeDownloadOperationHashVerificationError:
253 case kErrorCodeDownloadOperationExecutionError:
254 case kErrorCodeDownloadOperationHashMismatch:
255 case kErrorCodeDownloadInvalidMetadataSize:
256 case kErrorCodeDownloadInvalidMetadataSignature:
257 case kErrorCodeDownloadOperationHashMissingError:
258 case kErrorCodeDownloadMetadataSignatureMissingError:
Gilad Arnold21504f02013-05-24 08:51:22 -0700259 case kErrorCodePayloadMismatchedType:
Don Garrett4d039442013-10-28 18:40:06 -0700260 case kErrorCodeUnsupportedMajorPayloadVersion:
261 case kErrorCodeUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800262 IncrementUrlIndex();
263 break;
264
265 // Errors which seem to be just transient network/communication related
266 // failures and do not indicate any inherent problem with the URL itself.
267 // So, we should keep the current URL but just increment the
268 // failure count to give it more chances. This way, while we maximize our
269 // chances of downloading from the URLs that appear earlier in the response
270 // (because download from a local server URL that appears earlier in a
271 // response is preferable than downloading from the next URL which could be
272 // a internet URL and thus could be more expensive).
David Zeuthena99981f2013-04-29 13:42:47 -0700273 case kErrorCodeError:
274 case kErrorCodeDownloadTransferError:
275 case kErrorCodeDownloadWriteError:
276 case kErrorCodeDownloadStateInitializationError:
277 case kErrorCodeOmahaErrorInHTTPResponse: // Aggregate code for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800278 IncrementFailureCount();
279 break;
280
281 // Errors which are not specific to a URL and hence shouldn't result in
282 // the URL being penalized. This can happen in two cases:
283 // 1. We haven't started downloading anything: These errors don't cost us
284 // anything in terms of actual payload bytes, so we should just do the
285 // regular retries at the next update check.
286 // 2. We have successfully downloaded the payload: In this case, the
287 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800288 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800289 // In either case, there's no need to update URL index or failure count.
David Zeuthena99981f2013-04-29 13:42:47 -0700290 case kErrorCodeOmahaRequestError:
291 case kErrorCodeOmahaResponseHandlerError:
292 case kErrorCodePostinstallRunnerError:
293 case kErrorCodeFilesystemCopierError:
294 case kErrorCodeInstallDeviceOpenError:
295 case kErrorCodeKernelDeviceOpenError:
296 case kErrorCodeDownloadNewPartitionInfoError:
297 case kErrorCodeNewRootfsVerificationError:
298 case kErrorCodeNewKernelVerificationError:
299 case kErrorCodePostinstallBootedFromFirmwareB:
Don Garrett81018e02013-07-30 18:46:31 -0700300 case kErrorCodePostinstallFirmwareRONotUpdatable:
David Zeuthena99981f2013-04-29 13:42:47 -0700301 case kErrorCodeOmahaRequestEmptyResponseError:
302 case kErrorCodeOmahaRequestXMLParseError:
303 case kErrorCodeOmahaResponseInvalid:
304 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
305 case kErrorCodeOmahaUpdateDeferredPerPolicy:
306 case kErrorCodeOmahaUpdateDeferredForBackoff:
307 case kErrorCodePostinstallPowerwashError:
308 case kErrorCodeUpdateCanceledByChannelChange:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800309 LOG(INFO) << "Not incrementing URL index or failure count for this error";
310 break;
311
David Zeuthena99981f2013-04-29 13:42:47 -0700312 case kErrorCodeSuccess: // success code
David Zeuthena99981f2013-04-29 13:42:47 -0700313 case kErrorCodeUmaReportedMax: // not an error code
314 case kErrorCodeOmahaRequestHTTPResponseBase: // aggregated already
315 case kErrorCodeDevModeFlag: // not an error code
316 case kErrorCodeResumedFlag: // not an error code
317 case kErrorCodeTestImageFlag: // not an error code
318 case kErrorCodeTestOmahaUrlFlag: // not an error code
319 case kErrorCodeSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800320 // These shouldn't happen. Enumerating these explicitly here so that we
321 // can let the compiler warn about new error codes that are added to
322 // action_processor.h but not added here.
323 LOG(WARNING) << "Unexpected error code for UpdateFailed";
324 break;
325
326 // Note: Not adding a default here so as to let the compiler warn us of
327 // any new enums that were added in the .h but not listed in this switch.
328 }
329}
330
Jay Srinivasan08262882012-12-28 19:29:43 -0800331bool PayloadState::ShouldBackoffDownload() {
332 if (response_.disable_payload_backoff) {
333 LOG(INFO) << "Payload backoff logic is disabled. "
334 "Can proceed with the download";
335 return false;
336 }
Chris Sosa20f005c2013-09-05 13:53:08 -0700337 if (system_state_->request_params()->use_p2p_for_downloading() &&
338 !system_state_->request_params()->p2p_url().empty()) {
339 LOG(INFO) << "Payload backoff logic is disabled because download "
340 << "will happen from local peer (via p2p).";
341 return false;
342 }
343 if (system_state_->request_params()->interactive()) {
344 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
345 return false;
346 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800347 if (response_.is_delta_payload) {
348 // If delta payloads fail, we want to fallback quickly to full payloads as
349 // they are more likely to succeed. Exponential backoffs would greatly
350 // slow down the fallback to full payloads. So we don't backoff for delta
351 // payloads.
352 LOG(INFO) << "No backoffs for delta payloads. "
353 << "Can proceed with the download";
354 return false;
355 }
356
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700357 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800358 // Backoffs are needed only for official builds. We do not want any delays
359 // or update failures due to backoffs during testing or development.
360 LOG(INFO) << "No backoffs for test/dev images. "
361 << "Can proceed with the download";
362 return false;
363 }
364
365 if (backoff_expiry_time_.is_null()) {
366 LOG(INFO) << "No backoff expiry time has been set. "
367 << "Can proceed with the download";
368 return false;
369 }
370
371 if (backoff_expiry_time_ < Time::Now()) {
372 LOG(INFO) << "The backoff expiry time ("
373 << utils::ToString(backoff_expiry_time_)
374 << ") has elapsed. Can proceed with the download";
375 return false;
376 }
377
378 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
379 << utils::ToString(backoff_expiry_time_);
380 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800381}
382
Chris Sosaaa18e162013-06-20 13:20:30 -0700383void PayloadState::Rollback() {
384 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700385 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700386}
387
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800388void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700389 // Update the payload attempt number for both payload types: full and delta.
390 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Alex Deymo29b51d92013-07-09 15:26:24 -0700391
392 // Report the metric every time the value is incremented.
393 string metric = "Installer.PayloadAttemptNumber";
394 int value = GetPayloadAttemptNumber();
395
396 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
397 system_state_->metrics_lib()->SendToUMA(
398 metric,
399 value,
400 1, // min value
401 50, // max value
402 kNumDefaultUmaBuckets);
Alex Deymo820cc702013-06-28 15:43:46 -0700403}
404
405void PayloadState::IncrementFullPayloadAttemptNumber() {
406 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800407 if (response_.is_delta_payload) {
408 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
409 return;
410 }
411
Alex Deymo29b51d92013-07-09 15:26:24 -0700412 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700413 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800414 UpdateBackoffExpiryTime();
Alex Deymo29b51d92013-07-09 15:26:24 -0700415
416 // Report the metric every time the value is incremented.
417 string metric = "Installer.FullPayloadAttemptNumber";
418 int value = GetFullPayloadAttemptNumber();
419
420 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
421 system_state_->metrics_lib()->SendToUMA(
422 metric,
423 value,
424 1, // min value
425 50, // max value
426 kNumDefaultUmaBuckets);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800427}
428
429void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800430 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700431 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800432 LOG(INFO) << "Incrementing the URL index for next attempt";
433 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800434 } else {
435 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700436 << "0 as we only have " << candidate_urls_.size()
437 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800438 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700439 IncrementPayloadAttemptNumber();
440 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800441 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800442
David Zeuthencc6f9962013-04-18 11:57:24 -0700443 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700444 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700445 SetUrlSwitchCount(url_switch_count_ + 1);
446
Jay Srinivasan08262882012-12-28 19:29:43 -0800447 // Whenever we update the URL index, we should also clear the URL failure
448 // count so we can start over fresh for the new URL.
449 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800450}
451
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800452void PayloadState::IncrementFailureCount() {
453 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800454 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800455 LOG(INFO) << "Incrementing the URL failure count";
456 SetUrlFailureCount(next_url_failure_count);
457 } else {
458 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
459 << ". Trying next available URL";
460 IncrementUrlIndex();
461 }
462}
463
Jay Srinivasan08262882012-12-28 19:29:43 -0800464void PayloadState::UpdateBackoffExpiryTime() {
465 if (response_.disable_payload_backoff) {
466 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
467 SetBackoffExpiryTime(Time());
468 return;
469 }
470
Alex Deymo820cc702013-06-28 15:43:46 -0700471 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800472 SetBackoffExpiryTime(Time());
473 return;
474 }
475
476 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700477 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800478 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Deymo820cc702013-06-28 15:43:46 -0700479 int num_days = 1; // the value to be shifted.
480 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800481
482 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
483 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700484 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800485
486 // The number of days is the minimum of 2 raised to (payload_attempt_number
487 // - 1) or kMaxBackoffDays.
488 num_days = min(num_days << power, kMaxBackoffDays);
489
490 // We don't want all retries to happen exactly at the same time when
491 // retrying after backoff. So add some random minutes to fuzz.
492 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
493 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
494 TimeDelta::FromMinutes(fuzz_minutes);
495 LOG(INFO) << "Incrementing the backoff expiry time by "
496 << utils::FormatTimeDelta(next_backoff_interval);
497 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
498}
499
Jay Srinivasan19409b72013-04-12 19:23:36 -0700500void PayloadState::UpdateCurrentDownloadSource() {
501 current_download_source_ = kNumDownloadSources;
502
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700503 if (using_p2p_for_downloading_) {
504 current_download_source_ = kDownloadSourceHttpPeer;
505 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700506 string current_url = candidate_urls_[GetUrlIndex()];
Jay Srinivasan19409b72013-04-12 19:23:36 -0700507 if (StartsWithASCII(current_url, "https://", false))
508 current_download_source_ = kDownloadSourceHttpsServer;
509 else if (StartsWithASCII(current_url, "http://", false))
510 current_download_source_ = kDownloadSourceHttpServer;
511 }
512
513 LOG(INFO) << "Current download source: "
514 << utils::ToString(current_download_source_);
515}
516
517void PayloadState::UpdateBytesDownloaded(size_t count) {
518 SetCurrentBytesDownloaded(
519 current_download_source_,
520 GetCurrentBytesDownloaded(current_download_source_) + count,
521 false);
522 SetTotalBytesDownloaded(
523 current_download_source_,
524 GetTotalBytesDownloaded(current_download_source_) + count,
525 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800526
527 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700528}
529
David Zeuthen33bae492014-02-25 16:16:18 -0800530PayloadType PayloadState::CalculatePayloadType() {
531 PayloadType payload_type;
532 OmahaRequestParams* params = system_state_->request_params();
533 if (response_.is_delta_payload) {
534 payload_type = kPayloadTypeDelta;
535 } else if (params->delta_okay()) {
536 payload_type = kPayloadTypeFull;
537 } else { // Full payload, delta was not allowed by request.
538 payload_type = kPayloadTypeForcedFull;
539 }
540 return payload_type;
541}
542
543// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
544// metrics if the attempt ends abnormally, e.g. if the update_engine
545// process crashes or the device is rebooted. See
546// http://crbug.com/357676
547void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
548 int attempt_number = GetPayloadAttemptNumber();
549
550 PayloadType payload_type = CalculatePayloadType();
551
552 int64_t payload_size = response_.size;
553
554 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
555
556 ClockInterface *clock = system_state_->clock();
557 base::TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
558 base::TimeDelta duration_uptime = clock->GetMonotonicTime() -
559 attempt_start_time_monotonic_;
560
561 int64_t payload_download_speed_bps = 0;
562 int64_t usec = duration_uptime.InMicroseconds();
563 if (usec > 0) {
564 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
565 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
566 payload_download_speed_bps = static_cast<int64_t>(bps);
567 }
568
569 DownloadSource download_source = current_download_source_;
570
571 metrics::DownloadErrorCode payload_download_error_code =
572 metrics::DownloadErrorCode::kUnset;
573 ErrorCode internal_error_code = kErrorCodeSuccess;
574 metrics::AttemptResult attempt_result = utils::GetAttemptResult(code);
575
576 // Add additional detail to AttemptResult
577 switch (attempt_result) {
578 case metrics::AttemptResult::kPayloadDownloadError:
579 payload_download_error_code = utils::GetDownloadErrorCode(code);
580 break;
581
582 case metrics::AttemptResult::kInternalError:
583 internal_error_code = code;
584 break;
585
586 // Explicit fall-through for cases where we do not have additional
587 // detail. We avoid the default keyword to force people adding new
588 // AttemptResult values to visit this code and examine whether
589 // additional detail is needed.
590 case metrics::AttemptResult::kUpdateSucceeded:
591 case metrics::AttemptResult::kMetadataMalformed:
592 case metrics::AttemptResult::kOperationMalformed:
593 case metrics::AttemptResult::kOperationExecutionError:
594 case metrics::AttemptResult::kMetadataVerificationFailed:
595 case metrics::AttemptResult::kPayloadVerificationFailed:
596 case metrics::AttemptResult::kVerificationFailed:
597 case metrics::AttemptResult::kPostInstallFailed:
598 case metrics::AttemptResult::kAbnormalTermination:
599 case metrics::AttemptResult::kNumConstants:
600 case metrics::AttemptResult::kUnset:
601 break;
602 }
603
604 metrics::ReportUpdateAttemptMetrics(system_state_,
605 attempt_number,
606 payload_type,
607 duration,
608 duration_uptime,
609 payload_size,
610 payload_bytes_downloaded,
611 payload_download_speed_bps,
612 download_source,
613 attempt_result,
614 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700615 payload_download_error_code,
616 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800617}
618
619void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700620 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800621
622 // Report metrics collected from all known download sources to UMA.
623 int64_t successful_bytes_by_source[kNumDownloadSources];
624 int64_t total_bytes_by_source[kNumDownloadSources];
625 int64_t successful_bytes = 0;
626 int64_t total_bytes = 0;
627 int64_t successful_mbs = 0;
628 int64_t total_mbs = 0;
629
Jay Srinivasan19409b72013-04-12 19:23:36 -0700630 for (int i = 0; i < kNumDownloadSources; i++) {
631 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800632 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700633
David Zeuthen44848602013-06-24 13:32:14 -0700634 // Only consider this download source (and send byte counts) as
635 // having been used if we downloaded a non-trivial amount of bytes
636 // (e.g. at least 1 MiB) that contributed to the final success of
637 // the update. Otherwise we're going to end up with a lot of
638 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700639
David Zeuthen33bae492014-02-25 16:16:18 -0800640 bytes = GetCurrentBytesDownloaded(source);
641 successful_bytes_by_source[i] = bytes;
642 successful_bytes += bytes;
643 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700644 SetCurrentBytesDownloaded(source, 0, true);
645
David Zeuthen33bae492014-02-25 16:16:18 -0800646 bytes = GetTotalBytesDownloaded(source);
647 total_bytes_by_source[i] = bytes;
648 total_bytes += bytes;
649 total_mbs += bytes / kNumBytesInOneMiB;
650 SetTotalBytesDownloaded(source, 0, true);
651 }
652
653 int download_overhead_percentage = 0;
654 if (successful_bytes > 0) {
655 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
656 successful_bytes;
657 }
658
659 int url_switch_count = static_cast<int>(url_switch_count_);
660
661 int reboot_count = GetNumReboots();
662
663 SetNumReboots(0);
664
665 TimeDelta duration = GetUpdateDuration();
666 TimeDelta duration_uptime = GetUpdateDurationUptime();
667
668 prefs_->Delete(kPrefsUpdateTimestampStart);
669 prefs_->Delete(kPrefsUpdateDurationUptime);
670
671 PayloadType payload_type = CalculatePayloadType();
672
673 int64_t payload_size = response_.size;
674
675 int attempt_count = GetPayloadAttemptNumber();
676
677 int updates_abandoned_count = num_responses_seen_ - 1;
678
679 metrics::ReportSuccessfulUpdateMetrics(system_state_,
680 attempt_count,
681 updates_abandoned_count,
682 payload_type,
683 payload_size,
684 total_bytes_by_source,
685 download_overhead_percentage,
686 duration,
687 reboot_count,
688 url_switch_count);
689
690 // TODO(zeuthen): This is the old metric reporting code which is
691 // slated for removal soon. See http://crbug.com/355745 for details.
692
693 // The old metrics code is using MiB's instead of bytes to calculate
694 // the overhead which due to rounding makes the numbers slightly
695 // different.
696 download_overhead_percentage = 0;
697 if (successful_mbs > 0) {
698 download_overhead_percentage = (total_mbs - successful_mbs) * 100ULL /
699 successful_mbs;
700 }
701
702 int download_sources_used = 0;
703 for (int i = 0; i < kNumDownloadSources; i++) {
704 DownloadSource source = static_cast<DownloadSource>(i);
705 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
706 int64_t mbs;
707
708 // Only consider this download source (and send byte counts) as
709 // having been used if we downloaded a non-trivial amount of bytes
710 // (e.g. at least 1 MiB) that contributed to the final success of
711 // the update. Otherwise we're going to end up with a lot of
712 // zero-byte events in the histogram.
713
714 mbs = successful_bytes_by_source[i] / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700715 if (mbs > 0) {
David Zeuthen33bae492014-02-25 16:16:18 -0800716 metric = "Installer.SuccessfulMBsDownloadedFrom" +
717 utils::ToString(source);
David Zeuthen44848602013-06-24 13:32:14 -0700718 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
719 system_state_->metrics_lib()->SendToUMA(metric,
720 mbs,
721 0, // min
722 kMaxMiBs,
723 kNumDefaultUmaBuckets);
724 }
David Zeuthen33bae492014-02-25 16:16:18 -0800725
726 mbs = total_bytes_by_source[i] / kNumBytesInOneMiB;
727 if (mbs > 0) {
728 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
729 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
730 system_state_->metrics_lib()->SendToUMA(metric,
731 mbs,
732 0, // min
733 kMaxMiBs,
734 kNumDefaultUmaBuckets);
735 download_sources_used |= (1 << i);
736 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700737 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700738
739 metric = "Installer.DownloadSourcesUsed";
740 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
741 << " (bit flags) for metric " << metric;
742 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
743 system_state_->metrics_lib()->SendToUMA(metric,
744 download_sources_used,
745 0, // min
746 1 << kNumDownloadSources,
747 num_buckets);
748
David Zeuthen33bae492014-02-25 16:16:18 -0800749 metric = "Installer.DownloadOverheadPercentage";
750 LOG(INFO) << "Uploading " << download_overhead_percentage
751 << "% for metric " << metric;
752 system_state_->metrics_lib()->SendToUMA(metric,
753 download_overhead_percentage,
754 0, // min: 0% overhead
755 1000, // max: 1000% overhead
756 kNumDefaultUmaBuckets);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700757
David Zeuthen33bae492014-02-25 16:16:18 -0800758 metric = "Installer.UpdateURLSwitches";
759 LOG(INFO) << "Uploading " << url_switch_count
760 << " (count) for metric " << metric;
David Zeuthencc6f9962013-04-18 11:57:24 -0700761 system_state_->metrics_lib()->SendToUMA(
762 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800763 url_switch_count,
David Zeuthencc6f9962013-04-18 11:57:24 -0700764 0, // min value
765 100, // max value
766 kNumDefaultUmaBuckets);
David Zeuthencc6f9962013-04-18 11:57:24 -0700767
David Zeuthen33bae492014-02-25 16:16:18 -0800768 metric = "Installer.UpdateNumReboots";
769 LOG(INFO) << "Uploading reboot count of " << reboot_count << " for metric "
Chris Sosabe45bef2013-04-09 18:25:12 -0700770 << metric;
771 system_state_->metrics_lib()->SendToUMA(
772 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800773 reboot_count, // sample
774 0, // min = 0.
775 50, // max
Chris Sosabe45bef2013-04-09 18:25:12 -0700776 25); // buckets
David Zeuthen33bae492014-02-25 16:16:18 -0800777
778 metric = "Installer.UpdateDurationMinutes";
779 system_state_->metrics_lib()->SendToUMA(
780 metric,
781 static_cast<int>(duration.InMinutes()),
782 1, // min: 1 minute
783 365*24*60, // max: 1 year (approx)
784 kNumDefaultUmaBuckets);
785 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
786 << " for metric " << metric;
787
788 metric = "Installer.UpdateDurationUptimeMinutes";
789 system_state_->metrics_lib()->SendToUMA(
790 metric,
791 static_cast<int>(duration_uptime.InMinutes()),
792 1, // min: 1 minute
793 30*24*60, // max: 1 month (approx)
794 kNumDefaultUmaBuckets);
795 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
796 << " for metric " << metric;
797
798 metric = "Installer.PayloadFormat";
799 system_state_->metrics_lib()->SendEnumToUMA(
800 metric,
801 payload_type,
802 kNumPayloadTypes);
803 LOG(INFO) << "Uploading " << utils::ToString(payload_type)
804 << " for metric " << metric;
805
806 metric = "Installer.AttemptsCount.Total";
807 system_state_->metrics_lib()->SendToUMA(
808 metric,
809 attempt_count,
810 1, // min
811 50, // max
812 kNumDefaultUmaBuckets);
813 LOG(INFO) << "Uploading " << attempt_count
814 << " for metric " << metric;
815
816 metric = "Installer.UpdatesAbandonedCount";
817 LOG(INFO) << "Uploading " << updates_abandoned_count
818 << " (count) for metric " << metric;
819 system_state_->metrics_lib()->SendToUMA(
820 metric,
821 updates_abandoned_count,
822 0, // min value
823 100, // max value
824 kNumDefaultUmaBuckets);
Chris Sosabe45bef2013-04-09 18:25:12 -0700825}
826
827void PayloadState::UpdateNumReboots() {
828 // We only update the reboot count when the system has been detected to have
829 // been rebooted.
830 if (!system_state_->system_rebooted()) {
831 return;
832 }
833
834 SetNumReboots(GetNumReboots() + 1);
835}
836
837void PayloadState::SetNumReboots(uint32_t num_reboots) {
838 CHECK(prefs_);
839 num_reboots_ = num_reboots;
840 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
841 LOG(INFO) << "Number of Reboots during current update attempt = "
842 << num_reboots_;
843}
844
Jay Srinivasan08262882012-12-28 19:29:43 -0800845void PayloadState::ResetPersistedState() {
846 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700847 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800848 SetUrlIndex(0);
849 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700850 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800851 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700852 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
David Zeuthen9a017f22013-04-11 16:10:26 -0700853 SetUpdateTimestampEnd(Time()); // Set to null time
854 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700855 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700856 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700857 SetP2PNumAttempts(0);
858 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Chris Sosaaa18e162013-06-20 13:20:30 -0700859}
860
861void PayloadState::ResetRollbackVersion() {
862 CHECK(powerwash_safe_prefs_);
863 rollback_version_ = "";
864 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700865}
866
867void PayloadState::ResetDownloadSourcesOnNewUpdate() {
868 for (int i = 0; i < kNumDownloadSources; i++) {
869 DownloadSource source = static_cast<DownloadSource>(i);
870 SetCurrentBytesDownloaded(source, 0, true);
871 // Note: Not resetting the TotalBytesDownloaded as we want that metric
872 // to count the bytes downloaded across various update attempts until
873 // we have successfully applied the update.
874 }
875}
876
Chris Sosab3dcdb32013-09-04 15:22:12 -0700877int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700878 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700879 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700880 return 0;
881
882 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700883 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700884 return 0;
885
886 if (stored_value < 0) {
887 LOG(ERROR) << key << ": Invalid value (" << stored_value
888 << ") in persisted state. Defaulting to 0";
889 return 0;
890 }
891
892 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800893}
894
895string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700896 string response_sign = base::StringPrintf(
897 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800898
Jay Srinivasan53173b92013-05-17 17:13:01 -0700899 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700900 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
901 static_cast<int>(i),
902 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800903
Alex Vakulenko75039d72014-03-25 12:36:28 -0700904 response_sign += base::StringPrintf(
905 "Payload Size = %ju\n"
906 "Payload Sha256 Hash = %s\n"
907 "Metadata Size = %ju\n"
908 "Metadata Signature = %s\n"
909 "Is Delta Payload = %d\n"
910 "Max Failure Count Per Url = %d\n"
911 "Disable Payload Backoff = %d\n",
912 static_cast<uintmax_t>(response_.size),
913 response_.hash.c_str(),
914 static_cast<uintmax_t>(response_.metadata_size),
915 response_.metadata_signature.c_str(),
916 response_.is_delta_payload,
917 response_.max_failure_count_per_url,
918 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800919 return response_sign;
920}
921
922void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800923 CHECK(prefs_);
924 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800925 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
926 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
927 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800928 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800929}
930
Jay Srinivasan19409b72013-04-12 19:23:36 -0700931void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800932 CHECK(prefs_);
933 response_signature_ = response_signature;
934 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
935 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
936}
937
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800938void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700939 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800940}
941
Alex Deymo820cc702013-06-28 15:43:46 -0700942void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700943 SetFullPayloadAttemptNumber(GetPersistedValue(
944 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700945}
946
947void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800948 CHECK(prefs_);
949 payload_attempt_number_ = payload_attempt_number;
950 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
951 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
952}
953
Alex Deymo820cc702013-06-28 15:43:46 -0700954void PayloadState::SetFullPayloadAttemptNumber(
955 int full_payload_attempt_number) {
956 CHECK(prefs_);
957 full_payload_attempt_number_ = full_payload_attempt_number;
958 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
959 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
960 full_payload_attempt_number_);
961}
962
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800963void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700964 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800965}
966
967void PayloadState::SetUrlIndex(uint32_t url_index) {
968 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800969 url_index_ = url_index;
970 LOG(INFO) << "Current URL Index = " << url_index_;
971 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700972
973 // Also update the download source, which is purely dependent on the
974 // current URL index alone.
975 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800976}
977
David Zeuthencc6f9962013-04-18 11:57:24 -0700978void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700979 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700980}
981
982void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
983 CHECK(prefs_);
984 url_switch_count_ = url_switch_count;
985 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
986 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
987}
988
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800989void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700990 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800991}
992
993void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
994 CHECK(prefs_);
995 url_failure_count_ = url_failure_count;
996 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
997 << ")'s Failure Count = " << url_failure_count_;
998 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800999}
1000
Jay Srinivasan08262882012-12-28 19:29:43 -08001001void PayloadState::LoadBackoffExpiryTime() {
1002 CHECK(prefs_);
1003 int64_t stored_value;
1004 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
1005 return;
1006
1007 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
1008 return;
1009
1010 Time stored_time = Time::FromInternalValue(stored_value);
1011 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
1012 LOG(ERROR) << "Invalid backoff expiry time ("
1013 << utils::ToString(stored_time)
1014 << ") in persisted state. Resetting.";
1015 stored_time = Time();
1016 }
1017 SetBackoffExpiryTime(stored_time);
1018}
1019
1020void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
1021 CHECK(prefs_);
1022 backoff_expiry_time_ = new_time;
1023 LOG(INFO) << "Backoff Expiry Time = "
1024 << utils::ToString(backoff_expiry_time_);
1025 prefs_->SetInt64(kPrefsBackoffExpiryTime,
1026 backoff_expiry_time_.ToInternalValue());
1027}
1028
David Zeuthen9a017f22013-04-11 16:10:26 -07001029TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001030 Time end_time = update_timestamp_end_.is_null()
1031 ? system_state_->clock()->GetWallclockTime() :
1032 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001033 return end_time - update_timestamp_start_;
1034}
1035
1036void PayloadState::LoadUpdateTimestampStart() {
1037 int64_t stored_value;
1038 Time stored_time;
1039
1040 CHECK(prefs_);
1041
David Zeuthenf413fe52013-04-22 14:04:39 -07001042 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001043
1044 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1045 // The preference missing is not unexpected - in that case, just
1046 // use the current time as start time
1047 stored_time = now;
1048 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1049 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1050 stored_time = now;
1051 } else {
1052 stored_time = Time::FromInternalValue(stored_value);
1053 }
1054
1055 // Sanity check: If the time read from disk is in the future
1056 // (modulo some slack to account for possible NTP drift
1057 // adjustments), something is fishy and we should report and
1058 // reset.
1059 TimeDelta duration_according_to_stored_time = now - stored_time;
1060 if (duration_according_to_stored_time < -kDurationSlack) {
1061 LOG(ERROR) << "The UpdateTimestampStart value ("
1062 << utils::ToString(stored_time)
1063 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001064 << utils::FormatTimeDelta(duration_according_to_stored_time)
1065 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001066 stored_time = now;
1067 }
1068
1069 SetUpdateTimestampStart(stored_time);
1070}
1071
1072void PayloadState::SetUpdateTimestampStart(const Time& value) {
1073 CHECK(prefs_);
1074 update_timestamp_start_ = value;
1075 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1076 update_timestamp_start_.ToInternalValue());
1077 LOG(INFO) << "Update Timestamp Start = "
1078 << utils::ToString(update_timestamp_start_);
1079}
1080
1081void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1082 update_timestamp_end_ = value;
1083 LOG(INFO) << "Update Timestamp End = "
1084 << utils::ToString(update_timestamp_end_);
1085}
1086
1087TimeDelta PayloadState::GetUpdateDurationUptime() {
1088 return update_duration_uptime_;
1089}
1090
1091void PayloadState::LoadUpdateDurationUptime() {
1092 int64_t stored_value;
1093 TimeDelta stored_delta;
1094
1095 CHECK(prefs_);
1096
1097 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1098 // The preference missing is not unexpected - in that case, just
1099 // we'll use zero as the delta
1100 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1101 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1102 stored_delta = TimeDelta::FromSeconds(0);
1103 } else {
1104 stored_delta = TimeDelta::FromInternalValue(stored_value);
1105 }
1106
1107 // Sanity-check: Uptime can never be greater than the wall-clock
1108 // difference (modulo some slack). If it is, report and reset
1109 // to the wall-clock difference.
1110 TimeDelta diff = GetUpdateDuration() - stored_delta;
1111 if (diff < -kDurationSlack) {
1112 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001113 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001114 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001115 << utils::FormatTimeDelta(diff)
1116 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001117 stored_delta = update_duration_current_;
1118 }
1119
1120 SetUpdateDurationUptime(stored_delta);
1121}
1122
Chris Sosabe45bef2013-04-09 18:25:12 -07001123void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001124 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001125}
1126
1127void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001128 CHECK(powerwash_safe_prefs_);
1129 string rollback_version;
1130 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1131 &rollback_version)) {
1132 SetRollbackVersion(rollback_version);
1133 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001134}
1135
1136void PayloadState::SetRollbackVersion(const string& rollback_version) {
1137 CHECK(powerwash_safe_prefs_);
1138 LOG(INFO) << "Blacklisting version "<< rollback_version;
1139 rollback_version_ = rollback_version;
1140 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001141}
1142
David Zeuthen9a017f22013-04-11 16:10:26 -07001143void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1144 const Time& timestamp,
1145 bool use_logging) {
1146 CHECK(prefs_);
1147 update_duration_uptime_ = value;
1148 update_duration_uptime_timestamp_ = timestamp;
1149 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1150 update_duration_uptime_.ToInternalValue());
1151 if (use_logging) {
1152 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001153 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001154 }
1155}
1156
1157void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001158 Time now = system_state_->clock()->GetMonotonicTime();
1159 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001160}
1161
1162void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001163 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001164 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1165 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1166 // We're frequently called so avoid logging this write
1167 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1168}
1169
Jay Srinivasan19409b72013-04-12 19:23:36 -07001170string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1171 return prefix + "-from-" + utils::ToString(source);
1172}
1173
1174void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1175 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001176 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001177}
1178
1179void PayloadState::SetCurrentBytesDownloaded(
1180 DownloadSource source,
1181 uint64_t current_bytes_downloaded,
1182 bool log) {
1183 CHECK(prefs_);
1184
1185 if (source >= kNumDownloadSources)
1186 return;
1187
1188 // Update the in-memory value.
1189 current_bytes_downloaded_[source] = current_bytes_downloaded;
1190
1191 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1192 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1193 LOG_IF(INFO, log) << "Current bytes downloaded for "
1194 << utils::ToString(source) << " = "
1195 << GetCurrentBytesDownloaded(source);
1196}
1197
1198void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1199 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001200 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001201}
1202
1203void PayloadState::SetTotalBytesDownloaded(
1204 DownloadSource source,
1205 uint64_t total_bytes_downloaded,
1206 bool log) {
1207 CHECK(prefs_);
1208
1209 if (source >= kNumDownloadSources)
1210 return;
1211
1212 // Update the in-memory value.
1213 total_bytes_downloaded_[source] = total_bytes_downloaded;
1214
1215 // Persist.
1216 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1217 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1218 LOG_IF(INFO, log) << "Total bytes downloaded for "
1219 << utils::ToString(source) << " = "
1220 << GetTotalBytesDownloaded(source);
1221}
1222
David Zeuthena573d6f2013-06-14 16:13:36 -07001223void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001224 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001225}
1226
1227void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1228 CHECK(prefs_);
1229 num_responses_seen_ = num_responses_seen;
1230 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1231 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1232}
1233
Alex Deymob33b0f02013-08-08 21:10:02 -07001234void PayloadState::ReportUpdatesAbandonedEventCountMetric() {
1235 string metric = "Installer.UpdatesAbandonedEventCount";
1236 int value = num_responses_seen_ - 1;
1237
1238 // Do not send an "abandoned" event when 0 payloads were abandoned since the
1239 // last successful update.
1240 if (value == 0)
1241 return;
1242
1243 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1244 system_state_->metrics_lib()->SendToUMA(
1245 metric,
1246 value,
1247 0, // min value
1248 100, // max value
1249 kNumDefaultUmaBuckets);
1250}
1251
Jay Srinivasan53173b92013-05-17 17:13:01 -07001252void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001253 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001254
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001255 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001256 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001257 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001258 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1259 } else {
1260 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1261 http_url_ok = true;
1262 }
1263
1264 candidate_urls_.clear();
1265 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1266 string candidate_url = response_.payload_urls[i];
1267 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1268 continue;
1269 candidate_urls_.push_back(candidate_url);
1270 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1271 << ": " << candidate_url;
1272 }
1273
1274 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1275 << "out of " << response_.payload_urls.size() << " URLs supplied";
1276}
1277
David Zeuthene4c58bf2013-06-18 17:26:50 -07001278void PayloadState::CreateSystemUpdatedMarkerFile() {
1279 CHECK(prefs_);
1280 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1281 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1282}
1283
1284void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1285 // Send |time_to_reboot| as a UMA stat.
1286 string metric = "Installer.TimeToRebootMinutes";
1287 system_state_->metrics_lib()->SendToUMA(metric,
1288 time_to_reboot.InMinutes(),
1289 0, // min: 0 minute
1290 30*24*60, // max: 1 month (approx)
1291 kNumDefaultUmaBuckets);
1292 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1293 << " for metric " << metric;
David Zeuthen33bae492014-02-25 16:16:18 -08001294
1295 metric = metrics::kMetricTimeToRebootMinutes;
1296 system_state_->metrics_lib()->SendToUMA(metric,
1297 time_to_reboot.InMinutes(),
1298 0, // min: 0 minute
1299 30*24*60, // max: 1 month (approx)
1300 kNumDefaultUmaBuckets);
1301 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1302 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001303}
1304
1305void PayloadState::UpdateEngineStarted() {
Alex Deymo569c4242013-07-24 12:01:01 -07001306 // Avoid the UpdateEngineStarted actions if this is not the first time we
1307 // run the update engine since reboot.
1308 if (!system_state_->system_rebooted())
1309 return;
1310
David Zeuthene4c58bf2013-06-18 17:26:50 -07001311 // Figure out if we just booted into a new update
1312 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1313 int64_t stored_value;
1314 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1315 Time system_updated_at = Time::FromInternalValue(stored_value);
1316 if (!system_updated_at.is_null()) {
1317 TimeDelta time_to_reboot =
1318 system_state_->clock()->GetWallclockTime() - system_updated_at;
1319 if (time_to_reboot.ToInternalValue() < 0) {
1320 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1321 << utils::ToString(system_updated_at);
1322 } else {
1323 BootedIntoUpdate(time_to_reboot);
1324 }
1325 }
1326 }
1327 prefs_->Delete(kPrefsSystemUpdatedMarker);
1328 }
Alex Deymo42432912013-07-12 20:21:15 -07001329 // Check if it is needed to send metrics about a failed reboot into a new
1330 // version.
1331 ReportFailedBootIfNeeded();
1332}
1333
1334void PayloadState::ReportFailedBootIfNeeded() {
1335 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1336 // payload was marked as ready immediately before the last reboot, and we
1337 // need to check if such payload successfully rebooted or not.
1338 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001339 int64_t installed_from = 0;
1340 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001341 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1342 return;
1343 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001344 if (int(installed_from) ==
1345 utils::GetPartitionNumber(system_state_->hardware()->BootDevice())) {
Alex Deymo42432912013-07-12 20:21:15 -07001346 // A reboot was pending, but the chromebook is again in the same
1347 // BootDevice where the update was installed from.
1348 int64_t target_attempt;
1349 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1350 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1351 "TargetVersionInstalledFrom was present.";
1352 target_attempt = 1;
1353 }
1354
1355 // Report the UMA metric of the current boot failure.
1356 string metric = "Installer.RebootToNewPartitionAttempt";
1357
1358 LOG(INFO) << "Uploading " << target_attempt
1359 << " (count) for metric " << metric;
1360 system_state_->metrics_lib()->SendToUMA(
1361 metric,
1362 target_attempt,
1363 1, // min value
1364 50, // max value
1365 kNumDefaultUmaBuckets);
David Zeuthen33bae492014-02-25 16:16:18 -08001366
1367 metric = metrics::kMetricFailedUpdateCount;
1368 LOG(INFO) << "Uploading " << target_attempt
1369 << " (count) for metric " << metric;
1370 system_state_->metrics_lib()->SendToUMA(
1371 metric,
1372 target_attempt,
1373 1, // min value
1374 50, // max value
1375 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001376 } else {
1377 prefs_->Delete(kPrefsTargetVersionAttempt);
1378 prefs_->Delete(kPrefsTargetVersionUniqueId);
1379 }
1380 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1381 }
1382}
1383
1384void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1385 // Expect to boot into the new partition in the next reboot setting the
1386 // TargetVersion* flags in the Prefs.
1387 string stored_target_version_uid;
1388 string target_version_id;
1389 string target_partition;
1390 int64_t target_attempt;
1391
1392 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1393 prefs_->GetString(kPrefsTargetVersionUniqueId,
1394 &stored_target_version_uid) &&
1395 stored_target_version_uid == target_version_uid) {
1396 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1397 target_attempt = 0;
1398 } else {
1399 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1400 target_attempt = 0;
1401 }
1402 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1403
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001404 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
1405 utils::GetPartitionNumber(
Alex Deymo42432912013-07-12 20:21:15 -07001406 system_state_->hardware()->BootDevice()));
1407}
1408
1409void PayloadState::ResetUpdateStatus() {
1410 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1411 // rebooted the next boot is not flagged as failed to rebooted into the
1412 // new applied payload.
1413 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1414
1415 // Also decrement the attempt number if it exists.
1416 int64_t target_attempt;
1417 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1418 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt-1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001419}
1420
David Zeuthendcba8092013-08-06 12:16:35 -07001421int PayloadState::GetP2PNumAttempts() {
1422 return p2p_num_attempts_;
1423}
1424
1425void PayloadState::SetP2PNumAttempts(int value) {
1426 p2p_num_attempts_ = value;
1427 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1428 CHECK(prefs_);
1429 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1430}
1431
1432void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001433 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001434}
1435
1436Time PayloadState::GetP2PFirstAttemptTimestamp() {
1437 return p2p_first_attempt_timestamp_;
1438}
1439
1440void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1441 p2p_first_attempt_timestamp_ = time;
1442 LOG(INFO) << "p2p First Attempt Timestamp = "
1443 << utils::ToString(p2p_first_attempt_timestamp_);
1444 CHECK(prefs_);
1445 int64_t stored_value = time.ToInternalValue();
1446 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1447}
1448
1449void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001450 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001451 Time stored_time = Time::FromInternalValue(stored_value);
1452 SetP2PFirstAttemptTimestamp(stored_time);
1453}
1454
1455void PayloadState::P2PNewAttempt() {
1456 CHECK(prefs_);
1457 // Set timestamp, if it hasn't been set already
1458 if (p2p_first_attempt_timestamp_.is_null()) {
1459 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1460 }
1461 // Increase number of attempts
1462 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1463}
1464
1465bool PayloadState::P2PAttemptAllowed() {
1466 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1467 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1468 << " which is greater than "
1469 << kMaxP2PAttempts
1470 << " - disallowing p2p.";
1471 return false;
1472 }
1473
1474 if (!p2p_first_attempt_timestamp_.is_null()) {
1475 Time now = system_state_->clock()->GetWallclockTime();
1476 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1477 if (time_spent_attempting_p2p.InSeconds() < 0) {
1478 LOG(ERROR) << "Time spent attempting p2p is negative"
1479 << " - disallowing p2p.";
1480 return false;
1481 }
1482 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1483 LOG(INFO) << "Time spent attempting p2p is "
1484 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1485 << " which is greater than "
1486 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1487 kMaxP2PAttemptTimeSeconds))
1488 << " - disallowing p2p.";
1489 return false;
1490 }
1491 }
1492
1493 return true;
1494}
1495
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001496} // namespace chromeos_update_engine