blob: bae21b9d821188ba4c96fd6dcdfdfbc833f937e5 [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
Jay Srinivasand29695d2013-04-08 15:08:05 -070013#include "update_engine/constants.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070014#include "update_engine/prefs.h"
15#include "update_engine/system_state.h"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080016#include "update_engine/utils.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080017
Jay Srinivasan08262882012-12-28 19:29:43 -080018using base::Time;
19using base::TimeDelta;
20using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080021using std::string;
22
23namespace chromeos_update_engine {
24
David Zeuthen9a017f22013-04-11 16:10:26 -070025const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
26
Jay Srinivasan08262882012-12-28 19:29:43 -080027// We want to upperbound backoffs to 16 days
28static const uint32_t kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080029
Jay Srinivasan08262882012-12-28 19:29:43 -080030// We want to randomize retry attempts after the backoff by +/- 6 hours.
31static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080032
Jay Srinivasan19409b72013-04-12 19:23:36 -070033PayloadState::PayloadState()
34 : prefs_(NULL),
35 payload_attempt_number_(0),
36 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070037 url_failure_count_(0),
38 url_switch_count_(0) {
Jay Srinivasan19409b72013-04-12 19:23:36 -070039 for (int i = 0; i <= kNumDownloadSources; i++)
40 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
41}
42
43bool PayloadState::Initialize(SystemState* system_state) {
44 system_state_ = system_state;
45 prefs_ = system_state_->prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080046 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080047 LoadPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080048 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080049 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070050 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080051 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070052 LoadUpdateTimestampStart();
53 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
54 // being called before it. Don't reorder.
55 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070056 for (int i = 0; i < kNumDownloadSources; i++) {
57 DownloadSource source = static_cast<DownloadSource>(i);
58 LoadCurrentBytesDownloaded(source);
59 LoadTotalBytesDownloaded(source);
60 }
Chris Sosabe45bef2013-04-09 18:25:12 -070061 LoadNumReboots();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080062 return true;
63}
64
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080065void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080066 // Always store the latest response.
67 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080068
Jay Srinivasan08262882012-12-28 19:29:43 -080069 // Check if the "signature" of this response (i.e. the fields we care about)
70 // has changed.
71 string new_response_signature = CalculateResponseSignature();
72 bool has_response_changed = (response_signature_ != new_response_signature);
73
74 // If the response has changed, we should persist the new signature and
75 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080076 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -080077 LOG(INFO) << "Resetting all persisted state as this is a new response";
78 SetResponseSignature(new_response_signature);
79 ResetPersistedState();
80 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080081 }
82
Jay Srinivasan08262882012-12-28 19:29:43 -080083 // This is the earliest point at which we can validate whether the URL index
84 // we loaded from the persisted state is a valid value. If the response
85 // hasn't changed but the URL index is invalid, it's indicative of some
86 // tampering of the persisted state.
87 if (url_index_ >= GetNumUrls()) {
88 LOG(INFO) << "Resetting all payload state as the url index seems to have "
89 "been tampered with";
90 ResetPersistedState();
91 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080092 }
Jay Srinivasan19409b72013-04-12 19:23:36 -070093
94 // Update the current download source which depends on the latest value of
95 // the response.
96 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080097}
98
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080099void PayloadState::DownloadComplete() {
100 LOG(INFO) << "Payload downloaded successfully";
101 IncrementPayloadAttemptNumber();
102}
103
104void PayloadState::DownloadProgress(size_t count) {
105 if (count == 0)
106 return;
107
David Zeuthen9a017f22013-04-11 16:10:26 -0700108 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700109 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700110
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800111 // We've received non-zero bytes from a recent download operation. Since our
112 // URL failure count is meant to penalize a URL only for consecutive
113 // failures, downloading bytes successfully means we should reset the failure
114 // count (as we know at least that the URL is working). In future, we can
115 // design this to be more sophisticated to check for more intelligent failure
116 // patterns, but right now, even 1 byte downloaded will mark the URL to be
117 // good unless it hits 10 (or configured number of) consecutive failures
118 // again.
119
120 if (GetUrlFailureCount() == 0)
121 return;
122
123 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
124 << " to 0 as we received " << count << " bytes successfully";
125 SetUrlFailureCount(0);
126}
127
Chris Sosabe45bef2013-04-09 18:25:12 -0700128void PayloadState::UpdateResumed() {
129 LOG(INFO) << "Resuming an update that was previously started.";
130 UpdateNumReboots();
131}
132
Jay Srinivasan19409b72013-04-12 19:23:36 -0700133void PayloadState::UpdateRestarted() {
134 LOG(INFO) << "Starting a new update";
135 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700136 SetNumReboots(0);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700137}
138
David Zeuthen9a017f22013-04-11 16:10:26 -0700139void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700140 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700141 CalculateUpdateDurationUptime();
142 SetUpdateTimestampEnd(Time::Now());
Jay Srinivasan19409b72013-04-12 19:23:36 -0700143 ReportBytesDownloadedMetrics();
David Zeuthencc6f9962013-04-18 11:57:24 -0700144 ReportUpdateUrlSwitchesMetric();
Chris Sosabe45bef2013-04-09 18:25:12 -0700145 ReportRebootMetrics();
David Zeuthen9a017f22013-04-11 16:10:26 -0700146}
147
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800148void PayloadState::UpdateFailed(ActionExitCode error) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800149 ActionExitCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800150 LOG(INFO) << "Updating payload state for error code: " << base_error
151 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800152
Jay Srinivasan08262882012-12-28 19:29:43 -0800153 if (GetNumUrls() == 0) {
154 // This means we got this error even before we got a valid Omaha response.
155 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800156 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
157 return;
158 }
159
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800160 switch (base_error) {
161 // Errors which are good indicators of a problem with a particular URL or
162 // the protocol used in the URL or entities in the communication channel
163 // (e.g. proxies). We should try the next available URL in the next update
164 // check to quickly recover from these errors.
165 case kActionCodePayloadHashMismatchError:
166 case kActionCodePayloadSizeMismatchError:
167 case kActionCodeDownloadPayloadVerificationError:
168 case kActionCodeDownloadPayloadPubKeyVerificationError:
169 case kActionCodeSignedDeltaPayloadExpectedError:
170 case kActionCodeDownloadInvalidMetadataMagicString:
171 case kActionCodeDownloadSignatureMissingInManifest:
172 case kActionCodeDownloadManifestParseError:
173 case kActionCodeDownloadMetadataSignatureError:
174 case kActionCodeDownloadMetadataSignatureVerificationError:
175 case kActionCodeDownloadMetadataSignatureMismatch:
176 case kActionCodeDownloadOperationHashVerificationError:
177 case kActionCodeDownloadOperationExecutionError:
178 case kActionCodeDownloadOperationHashMismatch:
179 case kActionCodeDownloadInvalidMetadataSize:
180 case kActionCodeDownloadInvalidMetadataSignature:
181 case kActionCodeDownloadOperationHashMissingError:
182 case kActionCodeDownloadMetadataSignatureMissingError:
183 IncrementUrlIndex();
184 break;
185
186 // Errors which seem to be just transient network/communication related
187 // failures and do not indicate any inherent problem with the URL itself.
188 // So, we should keep the current URL but just increment the
189 // failure count to give it more chances. This way, while we maximize our
190 // chances of downloading from the URLs that appear earlier in the response
191 // (because download from a local server URL that appears earlier in a
192 // response is preferable than downloading from the next URL which could be
193 // a internet URL and thus could be more expensive).
194 case kActionCodeError:
195 case kActionCodeDownloadTransferError:
196 case kActionCodeDownloadWriteError:
197 case kActionCodeDownloadStateInitializationError:
198 case kActionCodeOmahaErrorInHTTPResponse: // Aggregate code for HTTP errors.
199 IncrementFailureCount();
200 break;
201
202 // Errors which are not specific to a URL and hence shouldn't result in
203 // the URL being penalized. This can happen in two cases:
204 // 1. We haven't started downloading anything: These errors don't cost us
205 // anything in terms of actual payload bytes, so we should just do the
206 // regular retries at the next update check.
207 // 2. We have successfully downloaded the payload: In this case, the
208 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800209 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800210 // In either case, there's no need to update URL index or failure count.
211 case kActionCodeOmahaRequestError:
212 case kActionCodeOmahaResponseHandlerError:
213 case kActionCodePostinstallRunnerError:
214 case kActionCodeFilesystemCopierError:
215 case kActionCodeInstallDeviceOpenError:
216 case kActionCodeKernelDeviceOpenError:
217 case kActionCodeDownloadNewPartitionInfoError:
218 case kActionCodeNewRootfsVerificationError:
219 case kActionCodeNewKernelVerificationError:
220 case kActionCodePostinstallBootedFromFirmwareB:
221 case kActionCodeOmahaRequestEmptyResponseError:
222 case kActionCodeOmahaRequestXMLParseError:
223 case kActionCodeOmahaResponseInvalid:
224 case kActionCodeOmahaUpdateIgnoredPerPolicy:
225 case kActionCodeOmahaUpdateDeferredPerPolicy:
Jay Srinivasan08262882012-12-28 19:29:43 -0800226 case kActionCodeOmahaUpdateDeferredForBackoff:
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700227 case kActionCodePostinstallPowerwashError:
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700228 case kActionCodeUpdateCanceledByChannelChange:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800229 LOG(INFO) << "Not incrementing URL index or failure count for this error";
230 break;
231
232 case kActionCodeSuccess: // success code
233 case kActionCodeSetBootableFlagError: // unused
234 case kActionCodeUmaReportedMax: // not an error code
235 case kActionCodeOmahaRequestHTTPResponseBase: // aggregated already
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800236 case kActionCodeDevModeFlag: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800237 case kActionCodeResumedFlag: // not an error code
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800238 case kActionCodeTestImageFlag: // not an error code
239 case kActionCodeTestOmahaUrlFlag: // not an error code
240 case kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800241 // These shouldn't happen. Enumerating these explicitly here so that we
242 // can let the compiler warn about new error codes that are added to
243 // action_processor.h but not added here.
244 LOG(WARNING) << "Unexpected error code for UpdateFailed";
245 break;
246
247 // Note: Not adding a default here so as to let the compiler warn us of
248 // any new enums that were added in the .h but not listed in this switch.
249 }
250}
251
Jay Srinivasan08262882012-12-28 19:29:43 -0800252bool PayloadState::ShouldBackoffDownload() {
253 if (response_.disable_payload_backoff) {
254 LOG(INFO) << "Payload backoff logic is disabled. "
255 "Can proceed with the download";
256 return false;
257 }
258
259 if (response_.is_delta_payload) {
260 // If delta payloads fail, we want to fallback quickly to full payloads as
261 // they are more likely to succeed. Exponential backoffs would greatly
262 // slow down the fallback to full payloads. So we don't backoff for delta
263 // payloads.
264 LOG(INFO) << "No backoffs for delta payloads. "
265 << "Can proceed with the download";
266 return false;
267 }
268
269 if (!utils::IsOfficialBuild()) {
270 // Backoffs are needed only for official builds. We do not want any delays
271 // or update failures due to backoffs during testing or development.
272 LOG(INFO) << "No backoffs for test/dev images. "
273 << "Can proceed with the download";
274 return false;
275 }
276
277 if (backoff_expiry_time_.is_null()) {
278 LOG(INFO) << "No backoff expiry time has been set. "
279 << "Can proceed with the download";
280 return false;
281 }
282
283 if (backoff_expiry_time_ < Time::Now()) {
284 LOG(INFO) << "The backoff expiry time ("
285 << utils::ToString(backoff_expiry_time_)
286 << ") has elapsed. Can proceed with the download";
287 return false;
288 }
289
290 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
291 << utils::ToString(backoff_expiry_time_);
292 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800293}
294
295void PayloadState::IncrementPayloadAttemptNumber() {
Jay Srinivasan08262882012-12-28 19:29:43 -0800296 if (response_.is_delta_payload) {
297 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
298 return;
299 }
300
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800301 LOG(INFO) << "Incrementing the payload attempt number";
302 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800303 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800304}
305
306void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800307 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800308 if (next_url_index < GetNumUrls()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800309 LOG(INFO) << "Incrementing the URL index for next attempt";
310 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800311 } else {
312 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan08262882012-12-28 19:29:43 -0800313 << "0 as we only have " << GetNumUrls() << " URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800314 SetUrlIndex(0);
315 IncrementPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800316 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800317
David Zeuthencc6f9962013-04-18 11:57:24 -0700318 // If we have multiple URLs, record that we just switched to another one
319 if (GetNumUrls() > 1)
320 SetUrlSwitchCount(url_switch_count_ + 1);
321
Jay Srinivasan08262882012-12-28 19:29:43 -0800322 // Whenever we update the URL index, we should also clear the URL failure
323 // count so we can start over fresh for the new URL.
324 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800325}
326
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800327void PayloadState::IncrementFailureCount() {
328 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800329 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800330 LOG(INFO) << "Incrementing the URL failure count";
331 SetUrlFailureCount(next_url_failure_count);
332 } else {
333 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
334 << ". Trying next available URL";
335 IncrementUrlIndex();
336 }
337}
338
Jay Srinivasan08262882012-12-28 19:29:43 -0800339void PayloadState::UpdateBackoffExpiryTime() {
340 if (response_.disable_payload_backoff) {
341 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
342 SetBackoffExpiryTime(Time());
343 return;
344 }
345
346 if (GetPayloadAttemptNumber() == 0) {
347 SetBackoffExpiryTime(Time());
348 return;
349 }
350
351 // Since we're doing left-shift below, make sure we don't shift more
352 // than this. E.g. if uint32_t is 4-bytes, don't left-shift more than 30 bits,
353 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
354 uint32_t num_days = 1; // the value to be shifted.
355 const uint32_t kMaxShifts = (sizeof(num_days) * 8) - 2;
356
357 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
358 // E.g. if payload_attempt_number is over 30, limit power to 30.
359 uint32_t power = min(GetPayloadAttemptNumber() - 1, kMaxShifts);
360
361 // The number of days is the minimum of 2 raised to (payload_attempt_number
362 // - 1) or kMaxBackoffDays.
363 num_days = min(num_days << power, kMaxBackoffDays);
364
365 // We don't want all retries to happen exactly at the same time when
366 // retrying after backoff. So add some random minutes to fuzz.
367 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
368 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
369 TimeDelta::FromMinutes(fuzz_minutes);
370 LOG(INFO) << "Incrementing the backoff expiry time by "
371 << utils::FormatTimeDelta(next_backoff_interval);
372 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
373}
374
Jay Srinivasan19409b72013-04-12 19:23:36 -0700375void PayloadState::UpdateCurrentDownloadSource() {
376 current_download_source_ = kNumDownloadSources;
377
378 if (GetUrlIndex() < response_.payload_urls.size()) {
379 string current_url = response_.payload_urls[GetUrlIndex()];
380 if (StartsWithASCII(current_url, "https://", false))
381 current_download_source_ = kDownloadSourceHttpsServer;
382 else if (StartsWithASCII(current_url, "http://", false))
383 current_download_source_ = kDownloadSourceHttpServer;
384 }
385
386 LOG(INFO) << "Current download source: "
387 << utils::ToString(current_download_source_);
388}
389
390void PayloadState::UpdateBytesDownloaded(size_t count) {
391 SetCurrentBytesDownloaded(
392 current_download_source_,
393 GetCurrentBytesDownloaded(current_download_source_) + count,
394 false);
395 SetTotalBytesDownloaded(
396 current_download_source_,
397 GetTotalBytesDownloaded(current_download_source_) + count,
398 false);
399}
400
401void PayloadState::ReportBytesDownloadedMetrics() {
402 // Report metrics collected from all known download sources to UMA.
403 // The reported data is in Megabytes in order to represent a larger
404 // sample range.
405 for (int i = 0; i < kNumDownloadSources; i++) {
406 DownloadSource source = static_cast<DownloadSource>(i);
407 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
408
409 string metric = "Installer.SuccessfulMBsDownloadedFrom" +
410 utils::ToString(source);
411 uint64_t mbs = GetCurrentBytesDownloaded(source) / kNumBytesInOneMiB;
412 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
413 system_state_->metrics_lib()->SendToUMA(metric,
414 mbs,
415 0, // min
416 kMaxMiBs,
417 kNumDefaultUmaBuckets);
418 SetCurrentBytesDownloaded(source, 0, true);
419
420 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
421 mbs = GetTotalBytesDownloaded(source) / kNumBytesInOneMiB;
422 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
423 system_state_->metrics_lib()->SendToUMA(metric,
424 mbs,
425 0, // min
426 kMaxMiBs,
427 kNumDefaultUmaBuckets);
428
429 SetTotalBytesDownloaded(source, 0, true);
430 }
431}
432
David Zeuthencc6f9962013-04-18 11:57:24 -0700433void PayloadState::ReportUpdateUrlSwitchesMetric() {
434 string metric = "Installer.UpdateURLSwitches";
435 int value = static_cast<int>(url_switch_count_);
436
437 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
438 system_state_->metrics_lib()->SendToUMA(
439 metric,
440 value,
441 0, // min value
442 100, // max value
443 kNumDefaultUmaBuckets);
444}
445
Chris Sosabe45bef2013-04-09 18:25:12 -0700446void PayloadState::ReportRebootMetrics() {
447 // Report the number of num_reboots.
448 string metric = "Installer.UpdateNumReboots";
449 uint32_t num_reboots = GetNumReboots();
450 LOG(INFO) << "Uploading reboot count of " << num_reboots << " for metric "
451 << metric;
452 system_state_->metrics_lib()->SendToUMA(
453 metric,
454 static_cast<int>(num_reboots), // sample
455 0, // min = 0.
456 50, // max
457 25); // buckets
458 SetNumReboots(0);
459}
460
461void PayloadState::UpdateNumReboots() {
462 // We only update the reboot count when the system has been detected to have
463 // been rebooted.
464 if (!system_state_->system_rebooted()) {
465 return;
466 }
467
468 SetNumReboots(GetNumReboots() + 1);
469}
470
471void PayloadState::SetNumReboots(uint32_t num_reboots) {
472 CHECK(prefs_);
473 num_reboots_ = num_reboots;
474 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
475 LOG(INFO) << "Number of Reboots during current update attempt = "
476 << num_reboots_;
477}
478
Jay Srinivasan08262882012-12-28 19:29:43 -0800479void PayloadState::ResetPersistedState() {
480 SetPayloadAttemptNumber(0);
481 SetUrlIndex(0);
482 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700483 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800484 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthen9a017f22013-04-11 16:10:26 -0700485 SetUpdateTimestampStart(Time::Now());
486 SetUpdateTimestampEnd(Time()); // Set to null time
487 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700488 ResetDownloadSourcesOnNewUpdate();
489}
490
491void PayloadState::ResetDownloadSourcesOnNewUpdate() {
492 for (int i = 0; i < kNumDownloadSources; i++) {
493 DownloadSource source = static_cast<DownloadSource>(i);
494 SetCurrentBytesDownloaded(source, 0, true);
495 // Note: Not resetting the TotalBytesDownloaded as we want that metric
496 // to count the bytes downloaded across various update attempts until
497 // we have successfully applied the update.
498 }
499}
500
501int64_t PayloadState::GetPersistedValue(const string& key) {
502 CHECK(prefs_);
503 if (!prefs_->Exists(key))
504 return 0;
505
506 int64_t stored_value;
507 if (!prefs_->GetInt64(key, &stored_value))
508 return 0;
509
510 if (stored_value < 0) {
511 LOG(ERROR) << key << ": Invalid value (" << stored_value
512 << ") in persisted state. Defaulting to 0";
513 return 0;
514 }
515
516 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800517}
518
519string PayloadState::CalculateResponseSignature() {
520 string response_sign = StringPrintf("NumURLs = %d\n",
521 response_.payload_urls.size());
522
523 for (size_t i = 0; i < response_.payload_urls.size(); i++)
524 response_sign += StringPrintf("Url%d = %s\n",
525 i, response_.payload_urls[i].c_str());
526
527 response_sign += StringPrintf("Payload Size = %llu\n"
528 "Payload Sha256 Hash = %s\n"
529 "Metadata Size = %llu\n"
530 "Metadata Signature = %s\n"
531 "Is Delta Payload = %d\n"
532 "Max Failure Count Per Url = %d\n"
533 "Disable Payload Backoff = %d\n",
534 response_.size,
535 response_.hash.c_str(),
536 response_.metadata_size,
537 response_.metadata_signature.c_str(),
538 response_.is_delta_payload,
539 response_.max_failure_count_per_url,
540 response_.disable_payload_backoff);
541 return response_sign;
542}
543
544void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800545 CHECK(prefs_);
546 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800547 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
548 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
549 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800550 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800551}
552
Jay Srinivasan19409b72013-04-12 19:23:36 -0700553void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800554 CHECK(prefs_);
555 response_signature_ = response_signature;
556 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
557 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
558}
559
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800560void PayloadState::LoadPayloadAttemptNumber() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700561 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800562}
563
564void PayloadState::SetPayloadAttemptNumber(uint32_t payload_attempt_number) {
565 CHECK(prefs_);
566 payload_attempt_number_ = payload_attempt_number;
567 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
568 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
569}
570
571void PayloadState::LoadUrlIndex() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700572 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800573}
574
575void PayloadState::SetUrlIndex(uint32_t url_index) {
576 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800577 url_index_ = url_index;
578 LOG(INFO) << "Current URL Index = " << url_index_;
579 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700580
581 // Also update the download source, which is purely dependent on the
582 // current URL index alone.
583 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800584}
585
David Zeuthencc6f9962013-04-18 11:57:24 -0700586void PayloadState::LoadUrlSwitchCount() {
587 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
588}
589
590void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
591 CHECK(prefs_);
592 url_switch_count_ = url_switch_count;
593 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
594 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
595}
596
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800597void PayloadState::LoadUrlFailureCount() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700598 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800599}
600
601void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
602 CHECK(prefs_);
603 url_failure_count_ = url_failure_count;
604 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
605 << ")'s Failure Count = " << url_failure_count_;
606 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800607}
608
Jay Srinivasan08262882012-12-28 19:29:43 -0800609void PayloadState::LoadBackoffExpiryTime() {
610 CHECK(prefs_);
611 int64_t stored_value;
612 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
613 return;
614
615 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
616 return;
617
618 Time stored_time = Time::FromInternalValue(stored_value);
619 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
620 LOG(ERROR) << "Invalid backoff expiry time ("
621 << utils::ToString(stored_time)
622 << ") in persisted state. Resetting.";
623 stored_time = Time();
624 }
625 SetBackoffExpiryTime(stored_time);
626}
627
628void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
629 CHECK(prefs_);
630 backoff_expiry_time_ = new_time;
631 LOG(INFO) << "Backoff Expiry Time = "
632 << utils::ToString(backoff_expiry_time_);
633 prefs_->SetInt64(kPrefsBackoffExpiryTime,
634 backoff_expiry_time_.ToInternalValue());
635}
636
David Zeuthen9a017f22013-04-11 16:10:26 -0700637TimeDelta PayloadState::GetUpdateDuration() {
638 Time end_time = update_timestamp_end_.is_null() ? Time::Now() :
639 update_timestamp_end_;
640 return end_time - update_timestamp_start_;
641}
642
643void PayloadState::LoadUpdateTimestampStart() {
644 int64_t stored_value;
645 Time stored_time;
646
647 CHECK(prefs_);
648
649 Time now = Time::Now();
650
651 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
652 // The preference missing is not unexpected - in that case, just
653 // use the current time as start time
654 stored_time = now;
655 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
656 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
657 stored_time = now;
658 } else {
659 stored_time = Time::FromInternalValue(stored_value);
660 }
661
662 // Sanity check: If the time read from disk is in the future
663 // (modulo some slack to account for possible NTP drift
664 // adjustments), something is fishy and we should report and
665 // reset.
666 TimeDelta duration_according_to_stored_time = now - stored_time;
667 if (duration_according_to_stored_time < -kDurationSlack) {
668 LOG(ERROR) << "The UpdateTimestampStart value ("
669 << utils::ToString(stored_time)
670 << ") in persisted state is "
671 << duration_according_to_stored_time.InSeconds()
672 << " seconds in the future. Resetting.";
673 stored_time = now;
674 }
675
676 SetUpdateTimestampStart(stored_time);
677}
678
679void PayloadState::SetUpdateTimestampStart(const Time& value) {
680 CHECK(prefs_);
681 update_timestamp_start_ = value;
682 prefs_->SetInt64(kPrefsUpdateTimestampStart,
683 update_timestamp_start_.ToInternalValue());
684 LOG(INFO) << "Update Timestamp Start = "
685 << utils::ToString(update_timestamp_start_);
686}
687
688void PayloadState::SetUpdateTimestampEnd(const Time& value) {
689 update_timestamp_end_ = value;
690 LOG(INFO) << "Update Timestamp End = "
691 << utils::ToString(update_timestamp_end_);
692}
693
694TimeDelta PayloadState::GetUpdateDurationUptime() {
695 return update_duration_uptime_;
696}
697
698void PayloadState::LoadUpdateDurationUptime() {
699 int64_t stored_value;
700 TimeDelta stored_delta;
701
702 CHECK(prefs_);
703
704 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
705 // The preference missing is not unexpected - in that case, just
706 // we'll use zero as the delta
707 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
708 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
709 stored_delta = TimeDelta::FromSeconds(0);
710 } else {
711 stored_delta = TimeDelta::FromInternalValue(stored_value);
712 }
713
714 // Sanity-check: Uptime can never be greater than the wall-clock
715 // difference (modulo some slack). If it is, report and reset
716 // to the wall-clock difference.
717 TimeDelta diff = GetUpdateDuration() - stored_delta;
718 if (diff < -kDurationSlack) {
719 LOG(ERROR) << "The UpdateDurationUptime value ("
720 << stored_delta.InSeconds() << " seconds"
721 << ") in persisted state is "
722 << diff.InSeconds()
723 << " seconds larger than the wall-clock delta. Resetting.";
724 stored_delta = update_duration_current_;
725 }
726
727 SetUpdateDurationUptime(stored_delta);
728}
729
Chris Sosabe45bef2013-04-09 18:25:12 -0700730void PayloadState::LoadNumReboots() {
731 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
732}
733
David Zeuthen9a017f22013-04-11 16:10:26 -0700734void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
735 const Time& timestamp,
736 bool use_logging) {
737 CHECK(prefs_);
738 update_duration_uptime_ = value;
739 update_duration_uptime_timestamp_ = timestamp;
740 prefs_->SetInt64(kPrefsUpdateDurationUptime,
741 update_duration_uptime_.ToInternalValue());
742 if (use_logging) {
743 LOG(INFO) << "Update Duration Uptime = "
744 << update_duration_uptime_.InSeconds()
745 << " seconds";
746 }
747}
748
749void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
750 SetUpdateDurationUptimeExtended(value, utils::GetMonotonicTime(), true);
751}
752
753void PayloadState::CalculateUpdateDurationUptime() {
754 Time now = utils::GetMonotonicTime();
755 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
756 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
757 // We're frequently called so avoid logging this write
758 SetUpdateDurationUptimeExtended(new_uptime, now, false);
759}
760
Jay Srinivasan19409b72013-04-12 19:23:36 -0700761string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
762 return prefix + "-from-" + utils::ToString(source);
763}
764
765void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
766 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
767 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
768}
769
770void PayloadState::SetCurrentBytesDownloaded(
771 DownloadSource source,
772 uint64_t current_bytes_downloaded,
773 bool log) {
774 CHECK(prefs_);
775
776 if (source >= kNumDownloadSources)
777 return;
778
779 // Update the in-memory value.
780 current_bytes_downloaded_[source] = current_bytes_downloaded;
781
782 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
783 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
784 LOG_IF(INFO, log) << "Current bytes downloaded for "
785 << utils::ToString(source) << " = "
786 << GetCurrentBytesDownloaded(source);
787}
788
789void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
790 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
791 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
792}
793
794void PayloadState::SetTotalBytesDownloaded(
795 DownloadSource source,
796 uint64_t total_bytes_downloaded,
797 bool log) {
798 CHECK(prefs_);
799
800 if (source >= kNumDownloadSources)
801 return;
802
803 // Update the in-memory value.
804 total_bytes_downloaded_[source] = total_bytes_downloaded;
805
806 // Persist.
807 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
808 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
809 LOG_IF(INFO, log) << "Total bytes downloaded for "
810 << utils::ToString(source) << " = "
811 << GetTotalBytesDownloaded(source);
812}
813
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800814} // namespace chromeos_update_engine