blob: f7c75dab04810493f07e37a0e07ff27ed0126ff0 [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:
249 case kErrorCodeOmahaRequestEmptyResponseError:
250 case kErrorCodeOmahaRequestXMLParseError:
251 case kErrorCodeOmahaResponseInvalid:
252 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
253 case kErrorCodeOmahaUpdateDeferredPerPolicy:
254 case kErrorCodeOmahaUpdateDeferredForBackoff:
255 case kErrorCodePostinstallPowerwashError:
256 case kErrorCodeUpdateCanceledByChannelChange:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800257 LOG(INFO) << "Not incrementing URL index or failure count for this error";
258 break;
259
David Zeuthena99981f2013-04-29 13:42:47 -0700260 case kErrorCodeSuccess: // success code
David Zeuthena99981f2013-04-29 13:42:47 -0700261 case kErrorCodeUmaReportedMax: // not an error code
262 case kErrorCodeOmahaRequestHTTPResponseBase: // aggregated already
263 case kErrorCodeDevModeFlag: // not an error code
264 case kErrorCodeResumedFlag: // not an error code
265 case kErrorCodeTestImageFlag: // not an error code
266 case kErrorCodeTestOmahaUrlFlag: // not an error code
267 case kErrorCodeSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800268 // These shouldn't happen. Enumerating these explicitly here so that we
269 // can let the compiler warn about new error codes that are added to
270 // action_processor.h but not added here.
271 LOG(WARNING) << "Unexpected error code for UpdateFailed";
272 break;
273
274 // Note: Not adding a default here so as to let the compiler warn us of
275 // any new enums that were added in the .h but not listed in this switch.
276 }
277}
278
Jay Srinivasan08262882012-12-28 19:29:43 -0800279bool PayloadState::ShouldBackoffDownload() {
280 if (response_.disable_payload_backoff) {
281 LOG(INFO) << "Payload backoff logic is disabled. "
282 "Can proceed with the download";
283 return false;
284 }
285
286 if (response_.is_delta_payload) {
287 // If delta payloads fail, we want to fallback quickly to full payloads as
288 // they are more likely to succeed. Exponential backoffs would greatly
289 // slow down the fallback to full payloads. So we don't backoff for delta
290 // payloads.
291 LOG(INFO) << "No backoffs for delta payloads. "
292 << "Can proceed with the download";
293 return false;
294 }
295
296 if (!utils::IsOfficialBuild()) {
297 // Backoffs are needed only for official builds. We do not want any delays
298 // or update failures due to backoffs during testing or development.
299 LOG(INFO) << "No backoffs for test/dev images. "
300 << "Can proceed with the download";
301 return false;
302 }
303
304 if (backoff_expiry_time_.is_null()) {
305 LOG(INFO) << "No backoff expiry time has been set. "
306 << "Can proceed with the download";
307 return false;
308 }
309
310 if (backoff_expiry_time_ < Time::Now()) {
311 LOG(INFO) << "The backoff expiry time ("
312 << utils::ToString(backoff_expiry_time_)
313 << ") has elapsed. Can proceed with the download";
314 return false;
315 }
316
317 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
318 << utils::ToString(backoff_expiry_time_);
319 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800320}
321
Chris Sosaaa18e162013-06-20 13:20:30 -0700322void PayloadState::Rollback() {
323 SetRollbackVersion(system_state_->request_params()->app_version());
324}
325
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800326void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700327 // Update the payload attempt number for both payload types: full and delta.
328 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Alex Deymo29b51d92013-07-09 15:26:24 -0700329
330 // Report the metric every time the value is incremented.
331 string metric = "Installer.PayloadAttemptNumber";
332 int value = GetPayloadAttemptNumber();
333
334 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
335 system_state_->metrics_lib()->SendToUMA(
336 metric,
337 value,
338 1, // min value
339 50, // max value
340 kNumDefaultUmaBuckets);
Alex Deymo820cc702013-06-28 15:43:46 -0700341}
342
343void PayloadState::IncrementFullPayloadAttemptNumber() {
344 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800345 if (response_.is_delta_payload) {
346 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
347 return;
348 }
349
Alex Deymo29b51d92013-07-09 15:26:24 -0700350 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700351 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800352 UpdateBackoffExpiryTime();
Alex Deymo29b51d92013-07-09 15:26:24 -0700353
354 // Report the metric every time the value is incremented.
355 string metric = "Installer.FullPayloadAttemptNumber";
356 int value = GetFullPayloadAttemptNumber();
357
358 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
359 system_state_->metrics_lib()->SendToUMA(
360 metric,
361 value,
362 1, // min value
363 50, // max value
364 kNumDefaultUmaBuckets);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800365}
366
367void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800368 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700369 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800370 LOG(INFO) << "Incrementing the URL index for next attempt";
371 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800372 } else {
373 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700374 << "0 as we only have " << candidate_urls_.size()
375 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800376 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700377 IncrementPayloadAttemptNumber();
378 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800379 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800380
David Zeuthencc6f9962013-04-18 11:57:24 -0700381 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700382 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700383 SetUrlSwitchCount(url_switch_count_ + 1);
384
Jay Srinivasan08262882012-12-28 19:29:43 -0800385 // Whenever we update the URL index, we should also clear the URL failure
386 // count so we can start over fresh for the new URL.
387 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800388}
389
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800390void PayloadState::IncrementFailureCount() {
391 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800392 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800393 LOG(INFO) << "Incrementing the URL failure count";
394 SetUrlFailureCount(next_url_failure_count);
395 } else {
396 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
397 << ". Trying next available URL";
398 IncrementUrlIndex();
399 }
400}
401
Jay Srinivasan08262882012-12-28 19:29:43 -0800402void PayloadState::UpdateBackoffExpiryTime() {
403 if (response_.disable_payload_backoff) {
404 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
405 SetBackoffExpiryTime(Time());
406 return;
407 }
408
Alex Deymo820cc702013-06-28 15:43:46 -0700409 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800410 SetBackoffExpiryTime(Time());
411 return;
412 }
413
414 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700415 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800416 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Deymo820cc702013-06-28 15:43:46 -0700417 int num_days = 1; // the value to be shifted.
418 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800419
420 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
421 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700422 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800423
424 // The number of days is the minimum of 2 raised to (payload_attempt_number
425 // - 1) or kMaxBackoffDays.
426 num_days = min(num_days << power, kMaxBackoffDays);
427
428 // We don't want all retries to happen exactly at the same time when
429 // retrying after backoff. So add some random minutes to fuzz.
430 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
431 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
432 TimeDelta::FromMinutes(fuzz_minutes);
433 LOG(INFO) << "Incrementing the backoff expiry time by "
434 << utils::FormatTimeDelta(next_backoff_interval);
435 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
436}
437
Jay Srinivasan19409b72013-04-12 19:23:36 -0700438void PayloadState::UpdateCurrentDownloadSource() {
439 current_download_source_ = kNumDownloadSources;
440
Jay Srinivasan53173b92013-05-17 17:13:01 -0700441 if (GetUrlIndex() < candidate_urls_.size()) {
442 string current_url = candidate_urls_[GetUrlIndex()];
Jay Srinivasan19409b72013-04-12 19:23:36 -0700443 if (StartsWithASCII(current_url, "https://", false))
444 current_download_source_ = kDownloadSourceHttpsServer;
445 else if (StartsWithASCII(current_url, "http://", false))
446 current_download_source_ = kDownloadSourceHttpServer;
447 }
448
449 LOG(INFO) << "Current download source: "
450 << utils::ToString(current_download_source_);
451}
452
453void PayloadState::UpdateBytesDownloaded(size_t count) {
454 SetCurrentBytesDownloaded(
455 current_download_source_,
456 GetCurrentBytesDownloaded(current_download_source_) + count,
457 false);
458 SetTotalBytesDownloaded(
459 current_download_source_,
460 GetTotalBytesDownloaded(current_download_source_) + count,
461 false);
462}
463
464void PayloadState::ReportBytesDownloadedMetrics() {
465 // Report metrics collected from all known download sources to UMA.
466 // The reported data is in Megabytes in order to represent a larger
467 // sample range.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700468 int download_sources_used = 0;
469 string metric;
470 uint64_t successful_mbs = 0;
471 uint64_t total_mbs = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700472 for (int i = 0; i < kNumDownloadSources; i++) {
473 DownloadSource source = static_cast<DownloadSource>(i);
474 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
David Zeuthen44848602013-06-24 13:32:14 -0700475 uint64_t mbs;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700476
David Zeuthen44848602013-06-24 13:32:14 -0700477 // Only consider this download source (and send byte counts) as
478 // having been used if we downloaded a non-trivial amount of bytes
479 // (e.g. at least 1 MiB) that contributed to the final success of
480 // the update. Otherwise we're going to end up with a lot of
481 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700482
David Zeuthen44848602013-06-24 13:32:14 -0700483 mbs = GetCurrentBytesDownloaded(source) / kNumBytesInOneMiB;
484 if (mbs > 0) {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700485 download_sources_used |= (1 << source);
486
David Zeuthen44848602013-06-24 13:32:14 -0700487 metric = "Installer.SuccessfulMBsDownloadedFrom" +
488 utils::ToString(source);
489 successful_mbs += mbs;
490 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
491 system_state_->metrics_lib()->SendToUMA(metric,
492 mbs,
493 0, // min
494 kMaxMiBs,
495 kNumDefaultUmaBuckets);
496 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700497 SetCurrentBytesDownloaded(source, 0, true);
498
Jay Srinivasan19409b72013-04-12 19:23:36 -0700499 mbs = GetTotalBytesDownloaded(source) / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700500 if (mbs > 0) {
501 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
502 total_mbs += mbs;
503 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
504 system_state_->metrics_lib()->SendToUMA(metric,
505 mbs,
506 0, // min
507 kMaxMiBs,
508 kNumDefaultUmaBuckets);
509 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700510 SetTotalBytesDownloaded(source, 0, true);
511 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700512
513 metric = "Installer.DownloadSourcesUsed";
514 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
515 << " (bit flags) for metric " << metric;
516 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
517 system_state_->metrics_lib()->SendToUMA(metric,
518 download_sources_used,
519 0, // min
520 1 << kNumDownloadSources,
521 num_buckets);
522
523 if (successful_mbs) {
524 metric = "Installer.DownloadOverheadPercentage";
525 int percent_overhead = (total_mbs - successful_mbs) * 100 / successful_mbs;
526 LOG(INFO) << "Uploading " << percent_overhead << "% for metric " << metric;
527 system_state_->metrics_lib()->SendToUMA(metric,
528 percent_overhead,
529 0, // min: 0% overhead
530 1000, // max: 1000% overhead
531 kNumDefaultUmaBuckets);
532 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700533}
534
David Zeuthencc6f9962013-04-18 11:57:24 -0700535void PayloadState::ReportUpdateUrlSwitchesMetric() {
536 string metric = "Installer.UpdateURLSwitches";
537 int value = static_cast<int>(url_switch_count_);
538
539 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
540 system_state_->metrics_lib()->SendToUMA(
541 metric,
542 value,
543 0, // min value
544 100, // max value
545 kNumDefaultUmaBuckets);
546}
547
Chris Sosabe45bef2013-04-09 18:25:12 -0700548void PayloadState::ReportRebootMetrics() {
549 // Report the number of num_reboots.
550 string metric = "Installer.UpdateNumReboots";
551 uint32_t num_reboots = GetNumReboots();
552 LOG(INFO) << "Uploading reboot count of " << num_reboots << " for metric "
553 << metric;
554 system_state_->metrics_lib()->SendToUMA(
555 metric,
556 static_cast<int>(num_reboots), // sample
557 0, // min = 0.
558 50, // max
559 25); // buckets
560 SetNumReboots(0);
561}
562
563void PayloadState::UpdateNumReboots() {
564 // We only update the reboot count when the system has been detected to have
565 // been rebooted.
566 if (!system_state_->system_rebooted()) {
567 return;
568 }
569
570 SetNumReboots(GetNumReboots() + 1);
571}
572
573void PayloadState::SetNumReboots(uint32_t num_reboots) {
574 CHECK(prefs_);
575 num_reboots_ = num_reboots;
576 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
577 LOG(INFO) << "Number of Reboots during current update attempt = "
578 << num_reboots_;
579}
580
Jay Srinivasan08262882012-12-28 19:29:43 -0800581void PayloadState::ResetPersistedState() {
582 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700583 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800584 SetUrlIndex(0);
585 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700586 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800587 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700588 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
David Zeuthen9a017f22013-04-11 16:10:26 -0700589 SetUpdateTimestampEnd(Time()); // Set to null time
590 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700591 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700592 ResetRollbackVersion();
593}
594
595void PayloadState::ResetRollbackVersion() {
596 CHECK(powerwash_safe_prefs_);
597 rollback_version_ = "";
598 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700599}
600
601void PayloadState::ResetDownloadSourcesOnNewUpdate() {
602 for (int i = 0; i < kNumDownloadSources; i++) {
603 DownloadSource source = static_cast<DownloadSource>(i);
604 SetCurrentBytesDownloaded(source, 0, true);
605 // Note: Not resetting the TotalBytesDownloaded as we want that metric
606 // to count the bytes downloaded across various update attempts until
607 // we have successfully applied the update.
608 }
609}
610
Chris Sosaaa18e162013-06-20 13:20:30 -0700611int64_t PayloadState::GetPersistedValue(const string& key,
612 bool across_powerwash) {
613 PrefsInterface* prefs = prefs_;
614 if (across_powerwash)
615 prefs = powerwash_safe_prefs_;
616
Jay Srinivasan19409b72013-04-12 19:23:36 -0700617 CHECK(prefs_);
Chris Sosaaa18e162013-06-20 13:20:30 -0700618 if (!prefs->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700619 return 0;
620
621 int64_t stored_value;
Chris Sosaaa18e162013-06-20 13:20:30 -0700622 if (!prefs->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700623 return 0;
624
625 if (stored_value < 0) {
626 LOG(ERROR) << key << ": Invalid value (" << stored_value
627 << ") in persisted state. Defaulting to 0";
628 return 0;
629 }
630
631 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800632}
633
634string PayloadState::CalculateResponseSignature() {
635 string response_sign = StringPrintf("NumURLs = %d\n",
Jay Srinivasan53173b92013-05-17 17:13:01 -0700636 candidate_urls_.size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800637
Jay Srinivasan53173b92013-05-17 17:13:01 -0700638 for (size_t i = 0; i < candidate_urls_.size(); i++)
639 response_sign += StringPrintf("Candidate Url%d = %s\n",
640 i, candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800641
642 response_sign += StringPrintf("Payload Size = %llu\n"
643 "Payload Sha256 Hash = %s\n"
644 "Metadata Size = %llu\n"
645 "Metadata Signature = %s\n"
646 "Is Delta Payload = %d\n"
647 "Max Failure Count Per Url = %d\n"
648 "Disable Payload Backoff = %d\n",
649 response_.size,
650 response_.hash.c_str(),
651 response_.metadata_size,
652 response_.metadata_signature.c_str(),
653 response_.is_delta_payload,
654 response_.max_failure_count_per_url,
655 response_.disable_payload_backoff);
656 return response_sign;
657}
658
659void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800660 CHECK(prefs_);
661 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800662 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
663 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
664 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800665 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800666}
667
Jay Srinivasan19409b72013-04-12 19:23:36 -0700668void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800669 CHECK(prefs_);
670 response_signature_ = response_signature;
671 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
672 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
673}
674
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800675void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700676 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber,
677 false));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800678}
679
Alex Deymo820cc702013-06-28 15:43:46 -0700680void PayloadState::LoadFullPayloadAttemptNumber() {
681 SetFullPayloadAttemptNumber(GetPersistedValue(kPrefsFullPayloadAttemptNumber,
682 false));
683}
684
685void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800686 CHECK(prefs_);
687 payload_attempt_number_ = payload_attempt_number;
688 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
689 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
690}
691
Alex Deymo820cc702013-06-28 15:43:46 -0700692void PayloadState::SetFullPayloadAttemptNumber(
693 int full_payload_attempt_number) {
694 CHECK(prefs_);
695 full_payload_attempt_number_ = full_payload_attempt_number;
696 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
697 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
698 full_payload_attempt_number_);
699}
700
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800701void PayloadState::LoadUrlIndex() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700702 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex, false));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800703}
704
705void PayloadState::SetUrlIndex(uint32_t url_index) {
706 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800707 url_index_ = url_index;
708 LOG(INFO) << "Current URL Index = " << url_index_;
709 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700710
711 // Also update the download source, which is purely dependent on the
712 // current URL index alone.
713 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800714}
715
David Zeuthencc6f9962013-04-18 11:57:24 -0700716void PayloadState::LoadUrlSwitchCount() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700717 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount, false));
David Zeuthencc6f9962013-04-18 11:57:24 -0700718}
719
720void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
721 CHECK(prefs_);
722 url_switch_count_ = url_switch_count;
723 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
724 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
725}
726
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800727void PayloadState::LoadUrlFailureCount() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700728 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount,
729 false));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800730}
731
732void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
733 CHECK(prefs_);
734 url_failure_count_ = url_failure_count;
735 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
736 << ")'s Failure Count = " << url_failure_count_;
737 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800738}
739
Jay Srinivasan08262882012-12-28 19:29:43 -0800740void PayloadState::LoadBackoffExpiryTime() {
741 CHECK(prefs_);
742 int64_t stored_value;
743 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
744 return;
745
746 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
747 return;
748
749 Time stored_time = Time::FromInternalValue(stored_value);
750 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
751 LOG(ERROR) << "Invalid backoff expiry time ("
752 << utils::ToString(stored_time)
753 << ") in persisted state. Resetting.";
754 stored_time = Time();
755 }
756 SetBackoffExpiryTime(stored_time);
757}
758
759void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
760 CHECK(prefs_);
761 backoff_expiry_time_ = new_time;
762 LOG(INFO) << "Backoff Expiry Time = "
763 << utils::ToString(backoff_expiry_time_);
764 prefs_->SetInt64(kPrefsBackoffExpiryTime,
765 backoff_expiry_time_.ToInternalValue());
766}
767
David Zeuthen9a017f22013-04-11 16:10:26 -0700768TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700769 Time end_time = update_timestamp_end_.is_null()
770 ? system_state_->clock()->GetWallclockTime() :
771 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700772 return end_time - update_timestamp_start_;
773}
774
775void PayloadState::LoadUpdateTimestampStart() {
776 int64_t stored_value;
777 Time stored_time;
778
779 CHECK(prefs_);
780
David Zeuthenf413fe52013-04-22 14:04:39 -0700781 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700782
783 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
784 // The preference missing is not unexpected - in that case, just
785 // use the current time as start time
786 stored_time = now;
787 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
788 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
789 stored_time = now;
790 } else {
791 stored_time = Time::FromInternalValue(stored_value);
792 }
793
794 // Sanity check: If the time read from disk is in the future
795 // (modulo some slack to account for possible NTP drift
796 // adjustments), something is fishy and we should report and
797 // reset.
798 TimeDelta duration_according_to_stored_time = now - stored_time;
799 if (duration_according_to_stored_time < -kDurationSlack) {
800 LOG(ERROR) << "The UpdateTimestampStart value ("
801 << utils::ToString(stored_time)
802 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700803 << utils::FormatTimeDelta(duration_according_to_stored_time)
804 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700805 stored_time = now;
806 }
807
808 SetUpdateTimestampStart(stored_time);
809}
810
811void PayloadState::SetUpdateTimestampStart(const Time& value) {
812 CHECK(prefs_);
813 update_timestamp_start_ = value;
814 prefs_->SetInt64(kPrefsUpdateTimestampStart,
815 update_timestamp_start_.ToInternalValue());
816 LOG(INFO) << "Update Timestamp Start = "
817 << utils::ToString(update_timestamp_start_);
818}
819
820void PayloadState::SetUpdateTimestampEnd(const Time& value) {
821 update_timestamp_end_ = value;
822 LOG(INFO) << "Update Timestamp End = "
823 << utils::ToString(update_timestamp_end_);
824}
825
826TimeDelta PayloadState::GetUpdateDurationUptime() {
827 return update_duration_uptime_;
828}
829
830void PayloadState::LoadUpdateDurationUptime() {
831 int64_t stored_value;
832 TimeDelta stored_delta;
833
834 CHECK(prefs_);
835
836 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
837 // The preference missing is not unexpected - in that case, just
838 // we'll use zero as the delta
839 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
840 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
841 stored_delta = TimeDelta::FromSeconds(0);
842 } else {
843 stored_delta = TimeDelta::FromInternalValue(stored_value);
844 }
845
846 // Sanity-check: Uptime can never be greater than the wall-clock
847 // difference (modulo some slack). If it is, report and reset
848 // to the wall-clock difference.
849 TimeDelta diff = GetUpdateDuration() - stored_delta;
850 if (diff < -kDurationSlack) {
851 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -0700852 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -0700853 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700854 << utils::FormatTimeDelta(diff)
855 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700856 stored_delta = update_duration_current_;
857 }
858
859 SetUpdateDurationUptime(stored_delta);
860}
861
Chris Sosabe45bef2013-04-09 18:25:12 -0700862void PayloadState::LoadNumReboots() {
Chris Sosaaa18e162013-06-20 13:20:30 -0700863 SetNumReboots(GetPersistedValue(kPrefsNumReboots, false));
864}
865
866void PayloadState::LoadRollbackVersion() {
867 SetNumReboots(GetPersistedValue(kPrefsRollbackVersion, true));
868}
869
870void PayloadState::SetRollbackVersion(const string& rollback_version) {
871 CHECK(powerwash_safe_prefs_);
872 LOG(INFO) << "Blacklisting version "<< rollback_version;
873 rollback_version_ = rollback_version;
874 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -0700875}
876
David Zeuthen9a017f22013-04-11 16:10:26 -0700877void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
878 const Time& timestamp,
879 bool use_logging) {
880 CHECK(prefs_);
881 update_duration_uptime_ = value;
882 update_duration_uptime_timestamp_ = timestamp;
883 prefs_->SetInt64(kPrefsUpdateDurationUptime,
884 update_duration_uptime_.ToInternalValue());
885 if (use_logging) {
886 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -0700887 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -0700888 }
889}
890
891void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -0700892 Time now = system_state_->clock()->GetMonotonicTime();
893 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -0700894}
895
896void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700897 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700898 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
899 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
900 // We're frequently called so avoid logging this write
901 SetUpdateDurationUptimeExtended(new_uptime, now, false);
902}
903
David Zeuthen674c3182013-04-18 14:05:20 -0700904void PayloadState::ReportDurationMetrics() {
905 TimeDelta duration = GetUpdateDuration();
906 TimeDelta duration_uptime = GetUpdateDurationUptime();
907 string metric;
908
909 metric = "Installer.UpdateDurationMinutes";
910 system_state_->metrics_lib()->SendToUMA(
911 metric,
912 static_cast<int>(duration.InMinutes()),
913 1, // min: 1 minute
914 365*24*60, // max: 1 year (approx)
915 kNumDefaultUmaBuckets);
916 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
917 << " for metric " << metric;
918
919 metric = "Installer.UpdateDurationUptimeMinutes";
920 system_state_->metrics_lib()->SendToUMA(
921 metric,
922 static_cast<int>(duration_uptime.InMinutes()),
923 1, // min: 1 minute
924 30*24*60, // max: 1 month (approx)
925 kNumDefaultUmaBuckets);
926 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
927 << " for metric " << metric;
928
929 prefs_->Delete(kPrefsUpdateTimestampStart);
930 prefs_->Delete(kPrefsUpdateDurationUptime);
931}
932
Alex Deymo1c656c42013-06-28 11:02:14 -0700933void PayloadState::ReportPayloadTypeMetric() {
934 string metric;
935 PayloadType uma_payload_type;
936 OmahaRequestParams* params = system_state_->request_params();
937
938 if (response_.is_delta_payload) {
939 uma_payload_type = kPayloadTypeDelta;
940 } else if (params->delta_okay()) {
941 uma_payload_type = kPayloadTypeFull;
942 } else { // Full payload, delta was not allowed by request.
943 uma_payload_type = kPayloadTypeForcedFull;
944 }
945
946 metric = "Installer.PayloadFormat";
947 system_state_->metrics_lib()->SendEnumToUMA(
948 metric,
949 uma_payload_type,
950 kNumPayloadTypes);
951 LOG(INFO) << "Uploading " << utils::ToString(uma_payload_type)
952 << " for metric " << metric;
953}
954
Alex Deymo820cc702013-06-28 15:43:46 -0700955void PayloadState::ReportAttemptsCountMetrics() {
956 string metric;
957 int total_attempts = GetPayloadAttemptNumber();
958
959 metric = "Installer.AttemptsCount.Total";
960 system_state_->metrics_lib()->SendToUMA(
961 metric,
962 total_attempts,
963 1, // min
964 50, // max
965 kNumDefaultUmaBuckets);
966 LOG(INFO) << "Uploading " << total_attempts
967 << " for metric " << metric;
968}
969
Jay Srinivasan19409b72013-04-12 19:23:36 -0700970string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
971 return prefix + "-from-" + utils::ToString(source);
972}
973
974void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
975 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosaaa18e162013-06-20 13:20:30 -0700976 SetCurrentBytesDownloaded(source, GetPersistedValue(key, false), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700977}
978
979void PayloadState::SetCurrentBytesDownloaded(
980 DownloadSource source,
981 uint64_t current_bytes_downloaded,
982 bool log) {
983 CHECK(prefs_);
984
985 if (source >= kNumDownloadSources)
986 return;
987
988 // Update the in-memory value.
989 current_bytes_downloaded_[source] = current_bytes_downloaded;
990
991 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
992 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
993 LOG_IF(INFO, log) << "Current bytes downloaded for "
994 << utils::ToString(source) << " = "
995 << GetCurrentBytesDownloaded(source);
996}
997
998void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
999 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosaaa18e162013-06-20 13:20:30 -07001000 SetTotalBytesDownloaded(source, GetPersistedValue(key, false), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001001}
1002
1003void PayloadState::SetTotalBytesDownloaded(
1004 DownloadSource source,
1005 uint64_t total_bytes_downloaded,
1006 bool log) {
1007 CHECK(prefs_);
1008
1009 if (source >= kNumDownloadSources)
1010 return;
1011
1012 // Update the in-memory value.
1013 total_bytes_downloaded_[source] = total_bytes_downloaded;
1014
1015 // Persist.
1016 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1017 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1018 LOG_IF(INFO, log) << "Total bytes downloaded for "
1019 << utils::ToString(source) << " = "
1020 << GetTotalBytesDownloaded(source);
1021}
1022
David Zeuthena573d6f2013-06-14 16:13:36 -07001023void PayloadState::LoadNumResponsesSeen() {
Chris Sosaaa18e162013-06-20 13:20:30 -07001024 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen, false));
David Zeuthena573d6f2013-06-14 16:13:36 -07001025}
1026
1027void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1028 CHECK(prefs_);
1029 num_responses_seen_ = num_responses_seen;
1030 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1031 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1032}
1033
1034void PayloadState::ReportUpdatesAbandonedCountMetric() {
1035 string metric = "Installer.UpdatesAbandonedCount";
1036 int value = num_responses_seen_ - 1;
1037
1038 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1039 system_state_->metrics_lib()->SendToUMA(
1040 metric,
1041 value,
1042 0, // min value
1043 100, // max value
1044 kNumDefaultUmaBuckets);
1045}
1046
Jay Srinivasan53173b92013-05-17 17:13:01 -07001047void PayloadState::ComputeCandidateUrls() {
1048 bool http_url_ok = false;
1049
1050 if (system_state_->IsOfficialBuild()) {
1051 const policy::DevicePolicy* policy = system_state_->device_policy();
1052 if (!(policy && policy->GetHttpDownloadsEnabled(&http_url_ok) &&
1053 http_url_ok))
1054 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1055 } else {
1056 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1057 http_url_ok = true;
1058 }
1059
1060 candidate_urls_.clear();
1061 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1062 string candidate_url = response_.payload_urls[i];
1063 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1064 continue;
1065 candidate_urls_.push_back(candidate_url);
1066 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1067 << ": " << candidate_url;
1068 }
1069
1070 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1071 << "out of " << response_.payload_urls.size() << " URLs supplied";
1072}
1073
David Zeuthene4c58bf2013-06-18 17:26:50 -07001074void PayloadState::CreateSystemUpdatedMarkerFile() {
1075 CHECK(prefs_);
1076 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1077 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1078}
1079
1080void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1081 // Send |time_to_reboot| as a UMA stat.
1082 string metric = "Installer.TimeToRebootMinutes";
1083 system_state_->metrics_lib()->SendToUMA(metric,
1084 time_to_reboot.InMinutes(),
1085 0, // min: 0 minute
1086 30*24*60, // max: 1 month (approx)
1087 kNumDefaultUmaBuckets);
1088 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1089 << " for metric " << metric;
1090}
1091
1092void PayloadState::UpdateEngineStarted() {
Alex Deymo569c4242013-07-24 12:01:01 -07001093 // Avoid the UpdateEngineStarted actions if this is not the first time we
1094 // run the update engine since reboot.
1095 if (!system_state_->system_rebooted())
1096 return;
1097
David Zeuthene4c58bf2013-06-18 17:26:50 -07001098 // Figure out if we just booted into a new update
1099 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1100 int64_t stored_value;
1101 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1102 Time system_updated_at = Time::FromInternalValue(stored_value);
1103 if (!system_updated_at.is_null()) {
1104 TimeDelta time_to_reboot =
1105 system_state_->clock()->GetWallclockTime() - system_updated_at;
1106 if (time_to_reboot.ToInternalValue() < 0) {
1107 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1108 << utils::ToString(system_updated_at);
1109 } else {
1110 BootedIntoUpdate(time_to_reboot);
1111 }
1112 }
1113 }
1114 prefs_->Delete(kPrefsSystemUpdatedMarker);
1115 }
Alex Deymo42432912013-07-12 20:21:15 -07001116 // Check if it is needed to send metrics about a failed reboot into a new
1117 // version.
1118 ReportFailedBootIfNeeded();
1119}
1120
1121void PayloadState::ReportFailedBootIfNeeded() {
1122 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1123 // payload was marked as ready immediately before the last reboot, and we
1124 // need to check if such payload successfully rebooted or not.
1125 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
1126 string installed_from;
1127 if (!prefs_->GetString(kPrefsTargetVersionInstalledFrom, &installed_from)) {
1128 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1129 return;
1130 }
1131 if (installed_from ==
1132 utils::PartitionNumber(system_state_->hardware()->BootDevice())) {
1133 // A reboot was pending, but the chromebook is again in the same
1134 // BootDevice where the update was installed from.
1135 int64_t target_attempt;
1136 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1137 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1138 "TargetVersionInstalledFrom was present.";
1139 target_attempt = 1;
1140 }
1141
1142 // Report the UMA metric of the current boot failure.
1143 string metric = "Installer.RebootToNewPartitionAttempt";
1144
1145 LOG(INFO) << "Uploading " << target_attempt
1146 << " (count) for metric " << metric;
1147 system_state_->metrics_lib()->SendToUMA(
1148 metric,
1149 target_attempt,
1150 1, // min value
1151 50, // max value
1152 kNumDefaultUmaBuckets);
1153 } else {
1154 prefs_->Delete(kPrefsTargetVersionAttempt);
1155 prefs_->Delete(kPrefsTargetVersionUniqueId);
1156 }
1157 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1158 }
1159}
1160
1161void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1162 // Expect to boot into the new partition in the next reboot setting the
1163 // TargetVersion* flags in the Prefs.
1164 string stored_target_version_uid;
1165 string target_version_id;
1166 string target_partition;
1167 int64_t target_attempt;
1168
1169 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1170 prefs_->GetString(kPrefsTargetVersionUniqueId,
1171 &stored_target_version_uid) &&
1172 stored_target_version_uid == target_version_uid) {
1173 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1174 target_attempt = 0;
1175 } else {
1176 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1177 target_attempt = 0;
1178 }
1179 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1180
1181 prefs_->SetString(kPrefsTargetVersionInstalledFrom,
1182 utils::PartitionNumber(
1183 system_state_->hardware()->BootDevice()));
1184}
1185
1186void PayloadState::ResetUpdateStatus() {
1187 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1188 // rebooted the next boot is not flagged as failed to rebooted into the
1189 // new applied payload.
1190 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1191
1192 // Also decrement the attempt number if it exists.
1193 int64_t target_attempt;
1194 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1195 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt-1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001196}
1197
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001198} // namespace chromeos_update_engine