blob: 8c2547f39cefdcee044ac3e0d868df5c9a195952 [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"
Jay Srinivasan19409b72013-04-12 19:23:36 -070015#include "update_engine/prefs.h"
16#include "update_engine/system_state.h"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080017#include "update_engine/utils.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080018
Jay Srinivasan08262882012-12-28 19:29:43 -080019using base::Time;
20using base::TimeDelta;
21using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080022using std::string;
23
24namespace chromeos_update_engine {
25
David Zeuthen9a017f22013-04-11 16:10:26 -070026const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
27
Jay Srinivasan08262882012-12-28 19:29:43 -080028// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070029static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080030
Jay Srinivasan08262882012-12-28 19:29:43 -080031// We want to randomize retry attempts after the backoff by +/- 6 hours.
32static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080033
Jay Srinivasan19409b72013-04-12 19:23:36 -070034PayloadState::PayloadState()
35 : prefs_(NULL),
36 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070037 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070038 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070039 url_failure_count_(0),
40 url_switch_count_(0) {
Jay Srinivasan19409b72013-04-12 19:23:36 -070041 for (int i = 0; i <= kNumDownloadSources; i++)
42 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
43}
44
45bool PayloadState::Initialize(SystemState* system_state) {
46 system_state_ = system_state;
47 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070048 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080049 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080050 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070051 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080052 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080053 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070054 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080055 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070056 LoadUpdateTimestampStart();
57 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
58 // being called before it. Don't reorder.
59 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070060 for (int i = 0; i < kNumDownloadSources; i++) {
61 DownloadSource source = static_cast<DownloadSource>(i);
62 LoadCurrentBytesDownloaded(source);
63 LoadTotalBytesDownloaded(source);
64 }
Chris Sosabe45bef2013-04-09 18:25:12 -070065 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070066 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070067 LoadRollbackVersion();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080068 return true;
69}
70
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080071void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080072 // Always store the latest response.
73 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080074
Jay Srinivasan53173b92013-05-17 17:13:01 -070075 // Compute the candidate URLs first as they are used to calculate the
76 // response signature so that a change in enterprise policy for
77 // HTTP downloads being enabled or not could be honored as soon as the
78 // next update check happens.
79 ComputeCandidateUrls();
80
Jay Srinivasan08262882012-12-28 19:29:43 -080081 // Check if the "signature" of this response (i.e. the fields we care about)
82 // has changed.
83 string new_response_signature = CalculateResponseSignature();
84 bool has_response_changed = (response_signature_ != new_response_signature);
85
86 // If the response has changed, we should persist the new signature and
87 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080088 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -080089 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -070090 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -080091 SetResponseSignature(new_response_signature);
92 ResetPersistedState();
93 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080094 }
95
Jay Srinivasan08262882012-12-28 19:29:43 -080096 // This is the earliest point at which we can validate whether the URL index
97 // we loaded from the persisted state is a valid value. If the response
98 // hasn't changed but the URL index is invalid, it's indicative of some
99 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700100 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800101 LOG(INFO) << "Resetting all payload state as the url index seems to have "
102 "been tampered with";
103 ResetPersistedState();
104 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800105 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700106
107 // Update the current download source which depends on the latest value of
108 // the response.
109 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800110}
111
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800112void PayloadState::DownloadComplete() {
113 LOG(INFO) << "Payload downloaded successfully";
114 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700115 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800116}
117
118void PayloadState::DownloadProgress(size_t count) {
119 if (count == 0)
120 return;
121
David Zeuthen9a017f22013-04-11 16:10:26 -0700122 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700123 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700124
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800125 // We've received non-zero bytes from a recent download operation. Since our
126 // URL failure count is meant to penalize a URL only for consecutive
127 // failures, downloading bytes successfully means we should reset the failure
128 // count (as we know at least that the URL is working). In future, we can
129 // design this to be more sophisticated to check for more intelligent failure
130 // patterns, but right now, even 1 byte downloaded will mark the URL to be
131 // good unless it hits 10 (or configured number of) consecutive failures
132 // again.
133
134 if (GetUrlFailureCount() == 0)
135 return;
136
137 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
138 << " to 0 as we received " << count << " bytes successfully";
139 SetUrlFailureCount(0);
140}
141
Chris Sosabe45bef2013-04-09 18:25:12 -0700142void PayloadState::UpdateResumed() {
143 LOG(INFO) << "Resuming an update that was previously started.";
144 UpdateNumReboots();
145}
146
Jay Srinivasan19409b72013-04-12 19:23:36 -0700147void PayloadState::UpdateRestarted() {
148 LOG(INFO) << "Starting a new update";
149 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700150 SetNumReboots(0);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700151}
152
David Zeuthen9a017f22013-04-11 16:10:26 -0700153void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700154 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700155 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700156 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
Jay Srinivasan19409b72013-04-12 19:23:36 -0700157 ReportBytesDownloadedMetrics();
David Zeuthencc6f9962013-04-18 11:57:24 -0700158 ReportUpdateUrlSwitchesMetric();
Chris Sosabe45bef2013-04-09 18:25:12 -0700159 ReportRebootMetrics();
David Zeuthen674c3182013-04-18 14:05:20 -0700160 ReportDurationMetrics();
David Zeuthena573d6f2013-06-14 16:13:36 -0700161 ReportUpdatesAbandonedCountMetric();
Alex Deymo1c656c42013-06-28 11:02:14 -0700162 ReportPayloadTypeMetric();
Alex Deymo820cc702013-06-28 15:43:46 -0700163 ReportAttemptsCountMetrics();
David Zeuthena573d6f2013-06-14 16:13:36 -0700164
165 // Reset the number of responses seen since it counts from the last
166 // successful update, e.g. now.
167 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700168
169 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700170}
171
David Zeuthena99981f2013-04-29 13:42:47 -0700172void PayloadState::UpdateFailed(ErrorCode error) {
173 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800174 LOG(INFO) << "Updating payload state for error code: " << base_error
175 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800176
Jay Srinivasan53173b92013-05-17 17:13:01 -0700177 if (candidate_urls_.size() == 0) {
178 // This means we got this error even before we got a valid Omaha response
179 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800180 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800181 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
182 return;
183 }
184
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800185 switch (base_error) {
186 // Errors which are good indicators of a problem with a particular URL or
187 // the protocol used in the URL or entities in the communication channel
188 // (e.g. proxies). We should try the next available URL in the next update
189 // check to quickly recover from these errors.
David Zeuthena99981f2013-04-29 13:42:47 -0700190 case kErrorCodePayloadHashMismatchError:
191 case kErrorCodePayloadSizeMismatchError:
192 case kErrorCodeDownloadPayloadVerificationError:
193 case kErrorCodeDownloadPayloadPubKeyVerificationError:
194 case kErrorCodeSignedDeltaPayloadExpectedError:
195 case kErrorCodeDownloadInvalidMetadataMagicString:
196 case kErrorCodeDownloadSignatureMissingInManifest:
197 case kErrorCodeDownloadManifestParseError:
198 case kErrorCodeDownloadMetadataSignatureError:
199 case kErrorCodeDownloadMetadataSignatureVerificationError:
200 case kErrorCodeDownloadMetadataSignatureMismatch:
201 case kErrorCodeDownloadOperationHashVerificationError:
202 case kErrorCodeDownloadOperationExecutionError:
203 case kErrorCodeDownloadOperationHashMismatch:
204 case kErrorCodeDownloadInvalidMetadataSize:
205 case kErrorCodeDownloadInvalidMetadataSignature:
206 case kErrorCodeDownloadOperationHashMissingError:
207 case kErrorCodeDownloadMetadataSignatureMissingError:
Gilad Arnold21504f02013-05-24 08:51:22 -0700208 case kErrorCodePayloadMismatchedType:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800209 IncrementUrlIndex();
210 break;
211
212 // Errors which seem to be just transient network/communication related
213 // failures and do not indicate any inherent problem with the URL itself.
214 // So, we should keep the current URL but just increment the
215 // failure count to give it more chances. This way, while we maximize our
216 // chances of downloading from the URLs that appear earlier in the response
217 // (because download from a local server URL that appears earlier in a
218 // response is preferable than downloading from the next URL which could be
219 // a internet URL and thus could be more expensive).
David Zeuthena99981f2013-04-29 13:42:47 -0700220 case kErrorCodeError:
221 case kErrorCodeDownloadTransferError:
222 case kErrorCodeDownloadWriteError:
223 case kErrorCodeDownloadStateInitializationError:
224 case kErrorCodeOmahaErrorInHTTPResponse: // Aggregate code for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800225 IncrementFailureCount();
226 break;
227
228 // Errors which are not specific to a URL and hence shouldn't result in
229 // the URL being penalized. This can happen in two cases:
230 // 1. We haven't started downloading anything: These errors don't cost us
231 // anything in terms of actual payload bytes, so we should just do the
232 // regular retries at the next update check.
233 // 2. We have successfully downloaded the payload: In this case, the
234 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800235 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800236 // In either case, there's no need to update URL index or failure count.
David Zeuthena99981f2013-04-29 13:42:47 -0700237 case kErrorCodeOmahaRequestError:
238 case kErrorCodeOmahaResponseHandlerError:
239 case kErrorCodePostinstallRunnerError:
240 case kErrorCodeFilesystemCopierError:
241 case kErrorCodeInstallDeviceOpenError:
242 case kErrorCodeKernelDeviceOpenError:
243 case kErrorCodeDownloadNewPartitionInfoError:
244 case kErrorCodeNewRootfsVerificationError:
245 case kErrorCodeNewKernelVerificationError:
246 case kErrorCodePostinstallBootedFromFirmwareB:
247 case kErrorCodeOmahaRequestEmptyResponseError:
248 case kErrorCodeOmahaRequestXMLParseError:
249 case kErrorCodeOmahaResponseInvalid:
250 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
251 case kErrorCodeOmahaUpdateDeferredPerPolicy:
252 case kErrorCodeOmahaUpdateDeferredForBackoff:
253 case kErrorCodePostinstallPowerwashError:
254 case kErrorCodeUpdateCanceledByChannelChange:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800255 LOG(INFO) << "Not incrementing URL index or failure count for this error";
256 break;
257
David Zeuthena99981f2013-04-29 13:42:47 -0700258 case kErrorCodeSuccess: // success code
David Zeuthena99981f2013-04-29 13:42:47 -0700259 case kErrorCodeUmaReportedMax: // not an error code
260 case kErrorCodeOmahaRequestHTTPResponseBase: // aggregated already
261 case kErrorCodeDevModeFlag: // not an error code
262 case kErrorCodeResumedFlag: // not an error code
263 case kErrorCodeTestImageFlag: // not an error code
264 case kErrorCodeTestOmahaUrlFlag: // not an error code
265 case kErrorCodeSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800266 // These shouldn't happen. Enumerating these explicitly here so that we
267 // can let the compiler warn about new error codes that are added to
268 // action_processor.h but not added here.
269 LOG(WARNING) << "Unexpected error code for UpdateFailed";
270 break;
271
272 // Note: Not adding a default here so as to let the compiler warn us of
273 // any new enums that were added in the .h but not listed in this switch.
274 }
275}
276
Jay Srinivasan08262882012-12-28 19:29:43 -0800277bool PayloadState::ShouldBackoffDownload() {
278 if (response_.disable_payload_backoff) {
279 LOG(INFO) << "Payload backoff logic is disabled. "
280 "Can proceed with the download";
281 return false;
282 }
283
284 if (response_.is_delta_payload) {
285 // If delta payloads fail, we want to fallback quickly to full payloads as
286 // they are more likely to succeed. Exponential backoffs would greatly
287 // slow down the fallback to full payloads. So we don't backoff for delta
288 // payloads.
289 LOG(INFO) << "No backoffs for delta payloads. "
290 << "Can proceed with the download";
291 return false;
292 }
293
294 if (!utils::IsOfficialBuild()) {
295 // Backoffs are needed only for official builds. We do not want any delays
296 // or update failures due to backoffs during testing or development.
297 LOG(INFO) << "No backoffs for test/dev images. "
298 << "Can proceed with the download";
299 return false;
300 }
301
302 if (backoff_expiry_time_.is_null()) {
303 LOG(INFO) << "No backoff expiry time has been set. "
304 << "Can proceed with the download";
305 return false;
306 }
307
308 if (backoff_expiry_time_ < Time::Now()) {
309 LOG(INFO) << "The backoff expiry time ("
310 << utils::ToString(backoff_expiry_time_)
311 << ") has elapsed. Can proceed with the download";
312 return false;
313 }
314
315 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
316 << utils::ToString(backoff_expiry_time_);
317 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800318}
319
Chris Sosaaa18e162013-06-20 13:20:30 -0700320void PayloadState::Rollback() {
321 SetRollbackVersion(system_state_->request_params()->app_version());
322}
323
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800324void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700325 // Update the payload attempt number for both payload types: full and delta.
326 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Alex Deymo29b51d92013-07-09 15:26:24 -0700327
328 // Report the metric every time the value is incremented.
329 string metric = "Installer.PayloadAttemptNumber";
330 int value = GetPayloadAttemptNumber();
331
332 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
333 system_state_->metrics_lib()->SendToUMA(
334 metric,
335 value,
336 1, // min value
337 50, // max value
338 kNumDefaultUmaBuckets);
Alex Deymo820cc702013-06-28 15:43:46 -0700339}
340
341void PayloadState::IncrementFullPayloadAttemptNumber() {
342 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800343 if (response_.is_delta_payload) {
344 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
345 return;
346 }
347
Alex Deymo29b51d92013-07-09 15:26:24 -0700348 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700349 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800350 UpdateBackoffExpiryTime();
Alex Deymo29b51d92013-07-09 15:26:24 -0700351
352 // Report the metric every time the value is incremented.
353 string metric = "Installer.FullPayloadAttemptNumber";
354 int value = GetFullPayloadAttemptNumber();
355
356 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
357 system_state_->metrics_lib()->SendToUMA(
358 metric,
359 value,
360 1, // min value
361 50, // max value
362 kNumDefaultUmaBuckets);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800363}
364
365void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800366 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700367 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800368 LOG(INFO) << "Incrementing the URL index for next attempt";
369 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800370 } else {
371 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700372 << "0 as we only have " << candidate_urls_.size()
373 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800374 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700375 IncrementPayloadAttemptNumber();
376 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800377 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800378
David Zeuthencc6f9962013-04-18 11:57:24 -0700379 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700380 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700381 SetUrlSwitchCount(url_switch_count_ + 1);
382
Jay Srinivasan08262882012-12-28 19:29:43 -0800383 // Whenever we update the URL index, we should also clear the URL failure
384 // count so we can start over fresh for the new URL.
385 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800386}
387
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800388void PayloadState::IncrementFailureCount() {
389 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800390 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800391 LOG(INFO) << "Incrementing the URL failure count";
392 SetUrlFailureCount(next_url_failure_count);
393 } else {
394 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
395 << ". Trying next available URL";
396 IncrementUrlIndex();
397 }
398}
399
Jay Srinivasan08262882012-12-28 19:29:43 -0800400void PayloadState::UpdateBackoffExpiryTime() {
401 if (response_.disable_payload_backoff) {
402 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
403 SetBackoffExpiryTime(Time());
404 return;
405 }
406
Alex Deymo820cc702013-06-28 15:43:46 -0700407 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800408 SetBackoffExpiryTime(Time());
409 return;
410 }
411
412 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700413 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800414 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Deymo820cc702013-06-28 15:43:46 -0700415 int num_days = 1; // the value to be shifted.
416 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800417
418 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
419 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700420 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800421
422 // The number of days is the minimum of 2 raised to (payload_attempt_number
423 // - 1) or kMaxBackoffDays.
424 num_days = min(num_days << power, kMaxBackoffDays);
425
426 // We don't want all retries to happen exactly at the same time when
427 // retrying after backoff. So add some random minutes to fuzz.
428 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
429 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
430 TimeDelta::FromMinutes(fuzz_minutes);
431 LOG(INFO) << "Incrementing the backoff expiry time by "
432 << utils::FormatTimeDelta(next_backoff_interval);
433 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
434}
435
Jay Srinivasan19409b72013-04-12 19:23:36 -0700436void PayloadState::UpdateCurrentDownloadSource() {
437 current_download_source_ = kNumDownloadSources;
438
Jay Srinivasan53173b92013-05-17 17:13:01 -0700439 if (GetUrlIndex() < candidate_urls_.size()) {
440 string current_url = candidate_urls_[GetUrlIndex()];
Jay Srinivasan19409b72013-04-12 19:23:36 -0700441 if (StartsWithASCII(current_url, "https://", false))
442 current_download_source_ = kDownloadSourceHttpsServer;
443 else if (StartsWithASCII(current_url, "http://", false))
444 current_download_source_ = kDownloadSourceHttpServer;
445 }
446
447 LOG(INFO) << "Current download source: "
448 << utils::ToString(current_download_source_);
449}
450
451void PayloadState::UpdateBytesDownloaded(size_t count) {
452 SetCurrentBytesDownloaded(
453 current_download_source_,
454 GetCurrentBytesDownloaded(current_download_source_) + count,
455 false);
456 SetTotalBytesDownloaded(
457 current_download_source_,
458 GetTotalBytesDownloaded(current_download_source_) + count,
459 false);
460}
461
462void PayloadState::ReportBytesDownloadedMetrics() {
463 // Report metrics collected from all known download sources to UMA.
464 // The reported data is in Megabytes in order to represent a larger
465 // sample range.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700466 int download_sources_used = 0;
467 string metric;
468 uint64_t successful_mbs = 0;
469 uint64_t total_mbs = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700470 for (int i = 0; i < kNumDownloadSources; i++) {
471 DownloadSource source = static_cast<DownloadSource>(i);
472 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
David Zeuthen44848602013-06-24 13:32:14 -0700473 uint64_t mbs;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700474
David Zeuthen44848602013-06-24 13:32:14 -0700475 // Only consider this download source (and send byte counts) as
476 // having been used if we downloaded a non-trivial amount of bytes
477 // (e.g. at least 1 MiB) that contributed to the final success of
478 // the update. Otherwise we're going to end up with a lot of
479 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700480
David Zeuthen44848602013-06-24 13:32:14 -0700481 mbs = GetCurrentBytesDownloaded(source) / kNumBytesInOneMiB;
482 if (mbs > 0) {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700483 download_sources_used |= (1 << source);
484
David Zeuthen44848602013-06-24 13:32:14 -0700485 metric = "Installer.SuccessfulMBsDownloadedFrom" +
486 utils::ToString(source);
487 successful_mbs += mbs;
488 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
489 system_state_->metrics_lib()->SendToUMA(metric,
490 mbs,
491 0, // min
492 kMaxMiBs,
493 kNumDefaultUmaBuckets);
494 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700495 SetCurrentBytesDownloaded(source, 0, true);
496
Jay Srinivasan19409b72013-04-12 19:23:36 -0700497 mbs = GetTotalBytesDownloaded(source) / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700498 if (mbs > 0) {
499 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
500 total_mbs += mbs;
501 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
502 system_state_->metrics_lib()->SendToUMA(metric,
503 mbs,
504 0, // min
505 kMaxMiBs,
506 kNumDefaultUmaBuckets);
507 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700508 SetTotalBytesDownloaded(source, 0, true);
509 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700510
511 metric = "Installer.DownloadSourcesUsed";
512 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
513 << " (bit flags) for metric " << metric;
514 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
515 system_state_->metrics_lib()->SendToUMA(metric,
516 download_sources_used,
517 0, // min
518 1 << kNumDownloadSources,
519 num_buckets);
520
521 if (successful_mbs) {
522 metric = "Installer.DownloadOverheadPercentage";
523 int percent_overhead = (total_mbs - successful_mbs) * 100 / successful_mbs;
524 LOG(INFO) << "Uploading " << percent_overhead << "% for metric " << metric;
525 system_state_->metrics_lib()->SendToUMA(metric,
526 percent_overhead,
527 0, // min: 0% overhead
528 1000, // max: 1000% overhead
529 kNumDefaultUmaBuckets);
530 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700531}
532
David Zeuthencc6f9962013-04-18 11:57:24 -0700533void PayloadState::ReportUpdateUrlSwitchesMetric() {
534 string metric = "Installer.UpdateURLSwitches";
535 int value = static_cast<int>(url_switch_count_);
536
537 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
538 system_state_->metrics_lib()->SendToUMA(
539 metric,
540 value,
541 0, // min value
542 100, // max value
543 kNumDefaultUmaBuckets);
544}
545
Chris Sosabe45bef2013-04-09 18:25:12 -0700546void PayloadState::ReportRebootMetrics() {
547 // Report the number of num_reboots.
548 string metric = "Installer.UpdateNumReboots";
549 uint32_t num_reboots = GetNumReboots();
550 LOG(INFO) << "Uploading reboot count of " << num_reboots << " for metric "
551 << metric;
552 system_state_->metrics_lib()->SendToUMA(
553 metric,
554 static_cast<int>(num_reboots), // sample
555 0, // min = 0.
556 50, // max
557 25); // buckets
558 SetNumReboots(0);
559}
560
561void PayloadState::UpdateNumReboots() {
562 // We only update the reboot count when the system has been detected to have
563 // been rebooted.
564 if (!system_state_->system_rebooted()) {
565 return;
566 }
567
568 SetNumReboots(GetNumReboots() + 1);
569}
570
571void PayloadState::SetNumReboots(uint32_t num_reboots) {
572 CHECK(prefs_);
573 num_reboots_ = num_reboots;
574 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
575 LOG(INFO) << "Number of Reboots during current update attempt = "
576 << num_reboots_;
577}
578
Jay Srinivasan08262882012-12-28 19:29:43 -0800579void PayloadState::ResetPersistedState() {
580 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700581 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800582 SetUrlIndex(0);
583 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700584 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800585 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700586 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
David Zeuthen9a017f22013-04-11 16:10:26 -0700587 SetUpdateTimestampEnd(Time()); // Set to null time
588 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700589 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700590 ResetRollbackVersion();
591}
592
593void PayloadState::ResetRollbackVersion() {
594 CHECK(powerwash_safe_prefs_);
595 rollback_version_ = "";
596 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700597}
598
599void PayloadState::ResetDownloadSourcesOnNewUpdate() {
600 for (int i = 0; i < kNumDownloadSources; i++) {
601 DownloadSource source = static_cast<DownloadSource>(i);
602 SetCurrentBytesDownloaded(source, 0, true);
603 // Note: Not resetting the TotalBytesDownloaded as we want that metric
604 // to count the bytes downloaded across various update attempts until
605 // we have successfully applied the update.
606 }
607}
608
Chris Sosaaa18e162013-06-20 13:20:30 -0700609int64_t PayloadState::GetPersistedValue(const string& key,
610 bool across_powerwash) {
611 PrefsInterface* prefs = prefs_;
612 if (across_powerwash)
613 prefs = powerwash_safe_prefs_;
614
Jay Srinivasan19409b72013-04-12 19:23:36 -0700615 CHECK(prefs_);
Chris Sosaaa18e162013-06-20 13:20:30 -0700616 if (!prefs->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700617 return 0;
618
619 int64_t stored_value;
Chris Sosaaa18e162013-06-20 13:20:30 -0700620 if (!prefs->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700621 return 0;
622
623 if (stored_value < 0) {
624 LOG(ERROR) << key << ": Invalid value (" << stored_value
625 << ") in persisted state. Defaulting to 0";
626 return 0;
627 }
628
629 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800630}
631
632string PayloadState::CalculateResponseSignature() {
633 string response_sign = StringPrintf("NumURLs = %d\n",
Jay Srinivasan53173b92013-05-17 17:13:01 -0700634 candidate_urls_.size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800635
Jay Srinivasan53173b92013-05-17 17:13:01 -0700636 for (size_t i = 0; i < candidate_urls_.size(); i++)
637 response_sign += StringPrintf("Candidate Url%d = %s\n",
638 i, candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800639
640 response_sign += StringPrintf("Payload Size = %llu\n"
641 "Payload Sha256 Hash = %s\n"
642 "Metadata Size = %llu\n"
643 "Metadata Signature = %s\n"
644 "Is Delta Payload = %d\n"
645 "Max Failure Count Per Url = %d\n"
646 "Disable Payload Backoff = %d\n",
647 response_.size,
648 response_.hash.c_str(),
649 response_.metadata_size,
650 response_.metadata_signature.c_str(),
651 response_.is_delta_payload,
652 response_.max_failure_count_per_url,
653 response_.disable_payload_backoff);
654 return response_sign;
655}
656
657void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800658 CHECK(prefs_);
659 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800660 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
661 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
662 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800663 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800664}
665
Jay Srinivasan19409b72013-04-12 19:23:36 -0700666void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800667 CHECK(prefs_);
668 response_signature_ = response_signature;
669 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
670 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
671}
672
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800673void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700674 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber,
675 false));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800676}
677
Alex Deymo820cc702013-06-28 15:43:46 -0700678void PayloadState::LoadFullPayloadAttemptNumber() {
679 SetFullPayloadAttemptNumber(GetPersistedValue(kPrefsFullPayloadAttemptNumber,
680 false));
681}
682
683void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800684 CHECK(prefs_);
685 payload_attempt_number_ = payload_attempt_number;
686 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
687 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
688}
689
Alex Deymo820cc702013-06-28 15:43:46 -0700690void PayloadState::SetFullPayloadAttemptNumber(
691 int full_payload_attempt_number) {
692 CHECK(prefs_);
693 full_payload_attempt_number_ = full_payload_attempt_number;
694 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
695 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
696 full_payload_attempt_number_);
697}
698
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800699void PayloadState::LoadUrlIndex() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700700 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex, false));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800701}
702
703void PayloadState::SetUrlIndex(uint32_t url_index) {
704 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800705 url_index_ = url_index;
706 LOG(INFO) << "Current URL Index = " << url_index_;
707 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700708
709 // Also update the download source, which is purely dependent on the
710 // current URL index alone.
711 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800712}
713
David Zeuthencc6f9962013-04-18 11:57:24 -0700714void PayloadState::LoadUrlSwitchCount() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700715 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount, false));
David Zeuthencc6f9962013-04-18 11:57:24 -0700716}
717
718void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
719 CHECK(prefs_);
720 url_switch_count_ = url_switch_count;
721 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
722 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
723}
724
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800725void PayloadState::LoadUrlFailureCount() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700726 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount,
727 false));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800728}
729
730void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
731 CHECK(prefs_);
732 url_failure_count_ = url_failure_count;
733 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
734 << ")'s Failure Count = " << url_failure_count_;
735 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800736}
737
Jay Srinivasan08262882012-12-28 19:29:43 -0800738void PayloadState::LoadBackoffExpiryTime() {
739 CHECK(prefs_);
740 int64_t stored_value;
741 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
742 return;
743
744 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
745 return;
746
747 Time stored_time = Time::FromInternalValue(stored_value);
748 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
749 LOG(ERROR) << "Invalid backoff expiry time ("
750 << utils::ToString(stored_time)
751 << ") in persisted state. Resetting.";
752 stored_time = Time();
753 }
754 SetBackoffExpiryTime(stored_time);
755}
756
757void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
758 CHECK(prefs_);
759 backoff_expiry_time_ = new_time;
760 LOG(INFO) << "Backoff Expiry Time = "
761 << utils::ToString(backoff_expiry_time_);
762 prefs_->SetInt64(kPrefsBackoffExpiryTime,
763 backoff_expiry_time_.ToInternalValue());
764}
765
David Zeuthen9a017f22013-04-11 16:10:26 -0700766TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700767 Time end_time = update_timestamp_end_.is_null()
768 ? system_state_->clock()->GetWallclockTime() :
769 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700770 return end_time - update_timestamp_start_;
771}
772
773void PayloadState::LoadUpdateTimestampStart() {
774 int64_t stored_value;
775 Time stored_time;
776
777 CHECK(prefs_);
778
David Zeuthenf413fe52013-04-22 14:04:39 -0700779 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700780
781 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
782 // The preference missing is not unexpected - in that case, just
783 // use the current time as start time
784 stored_time = now;
785 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
786 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
787 stored_time = now;
788 } else {
789 stored_time = Time::FromInternalValue(stored_value);
790 }
791
792 // Sanity check: If the time read from disk is in the future
793 // (modulo some slack to account for possible NTP drift
794 // adjustments), something is fishy and we should report and
795 // reset.
796 TimeDelta duration_according_to_stored_time = now - stored_time;
797 if (duration_according_to_stored_time < -kDurationSlack) {
798 LOG(ERROR) << "The UpdateTimestampStart value ("
799 << utils::ToString(stored_time)
800 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700801 << utils::FormatTimeDelta(duration_according_to_stored_time)
802 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700803 stored_time = now;
804 }
805
806 SetUpdateTimestampStart(stored_time);
807}
808
809void PayloadState::SetUpdateTimestampStart(const Time& value) {
810 CHECK(prefs_);
811 update_timestamp_start_ = value;
812 prefs_->SetInt64(kPrefsUpdateTimestampStart,
813 update_timestamp_start_.ToInternalValue());
814 LOG(INFO) << "Update Timestamp Start = "
815 << utils::ToString(update_timestamp_start_);
816}
817
818void PayloadState::SetUpdateTimestampEnd(const Time& value) {
819 update_timestamp_end_ = value;
820 LOG(INFO) << "Update Timestamp End = "
821 << utils::ToString(update_timestamp_end_);
822}
823
824TimeDelta PayloadState::GetUpdateDurationUptime() {
825 return update_duration_uptime_;
826}
827
828void PayloadState::LoadUpdateDurationUptime() {
829 int64_t stored_value;
830 TimeDelta stored_delta;
831
832 CHECK(prefs_);
833
834 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
835 // The preference missing is not unexpected - in that case, just
836 // we'll use zero as the delta
837 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
838 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
839 stored_delta = TimeDelta::FromSeconds(0);
840 } else {
841 stored_delta = TimeDelta::FromInternalValue(stored_value);
842 }
843
844 // Sanity-check: Uptime can never be greater than the wall-clock
845 // difference (modulo some slack). If it is, report and reset
846 // to the wall-clock difference.
847 TimeDelta diff = GetUpdateDuration() - stored_delta;
848 if (diff < -kDurationSlack) {
849 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -0700850 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -0700851 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700852 << utils::FormatTimeDelta(diff)
853 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700854 stored_delta = update_duration_current_;
855 }
856
857 SetUpdateDurationUptime(stored_delta);
858}
859
Chris Sosabe45bef2013-04-09 18:25:12 -0700860void PayloadState::LoadNumReboots() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700861 SetNumReboots(GetPersistedValue(kPrefsNumReboots, false));
862}
863
864void PayloadState::LoadRollbackVersion() {
865 SetNumReboots(GetPersistedValue(kPrefsRollbackVersion, true));
866}
867
868void PayloadState::SetRollbackVersion(const string& rollback_version) {
869 CHECK(powerwash_safe_prefs_);
870 LOG(INFO) << "Blacklisting version "<< rollback_version;
871 rollback_version_ = rollback_version;
872 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -0700873}
874
David Zeuthen9a017f22013-04-11 16:10:26 -0700875void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
876 const Time& timestamp,
877 bool use_logging) {
878 CHECK(prefs_);
879 update_duration_uptime_ = value;
880 update_duration_uptime_timestamp_ = timestamp;
881 prefs_->SetInt64(kPrefsUpdateDurationUptime,
882 update_duration_uptime_.ToInternalValue());
883 if (use_logging) {
884 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -0700885 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -0700886 }
887}
888
889void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -0700890 Time now = system_state_->clock()->GetMonotonicTime();
891 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -0700892}
893
894void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700895 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700896 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
897 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
898 // We're frequently called so avoid logging this write
899 SetUpdateDurationUptimeExtended(new_uptime, now, false);
900}
901
David Zeuthen674c3182013-04-18 14:05:20 -0700902void PayloadState::ReportDurationMetrics() {
903 TimeDelta duration = GetUpdateDuration();
904 TimeDelta duration_uptime = GetUpdateDurationUptime();
905 string metric;
906
907 metric = "Installer.UpdateDurationMinutes";
908 system_state_->metrics_lib()->SendToUMA(
909 metric,
910 static_cast<int>(duration.InMinutes()),
911 1, // min: 1 minute
912 365*24*60, // max: 1 year (approx)
913 kNumDefaultUmaBuckets);
914 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
915 << " for metric " << metric;
916
917 metric = "Installer.UpdateDurationUptimeMinutes";
918 system_state_->metrics_lib()->SendToUMA(
919 metric,
920 static_cast<int>(duration_uptime.InMinutes()),
921 1, // min: 1 minute
922 30*24*60, // max: 1 month (approx)
923 kNumDefaultUmaBuckets);
924 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
925 << " for metric " << metric;
926
927 prefs_->Delete(kPrefsUpdateTimestampStart);
928 prefs_->Delete(kPrefsUpdateDurationUptime);
929}
930
Alex Deymo1c656c42013-06-28 11:02:14 -0700931void PayloadState::ReportPayloadTypeMetric() {
932 string metric;
933 PayloadType uma_payload_type;
934 OmahaRequestParams* params = system_state_->request_params();
935
936 if (response_.is_delta_payload) {
937 uma_payload_type = kPayloadTypeDelta;
938 } else if (params->delta_okay()) {
939 uma_payload_type = kPayloadTypeFull;
940 } else { // Full payload, delta was not allowed by request.
941 uma_payload_type = kPayloadTypeForcedFull;
942 }
943
944 metric = "Installer.PayloadFormat";
945 system_state_->metrics_lib()->SendEnumToUMA(
946 metric,
947 uma_payload_type,
948 kNumPayloadTypes);
949 LOG(INFO) << "Uploading " << utils::ToString(uma_payload_type)
950 << " for metric " << metric;
951}
952
Alex Deymo820cc702013-06-28 15:43:46 -0700953void PayloadState::ReportAttemptsCountMetrics() {
954 string metric;
955 int total_attempts = GetPayloadAttemptNumber();
956
957 metric = "Installer.AttemptsCount.Total";
958 system_state_->metrics_lib()->SendToUMA(
959 metric,
960 total_attempts,
961 1, // min
962 50, // max
963 kNumDefaultUmaBuckets);
964 LOG(INFO) << "Uploading " << total_attempts
965 << " for metric " << metric;
966}
967
Jay Srinivasan19409b72013-04-12 19:23:36 -0700968string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
969 return prefix + "-from-" + utils::ToString(source);
970}
971
972void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
973 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosaaa18e162013-06-20 13:20:30 -0700974 SetCurrentBytesDownloaded(source, GetPersistedValue(key, false), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700975}
976
977void PayloadState::SetCurrentBytesDownloaded(
978 DownloadSource source,
979 uint64_t current_bytes_downloaded,
980 bool log) {
981 CHECK(prefs_);
982
983 if (source >= kNumDownloadSources)
984 return;
985
986 // Update the in-memory value.
987 current_bytes_downloaded_[source] = current_bytes_downloaded;
988
989 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
990 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
991 LOG_IF(INFO, log) << "Current bytes downloaded for "
992 << utils::ToString(source) << " = "
993 << GetCurrentBytesDownloaded(source);
994}
995
996void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
997 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosaaa18e162013-06-20 13:20:30 -0700998 SetTotalBytesDownloaded(source, GetPersistedValue(key, false), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700999}
1000
1001void PayloadState::SetTotalBytesDownloaded(
1002 DownloadSource source,
1003 uint64_t total_bytes_downloaded,
1004 bool log) {
1005 CHECK(prefs_);
1006
1007 if (source >= kNumDownloadSources)
1008 return;
1009
1010 // Update the in-memory value.
1011 total_bytes_downloaded_[source] = total_bytes_downloaded;
1012
1013 // Persist.
1014 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1015 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1016 LOG_IF(INFO, log) << "Total bytes downloaded for "
1017 << utils::ToString(source) << " = "
1018 << GetTotalBytesDownloaded(source);
1019}
1020
David Zeuthena573d6f2013-06-14 16:13:36 -07001021void PayloadState::LoadNumResponsesSeen() {
Chris Sosaaa18e162013-06-20 13:20:30 -07001022 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen, false));
David Zeuthena573d6f2013-06-14 16:13:36 -07001023}
1024
1025void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1026 CHECK(prefs_);
1027 num_responses_seen_ = num_responses_seen;
1028 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1029 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1030}
1031
1032void PayloadState::ReportUpdatesAbandonedCountMetric() {
1033 string metric = "Installer.UpdatesAbandonedCount";
1034 int value = num_responses_seen_ - 1;
1035
1036 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1037 system_state_->metrics_lib()->SendToUMA(
1038 metric,
1039 value,
1040 0, // min value
1041 100, // max value
1042 kNumDefaultUmaBuckets);
1043}
1044
Jay Srinivasan53173b92013-05-17 17:13:01 -07001045void PayloadState::ComputeCandidateUrls() {
1046 bool http_url_ok = false;
1047
1048 if (system_state_->IsOfficialBuild()) {
1049 const policy::DevicePolicy* policy = system_state_->device_policy();
1050 if (!(policy && policy->GetHttpDownloadsEnabled(&http_url_ok) &&
1051 http_url_ok))
1052 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1053 } else {
1054 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1055 http_url_ok = true;
1056 }
1057
1058 candidate_urls_.clear();
1059 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1060 string candidate_url = response_.payload_urls[i];
1061 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1062 continue;
1063 candidate_urls_.push_back(candidate_url);
1064 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1065 << ": " << candidate_url;
1066 }
1067
1068 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1069 << "out of " << response_.payload_urls.size() << " URLs supplied";
1070}
1071
David Zeuthene4c58bf2013-06-18 17:26:50 -07001072void PayloadState::CreateSystemUpdatedMarkerFile() {
1073 CHECK(prefs_);
1074 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1075 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1076}
1077
1078void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1079 // Send |time_to_reboot| as a UMA stat.
1080 string metric = "Installer.TimeToRebootMinutes";
1081 system_state_->metrics_lib()->SendToUMA(metric,
1082 time_to_reboot.InMinutes(),
1083 0, // min: 0 minute
1084 30*24*60, // max: 1 month (approx)
1085 kNumDefaultUmaBuckets);
1086 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1087 << " for metric " << metric;
1088}
1089
1090void PayloadState::UpdateEngineStarted() {
1091 // Figure out if we just booted into a new update
1092 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1093 int64_t stored_value;
1094 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1095 Time system_updated_at = Time::FromInternalValue(stored_value);
1096 if (!system_updated_at.is_null()) {
1097 TimeDelta time_to_reboot =
1098 system_state_->clock()->GetWallclockTime() - system_updated_at;
1099 if (time_to_reboot.ToInternalValue() < 0) {
1100 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1101 << utils::ToString(system_updated_at);
1102 } else {
1103 BootedIntoUpdate(time_to_reboot);
1104 }
1105 }
1106 }
1107 prefs_->Delete(kPrefsSystemUpdatedMarker);
1108 }
1109}
1110
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001111} // namespace chromeos_update_engine