blob: 987cf1c7a5d198d43be898627e5564af2c9a0c3b [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>
Alex Deymoa2591792015-11-17 00:39:40 -030025#include <metrics/metrics_library.h>
Gilad Arnold1f847232014-04-07 12:07:49 -070026#include <policy/device_policy.h>
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080027
Alex Deymo39910dc2015-11-09 17:04:30 -080028#include "update_engine/common/clock.h"
29#include "update_engine/common/constants.h"
Alex Deymoe88e9fe2016-02-03 16:38:00 -080030#include "update_engine/common/error_code_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080031#include "update_engine/common/hardware_interface.h"
32#include "update_engine/common/prefs.h"
33#include "update_engine/common/utils.h"
Sen Jiang255e22b2016-05-20 16:15:29 -070034#include "update_engine/connection_manager_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080035#include "update_engine/metrics_utils.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070036#include "update_engine/omaha_request_params.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080037#include "update_engine/payload_consumer/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070038#include "update_engine/system_state.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080039
Jay Srinivasan08262882012-12-28 19:29:43 -080040using base::Time;
41using base::TimeDelta;
42using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080043using std::string;
44
45namespace chromeos_update_engine {
46
David Zeuthen9a017f22013-04-11 16:10:26 -070047const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
48
Jay Srinivasan08262882012-12-28 19:29:43 -080049// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070050static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080051
Jay Srinivasan08262882012-12-28 19:29:43 -080052// We want to randomize retry attempts after the backoff by +/- 6 hours.
53static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080054
Jay Srinivasan19409b72013-04-12 19:23:36 -070055PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070056 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070057 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070058 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070059 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070060 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070061 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070062 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070063 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070064 attempt_num_bytes_downloaded_(0),
65 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Shuqian Zhao29971732016-02-05 11:29:32 -080066 attempt_error_code_(ErrorCode::kSuccess),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070067 attempt_type_(AttemptType::kUpdate) {
68 for (int i = 0; i <= kNumDownloadSources; i++)
69 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070070}
71
72bool PayloadState::Initialize(SystemState* system_state) {
73 system_state_ = system_state;
74 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070075 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080076 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080077 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070078 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080079 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080080 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070081 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080082 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070083 LoadUpdateTimestampStart();
84 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
85 // being called before it. Don't reorder.
86 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070087 for (int i = 0; i < kNumDownloadSources; i++) {
88 DownloadSource source = static_cast<DownloadSource>(i);
89 LoadCurrentBytesDownloaded(source);
90 LoadTotalBytesDownloaded(source);
91 }
Chris Sosabe45bef2013-04-09 18:25:12 -070092 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070093 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070094 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070095 LoadP2PFirstAttemptTimestamp();
96 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080097 return true;
98}
99
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800100void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800101 // Always store the latest response.
102 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800103
Jay Srinivasan53173b92013-05-17 17:13:01 -0700104 // Compute the candidate URLs first as they are used to calculate the
105 // response signature so that a change in enterprise policy for
106 // HTTP downloads being enabled or not could be honored as soon as the
107 // next update check happens.
108 ComputeCandidateUrls();
109
Jay Srinivasan08262882012-12-28 19:29:43 -0800110 // Check if the "signature" of this response (i.e. the fields we care about)
111 // has changed.
112 string new_response_signature = CalculateResponseSignature();
113 bool has_response_changed = (response_signature_ != new_response_signature);
114
115 // If the response has changed, we should persist the new signature and
116 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800117 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800118 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700119 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800120 SetResponseSignature(new_response_signature);
121 ResetPersistedState();
122 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800123 }
124
Jay Srinivasan08262882012-12-28 19:29:43 -0800125 // This is the earliest point at which we can validate whether the URL index
126 // we loaded from the persisted state is a valid value. If the response
127 // hasn't changed but the URL index is invalid, it's indicative of some
128 // tampering of the persisted state.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800129 if (payload_index_ >= candidate_urls_.size() ||
130 url_index_ >= candidate_urls_[payload_index_].size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800131 LOG(INFO) << "Resetting all payload state as the url index seems to have "
132 "been tampered with";
133 ResetPersistedState();
134 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800135 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700136
137 // Update the current download source which depends on the latest value of
138 // the response.
139 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800140}
141
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700142void PayloadState::SetUsingP2PForDownloading(bool value) {
143 using_p2p_for_downloading_ = value;
144 // Update the current download source which depends on whether we are
145 // using p2p or not.
146 UpdateCurrentDownloadSource();
147}
148
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800149void PayloadState::DownloadComplete() {
150 LOG(INFO) << "Payload downloaded successfully";
151 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700152 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800153}
154
155void PayloadState::DownloadProgress(size_t count) {
156 if (count == 0)
157 return;
158
David Zeuthen9a017f22013-04-11 16:10:26 -0700159 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700160 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700161
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800162 // We've received non-zero bytes from a recent download operation. Since our
163 // URL failure count is meant to penalize a URL only for consecutive
164 // failures, downloading bytes successfully means we should reset the failure
165 // count (as we know at least that the URL is working). In future, we can
166 // design this to be more sophisticated to check for more intelligent failure
167 // patterns, but right now, even 1 byte downloaded will mark the URL to be
168 // good unless it hits 10 (or configured number of) consecutive failures
169 // again.
170
171 if (GetUrlFailureCount() == 0)
172 return;
173
174 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
175 << " to 0 as we received " << count << " bytes successfully";
176 SetUrlFailureCount(0);
177}
178
David Zeuthenafed4a12014-04-09 15:28:44 -0700179void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700180 // Flush previous state from abnormal attempt failure, if any.
181 ReportAndClearPersistedAttemptMetrics();
182
David Zeuthenafed4a12014-04-09 15:28:44 -0700183 attempt_type_ = attempt_type;
184
David Zeuthen33bae492014-02-25 16:16:18 -0800185 ClockInterface *clock = system_state_->clock();
186 attempt_start_time_boot_ = clock->GetBootTime();
187 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800188 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700189
190 metrics::ConnectionType type;
Sen Jiang255e22b2016-05-20 16:15:29 -0700191 ConnectionType network_connection_type;
192 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700193 ConnectionManagerInterface* connection_manager =
194 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700195 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700196 &tethering)) {
197 LOG(ERROR) << "Failed to determine connection type.";
198 type = metrics::ConnectionType::kUnknown;
199 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800200 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700201 }
202 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700203
204 if (attempt_type == AttemptType::kUpdate)
205 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800206}
207
Chris Sosabe45bef2013-04-09 18:25:12 -0700208void PayloadState::UpdateResumed() {
209 LOG(INFO) << "Resuming an update that was previously started.";
210 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700211 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700212}
213
Jay Srinivasan19409b72013-04-12 19:23:36 -0700214void PayloadState::UpdateRestarted() {
215 LOG(INFO) << "Starting a new update";
216 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700217 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700218 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700219}
220
David Zeuthen9a017f22013-04-11 16:10:26 -0700221void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700222 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700223 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700224 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800225
David Zeuthen96197df2014-04-16 12:22:39 -0700226 switch (attempt_type_) {
227 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700228 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700229 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700230 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700231 break;
232
233 case AttemptType::kRollback:
234 metrics::ReportRollbackMetrics(system_state_,
235 metrics::RollbackResult::kSuccess);
236 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700237 }
Shuqian Zhao29971732016-02-05 11:29:32 -0800238 attempt_error_code_ = ErrorCode::kSuccess;
David Zeuthena573d6f2013-06-14 16:13:36 -0700239
240 // Reset the number of responses seen since it counts from the last
241 // successful update, e.g. now.
242 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700243
244 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700245}
246
David Zeuthena99981f2013-04-29 13:42:47 -0700247void PayloadState::UpdateFailed(ErrorCode error) {
248 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800249 LOG(INFO) << "Updating payload state for error code: " << base_error
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800250 << " (" << utils::ErrorCodeToString(base_error) << ")";
Shuqian Zhaocd486362016-03-04 19:07:40 -0800251 attempt_error_code_ = base_error;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800252
Jay Srinivasan53173b92013-05-17 17:13:01 -0700253 if (candidate_urls_.size() == 0) {
254 // This means we got this error even before we got a valid Omaha response
255 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800256 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800257 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
258 return;
259 }
260
David Zeuthen96197df2014-04-16 12:22:39 -0700261 switch (attempt_type_) {
262 case AttemptType::kUpdate:
263 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700264 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700265 break;
266
267 case AttemptType::kRollback:
268 metrics::ReportRollbackMetrics(system_state_,
269 metrics::RollbackResult::kFailed);
270 break;
271 }
David Zeuthen33bae492014-02-25 16:16:18 -0800272
Shuqian Zhao29971732016-02-05 11:29:32 -0800273
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800274 switch (base_error) {
275 // Errors which are good indicators of a problem with a particular URL or
276 // the protocol used in the URL or entities in the communication channel
277 // (e.g. proxies). We should try the next available URL in the next update
278 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700279 case ErrorCode::kPayloadHashMismatchError:
280 case ErrorCode::kPayloadSizeMismatchError:
281 case ErrorCode::kDownloadPayloadVerificationError:
282 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
283 case ErrorCode::kSignedDeltaPayloadExpectedError:
284 case ErrorCode::kDownloadInvalidMetadataMagicString:
285 case ErrorCode::kDownloadSignatureMissingInManifest:
286 case ErrorCode::kDownloadManifestParseError:
287 case ErrorCode::kDownloadMetadataSignatureError:
288 case ErrorCode::kDownloadMetadataSignatureVerificationError:
289 case ErrorCode::kDownloadMetadataSignatureMismatch:
290 case ErrorCode::kDownloadOperationHashVerificationError:
291 case ErrorCode::kDownloadOperationExecutionError:
292 case ErrorCode::kDownloadOperationHashMismatch:
293 case ErrorCode::kDownloadInvalidMetadataSize:
294 case ErrorCode::kDownloadInvalidMetadataSignature:
295 case ErrorCode::kDownloadOperationHashMissingError:
296 case ErrorCode::kDownloadMetadataSignatureMissingError:
297 case ErrorCode::kPayloadMismatchedType:
298 case ErrorCode::kUnsupportedMajorPayloadVersion:
299 case ErrorCode::kUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800300 IncrementUrlIndex();
301 break;
302
303 // Errors which seem to be just transient network/communication related
304 // failures and do not indicate any inherent problem with the URL itself.
305 // So, we should keep the current URL but just increment the
306 // failure count to give it more chances. This way, while we maximize our
307 // chances of downloading from the URLs that appear earlier in the response
308 // (because download from a local server URL that appears earlier in a
309 // response is preferable than downloading from the next URL which could be
310 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700311
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700312 case ErrorCode::kError:
313 case ErrorCode::kDownloadTransferError:
314 case ErrorCode::kDownloadWriteError:
315 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700316 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800317 IncrementFailureCount();
318 break;
319
320 // Errors which are not specific to a URL and hence shouldn't result in
321 // the URL being penalized. This can happen in two cases:
322 // 1. We haven't started downloading anything: These errors don't cost us
323 // anything in terms of actual payload bytes, so we should just do the
324 // regular retries at the next update check.
325 // 2. We have successfully downloaded the payload: In this case, the
326 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800327 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800328 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700329 case ErrorCode::kOmahaRequestError:
330 case ErrorCode::kOmahaResponseHandlerError:
331 case ErrorCode::kPostinstallRunnerError:
332 case ErrorCode::kFilesystemCopierError:
333 case ErrorCode::kInstallDeviceOpenError:
334 case ErrorCode::kKernelDeviceOpenError:
335 case ErrorCode::kDownloadNewPartitionInfoError:
336 case ErrorCode::kNewRootfsVerificationError:
337 case ErrorCode::kNewKernelVerificationError:
338 case ErrorCode::kPostinstallBootedFromFirmwareB:
339 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
340 case ErrorCode::kOmahaRequestEmptyResponseError:
341 case ErrorCode::kOmahaRequestXMLParseError:
342 case ErrorCode::kOmahaResponseInvalid:
343 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
344 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700345 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700346 case ErrorCode::kOmahaUpdateDeferredForBackoff:
347 case ErrorCode::kPostinstallPowerwashError:
348 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400349 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700350 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800351 case ErrorCode::kUserCanceled:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800352 LOG(INFO) << "Not incrementing URL index or failure count for this error";
353 break;
354
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700355 case ErrorCode::kSuccess: // success code
356 case ErrorCode::kUmaReportedMax: // not an error code
357 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
358 case ErrorCode::kDevModeFlag: // not an error code
359 case ErrorCode::kResumedFlag: // not an error code
360 case ErrorCode::kTestImageFlag: // not an error code
361 case ErrorCode::kTestOmahaUrlFlag: // not an error code
362 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800363 // These shouldn't happen. Enumerating these explicitly here so that we
364 // can let the compiler warn about new error codes that are added to
365 // action_processor.h but not added here.
366 LOG(WARNING) << "Unexpected error code for UpdateFailed";
367 break;
368
369 // Note: Not adding a default here so as to let the compiler warn us of
370 // any new enums that were added in the .h but not listed in this switch.
371 }
372}
373
Jay Srinivasan08262882012-12-28 19:29:43 -0800374bool PayloadState::ShouldBackoffDownload() {
375 if (response_.disable_payload_backoff) {
376 LOG(INFO) << "Payload backoff logic is disabled. "
377 "Can proceed with the download";
378 return false;
379 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700380 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700381 LOG(INFO) << "Payload backoff logic is disabled because download "
382 << "will happen from local peer (via p2p).";
383 return false;
384 }
385 if (system_state_->request_params()->interactive()) {
386 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
387 return false;
388 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700389 for (const auto& package : response_.packages) {
390 if (package.is_delta) {
391 // If delta payloads fail, we want to fallback quickly to full payloads as
392 // they are more likely to succeed. Exponential backoffs would greatly
393 // slow down the fallback to full payloads. So we don't backoff for delta
394 // payloads.
395 LOG(INFO) << "No backoffs for delta payloads. "
396 << "Can proceed with the download";
397 return false;
398 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800399 }
400
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700401 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800402 // Backoffs are needed only for official builds. We do not want any delays
403 // or update failures due to backoffs during testing or development.
404 LOG(INFO) << "No backoffs for test/dev images. "
405 << "Can proceed with the download";
406 return false;
407 }
408
409 if (backoff_expiry_time_.is_null()) {
410 LOG(INFO) << "No backoff expiry time has been set. "
411 << "Can proceed with the download";
412 return false;
413 }
414
415 if (backoff_expiry_time_ < Time::Now()) {
416 LOG(INFO) << "The backoff expiry time ("
417 << utils::ToString(backoff_expiry_time_)
418 << ") has elapsed. Can proceed with the download";
419 return false;
420 }
421
422 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
423 << utils::ToString(backoff_expiry_time_);
424 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800425}
426
Chris Sosaaa18e162013-06-20 13:20:30 -0700427void PayloadState::Rollback() {
428 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700429 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700430}
431
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800432void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700433 // Update the payload attempt number for both payload types: full and delta.
434 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
435}
436
437void PayloadState::IncrementFullPayloadAttemptNumber() {
438 // Update the payload attempt number for full payloads and the backoff time.
Sen Jiangcdd52062017-05-18 15:33:10 -0700439 if (response_.packages[payload_index_].is_delta) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800440 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();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800447}
448
449void PayloadState::IncrementUrlIndex() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800450 size_t next_url_index = url_index_ + 1;
451 size_t max_url_size = 0;
452 for (const auto& urls : candidate_urls_)
453 max_url_size = std::max(max_url_size, urls.size());
454 if (next_url_index < max_url_size) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800455 LOG(INFO) << "Incrementing the URL index for next attempt";
456 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800457 } else {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800458 LOG(INFO) << "Resetting the current URL index (" << url_index_ << ") to "
459 << "0 as we only have " << max_url_size << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800460 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700461 IncrementPayloadAttemptNumber();
462 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800463 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800464
David Zeuthencc6f9962013-04-18 11:57:24 -0700465 // If we have multiple URLs, record that we just switched to another one
Sen Jiang0affc2c2017-02-10 15:55:05 -0800466 if (max_url_size > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700467 SetUrlSwitchCount(url_switch_count_ + 1);
468
Jay Srinivasan08262882012-12-28 19:29:43 -0800469 // Whenever we update the URL index, we should also clear the URL failure
470 // count so we can start over fresh for the new URL.
471 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800472}
473
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800474void PayloadState::IncrementFailureCount() {
475 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800476 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800477 LOG(INFO) << "Incrementing the URL failure count";
478 SetUrlFailureCount(next_url_failure_count);
479 } else {
480 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
481 << ". Trying next available URL";
482 IncrementUrlIndex();
483 }
484}
485
Jay Srinivasan08262882012-12-28 19:29:43 -0800486void PayloadState::UpdateBackoffExpiryTime() {
487 if (response_.disable_payload_backoff) {
488 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
489 SetBackoffExpiryTime(Time());
490 return;
491 }
492
Alex Deymo820cc702013-06-28 15:43:46 -0700493 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800494 SetBackoffExpiryTime(Time());
495 return;
496 }
497
498 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700499 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800500 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700501 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700502 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800503
504 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
505 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700506 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800507
508 // The number of days is the minimum of 2 raised to (payload_attempt_number
509 // - 1) or kMaxBackoffDays.
510 num_days = min(num_days << power, kMaxBackoffDays);
511
512 // We don't want all retries to happen exactly at the same time when
513 // retrying after backoff. So add some random minutes to fuzz.
514 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
515 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
516 TimeDelta::FromMinutes(fuzz_minutes);
517 LOG(INFO) << "Incrementing the backoff expiry time by "
518 << utils::FormatTimeDelta(next_backoff_interval);
519 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
520}
521
Jay Srinivasan19409b72013-04-12 19:23:36 -0700522void PayloadState::UpdateCurrentDownloadSource() {
523 current_download_source_ = kNumDownloadSources;
524
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700525 if (using_p2p_for_downloading_) {
526 current_download_source_ = kDownloadSourceHttpPeer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800527 } else if (payload_index_ < candidate_urls_.size() &&
528 candidate_urls_[payload_index_].size() != 0) {
529 const string& current_url = candidate_urls_[payload_index_][GetUrlIndex()];
530 if (base::StartsWith(
531 current_url, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700532 current_download_source_ = kDownloadSourceHttpsServer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800533 } else if (base::StartsWith(current_url,
534 "http://",
Alex Vakulenko0103c362016-01-20 07:56:15 -0800535 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700536 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800537 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700538 }
539
540 LOG(INFO) << "Current download source: "
541 << utils::ToString(current_download_source_);
542}
543
544void PayloadState::UpdateBytesDownloaded(size_t count) {
545 SetCurrentBytesDownloaded(
546 current_download_source_,
547 GetCurrentBytesDownloaded(current_download_source_) + count,
548 false);
549 SetTotalBytesDownloaded(
550 current_download_source_,
551 GetTotalBytesDownloaded(current_download_source_) + count,
552 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800553
554 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700555}
556
David Zeuthen33bae492014-02-25 16:16:18 -0800557PayloadType PayloadState::CalculatePayloadType() {
Sen Jiangcdd52062017-05-18 15:33:10 -0700558 for (const auto& package : response_.packages) {
559 if (package.is_delta) {
560 return kPayloadTypeDelta;
561 }
David Zeuthen33bae492014-02-25 16:16:18 -0800562 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700563 OmahaRequestParams* params = system_state_->request_params();
564 if (params->delta_okay()) {
565 return kPayloadTypeFull;
566 }
567 // Full payload, delta was not allowed by request.
568 return kPayloadTypeForcedFull;
David Zeuthen33bae492014-02-25 16:16:18 -0800569}
570
571// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
572// metrics if the attempt ends abnormally, e.g. if the update_engine
573// process crashes or the device is rebooted. See
574// http://crbug.com/357676
575void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
576 int attempt_number = GetPayloadAttemptNumber();
577
578 PayloadType payload_type = CalculatePayloadType();
579
Sen Jiang0affc2c2017-02-10 15:55:05 -0800580 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800581
582 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
583
584 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700585 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
586 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800587 attempt_start_time_monotonic_;
588
589 int64_t payload_download_speed_bps = 0;
590 int64_t usec = duration_uptime.InMicroseconds();
591 if (usec > 0) {
592 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
593 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
594 payload_download_speed_bps = static_cast<int64_t>(bps);
595 }
596
597 DownloadSource download_source = current_download_source_;
598
599 metrics::DownloadErrorCode payload_download_error_code =
600 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700601 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800602 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800603
604 // Add additional detail to AttemptResult
605 switch (attempt_result) {
606 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800607 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800608 break;
609
610 case metrics::AttemptResult::kInternalError:
611 internal_error_code = code;
612 break;
613
614 // Explicit fall-through for cases where we do not have additional
615 // detail. We avoid the default keyword to force people adding new
616 // AttemptResult values to visit this code and examine whether
617 // additional detail is needed.
618 case metrics::AttemptResult::kUpdateSucceeded:
619 case metrics::AttemptResult::kMetadataMalformed:
620 case metrics::AttemptResult::kOperationMalformed:
621 case metrics::AttemptResult::kOperationExecutionError:
622 case metrics::AttemptResult::kMetadataVerificationFailed:
623 case metrics::AttemptResult::kPayloadVerificationFailed:
624 case metrics::AttemptResult::kVerificationFailed:
625 case metrics::AttemptResult::kPostInstallFailed:
626 case metrics::AttemptResult::kAbnormalTermination:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800627 case metrics::AttemptResult::kUpdateCanceled:
David Zeuthen33bae492014-02-25 16:16:18 -0800628 case metrics::AttemptResult::kNumConstants:
629 case metrics::AttemptResult::kUnset:
630 break;
631 }
632
633 metrics::ReportUpdateAttemptMetrics(system_state_,
634 attempt_number,
635 payload_type,
636 duration,
637 duration_uptime,
638 payload_size,
639 payload_bytes_downloaded,
640 payload_download_speed_bps,
641 download_source,
642 attempt_result,
643 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700644 payload_download_error_code,
645 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800646}
647
David Zeuthen4e1d1492014-04-25 13:12:27 -0700648void PayloadState::PersistAttemptMetrics() {
649 // TODO(zeuthen): For now we only persist whether an attempt was in
650 // progress and not values/metrics related to the attempt. This
651 // means that when this happens, of all the UpdateEngine.Attempt.*
652 // metrics, only UpdateEngine.Attempt.Result is reported (with the
653 // value |kAbnormalTermination|). In the future we might want to
654 // persist more data so we can report other metrics in the
655 // UpdateEngine.Attempt.* namespace when this happens.
656 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
657}
658
659void PayloadState::ClearPersistedAttemptMetrics() {
660 prefs_->Delete(kPrefsAttemptInProgress);
661}
662
663void PayloadState::ReportAndClearPersistedAttemptMetrics() {
664 bool attempt_in_progress = false;
665 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
666 return;
667 if (!attempt_in_progress)
668 return;
669
670 metrics::ReportAbnormallyTerminatedUpdateAttemptMetrics(system_state_);
671
672 ClearPersistedAttemptMetrics();
673}
674
David Zeuthen33bae492014-02-25 16:16:18 -0800675void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700676 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800677
678 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800679 int64_t total_bytes_by_source[kNumDownloadSources];
680 int64_t successful_bytes = 0;
681 int64_t total_bytes = 0;
682 int64_t successful_mbs = 0;
683 int64_t total_mbs = 0;
684
Jay Srinivasan19409b72013-04-12 19:23:36 -0700685 for (int i = 0; i < kNumDownloadSources; i++) {
686 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800687 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700688
David Zeuthen44848602013-06-24 13:32:14 -0700689 // Only consider this download source (and send byte counts) as
690 // having been used if we downloaded a non-trivial amount of bytes
691 // (e.g. at least 1 MiB) that contributed to the final success of
692 // the update. Otherwise we're going to end up with a lot of
693 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700694
David Zeuthen33bae492014-02-25 16:16:18 -0800695 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800696 successful_bytes += bytes;
697 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700698 SetCurrentBytesDownloaded(source, 0, true);
699
David Zeuthen33bae492014-02-25 16:16:18 -0800700 bytes = GetTotalBytesDownloaded(source);
701 total_bytes_by_source[i] = bytes;
702 total_bytes += bytes;
703 total_mbs += bytes / kNumBytesInOneMiB;
704 SetTotalBytesDownloaded(source, 0, true);
705 }
706
707 int download_overhead_percentage = 0;
708 if (successful_bytes > 0) {
709 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
710 successful_bytes;
711 }
712
713 int url_switch_count = static_cast<int>(url_switch_count_);
714
715 int reboot_count = GetNumReboots();
716
717 SetNumReboots(0);
718
719 TimeDelta duration = GetUpdateDuration();
David Zeuthen33bae492014-02-25 16:16:18 -0800720
721 prefs_->Delete(kPrefsUpdateTimestampStart);
722 prefs_->Delete(kPrefsUpdateDurationUptime);
723
724 PayloadType payload_type = CalculatePayloadType();
725
Sen Jiang0affc2c2017-02-10 15:55:05 -0800726 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800727
728 int attempt_count = GetPayloadAttemptNumber();
729
730 int updates_abandoned_count = num_responses_seen_ - 1;
731
732 metrics::ReportSuccessfulUpdateMetrics(system_state_,
733 attempt_count,
734 updates_abandoned_count,
735 payload_type,
736 payload_size,
737 total_bytes_by_source,
738 download_overhead_percentage,
739 duration,
740 reboot_count,
741 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700742}
743
744void PayloadState::UpdateNumReboots() {
745 // We only update the reboot count when the system has been detected to have
746 // been rebooted.
747 if (!system_state_->system_rebooted()) {
748 return;
749 }
750
751 SetNumReboots(GetNumReboots() + 1);
752}
753
754void PayloadState::SetNumReboots(uint32_t num_reboots) {
755 CHECK(prefs_);
756 num_reboots_ = num_reboots;
757 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
758 LOG(INFO) << "Number of Reboots during current update attempt = "
759 << num_reboots_;
760}
761
Jay Srinivasan08262882012-12-28 19:29:43 -0800762void PayloadState::ResetPersistedState() {
763 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700764 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800765 SetUrlIndex(0);
766 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700767 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700768 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700769 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700770 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700771 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700772 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700773 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700774 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700775 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700776 SetScatteringWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700777}
778
779void PayloadState::ResetRollbackVersion() {
780 CHECK(powerwash_safe_prefs_);
781 rollback_version_ = "";
782 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700783}
784
785void PayloadState::ResetDownloadSourcesOnNewUpdate() {
786 for (int i = 0; i < kNumDownloadSources; i++) {
787 DownloadSource source = static_cast<DownloadSource>(i);
788 SetCurrentBytesDownloaded(source, 0, true);
789 // Note: Not resetting the TotalBytesDownloaded as we want that metric
790 // to count the bytes downloaded across various update attempts until
791 // we have successfully applied the update.
792 }
793}
794
Chris Sosab3dcdb32013-09-04 15:22:12 -0700795int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700796 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700797 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700798 return 0;
799
800 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700801 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700802 return 0;
803
804 if (stored_value < 0) {
805 LOG(ERROR) << key << ": Invalid value (" << stored_value
806 << ") in persisted state. Defaulting to 0";
807 return 0;
808 }
809
810 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800811}
812
813string PayloadState::CalculateResponseSignature() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800814 string response_sign;
815 for (size_t i = 0; i < response_.packages.size(); i++) {
816 const auto& package = response_.packages[i];
817 response_sign += base::StringPrintf(
818 "Payload %zu:\n"
819 " Size = %ju\n"
820 " Sha256 Hash = %s\n"
821 " Metadata Size = %ju\n"
822 " Metadata Signature = %s\n"
Sen Jiangcdd52062017-05-18 15:33:10 -0700823 " Is Delta = %d\n"
Sen Jiang0affc2c2017-02-10 15:55:05 -0800824 " NumURLs = %zu\n",
825 i,
826 static_cast<uintmax_t>(package.size),
827 package.hash.c_str(),
828 static_cast<uintmax_t>(package.metadata_size),
829 package.metadata_signature.c_str(),
Sen Jiangcdd52062017-05-18 15:33:10 -0700830 package.is_delta,
Sen Jiang0affc2c2017-02-10 15:55:05 -0800831 candidate_urls_[i].size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800832
Sen Jiang0affc2c2017-02-10 15:55:05 -0800833 for (size_t j = 0; j < candidate_urls_[i].size(); j++)
834 response_sign += base::StringPrintf(
835 " Candidate Url%zu = %s\n", j, candidate_urls_[i][j].c_str());
836 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800837
Alex Vakulenko75039d72014-03-25 12:36:28 -0700838 response_sign += base::StringPrintf(
Alex Vakulenko75039d72014-03-25 12:36:28 -0700839 "Max Failure Count Per Url = %d\n"
840 "Disable Payload Backoff = %d\n",
Alex Vakulenko75039d72014-03-25 12:36:28 -0700841 response_.max_failure_count_per_url,
842 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800843 return response_sign;
844}
845
846void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800847 CHECK(prefs_);
848 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800849 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
850 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
851 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800852 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800853}
854
Jay Srinivasan19409b72013-04-12 19:23:36 -0700855void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800856 CHECK(prefs_);
857 response_signature_ = response_signature;
858 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
859 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
860}
861
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800862void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700863 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800864}
865
Alex Deymo820cc702013-06-28 15:43:46 -0700866void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700867 SetFullPayloadAttemptNumber(GetPersistedValue(
868 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700869}
870
871void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800872 CHECK(prefs_);
873 payload_attempt_number_ = payload_attempt_number;
874 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
875 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
876}
877
Alex Deymo820cc702013-06-28 15:43:46 -0700878void PayloadState::SetFullPayloadAttemptNumber(
879 int full_payload_attempt_number) {
880 CHECK(prefs_);
881 full_payload_attempt_number_ = full_payload_attempt_number;
882 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
883 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
884 full_payload_attempt_number_);
885}
886
Sen Jiang5ae865b2017-04-18 14:24:40 -0700887void PayloadState::SetPayloadIndex(size_t payload_index) {
888 CHECK(prefs_);
889 payload_index_ = payload_index;
890 LOG(INFO) << "Payload Index = " << payload_index_;
891 prefs_->SetInt64(kPrefsUpdateStatePayloadIndex, payload_index_);
892}
893
894bool PayloadState::NextPayload() {
895 if (payload_index_ + 1 >= candidate_urls_.size())
896 return false;
897 SetPayloadIndex(payload_index_ + 1);
898 return true;
899}
900
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800901void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700902 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800903}
904
905void PayloadState::SetUrlIndex(uint32_t url_index) {
906 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800907 url_index_ = url_index;
908 LOG(INFO) << "Current URL Index = " << url_index_;
909 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700910
911 // Also update the download source, which is purely dependent on the
912 // current URL index alone.
913 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800914}
915
Gilad Arnold519cfc72014-10-02 10:34:54 -0700916void PayloadState::LoadScatteringWaitPeriod() {
917 SetScatteringWaitPeriod(
918 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
919}
920
Alex Deymof329b932014-10-30 01:37:48 -0700921void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700922 CHECK(prefs_);
923 scattering_wait_period_ = wait_period;
924 LOG(INFO) << "Scattering Wait Period (seconds) = "
925 << scattering_wait_period_.InSeconds();
926 if (scattering_wait_period_.InSeconds() > 0) {
927 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
928 scattering_wait_period_.InSeconds());
929 } else {
930 prefs_->Delete(kPrefsWallClockWaitPeriod);
931 }
932}
933
David Zeuthencc6f9962013-04-18 11:57:24 -0700934void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700935 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700936}
937
938void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
939 CHECK(prefs_);
940 url_switch_count_ = url_switch_count;
941 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
942 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
943}
944
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800945void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700946 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800947}
948
949void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
950 CHECK(prefs_);
951 url_failure_count_ = url_failure_count;
952 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
953 << ")'s Failure Count = " << url_failure_count_;
954 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800955}
956
Jay Srinivasan08262882012-12-28 19:29:43 -0800957void PayloadState::LoadBackoffExpiryTime() {
958 CHECK(prefs_);
959 int64_t stored_value;
960 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
961 return;
962
963 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
964 return;
965
966 Time stored_time = Time::FromInternalValue(stored_value);
967 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
968 LOG(ERROR) << "Invalid backoff expiry time ("
969 << utils::ToString(stored_time)
970 << ") in persisted state. Resetting.";
971 stored_time = Time();
972 }
973 SetBackoffExpiryTime(stored_time);
974}
975
976void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
977 CHECK(prefs_);
978 backoff_expiry_time_ = new_time;
979 LOG(INFO) << "Backoff Expiry Time = "
980 << utils::ToString(backoff_expiry_time_);
981 prefs_->SetInt64(kPrefsBackoffExpiryTime,
982 backoff_expiry_time_.ToInternalValue());
983}
984
David Zeuthen9a017f22013-04-11 16:10:26 -0700985TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700986 Time end_time = update_timestamp_end_.is_null()
987 ? system_state_->clock()->GetWallclockTime() :
988 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700989 return end_time - update_timestamp_start_;
990}
991
992void PayloadState::LoadUpdateTimestampStart() {
993 int64_t stored_value;
994 Time stored_time;
995
996 CHECK(prefs_);
997
David Zeuthenf413fe52013-04-22 14:04:39 -0700998 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700999
1000 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1001 // The preference missing is not unexpected - in that case, just
1002 // use the current time as start time
1003 stored_time = now;
1004 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1005 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1006 stored_time = now;
1007 } else {
1008 stored_time = Time::FromInternalValue(stored_value);
1009 }
1010
1011 // Sanity check: If the time read from disk is in the future
1012 // (modulo some slack to account for possible NTP drift
1013 // adjustments), something is fishy and we should report and
1014 // reset.
1015 TimeDelta duration_according_to_stored_time = now - stored_time;
1016 if (duration_according_to_stored_time < -kDurationSlack) {
1017 LOG(ERROR) << "The UpdateTimestampStart value ("
1018 << utils::ToString(stored_time)
1019 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001020 << utils::FormatTimeDelta(duration_according_to_stored_time)
1021 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001022 stored_time = now;
1023 }
1024
1025 SetUpdateTimestampStart(stored_time);
1026}
1027
1028void PayloadState::SetUpdateTimestampStart(const Time& value) {
1029 CHECK(prefs_);
1030 update_timestamp_start_ = value;
1031 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1032 update_timestamp_start_.ToInternalValue());
1033 LOG(INFO) << "Update Timestamp Start = "
1034 << utils::ToString(update_timestamp_start_);
1035}
1036
1037void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1038 update_timestamp_end_ = value;
1039 LOG(INFO) << "Update Timestamp End = "
1040 << utils::ToString(update_timestamp_end_);
1041}
1042
1043TimeDelta PayloadState::GetUpdateDurationUptime() {
1044 return update_duration_uptime_;
1045}
1046
1047void PayloadState::LoadUpdateDurationUptime() {
1048 int64_t stored_value;
1049 TimeDelta stored_delta;
1050
1051 CHECK(prefs_);
1052
1053 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1054 // The preference missing is not unexpected - in that case, just
1055 // we'll use zero as the delta
1056 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1057 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1058 stored_delta = TimeDelta::FromSeconds(0);
1059 } else {
1060 stored_delta = TimeDelta::FromInternalValue(stored_value);
1061 }
1062
1063 // Sanity-check: Uptime can never be greater than the wall-clock
1064 // difference (modulo some slack). If it is, report and reset
1065 // to the wall-clock difference.
1066 TimeDelta diff = GetUpdateDuration() - stored_delta;
1067 if (diff < -kDurationSlack) {
1068 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001069 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001070 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001071 << utils::FormatTimeDelta(diff)
1072 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001073 stored_delta = update_duration_current_;
1074 }
1075
1076 SetUpdateDurationUptime(stored_delta);
1077}
1078
Chris Sosabe45bef2013-04-09 18:25:12 -07001079void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001080 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001081}
1082
1083void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001084 CHECK(powerwash_safe_prefs_);
1085 string rollback_version;
1086 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1087 &rollback_version)) {
1088 SetRollbackVersion(rollback_version);
1089 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001090}
1091
1092void PayloadState::SetRollbackVersion(const string& rollback_version) {
1093 CHECK(powerwash_safe_prefs_);
1094 LOG(INFO) << "Blacklisting version "<< rollback_version;
1095 rollback_version_ = rollback_version;
1096 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001097}
1098
David Zeuthen9a017f22013-04-11 16:10:26 -07001099void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1100 const Time& timestamp,
1101 bool use_logging) {
1102 CHECK(prefs_);
1103 update_duration_uptime_ = value;
1104 update_duration_uptime_timestamp_ = timestamp;
1105 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1106 update_duration_uptime_.ToInternalValue());
1107 if (use_logging) {
1108 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001109 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001110 }
1111}
1112
1113void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001114 Time now = system_state_->clock()->GetMonotonicTime();
1115 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001116}
1117
1118void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001119 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001120 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1121 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1122 // We're frequently called so avoid logging this write
1123 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1124}
1125
Jay Srinivasan19409b72013-04-12 19:23:36 -07001126string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1127 return prefix + "-from-" + utils::ToString(source);
1128}
1129
1130void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1131 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001132 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001133}
1134
1135void PayloadState::SetCurrentBytesDownloaded(
1136 DownloadSource source,
1137 uint64_t current_bytes_downloaded,
1138 bool log) {
1139 CHECK(prefs_);
1140
1141 if (source >= kNumDownloadSources)
1142 return;
1143
1144 // Update the in-memory value.
1145 current_bytes_downloaded_[source] = current_bytes_downloaded;
1146
1147 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1148 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1149 LOG_IF(INFO, log) << "Current bytes downloaded for "
1150 << utils::ToString(source) << " = "
1151 << GetCurrentBytesDownloaded(source);
1152}
1153
1154void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1155 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001156 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001157}
1158
1159void PayloadState::SetTotalBytesDownloaded(
1160 DownloadSource source,
1161 uint64_t total_bytes_downloaded,
1162 bool log) {
1163 CHECK(prefs_);
1164
1165 if (source >= kNumDownloadSources)
1166 return;
1167
1168 // Update the in-memory value.
1169 total_bytes_downloaded_[source] = total_bytes_downloaded;
1170
1171 // Persist.
1172 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1173 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1174 LOG_IF(INFO, log) << "Total bytes downloaded for "
1175 << utils::ToString(source) << " = "
1176 << GetTotalBytesDownloaded(source);
1177}
1178
David Zeuthena573d6f2013-06-14 16:13:36 -07001179void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001180 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001181}
1182
1183void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1184 CHECK(prefs_);
1185 num_responses_seen_ = num_responses_seen;
1186 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1187 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1188}
1189
Jay Srinivasan53173b92013-05-17 17:13:01 -07001190void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001191 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001192
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001193 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001194 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001195 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001196 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1197 } else {
1198 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1199 http_url_ok = true;
1200 }
1201
1202 candidate_urls_.clear();
Sen Jiang0affc2c2017-02-10 15:55:05 -08001203 for (const auto& package : response_.packages) {
1204 candidate_urls_.emplace_back();
1205 for (const string& candidate_url : package.payload_urls) {
1206 if (base::StartsWith(
1207 candidate_url, "http://", base::CompareCase::INSENSITIVE_ASCII) &&
1208 !http_url_ok) {
1209 continue;
1210 }
1211 candidate_urls_.back().push_back(candidate_url);
1212 LOG(INFO) << "Candidate Url" << (candidate_urls_.back().size() - 1)
1213 << ": " << candidate_url;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001214 }
Sen Jiang0affc2c2017-02-10 15:55:05 -08001215 LOG(INFO) << "Found " << candidate_urls_.back().size() << " candidate URLs "
1216 << "out of " << package.payload_urls.size()
1217 << " URLs supplied in package " << candidate_urls_.size() - 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001218 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001219}
1220
David Zeuthene4c58bf2013-06-18 17:26:50 -07001221void PayloadState::CreateSystemUpdatedMarkerFile() {
1222 CHECK(prefs_);
1223 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1224 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1225}
1226
1227void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1228 // Send |time_to_reboot| as a UMA stat.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001229 string metric = metrics::kMetricTimeToRebootMinutes;
David Zeuthen33bae492014-02-25 16:16:18 -08001230 system_state_->metrics_lib()->SendToUMA(metric,
1231 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001232 0, // min: 0 minute
1233 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001234 kNumDefaultUmaBuckets);
1235 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1236 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001237}
1238
1239void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001240 // Flush previous state from abnormal attempt failure, if any.
1241 ReportAndClearPersistedAttemptMetrics();
1242
Alex Deymo569c4242013-07-24 12:01:01 -07001243 // Avoid the UpdateEngineStarted actions if this is not the first time we
1244 // run the update engine since reboot.
1245 if (!system_state_->system_rebooted())
1246 return;
1247
David Zeuthene4c58bf2013-06-18 17:26:50 -07001248 // Figure out if we just booted into a new update
1249 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1250 int64_t stored_value;
1251 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1252 Time system_updated_at = Time::FromInternalValue(stored_value);
1253 if (!system_updated_at.is_null()) {
1254 TimeDelta time_to_reboot =
1255 system_state_->clock()->GetWallclockTime() - system_updated_at;
1256 if (time_to_reboot.ToInternalValue() < 0) {
1257 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1258 << utils::ToString(system_updated_at);
1259 } else {
1260 BootedIntoUpdate(time_to_reboot);
1261 }
1262 }
1263 }
1264 prefs_->Delete(kPrefsSystemUpdatedMarker);
1265 }
Alex Deymo42432912013-07-12 20:21:15 -07001266 // Check if it is needed to send metrics about a failed reboot into a new
1267 // version.
1268 ReportFailedBootIfNeeded();
1269}
1270
1271void PayloadState::ReportFailedBootIfNeeded() {
1272 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1273 // payload was marked as ready immediately before the last reboot, and we
1274 // need to check if such payload successfully rebooted or not.
1275 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001276 int64_t installed_from = 0;
1277 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001278 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1279 return;
1280 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001281 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1282 // partition number. We are now using slot numbers (0 or 1) instead, so
1283 // the following comparison will not match if we are comparing an old
1284 // partition number against a new slot number, which is the correct outcome
1285 // since we successfully booted the new update in that case. If the boot
1286 // failed, we will read this value from the same version, so it will always
1287 // be compatible.
1288 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001289 // A reboot was pending, but the chromebook is again in the same
1290 // BootDevice where the update was installed from.
1291 int64_t target_attempt;
1292 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1293 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1294 "TargetVersionInstalledFrom was present.";
1295 target_attempt = 1;
1296 }
1297
1298 // Report the UMA metric of the current boot failure.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001299 string metric = metrics::kMetricFailedUpdateCount;
David Zeuthen33bae492014-02-25 16:16:18 -08001300 LOG(INFO) << "Uploading " << target_attempt
1301 << " (count) for metric " << metric;
1302 system_state_->metrics_lib()->SendToUMA(
1303 metric,
1304 target_attempt,
1305 1, // min value
1306 50, // max value
1307 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001308 } else {
1309 prefs_->Delete(kPrefsTargetVersionAttempt);
1310 prefs_->Delete(kPrefsTargetVersionUniqueId);
1311 }
1312 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1313 }
1314}
1315
1316void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1317 // Expect to boot into the new partition in the next reboot setting the
1318 // TargetVersion* flags in the Prefs.
1319 string stored_target_version_uid;
1320 string target_version_id;
1321 string target_partition;
1322 int64_t target_attempt;
1323
1324 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1325 prefs_->GetString(kPrefsTargetVersionUniqueId,
1326 &stored_target_version_uid) &&
1327 stored_target_version_uid == target_version_uid) {
1328 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1329 target_attempt = 0;
1330 } else {
1331 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1332 target_attempt = 0;
1333 }
1334 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1335
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001336 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001337 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001338}
1339
1340void PayloadState::ResetUpdateStatus() {
1341 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1342 // rebooted the next boot is not flagged as failed to rebooted into the
1343 // new applied payload.
1344 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1345
1346 // Also decrement the attempt number if it exists.
1347 int64_t target_attempt;
1348 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001349 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001350}
1351
David Zeuthendcba8092013-08-06 12:16:35 -07001352int PayloadState::GetP2PNumAttempts() {
1353 return p2p_num_attempts_;
1354}
1355
1356void PayloadState::SetP2PNumAttempts(int value) {
1357 p2p_num_attempts_ = value;
1358 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1359 CHECK(prefs_);
1360 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1361}
1362
1363void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001364 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001365}
1366
1367Time PayloadState::GetP2PFirstAttemptTimestamp() {
1368 return p2p_first_attempt_timestamp_;
1369}
1370
1371void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1372 p2p_first_attempt_timestamp_ = time;
1373 LOG(INFO) << "p2p First Attempt Timestamp = "
1374 << utils::ToString(p2p_first_attempt_timestamp_);
1375 CHECK(prefs_);
1376 int64_t stored_value = time.ToInternalValue();
1377 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1378}
1379
1380void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001381 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001382 Time stored_time = Time::FromInternalValue(stored_value);
1383 SetP2PFirstAttemptTimestamp(stored_time);
1384}
1385
1386void PayloadState::P2PNewAttempt() {
1387 CHECK(prefs_);
1388 // Set timestamp, if it hasn't been set already
1389 if (p2p_first_attempt_timestamp_.is_null()) {
1390 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1391 }
1392 // Increase number of attempts
1393 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1394}
1395
1396bool PayloadState::P2PAttemptAllowed() {
1397 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1398 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1399 << " which is greater than "
1400 << kMaxP2PAttempts
1401 << " - disallowing p2p.";
1402 return false;
1403 }
1404
1405 if (!p2p_first_attempt_timestamp_.is_null()) {
1406 Time now = system_state_->clock()->GetWallclockTime();
1407 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1408 if (time_spent_attempting_p2p.InSeconds() < 0) {
1409 LOG(ERROR) << "Time spent attempting p2p is negative"
1410 << " - disallowing p2p.";
1411 return false;
1412 }
1413 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1414 LOG(INFO) << "Time spent attempting p2p is "
1415 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1416 << " which is greater than "
1417 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1418 kMaxP2PAttemptTimeSeconds))
1419 << " - disallowing p2p.";
1420 return false;
1421 }
1422 }
1423
1424 return true;
1425}
1426
Sen Jiang0affc2c2017-02-10 15:55:05 -08001427int64_t PayloadState::GetPayloadSize() {
1428 int64_t payload_size = 0;
1429 for (const auto& package : response_.packages)
1430 payload_size += package.size;
1431 return payload_size;
1432}
1433
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001434} // namespace chromeos_update_engine