blob: 5ab602807e0ce8e0a69e3aa32a0725d727d45b64 [file] [log] [blame]
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/payload_state.h"
6
Jay Srinivasan08262882012-12-28 19:29:43 -08007#include <algorithm>
8
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08009#include <base/logging.h>
Jay Srinivasan19409b72013-04-12 19:23:36 -070010#include "base/string_util.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080011#include <base/stringprintf.h>
12
David Zeuthenf413fe52013-04-22 14:04:39 -070013#include "update_engine/clock.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070014#include "update_engine/constants.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070015#include "update_engine/prefs.h"
16#include "update_engine/system_state.h"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080017#include "update_engine/utils.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080018
Jay Srinivasan08262882012-12-28 19:29:43 -080019using base::Time;
20using base::TimeDelta;
21using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080022using std::string;
23
24namespace chromeos_update_engine {
25
David Zeuthen9a017f22013-04-11 16:10:26 -070026const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
27
Jay Srinivasan08262882012-12-28 19:29:43 -080028// We want to upperbound backoffs to 16 days
29static const uint32_t kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080030
Jay Srinivasan08262882012-12-28 19:29:43 -080031// We want to randomize retry attempts after the backoff by +/- 6 hours.
32static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080033
Jay Srinivasan19409b72013-04-12 19:23:36 -070034PayloadState::PayloadState()
35 : prefs_(NULL),
36 payload_attempt_number_(0),
37 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070038 url_failure_count_(0),
39 url_switch_count_(0) {
Jay Srinivasan19409b72013-04-12 19:23:36 -070040 for (int i = 0; i <= kNumDownloadSources; i++)
41 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
42}
43
44bool PayloadState::Initialize(SystemState* system_state) {
45 system_state_ = system_state;
46 prefs_ = system_state_->prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080047 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080048 LoadPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080049 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080050 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070051 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080052 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070053 LoadUpdateTimestampStart();
54 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
55 // being called before it. Don't reorder.
56 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070057 for (int i = 0; i < kNumDownloadSources; i++) {
58 DownloadSource source = static_cast<DownloadSource>(i);
59 LoadCurrentBytesDownloaded(source);
60 LoadTotalBytesDownloaded(source);
61 }
Chris Sosabe45bef2013-04-09 18:25:12 -070062 LoadNumReboots();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080063 return true;
64}
65
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080066void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080067 // Always store the latest response.
68 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080069
Jay Srinivasan08262882012-12-28 19:29:43 -080070 // Check if the "signature" of this response (i.e. the fields we care about)
71 // has changed.
72 string new_response_signature = CalculateResponseSignature();
73 bool has_response_changed = (response_signature_ != new_response_signature);
74
75 // If the response has changed, we should persist the new signature and
76 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080077 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -080078 LOG(INFO) << "Resetting all persisted state as this is a new response";
79 SetResponseSignature(new_response_signature);
80 ResetPersistedState();
81 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080082 }
83
Jay Srinivasan08262882012-12-28 19:29:43 -080084 // This is the earliest point at which we can validate whether the URL index
85 // we loaded from the persisted state is a valid value. If the response
86 // hasn't changed but the URL index is invalid, it's indicative of some
87 // tampering of the persisted state.
88 if (url_index_ >= GetNumUrls()) {
89 LOG(INFO) << "Resetting all payload state as the url index seems to have "
90 "been tampered with";
91 ResetPersistedState();
92 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080093 }
Jay Srinivasan19409b72013-04-12 19:23:36 -070094
95 // Update the current download source which depends on the latest value of
96 // the response.
97 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080098}
99
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800100void PayloadState::DownloadComplete() {
101 LOG(INFO) << "Payload downloaded successfully";
102 IncrementPayloadAttemptNumber();
103}
104
105void PayloadState::DownloadProgress(size_t count) {
106 if (count == 0)
107 return;
108
David Zeuthen9a017f22013-04-11 16:10:26 -0700109 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700110 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700111
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800112 // We've received non-zero bytes from a recent download operation. Since our
113 // URL failure count is meant to penalize a URL only for consecutive
114 // failures, downloading bytes successfully means we should reset the failure
115 // count (as we know at least that the URL is working). In future, we can
116 // design this to be more sophisticated to check for more intelligent failure
117 // patterns, but right now, even 1 byte downloaded will mark the URL to be
118 // good unless it hits 10 (or configured number of) consecutive failures
119 // again.
120
121 if (GetUrlFailureCount() == 0)
122 return;
123
124 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
125 << " to 0 as we received " << count << " bytes successfully";
126 SetUrlFailureCount(0);
127}
128
Chris Sosabe45bef2013-04-09 18:25:12 -0700129void PayloadState::UpdateResumed() {
130 LOG(INFO) << "Resuming an update that was previously started.";
131 UpdateNumReboots();
132}
133
Jay Srinivasan19409b72013-04-12 19:23:36 -0700134void PayloadState::UpdateRestarted() {
135 LOG(INFO) << "Starting a new update";
136 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700137 SetNumReboots(0);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700138}
139
David Zeuthen9a017f22013-04-11 16:10:26 -0700140void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700141 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700142 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700143 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
Jay Srinivasan19409b72013-04-12 19:23:36 -0700144 ReportBytesDownloadedMetrics();
David Zeuthencc6f9962013-04-18 11:57:24 -0700145 ReportUpdateUrlSwitchesMetric();
Chris Sosabe45bef2013-04-09 18:25:12 -0700146 ReportRebootMetrics();
David Zeuthen674c3182013-04-18 14:05:20 -0700147 ReportDurationMetrics();
David Zeuthen9a017f22013-04-11 16:10:26 -0700148}
149
David Zeuthena99981f2013-04-29 13:42:47 -0700150void PayloadState::UpdateFailed(ErrorCode error) {
151 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800152 LOG(INFO) << "Updating payload state for error code: " << base_error
153 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800154
Jay Srinivasan08262882012-12-28 19:29:43 -0800155 if (GetNumUrls() == 0) {
156 // This means we got this error even before we got a valid Omaha response.
157 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800158 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
159 return;
160 }
161
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800162 switch (base_error) {
163 // Errors which are good indicators of a problem with a particular URL or
164 // the protocol used in the URL or entities in the communication channel
165 // (e.g. proxies). We should try the next available URL in the next update
166 // check to quickly recover from these errors.
David Zeuthena99981f2013-04-29 13:42:47 -0700167 case kErrorCodePayloadHashMismatchError:
168 case kErrorCodePayloadSizeMismatchError:
169 case kErrorCodeDownloadPayloadVerificationError:
170 case kErrorCodeDownloadPayloadPubKeyVerificationError:
171 case kErrorCodeSignedDeltaPayloadExpectedError:
172 case kErrorCodeDownloadInvalidMetadataMagicString:
173 case kErrorCodeDownloadSignatureMissingInManifest:
174 case kErrorCodeDownloadManifestParseError:
175 case kErrorCodeDownloadMetadataSignatureError:
176 case kErrorCodeDownloadMetadataSignatureVerificationError:
177 case kErrorCodeDownloadMetadataSignatureMismatch:
178 case kErrorCodeDownloadOperationHashVerificationError:
179 case kErrorCodeDownloadOperationExecutionError:
180 case kErrorCodeDownloadOperationHashMismatch:
181 case kErrorCodeDownloadInvalidMetadataSize:
182 case kErrorCodeDownloadInvalidMetadataSignature:
183 case kErrorCodeDownloadOperationHashMissingError:
184 case kErrorCodeDownloadMetadataSignatureMissingError:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800185 IncrementUrlIndex();
186 break;
187
188 // Errors which seem to be just transient network/communication related
189 // failures and do not indicate any inherent problem with the URL itself.
190 // So, we should keep the current URL but just increment the
191 // failure count to give it more chances. This way, while we maximize our
192 // chances of downloading from the URLs that appear earlier in the response
193 // (because download from a local server URL that appears earlier in a
194 // response is preferable than downloading from the next URL which could be
195 // a internet URL and thus could be more expensive).
David Zeuthena99981f2013-04-29 13:42:47 -0700196 case kErrorCodeError:
197 case kErrorCodeDownloadTransferError:
198 case kErrorCodeDownloadWriteError:
199 case kErrorCodeDownloadStateInitializationError:
200 case kErrorCodeOmahaErrorInHTTPResponse: // Aggregate code for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800201 IncrementFailureCount();
202 break;
203
204 // Errors which are not specific to a URL and hence shouldn't result in
205 // the URL being penalized. This can happen in two cases:
206 // 1. We haven't started downloading anything: These errors don't cost us
207 // anything in terms of actual payload bytes, so we should just do the
208 // regular retries at the next update check.
209 // 2. We have successfully downloaded the payload: In this case, the
210 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800211 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800212 // In either case, there's no need to update URL index or failure count.
David Zeuthena99981f2013-04-29 13:42:47 -0700213 case kErrorCodeOmahaRequestError:
214 case kErrorCodeOmahaResponseHandlerError:
215 case kErrorCodePostinstallRunnerError:
216 case kErrorCodeFilesystemCopierError:
217 case kErrorCodeInstallDeviceOpenError:
218 case kErrorCodeKernelDeviceOpenError:
219 case kErrorCodeDownloadNewPartitionInfoError:
220 case kErrorCodeNewRootfsVerificationError:
221 case kErrorCodeNewKernelVerificationError:
222 case kErrorCodePostinstallBootedFromFirmwareB:
223 case kErrorCodeOmahaRequestEmptyResponseError:
224 case kErrorCodeOmahaRequestXMLParseError:
225 case kErrorCodeOmahaResponseInvalid:
226 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
227 case kErrorCodeOmahaUpdateDeferredPerPolicy:
228 case kErrorCodeOmahaUpdateDeferredForBackoff:
229 case kErrorCodePostinstallPowerwashError:
230 case kErrorCodeUpdateCanceledByChannelChange:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800231 LOG(INFO) << "Not incrementing URL index or failure count for this error";
232 break;
233
David Zeuthena99981f2013-04-29 13:42:47 -0700234 case kErrorCodeSuccess: // success code
235 case kErrorCodeSetBootableFlagError: // unused
236 case kErrorCodeUmaReportedMax: // not an error code
237 case kErrorCodeOmahaRequestHTTPResponseBase: // aggregated already
238 case kErrorCodeDevModeFlag: // not an error code
239 case kErrorCodeResumedFlag: // not an error code
240 case kErrorCodeTestImageFlag: // not an error code
241 case kErrorCodeTestOmahaUrlFlag: // not an error code
242 case kErrorCodeSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800243 // These shouldn't happen. Enumerating these explicitly here so that we
244 // can let the compiler warn about new error codes that are added to
245 // action_processor.h but not added here.
246 LOG(WARNING) << "Unexpected error code for UpdateFailed";
247 break;
248
249 // Note: Not adding a default here so as to let the compiler warn us of
250 // any new enums that were added in the .h but not listed in this switch.
251 }
252}
253
Jay Srinivasan08262882012-12-28 19:29:43 -0800254bool PayloadState::ShouldBackoffDownload() {
255 if (response_.disable_payload_backoff) {
256 LOG(INFO) << "Payload backoff logic is disabled. "
257 "Can proceed with the download";
258 return false;
259 }
260
261 if (response_.is_delta_payload) {
262 // If delta payloads fail, we want to fallback quickly to full payloads as
263 // they are more likely to succeed. Exponential backoffs would greatly
264 // slow down the fallback to full payloads. So we don't backoff for delta
265 // payloads.
266 LOG(INFO) << "No backoffs for delta payloads. "
267 << "Can proceed with the download";
268 return false;
269 }
270
271 if (!utils::IsOfficialBuild()) {
272 // Backoffs are needed only for official builds. We do not want any delays
273 // or update failures due to backoffs during testing or development.
274 LOG(INFO) << "No backoffs for test/dev images. "
275 << "Can proceed with the download";
276 return false;
277 }
278
279 if (backoff_expiry_time_.is_null()) {
280 LOG(INFO) << "No backoff expiry time has been set. "
281 << "Can proceed with the download";
282 return false;
283 }
284
285 if (backoff_expiry_time_ < Time::Now()) {
286 LOG(INFO) << "The backoff expiry time ("
287 << utils::ToString(backoff_expiry_time_)
288 << ") has elapsed. Can proceed with the download";
289 return false;
290 }
291
292 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
293 << utils::ToString(backoff_expiry_time_);
294 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800295}
296
297void PayloadState::IncrementPayloadAttemptNumber() {
Jay Srinivasan08262882012-12-28 19:29:43 -0800298 if (response_.is_delta_payload) {
299 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
300 return;
301 }
302
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800303 LOG(INFO) << "Incrementing the payload attempt number";
304 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800305 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800306}
307
308void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800309 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800310 if (next_url_index < GetNumUrls()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800311 LOG(INFO) << "Incrementing the URL index for next attempt";
312 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800313 } else {
314 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan08262882012-12-28 19:29:43 -0800315 << "0 as we only have " << GetNumUrls() << " URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800316 SetUrlIndex(0);
317 IncrementPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800318 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800319
David Zeuthencc6f9962013-04-18 11:57:24 -0700320 // If we have multiple URLs, record that we just switched to another one
321 if (GetNumUrls() > 1)
322 SetUrlSwitchCount(url_switch_count_ + 1);
323
Jay Srinivasan08262882012-12-28 19:29:43 -0800324 // Whenever we update the URL index, we should also clear the URL failure
325 // count so we can start over fresh for the new URL.
326 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800327}
328
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800329void PayloadState::IncrementFailureCount() {
330 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800331 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800332 LOG(INFO) << "Incrementing the URL failure count";
333 SetUrlFailureCount(next_url_failure_count);
334 } else {
335 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
336 << ". Trying next available URL";
337 IncrementUrlIndex();
338 }
339}
340
Jay Srinivasan08262882012-12-28 19:29:43 -0800341void PayloadState::UpdateBackoffExpiryTime() {
342 if (response_.disable_payload_backoff) {
343 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
344 SetBackoffExpiryTime(Time());
345 return;
346 }
347
348 if (GetPayloadAttemptNumber() == 0) {
349 SetBackoffExpiryTime(Time());
350 return;
351 }
352
353 // Since we're doing left-shift below, make sure we don't shift more
354 // than this. E.g. if uint32_t is 4-bytes, don't left-shift more than 30 bits,
355 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
356 uint32_t num_days = 1; // the value to be shifted.
357 const uint32_t kMaxShifts = (sizeof(num_days) * 8) - 2;
358
359 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
360 // E.g. if payload_attempt_number is over 30, limit power to 30.
361 uint32_t power = min(GetPayloadAttemptNumber() - 1, kMaxShifts);
362
363 // The number of days is the minimum of 2 raised to (payload_attempt_number
364 // - 1) or kMaxBackoffDays.
365 num_days = min(num_days << power, kMaxBackoffDays);
366
367 // We don't want all retries to happen exactly at the same time when
368 // retrying after backoff. So add some random minutes to fuzz.
369 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
370 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
371 TimeDelta::FromMinutes(fuzz_minutes);
372 LOG(INFO) << "Incrementing the backoff expiry time by "
373 << utils::FormatTimeDelta(next_backoff_interval);
374 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
375}
376
Jay Srinivasan19409b72013-04-12 19:23:36 -0700377void PayloadState::UpdateCurrentDownloadSource() {
378 current_download_source_ = kNumDownloadSources;
379
380 if (GetUrlIndex() < response_.payload_urls.size()) {
381 string current_url = response_.payload_urls[GetUrlIndex()];
382 if (StartsWithASCII(current_url, "https://", false))
383 current_download_source_ = kDownloadSourceHttpsServer;
384 else if (StartsWithASCII(current_url, "http://", false))
385 current_download_source_ = kDownloadSourceHttpServer;
386 }
387
388 LOG(INFO) << "Current download source: "
389 << utils::ToString(current_download_source_);
390}
391
392void PayloadState::UpdateBytesDownloaded(size_t count) {
393 SetCurrentBytesDownloaded(
394 current_download_source_,
395 GetCurrentBytesDownloaded(current_download_source_) + count,
396 false);
397 SetTotalBytesDownloaded(
398 current_download_source_,
399 GetTotalBytesDownloaded(current_download_source_) + count,
400 false);
401}
402
403void PayloadState::ReportBytesDownloadedMetrics() {
404 // Report metrics collected from all known download sources to UMA.
405 // The reported data is in Megabytes in order to represent a larger
406 // sample range.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700407 int download_sources_used = 0;
408 string metric;
409 uint64_t successful_mbs = 0;
410 uint64_t total_mbs = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700411 for (int i = 0; i < kNumDownloadSources; i++) {
412 DownloadSource source = static_cast<DownloadSource>(i);
413 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
414
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700415 metric = "Installer.SuccessfulMBsDownloadedFrom" + utils::ToString(source);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700416 uint64_t mbs = GetCurrentBytesDownloaded(source) / kNumBytesInOneMiB;
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700417
418 // Count this download source as having been used if we downloaded any
419 // bytes that contributed to the final success of the update.
420 if (mbs)
421 download_sources_used |= (1 << source);
422
423 successful_mbs += mbs;
424 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700425 system_state_->metrics_lib()->SendToUMA(metric,
426 mbs,
427 0, // min
428 kMaxMiBs,
429 kNumDefaultUmaBuckets);
430 SetCurrentBytesDownloaded(source, 0, true);
431
432 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
433 mbs = GetTotalBytesDownloaded(source) / kNumBytesInOneMiB;
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700434 total_mbs += mbs;
435 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700436 system_state_->metrics_lib()->SendToUMA(metric,
437 mbs,
438 0, // min
439 kMaxMiBs,
440 kNumDefaultUmaBuckets);
441
442 SetTotalBytesDownloaded(source, 0, true);
443 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700444
445 metric = "Installer.DownloadSourcesUsed";
446 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
447 << " (bit flags) for metric " << metric;
448 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
449 system_state_->metrics_lib()->SendToUMA(metric,
450 download_sources_used,
451 0, // min
452 1 << kNumDownloadSources,
453 num_buckets);
454
455 if (successful_mbs) {
456 metric = "Installer.DownloadOverheadPercentage";
457 int percent_overhead = (total_mbs - successful_mbs) * 100 / successful_mbs;
458 LOG(INFO) << "Uploading " << percent_overhead << "% for metric " << metric;
459 system_state_->metrics_lib()->SendToUMA(metric,
460 percent_overhead,
461 0, // min: 0% overhead
462 1000, // max: 1000% overhead
463 kNumDefaultUmaBuckets);
464 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700465}
466
David Zeuthencc6f9962013-04-18 11:57:24 -0700467void PayloadState::ReportUpdateUrlSwitchesMetric() {
468 string metric = "Installer.UpdateURLSwitches";
469 int value = static_cast<int>(url_switch_count_);
470
471 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
472 system_state_->metrics_lib()->SendToUMA(
473 metric,
474 value,
475 0, // min value
476 100, // max value
477 kNumDefaultUmaBuckets);
478}
479
Chris Sosabe45bef2013-04-09 18:25:12 -0700480void PayloadState::ReportRebootMetrics() {
481 // Report the number of num_reboots.
482 string metric = "Installer.UpdateNumReboots";
483 uint32_t num_reboots = GetNumReboots();
484 LOG(INFO) << "Uploading reboot count of " << num_reboots << " for metric "
485 << metric;
486 system_state_->metrics_lib()->SendToUMA(
487 metric,
488 static_cast<int>(num_reboots), // sample
489 0, // min = 0.
490 50, // max
491 25); // buckets
492 SetNumReboots(0);
493}
494
495void PayloadState::UpdateNumReboots() {
496 // We only update the reboot count when the system has been detected to have
497 // been rebooted.
498 if (!system_state_->system_rebooted()) {
499 return;
500 }
501
502 SetNumReboots(GetNumReboots() + 1);
503}
504
505void PayloadState::SetNumReboots(uint32_t num_reboots) {
506 CHECK(prefs_);
507 num_reboots_ = num_reboots;
508 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
509 LOG(INFO) << "Number of Reboots during current update attempt = "
510 << num_reboots_;
511}
512
Jay Srinivasan08262882012-12-28 19:29:43 -0800513void PayloadState::ResetPersistedState() {
514 SetPayloadAttemptNumber(0);
515 SetUrlIndex(0);
516 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700517 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800518 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700519 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
David Zeuthen9a017f22013-04-11 16:10:26 -0700520 SetUpdateTimestampEnd(Time()); // Set to null time
521 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700522 ResetDownloadSourcesOnNewUpdate();
523}
524
525void PayloadState::ResetDownloadSourcesOnNewUpdate() {
526 for (int i = 0; i < kNumDownloadSources; i++) {
527 DownloadSource source = static_cast<DownloadSource>(i);
528 SetCurrentBytesDownloaded(source, 0, true);
529 // Note: Not resetting the TotalBytesDownloaded as we want that metric
530 // to count the bytes downloaded across various update attempts until
531 // we have successfully applied the update.
532 }
533}
534
535int64_t PayloadState::GetPersistedValue(const string& key) {
536 CHECK(prefs_);
537 if (!prefs_->Exists(key))
538 return 0;
539
540 int64_t stored_value;
541 if (!prefs_->GetInt64(key, &stored_value))
542 return 0;
543
544 if (stored_value < 0) {
545 LOG(ERROR) << key << ": Invalid value (" << stored_value
546 << ") in persisted state. Defaulting to 0";
547 return 0;
548 }
549
550 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800551}
552
553string PayloadState::CalculateResponseSignature() {
554 string response_sign = StringPrintf("NumURLs = %d\n",
555 response_.payload_urls.size());
556
557 for (size_t i = 0; i < response_.payload_urls.size(); i++)
558 response_sign += StringPrintf("Url%d = %s\n",
559 i, response_.payload_urls[i].c_str());
560
561 response_sign += StringPrintf("Payload Size = %llu\n"
562 "Payload Sha256 Hash = %s\n"
563 "Metadata Size = %llu\n"
564 "Metadata Signature = %s\n"
565 "Is Delta Payload = %d\n"
566 "Max Failure Count Per Url = %d\n"
567 "Disable Payload Backoff = %d\n",
568 response_.size,
569 response_.hash.c_str(),
570 response_.metadata_size,
571 response_.metadata_signature.c_str(),
572 response_.is_delta_payload,
573 response_.max_failure_count_per_url,
574 response_.disable_payload_backoff);
575 return response_sign;
576}
577
578void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800579 CHECK(prefs_);
580 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800581 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
582 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
583 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800584 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800585}
586
Jay Srinivasan19409b72013-04-12 19:23:36 -0700587void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800588 CHECK(prefs_);
589 response_signature_ = response_signature;
590 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
591 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
592}
593
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800594void PayloadState::LoadPayloadAttemptNumber() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700595 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800596}
597
598void PayloadState::SetPayloadAttemptNumber(uint32_t payload_attempt_number) {
599 CHECK(prefs_);
600 payload_attempt_number_ = payload_attempt_number;
601 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
602 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
603}
604
605void PayloadState::LoadUrlIndex() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700606 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800607}
608
609void PayloadState::SetUrlIndex(uint32_t url_index) {
610 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800611 url_index_ = url_index;
612 LOG(INFO) << "Current URL Index = " << url_index_;
613 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700614
615 // Also update the download source, which is purely dependent on the
616 // current URL index alone.
617 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800618}
619
David Zeuthencc6f9962013-04-18 11:57:24 -0700620void PayloadState::LoadUrlSwitchCount() {
621 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
622}
623
624void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
625 CHECK(prefs_);
626 url_switch_count_ = url_switch_count;
627 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
628 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
629}
630
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800631void PayloadState::LoadUrlFailureCount() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700632 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800633}
634
635void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
636 CHECK(prefs_);
637 url_failure_count_ = url_failure_count;
638 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
639 << ")'s Failure Count = " << url_failure_count_;
640 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800641}
642
Jay Srinivasan08262882012-12-28 19:29:43 -0800643void PayloadState::LoadBackoffExpiryTime() {
644 CHECK(prefs_);
645 int64_t stored_value;
646 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
647 return;
648
649 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
650 return;
651
652 Time stored_time = Time::FromInternalValue(stored_value);
653 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
654 LOG(ERROR) << "Invalid backoff expiry time ("
655 << utils::ToString(stored_time)
656 << ") in persisted state. Resetting.";
657 stored_time = Time();
658 }
659 SetBackoffExpiryTime(stored_time);
660}
661
662void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
663 CHECK(prefs_);
664 backoff_expiry_time_ = new_time;
665 LOG(INFO) << "Backoff Expiry Time = "
666 << utils::ToString(backoff_expiry_time_);
667 prefs_->SetInt64(kPrefsBackoffExpiryTime,
668 backoff_expiry_time_.ToInternalValue());
669}
670
David Zeuthen9a017f22013-04-11 16:10:26 -0700671TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700672 Time end_time = update_timestamp_end_.is_null()
673 ? system_state_->clock()->GetWallclockTime() :
674 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700675 return end_time - update_timestamp_start_;
676}
677
678void PayloadState::LoadUpdateTimestampStart() {
679 int64_t stored_value;
680 Time stored_time;
681
682 CHECK(prefs_);
683
David Zeuthenf413fe52013-04-22 14:04:39 -0700684 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700685
686 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
687 // The preference missing is not unexpected - in that case, just
688 // use the current time as start time
689 stored_time = now;
690 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
691 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
692 stored_time = now;
693 } else {
694 stored_time = Time::FromInternalValue(stored_value);
695 }
696
697 // Sanity check: If the time read from disk is in the future
698 // (modulo some slack to account for possible NTP drift
699 // adjustments), something is fishy and we should report and
700 // reset.
701 TimeDelta duration_according_to_stored_time = now - stored_time;
702 if (duration_according_to_stored_time < -kDurationSlack) {
703 LOG(ERROR) << "The UpdateTimestampStart value ("
704 << utils::ToString(stored_time)
705 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700706 << utils::FormatTimeDelta(duration_according_to_stored_time)
707 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700708 stored_time = now;
709 }
710
711 SetUpdateTimestampStart(stored_time);
712}
713
714void PayloadState::SetUpdateTimestampStart(const Time& value) {
715 CHECK(prefs_);
716 update_timestamp_start_ = value;
717 prefs_->SetInt64(kPrefsUpdateTimestampStart,
718 update_timestamp_start_.ToInternalValue());
719 LOG(INFO) << "Update Timestamp Start = "
720 << utils::ToString(update_timestamp_start_);
721}
722
723void PayloadState::SetUpdateTimestampEnd(const Time& value) {
724 update_timestamp_end_ = value;
725 LOG(INFO) << "Update Timestamp End = "
726 << utils::ToString(update_timestamp_end_);
727}
728
729TimeDelta PayloadState::GetUpdateDurationUptime() {
730 return update_duration_uptime_;
731}
732
733void PayloadState::LoadUpdateDurationUptime() {
734 int64_t stored_value;
735 TimeDelta stored_delta;
736
737 CHECK(prefs_);
738
739 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
740 // The preference missing is not unexpected - in that case, just
741 // we'll use zero as the delta
742 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
743 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
744 stored_delta = TimeDelta::FromSeconds(0);
745 } else {
746 stored_delta = TimeDelta::FromInternalValue(stored_value);
747 }
748
749 // Sanity-check: Uptime can never be greater than the wall-clock
750 // difference (modulo some slack). If it is, report and reset
751 // to the wall-clock difference.
752 TimeDelta diff = GetUpdateDuration() - stored_delta;
753 if (diff < -kDurationSlack) {
754 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -0700755 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -0700756 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700757 << utils::FormatTimeDelta(diff)
758 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700759 stored_delta = update_duration_current_;
760 }
761
762 SetUpdateDurationUptime(stored_delta);
763}
764
Chris Sosabe45bef2013-04-09 18:25:12 -0700765void PayloadState::LoadNumReboots() {
766 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
767}
768
David Zeuthen9a017f22013-04-11 16:10:26 -0700769void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
770 const Time& timestamp,
771 bool use_logging) {
772 CHECK(prefs_);
773 update_duration_uptime_ = value;
774 update_duration_uptime_timestamp_ = timestamp;
775 prefs_->SetInt64(kPrefsUpdateDurationUptime,
776 update_duration_uptime_.ToInternalValue());
777 if (use_logging) {
778 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -0700779 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -0700780 }
781}
782
783void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -0700784 Time now = system_state_->clock()->GetMonotonicTime();
785 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -0700786}
787
788void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700789 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700790 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
791 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
792 // We're frequently called so avoid logging this write
793 SetUpdateDurationUptimeExtended(new_uptime, now, false);
794}
795
David Zeuthen674c3182013-04-18 14:05:20 -0700796void PayloadState::ReportDurationMetrics() {
797 TimeDelta duration = GetUpdateDuration();
798 TimeDelta duration_uptime = GetUpdateDurationUptime();
799 string metric;
800
801 metric = "Installer.UpdateDurationMinutes";
802 system_state_->metrics_lib()->SendToUMA(
803 metric,
804 static_cast<int>(duration.InMinutes()),
805 1, // min: 1 minute
806 365*24*60, // max: 1 year (approx)
807 kNumDefaultUmaBuckets);
808 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
809 << " for metric " << metric;
810
811 metric = "Installer.UpdateDurationUptimeMinutes";
812 system_state_->metrics_lib()->SendToUMA(
813 metric,
814 static_cast<int>(duration_uptime.InMinutes()),
815 1, // min: 1 minute
816 30*24*60, // max: 1 month (approx)
817 kNumDefaultUmaBuckets);
818 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
819 << " for metric " << metric;
820
821 prefs_->Delete(kPrefsUpdateTimestampStart);
822 prefs_->Delete(kPrefsUpdateDurationUptime);
823}
824
Jay Srinivasan19409b72013-04-12 19:23:36 -0700825string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
826 return prefix + "-from-" + utils::ToString(source);
827}
828
829void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
830 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
831 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
832}
833
834void PayloadState::SetCurrentBytesDownloaded(
835 DownloadSource source,
836 uint64_t current_bytes_downloaded,
837 bool log) {
838 CHECK(prefs_);
839
840 if (source >= kNumDownloadSources)
841 return;
842
843 // Update the in-memory value.
844 current_bytes_downloaded_[source] = current_bytes_downloaded;
845
846 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
847 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
848 LOG_IF(INFO, log) << "Current bytes downloaded for "
849 << utils::ToString(source) << " = "
850 << GetCurrentBytesDownloaded(source);
851}
852
853void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
854 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
855 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
856}
857
858void PayloadState::SetTotalBytesDownloaded(
859 DownloadSource source,
860 uint64_t total_bytes_downloaded,
861 bool log) {
862 CHECK(prefs_);
863
864 if (source >= kNumDownloadSources)
865 return;
866
867 // Update the in-memory value.
868 total_bytes_downloaded_[source] = total_bytes_downloaded;
869
870 // Persist.
871 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
872 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
873 LOG_IF(INFO, log) << "Total bytes downloaded for "
874 << utils::ToString(source) << " = "
875 << GetTotalBytesDownloaded(source);
876}
877
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800878} // namespace chromeos_update_engine