blob: 31c4e42175a028366b12c7295cc77358db1efa1c [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.
407 for (int i = 0; i < kNumDownloadSources; i++) {
408 DownloadSource source = static_cast<DownloadSource>(i);
409 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
410
411 string metric = "Installer.SuccessfulMBsDownloadedFrom" +
412 utils::ToString(source);
413 uint64_t mbs = GetCurrentBytesDownloaded(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 SetCurrentBytesDownloaded(source, 0, true);
421
422 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
423 mbs = GetTotalBytesDownloaded(source) / kNumBytesInOneMiB;
424 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
425 system_state_->metrics_lib()->SendToUMA(metric,
426 mbs,
427 0, // min
428 kMaxMiBs,
429 kNumDefaultUmaBuckets);
430
431 SetTotalBytesDownloaded(source, 0, true);
432 }
433}
434
David Zeuthencc6f9962013-04-18 11:57:24 -0700435void PayloadState::ReportUpdateUrlSwitchesMetric() {
436 string metric = "Installer.UpdateURLSwitches";
437 int value = static_cast<int>(url_switch_count_);
438
439 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
440 system_state_->metrics_lib()->SendToUMA(
441 metric,
442 value,
443 0, // min value
444 100, // max value
445 kNumDefaultUmaBuckets);
446}
447
Chris Sosabe45bef2013-04-09 18:25:12 -0700448void PayloadState::ReportRebootMetrics() {
449 // Report the number of num_reboots.
450 string metric = "Installer.UpdateNumReboots";
451 uint32_t num_reboots = GetNumReboots();
452 LOG(INFO) << "Uploading reboot count of " << num_reboots << " for metric "
453 << metric;
454 system_state_->metrics_lib()->SendToUMA(
455 metric,
456 static_cast<int>(num_reboots), // sample
457 0, // min = 0.
458 50, // max
459 25); // buckets
460 SetNumReboots(0);
461}
462
463void PayloadState::UpdateNumReboots() {
464 // We only update the reboot count when the system has been detected to have
465 // been rebooted.
466 if (!system_state_->system_rebooted()) {
467 return;
468 }
469
470 SetNumReboots(GetNumReboots() + 1);
471}
472
473void PayloadState::SetNumReboots(uint32_t num_reboots) {
474 CHECK(prefs_);
475 num_reboots_ = num_reboots;
476 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
477 LOG(INFO) << "Number of Reboots during current update attempt = "
478 << num_reboots_;
479}
480
Jay Srinivasan08262882012-12-28 19:29:43 -0800481void PayloadState::ResetPersistedState() {
482 SetPayloadAttemptNumber(0);
483 SetUrlIndex(0);
484 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700485 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800486 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700487 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
David Zeuthen9a017f22013-04-11 16:10:26 -0700488 SetUpdateTimestampEnd(Time()); // Set to null time
489 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700490 ResetDownloadSourcesOnNewUpdate();
491}
492
493void PayloadState::ResetDownloadSourcesOnNewUpdate() {
494 for (int i = 0; i < kNumDownloadSources; i++) {
495 DownloadSource source = static_cast<DownloadSource>(i);
496 SetCurrentBytesDownloaded(source, 0, true);
497 // Note: Not resetting the TotalBytesDownloaded as we want that metric
498 // to count the bytes downloaded across various update attempts until
499 // we have successfully applied the update.
500 }
501}
502
503int64_t PayloadState::GetPersistedValue(const string& key) {
504 CHECK(prefs_);
505 if (!prefs_->Exists(key))
506 return 0;
507
508 int64_t stored_value;
509 if (!prefs_->GetInt64(key, &stored_value))
510 return 0;
511
512 if (stored_value < 0) {
513 LOG(ERROR) << key << ": Invalid value (" << stored_value
514 << ") in persisted state. Defaulting to 0";
515 return 0;
516 }
517
518 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800519}
520
521string PayloadState::CalculateResponseSignature() {
522 string response_sign = StringPrintf("NumURLs = %d\n",
523 response_.payload_urls.size());
524
525 for (size_t i = 0; i < response_.payload_urls.size(); i++)
526 response_sign += StringPrintf("Url%d = %s\n",
527 i, response_.payload_urls[i].c_str());
528
529 response_sign += StringPrintf("Payload Size = %llu\n"
530 "Payload Sha256 Hash = %s\n"
531 "Metadata Size = %llu\n"
532 "Metadata Signature = %s\n"
533 "Is Delta Payload = %d\n"
534 "Max Failure Count Per Url = %d\n"
535 "Disable Payload Backoff = %d\n",
536 response_.size,
537 response_.hash.c_str(),
538 response_.metadata_size,
539 response_.metadata_signature.c_str(),
540 response_.is_delta_payload,
541 response_.max_failure_count_per_url,
542 response_.disable_payload_backoff);
543 return response_sign;
544}
545
546void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800547 CHECK(prefs_);
548 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800549 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
550 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
551 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800552 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800553}
554
Jay Srinivasan19409b72013-04-12 19:23:36 -0700555void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800556 CHECK(prefs_);
557 response_signature_ = response_signature;
558 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
559 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
560}
561
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800562void PayloadState::LoadPayloadAttemptNumber() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700563 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800564}
565
566void PayloadState::SetPayloadAttemptNumber(uint32_t payload_attempt_number) {
567 CHECK(prefs_);
568 payload_attempt_number_ = payload_attempt_number;
569 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
570 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
571}
572
573void PayloadState::LoadUrlIndex() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700574 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800575}
576
577void PayloadState::SetUrlIndex(uint32_t url_index) {
578 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800579 url_index_ = url_index;
580 LOG(INFO) << "Current URL Index = " << url_index_;
581 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700582
583 // Also update the download source, which is purely dependent on the
584 // current URL index alone.
585 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800586}
587
David Zeuthencc6f9962013-04-18 11:57:24 -0700588void PayloadState::LoadUrlSwitchCount() {
589 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
590}
591
592void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
593 CHECK(prefs_);
594 url_switch_count_ = url_switch_count;
595 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
596 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
597}
598
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800599void PayloadState::LoadUrlFailureCount() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700600 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800601}
602
603void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
604 CHECK(prefs_);
605 url_failure_count_ = url_failure_count;
606 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
607 << ")'s Failure Count = " << url_failure_count_;
608 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800609}
610
Jay Srinivasan08262882012-12-28 19:29:43 -0800611void PayloadState::LoadBackoffExpiryTime() {
612 CHECK(prefs_);
613 int64_t stored_value;
614 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
615 return;
616
617 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
618 return;
619
620 Time stored_time = Time::FromInternalValue(stored_value);
621 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
622 LOG(ERROR) << "Invalid backoff expiry time ("
623 << utils::ToString(stored_time)
624 << ") in persisted state. Resetting.";
625 stored_time = Time();
626 }
627 SetBackoffExpiryTime(stored_time);
628}
629
630void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
631 CHECK(prefs_);
632 backoff_expiry_time_ = new_time;
633 LOG(INFO) << "Backoff Expiry Time = "
634 << utils::ToString(backoff_expiry_time_);
635 prefs_->SetInt64(kPrefsBackoffExpiryTime,
636 backoff_expiry_time_.ToInternalValue());
637}
638
David Zeuthen9a017f22013-04-11 16:10:26 -0700639TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700640 Time end_time = update_timestamp_end_.is_null()
641 ? system_state_->clock()->GetWallclockTime() :
642 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700643 return end_time - update_timestamp_start_;
644}
645
646void PayloadState::LoadUpdateTimestampStart() {
647 int64_t stored_value;
648 Time stored_time;
649
650 CHECK(prefs_);
651
David Zeuthenf413fe52013-04-22 14:04:39 -0700652 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700653
654 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
655 // The preference missing is not unexpected - in that case, just
656 // use the current time as start time
657 stored_time = now;
658 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
659 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
660 stored_time = now;
661 } else {
662 stored_time = Time::FromInternalValue(stored_value);
663 }
664
665 // Sanity check: If the time read from disk is in the future
666 // (modulo some slack to account for possible NTP drift
667 // adjustments), something is fishy and we should report and
668 // reset.
669 TimeDelta duration_according_to_stored_time = now - stored_time;
670 if (duration_according_to_stored_time < -kDurationSlack) {
671 LOG(ERROR) << "The UpdateTimestampStart value ("
672 << utils::ToString(stored_time)
673 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700674 << utils::FormatTimeDelta(duration_according_to_stored_time)
675 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700676 stored_time = now;
677 }
678
679 SetUpdateTimestampStart(stored_time);
680}
681
682void PayloadState::SetUpdateTimestampStart(const Time& value) {
683 CHECK(prefs_);
684 update_timestamp_start_ = value;
685 prefs_->SetInt64(kPrefsUpdateTimestampStart,
686 update_timestamp_start_.ToInternalValue());
687 LOG(INFO) << "Update Timestamp Start = "
688 << utils::ToString(update_timestamp_start_);
689}
690
691void PayloadState::SetUpdateTimestampEnd(const Time& value) {
692 update_timestamp_end_ = value;
693 LOG(INFO) << "Update Timestamp End = "
694 << utils::ToString(update_timestamp_end_);
695}
696
697TimeDelta PayloadState::GetUpdateDurationUptime() {
698 return update_duration_uptime_;
699}
700
701void PayloadState::LoadUpdateDurationUptime() {
702 int64_t stored_value;
703 TimeDelta stored_delta;
704
705 CHECK(prefs_);
706
707 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
708 // The preference missing is not unexpected - in that case, just
709 // we'll use zero as the delta
710 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
711 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
712 stored_delta = TimeDelta::FromSeconds(0);
713 } else {
714 stored_delta = TimeDelta::FromInternalValue(stored_value);
715 }
716
717 // Sanity-check: Uptime can never be greater than the wall-clock
718 // difference (modulo some slack). If it is, report and reset
719 // to the wall-clock difference.
720 TimeDelta diff = GetUpdateDuration() - stored_delta;
721 if (diff < -kDurationSlack) {
722 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -0700723 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -0700724 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700725 << utils::FormatTimeDelta(diff)
726 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700727 stored_delta = update_duration_current_;
728 }
729
730 SetUpdateDurationUptime(stored_delta);
731}
732
Chris Sosabe45bef2013-04-09 18:25:12 -0700733void PayloadState::LoadNumReboots() {
734 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
735}
736
David Zeuthen9a017f22013-04-11 16:10:26 -0700737void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
738 const Time& timestamp,
739 bool use_logging) {
740 CHECK(prefs_);
741 update_duration_uptime_ = value;
742 update_duration_uptime_timestamp_ = timestamp;
743 prefs_->SetInt64(kPrefsUpdateDurationUptime,
744 update_duration_uptime_.ToInternalValue());
745 if (use_logging) {
746 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -0700747 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -0700748 }
749}
750
751void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -0700752 Time now = system_state_->clock()->GetMonotonicTime();
753 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -0700754}
755
756void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700757 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700758 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
759 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
760 // We're frequently called so avoid logging this write
761 SetUpdateDurationUptimeExtended(new_uptime, now, false);
762}
763
David Zeuthen674c3182013-04-18 14:05:20 -0700764void PayloadState::ReportDurationMetrics() {
765 TimeDelta duration = GetUpdateDuration();
766 TimeDelta duration_uptime = GetUpdateDurationUptime();
767 string metric;
768
769 metric = "Installer.UpdateDurationMinutes";
770 system_state_->metrics_lib()->SendToUMA(
771 metric,
772 static_cast<int>(duration.InMinutes()),
773 1, // min: 1 minute
774 365*24*60, // max: 1 year (approx)
775 kNumDefaultUmaBuckets);
776 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
777 << " for metric " << metric;
778
779 metric = "Installer.UpdateDurationUptimeMinutes";
780 system_state_->metrics_lib()->SendToUMA(
781 metric,
782 static_cast<int>(duration_uptime.InMinutes()),
783 1, // min: 1 minute
784 30*24*60, // max: 1 month (approx)
785 kNumDefaultUmaBuckets);
786 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
787 << " for metric " << metric;
788
789 prefs_->Delete(kPrefsUpdateTimestampStart);
790 prefs_->Delete(kPrefsUpdateDurationUptime);
791}
792
Jay Srinivasan19409b72013-04-12 19:23:36 -0700793string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
794 return prefix + "-from-" + utils::ToString(source);
795}
796
797void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
798 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
799 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
800}
801
802void PayloadState::SetCurrentBytesDownloaded(
803 DownloadSource source,
804 uint64_t current_bytes_downloaded,
805 bool log) {
806 CHECK(prefs_);
807
808 if (source >= kNumDownloadSources)
809 return;
810
811 // Update the in-memory value.
812 current_bytes_downloaded_[source] = current_bytes_downloaded;
813
814 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
815 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
816 LOG_IF(INFO, log) << "Current bytes downloaded for "
817 << utils::ToString(source) << " = "
818 << GetCurrentBytesDownloaded(source);
819}
820
821void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
822 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
823 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
824}
825
826void PayloadState::SetTotalBytesDownloaded(
827 DownloadSource source,
828 uint64_t total_bytes_downloaded,
829 bool log) {
830 CHECK(prefs_);
831
832 if (source >= kNumDownloadSources)
833 return;
834
835 // Update the in-memory value.
836 total_bytes_downloaded_[source] = total_bytes_downloaded;
837
838 // Persist.
839 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
840 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
841 LOG_IF(INFO, log) << "Total bytes downloaded for "
842 << utils::ToString(source) << " = "
843 << GetTotalBytesDownloaded(source);
844}
845
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800846} // namespace chromeos_update_engine