blob: 51041ef8de8f416d5327b31752003b3eb71c12cd [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>
Gilad Arnold1f847232014-04-07 12:07:49 -070013#include <policy/device_policy.h>
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080014
David Zeuthenf413fe52013-04-22 14:04:39 -070015#include "update_engine/clock.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070016#include "update_engine/constants.h"
Alex Deymo42432912013-07-12 20:21:15 -070017#include "update_engine/hardware_interface.h"
18#include "update_engine/install_plan.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070019#include "update_engine/omaha_request_params.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070020#include "update_engine/prefs.h"
David Zeuthenb281f072014-04-02 10:20:19 -070021#include "update_engine/real_dbus_wrapper.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070022#include "update_engine/system_state.h"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080023#include "update_engine/utils.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080024
Jay Srinivasan08262882012-12-28 19:29:43 -080025using base::Time;
26using base::TimeDelta;
27using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080028using std::string;
29
30namespace chromeos_update_engine {
31
David Zeuthen9a017f22013-04-11 16:10:26 -070032const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
33
Jay Srinivasan08262882012-12-28 19:29:43 -080034// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070035static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080036
Jay Srinivasan08262882012-12-28 19:29:43 -080037// We want to randomize retry attempts after the backoff by +/- 6 hours.
38static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080039
Jay Srinivasan19409b72013-04-12 19:23:36 -070040PayloadState::PayloadState()
41 : prefs_(NULL),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070042 using_p2p_for_downloading_(false),
Jay Srinivasan19409b72013-04-12 19:23:36 -070043 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070044 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070045 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070046 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070047 url_switch_count_(0),
48 p2p_num_attempts_(0) {
Jay Srinivasan19409b72013-04-12 19:23:36 -070049 for (int i = 0; i <= kNumDownloadSources; i++)
50 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
51}
52
53bool PayloadState::Initialize(SystemState* system_state) {
54 system_state_ = system_state;
55 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070056 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080057 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080058 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070059 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080060 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080061 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070062 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080063 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070064 LoadUpdateTimestampStart();
65 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
66 // being called before it. Don't reorder.
67 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070068 for (int i = 0; i < kNumDownloadSources; i++) {
69 DownloadSource source = static_cast<DownloadSource>(i);
70 LoadCurrentBytesDownloaded(source);
71 LoadTotalBytesDownloaded(source);
72 }
Chris Sosabe45bef2013-04-09 18:25:12 -070073 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070074 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070075 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070076 LoadP2PFirstAttemptTimestamp();
77 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080078 return true;
79}
80
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080081void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080082 // Always store the latest response.
83 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080084
Jay Srinivasan53173b92013-05-17 17:13:01 -070085 // Compute the candidate URLs first as they are used to calculate the
86 // response signature so that a change in enterprise policy for
87 // HTTP downloads being enabled or not could be honored as soon as the
88 // next update check happens.
89 ComputeCandidateUrls();
90
Jay Srinivasan08262882012-12-28 19:29:43 -080091 // Check if the "signature" of this response (i.e. the fields we care about)
92 // has changed.
93 string new_response_signature = CalculateResponseSignature();
94 bool has_response_changed = (response_signature_ != new_response_signature);
95
96 // If the response has changed, we should persist the new signature and
97 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080098 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -080099 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700100 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800101 SetResponseSignature(new_response_signature);
102 ResetPersistedState();
Alex Deymob33b0f02013-08-08 21:10:02 -0700103 ReportUpdatesAbandonedEventCountMetric();
Jay Srinivasan08262882012-12-28 19:29:43 -0800104 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800105 }
106
Jay Srinivasan08262882012-12-28 19:29:43 -0800107 // This is the earliest point at which we can validate whether the URL index
108 // we loaded from the persisted state is a valid value. If the response
109 // hasn't changed but the URL index is invalid, it's indicative of some
110 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700111 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800112 LOG(INFO) << "Resetting all payload state as the url index seems to have "
113 "been tampered with";
114 ResetPersistedState();
115 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800116 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700117
118 // Update the current download source which depends on the latest value of
119 // the response.
120 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800121}
122
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700123void PayloadState::SetUsingP2PForDownloading(bool value) {
124 using_p2p_for_downloading_ = value;
125 // Update the current download source which depends on whether we are
126 // using p2p or not.
127 UpdateCurrentDownloadSource();
128}
129
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800130void PayloadState::DownloadComplete() {
131 LOG(INFO) << "Payload downloaded successfully";
132 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700133 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800134}
135
136void PayloadState::DownloadProgress(size_t count) {
137 if (count == 0)
138 return;
139
David Zeuthen9a017f22013-04-11 16:10:26 -0700140 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700141 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700142
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800143 // We've received non-zero bytes from a recent download operation. Since our
144 // URL failure count is meant to penalize a URL only for consecutive
145 // failures, downloading bytes successfully means we should reset the failure
146 // count (as we know at least that the URL is working). In future, we can
147 // design this to be more sophisticated to check for more intelligent failure
148 // patterns, but right now, even 1 byte downloaded will mark the URL to be
149 // good unless it hits 10 (or configured number of) consecutive failures
150 // again.
151
152 if (GetUrlFailureCount() == 0)
153 return;
154
155 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
156 << " to 0 as we received " << count << " bytes successfully";
157 SetUrlFailureCount(0);
158}
159
David Zeuthen33bae492014-02-25 16:16:18 -0800160void PayloadState::AttemptStarted() {
161 ClockInterface *clock = system_state_->clock();
162 attempt_start_time_boot_ = clock->GetBootTime();
163 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800164 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700165
166 metrics::ConnectionType type;
167 NetworkConnectionType network_connection_type;
168 NetworkTethering tethering;
169 RealDBusWrapper dbus_iface;
170 ConnectionManager* connection_manager = system_state_->connection_manager();
171 if (!connection_manager->GetConnectionProperties(&dbus_iface,
172 &network_connection_type,
173 &tethering)) {
174 LOG(ERROR) << "Failed to determine connection type.";
175 type = metrics::ConnectionType::kUnknown;
176 } else {
177 type = utils::GetConnectionType(network_connection_type, tethering);
178 }
179 attempt_connection_type_ = type;
David Zeuthen33bae492014-02-25 16:16:18 -0800180}
181
Chris Sosabe45bef2013-04-09 18:25:12 -0700182void PayloadState::UpdateResumed() {
183 LOG(INFO) << "Resuming an update that was previously started.";
184 UpdateNumReboots();
David Zeuthen33bae492014-02-25 16:16:18 -0800185 AttemptStarted();
Chris Sosabe45bef2013-04-09 18:25:12 -0700186}
187
Jay Srinivasan19409b72013-04-12 19:23:36 -0700188void PayloadState::UpdateRestarted() {
189 LOG(INFO) << "Starting a new update";
190 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700191 SetNumReboots(0);
David Zeuthen33bae492014-02-25 16:16:18 -0800192 AttemptStarted();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700193}
194
David Zeuthen9a017f22013-04-11 16:10:26 -0700195void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700196 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700197 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700198 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800199
200 CollectAndReportAttemptMetrics(kErrorCodeSuccess);
201 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthena573d6f2013-06-14 16:13:36 -0700202
203 // Reset the number of responses seen since it counts from the last
204 // successful update, e.g. now.
205 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700206
207 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700208}
209
David Zeuthena99981f2013-04-29 13:42:47 -0700210void PayloadState::UpdateFailed(ErrorCode error) {
211 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800212 LOG(INFO) << "Updating payload state for error code: " << base_error
213 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800214
Jay Srinivasan53173b92013-05-17 17:13:01 -0700215 if (candidate_urls_.size() == 0) {
216 // This means we got this error even before we got a valid Omaha response
217 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800218 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800219 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
220 return;
221 }
222
David Zeuthen33bae492014-02-25 16:16:18 -0800223 CollectAndReportAttemptMetrics(base_error);
224
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800225 switch (base_error) {
226 // Errors which are good indicators of a problem with a particular URL or
227 // the protocol used in the URL or entities in the communication channel
228 // (e.g. proxies). We should try the next available URL in the next update
229 // check to quickly recover from these errors.
David Zeuthena99981f2013-04-29 13:42:47 -0700230 case kErrorCodePayloadHashMismatchError:
231 case kErrorCodePayloadSizeMismatchError:
232 case kErrorCodeDownloadPayloadVerificationError:
233 case kErrorCodeDownloadPayloadPubKeyVerificationError:
234 case kErrorCodeSignedDeltaPayloadExpectedError:
235 case kErrorCodeDownloadInvalidMetadataMagicString:
236 case kErrorCodeDownloadSignatureMissingInManifest:
237 case kErrorCodeDownloadManifestParseError:
238 case kErrorCodeDownloadMetadataSignatureError:
239 case kErrorCodeDownloadMetadataSignatureVerificationError:
240 case kErrorCodeDownloadMetadataSignatureMismatch:
241 case kErrorCodeDownloadOperationHashVerificationError:
242 case kErrorCodeDownloadOperationExecutionError:
243 case kErrorCodeDownloadOperationHashMismatch:
244 case kErrorCodeDownloadInvalidMetadataSize:
245 case kErrorCodeDownloadInvalidMetadataSignature:
246 case kErrorCodeDownloadOperationHashMissingError:
247 case kErrorCodeDownloadMetadataSignatureMissingError:
Gilad Arnold21504f02013-05-24 08:51:22 -0700248 case kErrorCodePayloadMismatchedType:
Don Garrett4d039442013-10-28 18:40:06 -0700249 case kErrorCodeUnsupportedMajorPayloadVersion:
250 case kErrorCodeUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800251 IncrementUrlIndex();
252 break;
253
254 // Errors which seem to be just transient network/communication related
255 // failures and do not indicate any inherent problem with the URL itself.
256 // So, we should keep the current URL but just increment the
257 // failure count to give it more chances. This way, while we maximize our
258 // chances of downloading from the URLs that appear earlier in the response
259 // (because download from a local server URL that appears earlier in a
260 // response is preferable than downloading from the next URL which could be
261 // a internet URL and thus could be more expensive).
David Zeuthena99981f2013-04-29 13:42:47 -0700262 case kErrorCodeError:
263 case kErrorCodeDownloadTransferError:
264 case kErrorCodeDownloadWriteError:
265 case kErrorCodeDownloadStateInitializationError:
266 case kErrorCodeOmahaErrorInHTTPResponse: // Aggregate code for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800267 IncrementFailureCount();
268 break;
269
270 // Errors which are not specific to a URL and hence shouldn't result in
271 // the URL being penalized. This can happen in two cases:
272 // 1. We haven't started downloading anything: These errors don't cost us
273 // anything in terms of actual payload bytes, so we should just do the
274 // regular retries at the next update check.
275 // 2. We have successfully downloaded the payload: In this case, the
276 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800277 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800278 // In either case, there's no need to update URL index or failure count.
David Zeuthena99981f2013-04-29 13:42:47 -0700279 case kErrorCodeOmahaRequestError:
280 case kErrorCodeOmahaResponseHandlerError:
281 case kErrorCodePostinstallRunnerError:
282 case kErrorCodeFilesystemCopierError:
283 case kErrorCodeInstallDeviceOpenError:
284 case kErrorCodeKernelDeviceOpenError:
285 case kErrorCodeDownloadNewPartitionInfoError:
286 case kErrorCodeNewRootfsVerificationError:
287 case kErrorCodeNewKernelVerificationError:
288 case kErrorCodePostinstallBootedFromFirmwareB:
Don Garrett81018e02013-07-30 18:46:31 -0700289 case kErrorCodePostinstallFirmwareRONotUpdatable:
David Zeuthena99981f2013-04-29 13:42:47 -0700290 case kErrorCodeOmahaRequestEmptyResponseError:
291 case kErrorCodeOmahaRequestXMLParseError:
292 case kErrorCodeOmahaResponseInvalid:
293 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
294 case kErrorCodeOmahaUpdateDeferredPerPolicy:
295 case kErrorCodeOmahaUpdateDeferredForBackoff:
296 case kErrorCodePostinstallPowerwashError:
297 case kErrorCodeUpdateCanceledByChannelChange:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800298 LOG(INFO) << "Not incrementing URL index or failure count for this error";
299 break;
300
David Zeuthena99981f2013-04-29 13:42:47 -0700301 case kErrorCodeSuccess: // success code
David Zeuthena99981f2013-04-29 13:42:47 -0700302 case kErrorCodeUmaReportedMax: // not an error code
303 case kErrorCodeOmahaRequestHTTPResponseBase: // aggregated already
304 case kErrorCodeDevModeFlag: // not an error code
305 case kErrorCodeResumedFlag: // not an error code
306 case kErrorCodeTestImageFlag: // not an error code
307 case kErrorCodeTestOmahaUrlFlag: // not an error code
308 case kErrorCodeSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800309 // These shouldn't happen. Enumerating these explicitly here so that we
310 // can let the compiler warn about new error codes that are added to
311 // action_processor.h but not added here.
312 LOG(WARNING) << "Unexpected error code for UpdateFailed";
313 break;
314
315 // Note: Not adding a default here so as to let the compiler warn us of
316 // any new enums that were added in the .h but not listed in this switch.
317 }
318}
319
Jay Srinivasan08262882012-12-28 19:29:43 -0800320bool PayloadState::ShouldBackoffDownload() {
321 if (response_.disable_payload_backoff) {
322 LOG(INFO) << "Payload backoff logic is disabled. "
323 "Can proceed with the download";
324 return false;
325 }
Chris Sosa20f005c2013-09-05 13:53:08 -0700326 if (system_state_->request_params()->use_p2p_for_downloading() &&
327 !system_state_->request_params()->p2p_url().empty()) {
328 LOG(INFO) << "Payload backoff logic is disabled because download "
329 << "will happen from local peer (via p2p).";
330 return false;
331 }
332 if (system_state_->request_params()->interactive()) {
333 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
334 return false;
335 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800336 if (response_.is_delta_payload) {
337 // If delta payloads fail, we want to fallback quickly to full payloads as
338 // they are more likely to succeed. Exponential backoffs would greatly
339 // slow down the fallback to full payloads. So we don't backoff for delta
340 // payloads.
341 LOG(INFO) << "No backoffs for delta payloads. "
342 << "Can proceed with the download";
343 return false;
344 }
345
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700346 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800347 // Backoffs are needed only for official builds. We do not want any delays
348 // or update failures due to backoffs during testing or development.
349 LOG(INFO) << "No backoffs for test/dev images. "
350 << "Can proceed with the download";
351 return false;
352 }
353
354 if (backoff_expiry_time_.is_null()) {
355 LOG(INFO) << "No backoff expiry time has been set. "
356 << "Can proceed with the download";
357 return false;
358 }
359
360 if (backoff_expiry_time_ < Time::Now()) {
361 LOG(INFO) << "The backoff expiry time ("
362 << utils::ToString(backoff_expiry_time_)
363 << ") has elapsed. Can proceed with the download";
364 return false;
365 }
366
367 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
368 << utils::ToString(backoff_expiry_time_);
369 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800370}
371
Chris Sosaaa18e162013-06-20 13:20:30 -0700372void PayloadState::Rollback() {
373 SetRollbackVersion(system_state_->request_params()->app_version());
374}
375
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800376void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700377 // Update the payload attempt number for both payload types: full and delta.
378 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Alex Deymo29b51d92013-07-09 15:26:24 -0700379
380 // Report the metric every time the value is incremented.
381 string metric = "Installer.PayloadAttemptNumber";
382 int value = GetPayloadAttemptNumber();
383
384 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
385 system_state_->metrics_lib()->SendToUMA(
386 metric,
387 value,
388 1, // min value
389 50, // max value
390 kNumDefaultUmaBuckets);
Alex Deymo820cc702013-06-28 15:43:46 -0700391}
392
393void PayloadState::IncrementFullPayloadAttemptNumber() {
394 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800395 if (response_.is_delta_payload) {
396 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
397 return;
398 }
399
Alex Deymo29b51d92013-07-09 15:26:24 -0700400 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700401 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800402 UpdateBackoffExpiryTime();
Alex Deymo29b51d92013-07-09 15:26:24 -0700403
404 // Report the metric every time the value is incremented.
405 string metric = "Installer.FullPayloadAttemptNumber";
406 int value = GetFullPayloadAttemptNumber();
407
408 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
409 system_state_->metrics_lib()->SendToUMA(
410 metric,
411 value,
412 1, // min value
413 50, // max value
414 kNumDefaultUmaBuckets);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800415}
416
417void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800418 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700419 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800420 LOG(INFO) << "Incrementing the URL index for next attempt";
421 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800422 } else {
423 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700424 << "0 as we only have " << candidate_urls_.size()
425 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800426 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700427 IncrementPayloadAttemptNumber();
428 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800429 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800430
David Zeuthencc6f9962013-04-18 11:57:24 -0700431 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700432 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700433 SetUrlSwitchCount(url_switch_count_ + 1);
434
Jay Srinivasan08262882012-12-28 19:29:43 -0800435 // Whenever we update the URL index, we should also clear the URL failure
436 // count so we can start over fresh for the new URL.
437 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800438}
439
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800440void PayloadState::IncrementFailureCount() {
441 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800442 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800443 LOG(INFO) << "Incrementing the URL failure count";
444 SetUrlFailureCount(next_url_failure_count);
445 } else {
446 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
447 << ". Trying next available URL";
448 IncrementUrlIndex();
449 }
450}
451
Jay Srinivasan08262882012-12-28 19:29:43 -0800452void PayloadState::UpdateBackoffExpiryTime() {
453 if (response_.disable_payload_backoff) {
454 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
455 SetBackoffExpiryTime(Time());
456 return;
457 }
458
Alex Deymo820cc702013-06-28 15:43:46 -0700459 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800460 SetBackoffExpiryTime(Time());
461 return;
462 }
463
464 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700465 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800466 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Deymo820cc702013-06-28 15:43:46 -0700467 int num_days = 1; // the value to be shifted.
468 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800469
470 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
471 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700472 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800473
474 // The number of days is the minimum of 2 raised to (payload_attempt_number
475 // - 1) or kMaxBackoffDays.
476 num_days = min(num_days << power, kMaxBackoffDays);
477
478 // We don't want all retries to happen exactly at the same time when
479 // retrying after backoff. So add some random minutes to fuzz.
480 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
481 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
482 TimeDelta::FromMinutes(fuzz_minutes);
483 LOG(INFO) << "Incrementing the backoff expiry time by "
484 << utils::FormatTimeDelta(next_backoff_interval);
485 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
486}
487
Jay Srinivasan19409b72013-04-12 19:23:36 -0700488void PayloadState::UpdateCurrentDownloadSource() {
489 current_download_source_ = kNumDownloadSources;
490
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700491 if (using_p2p_for_downloading_) {
492 current_download_source_ = kDownloadSourceHttpPeer;
493 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700494 string current_url = candidate_urls_[GetUrlIndex()];
Jay Srinivasan19409b72013-04-12 19:23:36 -0700495 if (StartsWithASCII(current_url, "https://", false))
496 current_download_source_ = kDownloadSourceHttpsServer;
497 else if (StartsWithASCII(current_url, "http://", false))
498 current_download_source_ = kDownloadSourceHttpServer;
499 }
500
501 LOG(INFO) << "Current download source: "
502 << utils::ToString(current_download_source_);
503}
504
505void PayloadState::UpdateBytesDownloaded(size_t count) {
506 SetCurrentBytesDownloaded(
507 current_download_source_,
508 GetCurrentBytesDownloaded(current_download_source_) + count,
509 false);
510 SetTotalBytesDownloaded(
511 current_download_source_,
512 GetTotalBytesDownloaded(current_download_source_) + count,
513 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800514
515 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700516}
517
David Zeuthen33bae492014-02-25 16:16:18 -0800518PayloadType PayloadState::CalculatePayloadType() {
519 PayloadType payload_type;
520 OmahaRequestParams* params = system_state_->request_params();
521 if (response_.is_delta_payload) {
522 payload_type = kPayloadTypeDelta;
523 } else if (params->delta_okay()) {
524 payload_type = kPayloadTypeFull;
525 } else { // Full payload, delta was not allowed by request.
526 payload_type = kPayloadTypeForcedFull;
527 }
528 return payload_type;
529}
530
531// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
532// metrics if the attempt ends abnormally, e.g. if the update_engine
533// process crashes or the device is rebooted. See
534// http://crbug.com/357676
535void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
536 int attempt_number = GetPayloadAttemptNumber();
537
538 PayloadType payload_type = CalculatePayloadType();
539
540 int64_t payload_size = response_.size;
541
542 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
543
544 ClockInterface *clock = system_state_->clock();
545 base::TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
546 base::TimeDelta duration_uptime = clock->GetMonotonicTime() -
547 attempt_start_time_monotonic_;
548
549 int64_t payload_download_speed_bps = 0;
550 int64_t usec = duration_uptime.InMicroseconds();
551 if (usec > 0) {
552 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
553 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
554 payload_download_speed_bps = static_cast<int64_t>(bps);
555 }
556
557 DownloadSource download_source = current_download_source_;
558
559 metrics::DownloadErrorCode payload_download_error_code =
560 metrics::DownloadErrorCode::kUnset;
561 ErrorCode internal_error_code = kErrorCodeSuccess;
562 metrics::AttemptResult attempt_result = utils::GetAttemptResult(code);
563
564 // Add additional detail to AttemptResult
565 switch (attempt_result) {
566 case metrics::AttemptResult::kPayloadDownloadError:
567 payload_download_error_code = utils::GetDownloadErrorCode(code);
568 break;
569
570 case metrics::AttemptResult::kInternalError:
571 internal_error_code = code;
572 break;
573
574 // Explicit fall-through for cases where we do not have additional
575 // detail. We avoid the default keyword to force people adding new
576 // AttemptResult values to visit this code and examine whether
577 // additional detail is needed.
578 case metrics::AttemptResult::kUpdateSucceeded:
579 case metrics::AttemptResult::kMetadataMalformed:
580 case metrics::AttemptResult::kOperationMalformed:
581 case metrics::AttemptResult::kOperationExecutionError:
582 case metrics::AttemptResult::kMetadataVerificationFailed:
583 case metrics::AttemptResult::kPayloadVerificationFailed:
584 case metrics::AttemptResult::kVerificationFailed:
585 case metrics::AttemptResult::kPostInstallFailed:
586 case metrics::AttemptResult::kAbnormalTermination:
587 case metrics::AttemptResult::kNumConstants:
588 case metrics::AttemptResult::kUnset:
589 break;
590 }
591
592 metrics::ReportUpdateAttemptMetrics(system_state_,
593 attempt_number,
594 payload_type,
595 duration,
596 duration_uptime,
597 payload_size,
598 payload_bytes_downloaded,
599 payload_download_speed_bps,
600 download_source,
601 attempt_result,
602 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700603 payload_download_error_code,
604 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800605}
606
607void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700608 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800609
610 // Report metrics collected from all known download sources to UMA.
611 int64_t successful_bytes_by_source[kNumDownloadSources];
612 int64_t total_bytes_by_source[kNumDownloadSources];
613 int64_t successful_bytes = 0;
614 int64_t total_bytes = 0;
615 int64_t successful_mbs = 0;
616 int64_t total_mbs = 0;
617
Jay Srinivasan19409b72013-04-12 19:23:36 -0700618 for (int i = 0; i < kNumDownloadSources; i++) {
619 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800620 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700621
David Zeuthen44848602013-06-24 13:32:14 -0700622 // Only consider this download source (and send byte counts) as
623 // having been used if we downloaded a non-trivial amount of bytes
624 // (e.g. at least 1 MiB) that contributed to the final success of
625 // the update. Otherwise we're going to end up with a lot of
626 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700627
David Zeuthen33bae492014-02-25 16:16:18 -0800628 bytes = GetCurrentBytesDownloaded(source);
629 successful_bytes_by_source[i] = bytes;
630 successful_bytes += bytes;
631 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700632 SetCurrentBytesDownloaded(source, 0, true);
633
David Zeuthen33bae492014-02-25 16:16:18 -0800634 bytes = GetTotalBytesDownloaded(source);
635 total_bytes_by_source[i] = bytes;
636 total_bytes += bytes;
637 total_mbs += bytes / kNumBytesInOneMiB;
638 SetTotalBytesDownloaded(source, 0, true);
639 }
640
641 int download_overhead_percentage = 0;
642 if (successful_bytes > 0) {
643 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
644 successful_bytes;
645 }
646
647 int url_switch_count = static_cast<int>(url_switch_count_);
648
649 int reboot_count = GetNumReboots();
650
651 SetNumReboots(0);
652
653 TimeDelta duration = GetUpdateDuration();
654 TimeDelta duration_uptime = GetUpdateDurationUptime();
655
656 prefs_->Delete(kPrefsUpdateTimestampStart);
657 prefs_->Delete(kPrefsUpdateDurationUptime);
658
659 PayloadType payload_type = CalculatePayloadType();
660
661 int64_t payload_size = response_.size;
662
663 int attempt_count = GetPayloadAttemptNumber();
664
665 int updates_abandoned_count = num_responses_seen_ - 1;
666
667 metrics::ReportSuccessfulUpdateMetrics(system_state_,
668 attempt_count,
669 updates_abandoned_count,
670 payload_type,
671 payload_size,
672 total_bytes_by_source,
673 download_overhead_percentage,
674 duration,
675 reboot_count,
676 url_switch_count);
677
678 // TODO(zeuthen): This is the old metric reporting code which is
679 // slated for removal soon. See http://crbug.com/355745 for details.
680
681 // The old metrics code is using MiB's instead of bytes to calculate
682 // the overhead which due to rounding makes the numbers slightly
683 // different.
684 download_overhead_percentage = 0;
685 if (successful_mbs > 0) {
686 download_overhead_percentage = (total_mbs - successful_mbs) * 100ULL /
687 successful_mbs;
688 }
689
690 int download_sources_used = 0;
691 for (int i = 0; i < kNumDownloadSources; i++) {
692 DownloadSource source = static_cast<DownloadSource>(i);
693 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
694 int64_t mbs;
695
696 // Only consider this download source (and send byte counts) as
697 // having been used if we downloaded a non-trivial amount of bytes
698 // (e.g. at least 1 MiB) that contributed to the final success of
699 // the update. Otherwise we're going to end up with a lot of
700 // zero-byte events in the histogram.
701
702 mbs = successful_bytes_by_source[i] / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700703 if (mbs > 0) {
David Zeuthen33bae492014-02-25 16:16:18 -0800704 metric = "Installer.SuccessfulMBsDownloadedFrom" +
705 utils::ToString(source);
David Zeuthen44848602013-06-24 13:32:14 -0700706 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
707 system_state_->metrics_lib()->SendToUMA(metric,
708 mbs,
709 0, // min
710 kMaxMiBs,
711 kNumDefaultUmaBuckets);
712 }
David Zeuthen33bae492014-02-25 16:16:18 -0800713
714 mbs = total_bytes_by_source[i] / kNumBytesInOneMiB;
715 if (mbs > 0) {
716 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
717 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
718 system_state_->metrics_lib()->SendToUMA(metric,
719 mbs,
720 0, // min
721 kMaxMiBs,
722 kNumDefaultUmaBuckets);
723 download_sources_used |= (1 << i);
724 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700725 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700726
727 metric = "Installer.DownloadSourcesUsed";
728 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
729 << " (bit flags) for metric " << metric;
730 int num_buckets = std::min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
731 system_state_->metrics_lib()->SendToUMA(metric,
732 download_sources_used,
733 0, // min
734 1 << kNumDownloadSources,
735 num_buckets);
736
David Zeuthen33bae492014-02-25 16:16:18 -0800737 metric = "Installer.DownloadOverheadPercentage";
738 LOG(INFO) << "Uploading " << download_overhead_percentage
739 << "% for metric " << metric;
740 system_state_->metrics_lib()->SendToUMA(metric,
741 download_overhead_percentage,
742 0, // min: 0% overhead
743 1000, // max: 1000% overhead
744 kNumDefaultUmaBuckets);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700745
David Zeuthen33bae492014-02-25 16:16:18 -0800746 metric = "Installer.UpdateURLSwitches";
747 LOG(INFO) << "Uploading " << url_switch_count
748 << " (count) for metric " << metric;
David Zeuthencc6f9962013-04-18 11:57:24 -0700749 system_state_->metrics_lib()->SendToUMA(
750 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800751 url_switch_count,
David Zeuthencc6f9962013-04-18 11:57:24 -0700752 0, // min value
753 100, // max value
754 kNumDefaultUmaBuckets);
David Zeuthencc6f9962013-04-18 11:57:24 -0700755
David Zeuthen33bae492014-02-25 16:16:18 -0800756 metric = "Installer.UpdateNumReboots";
757 LOG(INFO) << "Uploading reboot count of " << reboot_count << " for metric "
Chris Sosabe45bef2013-04-09 18:25:12 -0700758 << metric;
759 system_state_->metrics_lib()->SendToUMA(
760 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800761 reboot_count, // sample
762 0, // min = 0.
763 50, // max
Chris Sosabe45bef2013-04-09 18:25:12 -0700764 25); // buckets
David Zeuthen33bae492014-02-25 16:16:18 -0800765
766 metric = "Installer.UpdateDurationMinutes";
767 system_state_->metrics_lib()->SendToUMA(
768 metric,
769 static_cast<int>(duration.InMinutes()),
770 1, // min: 1 minute
771 365*24*60, // max: 1 year (approx)
772 kNumDefaultUmaBuckets);
773 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
774 << " for metric " << metric;
775
776 metric = "Installer.UpdateDurationUptimeMinutes";
777 system_state_->metrics_lib()->SendToUMA(
778 metric,
779 static_cast<int>(duration_uptime.InMinutes()),
780 1, // min: 1 minute
781 30*24*60, // max: 1 month (approx)
782 kNumDefaultUmaBuckets);
783 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
784 << " for metric " << metric;
785
786 metric = "Installer.PayloadFormat";
787 system_state_->metrics_lib()->SendEnumToUMA(
788 metric,
789 payload_type,
790 kNumPayloadTypes);
791 LOG(INFO) << "Uploading " << utils::ToString(payload_type)
792 << " for metric " << metric;
793
794 metric = "Installer.AttemptsCount.Total";
795 system_state_->metrics_lib()->SendToUMA(
796 metric,
797 attempt_count,
798 1, // min
799 50, // max
800 kNumDefaultUmaBuckets);
801 LOG(INFO) << "Uploading " << attempt_count
802 << " for metric " << metric;
803
804 metric = "Installer.UpdatesAbandonedCount";
805 LOG(INFO) << "Uploading " << updates_abandoned_count
806 << " (count) for metric " << metric;
807 system_state_->metrics_lib()->SendToUMA(
808 metric,
809 updates_abandoned_count,
810 0, // min value
811 100, // max value
812 kNumDefaultUmaBuckets);
Chris Sosabe45bef2013-04-09 18:25:12 -0700813}
814
815void PayloadState::UpdateNumReboots() {
816 // We only update the reboot count when the system has been detected to have
817 // been rebooted.
818 if (!system_state_->system_rebooted()) {
819 return;
820 }
821
822 SetNumReboots(GetNumReboots() + 1);
823}
824
825void PayloadState::SetNumReboots(uint32_t num_reboots) {
826 CHECK(prefs_);
827 num_reboots_ = num_reboots;
828 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
829 LOG(INFO) << "Number of Reboots during current update attempt = "
830 << num_reboots_;
831}
832
Jay Srinivasan08262882012-12-28 19:29:43 -0800833void PayloadState::ResetPersistedState() {
834 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700835 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800836 SetUrlIndex(0);
837 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700838 SetUrlSwitchCount(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800839 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700840 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
David Zeuthen9a017f22013-04-11 16:10:26 -0700841 SetUpdateTimestampEnd(Time()); // Set to null time
842 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700843 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700844 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700845 SetP2PNumAttempts(0);
846 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Chris Sosaaa18e162013-06-20 13:20:30 -0700847}
848
849void PayloadState::ResetRollbackVersion() {
850 CHECK(powerwash_safe_prefs_);
851 rollback_version_ = "";
852 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700853}
854
855void PayloadState::ResetDownloadSourcesOnNewUpdate() {
856 for (int i = 0; i < kNumDownloadSources; i++) {
857 DownloadSource source = static_cast<DownloadSource>(i);
858 SetCurrentBytesDownloaded(source, 0, true);
859 // Note: Not resetting the TotalBytesDownloaded as we want that metric
860 // to count the bytes downloaded across various update attempts until
861 // we have successfully applied the update.
862 }
863}
864
Chris Sosab3dcdb32013-09-04 15:22:12 -0700865int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700866 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700867 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700868 return 0;
869
870 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700871 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700872 return 0;
873
874 if (stored_value < 0) {
875 LOG(ERROR) << key << ": Invalid value (" << stored_value
876 << ") in persisted state. Defaulting to 0";
877 return 0;
878 }
879
880 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800881}
882
883string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700884 string response_sign = base::StringPrintf(
885 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800886
Jay Srinivasan53173b92013-05-17 17:13:01 -0700887 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700888 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
889 static_cast<int>(i),
890 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800891
Alex Vakulenko75039d72014-03-25 12:36:28 -0700892 response_sign += base::StringPrintf(
893 "Payload Size = %ju\n"
894 "Payload Sha256 Hash = %s\n"
895 "Metadata Size = %ju\n"
896 "Metadata Signature = %s\n"
897 "Is Delta Payload = %d\n"
898 "Max Failure Count Per Url = %d\n"
899 "Disable Payload Backoff = %d\n",
900 static_cast<uintmax_t>(response_.size),
901 response_.hash.c_str(),
902 static_cast<uintmax_t>(response_.metadata_size),
903 response_.metadata_signature.c_str(),
904 response_.is_delta_payload,
905 response_.max_failure_count_per_url,
906 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800907 return response_sign;
908}
909
910void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800911 CHECK(prefs_);
912 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800913 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
914 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
915 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800916 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800917}
918
Jay Srinivasan19409b72013-04-12 19:23:36 -0700919void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800920 CHECK(prefs_);
921 response_signature_ = response_signature;
922 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
923 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
924}
925
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800926void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700927 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800928}
929
Alex Deymo820cc702013-06-28 15:43:46 -0700930void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700931 SetFullPayloadAttemptNumber(GetPersistedValue(
932 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700933}
934
935void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800936 CHECK(prefs_);
937 payload_attempt_number_ = payload_attempt_number;
938 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
939 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
940}
941
Alex Deymo820cc702013-06-28 15:43:46 -0700942void PayloadState::SetFullPayloadAttemptNumber(
943 int full_payload_attempt_number) {
944 CHECK(prefs_);
945 full_payload_attempt_number_ = full_payload_attempt_number;
946 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
947 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
948 full_payload_attempt_number_);
949}
950
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800951void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700952 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800953}
954
955void PayloadState::SetUrlIndex(uint32_t url_index) {
956 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800957 url_index_ = url_index;
958 LOG(INFO) << "Current URL Index = " << url_index_;
959 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700960
961 // Also update the download source, which is purely dependent on the
962 // current URL index alone.
963 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800964}
965
David Zeuthencc6f9962013-04-18 11:57:24 -0700966void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700967 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700968}
969
970void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
971 CHECK(prefs_);
972 url_switch_count_ = url_switch_count;
973 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
974 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
975}
976
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800977void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700978 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800979}
980
981void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
982 CHECK(prefs_);
983 url_failure_count_ = url_failure_count;
984 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
985 << ")'s Failure Count = " << url_failure_count_;
986 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800987}
988
Jay Srinivasan08262882012-12-28 19:29:43 -0800989void PayloadState::LoadBackoffExpiryTime() {
990 CHECK(prefs_);
991 int64_t stored_value;
992 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
993 return;
994
995 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
996 return;
997
998 Time stored_time = Time::FromInternalValue(stored_value);
999 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
1000 LOG(ERROR) << "Invalid backoff expiry time ("
1001 << utils::ToString(stored_time)
1002 << ") in persisted state. Resetting.";
1003 stored_time = Time();
1004 }
1005 SetBackoffExpiryTime(stored_time);
1006}
1007
1008void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
1009 CHECK(prefs_);
1010 backoff_expiry_time_ = new_time;
1011 LOG(INFO) << "Backoff Expiry Time = "
1012 << utils::ToString(backoff_expiry_time_);
1013 prefs_->SetInt64(kPrefsBackoffExpiryTime,
1014 backoff_expiry_time_.ToInternalValue());
1015}
1016
David Zeuthen9a017f22013-04-11 16:10:26 -07001017TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001018 Time end_time = update_timestamp_end_.is_null()
1019 ? system_state_->clock()->GetWallclockTime() :
1020 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001021 return end_time - update_timestamp_start_;
1022}
1023
1024void PayloadState::LoadUpdateTimestampStart() {
1025 int64_t stored_value;
1026 Time stored_time;
1027
1028 CHECK(prefs_);
1029
David Zeuthenf413fe52013-04-22 14:04:39 -07001030 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001031
1032 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1033 // The preference missing is not unexpected - in that case, just
1034 // use the current time as start time
1035 stored_time = now;
1036 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1037 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1038 stored_time = now;
1039 } else {
1040 stored_time = Time::FromInternalValue(stored_value);
1041 }
1042
1043 // Sanity check: If the time read from disk is in the future
1044 // (modulo some slack to account for possible NTP drift
1045 // adjustments), something is fishy and we should report and
1046 // reset.
1047 TimeDelta duration_according_to_stored_time = now - stored_time;
1048 if (duration_according_to_stored_time < -kDurationSlack) {
1049 LOG(ERROR) << "The UpdateTimestampStart value ("
1050 << utils::ToString(stored_time)
1051 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001052 << utils::FormatTimeDelta(duration_according_to_stored_time)
1053 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001054 stored_time = now;
1055 }
1056
1057 SetUpdateTimestampStart(stored_time);
1058}
1059
1060void PayloadState::SetUpdateTimestampStart(const Time& value) {
1061 CHECK(prefs_);
1062 update_timestamp_start_ = value;
1063 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1064 update_timestamp_start_.ToInternalValue());
1065 LOG(INFO) << "Update Timestamp Start = "
1066 << utils::ToString(update_timestamp_start_);
1067}
1068
1069void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1070 update_timestamp_end_ = value;
1071 LOG(INFO) << "Update Timestamp End = "
1072 << utils::ToString(update_timestamp_end_);
1073}
1074
1075TimeDelta PayloadState::GetUpdateDurationUptime() {
1076 return update_duration_uptime_;
1077}
1078
1079void PayloadState::LoadUpdateDurationUptime() {
1080 int64_t stored_value;
1081 TimeDelta stored_delta;
1082
1083 CHECK(prefs_);
1084
1085 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1086 // The preference missing is not unexpected - in that case, just
1087 // we'll use zero as the delta
1088 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1089 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1090 stored_delta = TimeDelta::FromSeconds(0);
1091 } else {
1092 stored_delta = TimeDelta::FromInternalValue(stored_value);
1093 }
1094
1095 // Sanity-check: Uptime can never be greater than the wall-clock
1096 // difference (modulo some slack). If it is, report and reset
1097 // to the wall-clock difference.
1098 TimeDelta diff = GetUpdateDuration() - stored_delta;
1099 if (diff < -kDurationSlack) {
1100 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001101 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001102 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001103 << utils::FormatTimeDelta(diff)
1104 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001105 stored_delta = update_duration_current_;
1106 }
1107
1108 SetUpdateDurationUptime(stored_delta);
1109}
1110
Chris Sosabe45bef2013-04-09 18:25:12 -07001111void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001112 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001113}
1114
1115void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001116 CHECK(powerwash_safe_prefs_);
1117 string rollback_version;
1118 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1119 &rollback_version)) {
1120 SetRollbackVersion(rollback_version);
1121 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001122}
1123
1124void PayloadState::SetRollbackVersion(const string& rollback_version) {
1125 CHECK(powerwash_safe_prefs_);
1126 LOG(INFO) << "Blacklisting version "<< rollback_version;
1127 rollback_version_ = rollback_version;
1128 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001129}
1130
David Zeuthen9a017f22013-04-11 16:10:26 -07001131void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1132 const Time& timestamp,
1133 bool use_logging) {
1134 CHECK(prefs_);
1135 update_duration_uptime_ = value;
1136 update_duration_uptime_timestamp_ = timestamp;
1137 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1138 update_duration_uptime_.ToInternalValue());
1139 if (use_logging) {
1140 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001141 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001142 }
1143}
1144
1145void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001146 Time now = system_state_->clock()->GetMonotonicTime();
1147 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001148}
1149
1150void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001151 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001152 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1153 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1154 // We're frequently called so avoid logging this write
1155 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1156}
1157
Jay Srinivasan19409b72013-04-12 19:23:36 -07001158string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1159 return prefix + "-from-" + utils::ToString(source);
1160}
1161
1162void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1163 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001164 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001165}
1166
1167void PayloadState::SetCurrentBytesDownloaded(
1168 DownloadSource source,
1169 uint64_t current_bytes_downloaded,
1170 bool log) {
1171 CHECK(prefs_);
1172
1173 if (source >= kNumDownloadSources)
1174 return;
1175
1176 // Update the in-memory value.
1177 current_bytes_downloaded_[source] = current_bytes_downloaded;
1178
1179 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1180 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1181 LOG_IF(INFO, log) << "Current bytes downloaded for "
1182 << utils::ToString(source) << " = "
1183 << GetCurrentBytesDownloaded(source);
1184}
1185
1186void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1187 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001188 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001189}
1190
1191void PayloadState::SetTotalBytesDownloaded(
1192 DownloadSource source,
1193 uint64_t total_bytes_downloaded,
1194 bool log) {
1195 CHECK(prefs_);
1196
1197 if (source >= kNumDownloadSources)
1198 return;
1199
1200 // Update the in-memory value.
1201 total_bytes_downloaded_[source] = total_bytes_downloaded;
1202
1203 // Persist.
1204 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1205 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1206 LOG_IF(INFO, log) << "Total bytes downloaded for "
1207 << utils::ToString(source) << " = "
1208 << GetTotalBytesDownloaded(source);
1209}
1210
David Zeuthena573d6f2013-06-14 16:13:36 -07001211void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001212 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001213}
1214
1215void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1216 CHECK(prefs_);
1217 num_responses_seen_ = num_responses_seen;
1218 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1219 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1220}
1221
Alex Deymob33b0f02013-08-08 21:10:02 -07001222void PayloadState::ReportUpdatesAbandonedEventCountMetric() {
1223 string metric = "Installer.UpdatesAbandonedEventCount";
1224 int value = num_responses_seen_ - 1;
1225
1226 // Do not send an "abandoned" event when 0 payloads were abandoned since the
1227 // last successful update.
1228 if (value == 0)
1229 return;
1230
1231 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1232 system_state_->metrics_lib()->SendToUMA(
1233 metric,
1234 value,
1235 0, // min value
1236 100, // max value
1237 kNumDefaultUmaBuckets);
1238}
1239
Jay Srinivasan53173b92013-05-17 17:13:01 -07001240void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001241 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001242
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001243 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001244 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001245 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001246 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1247 } else {
1248 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1249 http_url_ok = true;
1250 }
1251
1252 candidate_urls_.clear();
1253 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1254 string candidate_url = response_.payload_urls[i];
1255 if (StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1256 continue;
1257 candidate_urls_.push_back(candidate_url);
1258 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1259 << ": " << candidate_url;
1260 }
1261
1262 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1263 << "out of " << response_.payload_urls.size() << " URLs supplied";
1264}
1265
David Zeuthene4c58bf2013-06-18 17:26:50 -07001266void PayloadState::CreateSystemUpdatedMarkerFile() {
1267 CHECK(prefs_);
1268 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1269 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1270}
1271
1272void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1273 // Send |time_to_reboot| as a UMA stat.
1274 string metric = "Installer.TimeToRebootMinutes";
1275 system_state_->metrics_lib()->SendToUMA(metric,
1276 time_to_reboot.InMinutes(),
1277 0, // min: 0 minute
1278 30*24*60, // max: 1 month (approx)
1279 kNumDefaultUmaBuckets);
1280 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1281 << " for metric " << metric;
David Zeuthen33bae492014-02-25 16:16:18 -08001282
1283 metric = metrics::kMetricTimeToRebootMinutes;
1284 system_state_->metrics_lib()->SendToUMA(metric,
1285 time_to_reboot.InMinutes(),
1286 0, // min: 0 minute
1287 30*24*60, // max: 1 month (approx)
1288 kNumDefaultUmaBuckets);
1289 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1290 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001291}
1292
1293void PayloadState::UpdateEngineStarted() {
Alex Deymo569c4242013-07-24 12:01:01 -07001294 // Avoid the UpdateEngineStarted actions if this is not the first time we
1295 // run the update engine since reboot.
1296 if (!system_state_->system_rebooted())
1297 return;
1298
David Zeuthene4c58bf2013-06-18 17:26:50 -07001299 // Figure out if we just booted into a new update
1300 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1301 int64_t stored_value;
1302 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1303 Time system_updated_at = Time::FromInternalValue(stored_value);
1304 if (!system_updated_at.is_null()) {
1305 TimeDelta time_to_reboot =
1306 system_state_->clock()->GetWallclockTime() - system_updated_at;
1307 if (time_to_reboot.ToInternalValue() < 0) {
1308 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1309 << utils::ToString(system_updated_at);
1310 } else {
1311 BootedIntoUpdate(time_to_reboot);
1312 }
1313 }
1314 }
1315 prefs_->Delete(kPrefsSystemUpdatedMarker);
1316 }
Alex Deymo42432912013-07-12 20:21:15 -07001317 // Check if it is needed to send metrics about a failed reboot into a new
1318 // version.
1319 ReportFailedBootIfNeeded();
1320}
1321
1322void PayloadState::ReportFailedBootIfNeeded() {
1323 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1324 // payload was marked as ready immediately before the last reboot, and we
1325 // need to check if such payload successfully rebooted or not.
1326 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001327 int64_t installed_from = 0;
1328 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001329 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1330 return;
1331 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001332 if (int(installed_from) ==
1333 utils::GetPartitionNumber(system_state_->hardware()->BootDevice())) {
Alex Deymo42432912013-07-12 20:21:15 -07001334 // A reboot was pending, but the chromebook is again in the same
1335 // BootDevice where the update was installed from.
1336 int64_t target_attempt;
1337 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1338 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1339 "TargetVersionInstalledFrom was present.";
1340 target_attempt = 1;
1341 }
1342
1343 // Report the UMA metric of the current boot failure.
1344 string metric = "Installer.RebootToNewPartitionAttempt";
1345
1346 LOG(INFO) << "Uploading " << target_attempt
1347 << " (count) for metric " << metric;
1348 system_state_->metrics_lib()->SendToUMA(
1349 metric,
1350 target_attempt,
1351 1, // min value
1352 50, // max value
1353 kNumDefaultUmaBuckets);
David Zeuthen33bae492014-02-25 16:16:18 -08001354
1355 metric = metrics::kMetricFailedUpdateCount;
1356 LOG(INFO) << "Uploading " << target_attempt
1357 << " (count) for metric " << metric;
1358 system_state_->metrics_lib()->SendToUMA(
1359 metric,
1360 target_attempt,
1361 1, // min value
1362 50, // max value
1363 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001364 } else {
1365 prefs_->Delete(kPrefsTargetVersionAttempt);
1366 prefs_->Delete(kPrefsTargetVersionUniqueId);
1367 }
1368 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1369 }
1370}
1371
1372void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1373 // Expect to boot into the new partition in the next reboot setting the
1374 // TargetVersion* flags in the Prefs.
1375 string stored_target_version_uid;
1376 string target_version_id;
1377 string target_partition;
1378 int64_t target_attempt;
1379
1380 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1381 prefs_->GetString(kPrefsTargetVersionUniqueId,
1382 &stored_target_version_uid) &&
1383 stored_target_version_uid == target_version_uid) {
1384 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1385 target_attempt = 0;
1386 } else {
1387 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1388 target_attempt = 0;
1389 }
1390 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1391
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001392 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
1393 utils::GetPartitionNumber(
Alex Deymo42432912013-07-12 20:21:15 -07001394 system_state_->hardware()->BootDevice()));
1395}
1396
1397void PayloadState::ResetUpdateStatus() {
1398 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1399 // rebooted the next boot is not flagged as failed to rebooted into the
1400 // new applied payload.
1401 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1402
1403 // Also decrement the attempt number if it exists.
1404 int64_t target_attempt;
1405 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1406 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt-1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001407}
1408
David Zeuthendcba8092013-08-06 12:16:35 -07001409int PayloadState::GetP2PNumAttempts() {
1410 return p2p_num_attempts_;
1411}
1412
1413void PayloadState::SetP2PNumAttempts(int value) {
1414 p2p_num_attempts_ = value;
1415 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1416 CHECK(prefs_);
1417 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1418}
1419
1420void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001421 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001422}
1423
1424Time PayloadState::GetP2PFirstAttemptTimestamp() {
1425 return p2p_first_attempt_timestamp_;
1426}
1427
1428void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1429 p2p_first_attempt_timestamp_ = time;
1430 LOG(INFO) << "p2p First Attempt Timestamp = "
1431 << utils::ToString(p2p_first_attempt_timestamp_);
1432 CHECK(prefs_);
1433 int64_t stored_value = time.ToInternalValue();
1434 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1435}
1436
1437void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001438 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001439 Time stored_time = Time::FromInternalValue(stored_value);
1440 SetP2PFirstAttemptTimestamp(stored_time);
1441}
1442
1443void PayloadState::P2PNewAttempt() {
1444 CHECK(prefs_);
1445 // Set timestamp, if it hasn't been set already
1446 if (p2p_first_attempt_timestamp_.is_null()) {
1447 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1448 }
1449 // Increase number of attempts
1450 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1451}
1452
1453bool PayloadState::P2PAttemptAllowed() {
1454 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1455 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1456 << " which is greater than "
1457 << kMaxP2PAttempts
1458 << " - disallowing p2p.";
1459 return false;
1460 }
1461
1462 if (!p2p_first_attempt_timestamp_.is_null()) {
1463 Time now = system_state_->clock()->GetWallclockTime();
1464 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1465 if (time_spent_attempting_p2p.InSeconds() < 0) {
1466 LOG(ERROR) << "Time spent attempting p2p is negative"
1467 << " - disallowing p2p.";
1468 return false;
1469 }
1470 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1471 LOG(INFO) << "Time spent attempting p2p is "
1472 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1473 << " which is greater than "
1474 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1475 kMaxP2PAttemptTimeSeconds))
1476 << " - disallowing p2p.";
1477 return false;
1478 }
1479 }
1480
1481 return true;
1482}
1483
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001484} // namespace chromeos_update_engine