blob: 779f708afaa487a723658336f0cce9cf9c29dda3 [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>
Alex Vakulenko75039d72014-03-25 12:36:28 -070010#include <base/strings/string_util.h>
11#include <base/strings/stringprintf.h>
12#include <base/format_macros.h>
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080013
David Zeuthenf413fe52013-04-22 14:04:39 -070014#include "update_engine/clock.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070015#include "update_engine/constants.h"
Alex Deymo42432912013-07-12 20:21:15 -070016#include "update_engine/hardware_interface.h"
17#include "update_engine/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070018#include "update_engine/prefs.h"
19#include "update_engine/system_state.h"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080020#include "update_engine/utils.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080021
Jay Srinivasan08262882012-12-28 19:29:43 -080022using base::Time;
23using base::TimeDelta;
24using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080025using std::string;
26
27namespace chromeos_update_engine {
28
David Zeuthen9a017f22013-04-11 16:10:26 -070029const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
30
Jay Srinivasan08262882012-12-28 19:29:43 -080031// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070032static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080033
Jay Srinivasan08262882012-12-28 19:29:43 -080034// We want to randomize retry attempts after the backoff by +/- 6 hours.
35static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080036
Jay Srinivasan19409b72013-04-12 19:23:36 -070037PayloadState::PayloadState()
38 : prefs_(NULL),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070039 using_p2p_for_downloading_(false),
Jay Srinivasan19409b72013-04-12 19:23:36 -070040 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070041 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070042 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070043 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070044 url_switch_count_(0),
45 p2p_num_attempts_(0) {
Jay Srinivasan19409b72013-04-12 19:23:36 -070046 for (int i = 0; i <= kNumDownloadSources; i++)
47 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
48}
49
50bool PayloadState::Initialize(SystemState* system_state) {
51 system_state_ = system_state;
52 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070053 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080054 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080055 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070056 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080057 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080058 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070059 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080060 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070061 LoadUpdateTimestampStart();
62 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
63 // being called before it. Don't reorder.
64 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070065 for (int i = 0; i < kNumDownloadSources; i++) {
66 DownloadSource source = static_cast<DownloadSource>(i);
67 LoadCurrentBytesDownloaded(source);
68 LoadTotalBytesDownloaded(source);
69 }
Chris Sosabe45bef2013-04-09 18:25:12 -070070 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070071 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070072 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070073 LoadP2PFirstAttemptTimestamp();
74 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080075 return true;
76}
77
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080078void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080079 // Always store the latest response.
80 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080081
Jay Srinivasan53173b92013-05-17 17:13:01 -070082 // Compute the candidate URLs first as they are used to calculate the
83 // response signature so that a change in enterprise policy for
84 // HTTP downloads being enabled or not could be honored as soon as the
85 // next update check happens.
86 ComputeCandidateUrls();
87
Jay Srinivasan08262882012-12-28 19:29:43 -080088 // Check if the "signature" of this response (i.e. the fields we care about)
89 // has changed.
90 string new_response_signature = CalculateResponseSignature();
91 bool has_response_changed = (response_signature_ != new_response_signature);
92
93 // If the response has changed, we should persist the new signature and
94 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080095 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -080096 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -070097 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -080098 SetResponseSignature(new_response_signature);
99 ResetPersistedState();
Alex Deymob33b0f02013-08-08 21:10:02 -0700100 ReportUpdatesAbandonedEventCountMetric();
Jay Srinivasan08262882012-12-28 19:29:43 -0800101 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800102 }
103
Jay Srinivasan08262882012-12-28 19:29:43 -0800104 // This is the earliest point at which we can validate whether the URL index
105 // we loaded from the persisted state is a valid value. If the response
106 // hasn't changed but the URL index is invalid, it's indicative of some
107 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700108 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800109 LOG(INFO) << "Resetting all payload state as the url index seems to have "
110 "been tampered with";
111 ResetPersistedState();
112 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800113 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700114
115 // Update the current download source which depends on the latest value of
116 // the response.
117 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800118}
119
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700120void PayloadState::SetUsingP2PForDownloading(bool value) {
121 using_p2p_for_downloading_ = value;
122 // Update the current download source which depends on whether we are
123 // using p2p or not.
124 UpdateCurrentDownloadSource();
125}
126
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800127void PayloadState::DownloadComplete() {
128 LOG(INFO) << "Payload downloaded successfully";
129 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700130 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800131}
132
133void PayloadState::DownloadProgress(size_t count) {
134 if (count == 0)
135 return;
136
David Zeuthen9a017f22013-04-11 16:10:26 -0700137 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700138 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700139
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800140 // We've received non-zero bytes from a recent download operation. Since our
141 // URL failure count is meant to penalize a URL only for consecutive
142 // failures, downloading bytes successfully means we should reset the failure
143 // count (as we know at least that the URL is working). In future, we can
144 // design this to be more sophisticated to check for more intelligent failure
145 // patterns, but right now, even 1 byte downloaded will mark the URL to be
146 // good unless it hits 10 (or configured number of) consecutive failures
147 // again.
148
149 if (GetUrlFailureCount() == 0)
150 return;
151
152 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
153 << " to 0 as we received " << count << " bytes successfully";
154 SetUrlFailureCount(0);
155}
156
David Zeuthen33bae492014-02-25 16:16:18 -0800157void PayloadState::AttemptStarted() {
158 ClockInterface *clock = system_state_->clock();
159 attempt_start_time_boot_ = clock->GetBootTime();
160 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
161
162 attempt_num_bytes_downloaded_ = 0;
163}
164
Chris Sosabe45bef2013-04-09 18:25:12 -0700165void PayloadState::UpdateResumed() {
166 LOG(INFO) << "Resuming an update that was previously started.";
167 UpdateNumReboots();
David Zeuthen33bae492014-02-25 16:16:18 -0800168 AttemptStarted();
Chris Sosabe45bef2013-04-09 18:25:12 -0700169}
170
Jay Srinivasan19409b72013-04-12 19:23:36 -0700171void PayloadState::UpdateRestarted() {
172 LOG(INFO) << "Starting a new update";
173 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700174 SetNumReboots(0);
David Zeuthen33bae492014-02-25 16:16:18 -0800175 AttemptStarted();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700176}
177
David Zeuthen9a017f22013-04-11 16:10:26 -0700178void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700179 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700180 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700181 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800182
183 CollectAndReportAttemptMetrics(kErrorCodeSuccess);
184 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthena573d6f2013-06-14 16:13:36 -0700185
186 // Reset the number of responses seen since it counts from the last
187 // successful update, e.g. now.
188 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700189
190 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700191}
192
David Zeuthena99981f2013-04-29 13:42:47 -0700193void PayloadState::UpdateFailed(ErrorCode error) {
194 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800195 LOG(INFO) << "Updating payload state for error code: " << base_error
196 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800197
Jay Srinivasan53173b92013-05-17 17:13:01 -0700198 if (candidate_urls_.size() == 0) {
199 // This means we got this error even before we got a valid Omaha response
200 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800201 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800202 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
203 return;
204 }
205
David Zeuthen33bae492014-02-25 16:16:18 -0800206 CollectAndReportAttemptMetrics(base_error);
207
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800208 switch (base_error) {
209 // Errors which are good indicators of a problem with a particular URL or
210 // the protocol used in the URL or entities in the communication channel
211 // (e.g. proxies). We should try the next available URL in the next update
212 // check to quickly recover from these errors.
David Zeuthena99981f2013-04-29 13:42:47 -0700213 case kErrorCodePayloadHashMismatchError:
214 case kErrorCodePayloadSizeMismatchError:
215 case kErrorCodeDownloadPayloadVerificationError:
216 case kErrorCodeDownloadPayloadPubKeyVerificationError:
217 case kErrorCodeSignedDeltaPayloadExpectedError:
218 case kErrorCodeDownloadInvalidMetadataMagicString:
219 case kErrorCodeDownloadSignatureMissingInManifest:
220 case kErrorCodeDownloadManifestParseError:
221 case kErrorCodeDownloadMetadataSignatureError:
222 case kErrorCodeDownloadMetadataSignatureVerificationError:
223 case kErrorCodeDownloadMetadataSignatureMismatch:
224 case kErrorCodeDownloadOperationHashVerificationError:
225 case kErrorCodeDownloadOperationExecutionError:
226 case kErrorCodeDownloadOperationHashMismatch:
227 case kErrorCodeDownloadInvalidMetadataSize:
228 case kErrorCodeDownloadInvalidMetadataSignature:
229 case kErrorCodeDownloadOperationHashMissingError:
230 case kErrorCodeDownloadMetadataSignatureMissingError:
Gilad Arnold21504f02013-05-24 08:51:22 -0700231 case kErrorCodePayloadMismatchedType:
Don Garrett4d039442013-10-28 18:40:06 -0700232 case kErrorCodeUnsupportedMajorPayloadVersion:
233 case kErrorCodeUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800234 IncrementUrlIndex();
235 break;
236
237 // Errors which seem to be just transient network/communication related
238 // failures and do not indicate any inherent problem with the URL itself.
239 // So, we should keep the current URL but just increment the
240 // failure count to give it more chances. This way, while we maximize our
241 // chances of downloading from the URLs that appear earlier in the response
242 // (because download from a local server URL that appears earlier in a
243 // response is preferable than downloading from the next URL which could be
244 // a internet URL and thus could be more expensive).
David Zeuthena99981f2013-04-29 13:42:47 -0700245 case kErrorCodeError:
246 case kErrorCodeDownloadTransferError:
247 case kErrorCodeDownloadWriteError:
248 case kErrorCodeDownloadStateInitializationError:
249 case kErrorCodeOmahaErrorInHTTPResponse: // Aggregate code for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800250 IncrementFailureCount();
251 break;
252
253 // Errors which are not specific to a URL and hence shouldn't result in
254 // the URL being penalized. This can happen in two cases:
255 // 1. We haven't started downloading anything: These errors don't cost us
256 // anything in terms of actual payload bytes, so we should just do the
257 // regular retries at the next update check.
258 // 2. We have successfully downloaded the payload: In this case, the
259 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800260 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800261 // In either case, there's no need to update URL index or failure count.
David Zeuthena99981f2013-04-29 13:42:47 -0700262 case kErrorCodeOmahaRequestError:
263 case kErrorCodeOmahaResponseHandlerError:
264 case kErrorCodePostinstallRunnerError:
265 case kErrorCodeFilesystemCopierError:
266 case kErrorCodeInstallDeviceOpenError:
267 case kErrorCodeKernelDeviceOpenError:
268 case kErrorCodeDownloadNewPartitionInfoError:
269 case kErrorCodeNewRootfsVerificationError:
270 case kErrorCodeNewKernelVerificationError:
271 case kErrorCodePostinstallBootedFromFirmwareB:
Don Garrett81018e02013-07-30 18:46:31 -0700272 case kErrorCodePostinstallFirmwareRONotUpdatable:
David Zeuthena99981f2013-04-29 13:42:47 -0700273 case kErrorCodeOmahaRequestEmptyResponseError:
274 case kErrorCodeOmahaRequestXMLParseError:
275 case kErrorCodeOmahaResponseInvalid:
276 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
277 case kErrorCodeOmahaUpdateDeferredPerPolicy:
278 case kErrorCodeOmahaUpdateDeferredForBackoff:
279 case kErrorCodePostinstallPowerwashError:
280 case kErrorCodeUpdateCanceledByChannelChange:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800281 LOG(INFO) << "Not incrementing URL index or failure count for this error";
282 break;
283
David Zeuthena99981f2013-04-29 13:42:47 -0700284 case kErrorCodeSuccess: // success code
David Zeuthena99981f2013-04-29 13:42:47 -0700285 case kErrorCodeUmaReportedMax: // not an error code
286 case kErrorCodeOmahaRequestHTTPResponseBase: // aggregated already
287 case kErrorCodeDevModeFlag: // not an error code
288 case kErrorCodeResumedFlag: // not an error code
289 case kErrorCodeTestImageFlag: // not an error code
290 case kErrorCodeTestOmahaUrlFlag: // not an error code
291 case kErrorCodeSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800292 // These shouldn't happen. Enumerating these explicitly here so that we
293 // can let the compiler warn about new error codes that are added to
294 // action_processor.h but not added here.
295 LOG(WARNING) << "Unexpected error code for UpdateFailed";
296 break;
297
298 // Note: Not adding a default here so as to let the compiler warn us of
299 // any new enums that were added in the .h but not listed in this switch.
300 }
301}
302
Jay Srinivasan08262882012-12-28 19:29:43 -0800303bool PayloadState::ShouldBackoffDownload() {
304 if (response_.disable_payload_backoff) {
305 LOG(INFO) << "Payload backoff logic is disabled. "
306 "Can proceed with the download";
307 return false;
308 }
Chris Sosa20f005c2013-09-05 13:53:08 -0700309 if (system_state_->request_params()->use_p2p_for_downloading() &&
310 !system_state_->request_params()->p2p_url().empty()) {
311 LOG(INFO) << "Payload backoff logic is disabled because download "
312 << "will happen from local peer (via p2p).";
313 return false;
314 }
315 if (system_state_->request_params()->interactive()) {
316 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
317 return false;
318 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800319 if (response_.is_delta_payload) {
320 // If delta payloads fail, we want to fallback quickly to full payloads as
321 // they are more likely to succeed. Exponential backoffs would greatly
322 // slow down the fallback to full payloads. So we don't backoff for delta
323 // payloads.
324 LOG(INFO) << "No backoffs for delta payloads. "
325 << "Can proceed with the download";
326 return false;
327 }
328
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700329 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800330 // Backoffs are needed only for official builds. We do not want any delays
331 // or update failures due to backoffs during testing or development.
332 LOG(INFO) << "No backoffs for test/dev images. "
333 << "Can proceed with the download";
334 return false;
335 }
336
337 if (backoff_expiry_time_.is_null()) {
338 LOG(INFO) << "No backoff expiry time has been set. "
339 << "Can proceed with the download";
340 return false;
341 }
342
343 if (backoff_expiry_time_ < Time::Now()) {
344 LOG(INFO) << "The backoff expiry time ("
345 << utils::ToString(backoff_expiry_time_)
346 << ") has elapsed. Can proceed with the download";
347 return false;
348 }
349
350 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
351 << utils::ToString(backoff_expiry_time_);
352 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800353}
354
Chris Sosaaa18e162013-06-20 13:20:30 -0700355void PayloadState::Rollback() {
356 SetRollbackVersion(system_state_->request_params()->app_version());
357}
358
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800359void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700360 // Update the payload attempt number for both payload types: full and delta.
361 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Alex Deymo29b51d92013-07-09 15:26:24 -0700362
363 // Report the metric every time the value is incremented.
364 string metric = "Installer.PayloadAttemptNumber";
365 int value = GetPayloadAttemptNumber();
366
367 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
368 system_state_->metrics_lib()->SendToUMA(
369 metric,
370 value,
371 1, // min value
372 50, // max value
373 kNumDefaultUmaBuckets);
Alex Deymo820cc702013-06-28 15:43:46 -0700374}
375
376void PayloadState::IncrementFullPayloadAttemptNumber() {
377 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800378 if (response_.is_delta_payload) {
379 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
380 return;
381 }
382
Alex Deymo29b51d92013-07-09 15:26:24 -0700383 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700384 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800385 UpdateBackoffExpiryTime();
Alex Deymo29b51d92013-07-09 15:26:24 -0700386
387 // Report the metric every time the value is incremented.
388 string metric = "Installer.FullPayloadAttemptNumber";
389 int value = GetFullPayloadAttemptNumber();
390
391 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
392 system_state_->metrics_lib()->SendToUMA(
393 metric,
394 value,
395 1, // min value
396 50, // max value
397 kNumDefaultUmaBuckets);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800398}
399
400void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800401 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700402 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800403 LOG(INFO) << "Incrementing the URL index for next attempt";
404 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800405 } else {
406 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700407 << "0 as we only have " << candidate_urls_.size()
408 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800409 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700410 IncrementPayloadAttemptNumber();
411 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800412 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800413
David Zeuthencc6f9962013-04-18 11:57:24 -0700414 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700415 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700416 SetUrlSwitchCount(url_switch_count_ + 1);
417
Jay Srinivasan08262882012-12-28 19:29:43 -0800418 // Whenever we update the URL index, we should also clear the URL failure
419 // count so we can start over fresh for the new URL.
420 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800421}
422
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800423void PayloadState::IncrementFailureCount() {
424 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800425 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800426 LOG(INFO) << "Incrementing the URL failure count";
427 SetUrlFailureCount(next_url_failure_count);
428 } else {
429 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
430 << ". Trying next available URL";
431 IncrementUrlIndex();
432 }
433}
434
Jay Srinivasan08262882012-12-28 19:29:43 -0800435void PayloadState::UpdateBackoffExpiryTime() {
436 if (response_.disable_payload_backoff) {
437 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
438 SetBackoffExpiryTime(Time());
439 return;
440 }
441
Alex Deymo820cc702013-06-28 15:43:46 -0700442 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800443 SetBackoffExpiryTime(Time());
444 return;
445 }
446
447 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700448 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800449 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Deymo820cc702013-06-28 15:43:46 -0700450 int num_days = 1; // the value to be shifted.
451 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800452
453 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
454 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700455 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800456
457 // The number of days is the minimum of 2 raised to (payload_attempt_number
458 // - 1) or kMaxBackoffDays.
459 num_days = min(num_days << power, kMaxBackoffDays);
460
461 // We don't want all retries to happen exactly at the same time when
462 // retrying after backoff. So add some random minutes to fuzz.
463 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
464 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
465 TimeDelta::FromMinutes(fuzz_minutes);
466 LOG(INFO) << "Incrementing the backoff expiry time by "
467 << utils::FormatTimeDelta(next_backoff_interval);
468 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
469}
470
Jay Srinivasan19409b72013-04-12 19:23:36 -0700471void PayloadState::UpdateCurrentDownloadSource() {
472 current_download_source_ = kNumDownloadSources;
473
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700474 if (using_p2p_for_downloading_) {
475 current_download_source_ = kDownloadSourceHttpPeer;
476 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700477 string current_url = candidate_urls_[GetUrlIndex()];
Jay Srinivasan19409b72013-04-12 19:23:36 -0700478 if (StartsWithASCII(current_url, "https://", false))
479 current_download_source_ = kDownloadSourceHttpsServer;
480 else if (StartsWithASCII(current_url, "http://", false))
481 current_download_source_ = kDownloadSourceHttpServer;
482 }
483
484 LOG(INFO) << "Current download source: "
485 << utils::ToString(current_download_source_);
486}
487
488void PayloadState::UpdateBytesDownloaded(size_t count) {
489 SetCurrentBytesDownloaded(
490 current_download_source_,
491 GetCurrentBytesDownloaded(current_download_source_) + count,
492 false);
493 SetTotalBytesDownloaded(
494 current_download_source_,
495 GetTotalBytesDownloaded(current_download_source_) + count,
496 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800497
498 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700499}
500
David Zeuthen33bae492014-02-25 16:16:18 -0800501PayloadType PayloadState::CalculatePayloadType() {
502 PayloadType payload_type;
503 OmahaRequestParams* params = system_state_->request_params();
504 if (response_.is_delta_payload) {
505 payload_type = kPayloadTypeDelta;
506 } else if (params->delta_okay()) {
507 payload_type = kPayloadTypeFull;
508 } else { // Full payload, delta was not allowed by request.
509 payload_type = kPayloadTypeForcedFull;
510 }
511 return payload_type;
512}
513
514// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
515// metrics if the attempt ends abnormally, e.g. if the update_engine
516// process crashes or the device is rebooted. See
517// http://crbug.com/357676
518void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
519 int attempt_number = GetPayloadAttemptNumber();
520
521 PayloadType payload_type = CalculatePayloadType();
522
523 int64_t payload_size = response_.size;
524
525 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
526
527 ClockInterface *clock = system_state_->clock();
528 base::TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
529 base::TimeDelta duration_uptime = clock->GetMonotonicTime() -
530 attempt_start_time_monotonic_;
531
532 int64_t payload_download_speed_bps = 0;
533 int64_t usec = duration_uptime.InMicroseconds();
534 if (usec > 0) {
535 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
536 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
537 payload_download_speed_bps = static_cast<int64_t>(bps);
538 }
539
540 DownloadSource download_source = current_download_source_;
541
542 metrics::DownloadErrorCode payload_download_error_code =
543 metrics::DownloadErrorCode::kUnset;
544 ErrorCode internal_error_code = kErrorCodeSuccess;
545 metrics::AttemptResult attempt_result = utils::GetAttemptResult(code);
546
547 // Add additional detail to AttemptResult
548 switch (attempt_result) {
549 case metrics::AttemptResult::kPayloadDownloadError:
550 payload_download_error_code = utils::GetDownloadErrorCode(code);
551 break;
552
553 case metrics::AttemptResult::kInternalError:
554 internal_error_code = code;
555 break;
556
557 // Explicit fall-through for cases where we do not have additional
558 // detail. We avoid the default keyword to force people adding new
559 // AttemptResult values to visit this code and examine whether
560 // additional detail is needed.
561 case metrics::AttemptResult::kUpdateSucceeded:
562 case metrics::AttemptResult::kMetadataMalformed:
563 case metrics::AttemptResult::kOperationMalformed:
564 case metrics::AttemptResult::kOperationExecutionError:
565 case metrics::AttemptResult::kMetadataVerificationFailed:
566 case metrics::AttemptResult::kPayloadVerificationFailed:
567 case metrics::AttemptResult::kVerificationFailed:
568 case metrics::AttemptResult::kPostInstallFailed:
569 case metrics::AttemptResult::kAbnormalTermination:
570 case metrics::AttemptResult::kNumConstants:
571 case metrics::AttemptResult::kUnset:
572 break;
573 }
574
575 metrics::ReportUpdateAttemptMetrics(system_state_,
576 attempt_number,
577 payload_type,
578 duration,
579 duration_uptime,
580 payload_size,
581 payload_bytes_downloaded,
582 payload_download_speed_bps,
583 download_source,
584 attempt_result,
585 internal_error_code,
586 payload_download_error_code);
587}
588
589void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700590 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800591
592 // Report metrics collected from all known download sources to UMA.
593 int64_t successful_bytes_by_source[kNumDownloadSources];
594 int64_t total_bytes_by_source[kNumDownloadSources];
595 int64_t successful_bytes = 0;
596 int64_t total_bytes = 0;
597 int64_t successful_mbs = 0;
598 int64_t total_mbs = 0;
599
Jay Srinivasan19409b72013-04-12 19:23:36 -0700600 for (int i = 0; i < kNumDownloadSources; i++) {
601 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800602 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700603
David Zeuthen44848602013-06-24 13:32:14 -0700604 // Only consider this download source (and send byte counts) as
605 // having been used if we downloaded a non-trivial amount of bytes
606 // (e.g. at least 1 MiB) that contributed to the final success of
607 // the update. Otherwise we're going to end up with a lot of
608 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700609
David Zeuthen33bae492014-02-25 16:16:18 -0800610 bytes = GetCurrentBytesDownloaded(source);
611 successful_bytes_by_source[i] = bytes;
612 successful_bytes += bytes;
613 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700614 SetCurrentBytesDownloaded(source, 0, true);
615
David Zeuthen33bae492014-02-25 16:16:18 -0800616 bytes = GetTotalBytesDownloaded(source);
617 total_bytes_by_source[i] = bytes;
618 total_bytes += bytes;
619 total_mbs += bytes / kNumBytesInOneMiB;
620 SetTotalBytesDownloaded(source, 0, true);
621 }
622
623 int download_overhead_percentage = 0;
624 if (successful_bytes > 0) {
625 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
626 successful_bytes;
627 }
628
629 int url_switch_count = static_cast<int>(url_switch_count_);
630
631 int reboot_count = GetNumReboots();
632
633 SetNumReboots(0);
634
635 TimeDelta duration = GetUpdateDuration();
636 TimeDelta duration_uptime = GetUpdateDurationUptime();
637
638 prefs_->Delete(kPrefsUpdateTimestampStart);
639 prefs_->Delete(kPrefsUpdateDurationUptime);
640
641 PayloadType payload_type = CalculatePayloadType();
642
643 int64_t payload_size = response_.size;
644
645 int attempt_count = GetPayloadAttemptNumber();
646
647 int updates_abandoned_count = num_responses_seen_ - 1;
648
649 metrics::ReportSuccessfulUpdateMetrics(system_state_,
650 attempt_count,
651 updates_abandoned_count,
652 payload_type,
653 payload_size,
654 total_bytes_by_source,
655 download_overhead_percentage,
656 duration,
657 reboot_count,
658 url_switch_count);
659
660 // TODO(zeuthen): This is the old metric reporting code which is
661 // slated for removal soon. See http://crbug.com/355745 for details.
662
663 // The old metrics code is using MiB's instead of bytes to calculate
664 // the overhead which due to rounding makes the numbers slightly
665 // different.
666 download_overhead_percentage = 0;
667 if (successful_mbs > 0) {
668 download_overhead_percentage = (total_mbs - successful_mbs) * 100ULL /
669 successful_mbs;
670 }
671
672 int download_sources_used = 0;
673 for (int i = 0; i < kNumDownloadSources; i++) {
674 DownloadSource source = static_cast<DownloadSource>(i);
675 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
676 int64_t mbs;
677
678 // Only consider this download source (and send byte counts) as
679 // having been used if we downloaded a non-trivial amount of bytes
680 // (e.g. at least 1 MiB) that contributed to the final success of
681 // the update. Otherwise we're going to end up with a lot of
682 // zero-byte events in the histogram.
683
684 mbs = successful_bytes_by_source[i] / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700685 if (mbs > 0) {
David Zeuthen33bae492014-02-25 16:16:18 -0800686 metric = "Installer.SuccessfulMBsDownloadedFrom" +
687 utils::ToString(source);
David Zeuthen44848602013-06-24 13:32:14 -0700688 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
689 system_state_->metrics_lib()->SendToUMA(metric,
690 mbs,
691 0, // min
692 kMaxMiBs,
693 kNumDefaultUmaBuckets);
694 }
David Zeuthen33bae492014-02-25 16:16:18 -0800695
696 mbs = total_bytes_by_source[i] / kNumBytesInOneMiB;
697 if (mbs > 0) {
698 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
699 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
700 system_state_->metrics_lib()->SendToUMA(metric,
701 mbs,
702 0, // min
703 kMaxMiBs,
704 kNumDefaultUmaBuckets);
705 download_sources_used |= (1 << i);
706 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700707 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700708
709 metric = "Installer.DownloadSourcesUsed";
710 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
711 << " (bit flags) for metric " << metric;
712 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
713 system_state_->metrics_lib()->SendToUMA(metric,
714 download_sources_used,
715 0, // min
716 1 << kNumDownloadSources,
717 num_buckets);
718
David Zeuthen33bae492014-02-25 16:16:18 -0800719 metric = "Installer.DownloadOverheadPercentage";
720 LOG(INFO) << "Uploading " << download_overhead_percentage
721 << "% for metric " << metric;
722 system_state_->metrics_lib()->SendToUMA(metric,
723 download_overhead_percentage,
724 0, // min: 0% overhead
725 1000, // max: 1000% overhead
726 kNumDefaultUmaBuckets);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700727
David Zeuthen33bae492014-02-25 16:16:18 -0800728 metric = "Installer.UpdateURLSwitches";
729 LOG(INFO) << "Uploading " << url_switch_count
730 << " (count) for metric " << metric;
David Zeuthencc6f9962013-04-18 11:57:24 -0700731 system_state_->metrics_lib()->SendToUMA(
732 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800733 url_switch_count,
David Zeuthencc6f9962013-04-18 11:57:24 -0700734 0, // min value
735 100, // max value
736 kNumDefaultUmaBuckets);
David Zeuthencc6f9962013-04-18 11:57:24 -0700737
David Zeuthen33bae492014-02-25 16:16:18 -0800738 metric = "Installer.UpdateNumReboots";
739 LOG(INFO) << "Uploading reboot count of " << reboot_count << " for metric "
Chris Sosabe45bef2013-04-09 18:25:12 -0700740 << metric;
741 system_state_->metrics_lib()->SendToUMA(
742 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800743 reboot_count, // sample
744 0, // min = 0.
745 50, // max
Chris Sosabe45bef2013-04-09 18:25:12 -0700746 25); // buckets
David Zeuthen33bae492014-02-25 16:16:18 -0800747
748 metric = "Installer.UpdateDurationMinutes";
749 system_state_->metrics_lib()->SendToUMA(
750 metric,
751 static_cast<int>(duration.InMinutes()),
752 1, // min: 1 minute
753 365*24*60, // max: 1 year (approx)
754 kNumDefaultUmaBuckets);
755 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
756 << " for metric " << metric;
757
758 metric = "Installer.UpdateDurationUptimeMinutes";
759 system_state_->metrics_lib()->SendToUMA(
760 metric,
761 static_cast<int>(duration_uptime.InMinutes()),
762 1, // min: 1 minute
763 30*24*60, // max: 1 month (approx)
764 kNumDefaultUmaBuckets);
765 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
766 << " for metric " << metric;
767
768 metric = "Installer.PayloadFormat";
769 system_state_->metrics_lib()->SendEnumToUMA(
770 metric,
771 payload_type,
772 kNumPayloadTypes);
773 LOG(INFO) << "Uploading " << utils::ToString(payload_type)
774 << " for metric " << metric;
775
776 metric = "Installer.AttemptsCount.Total";
777 system_state_->metrics_lib()->SendToUMA(
778 metric,
779 attempt_count,
780 1, // min
781 50, // max
782 kNumDefaultUmaBuckets);
783 LOG(INFO) << "Uploading " << attempt_count
784 << " for metric " << metric;
785
786 metric = "Installer.UpdatesAbandonedCount";
787 LOG(INFO) << "Uploading " << updates_abandoned_count
788 << " (count) for metric " << metric;
789 system_state_->metrics_lib()->SendToUMA(
790 metric,
791 updates_abandoned_count,
792 0, // min value
793 100, // max value
794 kNumDefaultUmaBuckets);
Chris Sosabe45bef2013-04-09 18:25:12 -0700795}
796
797void PayloadState::UpdateNumReboots() {
798 // We only update the reboot count when the system has been detected to have
799 // been rebooted.
800 if (!system_state_->system_rebooted()) {
801 return;
802 }
803
804 SetNumReboots(GetNumReboots() + 1);
805}
806
807void PayloadState::SetNumReboots(uint32_t num_reboots) {
808 CHECK(prefs_);
809 num_reboots_ = num_reboots;
810 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
811 LOG(INFO) << "Number of Reboots during current update attempt = "
812 << num_reboots_;
813}
814
Jay Srinivasan08262882012-12-28 19:29:43 -0800815void PayloadState::ResetPersistedState() {
816 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700817 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800818 SetUrlIndex(0);
819 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700820 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800821 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700822 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
David Zeuthen9a017f22013-04-11 16:10:26 -0700823 SetUpdateTimestampEnd(Time()); // Set to null time
824 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700825 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700826 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700827 SetP2PNumAttempts(0);
828 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Chris Sosaaa18e162013-06-20 13:20:30 -0700829}
830
831void PayloadState::ResetRollbackVersion() {
832 CHECK(powerwash_safe_prefs_);
833 rollback_version_ = "";
834 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700835}
836
837void PayloadState::ResetDownloadSourcesOnNewUpdate() {
838 for (int i = 0; i < kNumDownloadSources; i++) {
839 DownloadSource source = static_cast<DownloadSource>(i);
840 SetCurrentBytesDownloaded(source, 0, true);
841 // Note: Not resetting the TotalBytesDownloaded as we want that metric
842 // to count the bytes downloaded across various update attempts until
843 // we have successfully applied the update.
844 }
845}
846
Chris Sosab3dcdb32013-09-04 15:22:12 -0700847int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700848 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700849 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700850 return 0;
851
852 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700853 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700854 return 0;
855
856 if (stored_value < 0) {
857 LOG(ERROR) << key << ": Invalid value (" << stored_value
858 << ") in persisted state. Defaulting to 0";
859 return 0;
860 }
861
862 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800863}
864
865string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700866 string response_sign = base::StringPrintf(
867 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800868
Jay Srinivasan53173b92013-05-17 17:13:01 -0700869 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700870 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
871 static_cast<int>(i),
872 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800873
Alex Vakulenko75039d72014-03-25 12:36:28 -0700874 response_sign += base::StringPrintf(
875 "Payload Size = %ju\n"
876 "Payload Sha256 Hash = %s\n"
877 "Metadata Size = %ju\n"
878 "Metadata Signature = %s\n"
879 "Is Delta Payload = %d\n"
880 "Max Failure Count Per Url = %d\n"
881 "Disable Payload Backoff = %d\n",
882 static_cast<uintmax_t>(response_.size),
883 response_.hash.c_str(),
884 static_cast<uintmax_t>(response_.metadata_size),
885 response_.metadata_signature.c_str(),
886 response_.is_delta_payload,
887 response_.max_failure_count_per_url,
888 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800889 return response_sign;
890}
891
892void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800893 CHECK(prefs_);
894 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800895 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
896 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
897 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800898 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800899}
900
Jay Srinivasan19409b72013-04-12 19:23:36 -0700901void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800902 CHECK(prefs_);
903 response_signature_ = response_signature;
904 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
905 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
906}
907
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800908void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700909 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800910}
911
Alex Deymo820cc702013-06-28 15:43:46 -0700912void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700913 SetFullPayloadAttemptNumber(GetPersistedValue(
914 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700915}
916
917void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800918 CHECK(prefs_);
919 payload_attempt_number_ = payload_attempt_number;
920 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
921 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
922}
923
Alex Deymo820cc702013-06-28 15:43:46 -0700924void PayloadState::SetFullPayloadAttemptNumber(
925 int full_payload_attempt_number) {
926 CHECK(prefs_);
927 full_payload_attempt_number_ = full_payload_attempt_number;
928 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
929 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
930 full_payload_attempt_number_);
931}
932
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800933void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700934 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800935}
936
937void PayloadState::SetUrlIndex(uint32_t url_index) {
938 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800939 url_index_ = url_index;
940 LOG(INFO) << "Current URL Index = " << url_index_;
941 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700942
943 // Also update the download source, which is purely dependent on the
944 // current URL index alone.
945 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800946}
947
David Zeuthencc6f9962013-04-18 11:57:24 -0700948void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700949 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700950}
951
952void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
953 CHECK(prefs_);
954 url_switch_count_ = url_switch_count;
955 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
956 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
957}
958
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800959void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700960 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800961}
962
963void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
964 CHECK(prefs_);
965 url_failure_count_ = url_failure_count;
966 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
967 << ")'s Failure Count = " << url_failure_count_;
968 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800969}
970
Jay Srinivasan08262882012-12-28 19:29:43 -0800971void PayloadState::LoadBackoffExpiryTime() {
972 CHECK(prefs_);
973 int64_t stored_value;
974 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
975 return;
976
977 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
978 return;
979
980 Time stored_time = Time::FromInternalValue(stored_value);
981 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
982 LOG(ERROR) << "Invalid backoff expiry time ("
983 << utils::ToString(stored_time)
984 << ") in persisted state. Resetting.";
985 stored_time = Time();
986 }
987 SetBackoffExpiryTime(stored_time);
988}
989
990void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
991 CHECK(prefs_);
992 backoff_expiry_time_ = new_time;
993 LOG(INFO) << "Backoff Expiry Time = "
994 << utils::ToString(backoff_expiry_time_);
995 prefs_->SetInt64(kPrefsBackoffExpiryTime,
996 backoff_expiry_time_.ToInternalValue());
997}
998
David Zeuthen9a017f22013-04-11 16:10:26 -0700999TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001000 Time end_time = update_timestamp_end_.is_null()
1001 ? system_state_->clock()->GetWallclockTime() :
1002 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001003 return end_time - update_timestamp_start_;
1004}
1005
1006void PayloadState::LoadUpdateTimestampStart() {
1007 int64_t stored_value;
1008 Time stored_time;
1009
1010 CHECK(prefs_);
1011
David Zeuthenf413fe52013-04-22 14:04:39 -07001012 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001013
1014 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1015 // The preference missing is not unexpected - in that case, just
1016 // use the current time as start time
1017 stored_time = now;
1018 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1019 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1020 stored_time = now;
1021 } else {
1022 stored_time = Time::FromInternalValue(stored_value);
1023 }
1024
1025 // Sanity check: If the time read from disk is in the future
1026 // (modulo some slack to account for possible NTP drift
1027 // adjustments), something is fishy and we should report and
1028 // reset.
1029 TimeDelta duration_according_to_stored_time = now - stored_time;
1030 if (duration_according_to_stored_time < -kDurationSlack) {
1031 LOG(ERROR) << "The UpdateTimestampStart value ("
1032 << utils::ToString(stored_time)
1033 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001034 << utils::FormatTimeDelta(duration_according_to_stored_time)
1035 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001036 stored_time = now;
1037 }
1038
1039 SetUpdateTimestampStart(stored_time);
1040}
1041
1042void PayloadState::SetUpdateTimestampStart(const Time& value) {
1043 CHECK(prefs_);
1044 update_timestamp_start_ = value;
1045 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1046 update_timestamp_start_.ToInternalValue());
1047 LOG(INFO) << "Update Timestamp Start = "
1048 << utils::ToString(update_timestamp_start_);
1049}
1050
1051void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1052 update_timestamp_end_ = value;
1053 LOG(INFO) << "Update Timestamp End = "
1054 << utils::ToString(update_timestamp_end_);
1055}
1056
1057TimeDelta PayloadState::GetUpdateDurationUptime() {
1058 return update_duration_uptime_;
1059}
1060
1061void PayloadState::LoadUpdateDurationUptime() {
1062 int64_t stored_value;
1063 TimeDelta stored_delta;
1064
1065 CHECK(prefs_);
1066
1067 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1068 // The preference missing is not unexpected - in that case, just
1069 // we'll use zero as the delta
1070 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1071 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1072 stored_delta = TimeDelta::FromSeconds(0);
1073 } else {
1074 stored_delta = TimeDelta::FromInternalValue(stored_value);
1075 }
1076
1077 // Sanity-check: Uptime can never be greater than the wall-clock
1078 // difference (modulo some slack). If it is, report and reset
1079 // to the wall-clock difference.
1080 TimeDelta diff = GetUpdateDuration() - stored_delta;
1081 if (diff < -kDurationSlack) {
1082 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001083 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001084 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001085 << utils::FormatTimeDelta(diff)
1086 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001087 stored_delta = update_duration_current_;
1088 }
1089
1090 SetUpdateDurationUptime(stored_delta);
1091}
1092
Chris Sosabe45bef2013-04-09 18:25:12 -07001093void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001094 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001095}
1096
1097void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001098 CHECK(powerwash_safe_prefs_);
1099 string rollback_version;
1100 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1101 &rollback_version)) {
1102 SetRollbackVersion(rollback_version);
1103 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001104}
1105
1106void PayloadState::SetRollbackVersion(const string& rollback_version) {
1107 CHECK(powerwash_safe_prefs_);
1108 LOG(INFO) << "Blacklisting version "<< rollback_version;
1109 rollback_version_ = rollback_version;
1110 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001111}
1112
David Zeuthen9a017f22013-04-11 16:10:26 -07001113void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1114 const Time& timestamp,
1115 bool use_logging) {
1116 CHECK(prefs_);
1117 update_duration_uptime_ = value;
1118 update_duration_uptime_timestamp_ = timestamp;
1119 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1120 update_duration_uptime_.ToInternalValue());
1121 if (use_logging) {
1122 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001123 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001124 }
1125}
1126
1127void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001128 Time now = system_state_->clock()->GetMonotonicTime();
1129 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001130}
1131
1132void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001133 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001134 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1135 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1136 // We're frequently called so avoid logging this write
1137 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1138}
1139
Jay Srinivasan19409b72013-04-12 19:23:36 -07001140string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1141 return prefix + "-from-" + utils::ToString(source);
1142}
1143
1144void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1145 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001146 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001147}
1148
1149void PayloadState::SetCurrentBytesDownloaded(
1150 DownloadSource source,
1151 uint64_t current_bytes_downloaded,
1152 bool log) {
1153 CHECK(prefs_);
1154
1155 if (source >= kNumDownloadSources)
1156 return;
1157
1158 // Update the in-memory value.
1159 current_bytes_downloaded_[source] = current_bytes_downloaded;
1160
1161 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1162 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1163 LOG_IF(INFO, log) << "Current bytes downloaded for "
1164 << utils::ToString(source) << " = "
1165 << GetCurrentBytesDownloaded(source);
1166}
1167
1168void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1169 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001170 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001171}
1172
1173void PayloadState::SetTotalBytesDownloaded(
1174 DownloadSource source,
1175 uint64_t total_bytes_downloaded,
1176 bool log) {
1177 CHECK(prefs_);
1178
1179 if (source >= kNumDownloadSources)
1180 return;
1181
1182 // Update the in-memory value.
1183 total_bytes_downloaded_[source] = total_bytes_downloaded;
1184
1185 // Persist.
1186 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1187 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1188 LOG_IF(INFO, log) << "Total bytes downloaded for "
1189 << utils::ToString(source) << " = "
1190 << GetTotalBytesDownloaded(source);
1191}
1192
David Zeuthena573d6f2013-06-14 16:13:36 -07001193void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001194 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001195}
1196
1197void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1198 CHECK(prefs_);
1199 num_responses_seen_ = num_responses_seen;
1200 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1201 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1202}
1203
Alex Deymob33b0f02013-08-08 21:10:02 -07001204void PayloadState::ReportUpdatesAbandonedEventCountMetric() {
1205 string metric = "Installer.UpdatesAbandonedEventCount";
1206 int value = num_responses_seen_ - 1;
1207
1208 // Do not send an "abandoned" event when 0 payloads were abandoned since the
1209 // last successful update.
1210 if (value == 0)
1211 return;
1212
1213 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1214 system_state_->metrics_lib()->SendToUMA(
1215 metric,
1216 value,
1217 0, // min value
1218 100, // max value
1219 kNumDefaultUmaBuckets);
1220}
1221
Jay Srinivasan53173b92013-05-17 17:13:01 -07001222void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001223 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001224
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001225 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001226 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001227 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001228 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1229 } else {
1230 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1231 http_url_ok = true;
1232 }
1233
1234 candidate_urls_.clear();
1235 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1236 string candidate_url = response_.payload_urls[i];
1237 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1238 continue;
1239 candidate_urls_.push_back(candidate_url);
1240 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1241 << ": " << candidate_url;
1242 }
1243
1244 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1245 << "out of " << response_.payload_urls.size() << " URLs supplied";
1246}
1247
David Zeuthene4c58bf2013-06-18 17:26:50 -07001248void PayloadState::CreateSystemUpdatedMarkerFile() {
1249 CHECK(prefs_);
1250 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1251 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1252}
1253
1254void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1255 // Send |time_to_reboot| as a UMA stat.
1256 string metric = "Installer.TimeToRebootMinutes";
1257 system_state_->metrics_lib()->SendToUMA(metric,
1258 time_to_reboot.InMinutes(),
1259 0, // min: 0 minute
1260 30*24*60, // max: 1 month (approx)
1261 kNumDefaultUmaBuckets);
1262 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1263 << " for metric " << metric;
David Zeuthen33bae492014-02-25 16:16:18 -08001264
1265 metric = metrics::kMetricTimeToRebootMinutes;
1266 system_state_->metrics_lib()->SendToUMA(metric,
1267 time_to_reboot.InMinutes(),
1268 0, // min: 0 minute
1269 30*24*60, // max: 1 month (approx)
1270 kNumDefaultUmaBuckets);
1271 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1272 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001273}
1274
1275void PayloadState::UpdateEngineStarted() {
Alex Deymo569c4242013-07-24 12:01:01 -07001276 // Avoid the UpdateEngineStarted actions if this is not the first time we
1277 // run the update engine since reboot.
1278 if (!system_state_->system_rebooted())
1279 return;
1280
David Zeuthene4c58bf2013-06-18 17:26:50 -07001281 // Figure out if we just booted into a new update
1282 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1283 int64_t stored_value;
1284 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1285 Time system_updated_at = Time::FromInternalValue(stored_value);
1286 if (!system_updated_at.is_null()) {
1287 TimeDelta time_to_reboot =
1288 system_state_->clock()->GetWallclockTime() - system_updated_at;
1289 if (time_to_reboot.ToInternalValue() < 0) {
1290 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1291 << utils::ToString(system_updated_at);
1292 } else {
1293 BootedIntoUpdate(time_to_reboot);
1294 }
1295 }
1296 }
1297 prefs_->Delete(kPrefsSystemUpdatedMarker);
1298 }
Alex Deymo42432912013-07-12 20:21:15 -07001299 // Check if it is needed to send metrics about a failed reboot into a new
1300 // version.
1301 ReportFailedBootIfNeeded();
1302}
1303
1304void PayloadState::ReportFailedBootIfNeeded() {
1305 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1306 // payload was marked as ready immediately before the last reboot, and we
1307 // need to check if such payload successfully rebooted or not.
1308 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001309 int64_t installed_from = 0;
1310 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001311 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1312 return;
1313 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001314 if (int(installed_from) ==
1315 utils::GetPartitionNumber(system_state_->hardware()->BootDevice())) {
Alex Deymo42432912013-07-12 20:21:15 -07001316 // A reboot was pending, but the chromebook is again in the same
1317 // BootDevice where the update was installed from.
1318 int64_t target_attempt;
1319 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1320 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1321 "TargetVersionInstalledFrom was present.";
1322 target_attempt = 1;
1323 }
1324
1325 // Report the UMA metric of the current boot failure.
1326 string metric = "Installer.RebootToNewPartitionAttempt";
1327
1328 LOG(INFO) << "Uploading " << target_attempt
1329 << " (count) for metric " << metric;
1330 system_state_->metrics_lib()->SendToUMA(
1331 metric,
1332 target_attempt,
1333 1, // min value
1334 50, // max value
1335 kNumDefaultUmaBuckets);
David Zeuthen33bae492014-02-25 16:16:18 -08001336
1337 metric = metrics::kMetricFailedUpdateCount;
1338 LOG(INFO) << "Uploading " << target_attempt
1339 << " (count) for metric " << metric;
1340 system_state_->metrics_lib()->SendToUMA(
1341 metric,
1342 target_attempt,
1343 1, // min value
1344 50, // max value
1345 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001346 } else {
1347 prefs_->Delete(kPrefsTargetVersionAttempt);
1348 prefs_->Delete(kPrefsTargetVersionUniqueId);
1349 }
1350 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1351 }
1352}
1353
1354void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1355 // Expect to boot into the new partition in the next reboot setting the
1356 // TargetVersion* flags in the Prefs.
1357 string stored_target_version_uid;
1358 string target_version_id;
1359 string target_partition;
1360 int64_t target_attempt;
1361
1362 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1363 prefs_->GetString(kPrefsTargetVersionUniqueId,
1364 &stored_target_version_uid) &&
1365 stored_target_version_uid == target_version_uid) {
1366 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1367 target_attempt = 0;
1368 } else {
1369 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1370 target_attempt = 0;
1371 }
1372 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1373
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001374 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
1375 utils::GetPartitionNumber(
Alex Deymo42432912013-07-12 20:21:15 -07001376 system_state_->hardware()->BootDevice()));
1377}
1378
1379void PayloadState::ResetUpdateStatus() {
1380 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1381 // rebooted the next boot is not flagged as failed to rebooted into the
1382 // new applied payload.
1383 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1384
1385 // Also decrement the attempt number if it exists.
1386 int64_t target_attempt;
1387 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1388 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt-1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001389}
1390
David Zeuthendcba8092013-08-06 12:16:35 -07001391int PayloadState::GetP2PNumAttempts() {
1392 return p2p_num_attempts_;
1393}
1394
1395void PayloadState::SetP2PNumAttempts(int value) {
1396 p2p_num_attempts_ = value;
1397 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1398 CHECK(prefs_);
1399 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1400}
1401
1402void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001403 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001404}
1405
1406Time PayloadState::GetP2PFirstAttemptTimestamp() {
1407 return p2p_first_attempt_timestamp_;
1408}
1409
1410void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1411 p2p_first_attempt_timestamp_ = time;
1412 LOG(INFO) << "p2p First Attempt Timestamp = "
1413 << utils::ToString(p2p_first_attempt_timestamp_);
1414 CHECK(prefs_);
1415 int64_t stored_value = time.ToInternalValue();
1416 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1417}
1418
1419void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001420 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001421 Time stored_time = Time::FromInternalValue(stored_value);
1422 SetP2PFirstAttemptTimestamp(stored_time);
1423}
1424
1425void PayloadState::P2PNewAttempt() {
1426 CHECK(prefs_);
1427 // Set timestamp, if it hasn't been set already
1428 if (p2p_first_attempt_timestamp_.is_null()) {
1429 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1430 }
1431 // Increase number of attempts
1432 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1433}
1434
1435bool PayloadState::P2PAttemptAllowed() {
1436 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1437 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1438 << " which is greater than "
1439 << kMaxP2PAttempts
1440 << " - disallowing p2p.";
1441 return false;
1442 }
1443
1444 if (!p2p_first_attempt_timestamp_.is_null()) {
1445 Time now = system_state_->clock()->GetWallclockTime();
1446 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1447 if (time_spent_attempting_p2p.InSeconds() < 0) {
1448 LOG(ERROR) << "Time spent attempting p2p is negative"
1449 << " - disallowing p2p.";
1450 return false;
1451 }
1452 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1453 LOG(INFO) << "Time spent attempting p2p is "
1454 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1455 << " which is greater than "
1456 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1457 kMaxP2PAttemptTimeSeconds))
1458 << " - disallowing p2p.";
1459 return false;
1460 }
1461 }
1462
1463 return true;
1464}
1465
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001466} // namespace chromeos_update_engine