blob: c8647dd465823894fa7abaa499d4d8008d0f0034 [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
29static const uint32_t 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),
37 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070038 url_failure_count_(0),
39 url_switch_count_(0) {
Jay Srinivasan19409b72013-04-12 19:23:36 -070040 for (int i = 0; i <= kNumDownloadSources; i++)
41 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
42}
43
44bool PayloadState::Initialize(SystemState* system_state) {
45 system_state_ = system_state;
46 prefs_ = system_state_->prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080047 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080048 LoadPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080049 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080050 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070051 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080052 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070053 LoadUpdateTimestampStart();
54 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
55 // being called before it. Don't reorder.
56 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070057 for (int i = 0; i < kNumDownloadSources; i++) {
58 DownloadSource source = static_cast<DownloadSource>(i);
59 LoadCurrentBytesDownloaded(source);
60 LoadTotalBytesDownloaded(source);
61 }
Chris Sosabe45bef2013-04-09 18:25:12 -070062 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070063 LoadNumResponsesSeen();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080064 return true;
65}
66
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080067void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080068 // Always store the latest response.
69 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080070
Jay Srinivasan53173b92013-05-17 17:13:01 -070071 // Compute the candidate URLs first as they are used to calculate the
72 // response signature so that a change in enterprise policy for
73 // HTTP downloads being enabled or not could be honored as soon as the
74 // next update check happens.
75 ComputeCandidateUrls();
76
Jay Srinivasan08262882012-12-28 19:29:43 -080077 // Check if the "signature" of this response (i.e. the fields we care about)
78 // has changed.
79 string new_response_signature = CalculateResponseSignature();
80 bool has_response_changed = (response_signature_ != new_response_signature);
81
82 // If the response has changed, we should persist the new signature and
83 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080084 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -080085 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -070086 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -080087 SetResponseSignature(new_response_signature);
88 ResetPersistedState();
89 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080090 }
91
Jay Srinivasan08262882012-12-28 19:29:43 -080092 // This is the earliest point at which we can validate whether the URL index
93 // we loaded from the persisted state is a valid value. If the response
94 // hasn't changed but the URL index is invalid, it's indicative of some
95 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -070096 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -080097 LOG(INFO) << "Resetting all payload state as the url index seems to have "
98 "been tampered with";
99 ResetPersistedState();
100 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800101 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700102
103 // Update the current download source which depends on the latest value of
104 // the response.
105 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800106}
107
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800108void PayloadState::DownloadComplete() {
109 LOG(INFO) << "Payload downloaded successfully";
110 IncrementPayloadAttemptNumber();
111}
112
113void PayloadState::DownloadProgress(size_t count) {
114 if (count == 0)
115 return;
116
David Zeuthen9a017f22013-04-11 16:10:26 -0700117 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700118 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700119
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800120 // We've received non-zero bytes from a recent download operation. Since our
121 // URL failure count is meant to penalize a URL only for consecutive
122 // failures, downloading bytes successfully means we should reset the failure
123 // count (as we know at least that the URL is working). In future, we can
124 // design this to be more sophisticated to check for more intelligent failure
125 // patterns, but right now, even 1 byte downloaded will mark the URL to be
126 // good unless it hits 10 (or configured number of) consecutive failures
127 // again.
128
129 if (GetUrlFailureCount() == 0)
130 return;
131
132 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
133 << " to 0 as we received " << count << " bytes successfully";
134 SetUrlFailureCount(0);
135}
136
Chris Sosabe45bef2013-04-09 18:25:12 -0700137void PayloadState::UpdateResumed() {
138 LOG(INFO) << "Resuming an update that was previously started.";
139 UpdateNumReboots();
140}
141
Jay Srinivasan19409b72013-04-12 19:23:36 -0700142void PayloadState::UpdateRestarted() {
143 LOG(INFO) << "Starting a new update";
144 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700145 SetNumReboots(0);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700146}
147
David Zeuthen9a017f22013-04-11 16:10:26 -0700148void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700149 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700150 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700151 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
Jay Srinivasan19409b72013-04-12 19:23:36 -0700152 ReportBytesDownloadedMetrics();
David Zeuthencc6f9962013-04-18 11:57:24 -0700153 ReportUpdateUrlSwitchesMetric();
Chris Sosabe45bef2013-04-09 18:25:12 -0700154 ReportRebootMetrics();
David Zeuthen674c3182013-04-18 14:05:20 -0700155 ReportDurationMetrics();
David Zeuthena573d6f2013-06-14 16:13:36 -0700156 ReportUpdatesAbandonedCountMetric();
157
158 // Reset the number of responses seen since it counts from the last
159 // successful update, e.g. now.
160 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700161
162 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700163}
164
David Zeuthena99981f2013-04-29 13:42:47 -0700165void PayloadState::UpdateFailed(ErrorCode error) {
166 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800167 LOG(INFO) << "Updating payload state for error code: " << base_error
168 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800169
Jay Srinivasan53173b92013-05-17 17:13:01 -0700170 if (candidate_urls_.size() == 0) {
171 // This means we got this error even before we got a valid Omaha response
172 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800173 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800174 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
175 return;
176 }
177
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800178 switch (base_error) {
179 // Errors which are good indicators of a problem with a particular URL or
180 // the protocol used in the URL or entities in the communication channel
181 // (e.g. proxies). We should try the next available URL in the next update
182 // check to quickly recover from these errors.
David Zeuthena99981f2013-04-29 13:42:47 -0700183 case kErrorCodePayloadHashMismatchError:
184 case kErrorCodePayloadSizeMismatchError:
185 case kErrorCodeDownloadPayloadVerificationError:
186 case kErrorCodeDownloadPayloadPubKeyVerificationError:
187 case kErrorCodeSignedDeltaPayloadExpectedError:
188 case kErrorCodeDownloadInvalidMetadataMagicString:
189 case kErrorCodeDownloadSignatureMissingInManifest:
190 case kErrorCodeDownloadManifestParseError:
191 case kErrorCodeDownloadMetadataSignatureError:
192 case kErrorCodeDownloadMetadataSignatureVerificationError:
193 case kErrorCodeDownloadMetadataSignatureMismatch:
194 case kErrorCodeDownloadOperationHashVerificationError:
195 case kErrorCodeDownloadOperationExecutionError:
196 case kErrorCodeDownloadOperationHashMismatch:
197 case kErrorCodeDownloadInvalidMetadataSize:
198 case kErrorCodeDownloadInvalidMetadataSignature:
199 case kErrorCodeDownloadOperationHashMissingError:
200 case kErrorCodeDownloadMetadataSignatureMissingError:
Gilad Arnold21504f02013-05-24 08:51:22 -0700201 case kErrorCodePayloadMismatchedType:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800202 IncrementUrlIndex();
203 break;
204
205 // Errors which seem to be just transient network/communication related
206 // failures and do not indicate any inherent problem with the URL itself.
207 // So, we should keep the current URL but just increment the
208 // failure count to give it more chances. This way, while we maximize our
209 // chances of downloading from the URLs that appear earlier in the response
210 // (because download from a local server URL that appears earlier in a
211 // response is preferable than downloading from the next URL which could be
212 // a internet URL and thus could be more expensive).
David Zeuthena99981f2013-04-29 13:42:47 -0700213 case kErrorCodeError:
214 case kErrorCodeDownloadTransferError:
215 case kErrorCodeDownloadWriteError:
216 case kErrorCodeDownloadStateInitializationError:
217 case kErrorCodeOmahaErrorInHTTPResponse: // Aggregate code for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800218 IncrementFailureCount();
219 break;
220
221 // Errors which are not specific to a URL and hence shouldn't result in
222 // the URL being penalized. This can happen in two cases:
223 // 1. We haven't started downloading anything: These errors don't cost us
224 // anything in terms of actual payload bytes, so we should just do the
225 // regular retries at the next update check.
226 // 2. We have successfully downloaded the payload: In this case, the
227 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800228 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800229 // In either case, there's no need to update URL index or failure count.
David Zeuthena99981f2013-04-29 13:42:47 -0700230 case kErrorCodeOmahaRequestError:
231 case kErrorCodeOmahaResponseHandlerError:
232 case kErrorCodePostinstallRunnerError:
233 case kErrorCodeFilesystemCopierError:
234 case kErrorCodeInstallDeviceOpenError:
235 case kErrorCodeKernelDeviceOpenError:
236 case kErrorCodeDownloadNewPartitionInfoError:
237 case kErrorCodeNewRootfsVerificationError:
238 case kErrorCodeNewKernelVerificationError:
239 case kErrorCodePostinstallBootedFromFirmwareB:
240 case kErrorCodeOmahaRequestEmptyResponseError:
241 case kErrorCodeOmahaRequestXMLParseError:
242 case kErrorCodeOmahaResponseInvalid:
243 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
244 case kErrorCodeOmahaUpdateDeferredPerPolicy:
245 case kErrorCodeOmahaUpdateDeferredForBackoff:
246 case kErrorCodePostinstallPowerwashError:
247 case kErrorCodeUpdateCanceledByChannelChange:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800248 LOG(INFO) << "Not incrementing URL index or failure count for this error";
249 break;
250
David Zeuthena99981f2013-04-29 13:42:47 -0700251 case kErrorCodeSuccess: // success code
David Zeuthena99981f2013-04-29 13:42:47 -0700252 case kErrorCodeUmaReportedMax: // not an error code
253 case kErrorCodeOmahaRequestHTTPResponseBase: // aggregated already
254 case kErrorCodeDevModeFlag: // not an error code
255 case kErrorCodeResumedFlag: // not an error code
256 case kErrorCodeTestImageFlag: // not an error code
257 case kErrorCodeTestOmahaUrlFlag: // not an error code
258 case kErrorCodeSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800259 // These shouldn't happen. Enumerating these explicitly here so that we
260 // can let the compiler warn about new error codes that are added to
261 // action_processor.h but not added here.
262 LOG(WARNING) << "Unexpected error code for UpdateFailed";
263 break;
264
265 // Note: Not adding a default here so as to let the compiler warn us of
266 // any new enums that were added in the .h but not listed in this switch.
267 }
268}
269
Jay Srinivasan08262882012-12-28 19:29:43 -0800270bool PayloadState::ShouldBackoffDownload() {
271 if (response_.disable_payload_backoff) {
272 LOG(INFO) << "Payload backoff logic is disabled. "
273 "Can proceed with the download";
274 return false;
275 }
276
277 if (response_.is_delta_payload) {
278 // If delta payloads fail, we want to fallback quickly to full payloads as
279 // they are more likely to succeed. Exponential backoffs would greatly
280 // slow down the fallback to full payloads. So we don't backoff for delta
281 // payloads.
282 LOG(INFO) << "No backoffs for delta payloads. "
283 << "Can proceed with the download";
284 return false;
285 }
286
287 if (!utils::IsOfficialBuild()) {
288 // Backoffs are needed only for official builds. We do not want any delays
289 // or update failures due to backoffs during testing or development.
290 LOG(INFO) << "No backoffs for test/dev images. "
291 << "Can proceed with the download";
292 return false;
293 }
294
295 if (backoff_expiry_time_.is_null()) {
296 LOG(INFO) << "No backoff expiry time has been set. "
297 << "Can proceed with the download";
298 return false;
299 }
300
301 if (backoff_expiry_time_ < Time::Now()) {
302 LOG(INFO) << "The backoff expiry time ("
303 << utils::ToString(backoff_expiry_time_)
304 << ") has elapsed. Can proceed with the download";
305 return false;
306 }
307
308 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
309 << utils::ToString(backoff_expiry_time_);
310 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800311}
312
313void PayloadState::IncrementPayloadAttemptNumber() {
Jay Srinivasan08262882012-12-28 19:29:43 -0800314 if (response_.is_delta_payload) {
315 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
316 return;
317 }
318
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800319 LOG(INFO) << "Incrementing the payload attempt number";
320 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800321 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800322}
323
324void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800325 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700326 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800327 LOG(INFO) << "Incrementing the URL index for next attempt";
328 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800329 } else {
330 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700331 << "0 as we only have " << candidate_urls_.size()
332 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800333 SetUrlIndex(0);
334 IncrementPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800335 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800336
David Zeuthencc6f9962013-04-18 11:57:24 -0700337 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700338 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700339 SetUrlSwitchCount(url_switch_count_ + 1);
340
Jay Srinivasan08262882012-12-28 19:29:43 -0800341 // Whenever we update the URL index, we should also clear the URL failure
342 // count so we can start over fresh for the new URL.
343 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800344}
345
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800346void PayloadState::IncrementFailureCount() {
347 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800348 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800349 LOG(INFO) << "Incrementing the URL failure count";
350 SetUrlFailureCount(next_url_failure_count);
351 } else {
352 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
353 << ". Trying next available URL";
354 IncrementUrlIndex();
355 }
356}
357
Jay Srinivasan08262882012-12-28 19:29:43 -0800358void PayloadState::UpdateBackoffExpiryTime() {
359 if (response_.disable_payload_backoff) {
360 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
361 SetBackoffExpiryTime(Time());
362 return;
363 }
364
365 if (GetPayloadAttemptNumber() == 0) {
366 SetBackoffExpiryTime(Time());
367 return;
368 }
369
370 // Since we're doing left-shift below, make sure we don't shift more
371 // than this. E.g. if uint32_t is 4-bytes, don't left-shift more than 30 bits,
372 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
373 uint32_t num_days = 1; // the value to be shifted.
374 const uint32_t kMaxShifts = (sizeof(num_days) * 8) - 2;
375
376 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
377 // E.g. if payload_attempt_number is over 30, limit power to 30.
378 uint32_t power = min(GetPayloadAttemptNumber() - 1, kMaxShifts);
379
380 // The number of days is the minimum of 2 raised to (payload_attempt_number
381 // - 1) or kMaxBackoffDays.
382 num_days = min(num_days << power, kMaxBackoffDays);
383
384 // We don't want all retries to happen exactly at the same time when
385 // retrying after backoff. So add some random minutes to fuzz.
386 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
387 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
388 TimeDelta::FromMinutes(fuzz_minutes);
389 LOG(INFO) << "Incrementing the backoff expiry time by "
390 << utils::FormatTimeDelta(next_backoff_interval);
391 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
392}
393
Jay Srinivasan19409b72013-04-12 19:23:36 -0700394void PayloadState::UpdateCurrentDownloadSource() {
395 current_download_source_ = kNumDownloadSources;
396
Jay Srinivasan53173b92013-05-17 17:13:01 -0700397 if (GetUrlIndex() < candidate_urls_.size()) {
398 string current_url = candidate_urls_[GetUrlIndex()];
Jay Srinivasan19409b72013-04-12 19:23:36 -0700399 if (StartsWithASCII(current_url, "https://", false))
400 current_download_source_ = kDownloadSourceHttpsServer;
401 else if (StartsWithASCII(current_url, "http://", false))
402 current_download_source_ = kDownloadSourceHttpServer;
403 }
404
405 LOG(INFO) << "Current download source: "
406 << utils::ToString(current_download_source_);
407}
408
409void PayloadState::UpdateBytesDownloaded(size_t count) {
410 SetCurrentBytesDownloaded(
411 current_download_source_,
412 GetCurrentBytesDownloaded(current_download_source_) + count,
413 false);
414 SetTotalBytesDownloaded(
415 current_download_source_,
416 GetTotalBytesDownloaded(current_download_source_) + count,
417 false);
418}
419
420void PayloadState::ReportBytesDownloadedMetrics() {
421 // Report metrics collected from all known download sources to UMA.
422 // The reported data is in Megabytes in order to represent a larger
423 // sample range.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700424 int download_sources_used = 0;
425 string metric;
426 uint64_t successful_mbs = 0;
427 uint64_t total_mbs = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700428 for (int i = 0; i < kNumDownloadSources; i++) {
429 DownloadSource source = static_cast<DownloadSource>(i);
430 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
431
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700432 metric = "Installer.SuccessfulMBsDownloadedFrom" + utils::ToString(source);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700433 uint64_t mbs = GetCurrentBytesDownloaded(source) / kNumBytesInOneMiB;
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700434
435 // Count this download source as having been used if we downloaded any
436 // bytes that contributed to the final success of the update.
437 if (mbs)
438 download_sources_used |= (1 << source);
439
440 successful_mbs += mbs;
441 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700442 system_state_->metrics_lib()->SendToUMA(metric,
443 mbs,
444 0, // min
445 kMaxMiBs,
446 kNumDefaultUmaBuckets);
447 SetCurrentBytesDownloaded(source, 0, true);
448
449 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
450 mbs = GetTotalBytesDownloaded(source) / kNumBytesInOneMiB;
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700451 total_mbs += mbs;
452 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700453 system_state_->metrics_lib()->SendToUMA(metric,
454 mbs,
455 0, // min
456 kMaxMiBs,
457 kNumDefaultUmaBuckets);
458
459 SetTotalBytesDownloaded(source, 0, true);
460 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700461
462 metric = "Installer.DownloadSourcesUsed";
463 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
464 << " (bit flags) for metric " << metric;
465 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
466 system_state_->metrics_lib()->SendToUMA(metric,
467 download_sources_used,
468 0, // min
469 1 << kNumDownloadSources,
470 num_buckets);
471
472 if (successful_mbs) {
473 metric = "Installer.DownloadOverheadPercentage";
474 int percent_overhead = (total_mbs - successful_mbs) * 100 / successful_mbs;
475 LOG(INFO) << "Uploading " << percent_overhead << "% for metric " << metric;
476 system_state_->metrics_lib()->SendToUMA(metric,
477 percent_overhead,
478 0, // min: 0% overhead
479 1000, // max: 1000% overhead
480 kNumDefaultUmaBuckets);
481 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700482}
483
David Zeuthencc6f9962013-04-18 11:57:24 -0700484void PayloadState::ReportUpdateUrlSwitchesMetric() {
485 string metric = "Installer.UpdateURLSwitches";
486 int value = static_cast<int>(url_switch_count_);
487
488 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
489 system_state_->metrics_lib()->SendToUMA(
490 metric,
491 value,
492 0, // min value
493 100, // max value
494 kNumDefaultUmaBuckets);
495}
496
Chris Sosabe45bef2013-04-09 18:25:12 -0700497void PayloadState::ReportRebootMetrics() {
498 // Report the number of num_reboots.
499 string metric = "Installer.UpdateNumReboots";
500 uint32_t num_reboots = GetNumReboots();
501 LOG(INFO) << "Uploading reboot count of " << num_reboots << " for metric "
502 << metric;
503 system_state_->metrics_lib()->SendToUMA(
504 metric,
505 static_cast<int>(num_reboots), // sample
506 0, // min = 0.
507 50, // max
508 25); // buckets
509 SetNumReboots(0);
510}
511
512void PayloadState::UpdateNumReboots() {
513 // We only update the reboot count when the system has been detected to have
514 // been rebooted.
515 if (!system_state_->system_rebooted()) {
516 return;
517 }
518
519 SetNumReboots(GetNumReboots() + 1);
520}
521
522void PayloadState::SetNumReboots(uint32_t num_reboots) {
523 CHECK(prefs_);
524 num_reboots_ = num_reboots;
525 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
526 LOG(INFO) << "Number of Reboots during current update attempt = "
527 << num_reboots_;
528}
529
Jay Srinivasan08262882012-12-28 19:29:43 -0800530void PayloadState::ResetPersistedState() {
531 SetPayloadAttemptNumber(0);
532 SetUrlIndex(0);
533 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700534 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800535 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700536 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
David Zeuthen9a017f22013-04-11 16:10:26 -0700537 SetUpdateTimestampEnd(Time()); // Set to null time
538 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700539 ResetDownloadSourcesOnNewUpdate();
540}
541
542void PayloadState::ResetDownloadSourcesOnNewUpdate() {
543 for (int i = 0; i < kNumDownloadSources; i++) {
544 DownloadSource source = static_cast<DownloadSource>(i);
545 SetCurrentBytesDownloaded(source, 0, true);
546 // Note: Not resetting the TotalBytesDownloaded as we want that metric
547 // to count the bytes downloaded across various update attempts until
548 // we have successfully applied the update.
549 }
550}
551
552int64_t PayloadState::GetPersistedValue(const string& key) {
553 CHECK(prefs_);
554 if (!prefs_->Exists(key))
555 return 0;
556
557 int64_t stored_value;
558 if (!prefs_->GetInt64(key, &stored_value))
559 return 0;
560
561 if (stored_value < 0) {
562 LOG(ERROR) << key << ": Invalid value (" << stored_value
563 << ") in persisted state. Defaulting to 0";
564 return 0;
565 }
566
567 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800568}
569
570string PayloadState::CalculateResponseSignature() {
571 string response_sign = StringPrintf("NumURLs = %d\n",
Jay Srinivasan53173b92013-05-17 17:13:01 -0700572 candidate_urls_.size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800573
Jay Srinivasan53173b92013-05-17 17:13:01 -0700574 for (size_t i = 0; i < candidate_urls_.size(); i++)
575 response_sign += StringPrintf("Candidate Url%d = %s\n",
576 i, candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800577
578 response_sign += StringPrintf("Payload Size = %llu\n"
579 "Payload Sha256 Hash = %s\n"
580 "Metadata Size = %llu\n"
581 "Metadata Signature = %s\n"
582 "Is Delta Payload = %d\n"
583 "Max Failure Count Per Url = %d\n"
584 "Disable Payload Backoff = %d\n",
585 response_.size,
586 response_.hash.c_str(),
587 response_.metadata_size,
588 response_.metadata_signature.c_str(),
589 response_.is_delta_payload,
590 response_.max_failure_count_per_url,
591 response_.disable_payload_backoff);
592 return response_sign;
593}
594
595void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800596 CHECK(prefs_);
597 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800598 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
599 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
600 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800601 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800602}
603
Jay Srinivasan19409b72013-04-12 19:23:36 -0700604void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800605 CHECK(prefs_);
606 response_signature_ = response_signature;
607 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
608 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
609}
610
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800611void PayloadState::LoadPayloadAttemptNumber() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700612 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800613}
614
615void PayloadState::SetPayloadAttemptNumber(uint32_t payload_attempt_number) {
616 CHECK(prefs_);
617 payload_attempt_number_ = payload_attempt_number;
618 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
619 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
620}
621
622void PayloadState::LoadUrlIndex() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700623 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800624}
625
626void PayloadState::SetUrlIndex(uint32_t url_index) {
627 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800628 url_index_ = url_index;
629 LOG(INFO) << "Current URL Index = " << url_index_;
630 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700631
632 // Also update the download source, which is purely dependent on the
633 // current URL index alone.
634 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800635}
636
David Zeuthencc6f9962013-04-18 11:57:24 -0700637void PayloadState::LoadUrlSwitchCount() {
638 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
639}
640
641void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
642 CHECK(prefs_);
643 url_switch_count_ = url_switch_count;
644 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
645 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
646}
647
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800648void PayloadState::LoadUrlFailureCount() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700649 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800650}
651
652void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
653 CHECK(prefs_);
654 url_failure_count_ = url_failure_count;
655 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
656 << ")'s Failure Count = " << url_failure_count_;
657 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800658}
659
Jay Srinivasan08262882012-12-28 19:29:43 -0800660void PayloadState::LoadBackoffExpiryTime() {
661 CHECK(prefs_);
662 int64_t stored_value;
663 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
664 return;
665
666 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
667 return;
668
669 Time stored_time = Time::FromInternalValue(stored_value);
670 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
671 LOG(ERROR) << "Invalid backoff expiry time ("
672 << utils::ToString(stored_time)
673 << ") in persisted state. Resetting.";
674 stored_time = Time();
675 }
676 SetBackoffExpiryTime(stored_time);
677}
678
679void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
680 CHECK(prefs_);
681 backoff_expiry_time_ = new_time;
682 LOG(INFO) << "Backoff Expiry Time = "
683 << utils::ToString(backoff_expiry_time_);
684 prefs_->SetInt64(kPrefsBackoffExpiryTime,
685 backoff_expiry_time_.ToInternalValue());
686}
687
David Zeuthen9a017f22013-04-11 16:10:26 -0700688TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700689 Time end_time = update_timestamp_end_.is_null()
690 ? system_state_->clock()->GetWallclockTime() :
691 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700692 return end_time - update_timestamp_start_;
693}
694
695void PayloadState::LoadUpdateTimestampStart() {
696 int64_t stored_value;
697 Time stored_time;
698
699 CHECK(prefs_);
700
David Zeuthenf413fe52013-04-22 14:04:39 -0700701 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700702
703 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
704 // The preference missing is not unexpected - in that case, just
705 // use the current time as start time
706 stored_time = now;
707 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
708 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
709 stored_time = now;
710 } else {
711 stored_time = Time::FromInternalValue(stored_value);
712 }
713
714 // Sanity check: If the time read from disk is in the future
715 // (modulo some slack to account for possible NTP drift
716 // adjustments), something is fishy and we should report and
717 // reset.
718 TimeDelta duration_according_to_stored_time = now - stored_time;
719 if (duration_according_to_stored_time < -kDurationSlack) {
720 LOG(ERROR) << "The UpdateTimestampStart value ("
721 << utils::ToString(stored_time)
722 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700723 << utils::FormatTimeDelta(duration_according_to_stored_time)
724 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700725 stored_time = now;
726 }
727
728 SetUpdateTimestampStart(stored_time);
729}
730
731void PayloadState::SetUpdateTimestampStart(const Time& value) {
732 CHECK(prefs_);
733 update_timestamp_start_ = value;
734 prefs_->SetInt64(kPrefsUpdateTimestampStart,
735 update_timestamp_start_.ToInternalValue());
736 LOG(INFO) << "Update Timestamp Start = "
737 << utils::ToString(update_timestamp_start_);
738}
739
740void PayloadState::SetUpdateTimestampEnd(const Time& value) {
741 update_timestamp_end_ = value;
742 LOG(INFO) << "Update Timestamp End = "
743 << utils::ToString(update_timestamp_end_);
744}
745
746TimeDelta PayloadState::GetUpdateDurationUptime() {
747 return update_duration_uptime_;
748}
749
750void PayloadState::LoadUpdateDurationUptime() {
751 int64_t stored_value;
752 TimeDelta stored_delta;
753
754 CHECK(prefs_);
755
756 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
757 // The preference missing is not unexpected - in that case, just
758 // we'll use zero as the delta
759 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
760 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
761 stored_delta = TimeDelta::FromSeconds(0);
762 } else {
763 stored_delta = TimeDelta::FromInternalValue(stored_value);
764 }
765
766 // Sanity-check: Uptime can never be greater than the wall-clock
767 // difference (modulo some slack). If it is, report and reset
768 // to the wall-clock difference.
769 TimeDelta diff = GetUpdateDuration() - stored_delta;
770 if (diff < -kDurationSlack) {
771 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -0700772 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -0700773 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700774 << utils::FormatTimeDelta(diff)
775 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700776 stored_delta = update_duration_current_;
777 }
778
779 SetUpdateDurationUptime(stored_delta);
780}
781
Chris Sosabe45bef2013-04-09 18:25:12 -0700782void PayloadState::LoadNumReboots() {
783 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
784}
785
David Zeuthen9a017f22013-04-11 16:10:26 -0700786void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
787 const Time& timestamp,
788 bool use_logging) {
789 CHECK(prefs_);
790 update_duration_uptime_ = value;
791 update_duration_uptime_timestamp_ = timestamp;
792 prefs_->SetInt64(kPrefsUpdateDurationUptime,
793 update_duration_uptime_.ToInternalValue());
794 if (use_logging) {
795 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -0700796 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -0700797 }
798}
799
800void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -0700801 Time now = system_state_->clock()->GetMonotonicTime();
802 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -0700803}
804
805void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700806 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700807 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
808 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
809 // We're frequently called so avoid logging this write
810 SetUpdateDurationUptimeExtended(new_uptime, now, false);
811}
812
David Zeuthen674c3182013-04-18 14:05:20 -0700813void PayloadState::ReportDurationMetrics() {
814 TimeDelta duration = GetUpdateDuration();
815 TimeDelta duration_uptime = GetUpdateDurationUptime();
816 string metric;
817
818 metric = "Installer.UpdateDurationMinutes";
819 system_state_->metrics_lib()->SendToUMA(
820 metric,
821 static_cast<int>(duration.InMinutes()),
822 1, // min: 1 minute
823 365*24*60, // max: 1 year (approx)
824 kNumDefaultUmaBuckets);
825 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
826 << " for metric " << metric;
827
828 metric = "Installer.UpdateDurationUptimeMinutes";
829 system_state_->metrics_lib()->SendToUMA(
830 metric,
831 static_cast<int>(duration_uptime.InMinutes()),
832 1, // min: 1 minute
833 30*24*60, // max: 1 month (approx)
834 kNumDefaultUmaBuckets);
835 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
836 << " for metric " << metric;
837
838 prefs_->Delete(kPrefsUpdateTimestampStart);
839 prefs_->Delete(kPrefsUpdateDurationUptime);
840}
841
Jay Srinivasan19409b72013-04-12 19:23:36 -0700842string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
843 return prefix + "-from-" + utils::ToString(source);
844}
845
846void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
847 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
848 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
849}
850
851void PayloadState::SetCurrentBytesDownloaded(
852 DownloadSource source,
853 uint64_t current_bytes_downloaded,
854 bool log) {
855 CHECK(prefs_);
856
857 if (source >= kNumDownloadSources)
858 return;
859
860 // Update the in-memory value.
861 current_bytes_downloaded_[source] = current_bytes_downloaded;
862
863 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
864 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
865 LOG_IF(INFO, log) << "Current bytes downloaded for "
866 << utils::ToString(source) << " = "
867 << GetCurrentBytesDownloaded(source);
868}
869
870void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
871 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
872 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
873}
874
875void PayloadState::SetTotalBytesDownloaded(
876 DownloadSource source,
877 uint64_t total_bytes_downloaded,
878 bool log) {
879 CHECK(prefs_);
880
881 if (source >= kNumDownloadSources)
882 return;
883
884 // Update the in-memory value.
885 total_bytes_downloaded_[source] = total_bytes_downloaded;
886
887 // Persist.
888 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
889 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
890 LOG_IF(INFO, log) << "Total bytes downloaded for "
891 << utils::ToString(source) << " = "
892 << GetTotalBytesDownloaded(source);
893}
894
David Zeuthena573d6f2013-06-14 16:13:36 -0700895void PayloadState::LoadNumResponsesSeen() {
896 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
897}
898
899void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
900 CHECK(prefs_);
901 num_responses_seen_ = num_responses_seen;
902 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
903 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
904}
905
906void PayloadState::ReportUpdatesAbandonedCountMetric() {
907 string metric = "Installer.UpdatesAbandonedCount";
908 int value = num_responses_seen_ - 1;
909
910 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
911 system_state_->metrics_lib()->SendToUMA(
912 metric,
913 value,
914 0, // min value
915 100, // max value
916 kNumDefaultUmaBuckets);
917}
918
Jay Srinivasan53173b92013-05-17 17:13:01 -0700919void PayloadState::ComputeCandidateUrls() {
920 bool http_url_ok = false;
921
922 if (system_state_->IsOfficialBuild()) {
923 const policy::DevicePolicy* policy = system_state_->device_policy();
924 if (!(policy && policy->GetHttpDownloadsEnabled(&http_url_ok) &&
925 http_url_ok))
926 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
927 } else {
928 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
929 http_url_ok = true;
930 }
931
932 candidate_urls_.clear();
933 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
934 string candidate_url = response_.payload_urls[i];
935 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
936 continue;
937 candidate_urls_.push_back(candidate_url);
938 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
939 << ": " << candidate_url;
940 }
941
942 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
943 << "out of " << response_.payload_urls.size() << " URLs supplied";
944}
945
David Zeuthene4c58bf2013-06-18 17:26:50 -0700946void PayloadState::CreateSystemUpdatedMarkerFile() {
947 CHECK(prefs_);
948 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
949 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
950}
951
952void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
953 // Send |time_to_reboot| as a UMA stat.
954 string metric = "Installer.TimeToRebootMinutes";
955 system_state_->metrics_lib()->SendToUMA(metric,
956 time_to_reboot.InMinutes(),
957 0, // min: 0 minute
958 30*24*60, // max: 1 month (approx)
959 kNumDefaultUmaBuckets);
960 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
961 << " for metric " << metric;
962}
963
964void PayloadState::UpdateEngineStarted() {
965 // Figure out if we just booted into a new update
966 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
967 int64_t stored_value;
968 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
969 Time system_updated_at = Time::FromInternalValue(stored_value);
970 if (!system_updated_at.is_null()) {
971 TimeDelta time_to_reboot =
972 system_state_->clock()->GetWallclockTime() - system_updated_at;
973 if (time_to_reboot.ToInternalValue() < 0) {
974 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
975 << utils::ToString(system_updated_at);
976 } else {
977 BootedIntoUpdate(time_to_reboot);
978 }
979 }
980 }
981 prefs_->Delete(kPrefsSystemUpdatedMarker);
982 }
983}
984
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800985} // namespace chromeos_update_engine