blob: 6d6791fd71a1e4e03880b7dd7cabfd8d12b6d3e4 [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"
Alex Deymo42432912013-07-12 20:21:15 -070015#include "update_engine/hardware_interface.h"
16#include "update_engine/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070017#include "update_engine/prefs.h"
18#include "update_engine/system_state.h"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080019#include "update_engine/utils.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080020
Jay Srinivasan08262882012-12-28 19:29:43 -080021using base::Time;
22using base::TimeDelta;
23using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080024using std::string;
25
26namespace chromeos_update_engine {
27
David Zeuthen9a017f22013-04-11 16:10:26 -070028const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
29
Jay Srinivasan08262882012-12-28 19:29:43 -080030// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070031static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080032
Jay Srinivasan08262882012-12-28 19:29:43 -080033// We want to randomize retry attempts after the backoff by +/- 6 hours.
34static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080035
Jay Srinivasan19409b72013-04-12 19:23:36 -070036PayloadState::PayloadState()
37 : prefs_(NULL),
38 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070039 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070040 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070041 url_failure_count_(0),
42 url_switch_count_(0) {
Jay Srinivasan19409b72013-04-12 19:23:36 -070043 for (int i = 0; i <= kNumDownloadSources; i++)
44 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
45}
46
47bool PayloadState::Initialize(SystemState* system_state) {
48 system_state_ = system_state;
49 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070050 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080051 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080052 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070053 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080054 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080055 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070056 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080057 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070058 LoadUpdateTimestampStart();
59 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
60 // being called before it. Don't reorder.
61 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070062 for (int i = 0; i < kNumDownloadSources; i++) {
63 DownloadSource source = static_cast<DownloadSource>(i);
64 LoadCurrentBytesDownloaded(source);
65 LoadTotalBytesDownloaded(source);
66 }
Chris Sosabe45bef2013-04-09 18:25:12 -070067 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070068 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070069 LoadRollbackVersion();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080070 return true;
71}
72
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080073void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080074 // Always store the latest response.
75 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080076
Jay Srinivasan53173b92013-05-17 17:13:01 -070077 // Compute the candidate URLs first as they are used to calculate the
78 // response signature so that a change in enterprise policy for
79 // HTTP downloads being enabled or not could be honored as soon as the
80 // next update check happens.
81 ComputeCandidateUrls();
82
Jay Srinivasan08262882012-12-28 19:29:43 -080083 // Check if the "signature" of this response (i.e. the fields we care about)
84 // has changed.
85 string new_response_signature = CalculateResponseSignature();
86 bool has_response_changed = (response_signature_ != new_response_signature);
87
88 // If the response has changed, we should persist the new signature and
89 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080090 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -080091 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -070092 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -080093 SetResponseSignature(new_response_signature);
94 ResetPersistedState();
95 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080096 }
97
Jay Srinivasan08262882012-12-28 19:29:43 -080098 // This is the earliest point at which we can validate whether the URL index
99 // we loaded from the persisted state is a valid value. If the response
100 // hasn't changed but the URL index is invalid, it's indicative of some
101 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700102 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800103 LOG(INFO) << "Resetting all payload state as the url index seems to have "
104 "been tampered with";
105 ResetPersistedState();
106 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800107 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700108
109 // Update the current download source which depends on the latest value of
110 // the response.
111 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800112}
113
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800114void PayloadState::DownloadComplete() {
115 LOG(INFO) << "Payload downloaded successfully";
116 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700117 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800118}
119
120void PayloadState::DownloadProgress(size_t count) {
121 if (count == 0)
122 return;
123
David Zeuthen9a017f22013-04-11 16:10:26 -0700124 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700125 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700126
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800127 // We've received non-zero bytes from a recent download operation. Since our
128 // URL failure count is meant to penalize a URL only for consecutive
129 // failures, downloading bytes successfully means we should reset the failure
130 // count (as we know at least that the URL is working). In future, we can
131 // design this to be more sophisticated to check for more intelligent failure
132 // patterns, but right now, even 1 byte downloaded will mark the URL to be
133 // good unless it hits 10 (or configured number of) consecutive failures
134 // again.
135
136 if (GetUrlFailureCount() == 0)
137 return;
138
139 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
140 << " to 0 as we received " << count << " bytes successfully";
141 SetUrlFailureCount(0);
142}
143
Chris Sosabe45bef2013-04-09 18:25:12 -0700144void PayloadState::UpdateResumed() {
145 LOG(INFO) << "Resuming an update that was previously started.";
146 UpdateNumReboots();
147}
148
Jay Srinivasan19409b72013-04-12 19:23:36 -0700149void PayloadState::UpdateRestarted() {
150 LOG(INFO) << "Starting a new update";
151 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700152 SetNumReboots(0);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700153}
154
David Zeuthen9a017f22013-04-11 16:10:26 -0700155void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700156 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700157 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700158 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
Jay Srinivasan19409b72013-04-12 19:23:36 -0700159 ReportBytesDownloadedMetrics();
David Zeuthencc6f9962013-04-18 11:57:24 -0700160 ReportUpdateUrlSwitchesMetric();
Chris Sosabe45bef2013-04-09 18:25:12 -0700161 ReportRebootMetrics();
David Zeuthen674c3182013-04-18 14:05:20 -0700162 ReportDurationMetrics();
David Zeuthena573d6f2013-06-14 16:13:36 -0700163 ReportUpdatesAbandonedCountMetric();
Alex Deymo1c656c42013-06-28 11:02:14 -0700164 ReportPayloadTypeMetric();
Alex Deymo820cc702013-06-28 15:43:46 -0700165 ReportAttemptsCountMetrics();
David Zeuthena573d6f2013-06-14 16:13:36 -0700166
167 // Reset the number of responses seen since it counts from the last
168 // successful update, e.g. now.
169 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700170
171 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700172}
173
David Zeuthena99981f2013-04-29 13:42:47 -0700174void PayloadState::UpdateFailed(ErrorCode error) {
175 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800176 LOG(INFO) << "Updating payload state for error code: " << base_error
177 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800178
Jay Srinivasan53173b92013-05-17 17:13:01 -0700179 if (candidate_urls_.size() == 0) {
180 // This means we got this error even before we got a valid Omaha response
181 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800182 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800183 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
184 return;
185 }
186
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800187 switch (base_error) {
188 // Errors which are good indicators of a problem with a particular URL or
189 // the protocol used in the URL or entities in the communication channel
190 // (e.g. proxies). We should try the next available URL in the next update
191 // check to quickly recover from these errors.
David Zeuthena99981f2013-04-29 13:42:47 -0700192 case kErrorCodePayloadHashMismatchError:
193 case kErrorCodePayloadSizeMismatchError:
194 case kErrorCodeDownloadPayloadVerificationError:
195 case kErrorCodeDownloadPayloadPubKeyVerificationError:
196 case kErrorCodeSignedDeltaPayloadExpectedError:
197 case kErrorCodeDownloadInvalidMetadataMagicString:
198 case kErrorCodeDownloadSignatureMissingInManifest:
199 case kErrorCodeDownloadManifestParseError:
200 case kErrorCodeDownloadMetadataSignatureError:
201 case kErrorCodeDownloadMetadataSignatureVerificationError:
202 case kErrorCodeDownloadMetadataSignatureMismatch:
203 case kErrorCodeDownloadOperationHashVerificationError:
204 case kErrorCodeDownloadOperationExecutionError:
205 case kErrorCodeDownloadOperationHashMismatch:
206 case kErrorCodeDownloadInvalidMetadataSize:
207 case kErrorCodeDownloadInvalidMetadataSignature:
208 case kErrorCodeDownloadOperationHashMissingError:
209 case kErrorCodeDownloadMetadataSignatureMissingError:
Gilad Arnold21504f02013-05-24 08:51:22 -0700210 case kErrorCodePayloadMismatchedType:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800211 IncrementUrlIndex();
212 break;
213
214 // Errors which seem to be just transient network/communication related
215 // failures and do not indicate any inherent problem with the URL itself.
216 // So, we should keep the current URL but just increment the
217 // failure count to give it more chances. This way, while we maximize our
218 // chances of downloading from the URLs that appear earlier in the response
219 // (because download from a local server URL that appears earlier in a
220 // response is preferable than downloading from the next URL which could be
221 // a internet URL and thus could be more expensive).
David Zeuthena99981f2013-04-29 13:42:47 -0700222 case kErrorCodeError:
223 case kErrorCodeDownloadTransferError:
224 case kErrorCodeDownloadWriteError:
225 case kErrorCodeDownloadStateInitializationError:
226 case kErrorCodeOmahaErrorInHTTPResponse: // Aggregate code for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800227 IncrementFailureCount();
228 break;
229
230 // Errors which are not specific to a URL and hence shouldn't result in
231 // the URL being penalized. This can happen in two cases:
232 // 1. We haven't started downloading anything: These errors don't cost us
233 // anything in terms of actual payload bytes, so we should just do the
234 // regular retries at the next update check.
235 // 2. We have successfully downloaded the payload: In this case, the
236 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800237 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800238 // In either case, there's no need to update URL index or failure count.
David Zeuthena99981f2013-04-29 13:42:47 -0700239 case kErrorCodeOmahaRequestError:
240 case kErrorCodeOmahaResponseHandlerError:
241 case kErrorCodePostinstallRunnerError:
242 case kErrorCodeFilesystemCopierError:
243 case kErrorCodeInstallDeviceOpenError:
244 case kErrorCodeKernelDeviceOpenError:
245 case kErrorCodeDownloadNewPartitionInfoError:
246 case kErrorCodeNewRootfsVerificationError:
247 case kErrorCodeNewKernelVerificationError:
248 case kErrorCodePostinstallBootedFromFirmwareB:
Don Garrett81018e02013-07-30 18:46:31 -0700249 case kErrorCodePostinstallFirmwareRONotUpdatable:
David Zeuthena99981f2013-04-29 13:42:47 -0700250 case kErrorCodeOmahaRequestEmptyResponseError:
251 case kErrorCodeOmahaRequestXMLParseError:
252 case kErrorCodeOmahaResponseInvalid:
253 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
254 case kErrorCodeOmahaUpdateDeferredPerPolicy:
255 case kErrorCodeOmahaUpdateDeferredForBackoff:
256 case kErrorCodePostinstallPowerwashError:
257 case kErrorCodeUpdateCanceledByChannelChange:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800258 LOG(INFO) << "Not incrementing URL index or failure count for this error";
259 break;
260
David Zeuthena99981f2013-04-29 13:42:47 -0700261 case kErrorCodeSuccess: // success code
David Zeuthena99981f2013-04-29 13:42:47 -0700262 case kErrorCodeUmaReportedMax: // not an error code
263 case kErrorCodeOmahaRequestHTTPResponseBase: // aggregated already
264 case kErrorCodeDevModeFlag: // not an error code
265 case kErrorCodeResumedFlag: // not an error code
266 case kErrorCodeTestImageFlag: // not an error code
267 case kErrorCodeTestOmahaUrlFlag: // not an error code
268 case kErrorCodeSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800269 // These shouldn't happen. Enumerating these explicitly here so that we
270 // can let the compiler warn about new error codes that are added to
271 // action_processor.h but not added here.
272 LOG(WARNING) << "Unexpected error code for UpdateFailed";
273 break;
274
275 // Note: Not adding a default here so as to let the compiler warn us of
276 // any new enums that were added in the .h but not listed in this switch.
277 }
278}
279
Jay Srinivasan08262882012-12-28 19:29:43 -0800280bool PayloadState::ShouldBackoffDownload() {
281 if (response_.disable_payload_backoff) {
282 LOG(INFO) << "Payload backoff logic is disabled. "
283 "Can proceed with the download";
284 return false;
285 }
286
287 if (response_.is_delta_payload) {
288 // If delta payloads fail, we want to fallback quickly to full payloads as
289 // they are more likely to succeed. Exponential backoffs would greatly
290 // slow down the fallback to full payloads. So we don't backoff for delta
291 // payloads.
292 LOG(INFO) << "No backoffs for delta payloads. "
293 << "Can proceed with the download";
294 return false;
295 }
296
297 if (!utils::IsOfficialBuild()) {
298 // Backoffs are needed only for official builds. We do not want any delays
299 // or update failures due to backoffs during testing or development.
300 LOG(INFO) << "No backoffs for test/dev images. "
301 << "Can proceed with the download";
302 return false;
303 }
304
305 if (backoff_expiry_time_.is_null()) {
306 LOG(INFO) << "No backoff expiry time has been set. "
307 << "Can proceed with the download";
308 return false;
309 }
310
311 if (backoff_expiry_time_ < Time::Now()) {
312 LOG(INFO) << "The backoff expiry time ("
313 << utils::ToString(backoff_expiry_time_)
314 << ") has elapsed. Can proceed with the download";
315 return false;
316 }
317
318 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
319 << utils::ToString(backoff_expiry_time_);
320 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800321}
322
Chris Sosaaa18e162013-06-20 13:20:30 -0700323void PayloadState::Rollback() {
324 SetRollbackVersion(system_state_->request_params()->app_version());
325}
326
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800327void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700328 // Update the payload attempt number for both payload types: full and delta.
329 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Alex Deymo29b51d92013-07-09 15:26:24 -0700330
331 // Report the metric every time the value is incremented.
332 string metric = "Installer.PayloadAttemptNumber";
333 int value = GetPayloadAttemptNumber();
334
335 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
336 system_state_->metrics_lib()->SendToUMA(
337 metric,
338 value,
339 1, // min value
340 50, // max value
341 kNumDefaultUmaBuckets);
Alex Deymo820cc702013-06-28 15:43:46 -0700342}
343
344void PayloadState::IncrementFullPayloadAttemptNumber() {
345 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800346 if (response_.is_delta_payload) {
347 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
348 return;
349 }
350
Alex Deymo29b51d92013-07-09 15:26:24 -0700351 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700352 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800353 UpdateBackoffExpiryTime();
Alex Deymo29b51d92013-07-09 15:26:24 -0700354
355 // Report the metric every time the value is incremented.
356 string metric = "Installer.FullPayloadAttemptNumber";
357 int value = GetFullPayloadAttemptNumber();
358
359 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
360 system_state_->metrics_lib()->SendToUMA(
361 metric,
362 value,
363 1, // min value
364 50, // max value
365 kNumDefaultUmaBuckets);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800366}
367
368void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800369 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700370 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800371 LOG(INFO) << "Incrementing the URL index for next attempt";
372 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800373 } else {
374 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700375 << "0 as we only have " << candidate_urls_.size()
376 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800377 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700378 IncrementPayloadAttemptNumber();
379 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800380 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800381
David Zeuthencc6f9962013-04-18 11:57:24 -0700382 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700383 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700384 SetUrlSwitchCount(url_switch_count_ + 1);
385
Jay Srinivasan08262882012-12-28 19:29:43 -0800386 // Whenever we update the URL index, we should also clear the URL failure
387 // count so we can start over fresh for the new URL.
388 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800389}
390
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800391void PayloadState::IncrementFailureCount() {
392 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800393 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800394 LOG(INFO) << "Incrementing the URL failure count";
395 SetUrlFailureCount(next_url_failure_count);
396 } else {
397 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
398 << ". Trying next available URL";
399 IncrementUrlIndex();
400 }
401}
402
Jay Srinivasan08262882012-12-28 19:29:43 -0800403void PayloadState::UpdateBackoffExpiryTime() {
404 if (response_.disable_payload_backoff) {
405 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
406 SetBackoffExpiryTime(Time());
407 return;
408 }
409
Alex Deymo820cc702013-06-28 15:43:46 -0700410 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800411 SetBackoffExpiryTime(Time());
412 return;
413 }
414
415 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700416 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800417 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Deymo820cc702013-06-28 15:43:46 -0700418 int num_days = 1; // the value to be shifted.
419 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800420
421 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
422 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700423 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800424
425 // The number of days is the minimum of 2 raised to (payload_attempt_number
426 // - 1) or kMaxBackoffDays.
427 num_days = min(num_days << power, kMaxBackoffDays);
428
429 // We don't want all retries to happen exactly at the same time when
430 // retrying after backoff. So add some random minutes to fuzz.
431 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
432 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
433 TimeDelta::FromMinutes(fuzz_minutes);
434 LOG(INFO) << "Incrementing the backoff expiry time by "
435 << utils::FormatTimeDelta(next_backoff_interval);
436 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
437}
438
Jay Srinivasan19409b72013-04-12 19:23:36 -0700439void PayloadState::UpdateCurrentDownloadSource() {
440 current_download_source_ = kNumDownloadSources;
441
Jay Srinivasan53173b92013-05-17 17:13:01 -0700442 if (GetUrlIndex() < candidate_urls_.size()) {
443 string current_url = candidate_urls_[GetUrlIndex()];
Jay Srinivasan19409b72013-04-12 19:23:36 -0700444 if (StartsWithASCII(current_url, "https://", false))
445 current_download_source_ = kDownloadSourceHttpsServer;
446 else if (StartsWithASCII(current_url, "http://", false))
447 current_download_source_ = kDownloadSourceHttpServer;
448 }
449
450 LOG(INFO) << "Current download source: "
451 << utils::ToString(current_download_source_);
452}
453
454void PayloadState::UpdateBytesDownloaded(size_t count) {
455 SetCurrentBytesDownloaded(
456 current_download_source_,
457 GetCurrentBytesDownloaded(current_download_source_) + count,
458 false);
459 SetTotalBytesDownloaded(
460 current_download_source_,
461 GetTotalBytesDownloaded(current_download_source_) + count,
462 false);
463}
464
465void PayloadState::ReportBytesDownloadedMetrics() {
466 // Report metrics collected from all known download sources to UMA.
467 // The reported data is in Megabytes in order to represent a larger
468 // sample range.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700469 int download_sources_used = 0;
470 string metric;
471 uint64_t successful_mbs = 0;
472 uint64_t total_mbs = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700473 for (int i = 0; i < kNumDownloadSources; i++) {
474 DownloadSource source = static_cast<DownloadSource>(i);
475 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
David Zeuthen44848602013-06-24 13:32:14 -0700476 uint64_t mbs;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700477
David Zeuthen44848602013-06-24 13:32:14 -0700478 // Only consider this download source (and send byte counts) as
479 // having been used if we downloaded a non-trivial amount of bytes
480 // (e.g. at least 1 MiB) that contributed to the final success of
481 // the update. Otherwise we're going to end up with a lot of
482 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700483
David Zeuthen44848602013-06-24 13:32:14 -0700484 mbs = GetCurrentBytesDownloaded(source) / kNumBytesInOneMiB;
485 if (mbs > 0) {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700486 download_sources_used |= (1 << source);
487
David Zeuthen44848602013-06-24 13:32:14 -0700488 metric = "Installer.SuccessfulMBsDownloadedFrom" +
489 utils::ToString(source);
490 successful_mbs += mbs;
491 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
492 system_state_->metrics_lib()->SendToUMA(metric,
493 mbs,
494 0, // min
495 kMaxMiBs,
496 kNumDefaultUmaBuckets);
497 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700498 SetCurrentBytesDownloaded(source, 0, true);
499
Jay Srinivasan19409b72013-04-12 19:23:36 -0700500 mbs = GetTotalBytesDownloaded(source) / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700501 if (mbs > 0) {
502 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
503 total_mbs += mbs;
504 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
505 system_state_->metrics_lib()->SendToUMA(metric,
506 mbs,
507 0, // min
508 kMaxMiBs,
509 kNumDefaultUmaBuckets);
510 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700511 SetTotalBytesDownloaded(source, 0, true);
512 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700513
514 metric = "Installer.DownloadSourcesUsed";
515 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
516 << " (bit flags) for metric " << metric;
517 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
518 system_state_->metrics_lib()->SendToUMA(metric,
519 download_sources_used,
520 0, // min
521 1 << kNumDownloadSources,
522 num_buckets);
523
524 if (successful_mbs) {
525 metric = "Installer.DownloadOverheadPercentage";
526 int percent_overhead = (total_mbs - successful_mbs) * 100 / successful_mbs;
527 LOG(INFO) << "Uploading " << percent_overhead << "% for metric " << metric;
528 system_state_->metrics_lib()->SendToUMA(metric,
529 percent_overhead,
530 0, // min: 0% overhead
531 1000, // max: 1000% overhead
532 kNumDefaultUmaBuckets);
533 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700534}
535
David Zeuthencc6f9962013-04-18 11:57:24 -0700536void PayloadState::ReportUpdateUrlSwitchesMetric() {
537 string metric = "Installer.UpdateURLSwitches";
538 int value = static_cast<int>(url_switch_count_);
539
540 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
541 system_state_->metrics_lib()->SendToUMA(
542 metric,
543 value,
544 0, // min value
545 100, // max value
546 kNumDefaultUmaBuckets);
547}
548
Chris Sosabe45bef2013-04-09 18:25:12 -0700549void PayloadState::ReportRebootMetrics() {
550 // Report the number of num_reboots.
551 string metric = "Installer.UpdateNumReboots";
552 uint32_t num_reboots = GetNumReboots();
553 LOG(INFO) << "Uploading reboot count of " << num_reboots << " for metric "
554 << metric;
555 system_state_->metrics_lib()->SendToUMA(
556 metric,
557 static_cast<int>(num_reboots), // sample
558 0, // min = 0.
559 50, // max
560 25); // buckets
561 SetNumReboots(0);
562}
563
564void PayloadState::UpdateNumReboots() {
565 // We only update the reboot count when the system has been detected to have
566 // been rebooted.
567 if (!system_state_->system_rebooted()) {
568 return;
569 }
570
571 SetNumReboots(GetNumReboots() + 1);
572}
573
574void PayloadState::SetNumReboots(uint32_t num_reboots) {
575 CHECK(prefs_);
576 num_reboots_ = num_reboots;
577 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
578 LOG(INFO) << "Number of Reboots during current update attempt = "
579 << num_reboots_;
580}
581
Jay Srinivasan08262882012-12-28 19:29:43 -0800582void PayloadState::ResetPersistedState() {
583 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700584 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800585 SetUrlIndex(0);
586 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700587 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800588 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700589 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
David Zeuthen9a017f22013-04-11 16:10:26 -0700590 SetUpdateTimestampEnd(Time()); // Set to null time
591 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700592 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700593 ResetRollbackVersion();
594}
595
596void PayloadState::ResetRollbackVersion() {
597 CHECK(powerwash_safe_prefs_);
598 rollback_version_ = "";
599 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700600}
601
602void PayloadState::ResetDownloadSourcesOnNewUpdate() {
603 for (int i = 0; i < kNumDownloadSources; i++) {
604 DownloadSource source = static_cast<DownloadSource>(i);
605 SetCurrentBytesDownloaded(source, 0, true);
606 // Note: Not resetting the TotalBytesDownloaded as we want that metric
607 // to count the bytes downloaded across various update attempts until
608 // we have successfully applied the update.
609 }
610}
611
Chris Sosaaa18e162013-06-20 13:20:30 -0700612int64_t PayloadState::GetPersistedValue(const string& key,
613 bool across_powerwash) {
614 PrefsInterface* prefs = prefs_;
615 if (across_powerwash)
616 prefs = powerwash_safe_prefs_;
617
Jay Srinivasan19409b72013-04-12 19:23:36 -0700618 CHECK(prefs_);
Chris Sosaaa18e162013-06-20 13:20:30 -0700619 if (!prefs->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700620 return 0;
621
622 int64_t stored_value;
Chris Sosaaa18e162013-06-20 13:20:30 -0700623 if (!prefs->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700624 return 0;
625
626 if (stored_value < 0) {
627 LOG(ERROR) << key << ": Invalid value (" << stored_value
628 << ") in persisted state. Defaulting to 0";
629 return 0;
630 }
631
632 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800633}
634
635string PayloadState::CalculateResponseSignature() {
636 string response_sign = StringPrintf("NumURLs = %d\n",
Jay Srinivasan53173b92013-05-17 17:13:01 -0700637 candidate_urls_.size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800638
Jay Srinivasan53173b92013-05-17 17:13:01 -0700639 for (size_t i = 0; i < candidate_urls_.size(); i++)
640 response_sign += StringPrintf("Candidate Url%d = %s\n",
641 i, candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800642
643 response_sign += StringPrintf("Payload Size = %llu\n"
644 "Payload Sha256 Hash = %s\n"
645 "Metadata Size = %llu\n"
646 "Metadata Signature = %s\n"
647 "Is Delta Payload = %d\n"
648 "Max Failure Count Per Url = %d\n"
649 "Disable Payload Backoff = %d\n",
650 response_.size,
651 response_.hash.c_str(),
652 response_.metadata_size,
653 response_.metadata_signature.c_str(),
654 response_.is_delta_payload,
655 response_.max_failure_count_per_url,
656 response_.disable_payload_backoff);
657 return response_sign;
658}
659
660void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800661 CHECK(prefs_);
662 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800663 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
664 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
665 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800666 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800667}
668
Jay Srinivasan19409b72013-04-12 19:23:36 -0700669void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800670 CHECK(prefs_);
671 response_signature_ = response_signature;
672 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
673 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
674}
675
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800676void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700677 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber,
678 false));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800679}
680
Alex Deymo820cc702013-06-28 15:43:46 -0700681void PayloadState::LoadFullPayloadAttemptNumber() {
682 SetFullPayloadAttemptNumber(GetPersistedValue(kPrefsFullPayloadAttemptNumber,
683 false));
684}
685
686void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800687 CHECK(prefs_);
688 payload_attempt_number_ = payload_attempt_number;
689 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
690 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
691}
692
Alex Deymo820cc702013-06-28 15:43:46 -0700693void PayloadState::SetFullPayloadAttemptNumber(
694 int full_payload_attempt_number) {
695 CHECK(prefs_);
696 full_payload_attempt_number_ = full_payload_attempt_number;
697 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
698 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
699 full_payload_attempt_number_);
700}
701
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800702void PayloadState::LoadUrlIndex() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700703 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex, false));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800704}
705
706void PayloadState::SetUrlIndex(uint32_t url_index) {
707 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800708 url_index_ = url_index;
709 LOG(INFO) << "Current URL Index = " << url_index_;
710 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700711
712 // Also update the download source, which is purely dependent on the
713 // current URL index alone.
714 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800715}
716
David Zeuthencc6f9962013-04-18 11:57:24 -0700717void PayloadState::LoadUrlSwitchCount() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700718 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount, false));
David Zeuthencc6f9962013-04-18 11:57:24 -0700719}
720
721void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
722 CHECK(prefs_);
723 url_switch_count_ = url_switch_count;
724 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
725 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
726}
727
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800728void PayloadState::LoadUrlFailureCount() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700729 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount,
730 false));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800731}
732
733void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
734 CHECK(prefs_);
735 url_failure_count_ = url_failure_count;
736 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
737 << ")'s Failure Count = " << url_failure_count_;
738 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800739}
740
Jay Srinivasan08262882012-12-28 19:29:43 -0800741void PayloadState::LoadBackoffExpiryTime() {
742 CHECK(prefs_);
743 int64_t stored_value;
744 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
745 return;
746
747 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
748 return;
749
750 Time stored_time = Time::FromInternalValue(stored_value);
751 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
752 LOG(ERROR) << "Invalid backoff expiry time ("
753 << utils::ToString(stored_time)
754 << ") in persisted state. Resetting.";
755 stored_time = Time();
756 }
757 SetBackoffExpiryTime(stored_time);
758}
759
760void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
761 CHECK(prefs_);
762 backoff_expiry_time_ = new_time;
763 LOG(INFO) << "Backoff Expiry Time = "
764 << utils::ToString(backoff_expiry_time_);
765 prefs_->SetInt64(kPrefsBackoffExpiryTime,
766 backoff_expiry_time_.ToInternalValue());
767}
768
David Zeuthen9a017f22013-04-11 16:10:26 -0700769TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700770 Time end_time = update_timestamp_end_.is_null()
771 ? system_state_->clock()->GetWallclockTime() :
772 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700773 return end_time - update_timestamp_start_;
774}
775
776void PayloadState::LoadUpdateTimestampStart() {
777 int64_t stored_value;
778 Time stored_time;
779
780 CHECK(prefs_);
781
David Zeuthenf413fe52013-04-22 14:04:39 -0700782 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700783
784 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
785 // The preference missing is not unexpected - in that case, just
786 // use the current time as start time
787 stored_time = now;
788 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
789 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
790 stored_time = now;
791 } else {
792 stored_time = Time::FromInternalValue(stored_value);
793 }
794
795 // Sanity check: If the time read from disk is in the future
796 // (modulo some slack to account for possible NTP drift
797 // adjustments), something is fishy and we should report and
798 // reset.
799 TimeDelta duration_according_to_stored_time = now - stored_time;
800 if (duration_according_to_stored_time < -kDurationSlack) {
801 LOG(ERROR) << "The UpdateTimestampStart value ("
802 << utils::ToString(stored_time)
803 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700804 << utils::FormatTimeDelta(duration_according_to_stored_time)
805 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700806 stored_time = now;
807 }
808
809 SetUpdateTimestampStart(stored_time);
810}
811
812void PayloadState::SetUpdateTimestampStart(const Time& value) {
813 CHECK(prefs_);
814 update_timestamp_start_ = value;
815 prefs_->SetInt64(kPrefsUpdateTimestampStart,
816 update_timestamp_start_.ToInternalValue());
817 LOG(INFO) << "Update Timestamp Start = "
818 << utils::ToString(update_timestamp_start_);
819}
820
821void PayloadState::SetUpdateTimestampEnd(const Time& value) {
822 update_timestamp_end_ = value;
823 LOG(INFO) << "Update Timestamp End = "
824 << utils::ToString(update_timestamp_end_);
825}
826
827TimeDelta PayloadState::GetUpdateDurationUptime() {
828 return update_duration_uptime_;
829}
830
831void PayloadState::LoadUpdateDurationUptime() {
832 int64_t stored_value;
833 TimeDelta stored_delta;
834
835 CHECK(prefs_);
836
837 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
838 // The preference missing is not unexpected - in that case, just
839 // we'll use zero as the delta
840 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
841 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
842 stored_delta = TimeDelta::FromSeconds(0);
843 } else {
844 stored_delta = TimeDelta::FromInternalValue(stored_value);
845 }
846
847 // Sanity-check: Uptime can never be greater than the wall-clock
848 // difference (modulo some slack). If it is, report and reset
849 // to the wall-clock difference.
850 TimeDelta diff = GetUpdateDuration() - stored_delta;
851 if (diff < -kDurationSlack) {
852 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -0700853 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -0700854 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700855 << utils::FormatTimeDelta(diff)
856 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700857 stored_delta = update_duration_current_;
858 }
859
860 SetUpdateDurationUptime(stored_delta);
861}
862
Chris Sosabe45bef2013-04-09 18:25:12 -0700863void PayloadState::LoadNumReboots() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700864 SetNumReboots(GetPersistedValue(kPrefsNumReboots, false));
865}
866
867void PayloadState::LoadRollbackVersion() {
868 SetNumReboots(GetPersistedValue(kPrefsRollbackVersion, true));
869}
870
871void PayloadState::SetRollbackVersion(const string& rollback_version) {
872 CHECK(powerwash_safe_prefs_);
873 LOG(INFO) << "Blacklisting version "<< rollback_version;
874 rollback_version_ = rollback_version;
875 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -0700876}
877
David Zeuthen9a017f22013-04-11 16:10:26 -0700878void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
879 const Time& timestamp,
880 bool use_logging) {
881 CHECK(prefs_);
882 update_duration_uptime_ = value;
883 update_duration_uptime_timestamp_ = timestamp;
884 prefs_->SetInt64(kPrefsUpdateDurationUptime,
885 update_duration_uptime_.ToInternalValue());
886 if (use_logging) {
887 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -0700888 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -0700889 }
890}
891
892void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -0700893 Time now = system_state_->clock()->GetMonotonicTime();
894 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -0700895}
896
897void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700898 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700899 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
900 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
901 // We're frequently called so avoid logging this write
902 SetUpdateDurationUptimeExtended(new_uptime, now, false);
903}
904
David Zeuthen674c3182013-04-18 14:05:20 -0700905void PayloadState::ReportDurationMetrics() {
906 TimeDelta duration = GetUpdateDuration();
907 TimeDelta duration_uptime = GetUpdateDurationUptime();
908 string metric;
909
910 metric = "Installer.UpdateDurationMinutes";
911 system_state_->metrics_lib()->SendToUMA(
912 metric,
913 static_cast<int>(duration.InMinutes()),
914 1, // min: 1 minute
915 365*24*60, // max: 1 year (approx)
916 kNumDefaultUmaBuckets);
917 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
918 << " for metric " << metric;
919
920 metric = "Installer.UpdateDurationUptimeMinutes";
921 system_state_->metrics_lib()->SendToUMA(
922 metric,
923 static_cast<int>(duration_uptime.InMinutes()),
924 1, // min: 1 minute
925 30*24*60, // max: 1 month (approx)
926 kNumDefaultUmaBuckets);
927 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
928 << " for metric " << metric;
929
930 prefs_->Delete(kPrefsUpdateTimestampStart);
931 prefs_->Delete(kPrefsUpdateDurationUptime);
932}
933
Alex Deymo1c656c42013-06-28 11:02:14 -0700934void PayloadState::ReportPayloadTypeMetric() {
935 string metric;
936 PayloadType uma_payload_type;
937 OmahaRequestParams* params = system_state_->request_params();
938
939 if (response_.is_delta_payload) {
940 uma_payload_type = kPayloadTypeDelta;
941 } else if (params->delta_okay()) {
942 uma_payload_type = kPayloadTypeFull;
943 } else { // Full payload, delta was not allowed by request.
944 uma_payload_type = kPayloadTypeForcedFull;
945 }
946
947 metric = "Installer.PayloadFormat";
948 system_state_->metrics_lib()->SendEnumToUMA(
949 metric,
950 uma_payload_type,
951 kNumPayloadTypes);
952 LOG(INFO) << "Uploading " << utils::ToString(uma_payload_type)
953 << " for metric " << metric;
954}
955
Alex Deymo820cc702013-06-28 15:43:46 -0700956void PayloadState::ReportAttemptsCountMetrics() {
957 string metric;
958 int total_attempts = GetPayloadAttemptNumber();
959
960 metric = "Installer.AttemptsCount.Total";
961 system_state_->metrics_lib()->SendToUMA(
962 metric,
963 total_attempts,
964 1, // min
965 50, // max
966 kNumDefaultUmaBuckets);
967 LOG(INFO) << "Uploading " << total_attempts
968 << " for metric " << metric;
969}
970
Jay Srinivasan19409b72013-04-12 19:23:36 -0700971string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
972 return prefix + "-from-" + utils::ToString(source);
973}
974
975void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
976 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosaaa18e162013-06-20 13:20:30 -0700977 SetCurrentBytesDownloaded(source, GetPersistedValue(key, false), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700978}
979
980void PayloadState::SetCurrentBytesDownloaded(
981 DownloadSource source,
982 uint64_t current_bytes_downloaded,
983 bool log) {
984 CHECK(prefs_);
985
986 if (source >= kNumDownloadSources)
987 return;
988
989 // Update the in-memory value.
990 current_bytes_downloaded_[source] = current_bytes_downloaded;
991
992 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
993 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
994 LOG_IF(INFO, log) << "Current bytes downloaded for "
995 << utils::ToString(source) << " = "
996 << GetCurrentBytesDownloaded(source);
997}
998
999void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1000 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosaaa18e162013-06-20 13:20:30 -07001001 SetTotalBytesDownloaded(source, GetPersistedValue(key, false), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001002}
1003
1004void PayloadState::SetTotalBytesDownloaded(
1005 DownloadSource source,
1006 uint64_t total_bytes_downloaded,
1007 bool log) {
1008 CHECK(prefs_);
1009
1010 if (source >= kNumDownloadSources)
1011 return;
1012
1013 // Update the in-memory value.
1014 total_bytes_downloaded_[source] = total_bytes_downloaded;
1015
1016 // Persist.
1017 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1018 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1019 LOG_IF(INFO, log) << "Total bytes downloaded for "
1020 << utils::ToString(source) << " = "
1021 << GetTotalBytesDownloaded(source);
1022}
1023
David Zeuthena573d6f2013-06-14 16:13:36 -07001024void PayloadState::LoadNumResponsesSeen() {
Chris Sosaaa18e162013-06-20 13:20:30 -07001025 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen, false));
David Zeuthena573d6f2013-06-14 16:13:36 -07001026}
1027
1028void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1029 CHECK(prefs_);
1030 num_responses_seen_ = num_responses_seen;
1031 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1032 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1033}
1034
1035void PayloadState::ReportUpdatesAbandonedCountMetric() {
1036 string metric = "Installer.UpdatesAbandonedCount";
1037 int value = num_responses_seen_ - 1;
1038
1039 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1040 system_state_->metrics_lib()->SendToUMA(
1041 metric,
1042 value,
1043 0, // min value
1044 100, // max value
1045 kNumDefaultUmaBuckets);
1046}
1047
Jay Srinivasan53173b92013-05-17 17:13:01 -07001048void PayloadState::ComputeCandidateUrls() {
1049 bool http_url_ok = false;
1050
1051 if (system_state_->IsOfficialBuild()) {
1052 const policy::DevicePolicy* policy = system_state_->device_policy();
1053 if (!(policy && policy->GetHttpDownloadsEnabled(&http_url_ok) &&
1054 http_url_ok))
1055 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1056 } else {
1057 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1058 http_url_ok = true;
1059 }
1060
1061 candidate_urls_.clear();
1062 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1063 string candidate_url = response_.payload_urls[i];
1064 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1065 continue;
1066 candidate_urls_.push_back(candidate_url);
1067 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1068 << ": " << candidate_url;
1069 }
1070
1071 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1072 << "out of " << response_.payload_urls.size() << " URLs supplied";
1073}
1074
David Zeuthene4c58bf2013-06-18 17:26:50 -07001075void PayloadState::CreateSystemUpdatedMarkerFile() {
1076 CHECK(prefs_);
1077 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1078 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1079}
1080
1081void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1082 // Send |time_to_reboot| as a UMA stat.
1083 string metric = "Installer.TimeToRebootMinutes";
1084 system_state_->metrics_lib()->SendToUMA(metric,
1085 time_to_reboot.InMinutes(),
1086 0, // min: 0 minute
1087 30*24*60, // max: 1 month (approx)
1088 kNumDefaultUmaBuckets);
1089 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1090 << " for metric " << metric;
1091}
1092
1093void PayloadState::UpdateEngineStarted() {
Alex Deymo569c4242013-07-24 12:01:01 -07001094 // Avoid the UpdateEngineStarted actions if this is not the first time we
1095 // run the update engine since reboot.
1096 if (!system_state_->system_rebooted())
1097 return;
1098
David Zeuthene4c58bf2013-06-18 17:26:50 -07001099 // Figure out if we just booted into a new update
1100 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1101 int64_t stored_value;
1102 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1103 Time system_updated_at = Time::FromInternalValue(stored_value);
1104 if (!system_updated_at.is_null()) {
1105 TimeDelta time_to_reboot =
1106 system_state_->clock()->GetWallclockTime() - system_updated_at;
1107 if (time_to_reboot.ToInternalValue() < 0) {
1108 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1109 << utils::ToString(system_updated_at);
1110 } else {
1111 BootedIntoUpdate(time_to_reboot);
1112 }
1113 }
1114 }
1115 prefs_->Delete(kPrefsSystemUpdatedMarker);
1116 }
Alex Deymo42432912013-07-12 20:21:15 -07001117 // Check if it is needed to send metrics about a failed reboot into a new
1118 // version.
1119 ReportFailedBootIfNeeded();
1120}
1121
1122void PayloadState::ReportFailedBootIfNeeded() {
1123 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1124 // payload was marked as ready immediately before the last reboot, and we
1125 // need to check if such payload successfully rebooted or not.
1126 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
1127 string installed_from;
1128 if (!prefs_->GetString(kPrefsTargetVersionInstalledFrom, &installed_from)) {
1129 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1130 return;
1131 }
1132 if (installed_from ==
1133 utils::PartitionNumber(system_state_->hardware()->BootDevice())) {
1134 // A reboot was pending, but the chromebook is again in the same
1135 // BootDevice where the update was installed from.
1136 int64_t target_attempt;
1137 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1138 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1139 "TargetVersionInstalledFrom was present.";
1140 target_attempt = 1;
1141 }
1142
1143 // Report the UMA metric of the current boot failure.
1144 string metric = "Installer.RebootToNewPartitionAttempt";
1145
1146 LOG(INFO) << "Uploading " << target_attempt
1147 << " (count) for metric " << metric;
1148 system_state_->metrics_lib()->SendToUMA(
1149 metric,
1150 target_attempt,
1151 1, // min value
1152 50, // max value
1153 kNumDefaultUmaBuckets);
1154 } else {
1155 prefs_->Delete(kPrefsTargetVersionAttempt);
1156 prefs_->Delete(kPrefsTargetVersionUniqueId);
1157 }
1158 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1159 }
1160}
1161
1162void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1163 // Expect to boot into the new partition in the next reboot setting the
1164 // TargetVersion* flags in the Prefs.
1165 string stored_target_version_uid;
1166 string target_version_id;
1167 string target_partition;
1168 int64_t target_attempt;
1169
1170 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1171 prefs_->GetString(kPrefsTargetVersionUniqueId,
1172 &stored_target_version_uid) &&
1173 stored_target_version_uid == target_version_uid) {
1174 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1175 target_attempt = 0;
1176 } else {
1177 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1178 target_attempt = 0;
1179 }
1180 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1181
1182 prefs_->SetString(kPrefsTargetVersionInstalledFrom,
1183 utils::PartitionNumber(
1184 system_state_->hardware()->BootDevice()));
1185}
1186
1187void PayloadState::ResetUpdateStatus() {
1188 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1189 // rebooted the next boot is not flagged as failed to rebooted into the
1190 // new applied payload.
1191 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1192
1193 // Also decrement the attempt number if it exists.
1194 int64_t target_attempt;
1195 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1196 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt-1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001197}
1198
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001199} // namespace chromeos_update_engine