blob: 268513063fa1f12149dc5f91bbb82522de952626 [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"
David Zeuthenb281f072014-04-02 10:20:19 -070019#include "update_engine/real_dbus_wrapper.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070020#include "update_engine/system_state.h"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080021#include "update_engine/utils.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080022
Jay Srinivasan08262882012-12-28 19:29:43 -080023using base::Time;
24using base::TimeDelta;
25using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080026using std::string;
27
28namespace chromeos_update_engine {
29
David Zeuthen9a017f22013-04-11 16:10:26 -070030const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
31
Jay Srinivasan08262882012-12-28 19:29:43 -080032// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070033static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080034
Jay Srinivasan08262882012-12-28 19:29:43 -080035// We want to randomize retry attempts after the backoff by +/- 6 hours.
36static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080037
Jay Srinivasan19409b72013-04-12 19:23:36 -070038PayloadState::PayloadState()
39 : prefs_(NULL),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070040 using_p2p_for_downloading_(false),
Jay Srinivasan19409b72013-04-12 19:23:36 -070041 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070042 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070043 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070044 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070045 url_switch_count_(0),
46 p2p_num_attempts_(0) {
Jay Srinivasan19409b72013-04-12 19:23:36 -070047 for (int i = 0; i <= kNumDownloadSources; i++)
48 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
49}
50
51bool PayloadState::Initialize(SystemState* system_state) {
52 system_state_ = system_state;
53 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070054 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080055 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080056 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070057 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080058 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080059 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070060 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080061 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070062 LoadUpdateTimestampStart();
63 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
64 // being called before it. Don't reorder.
65 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070066 for (int i = 0; i < kNumDownloadSources; i++) {
67 DownloadSource source = static_cast<DownloadSource>(i);
68 LoadCurrentBytesDownloaded(source);
69 LoadTotalBytesDownloaded(source);
70 }
Chris Sosabe45bef2013-04-09 18:25:12 -070071 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070072 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070073 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070074 LoadP2PFirstAttemptTimestamp();
75 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080076 return true;
77}
78
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080079void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080080 // Always store the latest response.
81 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080082
Jay Srinivasan53173b92013-05-17 17:13:01 -070083 // Compute the candidate URLs first as they are used to calculate the
84 // response signature so that a change in enterprise policy for
85 // HTTP downloads being enabled or not could be honored as soon as the
86 // next update check happens.
87 ComputeCandidateUrls();
88
Jay Srinivasan08262882012-12-28 19:29:43 -080089 // Check if the "signature" of this response (i.e. the fields we care about)
90 // has changed.
91 string new_response_signature = CalculateResponseSignature();
92 bool has_response_changed = (response_signature_ != new_response_signature);
93
94 // If the response has changed, we should persist the new signature and
95 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080096 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -080097 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -070098 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -080099 SetResponseSignature(new_response_signature);
100 ResetPersistedState();
Alex Deymob33b0f02013-08-08 21:10:02 -0700101 ReportUpdatesAbandonedEventCountMetric();
Jay Srinivasan08262882012-12-28 19:29:43 -0800102 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800103 }
104
Jay Srinivasan08262882012-12-28 19:29:43 -0800105 // This is the earliest point at which we can validate whether the URL index
106 // we loaded from the persisted state is a valid value. If the response
107 // hasn't changed but the URL index is invalid, it's indicative of some
108 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700109 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800110 LOG(INFO) << "Resetting all payload state as the url index seems to have "
111 "been tampered with";
112 ResetPersistedState();
113 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800114 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700115
116 // Update the current download source which depends on the latest value of
117 // the response.
118 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800119}
120
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700121void PayloadState::SetUsingP2PForDownloading(bool value) {
122 using_p2p_for_downloading_ = value;
123 // Update the current download source which depends on whether we are
124 // using p2p or not.
125 UpdateCurrentDownloadSource();
126}
127
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800128void PayloadState::DownloadComplete() {
129 LOG(INFO) << "Payload downloaded successfully";
130 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700131 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800132}
133
134void PayloadState::DownloadProgress(size_t count) {
135 if (count == 0)
136 return;
137
David Zeuthen9a017f22013-04-11 16:10:26 -0700138 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700139 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700140
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800141 // We've received non-zero bytes from a recent download operation. Since our
142 // URL failure count is meant to penalize a URL only for consecutive
143 // failures, downloading bytes successfully means we should reset the failure
144 // count (as we know at least that the URL is working). In future, we can
145 // design this to be more sophisticated to check for more intelligent failure
146 // patterns, but right now, even 1 byte downloaded will mark the URL to be
147 // good unless it hits 10 (or configured number of) consecutive failures
148 // again.
149
150 if (GetUrlFailureCount() == 0)
151 return;
152
153 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
154 << " to 0 as we received " << count << " bytes successfully";
155 SetUrlFailureCount(0);
156}
157
David Zeuthen33bae492014-02-25 16:16:18 -0800158void PayloadState::AttemptStarted() {
159 ClockInterface *clock = system_state_->clock();
160 attempt_start_time_boot_ = clock->GetBootTime();
161 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800162 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700163
164 metrics::ConnectionType type;
165 NetworkConnectionType network_connection_type;
166 NetworkTethering tethering;
167 RealDBusWrapper dbus_iface;
168 ConnectionManager* connection_manager = system_state_->connection_manager();
169 if (!connection_manager->GetConnectionProperties(&dbus_iface,
170 &network_connection_type,
171 &tethering)) {
172 LOG(ERROR) << "Failed to determine connection type.";
173 type = metrics::ConnectionType::kUnknown;
174 } else {
175 type = utils::GetConnectionType(network_connection_type, tethering);
176 }
177 attempt_connection_type_ = type;
David Zeuthen33bae492014-02-25 16:16:18 -0800178}
179
Chris Sosabe45bef2013-04-09 18:25:12 -0700180void PayloadState::UpdateResumed() {
181 LOG(INFO) << "Resuming an update that was previously started.";
182 UpdateNumReboots();
David Zeuthen33bae492014-02-25 16:16:18 -0800183 AttemptStarted();
Chris Sosabe45bef2013-04-09 18:25:12 -0700184}
185
Jay Srinivasan19409b72013-04-12 19:23:36 -0700186void PayloadState::UpdateRestarted() {
187 LOG(INFO) << "Starting a new update";
188 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700189 SetNumReboots(0);
David Zeuthen33bae492014-02-25 16:16:18 -0800190 AttemptStarted();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700191}
192
David Zeuthen9a017f22013-04-11 16:10:26 -0700193void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700194 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700195 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700196 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800197
198 CollectAndReportAttemptMetrics(kErrorCodeSuccess);
199 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthena573d6f2013-06-14 16:13:36 -0700200
201 // Reset the number of responses seen since it counts from the last
202 // successful update, e.g. now.
203 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700204
205 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700206}
207
David Zeuthena99981f2013-04-29 13:42:47 -0700208void PayloadState::UpdateFailed(ErrorCode error) {
209 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800210 LOG(INFO) << "Updating payload state for error code: " << base_error
211 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800212
Jay Srinivasan53173b92013-05-17 17:13:01 -0700213 if (candidate_urls_.size() == 0) {
214 // This means we got this error even before we got a valid Omaha response
215 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800216 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800217 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
218 return;
219 }
220
David Zeuthen33bae492014-02-25 16:16:18 -0800221 CollectAndReportAttemptMetrics(base_error);
222
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800223 switch (base_error) {
224 // Errors which are good indicators of a problem with a particular URL or
225 // the protocol used in the URL or entities in the communication channel
226 // (e.g. proxies). We should try the next available URL in the next update
227 // check to quickly recover from these errors.
David Zeuthena99981f2013-04-29 13:42:47 -0700228 case kErrorCodePayloadHashMismatchError:
229 case kErrorCodePayloadSizeMismatchError:
230 case kErrorCodeDownloadPayloadVerificationError:
231 case kErrorCodeDownloadPayloadPubKeyVerificationError:
232 case kErrorCodeSignedDeltaPayloadExpectedError:
233 case kErrorCodeDownloadInvalidMetadataMagicString:
234 case kErrorCodeDownloadSignatureMissingInManifest:
235 case kErrorCodeDownloadManifestParseError:
236 case kErrorCodeDownloadMetadataSignatureError:
237 case kErrorCodeDownloadMetadataSignatureVerificationError:
238 case kErrorCodeDownloadMetadataSignatureMismatch:
239 case kErrorCodeDownloadOperationHashVerificationError:
240 case kErrorCodeDownloadOperationExecutionError:
241 case kErrorCodeDownloadOperationHashMismatch:
242 case kErrorCodeDownloadInvalidMetadataSize:
243 case kErrorCodeDownloadInvalidMetadataSignature:
244 case kErrorCodeDownloadOperationHashMissingError:
245 case kErrorCodeDownloadMetadataSignatureMissingError:
Gilad Arnold21504f02013-05-24 08:51:22 -0700246 case kErrorCodePayloadMismatchedType:
Don Garrett4d039442013-10-28 18:40:06 -0700247 case kErrorCodeUnsupportedMajorPayloadVersion:
248 case kErrorCodeUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800249 IncrementUrlIndex();
250 break;
251
252 // Errors which seem to be just transient network/communication related
253 // failures and do not indicate any inherent problem with the URL itself.
254 // So, we should keep the current URL but just increment the
255 // failure count to give it more chances. This way, while we maximize our
256 // chances of downloading from the URLs that appear earlier in the response
257 // (because download from a local server URL that appears earlier in a
258 // response is preferable than downloading from the next URL which could be
259 // a internet URL and thus could be more expensive).
David Zeuthena99981f2013-04-29 13:42:47 -0700260 case kErrorCodeError:
261 case kErrorCodeDownloadTransferError:
262 case kErrorCodeDownloadWriteError:
263 case kErrorCodeDownloadStateInitializationError:
264 case kErrorCodeOmahaErrorInHTTPResponse: // Aggregate code for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800265 IncrementFailureCount();
266 break;
267
268 // Errors which are not specific to a URL and hence shouldn't result in
269 // the URL being penalized. This can happen in two cases:
270 // 1. We haven't started downloading anything: These errors don't cost us
271 // anything in terms of actual payload bytes, so we should just do the
272 // regular retries at the next update check.
273 // 2. We have successfully downloaded the payload: In this case, the
274 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800275 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800276 // In either case, there's no need to update URL index or failure count.
David Zeuthena99981f2013-04-29 13:42:47 -0700277 case kErrorCodeOmahaRequestError:
278 case kErrorCodeOmahaResponseHandlerError:
279 case kErrorCodePostinstallRunnerError:
280 case kErrorCodeFilesystemCopierError:
281 case kErrorCodeInstallDeviceOpenError:
282 case kErrorCodeKernelDeviceOpenError:
283 case kErrorCodeDownloadNewPartitionInfoError:
284 case kErrorCodeNewRootfsVerificationError:
285 case kErrorCodeNewKernelVerificationError:
286 case kErrorCodePostinstallBootedFromFirmwareB:
Don Garrett81018e02013-07-30 18:46:31 -0700287 case kErrorCodePostinstallFirmwareRONotUpdatable:
David Zeuthena99981f2013-04-29 13:42:47 -0700288 case kErrorCodeOmahaRequestEmptyResponseError:
289 case kErrorCodeOmahaRequestXMLParseError:
290 case kErrorCodeOmahaResponseInvalid:
291 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
292 case kErrorCodeOmahaUpdateDeferredPerPolicy:
293 case kErrorCodeOmahaUpdateDeferredForBackoff:
294 case kErrorCodePostinstallPowerwashError:
295 case kErrorCodeUpdateCanceledByChannelChange:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800296 LOG(INFO) << "Not incrementing URL index or failure count for this error";
297 break;
298
David Zeuthena99981f2013-04-29 13:42:47 -0700299 case kErrorCodeSuccess: // success code
David Zeuthena99981f2013-04-29 13:42:47 -0700300 case kErrorCodeUmaReportedMax: // not an error code
301 case kErrorCodeOmahaRequestHTTPResponseBase: // aggregated already
302 case kErrorCodeDevModeFlag: // not an error code
303 case kErrorCodeResumedFlag: // not an error code
304 case kErrorCodeTestImageFlag: // not an error code
305 case kErrorCodeTestOmahaUrlFlag: // not an error code
306 case kErrorCodeSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800307 // These shouldn't happen. Enumerating these explicitly here so that we
308 // can let the compiler warn about new error codes that are added to
309 // action_processor.h but not added here.
310 LOG(WARNING) << "Unexpected error code for UpdateFailed";
311 break;
312
313 // Note: Not adding a default here so as to let the compiler warn us of
314 // any new enums that were added in the .h but not listed in this switch.
315 }
316}
317
Jay Srinivasan08262882012-12-28 19:29:43 -0800318bool PayloadState::ShouldBackoffDownload() {
319 if (response_.disable_payload_backoff) {
320 LOG(INFO) << "Payload backoff logic is disabled. "
321 "Can proceed with the download";
322 return false;
323 }
Chris Sosa20f005c2013-09-05 13:53:08 -0700324 if (system_state_->request_params()->use_p2p_for_downloading() &&
325 !system_state_->request_params()->p2p_url().empty()) {
326 LOG(INFO) << "Payload backoff logic is disabled because download "
327 << "will happen from local peer (via p2p).";
328 return false;
329 }
330 if (system_state_->request_params()->interactive()) {
331 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
332 return false;
333 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800334 if (response_.is_delta_payload) {
335 // If delta payloads fail, we want to fallback quickly to full payloads as
336 // they are more likely to succeed. Exponential backoffs would greatly
337 // slow down the fallback to full payloads. So we don't backoff for delta
338 // payloads.
339 LOG(INFO) << "No backoffs for delta payloads. "
340 << "Can proceed with the download";
341 return false;
342 }
343
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700344 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800345 // Backoffs are needed only for official builds. We do not want any delays
346 // or update failures due to backoffs during testing or development.
347 LOG(INFO) << "No backoffs for test/dev images. "
348 << "Can proceed with the download";
349 return false;
350 }
351
352 if (backoff_expiry_time_.is_null()) {
353 LOG(INFO) << "No backoff expiry time has been set. "
354 << "Can proceed with the download";
355 return false;
356 }
357
358 if (backoff_expiry_time_ < Time::Now()) {
359 LOG(INFO) << "The backoff expiry time ("
360 << utils::ToString(backoff_expiry_time_)
361 << ") has elapsed. Can proceed with the download";
362 return false;
363 }
364
365 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
366 << utils::ToString(backoff_expiry_time_);
367 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800368}
369
Chris Sosaaa18e162013-06-20 13:20:30 -0700370void PayloadState::Rollback() {
371 SetRollbackVersion(system_state_->request_params()->app_version());
372}
373
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800374void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700375 // Update the payload attempt number for both payload types: full and delta.
376 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Alex Deymo29b51d92013-07-09 15:26:24 -0700377
378 // Report the metric every time the value is incremented.
379 string metric = "Installer.PayloadAttemptNumber";
380 int value = GetPayloadAttemptNumber();
381
382 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
383 system_state_->metrics_lib()->SendToUMA(
384 metric,
385 value,
386 1, // min value
387 50, // max value
388 kNumDefaultUmaBuckets);
Alex Deymo820cc702013-06-28 15:43:46 -0700389}
390
391void PayloadState::IncrementFullPayloadAttemptNumber() {
392 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800393 if (response_.is_delta_payload) {
394 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
395 return;
396 }
397
Alex Deymo29b51d92013-07-09 15:26:24 -0700398 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700399 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800400 UpdateBackoffExpiryTime();
Alex Deymo29b51d92013-07-09 15:26:24 -0700401
402 // Report the metric every time the value is incremented.
403 string metric = "Installer.FullPayloadAttemptNumber";
404 int value = GetFullPayloadAttemptNumber();
405
406 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
407 system_state_->metrics_lib()->SendToUMA(
408 metric,
409 value,
410 1, // min value
411 50, // max value
412 kNumDefaultUmaBuckets);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800413}
414
415void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800416 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700417 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800418 LOG(INFO) << "Incrementing the URL index for next attempt";
419 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800420 } else {
421 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700422 << "0 as we only have " << candidate_urls_.size()
423 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800424 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700425 IncrementPayloadAttemptNumber();
426 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800427 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800428
David Zeuthencc6f9962013-04-18 11:57:24 -0700429 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700430 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700431 SetUrlSwitchCount(url_switch_count_ + 1);
432
Jay Srinivasan08262882012-12-28 19:29:43 -0800433 // Whenever we update the URL index, we should also clear the URL failure
434 // count so we can start over fresh for the new URL.
435 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800436}
437
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800438void PayloadState::IncrementFailureCount() {
439 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800440 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800441 LOG(INFO) << "Incrementing the URL failure count";
442 SetUrlFailureCount(next_url_failure_count);
443 } else {
444 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
445 << ". Trying next available URL";
446 IncrementUrlIndex();
447 }
448}
449
Jay Srinivasan08262882012-12-28 19:29:43 -0800450void PayloadState::UpdateBackoffExpiryTime() {
451 if (response_.disable_payload_backoff) {
452 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
453 SetBackoffExpiryTime(Time());
454 return;
455 }
456
Alex Deymo820cc702013-06-28 15:43:46 -0700457 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800458 SetBackoffExpiryTime(Time());
459 return;
460 }
461
462 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700463 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800464 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Deymo820cc702013-06-28 15:43:46 -0700465 int num_days = 1; // the value to be shifted.
466 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800467
468 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
469 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700470 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800471
472 // The number of days is the minimum of 2 raised to (payload_attempt_number
473 // - 1) or kMaxBackoffDays.
474 num_days = min(num_days << power, kMaxBackoffDays);
475
476 // We don't want all retries to happen exactly at the same time when
477 // retrying after backoff. So add some random minutes to fuzz.
478 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
479 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
480 TimeDelta::FromMinutes(fuzz_minutes);
481 LOG(INFO) << "Incrementing the backoff expiry time by "
482 << utils::FormatTimeDelta(next_backoff_interval);
483 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
484}
485
Jay Srinivasan19409b72013-04-12 19:23:36 -0700486void PayloadState::UpdateCurrentDownloadSource() {
487 current_download_source_ = kNumDownloadSources;
488
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700489 if (using_p2p_for_downloading_) {
490 current_download_source_ = kDownloadSourceHttpPeer;
491 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700492 string current_url = candidate_urls_[GetUrlIndex()];
Jay Srinivasan19409b72013-04-12 19:23:36 -0700493 if (StartsWithASCII(current_url, "https://", false))
494 current_download_source_ = kDownloadSourceHttpsServer;
495 else if (StartsWithASCII(current_url, "http://", false))
496 current_download_source_ = kDownloadSourceHttpServer;
497 }
498
499 LOG(INFO) << "Current download source: "
500 << utils::ToString(current_download_source_);
501}
502
503void PayloadState::UpdateBytesDownloaded(size_t count) {
504 SetCurrentBytesDownloaded(
505 current_download_source_,
506 GetCurrentBytesDownloaded(current_download_source_) + count,
507 false);
508 SetTotalBytesDownloaded(
509 current_download_source_,
510 GetTotalBytesDownloaded(current_download_source_) + count,
511 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800512
513 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700514}
515
David Zeuthen33bae492014-02-25 16:16:18 -0800516PayloadType PayloadState::CalculatePayloadType() {
517 PayloadType payload_type;
518 OmahaRequestParams* params = system_state_->request_params();
519 if (response_.is_delta_payload) {
520 payload_type = kPayloadTypeDelta;
521 } else if (params->delta_okay()) {
522 payload_type = kPayloadTypeFull;
523 } else { // Full payload, delta was not allowed by request.
524 payload_type = kPayloadTypeForcedFull;
525 }
526 return payload_type;
527}
528
529// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
530// metrics if the attempt ends abnormally, e.g. if the update_engine
531// process crashes or the device is rebooted. See
532// http://crbug.com/357676
533void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
534 int attempt_number = GetPayloadAttemptNumber();
535
536 PayloadType payload_type = CalculatePayloadType();
537
538 int64_t payload_size = response_.size;
539
540 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
541
542 ClockInterface *clock = system_state_->clock();
543 base::TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
544 base::TimeDelta duration_uptime = clock->GetMonotonicTime() -
545 attempt_start_time_monotonic_;
546
547 int64_t payload_download_speed_bps = 0;
548 int64_t usec = duration_uptime.InMicroseconds();
549 if (usec > 0) {
550 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
551 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
552 payload_download_speed_bps = static_cast<int64_t>(bps);
553 }
554
555 DownloadSource download_source = current_download_source_;
556
557 metrics::DownloadErrorCode payload_download_error_code =
558 metrics::DownloadErrorCode::kUnset;
559 ErrorCode internal_error_code = kErrorCodeSuccess;
560 metrics::AttemptResult attempt_result = utils::GetAttemptResult(code);
561
562 // Add additional detail to AttemptResult
563 switch (attempt_result) {
564 case metrics::AttemptResult::kPayloadDownloadError:
565 payload_download_error_code = utils::GetDownloadErrorCode(code);
566 break;
567
568 case metrics::AttemptResult::kInternalError:
569 internal_error_code = code;
570 break;
571
572 // Explicit fall-through for cases where we do not have additional
573 // detail. We avoid the default keyword to force people adding new
574 // AttemptResult values to visit this code and examine whether
575 // additional detail is needed.
576 case metrics::AttemptResult::kUpdateSucceeded:
577 case metrics::AttemptResult::kMetadataMalformed:
578 case metrics::AttemptResult::kOperationMalformed:
579 case metrics::AttemptResult::kOperationExecutionError:
580 case metrics::AttemptResult::kMetadataVerificationFailed:
581 case metrics::AttemptResult::kPayloadVerificationFailed:
582 case metrics::AttemptResult::kVerificationFailed:
583 case metrics::AttemptResult::kPostInstallFailed:
584 case metrics::AttemptResult::kAbnormalTermination:
585 case metrics::AttemptResult::kNumConstants:
586 case metrics::AttemptResult::kUnset:
587 break;
588 }
589
590 metrics::ReportUpdateAttemptMetrics(system_state_,
591 attempt_number,
592 payload_type,
593 duration,
594 duration_uptime,
595 payload_size,
596 payload_bytes_downloaded,
597 payload_download_speed_bps,
598 download_source,
599 attempt_result,
600 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700601 payload_download_error_code,
602 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800603}
604
605void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700606 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800607
608 // Report metrics collected from all known download sources to UMA.
609 int64_t successful_bytes_by_source[kNumDownloadSources];
610 int64_t total_bytes_by_source[kNumDownloadSources];
611 int64_t successful_bytes = 0;
612 int64_t total_bytes = 0;
613 int64_t successful_mbs = 0;
614 int64_t total_mbs = 0;
615
Jay Srinivasan19409b72013-04-12 19:23:36 -0700616 for (int i = 0; i < kNumDownloadSources; i++) {
617 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800618 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700619
David Zeuthen44848602013-06-24 13:32:14 -0700620 // Only consider this download source (and send byte counts) as
621 // having been used if we downloaded a non-trivial amount of bytes
622 // (e.g. at least 1 MiB) that contributed to the final success of
623 // the update. Otherwise we're going to end up with a lot of
624 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700625
David Zeuthen33bae492014-02-25 16:16:18 -0800626 bytes = GetCurrentBytesDownloaded(source);
627 successful_bytes_by_source[i] = bytes;
628 successful_bytes += bytes;
629 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700630 SetCurrentBytesDownloaded(source, 0, true);
631
David Zeuthen33bae492014-02-25 16:16:18 -0800632 bytes = GetTotalBytesDownloaded(source);
633 total_bytes_by_source[i] = bytes;
634 total_bytes += bytes;
635 total_mbs += bytes / kNumBytesInOneMiB;
636 SetTotalBytesDownloaded(source, 0, true);
637 }
638
639 int download_overhead_percentage = 0;
640 if (successful_bytes > 0) {
641 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
642 successful_bytes;
643 }
644
645 int url_switch_count = static_cast<int>(url_switch_count_);
646
647 int reboot_count = GetNumReboots();
648
649 SetNumReboots(0);
650
651 TimeDelta duration = GetUpdateDuration();
652 TimeDelta duration_uptime = GetUpdateDurationUptime();
653
654 prefs_->Delete(kPrefsUpdateTimestampStart);
655 prefs_->Delete(kPrefsUpdateDurationUptime);
656
657 PayloadType payload_type = CalculatePayloadType();
658
659 int64_t payload_size = response_.size;
660
661 int attempt_count = GetPayloadAttemptNumber();
662
663 int updates_abandoned_count = num_responses_seen_ - 1;
664
665 metrics::ReportSuccessfulUpdateMetrics(system_state_,
666 attempt_count,
667 updates_abandoned_count,
668 payload_type,
669 payload_size,
670 total_bytes_by_source,
671 download_overhead_percentage,
672 duration,
673 reboot_count,
674 url_switch_count);
675
676 // TODO(zeuthen): This is the old metric reporting code which is
677 // slated for removal soon. See http://crbug.com/355745 for details.
678
679 // The old metrics code is using MiB's instead of bytes to calculate
680 // the overhead which due to rounding makes the numbers slightly
681 // different.
682 download_overhead_percentage = 0;
683 if (successful_mbs > 0) {
684 download_overhead_percentage = (total_mbs - successful_mbs) * 100ULL /
685 successful_mbs;
686 }
687
688 int download_sources_used = 0;
689 for (int i = 0; i < kNumDownloadSources; i++) {
690 DownloadSource source = static_cast<DownloadSource>(i);
691 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
692 int64_t mbs;
693
694 // Only consider this download source (and send byte counts) as
695 // having been used if we downloaded a non-trivial amount of bytes
696 // (e.g. at least 1 MiB) that contributed to the final success of
697 // the update. Otherwise we're going to end up with a lot of
698 // zero-byte events in the histogram.
699
700 mbs = successful_bytes_by_source[i] / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700701 if (mbs > 0) {
David Zeuthen33bae492014-02-25 16:16:18 -0800702 metric = "Installer.SuccessfulMBsDownloadedFrom" +
703 utils::ToString(source);
David Zeuthen44848602013-06-24 13:32:14 -0700704 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
705 system_state_->metrics_lib()->SendToUMA(metric,
706 mbs,
707 0, // min
708 kMaxMiBs,
709 kNumDefaultUmaBuckets);
710 }
David Zeuthen33bae492014-02-25 16:16:18 -0800711
712 mbs = total_bytes_by_source[i] / kNumBytesInOneMiB;
713 if (mbs > 0) {
714 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
715 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
716 system_state_->metrics_lib()->SendToUMA(metric,
717 mbs,
718 0, // min
719 kMaxMiBs,
720 kNumDefaultUmaBuckets);
721 download_sources_used |= (1 << i);
722 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700723 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700724
725 metric = "Installer.DownloadSourcesUsed";
726 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
727 << " (bit flags) for metric " << metric;
728 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
729 system_state_->metrics_lib()->SendToUMA(metric,
730 download_sources_used,
731 0, // min
732 1 << kNumDownloadSources,
733 num_buckets);
734
David Zeuthen33bae492014-02-25 16:16:18 -0800735 metric = "Installer.DownloadOverheadPercentage";
736 LOG(INFO) << "Uploading " << download_overhead_percentage
737 << "% for metric " << metric;
738 system_state_->metrics_lib()->SendToUMA(metric,
739 download_overhead_percentage,
740 0, // min: 0% overhead
741 1000, // max: 1000% overhead
742 kNumDefaultUmaBuckets);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700743
David Zeuthen33bae492014-02-25 16:16:18 -0800744 metric = "Installer.UpdateURLSwitches";
745 LOG(INFO) << "Uploading " << url_switch_count
746 << " (count) for metric " << metric;
David Zeuthencc6f9962013-04-18 11:57:24 -0700747 system_state_->metrics_lib()->SendToUMA(
748 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800749 url_switch_count,
David Zeuthencc6f9962013-04-18 11:57:24 -0700750 0, // min value
751 100, // max value
752 kNumDefaultUmaBuckets);
David Zeuthencc6f9962013-04-18 11:57:24 -0700753
David Zeuthen33bae492014-02-25 16:16:18 -0800754 metric = "Installer.UpdateNumReboots";
755 LOG(INFO) << "Uploading reboot count of " << reboot_count << " for metric "
Chris Sosabe45bef2013-04-09 18:25:12 -0700756 << metric;
757 system_state_->metrics_lib()->SendToUMA(
758 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800759 reboot_count, // sample
760 0, // min = 0.
761 50, // max
Chris Sosabe45bef2013-04-09 18:25:12 -0700762 25); // buckets
David Zeuthen33bae492014-02-25 16:16:18 -0800763
764 metric = "Installer.UpdateDurationMinutes";
765 system_state_->metrics_lib()->SendToUMA(
766 metric,
767 static_cast<int>(duration.InMinutes()),
768 1, // min: 1 minute
769 365*24*60, // max: 1 year (approx)
770 kNumDefaultUmaBuckets);
771 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
772 << " for metric " << metric;
773
774 metric = "Installer.UpdateDurationUptimeMinutes";
775 system_state_->metrics_lib()->SendToUMA(
776 metric,
777 static_cast<int>(duration_uptime.InMinutes()),
778 1, // min: 1 minute
779 30*24*60, // max: 1 month (approx)
780 kNumDefaultUmaBuckets);
781 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
782 << " for metric " << metric;
783
784 metric = "Installer.PayloadFormat";
785 system_state_->metrics_lib()->SendEnumToUMA(
786 metric,
787 payload_type,
788 kNumPayloadTypes);
789 LOG(INFO) << "Uploading " << utils::ToString(payload_type)
790 << " for metric " << metric;
791
792 metric = "Installer.AttemptsCount.Total";
793 system_state_->metrics_lib()->SendToUMA(
794 metric,
795 attempt_count,
796 1, // min
797 50, // max
798 kNumDefaultUmaBuckets);
799 LOG(INFO) << "Uploading " << attempt_count
800 << " for metric " << metric;
801
802 metric = "Installer.UpdatesAbandonedCount";
803 LOG(INFO) << "Uploading " << updates_abandoned_count
804 << " (count) for metric " << metric;
805 system_state_->metrics_lib()->SendToUMA(
806 metric,
807 updates_abandoned_count,
808 0, // min value
809 100, // max value
810 kNumDefaultUmaBuckets);
Chris Sosabe45bef2013-04-09 18:25:12 -0700811}
812
813void PayloadState::UpdateNumReboots() {
814 // We only update the reboot count when the system has been detected to have
815 // been rebooted.
816 if (!system_state_->system_rebooted()) {
817 return;
818 }
819
820 SetNumReboots(GetNumReboots() + 1);
821}
822
823void PayloadState::SetNumReboots(uint32_t num_reboots) {
824 CHECK(prefs_);
825 num_reboots_ = num_reboots;
826 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
827 LOG(INFO) << "Number of Reboots during current update attempt = "
828 << num_reboots_;
829}
830
Jay Srinivasan08262882012-12-28 19:29:43 -0800831void PayloadState::ResetPersistedState() {
832 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700833 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800834 SetUrlIndex(0);
835 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700836 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800837 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700838 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
David Zeuthen9a017f22013-04-11 16:10:26 -0700839 SetUpdateTimestampEnd(Time()); // Set to null time
840 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700841 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700842 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700843 SetP2PNumAttempts(0);
844 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Chris Sosaaa18e162013-06-20 13:20:30 -0700845}
846
847void PayloadState::ResetRollbackVersion() {
848 CHECK(powerwash_safe_prefs_);
849 rollback_version_ = "";
850 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700851}
852
853void PayloadState::ResetDownloadSourcesOnNewUpdate() {
854 for (int i = 0; i < kNumDownloadSources; i++) {
855 DownloadSource source = static_cast<DownloadSource>(i);
856 SetCurrentBytesDownloaded(source, 0, true);
857 // Note: Not resetting the TotalBytesDownloaded as we want that metric
858 // to count the bytes downloaded across various update attempts until
859 // we have successfully applied the update.
860 }
861}
862
Chris Sosab3dcdb32013-09-04 15:22:12 -0700863int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700864 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700865 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700866 return 0;
867
868 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700869 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700870 return 0;
871
872 if (stored_value < 0) {
873 LOG(ERROR) << key << ": Invalid value (" << stored_value
874 << ") in persisted state. Defaulting to 0";
875 return 0;
876 }
877
878 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800879}
880
881string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700882 string response_sign = base::StringPrintf(
883 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800884
Jay Srinivasan53173b92013-05-17 17:13:01 -0700885 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700886 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
887 static_cast<int>(i),
888 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800889
Alex Vakulenko75039d72014-03-25 12:36:28 -0700890 response_sign += base::StringPrintf(
891 "Payload Size = %ju\n"
892 "Payload Sha256 Hash = %s\n"
893 "Metadata Size = %ju\n"
894 "Metadata Signature = %s\n"
895 "Is Delta Payload = %d\n"
896 "Max Failure Count Per Url = %d\n"
897 "Disable Payload Backoff = %d\n",
898 static_cast<uintmax_t>(response_.size),
899 response_.hash.c_str(),
900 static_cast<uintmax_t>(response_.metadata_size),
901 response_.metadata_signature.c_str(),
902 response_.is_delta_payload,
903 response_.max_failure_count_per_url,
904 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800905 return response_sign;
906}
907
908void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800909 CHECK(prefs_);
910 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800911 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
912 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
913 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800914 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800915}
916
Jay Srinivasan19409b72013-04-12 19:23:36 -0700917void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800918 CHECK(prefs_);
919 response_signature_ = response_signature;
920 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
921 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
922}
923
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800924void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700925 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800926}
927
Alex Deymo820cc702013-06-28 15:43:46 -0700928void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700929 SetFullPayloadAttemptNumber(GetPersistedValue(
930 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700931}
932
933void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800934 CHECK(prefs_);
935 payload_attempt_number_ = payload_attempt_number;
936 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
937 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
938}
939
Alex Deymo820cc702013-06-28 15:43:46 -0700940void PayloadState::SetFullPayloadAttemptNumber(
941 int full_payload_attempt_number) {
942 CHECK(prefs_);
943 full_payload_attempt_number_ = full_payload_attempt_number;
944 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
945 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
946 full_payload_attempt_number_);
947}
948
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800949void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700950 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800951}
952
953void PayloadState::SetUrlIndex(uint32_t url_index) {
954 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800955 url_index_ = url_index;
956 LOG(INFO) << "Current URL Index = " << url_index_;
957 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700958
959 // Also update the download source, which is purely dependent on the
960 // current URL index alone.
961 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800962}
963
David Zeuthencc6f9962013-04-18 11:57:24 -0700964void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700965 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700966}
967
968void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
969 CHECK(prefs_);
970 url_switch_count_ = url_switch_count;
971 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
972 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
973}
974
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800975void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700976 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800977}
978
979void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
980 CHECK(prefs_);
981 url_failure_count_ = url_failure_count;
982 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
983 << ")'s Failure Count = " << url_failure_count_;
984 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800985}
986
Jay Srinivasan08262882012-12-28 19:29:43 -0800987void PayloadState::LoadBackoffExpiryTime() {
988 CHECK(prefs_);
989 int64_t stored_value;
990 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
991 return;
992
993 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
994 return;
995
996 Time stored_time = Time::FromInternalValue(stored_value);
997 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
998 LOG(ERROR) << "Invalid backoff expiry time ("
999 << utils::ToString(stored_time)
1000 << ") in persisted state. Resetting.";
1001 stored_time = Time();
1002 }
1003 SetBackoffExpiryTime(stored_time);
1004}
1005
1006void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
1007 CHECK(prefs_);
1008 backoff_expiry_time_ = new_time;
1009 LOG(INFO) << "Backoff Expiry Time = "
1010 << utils::ToString(backoff_expiry_time_);
1011 prefs_->SetInt64(kPrefsBackoffExpiryTime,
1012 backoff_expiry_time_.ToInternalValue());
1013}
1014
David Zeuthen9a017f22013-04-11 16:10:26 -07001015TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001016 Time end_time = update_timestamp_end_.is_null()
1017 ? system_state_->clock()->GetWallclockTime() :
1018 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001019 return end_time - update_timestamp_start_;
1020}
1021
1022void PayloadState::LoadUpdateTimestampStart() {
1023 int64_t stored_value;
1024 Time stored_time;
1025
1026 CHECK(prefs_);
1027
David Zeuthenf413fe52013-04-22 14:04:39 -07001028 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001029
1030 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1031 // The preference missing is not unexpected - in that case, just
1032 // use the current time as start time
1033 stored_time = now;
1034 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1035 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1036 stored_time = now;
1037 } else {
1038 stored_time = Time::FromInternalValue(stored_value);
1039 }
1040
1041 // Sanity check: If the time read from disk is in the future
1042 // (modulo some slack to account for possible NTP drift
1043 // adjustments), something is fishy and we should report and
1044 // reset.
1045 TimeDelta duration_according_to_stored_time = now - stored_time;
1046 if (duration_according_to_stored_time < -kDurationSlack) {
1047 LOG(ERROR) << "The UpdateTimestampStart value ("
1048 << utils::ToString(stored_time)
1049 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001050 << utils::FormatTimeDelta(duration_according_to_stored_time)
1051 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001052 stored_time = now;
1053 }
1054
1055 SetUpdateTimestampStart(stored_time);
1056}
1057
1058void PayloadState::SetUpdateTimestampStart(const Time& value) {
1059 CHECK(prefs_);
1060 update_timestamp_start_ = value;
1061 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1062 update_timestamp_start_.ToInternalValue());
1063 LOG(INFO) << "Update Timestamp Start = "
1064 << utils::ToString(update_timestamp_start_);
1065}
1066
1067void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1068 update_timestamp_end_ = value;
1069 LOG(INFO) << "Update Timestamp End = "
1070 << utils::ToString(update_timestamp_end_);
1071}
1072
1073TimeDelta PayloadState::GetUpdateDurationUptime() {
1074 return update_duration_uptime_;
1075}
1076
1077void PayloadState::LoadUpdateDurationUptime() {
1078 int64_t stored_value;
1079 TimeDelta stored_delta;
1080
1081 CHECK(prefs_);
1082
1083 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1084 // The preference missing is not unexpected - in that case, just
1085 // we'll use zero as the delta
1086 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1087 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1088 stored_delta = TimeDelta::FromSeconds(0);
1089 } else {
1090 stored_delta = TimeDelta::FromInternalValue(stored_value);
1091 }
1092
1093 // Sanity-check: Uptime can never be greater than the wall-clock
1094 // difference (modulo some slack). If it is, report and reset
1095 // to the wall-clock difference.
1096 TimeDelta diff = GetUpdateDuration() - stored_delta;
1097 if (diff < -kDurationSlack) {
1098 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001099 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001100 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001101 << utils::FormatTimeDelta(diff)
1102 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001103 stored_delta = update_duration_current_;
1104 }
1105
1106 SetUpdateDurationUptime(stored_delta);
1107}
1108
Chris Sosabe45bef2013-04-09 18:25:12 -07001109void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001110 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001111}
1112
1113void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001114 CHECK(powerwash_safe_prefs_);
1115 string rollback_version;
1116 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1117 &rollback_version)) {
1118 SetRollbackVersion(rollback_version);
1119 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001120}
1121
1122void PayloadState::SetRollbackVersion(const string& rollback_version) {
1123 CHECK(powerwash_safe_prefs_);
1124 LOG(INFO) << "Blacklisting version "<< rollback_version;
1125 rollback_version_ = rollback_version;
1126 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001127}
1128
David Zeuthen9a017f22013-04-11 16:10:26 -07001129void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1130 const Time& timestamp,
1131 bool use_logging) {
1132 CHECK(prefs_);
1133 update_duration_uptime_ = value;
1134 update_duration_uptime_timestamp_ = timestamp;
1135 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1136 update_duration_uptime_.ToInternalValue());
1137 if (use_logging) {
1138 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001139 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001140 }
1141}
1142
1143void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001144 Time now = system_state_->clock()->GetMonotonicTime();
1145 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001146}
1147
1148void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001149 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001150 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1151 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1152 // We're frequently called so avoid logging this write
1153 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1154}
1155
Jay Srinivasan19409b72013-04-12 19:23:36 -07001156string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1157 return prefix + "-from-" + utils::ToString(source);
1158}
1159
1160void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1161 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001162 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001163}
1164
1165void PayloadState::SetCurrentBytesDownloaded(
1166 DownloadSource source,
1167 uint64_t current_bytes_downloaded,
1168 bool log) {
1169 CHECK(prefs_);
1170
1171 if (source >= kNumDownloadSources)
1172 return;
1173
1174 // Update the in-memory value.
1175 current_bytes_downloaded_[source] = current_bytes_downloaded;
1176
1177 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1178 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1179 LOG_IF(INFO, log) << "Current bytes downloaded for "
1180 << utils::ToString(source) << " = "
1181 << GetCurrentBytesDownloaded(source);
1182}
1183
1184void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1185 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001186 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001187}
1188
1189void PayloadState::SetTotalBytesDownloaded(
1190 DownloadSource source,
1191 uint64_t total_bytes_downloaded,
1192 bool log) {
1193 CHECK(prefs_);
1194
1195 if (source >= kNumDownloadSources)
1196 return;
1197
1198 // Update the in-memory value.
1199 total_bytes_downloaded_[source] = total_bytes_downloaded;
1200
1201 // Persist.
1202 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1203 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1204 LOG_IF(INFO, log) << "Total bytes downloaded for "
1205 << utils::ToString(source) << " = "
1206 << GetTotalBytesDownloaded(source);
1207}
1208
David Zeuthena573d6f2013-06-14 16:13:36 -07001209void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001210 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001211}
1212
1213void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1214 CHECK(prefs_);
1215 num_responses_seen_ = num_responses_seen;
1216 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1217 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1218}
1219
Alex Deymob33b0f02013-08-08 21:10:02 -07001220void PayloadState::ReportUpdatesAbandonedEventCountMetric() {
1221 string metric = "Installer.UpdatesAbandonedEventCount";
1222 int value = num_responses_seen_ - 1;
1223
1224 // Do not send an "abandoned" event when 0 payloads were abandoned since the
1225 // last successful update.
1226 if (value == 0)
1227 return;
1228
1229 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1230 system_state_->metrics_lib()->SendToUMA(
1231 metric,
1232 value,
1233 0, // min value
1234 100, // max value
1235 kNumDefaultUmaBuckets);
1236}
1237
Jay Srinivasan53173b92013-05-17 17:13:01 -07001238void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001239 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001240
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001241 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001242 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001243 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001244 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1245 } else {
1246 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1247 http_url_ok = true;
1248 }
1249
1250 candidate_urls_.clear();
1251 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1252 string candidate_url = response_.payload_urls[i];
1253 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1254 continue;
1255 candidate_urls_.push_back(candidate_url);
1256 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1257 << ": " << candidate_url;
1258 }
1259
1260 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1261 << "out of " << response_.payload_urls.size() << " URLs supplied";
1262}
1263
David Zeuthene4c58bf2013-06-18 17:26:50 -07001264void PayloadState::CreateSystemUpdatedMarkerFile() {
1265 CHECK(prefs_);
1266 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1267 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1268}
1269
1270void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1271 // Send |time_to_reboot| as a UMA stat.
1272 string metric = "Installer.TimeToRebootMinutes";
1273 system_state_->metrics_lib()->SendToUMA(metric,
1274 time_to_reboot.InMinutes(),
1275 0, // min: 0 minute
1276 30*24*60, // max: 1 month (approx)
1277 kNumDefaultUmaBuckets);
1278 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1279 << " for metric " << metric;
David Zeuthen33bae492014-02-25 16:16:18 -08001280
1281 metric = metrics::kMetricTimeToRebootMinutes;
1282 system_state_->metrics_lib()->SendToUMA(metric,
1283 time_to_reboot.InMinutes(),
1284 0, // min: 0 minute
1285 30*24*60, // max: 1 month (approx)
1286 kNumDefaultUmaBuckets);
1287 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1288 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001289}
1290
1291void PayloadState::UpdateEngineStarted() {
Alex Deymo569c4242013-07-24 12:01:01 -07001292 // Avoid the UpdateEngineStarted actions if this is not the first time we
1293 // run the update engine since reboot.
1294 if (!system_state_->system_rebooted())
1295 return;
1296
David Zeuthene4c58bf2013-06-18 17:26:50 -07001297 // Figure out if we just booted into a new update
1298 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1299 int64_t stored_value;
1300 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1301 Time system_updated_at = Time::FromInternalValue(stored_value);
1302 if (!system_updated_at.is_null()) {
1303 TimeDelta time_to_reboot =
1304 system_state_->clock()->GetWallclockTime() - system_updated_at;
1305 if (time_to_reboot.ToInternalValue() < 0) {
1306 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1307 << utils::ToString(system_updated_at);
1308 } else {
1309 BootedIntoUpdate(time_to_reboot);
1310 }
1311 }
1312 }
1313 prefs_->Delete(kPrefsSystemUpdatedMarker);
1314 }
Alex Deymo42432912013-07-12 20:21:15 -07001315 // Check if it is needed to send metrics about a failed reboot into a new
1316 // version.
1317 ReportFailedBootIfNeeded();
1318}
1319
1320void PayloadState::ReportFailedBootIfNeeded() {
1321 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1322 // payload was marked as ready immediately before the last reboot, and we
1323 // need to check if such payload successfully rebooted or not.
1324 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001325 int64_t installed_from = 0;
1326 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001327 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1328 return;
1329 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001330 if (int(installed_from) ==
1331 utils::GetPartitionNumber(system_state_->hardware()->BootDevice())) {
Alex Deymo42432912013-07-12 20:21:15 -07001332 // A reboot was pending, but the chromebook is again in the same
1333 // BootDevice where the update was installed from.
1334 int64_t target_attempt;
1335 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1336 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1337 "TargetVersionInstalledFrom was present.";
1338 target_attempt = 1;
1339 }
1340
1341 // Report the UMA metric of the current boot failure.
1342 string metric = "Installer.RebootToNewPartitionAttempt";
1343
1344 LOG(INFO) << "Uploading " << target_attempt
1345 << " (count) for metric " << metric;
1346 system_state_->metrics_lib()->SendToUMA(
1347 metric,
1348 target_attempt,
1349 1, // min value
1350 50, // max value
1351 kNumDefaultUmaBuckets);
David Zeuthen33bae492014-02-25 16:16:18 -08001352
1353 metric = metrics::kMetricFailedUpdateCount;
1354 LOG(INFO) << "Uploading " << target_attempt
1355 << " (count) for metric " << metric;
1356 system_state_->metrics_lib()->SendToUMA(
1357 metric,
1358 target_attempt,
1359 1, // min value
1360 50, // max value
1361 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001362 } else {
1363 prefs_->Delete(kPrefsTargetVersionAttempt);
1364 prefs_->Delete(kPrefsTargetVersionUniqueId);
1365 }
1366 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1367 }
1368}
1369
1370void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1371 // Expect to boot into the new partition in the next reboot setting the
1372 // TargetVersion* flags in the Prefs.
1373 string stored_target_version_uid;
1374 string target_version_id;
1375 string target_partition;
1376 int64_t target_attempt;
1377
1378 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1379 prefs_->GetString(kPrefsTargetVersionUniqueId,
1380 &stored_target_version_uid) &&
1381 stored_target_version_uid == target_version_uid) {
1382 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1383 target_attempt = 0;
1384 } else {
1385 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1386 target_attempt = 0;
1387 }
1388 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1389
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001390 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
1391 utils::GetPartitionNumber(
Alex Deymo42432912013-07-12 20:21:15 -07001392 system_state_->hardware()->BootDevice()));
1393}
1394
1395void PayloadState::ResetUpdateStatus() {
1396 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1397 // rebooted the next boot is not flagged as failed to rebooted into the
1398 // new applied payload.
1399 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1400
1401 // Also decrement the attempt number if it exists.
1402 int64_t target_attempt;
1403 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1404 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt-1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001405}
1406
David Zeuthendcba8092013-08-06 12:16:35 -07001407int PayloadState::GetP2PNumAttempts() {
1408 return p2p_num_attempts_;
1409}
1410
1411void PayloadState::SetP2PNumAttempts(int value) {
1412 p2p_num_attempts_ = value;
1413 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1414 CHECK(prefs_);
1415 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1416}
1417
1418void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001419 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001420}
1421
1422Time PayloadState::GetP2PFirstAttemptTimestamp() {
1423 return p2p_first_attempt_timestamp_;
1424}
1425
1426void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1427 p2p_first_attempt_timestamp_ = time;
1428 LOG(INFO) << "p2p First Attempt Timestamp = "
1429 << utils::ToString(p2p_first_attempt_timestamp_);
1430 CHECK(prefs_);
1431 int64_t stored_value = time.ToInternalValue();
1432 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1433}
1434
1435void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001436 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001437 Time stored_time = Time::FromInternalValue(stored_value);
1438 SetP2PFirstAttemptTimestamp(stored_time);
1439}
1440
1441void PayloadState::P2PNewAttempt() {
1442 CHECK(prefs_);
1443 // Set timestamp, if it hasn't been set already
1444 if (p2p_first_attempt_timestamp_.is_null()) {
1445 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1446 }
1447 // Increase number of attempts
1448 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1449}
1450
1451bool PayloadState::P2PAttemptAllowed() {
1452 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1453 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1454 << " which is greater than "
1455 << kMaxP2PAttempts
1456 << " - disallowing p2p.";
1457 return false;
1458 }
1459
1460 if (!p2p_first_attempt_timestamp_.is_null()) {
1461 Time now = system_state_->clock()->GetWallclockTime();
1462 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1463 if (time_spent_attempting_p2p.InSeconds() < 0) {
1464 LOG(ERROR) << "Time spent attempting p2p is negative"
1465 << " - disallowing p2p.";
1466 return false;
1467 }
1468 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1469 LOG(INFO) << "Time spent attempting p2p is "
1470 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1471 << " which is greater than "
1472 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1473 kMaxP2PAttemptTimeSeconds))
1474 << " - disallowing p2p.";
1475 return false;
1476 }
1477 }
1478
1479 return true;
1480}
1481
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001482} // namespace chromeos_update_engine