blob: 2a26722e136f7018ef1402a623e1a18fce4b44b4 [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 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080061 return true;
62}
63
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080064void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080065 // Always store the latest response.
66 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080067
Jay Srinivasan08262882012-12-28 19:29:43 -080068 // Check if the "signature" of this response (i.e. the fields we care about)
69 // has changed.
70 string new_response_signature = CalculateResponseSignature();
71 bool has_response_changed = (response_signature_ != new_response_signature);
72
73 // If the response has changed, we should persist the new signature and
74 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080075 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -080076 LOG(INFO) << "Resetting all persisted state as this is a new response";
77 SetResponseSignature(new_response_signature);
78 ResetPersistedState();
79 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080080 }
81
Jay Srinivasan08262882012-12-28 19:29:43 -080082 // This is the earliest point at which we can validate whether the URL index
83 // we loaded from the persisted state is a valid value. If the response
84 // hasn't changed but the URL index is invalid, it's indicative of some
85 // tampering of the persisted state.
86 if (url_index_ >= GetNumUrls()) {
87 LOG(INFO) << "Resetting all payload state as the url index seems to have "
88 "been tampered with";
89 ResetPersistedState();
90 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080091 }
Jay Srinivasan19409b72013-04-12 19:23:36 -070092
93 // Update the current download source which depends on the latest value of
94 // the response.
95 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080096}
97
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080098void PayloadState::DownloadComplete() {
99 LOG(INFO) << "Payload downloaded successfully";
100 IncrementPayloadAttemptNumber();
101}
102
103void PayloadState::DownloadProgress(size_t count) {
104 if (count == 0)
105 return;
106
David Zeuthen9a017f22013-04-11 16:10:26 -0700107 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700108 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700109
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800110 // We've received non-zero bytes from a recent download operation. Since our
111 // URL failure count is meant to penalize a URL only for consecutive
112 // failures, downloading bytes successfully means we should reset the failure
113 // count (as we know at least that the URL is working). In future, we can
114 // design this to be more sophisticated to check for more intelligent failure
115 // patterns, but right now, even 1 byte downloaded will mark the URL to be
116 // good unless it hits 10 (or configured number of) consecutive failures
117 // again.
118
119 if (GetUrlFailureCount() == 0)
120 return;
121
122 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
123 << " to 0 as we received " << count << " bytes successfully";
124 SetUrlFailureCount(0);
125}
126
Jay Srinivasan19409b72013-04-12 19:23:36 -0700127void PayloadState::UpdateRestarted() {
128 LOG(INFO) << "Starting a new update";
129 ResetDownloadSourcesOnNewUpdate();
130}
131
David Zeuthen9a017f22013-04-11 16:10:26 -0700132void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700133 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700134 CalculateUpdateDurationUptime();
135 SetUpdateTimestampEnd(Time::Now());
Jay Srinivasan19409b72013-04-12 19:23:36 -0700136 ReportBytesDownloadedMetrics();
David Zeuthencc6f9962013-04-18 11:57:24 -0700137 ReportUpdateUrlSwitchesMetric();
David Zeuthen9a017f22013-04-11 16:10:26 -0700138}
139
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800140void PayloadState::UpdateFailed(ActionExitCode error) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800141 ActionExitCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800142 LOG(INFO) << "Updating payload state for error code: " << base_error
143 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800144
Jay Srinivasan08262882012-12-28 19:29:43 -0800145 if (GetNumUrls() == 0) {
146 // This means we got this error even before we got a valid Omaha response.
147 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800148 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
149 return;
150 }
151
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800152 switch (base_error) {
153 // Errors which are good indicators of a problem with a particular URL or
154 // the protocol used in the URL or entities in the communication channel
155 // (e.g. proxies). We should try the next available URL in the next update
156 // check to quickly recover from these errors.
157 case kActionCodePayloadHashMismatchError:
158 case kActionCodePayloadSizeMismatchError:
159 case kActionCodeDownloadPayloadVerificationError:
160 case kActionCodeDownloadPayloadPubKeyVerificationError:
161 case kActionCodeSignedDeltaPayloadExpectedError:
162 case kActionCodeDownloadInvalidMetadataMagicString:
163 case kActionCodeDownloadSignatureMissingInManifest:
164 case kActionCodeDownloadManifestParseError:
165 case kActionCodeDownloadMetadataSignatureError:
166 case kActionCodeDownloadMetadataSignatureVerificationError:
167 case kActionCodeDownloadMetadataSignatureMismatch:
168 case kActionCodeDownloadOperationHashVerificationError:
169 case kActionCodeDownloadOperationExecutionError:
170 case kActionCodeDownloadOperationHashMismatch:
171 case kActionCodeDownloadInvalidMetadataSize:
172 case kActionCodeDownloadInvalidMetadataSignature:
173 case kActionCodeDownloadOperationHashMissingError:
174 case kActionCodeDownloadMetadataSignatureMissingError:
175 IncrementUrlIndex();
176 break;
177
178 // Errors which seem to be just transient network/communication related
179 // failures and do not indicate any inherent problem with the URL itself.
180 // So, we should keep the current URL but just increment the
181 // failure count to give it more chances. This way, while we maximize our
182 // chances of downloading from the URLs that appear earlier in the response
183 // (because download from a local server URL that appears earlier in a
184 // response is preferable than downloading from the next URL which could be
185 // a internet URL and thus could be more expensive).
186 case kActionCodeError:
187 case kActionCodeDownloadTransferError:
188 case kActionCodeDownloadWriteError:
189 case kActionCodeDownloadStateInitializationError:
190 case kActionCodeOmahaErrorInHTTPResponse: // Aggregate code for HTTP errors.
191 IncrementFailureCount();
192 break;
193
194 // Errors which are not specific to a URL and hence shouldn't result in
195 // the URL being penalized. This can happen in two cases:
196 // 1. We haven't started downloading anything: These errors don't cost us
197 // anything in terms of actual payload bytes, so we should just do the
198 // regular retries at the next update check.
199 // 2. We have successfully downloaded the payload: In this case, the
200 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800201 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800202 // In either case, there's no need to update URL index or failure count.
203 case kActionCodeOmahaRequestError:
204 case kActionCodeOmahaResponseHandlerError:
205 case kActionCodePostinstallRunnerError:
206 case kActionCodeFilesystemCopierError:
207 case kActionCodeInstallDeviceOpenError:
208 case kActionCodeKernelDeviceOpenError:
209 case kActionCodeDownloadNewPartitionInfoError:
210 case kActionCodeNewRootfsVerificationError:
211 case kActionCodeNewKernelVerificationError:
212 case kActionCodePostinstallBootedFromFirmwareB:
213 case kActionCodeOmahaRequestEmptyResponseError:
214 case kActionCodeOmahaRequestXMLParseError:
215 case kActionCodeOmahaResponseInvalid:
216 case kActionCodeOmahaUpdateIgnoredPerPolicy:
217 case kActionCodeOmahaUpdateDeferredPerPolicy:
Jay Srinivasan08262882012-12-28 19:29:43 -0800218 case kActionCodeOmahaUpdateDeferredForBackoff:
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700219 case kActionCodePostinstallPowerwashError:
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700220 case kActionCodeUpdateCanceledByChannelChange:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800221 LOG(INFO) << "Not incrementing URL index or failure count for this error";
222 break;
223
224 case kActionCodeSuccess: // success code
225 case kActionCodeSetBootableFlagError: // unused
226 case kActionCodeUmaReportedMax: // not an error code
227 case kActionCodeOmahaRequestHTTPResponseBase: // aggregated already
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800228 case kActionCodeDevModeFlag: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800229 case kActionCodeResumedFlag: // not an error code
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800230 case kActionCodeTestImageFlag: // not an error code
231 case kActionCodeTestOmahaUrlFlag: // not an error code
232 case kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800233 // These shouldn't happen. Enumerating these explicitly here so that we
234 // can let the compiler warn about new error codes that are added to
235 // action_processor.h but not added here.
236 LOG(WARNING) << "Unexpected error code for UpdateFailed";
237 break;
238
239 // Note: Not adding a default here so as to let the compiler warn us of
240 // any new enums that were added in the .h but not listed in this switch.
241 }
242}
243
Jay Srinivasan08262882012-12-28 19:29:43 -0800244bool PayloadState::ShouldBackoffDownload() {
245 if (response_.disable_payload_backoff) {
246 LOG(INFO) << "Payload backoff logic is disabled. "
247 "Can proceed with the download";
248 return false;
249 }
250
251 if (response_.is_delta_payload) {
252 // If delta payloads fail, we want to fallback quickly to full payloads as
253 // they are more likely to succeed. Exponential backoffs would greatly
254 // slow down the fallback to full payloads. So we don't backoff for delta
255 // payloads.
256 LOG(INFO) << "No backoffs for delta payloads. "
257 << "Can proceed with the download";
258 return false;
259 }
260
261 if (!utils::IsOfficialBuild()) {
262 // Backoffs are needed only for official builds. We do not want any delays
263 // or update failures due to backoffs during testing or development.
264 LOG(INFO) << "No backoffs for test/dev images. "
265 << "Can proceed with the download";
266 return false;
267 }
268
269 if (backoff_expiry_time_.is_null()) {
270 LOG(INFO) << "No backoff expiry time has been set. "
271 << "Can proceed with the download";
272 return false;
273 }
274
275 if (backoff_expiry_time_ < Time::Now()) {
276 LOG(INFO) << "The backoff expiry time ("
277 << utils::ToString(backoff_expiry_time_)
278 << ") has elapsed. Can proceed with the download";
279 return false;
280 }
281
282 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
283 << utils::ToString(backoff_expiry_time_);
284 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800285}
286
287void PayloadState::IncrementPayloadAttemptNumber() {
Jay Srinivasan08262882012-12-28 19:29:43 -0800288 if (response_.is_delta_payload) {
289 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
290 return;
291 }
292
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800293 LOG(INFO) << "Incrementing the payload attempt number";
294 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800295 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800296}
297
298void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800299 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800300 if (next_url_index < GetNumUrls()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800301 LOG(INFO) << "Incrementing the URL index for next attempt";
302 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800303 } else {
304 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan08262882012-12-28 19:29:43 -0800305 << "0 as we only have " << GetNumUrls() << " URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800306 SetUrlIndex(0);
307 IncrementPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800308 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800309
David Zeuthencc6f9962013-04-18 11:57:24 -0700310 // If we have multiple URLs, record that we just switched to another one
311 if (GetNumUrls() > 1)
312 SetUrlSwitchCount(url_switch_count_ + 1);
313
Jay Srinivasan08262882012-12-28 19:29:43 -0800314 // Whenever we update the URL index, we should also clear the URL failure
315 // count so we can start over fresh for the new URL.
316 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800317}
318
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800319void PayloadState::IncrementFailureCount() {
320 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800321 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800322 LOG(INFO) << "Incrementing the URL failure count";
323 SetUrlFailureCount(next_url_failure_count);
324 } else {
325 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
326 << ". Trying next available URL";
327 IncrementUrlIndex();
328 }
329}
330
Jay Srinivasan08262882012-12-28 19:29:43 -0800331void PayloadState::UpdateBackoffExpiryTime() {
332 if (response_.disable_payload_backoff) {
333 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
334 SetBackoffExpiryTime(Time());
335 return;
336 }
337
338 if (GetPayloadAttemptNumber() == 0) {
339 SetBackoffExpiryTime(Time());
340 return;
341 }
342
343 // Since we're doing left-shift below, make sure we don't shift more
344 // than this. E.g. if uint32_t is 4-bytes, don't left-shift more than 30 bits,
345 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
346 uint32_t num_days = 1; // the value to be shifted.
347 const uint32_t kMaxShifts = (sizeof(num_days) * 8) - 2;
348
349 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
350 // E.g. if payload_attempt_number is over 30, limit power to 30.
351 uint32_t power = min(GetPayloadAttemptNumber() - 1, kMaxShifts);
352
353 // The number of days is the minimum of 2 raised to (payload_attempt_number
354 // - 1) or kMaxBackoffDays.
355 num_days = min(num_days << power, kMaxBackoffDays);
356
357 // We don't want all retries to happen exactly at the same time when
358 // retrying after backoff. So add some random minutes to fuzz.
359 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
360 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
361 TimeDelta::FromMinutes(fuzz_minutes);
362 LOG(INFO) << "Incrementing the backoff expiry time by "
363 << utils::FormatTimeDelta(next_backoff_interval);
364 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
365}
366
Jay Srinivasan19409b72013-04-12 19:23:36 -0700367void PayloadState::UpdateCurrentDownloadSource() {
368 current_download_source_ = kNumDownloadSources;
369
370 if (GetUrlIndex() < response_.payload_urls.size()) {
371 string current_url = response_.payload_urls[GetUrlIndex()];
372 if (StartsWithASCII(current_url, "https://", false))
373 current_download_source_ = kDownloadSourceHttpsServer;
374 else if (StartsWithASCII(current_url, "http://", false))
375 current_download_source_ = kDownloadSourceHttpServer;
376 }
377
378 LOG(INFO) << "Current download source: "
379 << utils::ToString(current_download_source_);
380}
381
382void PayloadState::UpdateBytesDownloaded(size_t count) {
383 SetCurrentBytesDownloaded(
384 current_download_source_,
385 GetCurrentBytesDownloaded(current_download_source_) + count,
386 false);
387 SetTotalBytesDownloaded(
388 current_download_source_,
389 GetTotalBytesDownloaded(current_download_source_) + count,
390 false);
391}
392
393void PayloadState::ReportBytesDownloadedMetrics() {
394 // Report metrics collected from all known download sources to UMA.
395 // The reported data is in Megabytes in order to represent a larger
396 // sample range.
397 for (int i = 0; i < kNumDownloadSources; i++) {
398 DownloadSource source = static_cast<DownloadSource>(i);
399 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
400
401 string metric = "Installer.SuccessfulMBsDownloadedFrom" +
402 utils::ToString(source);
403 uint64_t mbs = GetCurrentBytesDownloaded(source) / kNumBytesInOneMiB;
404 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
405 system_state_->metrics_lib()->SendToUMA(metric,
406 mbs,
407 0, // min
408 kMaxMiBs,
409 kNumDefaultUmaBuckets);
410 SetCurrentBytesDownloaded(source, 0, true);
411
412 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
413 mbs = GetTotalBytesDownloaded(source) / kNumBytesInOneMiB;
414 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
415 system_state_->metrics_lib()->SendToUMA(metric,
416 mbs,
417 0, // min
418 kMaxMiBs,
419 kNumDefaultUmaBuckets);
420
421 SetTotalBytesDownloaded(source, 0, true);
422 }
423}
424
David Zeuthencc6f9962013-04-18 11:57:24 -0700425void PayloadState::ReportUpdateUrlSwitchesMetric() {
426 string metric = "Installer.UpdateURLSwitches";
427 int value = static_cast<int>(url_switch_count_);
428
429 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
430 system_state_->metrics_lib()->SendToUMA(
431 metric,
432 value,
433 0, // min value
434 100, // max value
435 kNumDefaultUmaBuckets);
436}
437
Jay Srinivasan08262882012-12-28 19:29:43 -0800438void PayloadState::ResetPersistedState() {
439 SetPayloadAttemptNumber(0);
440 SetUrlIndex(0);
441 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700442 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800443 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthen9a017f22013-04-11 16:10:26 -0700444 SetUpdateTimestampStart(Time::Now());
445 SetUpdateTimestampEnd(Time()); // Set to null time
446 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700447 ResetDownloadSourcesOnNewUpdate();
448}
449
450void PayloadState::ResetDownloadSourcesOnNewUpdate() {
451 for (int i = 0; i < kNumDownloadSources; i++) {
452 DownloadSource source = static_cast<DownloadSource>(i);
453 SetCurrentBytesDownloaded(source, 0, true);
454 // Note: Not resetting the TotalBytesDownloaded as we want that metric
455 // to count the bytes downloaded across various update attempts until
456 // we have successfully applied the update.
457 }
458}
459
460int64_t PayloadState::GetPersistedValue(const string& key) {
461 CHECK(prefs_);
462 if (!prefs_->Exists(key))
463 return 0;
464
465 int64_t stored_value;
466 if (!prefs_->GetInt64(key, &stored_value))
467 return 0;
468
469 if (stored_value < 0) {
470 LOG(ERROR) << key << ": Invalid value (" << stored_value
471 << ") in persisted state. Defaulting to 0";
472 return 0;
473 }
474
475 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800476}
477
478string PayloadState::CalculateResponseSignature() {
479 string response_sign = StringPrintf("NumURLs = %d\n",
480 response_.payload_urls.size());
481
482 for (size_t i = 0; i < response_.payload_urls.size(); i++)
483 response_sign += StringPrintf("Url%d = %s\n",
484 i, response_.payload_urls[i].c_str());
485
486 response_sign += StringPrintf("Payload Size = %llu\n"
487 "Payload Sha256 Hash = %s\n"
488 "Metadata Size = %llu\n"
489 "Metadata Signature = %s\n"
490 "Is Delta Payload = %d\n"
491 "Max Failure Count Per Url = %d\n"
492 "Disable Payload Backoff = %d\n",
493 response_.size,
494 response_.hash.c_str(),
495 response_.metadata_size,
496 response_.metadata_signature.c_str(),
497 response_.is_delta_payload,
498 response_.max_failure_count_per_url,
499 response_.disable_payload_backoff);
500 return response_sign;
501}
502
503void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800504 CHECK(prefs_);
505 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800506 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
507 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
508 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800509 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800510}
511
Jay Srinivasan19409b72013-04-12 19:23:36 -0700512void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800513 CHECK(prefs_);
514 response_signature_ = response_signature;
515 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
516 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
517}
518
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800519void PayloadState::LoadPayloadAttemptNumber() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700520 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800521}
522
523void PayloadState::SetPayloadAttemptNumber(uint32_t payload_attempt_number) {
524 CHECK(prefs_);
525 payload_attempt_number_ = payload_attempt_number;
526 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
527 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
528}
529
530void PayloadState::LoadUrlIndex() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700531 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800532}
533
534void PayloadState::SetUrlIndex(uint32_t url_index) {
535 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800536 url_index_ = url_index;
537 LOG(INFO) << "Current URL Index = " << url_index_;
538 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700539
540 // Also update the download source, which is purely dependent on the
541 // current URL index alone.
542 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800543}
544
David Zeuthencc6f9962013-04-18 11:57:24 -0700545void PayloadState::LoadUrlSwitchCount() {
546 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
547}
548
549void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
550 CHECK(prefs_);
551 url_switch_count_ = url_switch_count;
552 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
553 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
554}
555
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800556void PayloadState::LoadUrlFailureCount() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700557 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800558}
559
560void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
561 CHECK(prefs_);
562 url_failure_count_ = url_failure_count;
563 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
564 << ")'s Failure Count = " << url_failure_count_;
565 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800566}
567
Jay Srinivasan08262882012-12-28 19:29:43 -0800568void PayloadState::LoadBackoffExpiryTime() {
569 CHECK(prefs_);
570 int64_t stored_value;
571 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
572 return;
573
574 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
575 return;
576
577 Time stored_time = Time::FromInternalValue(stored_value);
578 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
579 LOG(ERROR) << "Invalid backoff expiry time ("
580 << utils::ToString(stored_time)
581 << ") in persisted state. Resetting.";
582 stored_time = Time();
583 }
584 SetBackoffExpiryTime(stored_time);
585}
586
587void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
588 CHECK(prefs_);
589 backoff_expiry_time_ = new_time;
590 LOG(INFO) << "Backoff Expiry Time = "
591 << utils::ToString(backoff_expiry_time_);
592 prefs_->SetInt64(kPrefsBackoffExpiryTime,
593 backoff_expiry_time_.ToInternalValue());
594}
595
David Zeuthen9a017f22013-04-11 16:10:26 -0700596TimeDelta PayloadState::GetUpdateDuration() {
597 Time end_time = update_timestamp_end_.is_null() ? Time::Now() :
598 update_timestamp_end_;
599 return end_time - update_timestamp_start_;
600}
601
602void PayloadState::LoadUpdateTimestampStart() {
603 int64_t stored_value;
604 Time stored_time;
605
606 CHECK(prefs_);
607
608 Time now = Time::Now();
609
610 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
611 // The preference missing is not unexpected - in that case, just
612 // use the current time as start time
613 stored_time = now;
614 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
615 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
616 stored_time = now;
617 } else {
618 stored_time = Time::FromInternalValue(stored_value);
619 }
620
621 // Sanity check: If the time read from disk is in the future
622 // (modulo some slack to account for possible NTP drift
623 // adjustments), something is fishy and we should report and
624 // reset.
625 TimeDelta duration_according_to_stored_time = now - stored_time;
626 if (duration_according_to_stored_time < -kDurationSlack) {
627 LOG(ERROR) << "The UpdateTimestampStart value ("
628 << utils::ToString(stored_time)
629 << ") in persisted state is "
630 << duration_according_to_stored_time.InSeconds()
631 << " seconds in the future. Resetting.";
632 stored_time = now;
633 }
634
635 SetUpdateTimestampStart(stored_time);
636}
637
638void PayloadState::SetUpdateTimestampStart(const Time& value) {
639 CHECK(prefs_);
640 update_timestamp_start_ = value;
641 prefs_->SetInt64(kPrefsUpdateTimestampStart,
642 update_timestamp_start_.ToInternalValue());
643 LOG(INFO) << "Update Timestamp Start = "
644 << utils::ToString(update_timestamp_start_);
645}
646
647void PayloadState::SetUpdateTimestampEnd(const Time& value) {
648 update_timestamp_end_ = value;
649 LOG(INFO) << "Update Timestamp End = "
650 << utils::ToString(update_timestamp_end_);
651}
652
653TimeDelta PayloadState::GetUpdateDurationUptime() {
654 return update_duration_uptime_;
655}
656
657void PayloadState::LoadUpdateDurationUptime() {
658 int64_t stored_value;
659 TimeDelta stored_delta;
660
661 CHECK(prefs_);
662
663 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
664 // The preference missing is not unexpected - in that case, just
665 // we'll use zero as the delta
666 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
667 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
668 stored_delta = TimeDelta::FromSeconds(0);
669 } else {
670 stored_delta = TimeDelta::FromInternalValue(stored_value);
671 }
672
673 // Sanity-check: Uptime can never be greater than the wall-clock
674 // difference (modulo some slack). If it is, report and reset
675 // to the wall-clock difference.
676 TimeDelta diff = GetUpdateDuration() - stored_delta;
677 if (diff < -kDurationSlack) {
678 LOG(ERROR) << "The UpdateDurationUptime value ("
679 << stored_delta.InSeconds() << " seconds"
680 << ") in persisted state is "
681 << diff.InSeconds()
682 << " seconds larger than the wall-clock delta. Resetting.";
683 stored_delta = update_duration_current_;
684 }
685
686 SetUpdateDurationUptime(stored_delta);
687}
688
689void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
690 const Time& timestamp,
691 bool use_logging) {
692 CHECK(prefs_);
693 update_duration_uptime_ = value;
694 update_duration_uptime_timestamp_ = timestamp;
695 prefs_->SetInt64(kPrefsUpdateDurationUptime,
696 update_duration_uptime_.ToInternalValue());
697 if (use_logging) {
698 LOG(INFO) << "Update Duration Uptime = "
699 << update_duration_uptime_.InSeconds()
700 << " seconds";
701 }
702}
703
704void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
705 SetUpdateDurationUptimeExtended(value, utils::GetMonotonicTime(), true);
706}
707
708void PayloadState::CalculateUpdateDurationUptime() {
709 Time now = utils::GetMonotonicTime();
710 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
711 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
712 // We're frequently called so avoid logging this write
713 SetUpdateDurationUptimeExtended(new_uptime, now, false);
714}
715
Jay Srinivasan19409b72013-04-12 19:23:36 -0700716string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
717 return prefix + "-from-" + utils::ToString(source);
718}
719
720void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
721 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
722 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
723}
724
725void PayloadState::SetCurrentBytesDownloaded(
726 DownloadSource source,
727 uint64_t current_bytes_downloaded,
728 bool log) {
729 CHECK(prefs_);
730
731 if (source >= kNumDownloadSources)
732 return;
733
734 // Update the in-memory value.
735 current_bytes_downloaded_[source] = current_bytes_downloaded;
736
737 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
738 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
739 LOG_IF(INFO, log) << "Current bytes downloaded for "
740 << utils::ToString(source) << " = "
741 << GetCurrentBytesDownloaded(source);
742}
743
744void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
745 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
746 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
747}
748
749void PayloadState::SetTotalBytesDownloaded(
750 DownloadSource source,
751 uint64_t total_bytes_downloaded,
752 bool log) {
753 CHECK(prefs_);
754
755 if (source >= kNumDownloadSources)
756 return;
757
758 // Update the in-memory value.
759 total_bytes_downloaded_[source] = total_bytes_downloaded;
760
761 // Persist.
762 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
763 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
764 LOG_IF(INFO, log) << "Total bytes downloaded for "
765 << utils::ToString(source) << " = "
766 << GetTotalBytesDownloaded(source);
767}
768
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800769} // namespace chromeos_update_engine