blob: a933ea53c84cad2591c78d20d875cdf4d243c698 [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();
Chris Sosaaa18e162013-06-20 13:20:30 -070047 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080048 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080049 LoadPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080050 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080051 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070052 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080053 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070054 LoadUpdateTimestampStart();
55 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
56 // being called before it. Don't reorder.
57 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070058 for (int i = 0; i < kNumDownloadSources; i++) {
59 DownloadSource source = static_cast<DownloadSource>(i);
60 LoadCurrentBytesDownloaded(source);
61 LoadTotalBytesDownloaded(source);
62 }
Chris Sosabe45bef2013-04-09 18:25:12 -070063 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070064 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070065 LoadRollbackVersion();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080066 return true;
67}
68
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080069void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080070 // Always store the latest response.
71 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080072
Jay Srinivasan53173b92013-05-17 17:13:01 -070073 // Compute the candidate URLs first as they are used to calculate the
74 // response signature so that a change in enterprise policy for
75 // HTTP downloads being enabled or not could be honored as soon as the
76 // next update check happens.
77 ComputeCandidateUrls();
78
Jay Srinivasan08262882012-12-28 19:29:43 -080079 // Check if the "signature" of this response (i.e. the fields we care about)
80 // has changed.
81 string new_response_signature = CalculateResponseSignature();
82 bool has_response_changed = (response_signature_ != new_response_signature);
83
84 // If the response has changed, we should persist the new signature and
85 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080086 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -080087 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -070088 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -080089 SetResponseSignature(new_response_signature);
90 ResetPersistedState();
91 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080092 }
93
Jay Srinivasan08262882012-12-28 19:29:43 -080094 // This is the earliest point at which we can validate whether the URL index
95 // we loaded from the persisted state is a valid value. If the response
96 // hasn't changed but the URL index is invalid, it's indicative of some
97 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -070098 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -080099 LOG(INFO) << "Resetting all payload state as the url index seems to have "
100 "been tampered with";
101 ResetPersistedState();
102 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800103 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700104
105 // Update the current download source which depends on the latest value of
106 // the response.
107 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800108}
109
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800110void PayloadState::DownloadComplete() {
111 LOG(INFO) << "Payload downloaded successfully";
112 IncrementPayloadAttemptNumber();
113}
114
115void PayloadState::DownloadProgress(size_t count) {
116 if (count == 0)
117 return;
118
David Zeuthen9a017f22013-04-11 16:10:26 -0700119 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700120 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700121
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800122 // We've received non-zero bytes from a recent download operation. Since our
123 // URL failure count is meant to penalize a URL only for consecutive
124 // failures, downloading bytes successfully means we should reset the failure
125 // count (as we know at least that the URL is working). In future, we can
126 // design this to be more sophisticated to check for more intelligent failure
127 // patterns, but right now, even 1 byte downloaded will mark the URL to be
128 // good unless it hits 10 (or configured number of) consecutive failures
129 // again.
130
131 if (GetUrlFailureCount() == 0)
132 return;
133
134 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
135 << " to 0 as we received " << count << " bytes successfully";
136 SetUrlFailureCount(0);
137}
138
Chris Sosabe45bef2013-04-09 18:25:12 -0700139void PayloadState::UpdateResumed() {
140 LOG(INFO) << "Resuming an update that was previously started.";
141 UpdateNumReboots();
142}
143
Jay Srinivasan19409b72013-04-12 19:23:36 -0700144void PayloadState::UpdateRestarted() {
145 LOG(INFO) << "Starting a new update";
146 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700147 SetNumReboots(0);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700148}
149
David Zeuthen9a017f22013-04-11 16:10:26 -0700150void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700151 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700152 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700153 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
Jay Srinivasan19409b72013-04-12 19:23:36 -0700154 ReportBytesDownloadedMetrics();
David Zeuthencc6f9962013-04-18 11:57:24 -0700155 ReportUpdateUrlSwitchesMetric();
Chris Sosabe45bef2013-04-09 18:25:12 -0700156 ReportRebootMetrics();
David Zeuthen674c3182013-04-18 14:05:20 -0700157 ReportDurationMetrics();
David Zeuthena573d6f2013-06-14 16:13:36 -0700158 ReportUpdatesAbandonedCountMetric();
Alex Deymo1c656c42013-06-28 11:02:14 -0700159 ReportPayloadTypeMetric();
David Zeuthena573d6f2013-06-14 16:13:36 -0700160
161 // Reset the number of responses seen since it counts from the last
162 // successful update, e.g. now.
163 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700164
165 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700166}
167
David Zeuthena99981f2013-04-29 13:42:47 -0700168void PayloadState::UpdateFailed(ErrorCode error) {
169 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800170 LOG(INFO) << "Updating payload state for error code: " << base_error
171 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800172
Jay Srinivasan53173b92013-05-17 17:13:01 -0700173 if (candidate_urls_.size() == 0) {
174 // This means we got this error even before we got a valid Omaha response
175 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800176 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800177 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
178 return;
179 }
180
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800181 switch (base_error) {
182 // Errors which are good indicators of a problem with a particular URL or
183 // the protocol used in the URL or entities in the communication channel
184 // (e.g. proxies). We should try the next available URL in the next update
185 // check to quickly recover from these errors.
David Zeuthena99981f2013-04-29 13:42:47 -0700186 case kErrorCodePayloadHashMismatchError:
187 case kErrorCodePayloadSizeMismatchError:
188 case kErrorCodeDownloadPayloadVerificationError:
189 case kErrorCodeDownloadPayloadPubKeyVerificationError:
190 case kErrorCodeSignedDeltaPayloadExpectedError:
191 case kErrorCodeDownloadInvalidMetadataMagicString:
192 case kErrorCodeDownloadSignatureMissingInManifest:
193 case kErrorCodeDownloadManifestParseError:
194 case kErrorCodeDownloadMetadataSignatureError:
195 case kErrorCodeDownloadMetadataSignatureVerificationError:
196 case kErrorCodeDownloadMetadataSignatureMismatch:
197 case kErrorCodeDownloadOperationHashVerificationError:
198 case kErrorCodeDownloadOperationExecutionError:
199 case kErrorCodeDownloadOperationHashMismatch:
200 case kErrorCodeDownloadInvalidMetadataSize:
201 case kErrorCodeDownloadInvalidMetadataSignature:
202 case kErrorCodeDownloadOperationHashMissingError:
203 case kErrorCodeDownloadMetadataSignatureMissingError:
Gilad Arnold21504f02013-05-24 08:51:22 -0700204 case kErrorCodePayloadMismatchedType:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800205 IncrementUrlIndex();
206 break;
207
208 // Errors which seem to be just transient network/communication related
209 // failures and do not indicate any inherent problem with the URL itself.
210 // So, we should keep the current URL but just increment the
211 // failure count to give it more chances. This way, while we maximize our
212 // chances of downloading from the URLs that appear earlier in the response
213 // (because download from a local server URL that appears earlier in a
214 // response is preferable than downloading from the next URL which could be
215 // a internet URL and thus could be more expensive).
David Zeuthena99981f2013-04-29 13:42:47 -0700216 case kErrorCodeError:
217 case kErrorCodeDownloadTransferError:
218 case kErrorCodeDownloadWriteError:
219 case kErrorCodeDownloadStateInitializationError:
220 case kErrorCodeOmahaErrorInHTTPResponse: // Aggregate code for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800221 IncrementFailureCount();
222 break;
223
224 // Errors which are not specific to a URL and hence shouldn't result in
225 // the URL being penalized. This can happen in two cases:
226 // 1. We haven't started downloading anything: These errors don't cost us
227 // anything in terms of actual payload bytes, so we should just do the
228 // regular retries at the next update check.
229 // 2. We have successfully downloaded the payload: In this case, the
230 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800231 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800232 // In either case, there's no need to update URL index or failure count.
David Zeuthena99981f2013-04-29 13:42:47 -0700233 case kErrorCodeOmahaRequestError:
234 case kErrorCodeOmahaResponseHandlerError:
235 case kErrorCodePostinstallRunnerError:
236 case kErrorCodeFilesystemCopierError:
237 case kErrorCodeInstallDeviceOpenError:
238 case kErrorCodeKernelDeviceOpenError:
239 case kErrorCodeDownloadNewPartitionInfoError:
240 case kErrorCodeNewRootfsVerificationError:
241 case kErrorCodeNewKernelVerificationError:
242 case kErrorCodePostinstallBootedFromFirmwareB:
243 case kErrorCodeOmahaRequestEmptyResponseError:
244 case kErrorCodeOmahaRequestXMLParseError:
245 case kErrorCodeOmahaResponseInvalid:
246 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
247 case kErrorCodeOmahaUpdateDeferredPerPolicy:
248 case kErrorCodeOmahaUpdateDeferredForBackoff:
249 case kErrorCodePostinstallPowerwashError:
250 case kErrorCodeUpdateCanceledByChannelChange:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800251 LOG(INFO) << "Not incrementing URL index or failure count for this error";
252 break;
253
David Zeuthena99981f2013-04-29 13:42:47 -0700254 case kErrorCodeSuccess: // success code
David Zeuthena99981f2013-04-29 13:42:47 -0700255 case kErrorCodeUmaReportedMax: // not an error code
256 case kErrorCodeOmahaRequestHTTPResponseBase: // aggregated already
257 case kErrorCodeDevModeFlag: // not an error code
258 case kErrorCodeResumedFlag: // not an error code
259 case kErrorCodeTestImageFlag: // not an error code
260 case kErrorCodeTestOmahaUrlFlag: // not an error code
261 case kErrorCodeSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800262 // These shouldn't happen. Enumerating these explicitly here so that we
263 // can let the compiler warn about new error codes that are added to
264 // action_processor.h but not added here.
265 LOG(WARNING) << "Unexpected error code for UpdateFailed";
266 break;
267
268 // Note: Not adding a default here so as to let the compiler warn us of
269 // any new enums that were added in the .h but not listed in this switch.
270 }
271}
272
Jay Srinivasan08262882012-12-28 19:29:43 -0800273bool PayloadState::ShouldBackoffDownload() {
274 if (response_.disable_payload_backoff) {
275 LOG(INFO) << "Payload backoff logic is disabled. "
276 "Can proceed with the download";
277 return false;
278 }
279
280 if (response_.is_delta_payload) {
281 // If delta payloads fail, we want to fallback quickly to full payloads as
282 // they are more likely to succeed. Exponential backoffs would greatly
283 // slow down the fallback to full payloads. So we don't backoff for delta
284 // payloads.
285 LOG(INFO) << "No backoffs for delta payloads. "
286 << "Can proceed with the download";
287 return false;
288 }
289
290 if (!utils::IsOfficialBuild()) {
291 // Backoffs are needed only for official builds. We do not want any delays
292 // or update failures due to backoffs during testing or development.
293 LOG(INFO) << "No backoffs for test/dev images. "
294 << "Can proceed with the download";
295 return false;
296 }
297
298 if (backoff_expiry_time_.is_null()) {
299 LOG(INFO) << "No backoff expiry time has been set. "
300 << "Can proceed with the download";
301 return false;
302 }
303
304 if (backoff_expiry_time_ < Time::Now()) {
305 LOG(INFO) << "The backoff expiry time ("
306 << utils::ToString(backoff_expiry_time_)
307 << ") has elapsed. Can proceed with the download";
308 return false;
309 }
310
311 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
312 << utils::ToString(backoff_expiry_time_);
313 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800314}
315
Chris Sosaaa18e162013-06-20 13:20:30 -0700316void PayloadState::Rollback() {
317 SetRollbackVersion(system_state_->request_params()->app_version());
318}
319
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800320void PayloadState::IncrementPayloadAttemptNumber() {
Jay Srinivasan08262882012-12-28 19:29:43 -0800321 if (response_.is_delta_payload) {
322 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
323 return;
324 }
325
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800326 LOG(INFO) << "Incrementing the payload attempt number";
327 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800328 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800329}
330
331void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800332 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700333 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800334 LOG(INFO) << "Incrementing the URL index for next attempt";
335 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800336 } else {
337 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700338 << "0 as we only have " << candidate_urls_.size()
339 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800340 SetUrlIndex(0);
341 IncrementPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800342 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800343
David Zeuthencc6f9962013-04-18 11:57:24 -0700344 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700345 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700346 SetUrlSwitchCount(url_switch_count_ + 1);
347
Jay Srinivasan08262882012-12-28 19:29:43 -0800348 // Whenever we update the URL index, we should also clear the URL failure
349 // count so we can start over fresh for the new URL.
350 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800351}
352
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800353void PayloadState::IncrementFailureCount() {
354 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800355 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800356 LOG(INFO) << "Incrementing the URL failure count";
357 SetUrlFailureCount(next_url_failure_count);
358 } else {
359 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
360 << ". Trying next available URL";
361 IncrementUrlIndex();
362 }
363}
364
Jay Srinivasan08262882012-12-28 19:29:43 -0800365void PayloadState::UpdateBackoffExpiryTime() {
366 if (response_.disable_payload_backoff) {
367 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
368 SetBackoffExpiryTime(Time());
369 return;
370 }
371
372 if (GetPayloadAttemptNumber() == 0) {
373 SetBackoffExpiryTime(Time());
374 return;
375 }
376
377 // Since we're doing left-shift below, make sure we don't shift more
378 // than this. E.g. if uint32_t is 4-bytes, don't left-shift more than 30 bits,
379 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
380 uint32_t num_days = 1; // the value to be shifted.
381 const uint32_t kMaxShifts = (sizeof(num_days) * 8) - 2;
382
383 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
384 // E.g. if payload_attempt_number is over 30, limit power to 30.
385 uint32_t power = min(GetPayloadAttemptNumber() - 1, kMaxShifts);
386
387 // The number of days is the minimum of 2 raised to (payload_attempt_number
388 // - 1) or kMaxBackoffDays.
389 num_days = min(num_days << power, kMaxBackoffDays);
390
391 // We don't want all retries to happen exactly at the same time when
392 // retrying after backoff. So add some random minutes to fuzz.
393 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
394 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
395 TimeDelta::FromMinutes(fuzz_minutes);
396 LOG(INFO) << "Incrementing the backoff expiry time by "
397 << utils::FormatTimeDelta(next_backoff_interval);
398 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
399}
400
Jay Srinivasan19409b72013-04-12 19:23:36 -0700401void PayloadState::UpdateCurrentDownloadSource() {
402 current_download_source_ = kNumDownloadSources;
403
Jay Srinivasan53173b92013-05-17 17:13:01 -0700404 if (GetUrlIndex() < candidate_urls_.size()) {
405 string current_url = candidate_urls_[GetUrlIndex()];
Jay Srinivasan19409b72013-04-12 19:23:36 -0700406 if (StartsWithASCII(current_url, "https://", false))
407 current_download_source_ = kDownloadSourceHttpsServer;
408 else if (StartsWithASCII(current_url, "http://", false))
409 current_download_source_ = kDownloadSourceHttpServer;
410 }
411
412 LOG(INFO) << "Current download source: "
413 << utils::ToString(current_download_source_);
414}
415
416void PayloadState::UpdateBytesDownloaded(size_t count) {
417 SetCurrentBytesDownloaded(
418 current_download_source_,
419 GetCurrentBytesDownloaded(current_download_source_) + count,
420 false);
421 SetTotalBytesDownloaded(
422 current_download_source_,
423 GetTotalBytesDownloaded(current_download_source_) + count,
424 false);
425}
426
427void PayloadState::ReportBytesDownloadedMetrics() {
428 // Report metrics collected from all known download sources to UMA.
429 // The reported data is in Megabytes in order to represent a larger
430 // sample range.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700431 int download_sources_used = 0;
432 string metric;
433 uint64_t successful_mbs = 0;
434 uint64_t total_mbs = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700435 for (int i = 0; i < kNumDownloadSources; i++) {
436 DownloadSource source = static_cast<DownloadSource>(i);
437 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
David Zeuthen44848602013-06-24 13:32:14 -0700438 uint64_t mbs;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700439
David Zeuthen44848602013-06-24 13:32:14 -0700440 // Only consider this download source (and send byte counts) as
441 // having been used if we downloaded a non-trivial amount of bytes
442 // (e.g. at least 1 MiB) that contributed to the final success of
443 // the update. Otherwise we're going to end up with a lot of
444 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700445
David Zeuthen44848602013-06-24 13:32:14 -0700446 mbs = GetCurrentBytesDownloaded(source) / kNumBytesInOneMiB;
447 if (mbs > 0) {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700448 download_sources_used |= (1 << source);
449
David Zeuthen44848602013-06-24 13:32:14 -0700450 metric = "Installer.SuccessfulMBsDownloadedFrom" +
451 utils::ToString(source);
452 successful_mbs += mbs;
453 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
454 system_state_->metrics_lib()->SendToUMA(metric,
455 mbs,
456 0, // min
457 kMaxMiBs,
458 kNumDefaultUmaBuckets);
459 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700460 SetCurrentBytesDownloaded(source, 0, true);
461
Jay Srinivasan19409b72013-04-12 19:23:36 -0700462 mbs = GetTotalBytesDownloaded(source) / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700463 if (mbs > 0) {
464 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
465 total_mbs += mbs;
466 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
467 system_state_->metrics_lib()->SendToUMA(metric,
468 mbs,
469 0, // min
470 kMaxMiBs,
471 kNumDefaultUmaBuckets);
472 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700473 SetTotalBytesDownloaded(source, 0, true);
474 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700475
476 metric = "Installer.DownloadSourcesUsed";
477 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
478 << " (bit flags) for metric " << metric;
479 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
480 system_state_->metrics_lib()->SendToUMA(metric,
481 download_sources_used,
482 0, // min
483 1 << kNumDownloadSources,
484 num_buckets);
485
486 if (successful_mbs) {
487 metric = "Installer.DownloadOverheadPercentage";
488 int percent_overhead = (total_mbs - successful_mbs) * 100 / successful_mbs;
489 LOG(INFO) << "Uploading " << percent_overhead << "% for metric " << metric;
490 system_state_->metrics_lib()->SendToUMA(metric,
491 percent_overhead,
492 0, // min: 0% overhead
493 1000, // max: 1000% overhead
494 kNumDefaultUmaBuckets);
495 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700496}
497
David Zeuthencc6f9962013-04-18 11:57:24 -0700498void PayloadState::ReportUpdateUrlSwitchesMetric() {
499 string metric = "Installer.UpdateURLSwitches";
500 int value = static_cast<int>(url_switch_count_);
501
502 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
503 system_state_->metrics_lib()->SendToUMA(
504 metric,
505 value,
506 0, // min value
507 100, // max value
508 kNumDefaultUmaBuckets);
509}
510
Chris Sosabe45bef2013-04-09 18:25:12 -0700511void PayloadState::ReportRebootMetrics() {
512 // Report the number of num_reboots.
513 string metric = "Installer.UpdateNumReboots";
514 uint32_t num_reboots = GetNumReboots();
515 LOG(INFO) << "Uploading reboot count of " << num_reboots << " for metric "
516 << metric;
517 system_state_->metrics_lib()->SendToUMA(
518 metric,
519 static_cast<int>(num_reboots), // sample
520 0, // min = 0.
521 50, // max
522 25); // buckets
523 SetNumReboots(0);
524}
525
526void PayloadState::UpdateNumReboots() {
527 // We only update the reboot count when the system has been detected to have
528 // been rebooted.
529 if (!system_state_->system_rebooted()) {
530 return;
531 }
532
533 SetNumReboots(GetNumReboots() + 1);
534}
535
536void PayloadState::SetNumReboots(uint32_t num_reboots) {
537 CHECK(prefs_);
538 num_reboots_ = num_reboots;
539 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
540 LOG(INFO) << "Number of Reboots during current update attempt = "
541 << num_reboots_;
542}
543
Jay Srinivasan08262882012-12-28 19:29:43 -0800544void PayloadState::ResetPersistedState() {
545 SetPayloadAttemptNumber(0);
546 SetUrlIndex(0);
547 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700548 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800549 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700550 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
David Zeuthen9a017f22013-04-11 16:10:26 -0700551 SetUpdateTimestampEnd(Time()); // Set to null time
552 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700553 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700554 ResetRollbackVersion();
555}
556
557void PayloadState::ResetRollbackVersion() {
558 CHECK(powerwash_safe_prefs_);
559 rollback_version_ = "";
560 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700561}
562
563void PayloadState::ResetDownloadSourcesOnNewUpdate() {
564 for (int i = 0; i < kNumDownloadSources; i++) {
565 DownloadSource source = static_cast<DownloadSource>(i);
566 SetCurrentBytesDownloaded(source, 0, true);
567 // Note: Not resetting the TotalBytesDownloaded as we want that metric
568 // to count the bytes downloaded across various update attempts until
569 // we have successfully applied the update.
570 }
571}
572
Chris Sosaaa18e162013-06-20 13:20:30 -0700573int64_t PayloadState::GetPersistedValue(const string& key,
574 bool across_powerwash) {
575 PrefsInterface* prefs = prefs_;
576 if (across_powerwash)
577 prefs = powerwash_safe_prefs_;
578
Jay Srinivasan19409b72013-04-12 19:23:36 -0700579 CHECK(prefs_);
Chris Sosaaa18e162013-06-20 13:20:30 -0700580 if (!prefs->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700581 return 0;
582
583 int64_t stored_value;
Chris Sosaaa18e162013-06-20 13:20:30 -0700584 if (!prefs->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700585 return 0;
586
587 if (stored_value < 0) {
588 LOG(ERROR) << key << ": Invalid value (" << stored_value
589 << ") in persisted state. Defaulting to 0";
590 return 0;
591 }
592
593 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800594}
595
596string PayloadState::CalculateResponseSignature() {
597 string response_sign = StringPrintf("NumURLs = %d\n",
Jay Srinivasan53173b92013-05-17 17:13:01 -0700598 candidate_urls_.size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800599
Jay Srinivasan53173b92013-05-17 17:13:01 -0700600 for (size_t i = 0; i < candidate_urls_.size(); i++)
601 response_sign += StringPrintf("Candidate Url%d = %s\n",
602 i, candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800603
604 response_sign += StringPrintf("Payload Size = %llu\n"
605 "Payload Sha256 Hash = %s\n"
606 "Metadata Size = %llu\n"
607 "Metadata Signature = %s\n"
608 "Is Delta Payload = %d\n"
609 "Max Failure Count Per Url = %d\n"
610 "Disable Payload Backoff = %d\n",
611 response_.size,
612 response_.hash.c_str(),
613 response_.metadata_size,
614 response_.metadata_signature.c_str(),
615 response_.is_delta_payload,
616 response_.max_failure_count_per_url,
617 response_.disable_payload_backoff);
618 return response_sign;
619}
620
621void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800622 CHECK(prefs_);
623 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800624 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
625 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
626 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800627 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800628}
629
Jay Srinivasan19409b72013-04-12 19:23:36 -0700630void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800631 CHECK(prefs_);
632 response_signature_ = response_signature;
633 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
634 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
635}
636
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800637void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700638 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber,
639 false));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800640}
641
642void PayloadState::SetPayloadAttemptNumber(uint32_t payload_attempt_number) {
643 CHECK(prefs_);
644 payload_attempt_number_ = payload_attempt_number;
645 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
646 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
647}
648
649void PayloadState::LoadUrlIndex() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700650 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex, false));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800651}
652
653void PayloadState::SetUrlIndex(uint32_t url_index) {
654 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800655 url_index_ = url_index;
656 LOG(INFO) << "Current URL Index = " << url_index_;
657 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700658
659 // Also update the download source, which is purely dependent on the
660 // current URL index alone.
661 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800662}
663
David Zeuthencc6f9962013-04-18 11:57:24 -0700664void PayloadState::LoadUrlSwitchCount() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700665 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount, false));
David Zeuthencc6f9962013-04-18 11:57:24 -0700666}
667
668void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
669 CHECK(prefs_);
670 url_switch_count_ = url_switch_count;
671 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
672 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
673}
674
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800675void PayloadState::LoadUrlFailureCount() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700676 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount,
677 false));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800678}
679
680void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
681 CHECK(prefs_);
682 url_failure_count_ = url_failure_count;
683 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
684 << ")'s Failure Count = " << url_failure_count_;
685 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800686}
687
Jay Srinivasan08262882012-12-28 19:29:43 -0800688void PayloadState::LoadBackoffExpiryTime() {
689 CHECK(prefs_);
690 int64_t stored_value;
691 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
692 return;
693
694 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
695 return;
696
697 Time stored_time = Time::FromInternalValue(stored_value);
698 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
699 LOG(ERROR) << "Invalid backoff expiry time ("
700 << utils::ToString(stored_time)
701 << ") in persisted state. Resetting.";
702 stored_time = Time();
703 }
704 SetBackoffExpiryTime(stored_time);
705}
706
707void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
708 CHECK(prefs_);
709 backoff_expiry_time_ = new_time;
710 LOG(INFO) << "Backoff Expiry Time = "
711 << utils::ToString(backoff_expiry_time_);
712 prefs_->SetInt64(kPrefsBackoffExpiryTime,
713 backoff_expiry_time_.ToInternalValue());
714}
715
David Zeuthen9a017f22013-04-11 16:10:26 -0700716TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700717 Time end_time = update_timestamp_end_.is_null()
718 ? system_state_->clock()->GetWallclockTime() :
719 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700720 return end_time - update_timestamp_start_;
721}
722
723void PayloadState::LoadUpdateTimestampStart() {
724 int64_t stored_value;
725 Time stored_time;
726
727 CHECK(prefs_);
728
David Zeuthenf413fe52013-04-22 14:04:39 -0700729 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700730
731 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
732 // The preference missing is not unexpected - in that case, just
733 // use the current time as start time
734 stored_time = now;
735 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
736 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
737 stored_time = now;
738 } else {
739 stored_time = Time::FromInternalValue(stored_value);
740 }
741
742 // Sanity check: If the time read from disk is in the future
743 // (modulo some slack to account for possible NTP drift
744 // adjustments), something is fishy and we should report and
745 // reset.
746 TimeDelta duration_according_to_stored_time = now - stored_time;
747 if (duration_according_to_stored_time < -kDurationSlack) {
748 LOG(ERROR) << "The UpdateTimestampStart value ("
749 << utils::ToString(stored_time)
750 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700751 << utils::FormatTimeDelta(duration_according_to_stored_time)
752 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700753 stored_time = now;
754 }
755
756 SetUpdateTimestampStart(stored_time);
757}
758
759void PayloadState::SetUpdateTimestampStart(const Time& value) {
760 CHECK(prefs_);
761 update_timestamp_start_ = value;
762 prefs_->SetInt64(kPrefsUpdateTimestampStart,
763 update_timestamp_start_.ToInternalValue());
764 LOG(INFO) << "Update Timestamp Start = "
765 << utils::ToString(update_timestamp_start_);
766}
767
768void PayloadState::SetUpdateTimestampEnd(const Time& value) {
769 update_timestamp_end_ = value;
770 LOG(INFO) << "Update Timestamp End = "
771 << utils::ToString(update_timestamp_end_);
772}
773
774TimeDelta PayloadState::GetUpdateDurationUptime() {
775 return update_duration_uptime_;
776}
777
778void PayloadState::LoadUpdateDurationUptime() {
779 int64_t stored_value;
780 TimeDelta stored_delta;
781
782 CHECK(prefs_);
783
784 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
785 // The preference missing is not unexpected - in that case, just
786 // we'll use zero as the delta
787 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
788 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
789 stored_delta = TimeDelta::FromSeconds(0);
790 } else {
791 stored_delta = TimeDelta::FromInternalValue(stored_value);
792 }
793
794 // Sanity-check: Uptime can never be greater than the wall-clock
795 // difference (modulo some slack). If it is, report and reset
796 // to the wall-clock difference.
797 TimeDelta diff = GetUpdateDuration() - stored_delta;
798 if (diff < -kDurationSlack) {
799 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -0700800 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -0700801 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700802 << utils::FormatTimeDelta(diff)
803 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700804 stored_delta = update_duration_current_;
805 }
806
807 SetUpdateDurationUptime(stored_delta);
808}
809
Chris Sosabe45bef2013-04-09 18:25:12 -0700810void PayloadState::LoadNumReboots() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700811 SetNumReboots(GetPersistedValue(kPrefsNumReboots, false));
812}
813
814void PayloadState::LoadRollbackVersion() {
815 SetNumReboots(GetPersistedValue(kPrefsRollbackVersion, true));
816}
817
818void PayloadState::SetRollbackVersion(const string& rollback_version) {
819 CHECK(powerwash_safe_prefs_);
820 LOG(INFO) << "Blacklisting version "<< rollback_version;
821 rollback_version_ = rollback_version;
822 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -0700823}
824
David Zeuthen9a017f22013-04-11 16:10:26 -0700825void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
826 const Time& timestamp,
827 bool use_logging) {
828 CHECK(prefs_);
829 update_duration_uptime_ = value;
830 update_duration_uptime_timestamp_ = timestamp;
831 prefs_->SetInt64(kPrefsUpdateDurationUptime,
832 update_duration_uptime_.ToInternalValue());
833 if (use_logging) {
834 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -0700835 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -0700836 }
837}
838
839void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -0700840 Time now = system_state_->clock()->GetMonotonicTime();
841 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -0700842}
843
844void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700845 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700846 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
847 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
848 // We're frequently called so avoid logging this write
849 SetUpdateDurationUptimeExtended(new_uptime, now, false);
850}
851
David Zeuthen674c3182013-04-18 14:05:20 -0700852void PayloadState::ReportDurationMetrics() {
853 TimeDelta duration = GetUpdateDuration();
854 TimeDelta duration_uptime = GetUpdateDurationUptime();
855 string metric;
856
857 metric = "Installer.UpdateDurationMinutes";
858 system_state_->metrics_lib()->SendToUMA(
859 metric,
860 static_cast<int>(duration.InMinutes()),
861 1, // min: 1 minute
862 365*24*60, // max: 1 year (approx)
863 kNumDefaultUmaBuckets);
864 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
865 << " for metric " << metric;
866
867 metric = "Installer.UpdateDurationUptimeMinutes";
868 system_state_->metrics_lib()->SendToUMA(
869 metric,
870 static_cast<int>(duration_uptime.InMinutes()),
871 1, // min: 1 minute
872 30*24*60, // max: 1 month (approx)
873 kNumDefaultUmaBuckets);
874 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
875 << " for metric " << metric;
876
877 prefs_->Delete(kPrefsUpdateTimestampStart);
878 prefs_->Delete(kPrefsUpdateDurationUptime);
879}
880
Alex Deymo1c656c42013-06-28 11:02:14 -0700881void PayloadState::ReportPayloadTypeMetric() {
882 string metric;
883 PayloadType uma_payload_type;
884 OmahaRequestParams* params = system_state_->request_params();
885
886 if (response_.is_delta_payload) {
887 uma_payload_type = kPayloadTypeDelta;
888 } else if (params->delta_okay()) {
889 uma_payload_type = kPayloadTypeFull;
890 } else { // Full payload, delta was not allowed by request.
891 uma_payload_type = kPayloadTypeForcedFull;
892 }
893
894 metric = "Installer.PayloadFormat";
895 system_state_->metrics_lib()->SendEnumToUMA(
896 metric,
897 uma_payload_type,
898 kNumPayloadTypes);
899 LOG(INFO) << "Uploading " << utils::ToString(uma_payload_type)
900 << " for metric " << metric;
901}
902
Jay Srinivasan19409b72013-04-12 19:23:36 -0700903string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
904 return prefix + "-from-" + utils::ToString(source);
905}
906
907void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
908 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosaaa18e162013-06-20 13:20:30 -0700909 SetCurrentBytesDownloaded(source, GetPersistedValue(key, false), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700910}
911
912void PayloadState::SetCurrentBytesDownloaded(
913 DownloadSource source,
914 uint64_t current_bytes_downloaded,
915 bool log) {
916 CHECK(prefs_);
917
918 if (source >= kNumDownloadSources)
919 return;
920
921 // Update the in-memory value.
922 current_bytes_downloaded_[source] = current_bytes_downloaded;
923
924 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
925 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
926 LOG_IF(INFO, log) << "Current bytes downloaded for "
927 << utils::ToString(source) << " = "
928 << GetCurrentBytesDownloaded(source);
929}
930
931void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
932 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosaaa18e162013-06-20 13:20:30 -0700933 SetTotalBytesDownloaded(source, GetPersistedValue(key, false), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700934}
935
936void PayloadState::SetTotalBytesDownloaded(
937 DownloadSource source,
938 uint64_t total_bytes_downloaded,
939 bool log) {
940 CHECK(prefs_);
941
942 if (source >= kNumDownloadSources)
943 return;
944
945 // Update the in-memory value.
946 total_bytes_downloaded_[source] = total_bytes_downloaded;
947
948 // Persist.
949 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
950 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
951 LOG_IF(INFO, log) << "Total bytes downloaded for "
952 << utils::ToString(source) << " = "
953 << GetTotalBytesDownloaded(source);
954}
955
David Zeuthena573d6f2013-06-14 16:13:36 -0700956void PayloadState::LoadNumResponsesSeen() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700957 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen, false));
David Zeuthena573d6f2013-06-14 16:13:36 -0700958}
959
960void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
961 CHECK(prefs_);
962 num_responses_seen_ = num_responses_seen;
963 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
964 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
965}
966
967void PayloadState::ReportUpdatesAbandonedCountMetric() {
968 string metric = "Installer.UpdatesAbandonedCount";
969 int value = num_responses_seen_ - 1;
970
971 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
972 system_state_->metrics_lib()->SendToUMA(
973 metric,
974 value,
975 0, // min value
976 100, // max value
977 kNumDefaultUmaBuckets);
978}
979
Jay Srinivasan53173b92013-05-17 17:13:01 -0700980void PayloadState::ComputeCandidateUrls() {
981 bool http_url_ok = false;
982
983 if (system_state_->IsOfficialBuild()) {
984 const policy::DevicePolicy* policy = system_state_->device_policy();
985 if (!(policy && policy->GetHttpDownloadsEnabled(&http_url_ok) &&
986 http_url_ok))
987 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
988 } else {
989 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
990 http_url_ok = true;
991 }
992
993 candidate_urls_.clear();
994 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
995 string candidate_url = response_.payload_urls[i];
996 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
997 continue;
998 candidate_urls_.push_back(candidate_url);
999 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1000 << ": " << candidate_url;
1001 }
1002
1003 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1004 << "out of " << response_.payload_urls.size() << " URLs supplied";
1005}
1006
David Zeuthene4c58bf2013-06-18 17:26:50 -07001007void PayloadState::CreateSystemUpdatedMarkerFile() {
1008 CHECK(prefs_);
1009 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1010 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1011}
1012
1013void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1014 // Send |time_to_reboot| as a UMA stat.
1015 string metric = "Installer.TimeToRebootMinutes";
1016 system_state_->metrics_lib()->SendToUMA(metric,
1017 time_to_reboot.InMinutes(),
1018 0, // min: 0 minute
1019 30*24*60, // max: 1 month (approx)
1020 kNumDefaultUmaBuckets);
1021 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1022 << " for metric " << metric;
1023}
1024
1025void PayloadState::UpdateEngineStarted() {
1026 // Figure out if we just booted into a new update
1027 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1028 int64_t stored_value;
1029 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1030 Time system_updated_at = Time::FromInternalValue(stored_value);
1031 if (!system_updated_at.is_null()) {
1032 TimeDelta time_to_reboot =
1033 system_state_->clock()->GetWallclockTime() - system_updated_at;
1034 if (time_to_reboot.ToInternalValue() < 0) {
1035 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1036 << utils::ToString(system_updated_at);
1037 } else {
1038 BootedIntoUpdate(time_to_reboot);
1039 }
1040 }
1041 }
1042 prefs_->Delete(kPrefsSystemUpdatedMarker);
1043 }
1044}
1045
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001046} // namespace chromeos_update_engine