blob: 1823ce715404621f1d6be8589b09ae41020d4798 [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.
David Zeuthen44848602013-06-24 13:32:14 -0700431 uint64_t mbs;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700432
David Zeuthen44848602013-06-24 13:32:14 -0700433 // Only consider this download source (and send byte counts) as
434 // having been used if we downloaded a non-trivial amount of bytes
435 // (e.g. at least 1 MiB) that contributed to the final success of
436 // the update. Otherwise we're going to end up with a lot of
437 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700438
David Zeuthen44848602013-06-24 13:32:14 -0700439 mbs = GetCurrentBytesDownloaded(source) / kNumBytesInOneMiB;
440 if (mbs > 0) {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700441 download_sources_used |= (1 << source);
442
David Zeuthen44848602013-06-24 13:32:14 -0700443 metric = "Installer.SuccessfulMBsDownloadedFrom" +
444 utils::ToString(source);
445 successful_mbs += mbs;
446 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
447 system_state_->metrics_lib()->SendToUMA(metric,
448 mbs,
449 0, // min
450 kMaxMiBs,
451 kNumDefaultUmaBuckets);
452 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700453 SetCurrentBytesDownloaded(source, 0, true);
454
Jay Srinivasan19409b72013-04-12 19:23:36 -0700455 mbs = GetTotalBytesDownloaded(source) / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700456 if (mbs > 0) {
457 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
458 total_mbs += mbs;
459 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
460 system_state_->metrics_lib()->SendToUMA(metric,
461 mbs,
462 0, // min
463 kMaxMiBs,
464 kNumDefaultUmaBuckets);
465 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700466 SetTotalBytesDownloaded(source, 0, true);
467 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700468
469 metric = "Installer.DownloadSourcesUsed";
470 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
471 << " (bit flags) for metric " << metric;
472 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
473 system_state_->metrics_lib()->SendToUMA(metric,
474 download_sources_used,
475 0, // min
476 1 << kNumDownloadSources,
477 num_buckets);
478
479 if (successful_mbs) {
480 metric = "Installer.DownloadOverheadPercentage";
481 int percent_overhead = (total_mbs - successful_mbs) * 100 / successful_mbs;
482 LOG(INFO) << "Uploading " << percent_overhead << "% for metric " << metric;
483 system_state_->metrics_lib()->SendToUMA(metric,
484 percent_overhead,
485 0, // min: 0% overhead
486 1000, // max: 1000% overhead
487 kNumDefaultUmaBuckets);
488 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700489}
490
David Zeuthencc6f9962013-04-18 11:57:24 -0700491void PayloadState::ReportUpdateUrlSwitchesMetric() {
492 string metric = "Installer.UpdateURLSwitches";
493 int value = static_cast<int>(url_switch_count_);
494
495 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
496 system_state_->metrics_lib()->SendToUMA(
497 metric,
498 value,
499 0, // min value
500 100, // max value
501 kNumDefaultUmaBuckets);
502}
503
Chris Sosabe45bef2013-04-09 18:25:12 -0700504void PayloadState::ReportRebootMetrics() {
505 // Report the number of num_reboots.
506 string metric = "Installer.UpdateNumReboots";
507 uint32_t num_reboots = GetNumReboots();
508 LOG(INFO) << "Uploading reboot count of " << num_reboots << " for metric "
509 << metric;
510 system_state_->metrics_lib()->SendToUMA(
511 metric,
512 static_cast<int>(num_reboots), // sample
513 0, // min = 0.
514 50, // max
515 25); // buckets
516 SetNumReboots(0);
517}
518
519void PayloadState::UpdateNumReboots() {
520 // We only update the reboot count when the system has been detected to have
521 // been rebooted.
522 if (!system_state_->system_rebooted()) {
523 return;
524 }
525
526 SetNumReboots(GetNumReboots() + 1);
527}
528
529void PayloadState::SetNumReboots(uint32_t num_reboots) {
530 CHECK(prefs_);
531 num_reboots_ = num_reboots;
532 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
533 LOG(INFO) << "Number of Reboots during current update attempt = "
534 << num_reboots_;
535}
536
Jay Srinivasan08262882012-12-28 19:29:43 -0800537void PayloadState::ResetPersistedState() {
538 SetPayloadAttemptNumber(0);
539 SetUrlIndex(0);
540 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700541 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800542 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700543 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
David Zeuthen9a017f22013-04-11 16:10:26 -0700544 SetUpdateTimestampEnd(Time()); // Set to null time
545 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700546 ResetDownloadSourcesOnNewUpdate();
547}
548
549void PayloadState::ResetDownloadSourcesOnNewUpdate() {
550 for (int i = 0; i < kNumDownloadSources; i++) {
551 DownloadSource source = static_cast<DownloadSource>(i);
552 SetCurrentBytesDownloaded(source, 0, true);
553 // Note: Not resetting the TotalBytesDownloaded as we want that metric
554 // to count the bytes downloaded across various update attempts until
555 // we have successfully applied the update.
556 }
557}
558
559int64_t PayloadState::GetPersistedValue(const string& key) {
560 CHECK(prefs_);
561 if (!prefs_->Exists(key))
562 return 0;
563
564 int64_t stored_value;
565 if (!prefs_->GetInt64(key, &stored_value))
566 return 0;
567
568 if (stored_value < 0) {
569 LOG(ERROR) << key << ": Invalid value (" << stored_value
570 << ") in persisted state. Defaulting to 0";
571 return 0;
572 }
573
574 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800575}
576
577string PayloadState::CalculateResponseSignature() {
578 string response_sign = StringPrintf("NumURLs = %d\n",
Jay Srinivasan53173b92013-05-17 17:13:01 -0700579 candidate_urls_.size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800580
Jay Srinivasan53173b92013-05-17 17:13:01 -0700581 for (size_t i = 0; i < candidate_urls_.size(); i++)
582 response_sign += StringPrintf("Candidate Url%d = %s\n",
583 i, candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800584
585 response_sign += StringPrintf("Payload Size = %llu\n"
586 "Payload Sha256 Hash = %s\n"
587 "Metadata Size = %llu\n"
588 "Metadata Signature = %s\n"
589 "Is Delta Payload = %d\n"
590 "Max Failure Count Per Url = %d\n"
591 "Disable Payload Backoff = %d\n",
592 response_.size,
593 response_.hash.c_str(),
594 response_.metadata_size,
595 response_.metadata_signature.c_str(),
596 response_.is_delta_payload,
597 response_.max_failure_count_per_url,
598 response_.disable_payload_backoff);
599 return response_sign;
600}
601
602void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800603 CHECK(prefs_);
604 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800605 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
606 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
607 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800608 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800609}
610
Jay Srinivasan19409b72013-04-12 19:23:36 -0700611void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800612 CHECK(prefs_);
613 response_signature_ = response_signature;
614 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
615 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
616}
617
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800618void PayloadState::LoadPayloadAttemptNumber() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700619 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800620}
621
622void PayloadState::SetPayloadAttemptNumber(uint32_t payload_attempt_number) {
623 CHECK(prefs_);
624 payload_attempt_number_ = payload_attempt_number;
625 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
626 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
627}
628
629void PayloadState::LoadUrlIndex() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700630 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800631}
632
633void PayloadState::SetUrlIndex(uint32_t url_index) {
634 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800635 url_index_ = url_index;
636 LOG(INFO) << "Current URL Index = " << url_index_;
637 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700638
639 // Also update the download source, which is purely dependent on the
640 // current URL index alone.
641 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800642}
643
David Zeuthencc6f9962013-04-18 11:57:24 -0700644void PayloadState::LoadUrlSwitchCount() {
645 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
646}
647
648void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
649 CHECK(prefs_);
650 url_switch_count_ = url_switch_count;
651 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
652 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
653}
654
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800655void PayloadState::LoadUrlFailureCount() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700656 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800657}
658
659void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
660 CHECK(prefs_);
661 url_failure_count_ = url_failure_count;
662 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
663 << ")'s Failure Count = " << url_failure_count_;
664 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800665}
666
Jay Srinivasan08262882012-12-28 19:29:43 -0800667void PayloadState::LoadBackoffExpiryTime() {
668 CHECK(prefs_);
669 int64_t stored_value;
670 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
671 return;
672
673 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
674 return;
675
676 Time stored_time = Time::FromInternalValue(stored_value);
677 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
678 LOG(ERROR) << "Invalid backoff expiry time ("
679 << utils::ToString(stored_time)
680 << ") in persisted state. Resetting.";
681 stored_time = Time();
682 }
683 SetBackoffExpiryTime(stored_time);
684}
685
686void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
687 CHECK(prefs_);
688 backoff_expiry_time_ = new_time;
689 LOG(INFO) << "Backoff Expiry Time = "
690 << utils::ToString(backoff_expiry_time_);
691 prefs_->SetInt64(kPrefsBackoffExpiryTime,
692 backoff_expiry_time_.ToInternalValue());
693}
694
David Zeuthen9a017f22013-04-11 16:10:26 -0700695TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700696 Time end_time = update_timestamp_end_.is_null()
697 ? system_state_->clock()->GetWallclockTime() :
698 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700699 return end_time - update_timestamp_start_;
700}
701
702void PayloadState::LoadUpdateTimestampStart() {
703 int64_t stored_value;
704 Time stored_time;
705
706 CHECK(prefs_);
707
David Zeuthenf413fe52013-04-22 14:04:39 -0700708 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700709
710 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
711 // The preference missing is not unexpected - in that case, just
712 // use the current time as start time
713 stored_time = now;
714 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
715 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
716 stored_time = now;
717 } else {
718 stored_time = Time::FromInternalValue(stored_value);
719 }
720
721 // Sanity check: If the time read from disk is in the future
722 // (modulo some slack to account for possible NTP drift
723 // adjustments), something is fishy and we should report and
724 // reset.
725 TimeDelta duration_according_to_stored_time = now - stored_time;
726 if (duration_according_to_stored_time < -kDurationSlack) {
727 LOG(ERROR) << "The UpdateTimestampStart value ("
728 << utils::ToString(stored_time)
729 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700730 << utils::FormatTimeDelta(duration_according_to_stored_time)
731 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700732 stored_time = now;
733 }
734
735 SetUpdateTimestampStart(stored_time);
736}
737
738void PayloadState::SetUpdateTimestampStart(const Time& value) {
739 CHECK(prefs_);
740 update_timestamp_start_ = value;
741 prefs_->SetInt64(kPrefsUpdateTimestampStart,
742 update_timestamp_start_.ToInternalValue());
743 LOG(INFO) << "Update Timestamp Start = "
744 << utils::ToString(update_timestamp_start_);
745}
746
747void PayloadState::SetUpdateTimestampEnd(const Time& value) {
748 update_timestamp_end_ = value;
749 LOG(INFO) << "Update Timestamp End = "
750 << utils::ToString(update_timestamp_end_);
751}
752
753TimeDelta PayloadState::GetUpdateDurationUptime() {
754 return update_duration_uptime_;
755}
756
757void PayloadState::LoadUpdateDurationUptime() {
758 int64_t stored_value;
759 TimeDelta stored_delta;
760
761 CHECK(prefs_);
762
763 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
764 // The preference missing is not unexpected - in that case, just
765 // we'll use zero as the delta
766 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
767 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
768 stored_delta = TimeDelta::FromSeconds(0);
769 } else {
770 stored_delta = TimeDelta::FromInternalValue(stored_value);
771 }
772
773 // Sanity-check: Uptime can never be greater than the wall-clock
774 // difference (modulo some slack). If it is, report and reset
775 // to the wall-clock difference.
776 TimeDelta diff = GetUpdateDuration() - stored_delta;
777 if (diff < -kDurationSlack) {
778 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -0700779 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -0700780 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700781 << utils::FormatTimeDelta(diff)
782 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700783 stored_delta = update_duration_current_;
784 }
785
786 SetUpdateDurationUptime(stored_delta);
787}
788
Chris Sosabe45bef2013-04-09 18:25:12 -0700789void PayloadState::LoadNumReboots() {
790 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
791}
792
David Zeuthen9a017f22013-04-11 16:10:26 -0700793void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
794 const Time& timestamp,
795 bool use_logging) {
796 CHECK(prefs_);
797 update_duration_uptime_ = value;
798 update_duration_uptime_timestamp_ = timestamp;
799 prefs_->SetInt64(kPrefsUpdateDurationUptime,
800 update_duration_uptime_.ToInternalValue());
801 if (use_logging) {
802 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -0700803 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -0700804 }
805}
806
807void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -0700808 Time now = system_state_->clock()->GetMonotonicTime();
809 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -0700810}
811
812void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700813 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700814 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
815 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
816 // We're frequently called so avoid logging this write
817 SetUpdateDurationUptimeExtended(new_uptime, now, false);
818}
819
David Zeuthen674c3182013-04-18 14:05:20 -0700820void PayloadState::ReportDurationMetrics() {
821 TimeDelta duration = GetUpdateDuration();
822 TimeDelta duration_uptime = GetUpdateDurationUptime();
823 string metric;
824
825 metric = "Installer.UpdateDurationMinutes";
826 system_state_->metrics_lib()->SendToUMA(
827 metric,
828 static_cast<int>(duration.InMinutes()),
829 1, // min: 1 minute
830 365*24*60, // max: 1 year (approx)
831 kNumDefaultUmaBuckets);
832 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
833 << " for metric " << metric;
834
835 metric = "Installer.UpdateDurationUptimeMinutes";
836 system_state_->metrics_lib()->SendToUMA(
837 metric,
838 static_cast<int>(duration_uptime.InMinutes()),
839 1, // min: 1 minute
840 30*24*60, // max: 1 month (approx)
841 kNumDefaultUmaBuckets);
842 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
843 << " for metric " << metric;
844
845 prefs_->Delete(kPrefsUpdateTimestampStart);
846 prefs_->Delete(kPrefsUpdateDurationUptime);
847}
848
Jay Srinivasan19409b72013-04-12 19:23:36 -0700849string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
850 return prefix + "-from-" + utils::ToString(source);
851}
852
853void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
854 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
855 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
856}
857
858void PayloadState::SetCurrentBytesDownloaded(
859 DownloadSource source,
860 uint64_t current_bytes_downloaded,
861 bool log) {
862 CHECK(prefs_);
863
864 if (source >= kNumDownloadSources)
865 return;
866
867 // Update the in-memory value.
868 current_bytes_downloaded_[source] = current_bytes_downloaded;
869
870 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
871 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
872 LOG_IF(INFO, log) << "Current bytes downloaded for "
873 << utils::ToString(source) << " = "
874 << GetCurrentBytesDownloaded(source);
875}
876
877void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
878 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
879 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
880}
881
882void PayloadState::SetTotalBytesDownloaded(
883 DownloadSource source,
884 uint64_t total_bytes_downloaded,
885 bool log) {
886 CHECK(prefs_);
887
888 if (source >= kNumDownloadSources)
889 return;
890
891 // Update the in-memory value.
892 total_bytes_downloaded_[source] = total_bytes_downloaded;
893
894 // Persist.
895 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
896 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
897 LOG_IF(INFO, log) << "Total bytes downloaded for "
898 << utils::ToString(source) << " = "
899 << GetTotalBytesDownloaded(source);
900}
901
David Zeuthena573d6f2013-06-14 16:13:36 -0700902void PayloadState::LoadNumResponsesSeen() {
903 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
904}
905
906void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
907 CHECK(prefs_);
908 num_responses_seen_ = num_responses_seen;
909 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
910 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
911}
912
913void PayloadState::ReportUpdatesAbandonedCountMetric() {
914 string metric = "Installer.UpdatesAbandonedCount";
915 int value = num_responses_seen_ - 1;
916
917 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
918 system_state_->metrics_lib()->SendToUMA(
919 metric,
920 value,
921 0, // min value
922 100, // max value
923 kNumDefaultUmaBuckets);
924}
925
Jay Srinivasan53173b92013-05-17 17:13:01 -0700926void PayloadState::ComputeCandidateUrls() {
927 bool http_url_ok = false;
928
929 if (system_state_->IsOfficialBuild()) {
930 const policy::DevicePolicy* policy = system_state_->device_policy();
931 if (!(policy && policy->GetHttpDownloadsEnabled(&http_url_ok) &&
932 http_url_ok))
933 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
934 } else {
935 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
936 http_url_ok = true;
937 }
938
939 candidate_urls_.clear();
940 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
941 string candidate_url = response_.payload_urls[i];
942 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
943 continue;
944 candidate_urls_.push_back(candidate_url);
945 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
946 << ": " << candidate_url;
947 }
948
949 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
950 << "out of " << response_.payload_urls.size() << " URLs supplied";
951}
952
David Zeuthene4c58bf2013-06-18 17:26:50 -0700953void PayloadState::CreateSystemUpdatedMarkerFile() {
954 CHECK(prefs_);
955 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
956 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
957}
958
959void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
960 // Send |time_to_reboot| as a UMA stat.
961 string metric = "Installer.TimeToRebootMinutes";
962 system_state_->metrics_lib()->SendToUMA(metric,
963 time_to_reboot.InMinutes(),
964 0, // min: 0 minute
965 30*24*60, // max: 1 month (approx)
966 kNumDefaultUmaBuckets);
967 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
968 << " for metric " << metric;
969}
970
971void PayloadState::UpdateEngineStarted() {
972 // Figure out if we just booted into a new update
973 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
974 int64_t stored_value;
975 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
976 Time system_updated_at = Time::FromInternalValue(stored_value);
977 if (!system_updated_at.is_null()) {
978 TimeDelta time_to_reboot =
979 system_state_->clock()->GetWallclockTime() - system_updated_at;
980 if (time_to_reboot.ToInternalValue() < 0) {
981 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
982 << utils::ToString(system_updated_at);
983 } else {
984 BootedIntoUpdate(time_to_reboot);
985 }
986 }
987 }
988 prefs_->Delete(kPrefsSystemUpdatedMarker);
989 }
990}
991
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800992} // namespace chromeos_update_engine