blob: 20e2cacbec59378c413b1400e1310889e08262a2 [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();
159
160 // Reset the number of responses seen since it counts from the last
161 // successful update, e.g. now.
162 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700163
164 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700165}
166
David Zeuthena99981f2013-04-29 13:42:47 -0700167void PayloadState::UpdateFailed(ErrorCode error) {
168 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800169 LOG(INFO) << "Updating payload state for error code: " << base_error
170 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800171
Jay Srinivasan53173b92013-05-17 17:13:01 -0700172 if (candidate_urls_.size() == 0) {
173 // This means we got this error even before we got a valid Omaha response
174 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800175 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800176 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
177 return;
178 }
179
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800180 switch (base_error) {
181 // Errors which are good indicators of a problem with a particular URL or
182 // the protocol used in the URL or entities in the communication channel
183 // (e.g. proxies). We should try the next available URL in the next update
184 // check to quickly recover from these errors.
David Zeuthena99981f2013-04-29 13:42:47 -0700185 case kErrorCodePayloadHashMismatchError:
186 case kErrorCodePayloadSizeMismatchError:
187 case kErrorCodeDownloadPayloadVerificationError:
188 case kErrorCodeDownloadPayloadPubKeyVerificationError:
189 case kErrorCodeSignedDeltaPayloadExpectedError:
190 case kErrorCodeDownloadInvalidMetadataMagicString:
191 case kErrorCodeDownloadSignatureMissingInManifest:
192 case kErrorCodeDownloadManifestParseError:
193 case kErrorCodeDownloadMetadataSignatureError:
194 case kErrorCodeDownloadMetadataSignatureVerificationError:
195 case kErrorCodeDownloadMetadataSignatureMismatch:
196 case kErrorCodeDownloadOperationHashVerificationError:
197 case kErrorCodeDownloadOperationExecutionError:
198 case kErrorCodeDownloadOperationHashMismatch:
199 case kErrorCodeDownloadInvalidMetadataSize:
200 case kErrorCodeDownloadInvalidMetadataSignature:
201 case kErrorCodeDownloadOperationHashMissingError:
202 case kErrorCodeDownloadMetadataSignatureMissingError:
Gilad Arnold21504f02013-05-24 08:51:22 -0700203 case kErrorCodePayloadMismatchedType:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800204 IncrementUrlIndex();
205 break;
206
207 // Errors which seem to be just transient network/communication related
208 // failures and do not indicate any inherent problem with the URL itself.
209 // So, we should keep the current URL but just increment the
210 // failure count to give it more chances. This way, while we maximize our
211 // chances of downloading from the URLs that appear earlier in the response
212 // (because download from a local server URL that appears earlier in a
213 // response is preferable than downloading from the next URL which could be
214 // a internet URL and thus could be more expensive).
David Zeuthena99981f2013-04-29 13:42:47 -0700215 case kErrorCodeError:
216 case kErrorCodeDownloadTransferError:
217 case kErrorCodeDownloadWriteError:
218 case kErrorCodeDownloadStateInitializationError:
219 case kErrorCodeOmahaErrorInHTTPResponse: // Aggregate code for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800220 IncrementFailureCount();
221 break;
222
223 // Errors which are not specific to a URL and hence shouldn't result in
224 // the URL being penalized. This can happen in two cases:
225 // 1. We haven't started downloading anything: These errors don't cost us
226 // anything in terms of actual payload bytes, so we should just do the
227 // regular retries at the next update check.
228 // 2. We have successfully downloaded the payload: In this case, the
229 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800230 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800231 // In either case, there's no need to update URL index or failure count.
David Zeuthena99981f2013-04-29 13:42:47 -0700232 case kErrorCodeOmahaRequestError:
233 case kErrorCodeOmahaResponseHandlerError:
234 case kErrorCodePostinstallRunnerError:
235 case kErrorCodeFilesystemCopierError:
236 case kErrorCodeInstallDeviceOpenError:
237 case kErrorCodeKernelDeviceOpenError:
238 case kErrorCodeDownloadNewPartitionInfoError:
239 case kErrorCodeNewRootfsVerificationError:
240 case kErrorCodeNewKernelVerificationError:
241 case kErrorCodePostinstallBootedFromFirmwareB:
242 case kErrorCodeOmahaRequestEmptyResponseError:
243 case kErrorCodeOmahaRequestXMLParseError:
244 case kErrorCodeOmahaResponseInvalid:
245 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
246 case kErrorCodeOmahaUpdateDeferredPerPolicy:
247 case kErrorCodeOmahaUpdateDeferredForBackoff:
248 case kErrorCodePostinstallPowerwashError:
249 case kErrorCodeUpdateCanceledByChannelChange:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800250 LOG(INFO) << "Not incrementing URL index or failure count for this error";
251 break;
252
David Zeuthena99981f2013-04-29 13:42:47 -0700253 case kErrorCodeSuccess: // success code
David Zeuthena99981f2013-04-29 13:42:47 -0700254 case kErrorCodeUmaReportedMax: // not an error code
255 case kErrorCodeOmahaRequestHTTPResponseBase: // aggregated already
256 case kErrorCodeDevModeFlag: // not an error code
257 case kErrorCodeResumedFlag: // not an error code
258 case kErrorCodeTestImageFlag: // not an error code
259 case kErrorCodeTestOmahaUrlFlag: // not an error code
260 case kErrorCodeSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800261 // These shouldn't happen. Enumerating these explicitly here so that we
262 // can let the compiler warn about new error codes that are added to
263 // action_processor.h but not added here.
264 LOG(WARNING) << "Unexpected error code for UpdateFailed";
265 break;
266
267 // Note: Not adding a default here so as to let the compiler warn us of
268 // any new enums that were added in the .h but not listed in this switch.
269 }
270}
271
Jay Srinivasan08262882012-12-28 19:29:43 -0800272bool PayloadState::ShouldBackoffDownload() {
273 if (response_.disable_payload_backoff) {
274 LOG(INFO) << "Payload backoff logic is disabled. "
275 "Can proceed with the download";
276 return false;
277 }
278
279 if (response_.is_delta_payload) {
280 // If delta payloads fail, we want to fallback quickly to full payloads as
281 // they are more likely to succeed. Exponential backoffs would greatly
282 // slow down the fallback to full payloads. So we don't backoff for delta
283 // payloads.
284 LOG(INFO) << "No backoffs for delta payloads. "
285 << "Can proceed with the download";
286 return false;
287 }
288
289 if (!utils::IsOfficialBuild()) {
290 // Backoffs are needed only for official builds. We do not want any delays
291 // or update failures due to backoffs during testing or development.
292 LOG(INFO) << "No backoffs for test/dev images. "
293 << "Can proceed with the download";
294 return false;
295 }
296
297 if (backoff_expiry_time_.is_null()) {
298 LOG(INFO) << "No backoff expiry time has been set. "
299 << "Can proceed with the download";
300 return false;
301 }
302
303 if (backoff_expiry_time_ < Time::Now()) {
304 LOG(INFO) << "The backoff expiry time ("
305 << utils::ToString(backoff_expiry_time_)
306 << ") has elapsed. Can proceed with the download";
307 return false;
308 }
309
310 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
311 << utils::ToString(backoff_expiry_time_);
312 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800313}
314
Chris Sosaaa18e162013-06-20 13:20:30 -0700315void PayloadState::Rollback() {
316 SetRollbackVersion(system_state_->request_params()->app_version());
317}
318
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800319void PayloadState::IncrementPayloadAttemptNumber() {
Jay Srinivasan08262882012-12-28 19:29:43 -0800320 if (response_.is_delta_payload) {
321 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
322 return;
323 }
324
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800325 LOG(INFO) << "Incrementing the payload attempt number";
326 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800327 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800328}
329
330void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800331 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700332 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800333 LOG(INFO) << "Incrementing the URL index for next attempt";
334 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800335 } else {
336 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700337 << "0 as we only have " << candidate_urls_.size()
338 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800339 SetUrlIndex(0);
340 IncrementPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800341 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800342
David Zeuthencc6f9962013-04-18 11:57:24 -0700343 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700344 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700345 SetUrlSwitchCount(url_switch_count_ + 1);
346
Jay Srinivasan08262882012-12-28 19:29:43 -0800347 // Whenever we update the URL index, we should also clear the URL failure
348 // count so we can start over fresh for the new URL.
349 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800350}
351
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800352void PayloadState::IncrementFailureCount() {
353 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800354 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800355 LOG(INFO) << "Incrementing the URL failure count";
356 SetUrlFailureCount(next_url_failure_count);
357 } else {
358 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
359 << ". Trying next available URL";
360 IncrementUrlIndex();
361 }
362}
363
Jay Srinivasan08262882012-12-28 19:29:43 -0800364void PayloadState::UpdateBackoffExpiryTime() {
365 if (response_.disable_payload_backoff) {
366 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
367 SetBackoffExpiryTime(Time());
368 return;
369 }
370
371 if (GetPayloadAttemptNumber() == 0) {
372 SetBackoffExpiryTime(Time());
373 return;
374 }
375
376 // Since we're doing left-shift below, make sure we don't shift more
377 // than this. E.g. if uint32_t is 4-bytes, don't left-shift more than 30 bits,
378 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
379 uint32_t num_days = 1; // the value to be shifted.
380 const uint32_t kMaxShifts = (sizeof(num_days) * 8) - 2;
381
382 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
383 // E.g. if payload_attempt_number is over 30, limit power to 30.
384 uint32_t power = min(GetPayloadAttemptNumber() - 1, kMaxShifts);
385
386 // The number of days is the minimum of 2 raised to (payload_attempt_number
387 // - 1) or kMaxBackoffDays.
388 num_days = min(num_days << power, kMaxBackoffDays);
389
390 // We don't want all retries to happen exactly at the same time when
391 // retrying after backoff. So add some random minutes to fuzz.
392 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
393 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
394 TimeDelta::FromMinutes(fuzz_minutes);
395 LOG(INFO) << "Incrementing the backoff expiry time by "
396 << utils::FormatTimeDelta(next_backoff_interval);
397 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
398}
399
Jay Srinivasan19409b72013-04-12 19:23:36 -0700400void PayloadState::UpdateCurrentDownloadSource() {
401 current_download_source_ = kNumDownloadSources;
402
Jay Srinivasan53173b92013-05-17 17:13:01 -0700403 if (GetUrlIndex() < candidate_urls_.size()) {
404 string current_url = candidate_urls_[GetUrlIndex()];
Jay Srinivasan19409b72013-04-12 19:23:36 -0700405 if (StartsWithASCII(current_url, "https://", false))
406 current_download_source_ = kDownloadSourceHttpsServer;
407 else if (StartsWithASCII(current_url, "http://", false))
408 current_download_source_ = kDownloadSourceHttpServer;
409 }
410
411 LOG(INFO) << "Current download source: "
412 << utils::ToString(current_download_source_);
413}
414
415void PayloadState::UpdateBytesDownloaded(size_t count) {
416 SetCurrentBytesDownloaded(
417 current_download_source_,
418 GetCurrentBytesDownloaded(current_download_source_) + count,
419 false);
420 SetTotalBytesDownloaded(
421 current_download_source_,
422 GetTotalBytesDownloaded(current_download_source_) + count,
423 false);
424}
425
426void PayloadState::ReportBytesDownloadedMetrics() {
427 // Report metrics collected from all known download sources to UMA.
428 // The reported data is in Megabytes in order to represent a larger
429 // sample range.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700430 int download_sources_used = 0;
431 string metric;
432 uint64_t successful_mbs = 0;
433 uint64_t total_mbs = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700434 for (int i = 0; i < kNumDownloadSources; i++) {
435 DownloadSource source = static_cast<DownloadSource>(i);
436 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
David Zeuthen44848602013-06-24 13:32:14 -0700437 uint64_t mbs;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700438
David Zeuthen44848602013-06-24 13:32:14 -0700439 // Only consider this download source (and send byte counts) as
440 // having been used if we downloaded a non-trivial amount of bytes
441 // (e.g. at least 1 MiB) that contributed to the final success of
442 // the update. Otherwise we're going to end up with a lot of
443 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700444
David Zeuthen44848602013-06-24 13:32:14 -0700445 mbs = GetCurrentBytesDownloaded(source) / kNumBytesInOneMiB;
446 if (mbs > 0) {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700447 download_sources_used |= (1 << source);
448
David Zeuthen44848602013-06-24 13:32:14 -0700449 metric = "Installer.SuccessfulMBsDownloadedFrom" +
450 utils::ToString(source);
451 successful_mbs += mbs;
452 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
453 system_state_->metrics_lib()->SendToUMA(metric,
454 mbs,
455 0, // min
456 kMaxMiBs,
457 kNumDefaultUmaBuckets);
458 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700459 SetCurrentBytesDownloaded(source, 0, true);
460
Jay Srinivasan19409b72013-04-12 19:23:36 -0700461 mbs = GetTotalBytesDownloaded(source) / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700462 if (mbs > 0) {
463 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
464 total_mbs += mbs;
465 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
466 system_state_->metrics_lib()->SendToUMA(metric,
467 mbs,
468 0, // min
469 kMaxMiBs,
470 kNumDefaultUmaBuckets);
471 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700472 SetTotalBytesDownloaded(source, 0, true);
473 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700474
475 metric = "Installer.DownloadSourcesUsed";
476 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
477 << " (bit flags) for metric " << metric;
478 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
479 system_state_->metrics_lib()->SendToUMA(metric,
480 download_sources_used,
481 0, // min
482 1 << kNumDownloadSources,
483 num_buckets);
484
485 if (successful_mbs) {
486 metric = "Installer.DownloadOverheadPercentage";
487 int percent_overhead = (total_mbs - successful_mbs) * 100 / successful_mbs;
488 LOG(INFO) << "Uploading " << percent_overhead << "% for metric " << metric;
489 system_state_->metrics_lib()->SendToUMA(metric,
490 percent_overhead,
491 0, // min: 0% overhead
492 1000, // max: 1000% overhead
493 kNumDefaultUmaBuckets);
494 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700495}
496
David Zeuthencc6f9962013-04-18 11:57:24 -0700497void PayloadState::ReportUpdateUrlSwitchesMetric() {
498 string metric = "Installer.UpdateURLSwitches";
499 int value = static_cast<int>(url_switch_count_);
500
501 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
502 system_state_->metrics_lib()->SendToUMA(
503 metric,
504 value,
505 0, // min value
506 100, // max value
507 kNumDefaultUmaBuckets);
508}
509
Chris Sosabe45bef2013-04-09 18:25:12 -0700510void PayloadState::ReportRebootMetrics() {
511 // Report the number of num_reboots.
512 string metric = "Installer.UpdateNumReboots";
513 uint32_t num_reboots = GetNumReboots();
514 LOG(INFO) << "Uploading reboot count of " << num_reboots << " for metric "
515 << metric;
516 system_state_->metrics_lib()->SendToUMA(
517 metric,
518 static_cast<int>(num_reboots), // sample
519 0, // min = 0.
520 50, // max
521 25); // buckets
522 SetNumReboots(0);
523}
524
525void PayloadState::UpdateNumReboots() {
526 // We only update the reboot count when the system has been detected to have
527 // been rebooted.
528 if (!system_state_->system_rebooted()) {
529 return;
530 }
531
532 SetNumReboots(GetNumReboots() + 1);
533}
534
535void PayloadState::SetNumReboots(uint32_t num_reboots) {
536 CHECK(prefs_);
537 num_reboots_ = num_reboots;
538 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
539 LOG(INFO) << "Number of Reboots during current update attempt = "
540 << num_reboots_;
541}
542
Jay Srinivasan08262882012-12-28 19:29:43 -0800543void PayloadState::ResetPersistedState() {
544 SetPayloadAttemptNumber(0);
545 SetUrlIndex(0);
546 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700547 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800548 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700549 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
David Zeuthen9a017f22013-04-11 16:10:26 -0700550 SetUpdateTimestampEnd(Time()); // Set to null time
551 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700552 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700553 ResetRollbackVersion();
554}
555
556void PayloadState::ResetRollbackVersion() {
557 CHECK(powerwash_safe_prefs_);
558 rollback_version_ = "";
559 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700560}
561
562void PayloadState::ResetDownloadSourcesOnNewUpdate() {
563 for (int i = 0; i < kNumDownloadSources; i++) {
564 DownloadSource source = static_cast<DownloadSource>(i);
565 SetCurrentBytesDownloaded(source, 0, true);
566 // Note: Not resetting the TotalBytesDownloaded as we want that metric
567 // to count the bytes downloaded across various update attempts until
568 // we have successfully applied the update.
569 }
570}
571
Chris Sosaaa18e162013-06-20 13:20:30 -0700572int64_t PayloadState::GetPersistedValue(const string& key,
573 bool across_powerwash) {
574 PrefsInterface* prefs = prefs_;
575 if (across_powerwash)
576 prefs = powerwash_safe_prefs_;
577
Jay Srinivasan19409b72013-04-12 19:23:36 -0700578 CHECK(prefs_);
Chris Sosaaa18e162013-06-20 13:20:30 -0700579 if (!prefs->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700580 return 0;
581
582 int64_t stored_value;
Chris Sosaaa18e162013-06-20 13:20:30 -0700583 if (!prefs->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700584 return 0;
585
586 if (stored_value < 0) {
587 LOG(ERROR) << key << ": Invalid value (" << stored_value
588 << ") in persisted state. Defaulting to 0";
589 return 0;
590 }
591
592 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800593}
594
595string PayloadState::CalculateResponseSignature() {
596 string response_sign = StringPrintf("NumURLs = %d\n",
Jay Srinivasan53173b92013-05-17 17:13:01 -0700597 candidate_urls_.size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800598
Jay Srinivasan53173b92013-05-17 17:13:01 -0700599 for (size_t i = 0; i < candidate_urls_.size(); i++)
600 response_sign += StringPrintf("Candidate Url%d = %s\n",
601 i, candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800602
603 response_sign += StringPrintf("Payload Size = %llu\n"
604 "Payload Sha256 Hash = %s\n"
605 "Metadata Size = %llu\n"
606 "Metadata Signature = %s\n"
607 "Is Delta Payload = %d\n"
608 "Max Failure Count Per Url = %d\n"
609 "Disable Payload Backoff = %d\n",
610 response_.size,
611 response_.hash.c_str(),
612 response_.metadata_size,
613 response_.metadata_signature.c_str(),
614 response_.is_delta_payload,
615 response_.max_failure_count_per_url,
616 response_.disable_payload_backoff);
617 return response_sign;
618}
619
620void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800621 CHECK(prefs_);
622 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800623 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
624 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
625 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800626 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800627}
628
Jay Srinivasan19409b72013-04-12 19:23:36 -0700629void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800630 CHECK(prefs_);
631 response_signature_ = response_signature;
632 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
633 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
634}
635
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800636void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700637 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber,
638 false));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800639}
640
641void PayloadState::SetPayloadAttemptNumber(uint32_t payload_attempt_number) {
642 CHECK(prefs_);
643 payload_attempt_number_ = payload_attempt_number;
644 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
645 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
646}
647
648void PayloadState::LoadUrlIndex() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700649 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex, false));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800650}
651
652void PayloadState::SetUrlIndex(uint32_t url_index) {
653 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800654 url_index_ = url_index;
655 LOG(INFO) << "Current URL Index = " << url_index_;
656 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700657
658 // Also update the download source, which is purely dependent on the
659 // current URL index alone.
660 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800661}
662
David Zeuthencc6f9962013-04-18 11:57:24 -0700663void PayloadState::LoadUrlSwitchCount() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700664 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount, false));
David Zeuthencc6f9962013-04-18 11:57:24 -0700665}
666
667void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
668 CHECK(prefs_);
669 url_switch_count_ = url_switch_count;
670 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
671 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
672}
673
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800674void PayloadState::LoadUrlFailureCount() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700675 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount,
676 false));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800677}
678
679void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
680 CHECK(prefs_);
681 url_failure_count_ = url_failure_count;
682 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
683 << ")'s Failure Count = " << url_failure_count_;
684 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800685}
686
Jay Srinivasan08262882012-12-28 19:29:43 -0800687void PayloadState::LoadBackoffExpiryTime() {
688 CHECK(prefs_);
689 int64_t stored_value;
690 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
691 return;
692
693 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
694 return;
695
696 Time stored_time = Time::FromInternalValue(stored_value);
697 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
698 LOG(ERROR) << "Invalid backoff expiry time ("
699 << utils::ToString(stored_time)
700 << ") in persisted state. Resetting.";
701 stored_time = Time();
702 }
703 SetBackoffExpiryTime(stored_time);
704}
705
706void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
707 CHECK(prefs_);
708 backoff_expiry_time_ = new_time;
709 LOG(INFO) << "Backoff Expiry Time = "
710 << utils::ToString(backoff_expiry_time_);
711 prefs_->SetInt64(kPrefsBackoffExpiryTime,
712 backoff_expiry_time_.ToInternalValue());
713}
714
David Zeuthen9a017f22013-04-11 16:10:26 -0700715TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700716 Time end_time = update_timestamp_end_.is_null()
717 ? system_state_->clock()->GetWallclockTime() :
718 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700719 return end_time - update_timestamp_start_;
720}
721
722void PayloadState::LoadUpdateTimestampStart() {
723 int64_t stored_value;
724 Time stored_time;
725
726 CHECK(prefs_);
727
David Zeuthenf413fe52013-04-22 14:04:39 -0700728 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700729
730 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
731 // The preference missing is not unexpected - in that case, just
732 // use the current time as start time
733 stored_time = now;
734 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
735 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
736 stored_time = now;
737 } else {
738 stored_time = Time::FromInternalValue(stored_value);
739 }
740
741 // Sanity check: If the time read from disk is in the future
742 // (modulo some slack to account for possible NTP drift
743 // adjustments), something is fishy and we should report and
744 // reset.
745 TimeDelta duration_according_to_stored_time = now - stored_time;
746 if (duration_according_to_stored_time < -kDurationSlack) {
747 LOG(ERROR) << "The UpdateTimestampStart value ("
748 << utils::ToString(stored_time)
749 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700750 << utils::FormatTimeDelta(duration_according_to_stored_time)
751 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700752 stored_time = now;
753 }
754
755 SetUpdateTimestampStart(stored_time);
756}
757
758void PayloadState::SetUpdateTimestampStart(const Time& value) {
759 CHECK(prefs_);
760 update_timestamp_start_ = value;
761 prefs_->SetInt64(kPrefsUpdateTimestampStart,
762 update_timestamp_start_.ToInternalValue());
763 LOG(INFO) << "Update Timestamp Start = "
764 << utils::ToString(update_timestamp_start_);
765}
766
767void PayloadState::SetUpdateTimestampEnd(const Time& value) {
768 update_timestamp_end_ = value;
769 LOG(INFO) << "Update Timestamp End = "
770 << utils::ToString(update_timestamp_end_);
771}
772
773TimeDelta PayloadState::GetUpdateDurationUptime() {
774 return update_duration_uptime_;
775}
776
777void PayloadState::LoadUpdateDurationUptime() {
778 int64_t stored_value;
779 TimeDelta stored_delta;
780
781 CHECK(prefs_);
782
783 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
784 // The preference missing is not unexpected - in that case, just
785 // we'll use zero as the delta
786 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
787 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
788 stored_delta = TimeDelta::FromSeconds(0);
789 } else {
790 stored_delta = TimeDelta::FromInternalValue(stored_value);
791 }
792
793 // Sanity-check: Uptime can never be greater than the wall-clock
794 // difference (modulo some slack). If it is, report and reset
795 // to the wall-clock difference.
796 TimeDelta diff = GetUpdateDuration() - stored_delta;
797 if (diff < -kDurationSlack) {
798 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -0700799 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -0700800 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700801 << utils::FormatTimeDelta(diff)
802 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700803 stored_delta = update_duration_current_;
804 }
805
806 SetUpdateDurationUptime(stored_delta);
807}
808
Chris Sosabe45bef2013-04-09 18:25:12 -0700809void PayloadState::LoadNumReboots() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700810 SetNumReboots(GetPersistedValue(kPrefsNumReboots, false));
811}
812
813void PayloadState::LoadRollbackVersion() {
814 SetNumReboots(GetPersistedValue(kPrefsRollbackVersion, true));
815}
816
817void PayloadState::SetRollbackVersion(const string& rollback_version) {
818 CHECK(powerwash_safe_prefs_);
819 LOG(INFO) << "Blacklisting version "<< rollback_version;
820 rollback_version_ = rollback_version;
821 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -0700822}
823
David Zeuthen9a017f22013-04-11 16:10:26 -0700824void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
825 const Time& timestamp,
826 bool use_logging) {
827 CHECK(prefs_);
828 update_duration_uptime_ = value;
829 update_duration_uptime_timestamp_ = timestamp;
830 prefs_->SetInt64(kPrefsUpdateDurationUptime,
831 update_duration_uptime_.ToInternalValue());
832 if (use_logging) {
833 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -0700834 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -0700835 }
836}
837
838void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -0700839 Time now = system_state_->clock()->GetMonotonicTime();
840 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -0700841}
842
843void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700844 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700845 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
846 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
847 // We're frequently called so avoid logging this write
848 SetUpdateDurationUptimeExtended(new_uptime, now, false);
849}
850
David Zeuthen674c3182013-04-18 14:05:20 -0700851void PayloadState::ReportDurationMetrics() {
852 TimeDelta duration = GetUpdateDuration();
853 TimeDelta duration_uptime = GetUpdateDurationUptime();
854 string metric;
855
856 metric = "Installer.UpdateDurationMinutes";
857 system_state_->metrics_lib()->SendToUMA(
858 metric,
859 static_cast<int>(duration.InMinutes()),
860 1, // min: 1 minute
861 365*24*60, // max: 1 year (approx)
862 kNumDefaultUmaBuckets);
863 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
864 << " for metric " << metric;
865
866 metric = "Installer.UpdateDurationUptimeMinutes";
867 system_state_->metrics_lib()->SendToUMA(
868 metric,
869 static_cast<int>(duration_uptime.InMinutes()),
870 1, // min: 1 minute
871 30*24*60, // max: 1 month (approx)
872 kNumDefaultUmaBuckets);
873 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
874 << " for metric " << metric;
875
876 prefs_->Delete(kPrefsUpdateTimestampStart);
877 prefs_->Delete(kPrefsUpdateDurationUptime);
878}
879
Jay Srinivasan19409b72013-04-12 19:23:36 -0700880string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
881 return prefix + "-from-" + utils::ToString(source);
882}
883
884void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
885 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosaaa18e162013-06-20 13:20:30 -0700886 SetCurrentBytesDownloaded(source, GetPersistedValue(key, false), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700887}
888
889void PayloadState::SetCurrentBytesDownloaded(
890 DownloadSource source,
891 uint64_t current_bytes_downloaded,
892 bool log) {
893 CHECK(prefs_);
894
895 if (source >= kNumDownloadSources)
896 return;
897
898 // Update the in-memory value.
899 current_bytes_downloaded_[source] = current_bytes_downloaded;
900
901 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
902 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
903 LOG_IF(INFO, log) << "Current bytes downloaded for "
904 << utils::ToString(source) << " = "
905 << GetCurrentBytesDownloaded(source);
906}
907
908void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
909 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosaaa18e162013-06-20 13:20:30 -0700910 SetTotalBytesDownloaded(source, GetPersistedValue(key, false), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700911}
912
913void PayloadState::SetTotalBytesDownloaded(
914 DownloadSource source,
915 uint64_t total_bytes_downloaded,
916 bool log) {
917 CHECK(prefs_);
918
919 if (source >= kNumDownloadSources)
920 return;
921
922 // Update the in-memory value.
923 total_bytes_downloaded_[source] = total_bytes_downloaded;
924
925 // Persist.
926 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
927 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
928 LOG_IF(INFO, log) << "Total bytes downloaded for "
929 << utils::ToString(source) << " = "
930 << GetTotalBytesDownloaded(source);
931}
932
David Zeuthena573d6f2013-06-14 16:13:36 -0700933void PayloadState::LoadNumResponsesSeen() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700934 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen, false));
David Zeuthena573d6f2013-06-14 16:13:36 -0700935}
936
937void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
938 CHECK(prefs_);
939 num_responses_seen_ = num_responses_seen;
940 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
941 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
942}
943
944void PayloadState::ReportUpdatesAbandonedCountMetric() {
945 string metric = "Installer.UpdatesAbandonedCount";
946 int value = num_responses_seen_ - 1;
947
948 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
949 system_state_->metrics_lib()->SendToUMA(
950 metric,
951 value,
952 0, // min value
953 100, // max value
954 kNumDefaultUmaBuckets);
955}
956
Jay Srinivasan53173b92013-05-17 17:13:01 -0700957void PayloadState::ComputeCandidateUrls() {
958 bool http_url_ok = false;
959
960 if (system_state_->IsOfficialBuild()) {
961 const policy::DevicePolicy* policy = system_state_->device_policy();
962 if (!(policy && policy->GetHttpDownloadsEnabled(&http_url_ok) &&
963 http_url_ok))
964 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
965 } else {
966 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
967 http_url_ok = true;
968 }
969
970 candidate_urls_.clear();
971 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
972 string candidate_url = response_.payload_urls[i];
973 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
974 continue;
975 candidate_urls_.push_back(candidate_url);
976 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
977 << ": " << candidate_url;
978 }
979
980 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
981 << "out of " << response_.payload_urls.size() << " URLs supplied";
982}
983
David Zeuthene4c58bf2013-06-18 17:26:50 -0700984void PayloadState::CreateSystemUpdatedMarkerFile() {
985 CHECK(prefs_);
986 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
987 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
988}
989
990void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
991 // Send |time_to_reboot| as a UMA stat.
992 string metric = "Installer.TimeToRebootMinutes";
993 system_state_->metrics_lib()->SendToUMA(metric,
994 time_to_reboot.InMinutes(),
995 0, // min: 0 minute
996 30*24*60, // max: 1 month (approx)
997 kNumDefaultUmaBuckets);
998 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
999 << " for metric " << metric;
1000}
1001
1002void PayloadState::UpdateEngineStarted() {
1003 // Figure out if we just booted into a new update
1004 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1005 int64_t stored_value;
1006 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1007 Time system_updated_at = Time::FromInternalValue(stored_value);
1008 if (!system_updated_at.is_null()) {
1009 TimeDelta time_to_reboot =
1010 system_state_->clock()->GetWallclockTime() - system_updated_at;
1011 if (time_to_reboot.ToInternalValue() < 0) {
1012 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1013 << utils::ToString(system_updated_at);
1014 } else {
1015 BootedIntoUpdate(time_to_reboot);
1016 }
1017 }
1018 }
1019 prefs_->Delete(kPrefsSystemUpdatedMarker);
1020 }
1021}
1022
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001023} // namespace chromeos_update_engine