blob: 78c048b6ed1fce561efca3ae5365b1a543549fd3 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080016
17#include "update_engine/payload_state.h"
18
Jay Srinivasan08262882012-12-28 19:29:43 -080019#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070020#include <string>
Jay Srinivasan08262882012-12-28 19:29:43 -080021
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080022#include <base/logging.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070023#include <base/strings/string_util.h>
24#include <base/strings/stringprintf.h>
Gilad Arnold1f847232014-04-07 12:07:49 -070025#include <policy/device_policy.h>
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080026
David Zeuthenf413fe52013-04-22 14:04:39 -070027#include "update_engine/clock.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070028#include "update_engine/constants.h"
Alex Deymo42432912013-07-12 20:21:15 -070029#include "update_engine/hardware_interface.h"
30#include "update_engine/install_plan.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070031#include "update_engine/omaha_request_params.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070032#include "update_engine/prefs.h"
33#include "update_engine/system_state.h"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080034#include "update_engine/utils.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080035
Jay Srinivasan08262882012-12-28 19:29:43 -080036using base::Time;
37using base::TimeDelta;
38using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080039using std::string;
40
41namespace chromeos_update_engine {
42
David Zeuthen9a017f22013-04-11 16:10:26 -070043const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
44
Jay Srinivasan08262882012-12-28 19:29:43 -080045// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070046static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080047
Jay Srinivasan08262882012-12-28 19:29:43 -080048// We want to randomize retry attempts after the backoff by +/- 6 hours.
49static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080050
Jay Srinivasan19409b72013-04-12 19:23:36 -070051PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070052 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070053 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070054 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070055 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070056 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070057 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070058 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070059 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070060 attempt_num_bytes_downloaded_(0),
61 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070062 attempt_type_(AttemptType::kUpdate) {
63 for (int i = 0; i <= kNumDownloadSources; i++)
64 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070065}
66
67bool PayloadState::Initialize(SystemState* system_state) {
68 system_state_ = system_state;
69 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070070 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080071 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080072 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070073 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080074 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080075 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070076 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080077 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070078 LoadUpdateTimestampStart();
79 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
80 // being called before it. Don't reorder.
81 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070082 for (int i = 0; i < kNumDownloadSources; i++) {
83 DownloadSource source = static_cast<DownloadSource>(i);
84 LoadCurrentBytesDownloaded(source);
85 LoadTotalBytesDownloaded(source);
86 }
Chris Sosabe45bef2013-04-09 18:25:12 -070087 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070088 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070089 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070090 LoadP2PFirstAttemptTimestamp();
91 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080092 return true;
93}
94
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080095void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -080096 // Always store the latest response.
97 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080098
Jay Srinivasan53173b92013-05-17 17:13:01 -070099 // Compute the candidate URLs first as they are used to calculate the
100 // response signature so that a change in enterprise policy for
101 // HTTP downloads being enabled or not could be honored as soon as the
102 // next update check happens.
103 ComputeCandidateUrls();
104
Jay Srinivasan08262882012-12-28 19:29:43 -0800105 // Check if the "signature" of this response (i.e. the fields we care about)
106 // has changed.
107 string new_response_signature = CalculateResponseSignature();
108 bool has_response_changed = (response_signature_ != new_response_signature);
109
110 // If the response has changed, we should persist the new signature and
111 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800112 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800113 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700114 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800115 SetResponseSignature(new_response_signature);
116 ResetPersistedState();
Alex Deymob33b0f02013-08-08 21:10:02 -0700117 ReportUpdatesAbandonedEventCountMetric();
Jay Srinivasan08262882012-12-28 19:29:43 -0800118 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800119 }
120
Jay Srinivasan08262882012-12-28 19:29:43 -0800121 // This is the earliest point at which we can validate whether the URL index
122 // we loaded from the persisted state is a valid value. If the response
123 // hasn't changed but the URL index is invalid, it's indicative of some
124 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700125 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800126 LOG(INFO) << "Resetting all payload state as the url index seems to have "
127 "been tampered with";
128 ResetPersistedState();
129 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800130 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700131
132 // Update the current download source which depends on the latest value of
133 // the response.
134 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800135}
136
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700137void PayloadState::SetUsingP2PForDownloading(bool value) {
138 using_p2p_for_downloading_ = value;
139 // Update the current download source which depends on whether we are
140 // using p2p or not.
141 UpdateCurrentDownloadSource();
142}
143
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800144void PayloadState::DownloadComplete() {
145 LOG(INFO) << "Payload downloaded successfully";
146 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700147 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800148}
149
150void PayloadState::DownloadProgress(size_t count) {
151 if (count == 0)
152 return;
153
David Zeuthen9a017f22013-04-11 16:10:26 -0700154 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700155 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700156
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800157 // We've received non-zero bytes from a recent download operation. Since our
158 // URL failure count is meant to penalize a URL only for consecutive
159 // failures, downloading bytes successfully means we should reset the failure
160 // count (as we know at least that the URL is working). In future, we can
161 // design this to be more sophisticated to check for more intelligent failure
162 // patterns, but right now, even 1 byte downloaded will mark the URL to be
163 // good unless it hits 10 (or configured number of) consecutive failures
164 // again.
165
166 if (GetUrlFailureCount() == 0)
167 return;
168
169 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
170 << " to 0 as we received " << count << " bytes successfully";
171 SetUrlFailureCount(0);
172}
173
David Zeuthenafed4a12014-04-09 15:28:44 -0700174void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700175 // Flush previous state from abnormal attempt failure, if any.
176 ReportAndClearPersistedAttemptMetrics();
177
David Zeuthenafed4a12014-04-09 15:28:44 -0700178 attempt_type_ = attempt_type;
179
David Zeuthen33bae492014-02-25 16:16:18 -0800180 ClockInterface *clock = system_state_->clock();
181 attempt_start_time_boot_ = clock->GetBootTime();
182 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800183 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700184
185 metrics::ConnectionType type;
186 NetworkConnectionType network_connection_type;
187 NetworkTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700188 ConnectionManagerInterface* connection_manager =
189 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700190 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700191 &tethering)) {
192 LOG(ERROR) << "Failed to determine connection type.";
193 type = metrics::ConnectionType::kUnknown;
194 } else {
195 type = utils::GetConnectionType(network_connection_type, tethering);
196 }
197 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700198
199 if (attempt_type == AttemptType::kUpdate)
200 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800201}
202
Chris Sosabe45bef2013-04-09 18:25:12 -0700203void PayloadState::UpdateResumed() {
204 LOG(INFO) << "Resuming an update that was previously started.";
205 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700206 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700207}
208
Jay Srinivasan19409b72013-04-12 19:23:36 -0700209void PayloadState::UpdateRestarted() {
210 LOG(INFO) << "Starting a new update";
211 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700212 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700213 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700214}
215
David Zeuthen9a017f22013-04-11 16:10:26 -0700216void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700217 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700218 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700219 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800220
David Zeuthen96197df2014-04-16 12:22:39 -0700221 switch (attempt_type_) {
222 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700223 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700224 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700225 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700226 break;
227
228 case AttemptType::kRollback:
229 metrics::ReportRollbackMetrics(system_state_,
230 metrics::RollbackResult::kSuccess);
231 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700232 }
David Zeuthena573d6f2013-06-14 16:13:36 -0700233
234 // Reset the number of responses seen since it counts from the last
235 // successful update, e.g. now.
236 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700237
238 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700239}
240
David Zeuthena99981f2013-04-29 13:42:47 -0700241void PayloadState::UpdateFailed(ErrorCode error) {
242 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800243 LOG(INFO) << "Updating payload state for error code: " << base_error
244 << " (" << utils::CodeToString(base_error) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800245
Jay Srinivasan53173b92013-05-17 17:13:01 -0700246 if (candidate_urls_.size() == 0) {
247 // This means we got this error even before we got a valid Omaha response
248 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800249 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800250 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
251 return;
252 }
253
David Zeuthen96197df2014-04-16 12:22:39 -0700254 switch (attempt_type_) {
255 case AttemptType::kUpdate:
256 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700257 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700258 break;
259
260 case AttemptType::kRollback:
261 metrics::ReportRollbackMetrics(system_state_,
262 metrics::RollbackResult::kFailed);
263 break;
264 }
David Zeuthen33bae492014-02-25 16:16:18 -0800265
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800266 switch (base_error) {
267 // Errors which are good indicators of a problem with a particular URL or
268 // the protocol used in the URL or entities in the communication channel
269 // (e.g. proxies). We should try the next available URL in the next update
270 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700271 case ErrorCode::kPayloadHashMismatchError:
272 case ErrorCode::kPayloadSizeMismatchError:
273 case ErrorCode::kDownloadPayloadVerificationError:
274 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
275 case ErrorCode::kSignedDeltaPayloadExpectedError:
276 case ErrorCode::kDownloadInvalidMetadataMagicString:
277 case ErrorCode::kDownloadSignatureMissingInManifest:
278 case ErrorCode::kDownloadManifestParseError:
279 case ErrorCode::kDownloadMetadataSignatureError:
280 case ErrorCode::kDownloadMetadataSignatureVerificationError:
281 case ErrorCode::kDownloadMetadataSignatureMismatch:
282 case ErrorCode::kDownloadOperationHashVerificationError:
283 case ErrorCode::kDownloadOperationExecutionError:
284 case ErrorCode::kDownloadOperationHashMismatch:
285 case ErrorCode::kDownloadInvalidMetadataSize:
286 case ErrorCode::kDownloadInvalidMetadataSignature:
287 case ErrorCode::kDownloadOperationHashMissingError:
288 case ErrorCode::kDownloadMetadataSignatureMissingError:
289 case ErrorCode::kPayloadMismatchedType:
290 case ErrorCode::kUnsupportedMajorPayloadVersion:
291 case ErrorCode::kUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800292 IncrementUrlIndex();
293 break;
294
295 // Errors which seem to be just transient network/communication related
296 // failures and do not indicate any inherent problem with the URL itself.
297 // So, we should keep the current URL but just increment the
298 // failure count to give it more chances. This way, while we maximize our
299 // chances of downloading from the URLs that appear earlier in the response
300 // (because download from a local server URL that appears earlier in a
301 // response is preferable than downloading from the next URL which could be
302 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700303
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700304 case ErrorCode::kError:
305 case ErrorCode::kDownloadTransferError:
306 case ErrorCode::kDownloadWriteError:
307 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700308 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800309 IncrementFailureCount();
310 break;
311
312 // Errors which are not specific to a URL and hence shouldn't result in
313 // the URL being penalized. This can happen in two cases:
314 // 1. We haven't started downloading anything: These errors don't cost us
315 // anything in terms of actual payload bytes, so we should just do the
316 // regular retries at the next update check.
317 // 2. We have successfully downloaded the payload: In this case, the
318 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800319 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800320 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700321 case ErrorCode::kOmahaRequestError:
322 case ErrorCode::kOmahaResponseHandlerError:
323 case ErrorCode::kPostinstallRunnerError:
324 case ErrorCode::kFilesystemCopierError:
325 case ErrorCode::kInstallDeviceOpenError:
326 case ErrorCode::kKernelDeviceOpenError:
327 case ErrorCode::kDownloadNewPartitionInfoError:
328 case ErrorCode::kNewRootfsVerificationError:
329 case ErrorCode::kNewKernelVerificationError:
330 case ErrorCode::kPostinstallBootedFromFirmwareB:
331 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
332 case ErrorCode::kOmahaRequestEmptyResponseError:
333 case ErrorCode::kOmahaRequestXMLParseError:
334 case ErrorCode::kOmahaResponseInvalid:
335 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
336 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
337 case ErrorCode::kOmahaUpdateDeferredForBackoff:
338 case ErrorCode::kPostinstallPowerwashError:
339 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400340 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700341 case ErrorCode::kFilesystemVerifierError:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800342 LOG(INFO) << "Not incrementing URL index or failure count for this error";
343 break;
344
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700345 case ErrorCode::kSuccess: // success code
346 case ErrorCode::kUmaReportedMax: // not an error code
347 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
348 case ErrorCode::kDevModeFlag: // not an error code
349 case ErrorCode::kResumedFlag: // not an error code
350 case ErrorCode::kTestImageFlag: // not an error code
351 case ErrorCode::kTestOmahaUrlFlag: // not an error code
352 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800353 // These shouldn't happen. Enumerating these explicitly here so that we
354 // can let the compiler warn about new error codes that are added to
355 // action_processor.h but not added here.
356 LOG(WARNING) << "Unexpected error code for UpdateFailed";
357 break;
358
359 // Note: Not adding a default here so as to let the compiler warn us of
360 // any new enums that were added in the .h but not listed in this switch.
361 }
362}
363
Jay Srinivasan08262882012-12-28 19:29:43 -0800364bool PayloadState::ShouldBackoffDownload() {
365 if (response_.disable_payload_backoff) {
366 LOG(INFO) << "Payload backoff logic is disabled. "
367 "Can proceed with the download";
368 return false;
369 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700370 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700371 LOG(INFO) << "Payload backoff logic is disabled because download "
372 << "will happen from local peer (via p2p).";
373 return false;
374 }
375 if (system_state_->request_params()->interactive()) {
376 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
377 return false;
378 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800379 if (response_.is_delta_payload) {
380 // If delta payloads fail, we want to fallback quickly to full payloads as
381 // they are more likely to succeed. Exponential backoffs would greatly
382 // slow down the fallback to full payloads. So we don't backoff for delta
383 // payloads.
384 LOG(INFO) << "No backoffs for delta payloads. "
385 << "Can proceed with the download";
386 return false;
387 }
388
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700389 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800390 // Backoffs are needed only for official builds. We do not want any delays
391 // or update failures due to backoffs during testing or development.
392 LOG(INFO) << "No backoffs for test/dev images. "
393 << "Can proceed with the download";
394 return false;
395 }
396
397 if (backoff_expiry_time_.is_null()) {
398 LOG(INFO) << "No backoff expiry time has been set. "
399 << "Can proceed with the download";
400 return false;
401 }
402
403 if (backoff_expiry_time_ < Time::Now()) {
404 LOG(INFO) << "The backoff expiry time ("
405 << utils::ToString(backoff_expiry_time_)
406 << ") has elapsed. Can proceed with the download";
407 return false;
408 }
409
410 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
411 << utils::ToString(backoff_expiry_time_);
412 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800413}
414
Chris Sosaaa18e162013-06-20 13:20:30 -0700415void PayloadState::Rollback() {
416 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700417 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700418}
419
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800420void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700421 // Update the payload attempt number for both payload types: full and delta.
422 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
Alex Deymo29b51d92013-07-09 15:26:24 -0700423
424 // Report the metric every time the value is incremented.
425 string metric = "Installer.PayloadAttemptNumber";
426 int value = GetPayloadAttemptNumber();
427
428 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
429 system_state_->metrics_lib()->SendToUMA(
430 metric,
431 value,
432 1, // min value
433 50, // max value
434 kNumDefaultUmaBuckets);
Alex Deymo820cc702013-06-28 15:43:46 -0700435}
436
437void PayloadState::IncrementFullPayloadAttemptNumber() {
438 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800439 if (response_.is_delta_payload) {
440 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
441 return;
442 }
443
Alex Deymo29b51d92013-07-09 15:26:24 -0700444 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700445 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800446 UpdateBackoffExpiryTime();
Alex Deymo29b51d92013-07-09 15:26:24 -0700447
448 // Report the metric every time the value is incremented.
449 string metric = "Installer.FullPayloadAttemptNumber";
450 int value = GetFullPayloadAttemptNumber();
451
452 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
453 system_state_->metrics_lib()->SendToUMA(
454 metric,
455 value,
456 1, // min value
457 50, // max value
458 kNumDefaultUmaBuckets);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800459}
460
461void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800462 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700463 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800464 LOG(INFO) << "Incrementing the URL index for next attempt";
465 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800466 } else {
467 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700468 << "0 as we only have " << candidate_urls_.size()
469 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800470 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700471 IncrementPayloadAttemptNumber();
472 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800473 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800474
David Zeuthencc6f9962013-04-18 11:57:24 -0700475 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700476 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700477 SetUrlSwitchCount(url_switch_count_ + 1);
478
Jay Srinivasan08262882012-12-28 19:29:43 -0800479 // Whenever we update the URL index, we should also clear the URL failure
480 // count so we can start over fresh for the new URL.
481 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800482}
483
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800484void PayloadState::IncrementFailureCount() {
485 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800486 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800487 LOG(INFO) << "Incrementing the URL failure count";
488 SetUrlFailureCount(next_url_failure_count);
489 } else {
490 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
491 << ". Trying next available URL";
492 IncrementUrlIndex();
493 }
494}
495
Jay Srinivasan08262882012-12-28 19:29:43 -0800496void PayloadState::UpdateBackoffExpiryTime() {
497 if (response_.disable_payload_backoff) {
498 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
499 SetBackoffExpiryTime(Time());
500 return;
501 }
502
Alex Deymo820cc702013-06-28 15:43:46 -0700503 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800504 SetBackoffExpiryTime(Time());
505 return;
506 }
507
508 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700509 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800510 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700511 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700512 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800513
514 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
515 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700516 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800517
518 // The number of days is the minimum of 2 raised to (payload_attempt_number
519 // - 1) or kMaxBackoffDays.
520 num_days = min(num_days << power, kMaxBackoffDays);
521
522 // We don't want all retries to happen exactly at the same time when
523 // retrying after backoff. So add some random minutes to fuzz.
524 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
525 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
526 TimeDelta::FromMinutes(fuzz_minutes);
527 LOG(INFO) << "Incrementing the backoff expiry time by "
528 << utils::FormatTimeDelta(next_backoff_interval);
529 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
530}
531
Jay Srinivasan19409b72013-04-12 19:23:36 -0700532void PayloadState::UpdateCurrentDownloadSource() {
533 current_download_source_ = kNumDownloadSources;
534
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700535 if (using_p2p_for_downloading_) {
536 current_download_source_ = kDownloadSourceHttpPeer;
537 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700538 string current_url = candidate_urls_[GetUrlIndex()];
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700539 if (base::StartsWithASCII(current_url, "https://", false))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700540 current_download_source_ = kDownloadSourceHttpsServer;
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700541 else if (base::StartsWithASCII(current_url, "http://", false))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700542 current_download_source_ = kDownloadSourceHttpServer;
543 }
544
545 LOG(INFO) << "Current download source: "
546 << utils::ToString(current_download_source_);
547}
548
549void PayloadState::UpdateBytesDownloaded(size_t count) {
550 SetCurrentBytesDownloaded(
551 current_download_source_,
552 GetCurrentBytesDownloaded(current_download_source_) + count,
553 false);
554 SetTotalBytesDownloaded(
555 current_download_source_,
556 GetTotalBytesDownloaded(current_download_source_) + count,
557 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800558
559 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700560}
561
David Zeuthen33bae492014-02-25 16:16:18 -0800562PayloadType PayloadState::CalculatePayloadType() {
563 PayloadType payload_type;
564 OmahaRequestParams* params = system_state_->request_params();
565 if (response_.is_delta_payload) {
566 payload_type = kPayloadTypeDelta;
567 } else if (params->delta_okay()) {
568 payload_type = kPayloadTypeFull;
569 } else { // Full payload, delta was not allowed by request.
570 payload_type = kPayloadTypeForcedFull;
571 }
572 return payload_type;
573}
574
575// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
576// metrics if the attempt ends abnormally, e.g. if the update_engine
577// process crashes or the device is rebooted. See
578// http://crbug.com/357676
579void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
580 int attempt_number = GetPayloadAttemptNumber();
581
582 PayloadType payload_type = CalculatePayloadType();
583
584 int64_t payload_size = response_.size;
585
586 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
587
588 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700589 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
590 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800591 attempt_start_time_monotonic_;
592
593 int64_t payload_download_speed_bps = 0;
594 int64_t usec = duration_uptime.InMicroseconds();
595 if (usec > 0) {
596 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
597 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
598 payload_download_speed_bps = static_cast<int64_t>(bps);
599 }
600
601 DownloadSource download_source = current_download_source_;
602
603 metrics::DownloadErrorCode payload_download_error_code =
604 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700605 ErrorCode internal_error_code = ErrorCode::kSuccess;
David Zeuthen33bae492014-02-25 16:16:18 -0800606 metrics::AttemptResult attempt_result = utils::GetAttemptResult(code);
607
608 // Add additional detail to AttemptResult
609 switch (attempt_result) {
610 case metrics::AttemptResult::kPayloadDownloadError:
611 payload_download_error_code = utils::GetDownloadErrorCode(code);
612 break;
613
614 case metrics::AttemptResult::kInternalError:
615 internal_error_code = code;
616 break;
617
618 // Explicit fall-through for cases where we do not have additional
619 // detail. We avoid the default keyword to force people adding new
620 // AttemptResult values to visit this code and examine whether
621 // additional detail is needed.
622 case metrics::AttemptResult::kUpdateSucceeded:
623 case metrics::AttemptResult::kMetadataMalformed:
624 case metrics::AttemptResult::kOperationMalformed:
625 case metrics::AttemptResult::kOperationExecutionError:
626 case metrics::AttemptResult::kMetadataVerificationFailed:
627 case metrics::AttemptResult::kPayloadVerificationFailed:
628 case metrics::AttemptResult::kVerificationFailed:
629 case metrics::AttemptResult::kPostInstallFailed:
630 case metrics::AttemptResult::kAbnormalTermination:
631 case metrics::AttemptResult::kNumConstants:
632 case metrics::AttemptResult::kUnset:
633 break;
634 }
635
636 metrics::ReportUpdateAttemptMetrics(system_state_,
637 attempt_number,
638 payload_type,
639 duration,
640 duration_uptime,
641 payload_size,
642 payload_bytes_downloaded,
643 payload_download_speed_bps,
644 download_source,
645 attempt_result,
646 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700647 payload_download_error_code,
648 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800649}
650
David Zeuthen4e1d1492014-04-25 13:12:27 -0700651void PayloadState::PersistAttemptMetrics() {
652 // TODO(zeuthen): For now we only persist whether an attempt was in
653 // progress and not values/metrics related to the attempt. This
654 // means that when this happens, of all the UpdateEngine.Attempt.*
655 // metrics, only UpdateEngine.Attempt.Result is reported (with the
656 // value |kAbnormalTermination|). In the future we might want to
657 // persist more data so we can report other metrics in the
658 // UpdateEngine.Attempt.* namespace when this happens.
659 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
660}
661
662void PayloadState::ClearPersistedAttemptMetrics() {
663 prefs_->Delete(kPrefsAttemptInProgress);
664}
665
666void PayloadState::ReportAndClearPersistedAttemptMetrics() {
667 bool attempt_in_progress = false;
668 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
669 return;
670 if (!attempt_in_progress)
671 return;
672
673 metrics::ReportAbnormallyTerminatedUpdateAttemptMetrics(system_state_);
674
675 ClearPersistedAttemptMetrics();
676}
677
David Zeuthen33bae492014-02-25 16:16:18 -0800678void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700679 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800680
681 // Report metrics collected from all known download sources to UMA.
682 int64_t successful_bytes_by_source[kNumDownloadSources];
683 int64_t total_bytes_by_source[kNumDownloadSources];
684 int64_t successful_bytes = 0;
685 int64_t total_bytes = 0;
686 int64_t successful_mbs = 0;
687 int64_t total_mbs = 0;
688
Jay Srinivasan19409b72013-04-12 19:23:36 -0700689 for (int i = 0; i < kNumDownloadSources; i++) {
690 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800691 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700692
David Zeuthen44848602013-06-24 13:32:14 -0700693 // Only consider this download source (and send byte counts) as
694 // having been used if we downloaded a non-trivial amount of bytes
695 // (e.g. at least 1 MiB) that contributed to the final success of
696 // the update. Otherwise we're going to end up with a lot of
697 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700698
David Zeuthen33bae492014-02-25 16:16:18 -0800699 bytes = GetCurrentBytesDownloaded(source);
700 successful_bytes_by_source[i] = bytes;
701 successful_bytes += bytes;
702 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700703 SetCurrentBytesDownloaded(source, 0, true);
704
David Zeuthen33bae492014-02-25 16:16:18 -0800705 bytes = GetTotalBytesDownloaded(source);
706 total_bytes_by_source[i] = bytes;
707 total_bytes += bytes;
708 total_mbs += bytes / kNumBytesInOneMiB;
709 SetTotalBytesDownloaded(source, 0, true);
710 }
711
712 int download_overhead_percentage = 0;
713 if (successful_bytes > 0) {
714 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
715 successful_bytes;
716 }
717
718 int url_switch_count = static_cast<int>(url_switch_count_);
719
720 int reboot_count = GetNumReboots();
721
722 SetNumReboots(0);
723
724 TimeDelta duration = GetUpdateDuration();
725 TimeDelta duration_uptime = GetUpdateDurationUptime();
726
727 prefs_->Delete(kPrefsUpdateTimestampStart);
728 prefs_->Delete(kPrefsUpdateDurationUptime);
729
730 PayloadType payload_type = CalculatePayloadType();
731
732 int64_t payload_size = response_.size;
733
734 int attempt_count = GetPayloadAttemptNumber();
735
736 int updates_abandoned_count = num_responses_seen_ - 1;
737
738 metrics::ReportSuccessfulUpdateMetrics(system_state_,
739 attempt_count,
740 updates_abandoned_count,
741 payload_type,
742 payload_size,
743 total_bytes_by_source,
744 download_overhead_percentage,
745 duration,
746 reboot_count,
747 url_switch_count);
748
749 // TODO(zeuthen): This is the old metric reporting code which is
750 // slated for removal soon. See http://crbug.com/355745 for details.
751
752 // The old metrics code is using MiB's instead of bytes to calculate
753 // the overhead which due to rounding makes the numbers slightly
754 // different.
755 download_overhead_percentage = 0;
756 if (successful_mbs > 0) {
757 download_overhead_percentage = (total_mbs - successful_mbs) * 100ULL /
758 successful_mbs;
759 }
760
761 int download_sources_used = 0;
762 for (int i = 0; i < kNumDownloadSources; i++) {
763 DownloadSource source = static_cast<DownloadSource>(i);
764 const int kMaxMiBs = 10240; // Anything above 10GB goes in the last bucket.
765 int64_t mbs;
766
767 // Only consider this download source (and send byte counts) as
768 // having been used if we downloaded a non-trivial amount of bytes
769 // (e.g. at least 1 MiB) that contributed to the final success of
770 // the update. Otherwise we're going to end up with a lot of
771 // zero-byte events in the histogram.
772
773 mbs = successful_bytes_by_source[i] / kNumBytesInOneMiB;
David Zeuthen44848602013-06-24 13:32:14 -0700774 if (mbs > 0) {
David Zeuthen33bae492014-02-25 16:16:18 -0800775 metric = "Installer.SuccessfulMBsDownloadedFrom" +
776 utils::ToString(source);
David Zeuthen44848602013-06-24 13:32:14 -0700777 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
778 system_state_->metrics_lib()->SendToUMA(metric,
779 mbs,
780 0, // min
781 kMaxMiBs,
782 kNumDefaultUmaBuckets);
783 }
David Zeuthen33bae492014-02-25 16:16:18 -0800784
785 mbs = total_bytes_by_source[i] / kNumBytesInOneMiB;
786 if (mbs > 0) {
787 metric = "Installer.TotalMBsDownloadedFrom" + utils::ToString(source);
788 LOG(INFO) << "Uploading " << mbs << " (MBs) for metric " << metric;
789 system_state_->metrics_lib()->SendToUMA(metric,
790 mbs,
791 0, // min
792 kMaxMiBs,
793 kNumDefaultUmaBuckets);
794 download_sources_used |= (1 << i);
795 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700796 }
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700797
798 metric = "Installer.DownloadSourcesUsed";
799 LOG(INFO) << "Uploading 0x" << std::hex << download_sources_used
800 << " (bit flags) for metric " << metric;
Alex Deymof329b932014-10-30 01:37:48 -0700801 int num_buckets = min(1 << kNumDownloadSources, kNumDefaultUmaBuckets);
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700802 system_state_->metrics_lib()->SendToUMA(metric,
803 download_sources_used,
804 0, // min
805 1 << kNumDownloadSources,
806 num_buckets);
807
David Zeuthen33bae492014-02-25 16:16:18 -0800808 metric = "Installer.DownloadOverheadPercentage";
809 LOG(INFO) << "Uploading " << download_overhead_percentage
810 << "% for metric " << metric;
811 system_state_->metrics_lib()->SendToUMA(metric,
812 download_overhead_percentage,
813 0, // min: 0% overhead
814 1000, // max: 1000% overhead
815 kNumDefaultUmaBuckets);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700816
David Zeuthen33bae492014-02-25 16:16:18 -0800817 metric = "Installer.UpdateURLSwitches";
818 LOG(INFO) << "Uploading " << url_switch_count
819 << " (count) for metric " << metric;
David Zeuthencc6f9962013-04-18 11:57:24 -0700820 system_state_->metrics_lib()->SendToUMA(
821 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800822 url_switch_count,
David Zeuthencc6f9962013-04-18 11:57:24 -0700823 0, // min value
824 100, // max value
825 kNumDefaultUmaBuckets);
David Zeuthencc6f9962013-04-18 11:57:24 -0700826
David Zeuthen33bae492014-02-25 16:16:18 -0800827 metric = "Installer.UpdateNumReboots";
828 LOG(INFO) << "Uploading reboot count of " << reboot_count << " for metric "
Chris Sosabe45bef2013-04-09 18:25:12 -0700829 << metric;
830 system_state_->metrics_lib()->SendToUMA(
831 metric,
David Zeuthen33bae492014-02-25 16:16:18 -0800832 reboot_count, // sample
833 0, // min = 0.
834 50, // max
Chris Sosabe45bef2013-04-09 18:25:12 -0700835 25); // buckets
David Zeuthen33bae492014-02-25 16:16:18 -0800836
837 metric = "Installer.UpdateDurationMinutes";
838 system_state_->metrics_lib()->SendToUMA(
839 metric,
840 static_cast<int>(duration.InMinutes()),
841 1, // min: 1 minute
842 365*24*60, // max: 1 year (approx)
843 kNumDefaultUmaBuckets);
844 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration)
845 << " for metric " << metric;
846
847 metric = "Installer.UpdateDurationUptimeMinutes";
848 system_state_->metrics_lib()->SendToUMA(
849 metric,
850 static_cast<int>(duration_uptime.InMinutes()),
851 1, // min: 1 minute
852 30*24*60, // max: 1 month (approx)
853 kNumDefaultUmaBuckets);
854 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(duration_uptime)
855 << " for metric " << metric;
856
857 metric = "Installer.PayloadFormat";
858 system_state_->metrics_lib()->SendEnumToUMA(
859 metric,
860 payload_type,
861 kNumPayloadTypes);
862 LOG(INFO) << "Uploading " << utils::ToString(payload_type)
863 << " for metric " << metric;
864
865 metric = "Installer.AttemptsCount.Total";
866 system_state_->metrics_lib()->SendToUMA(
867 metric,
868 attempt_count,
869 1, // min
870 50, // max
871 kNumDefaultUmaBuckets);
872 LOG(INFO) << "Uploading " << attempt_count
873 << " for metric " << metric;
874
875 metric = "Installer.UpdatesAbandonedCount";
876 LOG(INFO) << "Uploading " << updates_abandoned_count
877 << " (count) for metric " << metric;
878 system_state_->metrics_lib()->SendToUMA(
879 metric,
880 updates_abandoned_count,
881 0, // min value
882 100, // max value
883 kNumDefaultUmaBuckets);
Chris Sosabe45bef2013-04-09 18:25:12 -0700884}
885
886void PayloadState::UpdateNumReboots() {
887 // We only update the reboot count when the system has been detected to have
888 // been rebooted.
889 if (!system_state_->system_rebooted()) {
890 return;
891 }
892
893 SetNumReboots(GetNumReboots() + 1);
894}
895
896void PayloadState::SetNumReboots(uint32_t num_reboots) {
897 CHECK(prefs_);
898 num_reboots_ = num_reboots;
899 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
900 LOG(INFO) << "Number of Reboots during current update attempt = "
901 << num_reboots_;
902}
903
Jay Srinivasan08262882012-12-28 19:29:43 -0800904void PayloadState::ResetPersistedState() {
905 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700906 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800907 SetUrlIndex(0);
908 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700909 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700910 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700911 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700912 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700913 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700914 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700915 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700916 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700917 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700918 SetScatteringWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700919}
920
921void PayloadState::ResetRollbackVersion() {
922 CHECK(powerwash_safe_prefs_);
923 rollback_version_ = "";
924 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700925}
926
927void PayloadState::ResetDownloadSourcesOnNewUpdate() {
928 for (int i = 0; i < kNumDownloadSources; i++) {
929 DownloadSource source = static_cast<DownloadSource>(i);
930 SetCurrentBytesDownloaded(source, 0, true);
931 // Note: Not resetting the TotalBytesDownloaded as we want that metric
932 // to count the bytes downloaded across various update attempts until
933 // we have successfully applied the update.
934 }
935}
936
Chris Sosab3dcdb32013-09-04 15:22:12 -0700937int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700938 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700939 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700940 return 0;
941
942 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700943 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700944 return 0;
945
946 if (stored_value < 0) {
947 LOG(ERROR) << key << ": Invalid value (" << stored_value
948 << ") in persisted state. Defaulting to 0";
949 return 0;
950 }
951
952 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800953}
954
955string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700956 string response_sign = base::StringPrintf(
957 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800958
Jay Srinivasan53173b92013-05-17 17:13:01 -0700959 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700960 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
961 static_cast<int>(i),
962 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800963
Alex Vakulenko75039d72014-03-25 12:36:28 -0700964 response_sign += base::StringPrintf(
965 "Payload Size = %ju\n"
966 "Payload Sha256 Hash = %s\n"
967 "Metadata Size = %ju\n"
968 "Metadata Signature = %s\n"
969 "Is Delta Payload = %d\n"
970 "Max Failure Count Per Url = %d\n"
971 "Disable Payload Backoff = %d\n",
972 static_cast<uintmax_t>(response_.size),
973 response_.hash.c_str(),
974 static_cast<uintmax_t>(response_.metadata_size),
975 response_.metadata_signature.c_str(),
976 response_.is_delta_payload,
977 response_.max_failure_count_per_url,
978 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800979 return response_sign;
980}
981
982void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800983 CHECK(prefs_);
984 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800985 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
986 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
987 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800988 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800989}
990
Jay Srinivasan19409b72013-04-12 19:23:36 -0700991void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800992 CHECK(prefs_);
993 response_signature_ = response_signature;
994 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
995 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
996}
997
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800998void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700999 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001000}
1001
Alex Deymo820cc702013-06-28 15:43:46 -07001002void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001003 SetFullPayloadAttemptNumber(GetPersistedValue(
1004 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -07001005}
1006
1007void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001008 CHECK(prefs_);
1009 payload_attempt_number_ = payload_attempt_number;
1010 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
1011 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
1012}
1013
Alex Deymo820cc702013-06-28 15:43:46 -07001014void PayloadState::SetFullPayloadAttemptNumber(
1015 int full_payload_attempt_number) {
1016 CHECK(prefs_);
1017 full_payload_attempt_number_ = full_payload_attempt_number;
1018 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
1019 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
1020 full_payload_attempt_number_);
1021}
1022
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001023void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001024 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001025}
1026
1027void PayloadState::SetUrlIndex(uint32_t url_index) {
1028 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001029 url_index_ = url_index;
1030 LOG(INFO) << "Current URL Index = " << url_index_;
1031 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001032
1033 // Also update the download source, which is purely dependent on the
1034 // current URL index alone.
1035 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001036}
1037
Gilad Arnold519cfc72014-10-02 10:34:54 -07001038void PayloadState::LoadScatteringWaitPeriod() {
1039 SetScatteringWaitPeriod(
1040 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
1041}
1042
Alex Deymof329b932014-10-30 01:37:48 -07001043void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -07001044 CHECK(prefs_);
1045 scattering_wait_period_ = wait_period;
1046 LOG(INFO) << "Scattering Wait Period (seconds) = "
1047 << scattering_wait_period_.InSeconds();
1048 if (scattering_wait_period_.InSeconds() > 0) {
1049 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
1050 scattering_wait_period_.InSeconds());
1051 } else {
1052 prefs_->Delete(kPrefsWallClockWaitPeriod);
1053 }
1054}
1055
David Zeuthencc6f9962013-04-18 11:57:24 -07001056void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001057 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -07001058}
1059
1060void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
1061 CHECK(prefs_);
1062 url_switch_count_ = url_switch_count;
1063 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
1064 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
1065}
1066
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001067void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001068 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001069}
1070
1071void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
1072 CHECK(prefs_);
1073 url_failure_count_ = url_failure_count;
1074 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
1075 << ")'s Failure Count = " << url_failure_count_;
1076 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001077}
1078
Jay Srinivasan08262882012-12-28 19:29:43 -08001079void PayloadState::LoadBackoffExpiryTime() {
1080 CHECK(prefs_);
1081 int64_t stored_value;
1082 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
1083 return;
1084
1085 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
1086 return;
1087
1088 Time stored_time = Time::FromInternalValue(stored_value);
1089 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
1090 LOG(ERROR) << "Invalid backoff expiry time ("
1091 << utils::ToString(stored_time)
1092 << ") in persisted state. Resetting.";
1093 stored_time = Time();
1094 }
1095 SetBackoffExpiryTime(stored_time);
1096}
1097
1098void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
1099 CHECK(prefs_);
1100 backoff_expiry_time_ = new_time;
1101 LOG(INFO) << "Backoff Expiry Time = "
1102 << utils::ToString(backoff_expiry_time_);
1103 prefs_->SetInt64(kPrefsBackoffExpiryTime,
1104 backoff_expiry_time_.ToInternalValue());
1105}
1106
David Zeuthen9a017f22013-04-11 16:10:26 -07001107TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001108 Time end_time = update_timestamp_end_.is_null()
1109 ? system_state_->clock()->GetWallclockTime() :
1110 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001111 return end_time - update_timestamp_start_;
1112}
1113
1114void PayloadState::LoadUpdateTimestampStart() {
1115 int64_t stored_value;
1116 Time stored_time;
1117
1118 CHECK(prefs_);
1119
David Zeuthenf413fe52013-04-22 14:04:39 -07001120 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001121
1122 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1123 // The preference missing is not unexpected - in that case, just
1124 // use the current time as start time
1125 stored_time = now;
1126 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1127 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1128 stored_time = now;
1129 } else {
1130 stored_time = Time::FromInternalValue(stored_value);
1131 }
1132
1133 // Sanity check: If the time read from disk is in the future
1134 // (modulo some slack to account for possible NTP drift
1135 // adjustments), something is fishy and we should report and
1136 // reset.
1137 TimeDelta duration_according_to_stored_time = now - stored_time;
1138 if (duration_according_to_stored_time < -kDurationSlack) {
1139 LOG(ERROR) << "The UpdateTimestampStart value ("
1140 << utils::ToString(stored_time)
1141 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001142 << utils::FormatTimeDelta(duration_according_to_stored_time)
1143 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001144 stored_time = now;
1145 }
1146
1147 SetUpdateTimestampStart(stored_time);
1148}
1149
1150void PayloadState::SetUpdateTimestampStart(const Time& value) {
1151 CHECK(prefs_);
1152 update_timestamp_start_ = value;
1153 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1154 update_timestamp_start_.ToInternalValue());
1155 LOG(INFO) << "Update Timestamp Start = "
1156 << utils::ToString(update_timestamp_start_);
1157}
1158
1159void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1160 update_timestamp_end_ = value;
1161 LOG(INFO) << "Update Timestamp End = "
1162 << utils::ToString(update_timestamp_end_);
1163}
1164
1165TimeDelta PayloadState::GetUpdateDurationUptime() {
1166 return update_duration_uptime_;
1167}
1168
1169void PayloadState::LoadUpdateDurationUptime() {
1170 int64_t stored_value;
1171 TimeDelta stored_delta;
1172
1173 CHECK(prefs_);
1174
1175 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1176 // The preference missing is not unexpected - in that case, just
1177 // we'll use zero as the delta
1178 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1179 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1180 stored_delta = TimeDelta::FromSeconds(0);
1181 } else {
1182 stored_delta = TimeDelta::FromInternalValue(stored_value);
1183 }
1184
1185 // Sanity-check: Uptime can never be greater than the wall-clock
1186 // difference (modulo some slack). If it is, report and reset
1187 // to the wall-clock difference.
1188 TimeDelta diff = GetUpdateDuration() - stored_delta;
1189 if (diff < -kDurationSlack) {
1190 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001191 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001192 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001193 << utils::FormatTimeDelta(diff)
1194 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001195 stored_delta = update_duration_current_;
1196 }
1197
1198 SetUpdateDurationUptime(stored_delta);
1199}
1200
Chris Sosabe45bef2013-04-09 18:25:12 -07001201void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001202 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001203}
1204
1205void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001206 CHECK(powerwash_safe_prefs_);
1207 string rollback_version;
1208 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1209 &rollback_version)) {
1210 SetRollbackVersion(rollback_version);
1211 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001212}
1213
1214void PayloadState::SetRollbackVersion(const string& rollback_version) {
1215 CHECK(powerwash_safe_prefs_);
1216 LOG(INFO) << "Blacklisting version "<< rollback_version;
1217 rollback_version_ = rollback_version;
1218 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001219}
1220
David Zeuthen9a017f22013-04-11 16:10:26 -07001221void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1222 const Time& timestamp,
1223 bool use_logging) {
1224 CHECK(prefs_);
1225 update_duration_uptime_ = value;
1226 update_duration_uptime_timestamp_ = timestamp;
1227 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1228 update_duration_uptime_.ToInternalValue());
1229 if (use_logging) {
1230 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001231 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001232 }
1233}
1234
1235void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001236 Time now = system_state_->clock()->GetMonotonicTime();
1237 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001238}
1239
1240void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001241 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001242 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1243 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1244 // We're frequently called so avoid logging this write
1245 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1246}
1247
Jay Srinivasan19409b72013-04-12 19:23:36 -07001248string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1249 return prefix + "-from-" + utils::ToString(source);
1250}
1251
1252void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1253 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001254 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001255}
1256
1257void PayloadState::SetCurrentBytesDownloaded(
1258 DownloadSource source,
1259 uint64_t current_bytes_downloaded,
1260 bool log) {
1261 CHECK(prefs_);
1262
1263 if (source >= kNumDownloadSources)
1264 return;
1265
1266 // Update the in-memory value.
1267 current_bytes_downloaded_[source] = current_bytes_downloaded;
1268
1269 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1270 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1271 LOG_IF(INFO, log) << "Current bytes downloaded for "
1272 << utils::ToString(source) << " = "
1273 << GetCurrentBytesDownloaded(source);
1274}
1275
1276void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1277 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001278 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001279}
1280
1281void PayloadState::SetTotalBytesDownloaded(
1282 DownloadSource source,
1283 uint64_t total_bytes_downloaded,
1284 bool log) {
1285 CHECK(prefs_);
1286
1287 if (source >= kNumDownloadSources)
1288 return;
1289
1290 // Update the in-memory value.
1291 total_bytes_downloaded_[source] = total_bytes_downloaded;
1292
1293 // Persist.
1294 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1295 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1296 LOG_IF(INFO, log) << "Total bytes downloaded for "
1297 << utils::ToString(source) << " = "
1298 << GetTotalBytesDownloaded(source);
1299}
1300
David Zeuthena573d6f2013-06-14 16:13:36 -07001301void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001302 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001303}
1304
1305void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1306 CHECK(prefs_);
1307 num_responses_seen_ = num_responses_seen;
1308 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1309 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1310}
1311
Alex Deymob33b0f02013-08-08 21:10:02 -07001312void PayloadState::ReportUpdatesAbandonedEventCountMetric() {
1313 string metric = "Installer.UpdatesAbandonedEventCount";
1314 int value = num_responses_seen_ - 1;
1315
1316 // Do not send an "abandoned" event when 0 payloads were abandoned since the
1317 // last successful update.
1318 if (value == 0)
1319 return;
1320
1321 LOG(INFO) << "Uploading " << value << " (count) for metric " << metric;
1322 system_state_->metrics_lib()->SendToUMA(
1323 metric,
1324 value,
1325 0, // min value
1326 100, // max value
1327 kNumDefaultUmaBuckets);
1328}
1329
Jay Srinivasan53173b92013-05-17 17:13:01 -07001330void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001331 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001332
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001333 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001334 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001335 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001336 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1337 } else {
1338 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1339 http_url_ok = true;
1340 }
1341
1342 candidate_urls_.clear();
1343 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1344 string candidate_url = response_.payload_urls[i];
Alex Vakulenko6a9d3492015-06-15 12:53:22 -07001345 if (base::StartsWithASCII(candidate_url, "http://", false) && !http_url_ok)
1346 continue;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001347 candidate_urls_.push_back(candidate_url);
1348 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1349 << ": " << candidate_url;
1350 }
1351
1352 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1353 << "out of " << response_.payload_urls.size() << " URLs supplied";
1354}
1355
David Zeuthene4c58bf2013-06-18 17:26:50 -07001356void PayloadState::CreateSystemUpdatedMarkerFile() {
1357 CHECK(prefs_);
1358 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1359 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1360}
1361
1362void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1363 // Send |time_to_reboot| as a UMA stat.
1364 string metric = "Installer.TimeToRebootMinutes";
1365 system_state_->metrics_lib()->SendToUMA(metric,
1366 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001367 0, // min: 0 minute
1368 30*24*60, // max: 1 month (approx)
David Zeuthene4c58bf2013-06-18 17:26:50 -07001369 kNumDefaultUmaBuckets);
1370 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1371 << " for metric " << metric;
David Zeuthen33bae492014-02-25 16:16:18 -08001372
1373 metric = metrics::kMetricTimeToRebootMinutes;
1374 system_state_->metrics_lib()->SendToUMA(metric,
1375 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001376 0, // min: 0 minute
1377 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001378 kNumDefaultUmaBuckets);
1379 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1380 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001381}
1382
1383void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001384 // Flush previous state from abnormal attempt failure, if any.
1385 ReportAndClearPersistedAttemptMetrics();
1386
Alex Deymo569c4242013-07-24 12:01:01 -07001387 // Avoid the UpdateEngineStarted actions if this is not the first time we
1388 // run the update engine since reboot.
1389 if (!system_state_->system_rebooted())
1390 return;
1391
David Zeuthene4c58bf2013-06-18 17:26:50 -07001392 // Figure out if we just booted into a new update
1393 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1394 int64_t stored_value;
1395 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1396 Time system_updated_at = Time::FromInternalValue(stored_value);
1397 if (!system_updated_at.is_null()) {
1398 TimeDelta time_to_reboot =
1399 system_state_->clock()->GetWallclockTime() - system_updated_at;
1400 if (time_to_reboot.ToInternalValue() < 0) {
1401 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1402 << utils::ToString(system_updated_at);
1403 } else {
1404 BootedIntoUpdate(time_to_reboot);
1405 }
1406 }
1407 }
1408 prefs_->Delete(kPrefsSystemUpdatedMarker);
1409 }
Alex Deymo42432912013-07-12 20:21:15 -07001410 // Check if it is needed to send metrics about a failed reboot into a new
1411 // version.
1412 ReportFailedBootIfNeeded();
1413}
1414
1415void PayloadState::ReportFailedBootIfNeeded() {
1416 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1417 // payload was marked as ready immediately before the last reboot, and we
1418 // need to check if such payload successfully rebooted or not.
1419 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001420 int64_t installed_from = 0;
1421 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001422 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1423 return;
1424 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001425 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1426 // partition number. We are now using slot numbers (0 or 1) instead, so
1427 // the following comparison will not match if we are comparing an old
1428 // partition number against a new slot number, which is the correct outcome
1429 // since we successfully booted the new update in that case. If the boot
1430 // failed, we will read this value from the same version, so it will always
1431 // be compatible.
1432 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001433 // A reboot was pending, but the chromebook is again in the same
1434 // BootDevice where the update was installed from.
1435 int64_t target_attempt;
1436 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1437 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1438 "TargetVersionInstalledFrom was present.";
1439 target_attempt = 1;
1440 }
1441
1442 // Report the UMA metric of the current boot failure.
1443 string metric = "Installer.RebootToNewPartitionAttempt";
1444
1445 LOG(INFO) << "Uploading " << target_attempt
1446 << " (count) for metric " << metric;
1447 system_state_->metrics_lib()->SendToUMA(
1448 metric,
1449 target_attempt,
1450 1, // min value
1451 50, // max value
1452 kNumDefaultUmaBuckets);
David Zeuthen33bae492014-02-25 16:16:18 -08001453
1454 metric = metrics::kMetricFailedUpdateCount;
1455 LOG(INFO) << "Uploading " << target_attempt
1456 << " (count) for metric " << metric;
1457 system_state_->metrics_lib()->SendToUMA(
1458 metric,
1459 target_attempt,
1460 1, // min value
1461 50, // max value
1462 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001463 } else {
1464 prefs_->Delete(kPrefsTargetVersionAttempt);
1465 prefs_->Delete(kPrefsTargetVersionUniqueId);
1466 }
1467 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1468 }
1469}
1470
1471void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1472 // Expect to boot into the new partition in the next reboot setting the
1473 // TargetVersion* flags in the Prefs.
1474 string stored_target_version_uid;
1475 string target_version_id;
1476 string target_partition;
1477 int64_t target_attempt;
1478
1479 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1480 prefs_->GetString(kPrefsTargetVersionUniqueId,
1481 &stored_target_version_uid) &&
1482 stored_target_version_uid == target_version_uid) {
1483 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1484 target_attempt = 0;
1485 } else {
1486 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1487 target_attempt = 0;
1488 }
1489 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1490
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001491 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001492 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001493}
1494
1495void PayloadState::ResetUpdateStatus() {
1496 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1497 // rebooted the next boot is not flagged as failed to rebooted into the
1498 // new applied payload.
1499 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1500
1501 // Also decrement the attempt number if it exists.
1502 int64_t target_attempt;
1503 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001504 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001505}
1506
David Zeuthendcba8092013-08-06 12:16:35 -07001507int PayloadState::GetP2PNumAttempts() {
1508 return p2p_num_attempts_;
1509}
1510
1511void PayloadState::SetP2PNumAttempts(int value) {
1512 p2p_num_attempts_ = value;
1513 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1514 CHECK(prefs_);
1515 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1516}
1517
1518void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001519 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001520}
1521
1522Time PayloadState::GetP2PFirstAttemptTimestamp() {
1523 return p2p_first_attempt_timestamp_;
1524}
1525
1526void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1527 p2p_first_attempt_timestamp_ = time;
1528 LOG(INFO) << "p2p First Attempt Timestamp = "
1529 << utils::ToString(p2p_first_attempt_timestamp_);
1530 CHECK(prefs_);
1531 int64_t stored_value = time.ToInternalValue();
1532 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1533}
1534
1535void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001536 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001537 Time stored_time = Time::FromInternalValue(stored_value);
1538 SetP2PFirstAttemptTimestamp(stored_time);
1539}
1540
1541void PayloadState::P2PNewAttempt() {
1542 CHECK(prefs_);
1543 // Set timestamp, if it hasn't been set already
1544 if (p2p_first_attempt_timestamp_.is_null()) {
1545 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1546 }
1547 // Increase number of attempts
1548 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1549}
1550
1551bool PayloadState::P2PAttemptAllowed() {
1552 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1553 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1554 << " which is greater than "
1555 << kMaxP2PAttempts
1556 << " - disallowing p2p.";
1557 return false;
1558 }
1559
1560 if (!p2p_first_attempt_timestamp_.is_null()) {
1561 Time now = system_state_->clock()->GetWallclockTime();
1562 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1563 if (time_spent_attempting_p2p.InSeconds() < 0) {
1564 LOG(ERROR) << "Time spent attempting p2p is negative"
1565 << " - disallowing p2p.";
1566 return false;
1567 }
1568 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1569 LOG(INFO) << "Time spent attempting p2p is "
1570 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1571 << " which is greater than "
1572 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1573 kMaxP2PAttemptTimeSeconds))
1574 << " - disallowing p2p.";
1575 return false;
1576 }
1577 }
1578
1579 return true;
1580}
1581
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001582} // namespace chromeos_update_engine