blob: e27e8d7e7d162a25cf03b0b9c44ecf4fff142c21 [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>
Jay Srinivasan19409b72013-04-12 19:23:36 -070010#include "base/string_util.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080011#include <base/stringprintf.h>
12
David Zeuthenf413fe52013-04-22 14:04:39 -070013#include "update_engine/clock.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070014#include "update_engine/constants.h"
Alex Deymo42432912013-07-12 20:21:15 -070015#include "update_engine/hardware_interface.h"
16#include "update_engine/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070017#include "update_engine/prefs.h"
18#include "update_engine/system_state.h"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080019#include "update_engine/utils.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080020
Jay Srinivasan08262882012-12-28 19:29:43 -080021using base::Time;
22using base::TimeDelta;
23using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080024using std::string;
25
26namespace chromeos_update_engine {
27
David Zeuthen9a017f22013-04-11 16:10:26 -070028const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
29
Jay Srinivasan08262882012-12-28 19:29:43 -080030// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070031static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080032
Jay Srinivasan08262882012-12-28 19:29:43 -080033// We want to randomize retry attempts after the backoff by +/- 6 hours.
34static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080035
Jay Srinivasan19409b72013-04-12 19:23:36 -070036PayloadState::PayloadState()
37 : prefs_(NULL),
38 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070039 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070040 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070041 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070042 url_switch_count_(0),
43 p2p_num_attempts_(0) {
Jay Srinivasan19409b72013-04-12 19:23:36 -070044 for (int i = 0; i <= kNumDownloadSources; i++)
45 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
46}
47
48bool PayloadState::Initialize(SystemState* system_state) {
49 system_state_ = system_state;
50 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070051 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080052 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080053 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070054 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080055 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080056 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070057 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080058 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070059 LoadUpdateTimestampStart();
60 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
61 // being called before it. Don't reorder.
62 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070063 for (int i = 0; i < kNumDownloadSources; i++) {
64 DownloadSource source = static_cast<DownloadSource>(i);
65 LoadCurrentBytesDownloaded(source);
66 LoadTotalBytesDownloaded(source);
67 }
Chris Sosabe45bef2013-04-09 18:25:12 -070068 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070069 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070070 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070071 LoadP2PFirstAttemptTimestamp();
72 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080073 return true;
74}
75
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080076void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080077 // Always store the latest response.
78 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080079
Jay Srinivasan53173b92013-05-17 17:13:01 -070080 // Compute the candidate URLs first as they are used to calculate the
81 // response signature so that a change in enterprise policy for
82 // HTTP downloads being enabled or not could be honored as soon as the
83 // next update check happens.
84 ComputeCandidateUrls();
85
Jay Srinivasan08262882012-12-28 19:29:43 -080086 // Check if the "signature" of this response (i.e. the fields we care about)
87 // has changed.
88 string new_response_signature = CalculateResponseSignature();
89 bool has_response_changed = (response_signature_ != new_response_signature);
90
91 // If the response has changed, we should persist the new signature and
92 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080093 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -080094 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -070095 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -080096 SetResponseSignature(new_response_signature);
97 ResetPersistedState();
Alex Deymob33b0f02013-08-08 21:10:02 -070098 ReportUpdatesAbandonedEventCountMetric();
Jay Srinivasan08262882012-12-28 19:29:43 -080099 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800100 }
101
Jay Srinivasan08262882012-12-28 19:29:43 -0800102 // This is the earliest point at which we can validate whether the URL index
103 // we loaded from the persisted state is a valid value. If the response
104 // hasn't changed but the URL index is invalid, it's indicative of some
105 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700106 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800107 LOG(INFO) << "Resetting all payload state as the url index seems to have "
108 "been tampered with";
109 ResetPersistedState();
110 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800111 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700112
113 // Update the current download source which depends on the latest value of
114 // the response.
115 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800116}
117
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800118void PayloadState::DownloadComplete() {
119 LOG(INFO) << "Payload downloaded successfully";
120 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700121 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800122}
123
124void PayloadState::DownloadProgress(size_t count) {
125 if (count == 0)
126 return;
127
David Zeuthen9a017f22013-04-11 16:10:26 -0700128 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700129 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700130
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800131 // We've received non-zero bytes from a recent download operation. Since our
132 // URL failure count is meant to penalize a URL only for consecutive
133 // failures, downloading bytes successfully means we should reset the failure
134 // count (as we know at least that the URL is working). In future, we can
135 // design this to be more sophisticated to check for more intelligent failure
136 // patterns, but right now, even 1 byte downloaded will mark the URL to be
137 // good unless it hits 10 (or configured number of) consecutive failures
138 // again.
139
140 if (GetUrlFailureCount() == 0)
141 return;
142
143 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
144 << " to 0 as we received " << count << " bytes successfully";
145 SetUrlFailureCount(0);
146}
147
Chris Sosabe45bef2013-04-09 18:25:12 -0700148void PayloadState::UpdateResumed() {
149 LOG(INFO) << "Resuming an update that was previously started.";
150 UpdateNumReboots();
151}
152
Jay Srinivasan19409b72013-04-12 19:23:36 -0700153void PayloadState::UpdateRestarted() {
154 LOG(INFO) << "Starting a new update";
155 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700156 SetNumReboots(0);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700157}
158
David Zeuthen9a017f22013-04-11 16:10:26 -0700159void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700160 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700161 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700162 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
Jay Srinivasan19409b72013-04-12 19:23:36 -0700163 ReportBytesDownloadedMetrics();
David Zeuthencc6f9962013-04-18 11:57:24 -0700164 ReportUpdateUrlSwitchesMetric();
Chris Sosabe45bef2013-04-09 18:25:12 -0700165 ReportRebootMetrics();
David Zeuthen674c3182013-04-18 14:05:20 -0700166 ReportDurationMetrics();
David Zeuthena573d6f2013-06-14 16:13:36 -0700167 ReportUpdatesAbandonedCountMetric();
Alex Deymo1c656c42013-06-28 11:02:14 -0700168 ReportPayloadTypeMetric();
Alex Deymo820cc702013-06-28 15:43:46 -0700169 ReportAttemptsCountMetrics();
David Zeuthena573d6f2013-06-14 16:13:36 -0700170
171 // Reset the number of responses seen since it counts from the last
172 // successful update, e.g. now.
173 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700174
175 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700176}
177
David Zeuthena99981f2013-04-29 13:42:47 -0700178void PayloadState::UpdateFailed(ErrorCode error) {
179 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800180 LOG(INFO) << "Updating payload state for error code: " << base_error
181 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800182
Jay Srinivasan53173b92013-05-17 17:13:01 -0700183 if (candidate_urls_.size() == 0) {
184 // This means we got this error even before we got a valid Omaha response
185 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800186 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800187 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
188 return;
189 }
190
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800191 switch (base_error) {
192 // Errors which are good indicators of a problem with a particular URL or
193 // the protocol used in the URL or entities in the communication channel
194 // (e.g. proxies). We should try the next available URL in the next update
195 // check to quickly recover from these errors.
David Zeuthena99981f2013-04-29 13:42:47 -0700196 case kErrorCodePayloadHashMismatchError:
197 case kErrorCodePayloadSizeMismatchError:
198 case kErrorCodeDownloadPayloadVerificationError:
199 case kErrorCodeDownloadPayloadPubKeyVerificationError:
200 case kErrorCodeSignedDeltaPayloadExpectedError:
201 case kErrorCodeDownloadInvalidMetadataMagicString:
202 case kErrorCodeDownloadSignatureMissingInManifest:
203 case kErrorCodeDownloadManifestParseError:
204 case kErrorCodeDownloadMetadataSignatureError:
205 case kErrorCodeDownloadMetadataSignatureVerificationError:
206 case kErrorCodeDownloadMetadataSignatureMismatch:
207 case kErrorCodeDownloadOperationHashVerificationError:
208 case kErrorCodeDownloadOperationExecutionError:
209 case kErrorCodeDownloadOperationHashMismatch:
210 case kErrorCodeDownloadInvalidMetadataSize:
211 case kErrorCodeDownloadInvalidMetadataSignature:
212 case kErrorCodeDownloadOperationHashMissingError:
213 case kErrorCodeDownloadMetadataSignatureMissingError:
Gilad Arnold21504f02013-05-24 08:51:22 -0700214 case kErrorCodePayloadMismatchedType:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800215 IncrementUrlIndex();
216 break;
217
218 // Errors which seem to be just transient network/communication related
219 // failures and do not indicate any inherent problem with the URL itself.
220 // So, we should keep the current URL but just increment the
221 // failure count to give it more chances. This way, while we maximize our
222 // chances of downloading from the URLs that appear earlier in the response
223 // (because download from a local server URL that appears earlier in a
224 // response is preferable than downloading from the next URL which could be
225 // a internet URL and thus could be more expensive).
David Zeuthena99981f2013-04-29 13:42:47 -0700226 case kErrorCodeError:
227 case kErrorCodeDownloadTransferError:
228 case kErrorCodeDownloadWriteError:
229 case kErrorCodeDownloadStateInitializationError:
230 case kErrorCodeOmahaErrorInHTTPResponse: // Aggregate code for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800231 IncrementFailureCount();
232 break;
233
234 // Errors which are not specific to a URL and hence shouldn't result in
235 // the URL being penalized. This can happen in two cases:
236 // 1. We haven't started downloading anything: These errors don't cost us
237 // anything in terms of actual payload bytes, so we should just do the
238 // regular retries at the next update check.
239 // 2. We have successfully downloaded the payload: In this case, the
240 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800241 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800242 // In either case, there's no need to update URL index or failure count.
David Zeuthena99981f2013-04-29 13:42:47 -0700243 case kErrorCodeOmahaRequestError:
244 case kErrorCodeOmahaResponseHandlerError:
245 case kErrorCodePostinstallRunnerError:
246 case kErrorCodeFilesystemCopierError:
247 case kErrorCodeInstallDeviceOpenError:
248 case kErrorCodeKernelDeviceOpenError:
249 case kErrorCodeDownloadNewPartitionInfoError:
250 case kErrorCodeNewRootfsVerificationError:
251 case kErrorCodeNewKernelVerificationError:
252 case kErrorCodePostinstallBootedFromFirmwareB:
Don Garrett81018e02013-07-30 18:46:31 -0700253 case kErrorCodePostinstallFirmwareRONotUpdatable:
David Zeuthena99981f2013-04-29 13:42:47 -0700254 case kErrorCodeOmahaRequestEmptyResponseError:
255 case kErrorCodeOmahaRequestXMLParseError:
256 case kErrorCodeOmahaResponseInvalid:
257 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
258 case kErrorCodeOmahaUpdateDeferredPerPolicy:
259 case kErrorCodeOmahaUpdateDeferredForBackoff:
260 case kErrorCodePostinstallPowerwashError:
261 case kErrorCodeUpdateCanceledByChannelChange:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800262 LOG(INFO) << "Not incrementing URL index or failure count for this error";
263 break;
264
David Zeuthena99981f2013-04-29 13:42:47 -0700265 case kErrorCodeSuccess: // success code
David Zeuthena99981f2013-04-29 13:42:47 -0700266 case kErrorCodeUmaReportedMax: // not an error code
267 case kErrorCodeOmahaRequestHTTPResponseBase: // aggregated already
268 case kErrorCodeDevModeFlag: // not an error code
269 case kErrorCodeResumedFlag: // not an error code
270 case kErrorCodeTestImageFlag: // not an error code
271 case kErrorCodeTestOmahaUrlFlag: // not an error code
272 case kErrorCodeSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800273 // These shouldn't happen. Enumerating these explicitly here so that we
274 // can let the compiler warn about new error codes that are added to
275 // action_processor.h but not added here.
276 LOG(WARNING) << "Unexpected error code for UpdateFailed";
277 break;
278
279 // Note: Not adding a default here so as to let the compiler warn us of
280 // any new enums that were added in the .h but not listed in this switch.
281 }
282}
283
Jay Srinivasan08262882012-12-28 19:29:43 -0800284bool PayloadState::ShouldBackoffDownload() {
285 if (response_.disable_payload_backoff) {
286 LOG(INFO) << "Payload backoff logic is disabled. "
287 "Can proceed with the download";
288 return false;
289 }
290
291 if (response_.is_delta_payload) {
292 // If delta payloads fail, we want to fallback quickly to full payloads as
293 // they are more likely to succeed. Exponential backoffs would greatly
294 // slow down the fallback to full payloads. So we don't backoff for delta
295 // payloads.
296 LOG(INFO) << "No backoffs for delta payloads. "
297 << "Can proceed with the download";
298 return false;
299 }
300
301 if (!utils::IsOfficialBuild()) {
302 // Backoffs are needed only for official builds. We do not want any delays
303 // or update failures due to backoffs during testing or development.
304 LOG(INFO) << "No backoffs for test/dev images. "
305 << "Can proceed with the download";
306 return false;
307 }
308
309 if (backoff_expiry_time_.is_null()) {
310 LOG(INFO) << "No backoff expiry time has been set. "
311 << "Can proceed with the download";
312 return false;
313 }
314
315 if (backoff_expiry_time_ < Time::Now()) {
316 LOG(INFO) << "The backoff expiry time ("
317 << utils::ToString(backoff_expiry_time_)
318 << ") has elapsed. Can proceed with the download";
319 return false;
320 }
321
322 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
323 << utils::ToString(backoff_expiry_time_);
324 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800325}
326
Chris Sosaaa18e162013-06-20 13:20:30 -0700327void PayloadState::Rollback() {
328 SetRollbackVersion(system_state_->request_params()->app_version());
329}
330
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800331void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700332 // Update the payload attempt number for both payload types: full and delta.
333 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Alex Deymo29b51d92013-07-09 15:26:24 -0700334
335 // Report the metric every time the value is incremented.
336 string metric = "Installer.PayloadAttemptNumber";
337 int value = GetPayloadAttemptNumber();
338
339 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
340 system_state_->metrics_lib()->SendToUMA(
341 metric,
342 value,
343 1, // min value
344 50, // max value
345 kNumDefaultUmaBuckets);
Alex Deymo820cc702013-06-28 15:43:46 -0700346}
347
348void PayloadState::IncrementFullPayloadAttemptNumber() {
349 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800350 if (response_.is_delta_payload) {
351 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
352 return;
353 }
354
Alex Deymo29b51d92013-07-09 15:26:24 -0700355 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700356 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800357 UpdateBackoffExpiryTime();
Alex Deymo29b51d92013-07-09 15:26:24 -0700358
359 // Report the metric every time the value is incremented.
360 string metric = "Installer.FullPayloadAttemptNumber";
361 int value = GetFullPayloadAttemptNumber();
362
363 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
364 system_state_->metrics_lib()->SendToUMA(
365 metric,
366 value,
367 1, // min value
368 50, // max value
369 kNumDefaultUmaBuckets);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800370}
371
372void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800373 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700374 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800375 LOG(INFO) << "Incrementing the URL index for next attempt";
376 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800377 } else {
378 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700379 << "0 as we only have " << candidate_urls_.size()
380 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800381 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700382 IncrementPayloadAttemptNumber();
383 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800384 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800385
David Zeuthencc6f9962013-04-18 11:57:24 -0700386 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700387 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700388 SetUrlSwitchCount(url_switch_count_ + 1);
389
Jay Srinivasan08262882012-12-28 19:29:43 -0800390 // Whenever we update the URL index, we should also clear the URL failure
391 // count so we can start over fresh for the new URL.
392 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800393}
394
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800395void PayloadState::IncrementFailureCount() {
396 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800397 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800398 LOG(INFO) << "Incrementing the URL failure count";
399 SetUrlFailureCount(next_url_failure_count);
400 } else {
401 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
402 << ". Trying next available URL";
403 IncrementUrlIndex();
404 }
405}
406
Jay Srinivasan08262882012-12-28 19:29:43 -0800407void PayloadState::UpdateBackoffExpiryTime() {
408 if (response_.disable_payload_backoff) {
409 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
410 SetBackoffExpiryTime(Time());
411 return;
412 }
413
Alex Deymo820cc702013-06-28 15:43:46 -0700414 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800415 SetBackoffExpiryTime(Time());
416 return;
417 }
418
419 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700420 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800421 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Deymo820cc702013-06-28 15:43:46 -0700422 int num_days = 1; // the value to be shifted.
423 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800424
425 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
426 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700427 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800428
429 // The number of days is the minimum of 2 raised to (payload_attempt_number
430 // - 1) or kMaxBackoffDays.
431 num_days = min(num_days << power, kMaxBackoffDays);
432
433 // We don't want all retries to happen exactly at the same time when
434 // retrying after backoff. So add some random minutes to fuzz.
435 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
436 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
437 TimeDelta::FromMinutes(fuzz_minutes);
438 LOG(INFO) << "Incrementing the backoff expiry time by "
439 << utils::FormatTimeDelta(next_backoff_interval);
440 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
441}
442
Jay Srinivasan19409b72013-04-12 19:23:36 -0700443void PayloadState::UpdateCurrentDownloadSource() {
444 current_download_source_ = kNumDownloadSources;
445
Jay Srinivasan53173b92013-05-17 17:13:01 -0700446 if (GetUrlIndex() < candidate_urls_.size()) {
447 string current_url = candidate_urls_[GetUrlIndex()];
Jay Srinivasan19409b72013-04-12 19:23:36 -0700448 if (StartsWithASCII(current_url, "https://", false))
449 current_download_source_ = kDownloadSourceHttpsServer;
450 else if (StartsWithASCII(current_url, "http://", false))
451 current_download_source_ = kDownloadSourceHttpServer;
452 }
453
454 LOG(INFO) << "Current download source: "
455 << utils::ToString(current_download_source_);
456}
457
458void PayloadState::UpdateBytesDownloaded(size_t count) {
459 SetCurrentBytesDownloaded(
460 current_download_source_,
461 GetCurrentBytesDownloaded(current_download_source_) + count,
462 false);
463 SetTotalBytesDownloaded(
464 current_download_source_,
465 GetTotalBytesDownloaded(current_download_source_) + count,
466 false);
467}
468
469void PayloadState::ReportBytesDownloadedMetrics() {
470 // Report metrics collected from all known download sources to UMA.
471 // The reported data is in Megabytes in order to represent a larger
472 // sample range.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700473 int download_sources_used = 0;
474 string metric;
475 uint64_t successful_mbs = 0;
476 uint64_t total_mbs = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700477 for (int i = 0; i < kNumDownloadSources; i++) {
478 DownloadSource source = static_cast<DownloadSource>(i);
479 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
David Zeuthen44848602013-06-24 13:32:14 -0700480 uint64_t mbs;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700481
David Zeuthen44848602013-06-24 13:32:14 -0700482 // Only consider this download source (and send byte counts) as
483 // having been used if we downloaded a non-trivial amount of bytes
484 // (e.g. at least 1 MiB) that contributed to the final success of
485 // the update. Otherwise we're going to end up with a lot of
486 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700487
David Zeuthen44848602013-06-24 13:32:14 -0700488 mbs = GetCurrentBytesDownloaded(source) / kNumBytesInOneMiB;
489 if (mbs > 0) {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700490 download_sources_used |= (1 << source);
491
David Zeuthen44848602013-06-24 13:32:14 -0700492 metric = "Installer.SuccessfulMBsDownloadedFrom" +
493 utils::ToString(source);
494 successful_mbs += mbs;
495 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
496 system_state_->metrics_lib()->SendToUMA(metric,
497 mbs,
498 0, // min
499 kMaxMiBs,
500 kNumDefaultUmaBuckets);
501 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700502 SetCurrentBytesDownloaded(source, 0, true);
503
Jay Srinivasan19409b72013-04-12 19:23:36 -0700504 mbs = GetTotalBytesDownloaded(source) / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700505 if (mbs > 0) {
506 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
507 total_mbs += mbs;
508 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
509 system_state_->metrics_lib()->SendToUMA(metric,
510 mbs,
511 0, // min
512 kMaxMiBs,
513 kNumDefaultUmaBuckets);
514 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700515 SetTotalBytesDownloaded(source, 0, true);
516 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700517
518 metric = "Installer.DownloadSourcesUsed";
519 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
520 << " (bit flags) for metric " << metric;
521 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
522 system_state_->metrics_lib()->SendToUMA(metric,
523 download_sources_used,
524 0, // min
525 1 << kNumDownloadSources,
526 num_buckets);
527
528 if (successful_mbs) {
529 metric = "Installer.DownloadOverheadPercentage";
530 int percent_overhead = (total_mbs - successful_mbs) * 100 / successful_mbs;
531 LOG(INFO) << "Uploading " << percent_overhead << "% for metric " << metric;
532 system_state_->metrics_lib()->SendToUMA(metric,
533 percent_overhead,
534 0, // min: 0% overhead
535 1000, // max: 1000% overhead
536 kNumDefaultUmaBuckets);
537 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700538}
539
David Zeuthencc6f9962013-04-18 11:57:24 -0700540void PayloadState::ReportUpdateUrlSwitchesMetric() {
541 string metric = "Installer.UpdateURLSwitches";
542 int value = static_cast<int>(url_switch_count_);
543
544 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
545 system_state_->metrics_lib()->SendToUMA(
546 metric,
547 value,
548 0, // min value
549 100, // max value
550 kNumDefaultUmaBuckets);
551}
552
Chris Sosabe45bef2013-04-09 18:25:12 -0700553void PayloadState::ReportRebootMetrics() {
554 // Report the number of num_reboots.
555 string metric = "Installer.UpdateNumReboots";
556 uint32_t num_reboots = GetNumReboots();
557 LOG(INFO) << "Uploading reboot count of " << num_reboots << " for metric "
558 << metric;
559 system_state_->metrics_lib()->SendToUMA(
560 metric,
561 static_cast<int>(num_reboots), // sample
562 0, // min = 0.
563 50, // max
564 25); // buckets
565 SetNumReboots(0);
566}
567
568void PayloadState::UpdateNumReboots() {
569 // We only update the reboot count when the system has been detected to have
570 // been rebooted.
571 if (!system_state_->system_rebooted()) {
572 return;
573 }
574
575 SetNumReboots(GetNumReboots() + 1);
576}
577
578void PayloadState::SetNumReboots(uint32_t num_reboots) {
579 CHECK(prefs_);
580 num_reboots_ = num_reboots;
581 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
582 LOG(INFO) << "Number of Reboots during current update attempt = "
583 << num_reboots_;
584}
585
Jay Srinivasan08262882012-12-28 19:29:43 -0800586void PayloadState::ResetPersistedState() {
587 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700588 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800589 SetUrlIndex(0);
590 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700591 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800592 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700593 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
David Zeuthen9a017f22013-04-11 16:10:26 -0700594 SetUpdateTimestampEnd(Time()); // Set to null time
595 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700596 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700597 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700598 SetP2PNumAttempts(0);
599 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Chris Sosaaa18e162013-06-20 13:20:30 -0700600}
601
602void PayloadState::ResetRollbackVersion() {
603 CHECK(powerwash_safe_prefs_);
604 rollback_version_ = "";
605 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700606}
607
608void PayloadState::ResetDownloadSourcesOnNewUpdate() {
609 for (int i = 0; i < kNumDownloadSources; i++) {
610 DownloadSource source = static_cast<DownloadSource>(i);
611 SetCurrentBytesDownloaded(source, 0, true);
612 // Note: Not resetting the TotalBytesDownloaded as we want that metric
613 // to count the bytes downloaded across various update attempts until
614 // we have successfully applied the update.
615 }
616}
617
Chris Sosaaa18e162013-06-20 13:20:30 -0700618int64_t PayloadState::GetPersistedValue(const string& key,
619 bool across_powerwash) {
620 PrefsInterface* prefs = prefs_;
621 if (across_powerwash)
622 prefs = powerwash_safe_prefs_;
623
Jay Srinivasan19409b72013-04-12 19:23:36 -0700624 CHECK(prefs_);
Chris Sosaaa18e162013-06-20 13:20:30 -0700625 if (!prefs->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700626 return 0;
627
628 int64_t stored_value;
Chris Sosaaa18e162013-06-20 13:20:30 -0700629 if (!prefs->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700630 return 0;
631
632 if (stored_value < 0) {
633 LOG(ERROR) << key << ": Invalid value (" << stored_value
634 << ") in persisted state. Defaulting to 0";
635 return 0;
636 }
637
638 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800639}
640
641string PayloadState::CalculateResponseSignature() {
642 string response_sign = StringPrintf("NumURLs = %d\n",
Jay Srinivasan53173b92013-05-17 17:13:01 -0700643 candidate_urls_.size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800644
Jay Srinivasan53173b92013-05-17 17:13:01 -0700645 for (size_t i = 0; i < candidate_urls_.size(); i++)
646 response_sign += StringPrintf("Candidate Url%d = %s\n",
647 i, candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800648
649 response_sign += StringPrintf("Payload Size = %llu\n"
650 "Payload Sha256 Hash = %s\n"
651 "Metadata Size = %llu\n"
652 "Metadata Signature = %s\n"
653 "Is Delta Payload = %d\n"
654 "Max Failure Count Per Url = %d\n"
655 "Disable Payload Backoff = %d\n",
656 response_.size,
657 response_.hash.c_str(),
658 response_.metadata_size,
659 response_.metadata_signature.c_str(),
660 response_.is_delta_payload,
661 response_.max_failure_count_per_url,
662 response_.disable_payload_backoff);
663 return response_sign;
664}
665
666void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800667 CHECK(prefs_);
668 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800669 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
670 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
671 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800672 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800673}
674
Jay Srinivasan19409b72013-04-12 19:23:36 -0700675void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800676 CHECK(prefs_);
677 response_signature_ = response_signature;
678 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
679 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
680}
681
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800682void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700683 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber,
684 false));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800685}
686
Alex Deymo820cc702013-06-28 15:43:46 -0700687void PayloadState::LoadFullPayloadAttemptNumber() {
688 SetFullPayloadAttemptNumber(GetPersistedValue(kPrefsFullPayloadAttemptNumber,
689 false));
690}
691
692void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800693 CHECK(prefs_);
694 payload_attempt_number_ = payload_attempt_number;
695 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
696 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
697}
698
Alex Deymo820cc702013-06-28 15:43:46 -0700699void PayloadState::SetFullPayloadAttemptNumber(
700 int full_payload_attempt_number) {
701 CHECK(prefs_);
702 full_payload_attempt_number_ = full_payload_attempt_number;
703 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
704 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
705 full_payload_attempt_number_);
706}
707
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800708void PayloadState::LoadUrlIndex() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700709 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex, false));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800710}
711
712void PayloadState::SetUrlIndex(uint32_t url_index) {
713 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800714 url_index_ = url_index;
715 LOG(INFO) << "Current URL Index = " << url_index_;
716 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700717
718 // Also update the download source, which is purely dependent on the
719 // current URL index alone.
720 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800721}
722
David Zeuthencc6f9962013-04-18 11:57:24 -0700723void PayloadState::LoadUrlSwitchCount() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700724 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount, false));
David Zeuthencc6f9962013-04-18 11:57:24 -0700725}
726
727void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
728 CHECK(prefs_);
729 url_switch_count_ = url_switch_count;
730 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
731 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
732}
733
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800734void PayloadState::LoadUrlFailureCount() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700735 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount,
736 false));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800737}
738
739void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
740 CHECK(prefs_);
741 url_failure_count_ = url_failure_count;
742 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
743 << ")'s Failure Count = " << url_failure_count_;
744 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800745}
746
Jay Srinivasan08262882012-12-28 19:29:43 -0800747void PayloadState::LoadBackoffExpiryTime() {
748 CHECK(prefs_);
749 int64_t stored_value;
750 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
751 return;
752
753 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
754 return;
755
756 Time stored_time = Time::FromInternalValue(stored_value);
757 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
758 LOG(ERROR) << "Invalid backoff expiry time ("
759 << utils::ToString(stored_time)
760 << ") in persisted state. Resetting.";
761 stored_time = Time();
762 }
763 SetBackoffExpiryTime(stored_time);
764}
765
766void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
767 CHECK(prefs_);
768 backoff_expiry_time_ = new_time;
769 LOG(INFO) << "Backoff Expiry Time = "
770 << utils::ToString(backoff_expiry_time_);
771 prefs_->SetInt64(kPrefsBackoffExpiryTime,
772 backoff_expiry_time_.ToInternalValue());
773}
774
David Zeuthen9a017f22013-04-11 16:10:26 -0700775TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700776 Time end_time = update_timestamp_end_.is_null()
777 ? system_state_->clock()->GetWallclockTime() :
778 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700779 return end_time - update_timestamp_start_;
780}
781
782void PayloadState::LoadUpdateTimestampStart() {
783 int64_t stored_value;
784 Time stored_time;
785
786 CHECK(prefs_);
787
David Zeuthenf413fe52013-04-22 14:04:39 -0700788 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700789
790 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
791 // The preference missing is not unexpected - in that case, just
792 // use the current time as start time
793 stored_time = now;
794 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
795 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
796 stored_time = now;
797 } else {
798 stored_time = Time::FromInternalValue(stored_value);
799 }
800
801 // Sanity check: If the time read from disk is in the future
802 // (modulo some slack to account for possible NTP drift
803 // adjustments), something is fishy and we should report and
804 // reset.
805 TimeDelta duration_according_to_stored_time = now - stored_time;
806 if (duration_according_to_stored_time < -kDurationSlack) {
807 LOG(ERROR) << "The UpdateTimestampStart value ("
808 << utils::ToString(stored_time)
809 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700810 << utils::FormatTimeDelta(duration_according_to_stored_time)
811 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700812 stored_time = now;
813 }
814
815 SetUpdateTimestampStart(stored_time);
816}
817
818void PayloadState::SetUpdateTimestampStart(const Time& value) {
819 CHECK(prefs_);
820 update_timestamp_start_ = value;
821 prefs_->SetInt64(kPrefsUpdateTimestampStart,
822 update_timestamp_start_.ToInternalValue());
823 LOG(INFO) << "Update Timestamp Start = "
824 << utils::ToString(update_timestamp_start_);
825}
826
827void PayloadState::SetUpdateTimestampEnd(const Time& value) {
828 update_timestamp_end_ = value;
829 LOG(INFO) << "Update Timestamp End = "
830 << utils::ToString(update_timestamp_end_);
831}
832
833TimeDelta PayloadState::GetUpdateDurationUptime() {
834 return update_duration_uptime_;
835}
836
837void PayloadState::LoadUpdateDurationUptime() {
838 int64_t stored_value;
839 TimeDelta stored_delta;
840
841 CHECK(prefs_);
842
843 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
844 // The preference missing is not unexpected - in that case, just
845 // we'll use zero as the delta
846 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
847 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
848 stored_delta = TimeDelta::FromSeconds(0);
849 } else {
850 stored_delta = TimeDelta::FromInternalValue(stored_value);
851 }
852
853 // Sanity-check: Uptime can never be greater than the wall-clock
854 // difference (modulo some slack). If it is, report and reset
855 // to the wall-clock difference.
856 TimeDelta diff = GetUpdateDuration() - stored_delta;
857 if (diff < -kDurationSlack) {
858 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -0700859 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -0700860 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700861 << utils::FormatTimeDelta(diff)
862 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700863 stored_delta = update_duration_current_;
864 }
865
866 SetUpdateDurationUptime(stored_delta);
867}
868
Chris Sosabe45bef2013-04-09 18:25:12 -0700869void PayloadState::LoadNumReboots() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700870 SetNumReboots(GetPersistedValue(kPrefsNumReboots, false));
871}
872
873void PayloadState::LoadRollbackVersion() {
874 SetNumReboots(GetPersistedValue(kPrefsRollbackVersion, true));
875}
876
877void PayloadState::SetRollbackVersion(const string& rollback_version) {
878 CHECK(powerwash_safe_prefs_);
879 LOG(INFO) << "Blacklisting version "<< rollback_version;
880 rollback_version_ = rollback_version;
881 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -0700882}
883
David Zeuthen9a017f22013-04-11 16:10:26 -0700884void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
885 const Time& timestamp,
886 bool use_logging) {
887 CHECK(prefs_);
888 update_duration_uptime_ = value;
889 update_duration_uptime_timestamp_ = timestamp;
890 prefs_->SetInt64(kPrefsUpdateDurationUptime,
891 update_duration_uptime_.ToInternalValue());
892 if (use_logging) {
893 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -0700894 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -0700895 }
896}
897
898void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -0700899 Time now = system_state_->clock()->GetMonotonicTime();
900 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -0700901}
902
903void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700904 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700905 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
906 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
907 // We're frequently called so avoid logging this write
908 SetUpdateDurationUptimeExtended(new_uptime, now, false);
909}
910
David Zeuthen674c3182013-04-18 14:05:20 -0700911void PayloadState::ReportDurationMetrics() {
912 TimeDelta duration = GetUpdateDuration();
913 TimeDelta duration_uptime = GetUpdateDurationUptime();
914 string metric;
915
916 metric = "Installer.UpdateDurationMinutes";
917 system_state_->metrics_lib()->SendToUMA(
918 metric,
919 static_cast<int>(duration.InMinutes()),
920 1, // min: 1 minute
921 365*24*60, // max: 1 year (approx)
922 kNumDefaultUmaBuckets);
923 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
924 << " for metric " << metric;
925
926 metric = "Installer.UpdateDurationUptimeMinutes";
927 system_state_->metrics_lib()->SendToUMA(
928 metric,
929 static_cast<int>(duration_uptime.InMinutes()),
930 1, // min: 1 minute
931 30*24*60, // max: 1 month (approx)
932 kNumDefaultUmaBuckets);
933 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
934 << " for metric " << metric;
935
936 prefs_->Delete(kPrefsUpdateTimestampStart);
937 prefs_->Delete(kPrefsUpdateDurationUptime);
938}
939
Alex Deymo1c656c42013-06-28 11:02:14 -0700940void PayloadState::ReportPayloadTypeMetric() {
941 string metric;
942 PayloadType uma_payload_type;
943 OmahaRequestParams* params = system_state_->request_params();
944
945 if (response_.is_delta_payload) {
946 uma_payload_type = kPayloadTypeDelta;
947 } else if (params->delta_okay()) {
948 uma_payload_type = kPayloadTypeFull;
949 } else { // Full payload, delta was not allowed by request.
950 uma_payload_type = kPayloadTypeForcedFull;
951 }
952
953 metric = "Installer.PayloadFormat";
954 system_state_->metrics_lib()->SendEnumToUMA(
955 metric,
956 uma_payload_type,
957 kNumPayloadTypes);
958 LOG(INFO) << "Uploading " << utils::ToString(uma_payload_type)
959 << " for metric " << metric;
960}
961
Alex Deymo820cc702013-06-28 15:43:46 -0700962void PayloadState::ReportAttemptsCountMetrics() {
963 string metric;
964 int total_attempts = GetPayloadAttemptNumber();
965
966 metric = "Installer.AttemptsCount.Total";
967 system_state_->metrics_lib()->SendToUMA(
968 metric,
969 total_attempts,
970 1, // min
971 50, // max
972 kNumDefaultUmaBuckets);
973 LOG(INFO) << "Uploading " << total_attempts
974 << " for metric " << metric;
975}
976
Jay Srinivasan19409b72013-04-12 19:23:36 -0700977string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
978 return prefix + "-from-" + utils::ToString(source);
979}
980
981void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
982 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosaaa18e162013-06-20 13:20:30 -0700983 SetCurrentBytesDownloaded(source, GetPersistedValue(key, false), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700984}
985
986void PayloadState::SetCurrentBytesDownloaded(
987 DownloadSource source,
988 uint64_t current_bytes_downloaded,
989 bool log) {
990 CHECK(prefs_);
991
992 if (source >= kNumDownloadSources)
993 return;
994
995 // Update the in-memory value.
996 current_bytes_downloaded_[source] = current_bytes_downloaded;
997
998 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
999 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1000 LOG_IF(INFO, log) << "Current bytes downloaded for "
1001 << utils::ToString(source) << " = "
1002 << GetCurrentBytesDownloaded(source);
1003}
1004
1005void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1006 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosaaa18e162013-06-20 13:20:30 -07001007 SetTotalBytesDownloaded(source, GetPersistedValue(key, false), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001008}
1009
1010void PayloadState::SetTotalBytesDownloaded(
1011 DownloadSource source,
1012 uint64_t total_bytes_downloaded,
1013 bool log) {
1014 CHECK(prefs_);
1015
1016 if (source >= kNumDownloadSources)
1017 return;
1018
1019 // Update the in-memory value.
1020 total_bytes_downloaded_[source] = total_bytes_downloaded;
1021
1022 // Persist.
1023 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1024 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1025 LOG_IF(INFO, log) << "Total bytes downloaded for "
1026 << utils::ToString(source) << " = "
1027 << GetTotalBytesDownloaded(source);
1028}
1029
David Zeuthena573d6f2013-06-14 16:13:36 -07001030void PayloadState::LoadNumResponsesSeen() {
Chris Sosaaa18e162013-06-20 13:20:30 -07001031 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen, false));
David Zeuthena573d6f2013-06-14 16:13:36 -07001032}
1033
1034void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1035 CHECK(prefs_);
1036 num_responses_seen_ = num_responses_seen;
1037 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1038 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1039}
1040
1041void PayloadState::ReportUpdatesAbandonedCountMetric() {
1042 string metric = "Installer.UpdatesAbandonedCount";
1043 int value = num_responses_seen_ - 1;
1044
1045 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1046 system_state_->metrics_lib()->SendToUMA(
1047 metric,
1048 value,
1049 0, // min value
1050 100, // max value
1051 kNumDefaultUmaBuckets);
1052}
1053
Alex Deymob33b0f02013-08-08 21:10:02 -07001054void PayloadState::ReportUpdatesAbandonedEventCountMetric() {
1055 string metric = "Installer.UpdatesAbandonedEventCount";
1056 int value = num_responses_seen_ - 1;
1057
1058 // Do not send an "abandoned" event when 0 payloads were abandoned since the
1059 // last successful update.
1060 if (value == 0)
1061 return;
1062
1063 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1064 system_state_->metrics_lib()->SendToUMA(
1065 metric,
1066 value,
1067 0, // min value
1068 100, // max value
1069 kNumDefaultUmaBuckets);
1070}
1071
Jay Srinivasan53173b92013-05-17 17:13:01 -07001072void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001073 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001074
1075 if (system_state_->IsOfficialBuild()) {
1076 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001077 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001078 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1079 } else {
1080 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1081 http_url_ok = true;
1082 }
1083
1084 candidate_urls_.clear();
1085 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1086 string candidate_url = response_.payload_urls[i];
1087 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1088 continue;
1089 candidate_urls_.push_back(candidate_url);
1090 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1091 << ": " << candidate_url;
1092 }
1093
1094 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1095 << "out of " << response_.payload_urls.size() << " URLs supplied";
1096}
1097
David Zeuthene4c58bf2013-06-18 17:26:50 -07001098void PayloadState::CreateSystemUpdatedMarkerFile() {
1099 CHECK(prefs_);
1100 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1101 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1102}
1103
1104void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1105 // Send |time_to_reboot| as a UMA stat.
1106 string metric = "Installer.TimeToRebootMinutes";
1107 system_state_->metrics_lib()->SendToUMA(metric,
1108 time_to_reboot.InMinutes(),
1109 0, // min: 0 minute
1110 30*24*60, // max: 1 month (approx)
1111 kNumDefaultUmaBuckets);
1112 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1113 << " for metric " << metric;
1114}
1115
1116void PayloadState::UpdateEngineStarted() {
Alex Deymo569c4242013-07-24 12:01:01 -07001117 // Avoid the UpdateEngineStarted actions if this is not the first time we
1118 // run the update engine since reboot.
1119 if (!system_state_->system_rebooted())
1120 return;
1121
David Zeuthene4c58bf2013-06-18 17:26:50 -07001122 // Figure out if we just booted into a new update
1123 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1124 int64_t stored_value;
1125 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1126 Time system_updated_at = Time::FromInternalValue(stored_value);
1127 if (!system_updated_at.is_null()) {
1128 TimeDelta time_to_reboot =
1129 system_state_->clock()->GetWallclockTime() - system_updated_at;
1130 if (time_to_reboot.ToInternalValue() < 0) {
1131 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1132 << utils::ToString(system_updated_at);
1133 } else {
1134 BootedIntoUpdate(time_to_reboot);
1135 }
1136 }
1137 }
1138 prefs_->Delete(kPrefsSystemUpdatedMarker);
1139 }
Alex Deymo42432912013-07-12 20:21:15 -07001140 // Check if it is needed to send metrics about a failed reboot into a new
1141 // version.
1142 ReportFailedBootIfNeeded();
1143}
1144
1145void PayloadState::ReportFailedBootIfNeeded() {
1146 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1147 // payload was marked as ready immediately before the last reboot, and we
1148 // need to check if such payload successfully rebooted or not.
1149 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
1150 string installed_from;
1151 if (!prefs_->GetString(kPrefsTargetVersionInstalledFrom, &installed_from)) {
1152 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1153 return;
1154 }
1155 if (installed_from ==
1156 utils::PartitionNumber(system_state_->hardware()->BootDevice())) {
1157 // A reboot was pending, but the chromebook is again in the same
1158 // BootDevice where the update was installed from.
1159 int64_t target_attempt;
1160 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1161 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1162 "TargetVersionInstalledFrom was present.";
1163 target_attempt = 1;
1164 }
1165
1166 // Report the UMA metric of the current boot failure.
1167 string metric = "Installer.RebootToNewPartitionAttempt";
1168
1169 LOG(INFO) << "Uploading " << target_attempt
1170 << " (count) for metric " << metric;
1171 system_state_->metrics_lib()->SendToUMA(
1172 metric,
1173 target_attempt,
1174 1, // min value
1175 50, // max value
1176 kNumDefaultUmaBuckets);
1177 } else {
1178 prefs_->Delete(kPrefsTargetVersionAttempt);
1179 prefs_->Delete(kPrefsTargetVersionUniqueId);
1180 }
1181 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1182 }
1183}
1184
1185void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1186 // Expect to boot into the new partition in the next reboot setting the
1187 // TargetVersion* flags in the Prefs.
1188 string stored_target_version_uid;
1189 string target_version_id;
1190 string target_partition;
1191 int64_t target_attempt;
1192
1193 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1194 prefs_->GetString(kPrefsTargetVersionUniqueId,
1195 &stored_target_version_uid) &&
1196 stored_target_version_uid == target_version_uid) {
1197 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1198 target_attempt = 0;
1199 } else {
1200 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1201 target_attempt = 0;
1202 }
1203 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1204
1205 prefs_->SetString(kPrefsTargetVersionInstalledFrom,
1206 utils::PartitionNumber(
1207 system_state_->hardware()->BootDevice()));
1208}
1209
1210void PayloadState::ResetUpdateStatus() {
1211 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1212 // rebooted the next boot is not flagged as failed to rebooted into the
1213 // new applied payload.
1214 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1215
1216 // Also decrement the attempt number if it exists.
1217 int64_t target_attempt;
1218 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1219 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt-1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001220}
1221
David Zeuthendcba8092013-08-06 12:16:35 -07001222int PayloadState::GetP2PNumAttempts() {
1223 return p2p_num_attempts_;
1224}
1225
1226void PayloadState::SetP2PNumAttempts(int value) {
1227 p2p_num_attempts_ = value;
1228 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1229 CHECK(prefs_);
1230 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1231}
1232
1233void PayloadState::LoadP2PNumAttempts() {
1234 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts, false));
1235}
1236
1237Time PayloadState::GetP2PFirstAttemptTimestamp() {
1238 return p2p_first_attempt_timestamp_;
1239}
1240
1241void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1242 p2p_first_attempt_timestamp_ = time;
1243 LOG(INFO) << "p2p First Attempt Timestamp = "
1244 << utils::ToString(p2p_first_attempt_timestamp_);
1245 CHECK(prefs_);
1246 int64_t stored_value = time.ToInternalValue();
1247 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1248}
1249
1250void PayloadState::LoadP2PFirstAttemptTimestamp() {
1251 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp,
1252 false);
1253 Time stored_time = Time::FromInternalValue(stored_value);
1254 SetP2PFirstAttemptTimestamp(stored_time);
1255}
1256
1257void PayloadState::P2PNewAttempt() {
1258 CHECK(prefs_);
1259 // Set timestamp, if it hasn't been set already
1260 if (p2p_first_attempt_timestamp_.is_null()) {
1261 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1262 }
1263 // Increase number of attempts
1264 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1265}
1266
1267bool PayloadState::P2PAttemptAllowed() {
1268 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1269 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1270 << " which is greater than "
1271 << kMaxP2PAttempts
1272 << " - disallowing p2p.";
1273 return false;
1274 }
1275
1276 if (!p2p_first_attempt_timestamp_.is_null()) {
1277 Time now = system_state_->clock()->GetWallclockTime();
1278 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1279 if (time_spent_attempting_p2p.InSeconds() < 0) {
1280 LOG(ERROR) << "Time spent attempting p2p is negative"
1281 << " - disallowing p2p.";
1282 return false;
1283 }
1284 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1285 LOG(INFO) << "Time spent attempting p2p is "
1286 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1287 << " which is greater than "
1288 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1289 kMaxP2PAttemptTimeSeconds))
1290 << " - disallowing p2p.";
1291 return false;
1292 }
1293 }
1294
1295 return true;
1296}
1297
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001298} // namespace chromeos_update_engine