blob: 410a0bfb55dc7afcf64ef624141a78b60854377e [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"
Tianjie Xu282aa1f2017-09-05 13:42:45 -070035#include "update_engine/metrics_reporter_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080036#include "update_engine/metrics_utils.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070037#include "update_engine/omaha_request_params.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080038#include "update_engine/payload_consumer/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070039#include "update_engine/system_state.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080040
Jay Srinivasan08262882012-12-28 19:29:43 -080041using base::Time;
42using base::TimeDelta;
43using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080044using std::string;
45
46namespace chromeos_update_engine {
47
David Zeuthen9a017f22013-04-11 16:10:26 -070048const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
49
Jay Srinivasan08262882012-12-28 19:29:43 -080050// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070051static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080052
Jay Srinivasan08262882012-12-28 19:29:43 -080053// We want to randomize retry attempts after the backoff by +/- 6 hours.
54static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080055
Jay Srinivasan19409b72013-04-12 19:23:36 -070056PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070057 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070058 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070059 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070060 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070061 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070062 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070063 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070064 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070065 attempt_num_bytes_downloaded_(0),
66 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Shuqian Zhao29971732016-02-05 11:29:32 -080067 attempt_error_code_(ErrorCode::kSuccess),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070068 attempt_type_(AttemptType::kUpdate) {
69 for (int i = 0; i <= kNumDownloadSources; i++)
70 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070071}
72
73bool PayloadState::Initialize(SystemState* system_state) {
74 system_state_ = system_state;
75 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070076 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080077 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080078 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070079 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080080 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080081 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070082 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080083 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070084 LoadUpdateTimestampStart();
85 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
86 // being called before it. Don't reorder.
87 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070088 for (int i = 0; i < kNumDownloadSources; i++) {
89 DownloadSource source = static_cast<DownloadSource>(i);
90 LoadCurrentBytesDownloaded(source);
91 LoadTotalBytesDownloaded(source);
92 }
Chris Sosabe45bef2013-04-09 18:25:12 -070093 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070094 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070095 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070096 LoadP2PFirstAttemptTimestamp();
97 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080098 return true;
99}
100
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800101void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800102 // Always store the latest response.
103 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800104
Jay Srinivasan53173b92013-05-17 17:13:01 -0700105 // Compute the candidate URLs first as they are used to calculate the
106 // response signature so that a change in enterprise policy for
107 // HTTP downloads being enabled or not could be honored as soon as the
108 // next update check happens.
109 ComputeCandidateUrls();
110
Jay Srinivasan08262882012-12-28 19:29:43 -0800111 // Check if the "signature" of this response (i.e. the fields we care about)
112 // has changed.
113 string new_response_signature = CalculateResponseSignature();
114 bool has_response_changed = (response_signature_ != new_response_signature);
115
116 // If the response has changed, we should persist the new signature and
117 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800118 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800119 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700120 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800121 SetResponseSignature(new_response_signature);
122 ResetPersistedState();
123 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800124 }
125
Sen Jiang97eba342017-05-22 14:34:11 -0700126 // Always start from payload index 0, even for resume, to download partition
127 // info from previous payloads.
128 payload_index_ = 0;
129
Jay Srinivasan08262882012-12-28 19:29:43 -0800130 // This is the earliest point at which we can validate whether the URL index
131 // we loaded from the persisted state is a valid value. If the response
132 // hasn't changed but the URL index is invalid, it's indicative of some
133 // tampering of the persisted state.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800134 if (payload_index_ >= candidate_urls_.size() ||
135 url_index_ >= candidate_urls_[payload_index_].size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800136 LOG(INFO) << "Resetting all payload state as the url index seems to have "
137 "been tampered with";
138 ResetPersistedState();
139 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800140 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700141
142 // Update the current download source which depends on the latest value of
143 // the response.
144 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800145}
146
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700147void PayloadState::SetUsingP2PForDownloading(bool value) {
148 using_p2p_for_downloading_ = value;
149 // Update the current download source which depends on whether we are
150 // using p2p or not.
151 UpdateCurrentDownloadSource();
152}
153
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800154void PayloadState::DownloadComplete() {
155 LOG(INFO) << "Payload downloaded successfully";
156 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700157 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800158}
159
160void PayloadState::DownloadProgress(size_t count) {
161 if (count == 0)
162 return;
163
David Zeuthen9a017f22013-04-11 16:10:26 -0700164 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700165 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700166
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800167 // We've received non-zero bytes from a recent download operation. Since our
168 // URL failure count is meant to penalize a URL only for consecutive
169 // failures, downloading bytes successfully means we should reset the failure
170 // count (as we know at least that the URL is working). In future, we can
171 // design this to be more sophisticated to check for more intelligent failure
172 // patterns, but right now, even 1 byte downloaded will mark the URL to be
173 // good unless it hits 10 (or configured number of) consecutive failures
174 // again.
175
176 if (GetUrlFailureCount() == 0)
177 return;
178
179 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
180 << " to 0 as we received " << count << " bytes successfully";
181 SetUrlFailureCount(0);
182}
183
David Zeuthenafed4a12014-04-09 15:28:44 -0700184void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700185 // Flush previous state from abnormal attempt failure, if any.
186 ReportAndClearPersistedAttemptMetrics();
187
David Zeuthenafed4a12014-04-09 15:28:44 -0700188 attempt_type_ = attempt_type;
189
David Zeuthen33bae492014-02-25 16:16:18 -0800190 ClockInterface *clock = system_state_->clock();
191 attempt_start_time_boot_ = clock->GetBootTime();
192 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800193 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700194
195 metrics::ConnectionType type;
Sen Jiang255e22b2016-05-20 16:15:29 -0700196 ConnectionType network_connection_type;
197 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700198 ConnectionManagerInterface* connection_manager =
199 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700200 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700201 &tethering)) {
202 LOG(ERROR) << "Failed to determine connection type.";
203 type = metrics::ConnectionType::kUnknown;
204 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800205 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700206 }
207 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700208
209 if (attempt_type == AttemptType::kUpdate)
210 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800211}
212
Chris Sosabe45bef2013-04-09 18:25:12 -0700213void PayloadState::UpdateResumed() {
214 LOG(INFO) << "Resuming an update that was previously started.";
215 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700216 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700217}
218
Jay Srinivasan19409b72013-04-12 19:23:36 -0700219void PayloadState::UpdateRestarted() {
220 LOG(INFO) << "Starting a new update";
221 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700222 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700223 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700224}
225
David Zeuthen9a017f22013-04-11 16:10:26 -0700226void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700227 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700228 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700229 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800230
David Zeuthen96197df2014-04-16 12:22:39 -0700231 switch (attempt_type_) {
232 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700233 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700234 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700235 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700236 break;
237
238 case AttemptType::kRollback:
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700239 system_state_->metrics_reporter()->ReportRollbackMetrics(
240 metrics::RollbackResult::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700241 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700242 }
Shuqian Zhao29971732016-02-05 11:29:32 -0800243 attempt_error_code_ = ErrorCode::kSuccess;
David Zeuthena573d6f2013-06-14 16:13:36 -0700244
245 // Reset the number of responses seen since it counts from the last
246 // successful update, e.g. now.
247 SetNumResponsesSeen(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700248 SetPayloadIndex(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700249
250 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700251}
252
David Zeuthena99981f2013-04-29 13:42:47 -0700253void PayloadState::UpdateFailed(ErrorCode error) {
254 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800255 LOG(INFO) << "Updating payload state for error code: " << base_error
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800256 << " (" << utils::ErrorCodeToString(base_error) << ")";
Shuqian Zhaocd486362016-03-04 19:07:40 -0800257 attempt_error_code_ = base_error;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800258
Jay Srinivasan53173b92013-05-17 17:13:01 -0700259 if (candidate_urls_.size() == 0) {
260 // This means we got this error even before we got a valid Omaha response
261 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800262 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800263 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
264 return;
265 }
266
David Zeuthen96197df2014-04-16 12:22:39 -0700267 switch (attempt_type_) {
268 case AttemptType::kUpdate:
269 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700270 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700271 break;
272
273 case AttemptType::kRollback:
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700274 system_state_->metrics_reporter()->ReportRollbackMetrics(
275 metrics::RollbackResult::kFailed);
David Zeuthen96197df2014-04-16 12:22:39 -0700276 break;
277 }
David Zeuthen33bae492014-02-25 16:16:18 -0800278
Shuqian Zhao29971732016-02-05 11:29:32 -0800279
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800280 switch (base_error) {
281 // Errors which are good indicators of a problem with a particular URL or
282 // the protocol used in the URL or entities in the communication channel
283 // (e.g. proxies). We should try the next available URL in the next update
284 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700285 case ErrorCode::kPayloadHashMismatchError:
286 case ErrorCode::kPayloadSizeMismatchError:
287 case ErrorCode::kDownloadPayloadVerificationError:
288 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
289 case ErrorCode::kSignedDeltaPayloadExpectedError:
290 case ErrorCode::kDownloadInvalidMetadataMagicString:
291 case ErrorCode::kDownloadSignatureMissingInManifest:
292 case ErrorCode::kDownloadManifestParseError:
293 case ErrorCode::kDownloadMetadataSignatureError:
294 case ErrorCode::kDownloadMetadataSignatureVerificationError:
295 case ErrorCode::kDownloadMetadataSignatureMismatch:
296 case ErrorCode::kDownloadOperationHashVerificationError:
297 case ErrorCode::kDownloadOperationExecutionError:
298 case ErrorCode::kDownloadOperationHashMismatch:
299 case ErrorCode::kDownloadInvalidMetadataSize:
300 case ErrorCode::kDownloadInvalidMetadataSignature:
301 case ErrorCode::kDownloadOperationHashMissingError:
302 case ErrorCode::kDownloadMetadataSignatureMissingError:
303 case ErrorCode::kPayloadMismatchedType:
304 case ErrorCode::kUnsupportedMajorPayloadVersion:
305 case ErrorCode::kUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800306 IncrementUrlIndex();
307 break;
308
309 // Errors which seem to be just transient network/communication related
310 // failures and do not indicate any inherent problem with the URL itself.
311 // So, we should keep the current URL but just increment the
312 // failure count to give it more chances. This way, while we maximize our
313 // chances of downloading from the URLs that appear earlier in the response
314 // (because download from a local server URL that appears earlier in a
315 // response is preferable than downloading from the next URL which could be
316 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700317
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700318 case ErrorCode::kError:
319 case ErrorCode::kDownloadTransferError:
320 case ErrorCode::kDownloadWriteError:
321 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700322 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800323 IncrementFailureCount();
324 break;
325
326 // Errors which are not specific to a URL and hence shouldn't result in
327 // the URL being penalized. This can happen in two cases:
328 // 1. We haven't started downloading anything: These errors don't cost us
329 // anything in terms of actual payload bytes, so we should just do the
330 // regular retries at the next update check.
331 // 2. We have successfully downloaded the payload: In this case, the
332 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800333 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800334 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700335 case ErrorCode::kOmahaRequestError:
336 case ErrorCode::kOmahaResponseHandlerError:
337 case ErrorCode::kPostinstallRunnerError:
338 case ErrorCode::kFilesystemCopierError:
339 case ErrorCode::kInstallDeviceOpenError:
340 case ErrorCode::kKernelDeviceOpenError:
341 case ErrorCode::kDownloadNewPartitionInfoError:
342 case ErrorCode::kNewRootfsVerificationError:
343 case ErrorCode::kNewKernelVerificationError:
344 case ErrorCode::kPostinstallBootedFromFirmwareB:
345 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
346 case ErrorCode::kOmahaRequestEmptyResponseError:
347 case ErrorCode::kOmahaRequestXMLParseError:
348 case ErrorCode::kOmahaResponseInvalid:
349 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
350 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700351 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700352 case ErrorCode::kOmahaUpdateDeferredForBackoff:
353 case ErrorCode::kPostinstallPowerwashError:
354 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400355 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700356 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800357 case ErrorCode::kUserCanceled:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800358 LOG(INFO) << "Not incrementing URL index or failure count for this error";
359 break;
360
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700361 case ErrorCode::kSuccess: // success code
362 case ErrorCode::kUmaReportedMax: // not an error code
363 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
364 case ErrorCode::kDevModeFlag: // not an error code
365 case ErrorCode::kResumedFlag: // not an error code
366 case ErrorCode::kTestImageFlag: // not an error code
367 case ErrorCode::kTestOmahaUrlFlag: // not an error code
368 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800369 // These shouldn't happen. Enumerating these explicitly here so that we
370 // can let the compiler warn about new error codes that are added to
371 // action_processor.h but not added here.
372 LOG(WARNING) << "Unexpected error code for UpdateFailed";
373 break;
374
375 // Note: Not adding a default here so as to let the compiler warn us of
376 // any new enums that were added in the .h but not listed in this switch.
377 }
378}
379
Jay Srinivasan08262882012-12-28 19:29:43 -0800380bool PayloadState::ShouldBackoffDownload() {
381 if (response_.disable_payload_backoff) {
382 LOG(INFO) << "Payload backoff logic is disabled. "
383 "Can proceed with the download";
384 return false;
385 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700386 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700387 LOG(INFO) << "Payload backoff logic is disabled because download "
388 << "will happen from local peer (via p2p).";
389 return false;
390 }
391 if (system_state_->request_params()->interactive()) {
392 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
393 return false;
394 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700395 for (const auto& package : response_.packages) {
396 if (package.is_delta) {
397 // If delta payloads fail, we want to fallback quickly to full payloads as
398 // they are more likely to succeed. Exponential backoffs would greatly
399 // slow down the fallback to full payloads. So we don't backoff for delta
400 // payloads.
401 LOG(INFO) << "No backoffs for delta payloads. "
402 << "Can proceed with the download";
403 return false;
404 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800405 }
406
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700407 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800408 // Backoffs are needed only for official builds. We do not want any delays
409 // or update failures due to backoffs during testing or development.
410 LOG(INFO) << "No backoffs for test/dev images. "
411 << "Can proceed with the download";
412 return false;
413 }
414
415 if (backoff_expiry_time_.is_null()) {
416 LOG(INFO) << "No backoff expiry time has been set. "
417 << "Can proceed with the download";
418 return false;
419 }
420
421 if (backoff_expiry_time_ < Time::Now()) {
422 LOG(INFO) << "The backoff expiry time ("
423 << utils::ToString(backoff_expiry_time_)
424 << ") has elapsed. Can proceed with the download";
425 return false;
426 }
427
428 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
429 << utils::ToString(backoff_expiry_time_);
430 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800431}
432
Chris Sosaaa18e162013-06-20 13:20:30 -0700433void PayloadState::Rollback() {
434 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700435 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700436}
437
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800438void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700439 // Update the payload attempt number for both payload types: full and delta.
440 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
441}
442
443void PayloadState::IncrementFullPayloadAttemptNumber() {
444 // Update the payload attempt number for full payloads and the backoff time.
Sen Jiangcdd52062017-05-18 15:33:10 -0700445 if (response_.packages[payload_index_].is_delta) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800446 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
447 return;
448 }
449
Alex Deymo29b51d92013-07-09 15:26:24 -0700450 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700451 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800452 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800453}
454
455void PayloadState::IncrementUrlIndex() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800456 size_t next_url_index = url_index_ + 1;
457 size_t max_url_size = 0;
458 for (const auto& urls : candidate_urls_)
459 max_url_size = std::max(max_url_size, urls.size());
460 if (next_url_index < max_url_size) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800461 LOG(INFO) << "Incrementing the URL index for next attempt";
462 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800463 } else {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800464 LOG(INFO) << "Resetting the current URL index (" << url_index_ << ") to "
465 << "0 as we only have " << max_url_size << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800466 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700467 IncrementPayloadAttemptNumber();
468 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800469 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800470
David Zeuthencc6f9962013-04-18 11:57:24 -0700471 // If we have multiple URLs, record that we just switched to another one
Sen Jiang0affc2c2017-02-10 15:55:05 -0800472 if (max_url_size > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700473 SetUrlSwitchCount(url_switch_count_ + 1);
474
Jay Srinivasan08262882012-12-28 19:29:43 -0800475 // Whenever we update the URL index, we should also clear the URL failure
476 // count so we can start over fresh for the new URL.
477 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800478}
479
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800480void PayloadState::IncrementFailureCount() {
481 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800482 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800483 LOG(INFO) << "Incrementing the URL failure count";
484 SetUrlFailureCount(next_url_failure_count);
485 } else {
486 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
487 << ". Trying next available URL";
488 IncrementUrlIndex();
489 }
490}
491
Jay Srinivasan08262882012-12-28 19:29:43 -0800492void PayloadState::UpdateBackoffExpiryTime() {
493 if (response_.disable_payload_backoff) {
494 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
495 SetBackoffExpiryTime(Time());
496 return;
497 }
498
Alex Deymo820cc702013-06-28 15:43:46 -0700499 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800500 SetBackoffExpiryTime(Time());
501 return;
502 }
503
504 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700505 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800506 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700507 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700508 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800509
510 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
511 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700512 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800513
514 // The number of days is the minimum of 2 raised to (payload_attempt_number
515 // - 1) or kMaxBackoffDays.
516 num_days = min(num_days << power, kMaxBackoffDays);
517
518 // We don't want all retries to happen exactly at the same time when
519 // retrying after backoff. So add some random minutes to fuzz.
520 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
521 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
522 TimeDelta::FromMinutes(fuzz_minutes);
523 LOG(INFO) << "Incrementing the backoff expiry time by "
524 << utils::FormatTimeDelta(next_backoff_interval);
525 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
526}
527
Jay Srinivasan19409b72013-04-12 19:23:36 -0700528void PayloadState::UpdateCurrentDownloadSource() {
529 current_download_source_ = kNumDownloadSources;
530
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700531 if (using_p2p_for_downloading_) {
532 current_download_source_ = kDownloadSourceHttpPeer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800533 } else if (payload_index_ < candidate_urls_.size() &&
534 candidate_urls_[payload_index_].size() != 0) {
535 const string& current_url = candidate_urls_[payload_index_][GetUrlIndex()];
536 if (base::StartsWith(
537 current_url, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700538 current_download_source_ = kDownloadSourceHttpsServer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800539 } else if (base::StartsWith(current_url,
540 "http://",
Alex Vakulenko0103c362016-01-20 07:56:15 -0800541 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700542 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800543 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700544 }
545
546 LOG(INFO) << "Current download source: "
547 << utils::ToString(current_download_source_);
548}
549
550void PayloadState::UpdateBytesDownloaded(size_t count) {
551 SetCurrentBytesDownloaded(
552 current_download_source_,
553 GetCurrentBytesDownloaded(current_download_source_) + count,
554 false);
555 SetTotalBytesDownloaded(
556 current_download_source_,
557 GetTotalBytesDownloaded(current_download_source_) + count,
558 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800559
560 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700561}
562
David Zeuthen33bae492014-02-25 16:16:18 -0800563PayloadType PayloadState::CalculatePayloadType() {
Sen Jiangcdd52062017-05-18 15:33:10 -0700564 for (const auto& package : response_.packages) {
565 if (package.is_delta) {
566 return kPayloadTypeDelta;
567 }
David Zeuthen33bae492014-02-25 16:16:18 -0800568 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700569 OmahaRequestParams* params = system_state_->request_params();
570 if (params->delta_okay()) {
571 return kPayloadTypeFull;
572 }
573 // Full payload, delta was not allowed by request.
574 return kPayloadTypeForcedFull;
David Zeuthen33bae492014-02-25 16:16:18 -0800575}
576
577// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
578// metrics if the attempt ends abnormally, e.g. if the update_engine
579// process crashes or the device is rebooted. See
580// http://crbug.com/357676
581void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
582 int attempt_number = GetPayloadAttemptNumber();
583
584 PayloadType payload_type = CalculatePayloadType();
585
Sen Jiang0affc2c2017-02-10 15:55:05 -0800586 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800587
588 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
589
590 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700591 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
592 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800593 attempt_start_time_monotonic_;
594
595 int64_t payload_download_speed_bps = 0;
596 int64_t usec = duration_uptime.InMicroseconds();
597 if (usec > 0) {
598 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
599 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
600 payload_download_speed_bps = static_cast<int64_t>(bps);
601 }
602
603 DownloadSource download_source = current_download_source_;
604
605 metrics::DownloadErrorCode payload_download_error_code =
606 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700607 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800608 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800609
610 // Add additional detail to AttemptResult
611 switch (attempt_result) {
612 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800613 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800614 break;
615
616 case metrics::AttemptResult::kInternalError:
617 internal_error_code = code;
618 break;
619
620 // Explicit fall-through for cases where we do not have additional
621 // detail. We avoid the default keyword to force people adding new
622 // AttemptResult values to visit this code and examine whether
623 // additional detail is needed.
624 case metrics::AttemptResult::kUpdateSucceeded:
625 case metrics::AttemptResult::kMetadataMalformed:
626 case metrics::AttemptResult::kOperationMalformed:
627 case metrics::AttemptResult::kOperationExecutionError:
628 case metrics::AttemptResult::kMetadataVerificationFailed:
629 case metrics::AttemptResult::kPayloadVerificationFailed:
630 case metrics::AttemptResult::kVerificationFailed:
631 case metrics::AttemptResult::kPostInstallFailed:
632 case metrics::AttemptResult::kAbnormalTermination:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800633 case metrics::AttemptResult::kUpdateCanceled:
David Zeuthen33bae492014-02-25 16:16:18 -0800634 case metrics::AttemptResult::kNumConstants:
635 case metrics::AttemptResult::kUnset:
636 break;
637 }
638
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700639 system_state_->metrics_reporter()->ReportUpdateAttemptMetrics(
640 system_state_,
641 attempt_number,
642 payload_type,
643 duration,
644 duration_uptime,
645 payload_size,
Tianjie Xu1f93d092017-10-09 12:13:29 -0700646 attempt_result,
647 internal_error_code);
648
649 system_state_->metrics_reporter()->ReportUpdateAttemptDownloadMetrics(
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700650 payload_bytes_downloaded,
651 payload_download_speed_bps,
652 download_source,
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700653 payload_download_error_code,
654 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800655}
656
David Zeuthen4e1d1492014-04-25 13:12:27 -0700657void PayloadState::PersistAttemptMetrics() {
658 // TODO(zeuthen): For now we only persist whether an attempt was in
659 // progress and not values/metrics related to the attempt. This
660 // means that when this happens, of all the UpdateEngine.Attempt.*
661 // metrics, only UpdateEngine.Attempt.Result is reported (with the
662 // value |kAbnormalTermination|). In the future we might want to
663 // persist more data so we can report other metrics in the
664 // UpdateEngine.Attempt.* namespace when this happens.
665 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
666}
667
668void PayloadState::ClearPersistedAttemptMetrics() {
669 prefs_->Delete(kPrefsAttemptInProgress);
670}
671
672void PayloadState::ReportAndClearPersistedAttemptMetrics() {
673 bool attempt_in_progress = false;
674 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
675 return;
676 if (!attempt_in_progress)
677 return;
678
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700679 system_state_->metrics_reporter()
680 ->ReportAbnormallyTerminatedUpdateAttemptMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700681
682 ClearPersistedAttemptMetrics();
683}
684
David Zeuthen33bae492014-02-25 16:16:18 -0800685void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700686 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800687
688 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800689 int64_t total_bytes_by_source[kNumDownloadSources];
690 int64_t successful_bytes = 0;
691 int64_t total_bytes = 0;
692 int64_t successful_mbs = 0;
693 int64_t total_mbs = 0;
694
Jay Srinivasan19409b72013-04-12 19:23:36 -0700695 for (int i = 0; i < kNumDownloadSources; i++) {
696 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800697 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700698
David Zeuthen44848602013-06-24 13:32:14 -0700699 // Only consider this download source (and send byte counts) as
700 // having been used if we downloaded a non-trivial amount of bytes
701 // (e.g. at least 1 MiB) that contributed to the final success of
702 // the update. Otherwise we're going to end up with a lot of
703 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700704
David Zeuthen33bae492014-02-25 16:16:18 -0800705 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800706 successful_bytes += bytes;
707 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700708 SetCurrentBytesDownloaded(source, 0, true);
709
David Zeuthen33bae492014-02-25 16:16:18 -0800710 bytes = GetTotalBytesDownloaded(source);
711 total_bytes_by_source[i] = bytes;
712 total_bytes += bytes;
713 total_mbs += bytes / kNumBytesInOneMiB;
714 SetTotalBytesDownloaded(source, 0, true);
715 }
716
717 int download_overhead_percentage = 0;
718 if (successful_bytes > 0) {
719 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
720 successful_bytes;
721 }
722
723 int url_switch_count = static_cast<int>(url_switch_count_);
724
725 int reboot_count = GetNumReboots();
726
727 SetNumReboots(0);
728
729 TimeDelta duration = GetUpdateDuration();
David Zeuthen33bae492014-02-25 16:16:18 -0800730
731 prefs_->Delete(kPrefsUpdateTimestampStart);
732 prefs_->Delete(kPrefsUpdateDurationUptime);
733
734 PayloadType payload_type = CalculatePayloadType();
735
Sen Jiang0affc2c2017-02-10 15:55:05 -0800736 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800737
738 int attempt_count = GetPayloadAttemptNumber();
739
740 int updates_abandoned_count = num_responses_seen_ - 1;
741
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700742 system_state_->metrics_reporter()->ReportSuccessfulUpdateMetrics(
743 attempt_count,
744 updates_abandoned_count,
745 payload_type,
746 payload_size,
747 total_bytes_by_source,
748 download_overhead_percentage,
749 duration,
750 reboot_count,
751 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700752}
753
754void PayloadState::UpdateNumReboots() {
755 // We only update the reboot count when the system has been detected to have
756 // been rebooted.
757 if (!system_state_->system_rebooted()) {
758 return;
759 }
760
761 SetNumReboots(GetNumReboots() + 1);
762}
763
764void PayloadState::SetNumReboots(uint32_t num_reboots) {
765 CHECK(prefs_);
766 num_reboots_ = num_reboots;
767 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
768 LOG(INFO) << "Number of Reboots during current update attempt = "
769 << num_reboots_;
770}
771
Jay Srinivasan08262882012-12-28 19:29:43 -0800772void PayloadState::ResetPersistedState() {
773 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700774 SetFullPayloadAttemptNumber(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700775 SetPayloadIndex(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800776 SetUrlIndex(0);
777 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700778 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700779 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700780 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700781 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700782 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700783 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700784 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700785 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700786 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700787 SetScatteringWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700788}
789
790void PayloadState::ResetRollbackVersion() {
791 CHECK(powerwash_safe_prefs_);
792 rollback_version_ = "";
793 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700794}
795
796void PayloadState::ResetDownloadSourcesOnNewUpdate() {
797 for (int i = 0; i < kNumDownloadSources; i++) {
798 DownloadSource source = static_cast<DownloadSource>(i);
799 SetCurrentBytesDownloaded(source, 0, true);
800 // Note: Not resetting the TotalBytesDownloaded as we want that metric
801 // to count the bytes downloaded across various update attempts until
802 // we have successfully applied the update.
803 }
804}
805
Chris Sosab3dcdb32013-09-04 15:22:12 -0700806int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700807 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700808 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700809 return 0;
810
811 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700812 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700813 return 0;
814
815 if (stored_value < 0) {
816 LOG(ERROR) << key << ": Invalid value (" << stored_value
817 << ") in persisted state. Defaulting to 0";
818 return 0;
819 }
820
821 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800822}
823
824string PayloadState::CalculateResponseSignature() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800825 string response_sign;
826 for (size_t i = 0; i < response_.packages.size(); i++) {
827 const auto& package = response_.packages[i];
828 response_sign += base::StringPrintf(
829 "Payload %zu:\n"
830 " Size = %ju\n"
831 " Sha256 Hash = %s\n"
832 " Metadata Size = %ju\n"
833 " Metadata Signature = %s\n"
Sen Jiangcdd52062017-05-18 15:33:10 -0700834 " Is Delta = %d\n"
Sen Jiang0affc2c2017-02-10 15:55:05 -0800835 " NumURLs = %zu\n",
836 i,
837 static_cast<uintmax_t>(package.size),
838 package.hash.c_str(),
839 static_cast<uintmax_t>(package.metadata_size),
840 package.metadata_signature.c_str(),
Sen Jiangcdd52062017-05-18 15:33:10 -0700841 package.is_delta,
Sen Jiang0affc2c2017-02-10 15:55:05 -0800842 candidate_urls_[i].size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800843
Sen Jiang0affc2c2017-02-10 15:55:05 -0800844 for (size_t j = 0; j < candidate_urls_[i].size(); j++)
845 response_sign += base::StringPrintf(
846 " Candidate Url%zu = %s\n", j, candidate_urls_[i][j].c_str());
847 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800848
Alex Vakulenko75039d72014-03-25 12:36:28 -0700849 response_sign += base::StringPrintf(
Alex Vakulenko75039d72014-03-25 12:36:28 -0700850 "Max Failure Count Per Url = %d\n"
851 "Disable Payload Backoff = %d\n",
Alex Vakulenko75039d72014-03-25 12:36:28 -0700852 response_.max_failure_count_per_url,
853 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800854 return response_sign;
855}
856
857void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800858 CHECK(prefs_);
859 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800860 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
861 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
862 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800863 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800864}
865
Jay Srinivasan19409b72013-04-12 19:23:36 -0700866void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800867 CHECK(prefs_);
868 response_signature_ = response_signature;
869 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
870 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
871}
872
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800873void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700874 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800875}
876
Alex Deymo820cc702013-06-28 15:43:46 -0700877void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700878 SetFullPayloadAttemptNumber(GetPersistedValue(
879 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700880}
881
882void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800883 CHECK(prefs_);
884 payload_attempt_number_ = payload_attempt_number;
885 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
886 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
887}
888
Alex Deymo820cc702013-06-28 15:43:46 -0700889void PayloadState::SetFullPayloadAttemptNumber(
890 int full_payload_attempt_number) {
891 CHECK(prefs_);
892 full_payload_attempt_number_ = full_payload_attempt_number;
893 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
894 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
895 full_payload_attempt_number_);
896}
897
Sen Jiang5ae865b2017-04-18 14:24:40 -0700898void PayloadState::SetPayloadIndex(size_t payload_index) {
899 CHECK(prefs_);
900 payload_index_ = payload_index;
901 LOG(INFO) << "Payload Index = " << payload_index_;
902 prefs_->SetInt64(kPrefsUpdateStatePayloadIndex, payload_index_);
903}
904
905bool PayloadState::NextPayload() {
906 if (payload_index_ + 1 >= candidate_urls_.size())
907 return false;
908 SetPayloadIndex(payload_index_ + 1);
909 return true;
910}
911
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800912void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700913 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800914}
915
916void PayloadState::SetUrlIndex(uint32_t url_index) {
917 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800918 url_index_ = url_index;
919 LOG(INFO) << "Current URL Index = " << url_index_;
920 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700921
922 // Also update the download source, which is purely dependent on the
923 // current URL index alone.
924 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800925}
926
Gilad Arnold519cfc72014-10-02 10:34:54 -0700927void PayloadState::LoadScatteringWaitPeriod() {
928 SetScatteringWaitPeriod(
929 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
930}
931
Alex Deymof329b932014-10-30 01:37:48 -0700932void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700933 CHECK(prefs_);
934 scattering_wait_period_ = wait_period;
935 LOG(INFO) << "Scattering Wait Period (seconds) = "
936 << scattering_wait_period_.InSeconds();
937 if (scattering_wait_period_.InSeconds() > 0) {
938 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
939 scattering_wait_period_.InSeconds());
940 } else {
941 prefs_->Delete(kPrefsWallClockWaitPeriod);
942 }
943}
944
David Zeuthencc6f9962013-04-18 11:57:24 -0700945void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700946 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700947}
948
949void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
950 CHECK(prefs_);
951 url_switch_count_ = url_switch_count;
952 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
953 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
954}
955
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800956void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700957 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800958}
959
960void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
961 CHECK(prefs_);
962 url_failure_count_ = url_failure_count;
963 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
964 << ")'s Failure Count = " << url_failure_count_;
965 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800966}
967
Jay Srinivasan08262882012-12-28 19:29:43 -0800968void PayloadState::LoadBackoffExpiryTime() {
969 CHECK(prefs_);
970 int64_t stored_value;
971 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
972 return;
973
974 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
975 return;
976
977 Time stored_time = Time::FromInternalValue(stored_value);
978 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
979 LOG(ERROR) << "Invalid backoff expiry time ("
980 << utils::ToString(stored_time)
981 << ") in persisted state. Resetting.";
982 stored_time = Time();
983 }
984 SetBackoffExpiryTime(stored_time);
985}
986
987void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
988 CHECK(prefs_);
989 backoff_expiry_time_ = new_time;
990 LOG(INFO) << "Backoff Expiry Time = "
991 << utils::ToString(backoff_expiry_time_);
992 prefs_->SetInt64(kPrefsBackoffExpiryTime,
993 backoff_expiry_time_.ToInternalValue());
994}
995
David Zeuthen9a017f22013-04-11 16:10:26 -0700996TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700997 Time end_time = update_timestamp_end_.is_null()
998 ? system_state_->clock()->GetWallclockTime() :
999 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -07001000 return end_time - update_timestamp_start_;
1001}
1002
1003void PayloadState::LoadUpdateTimestampStart() {
1004 int64_t stored_value;
1005 Time stored_time;
1006
1007 CHECK(prefs_);
1008
David Zeuthenf413fe52013-04-22 14:04:39 -07001009 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001010
1011 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1012 // The preference missing is not unexpected - in that case, just
1013 // use the current time as start time
1014 stored_time = now;
1015 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1016 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1017 stored_time = now;
1018 } else {
1019 stored_time = Time::FromInternalValue(stored_value);
1020 }
1021
1022 // Sanity check: If the time read from disk is in the future
1023 // (modulo some slack to account for possible NTP drift
1024 // adjustments), something is fishy and we should report and
1025 // reset.
1026 TimeDelta duration_according_to_stored_time = now - stored_time;
1027 if (duration_according_to_stored_time < -kDurationSlack) {
1028 LOG(ERROR) << "The UpdateTimestampStart value ("
1029 << utils::ToString(stored_time)
1030 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001031 << utils::FormatTimeDelta(duration_according_to_stored_time)
1032 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001033 stored_time = now;
1034 }
1035
1036 SetUpdateTimestampStart(stored_time);
1037}
1038
1039void PayloadState::SetUpdateTimestampStart(const Time& value) {
1040 CHECK(prefs_);
1041 update_timestamp_start_ = value;
1042 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1043 update_timestamp_start_.ToInternalValue());
1044 LOG(INFO) << "Update Timestamp Start = "
1045 << utils::ToString(update_timestamp_start_);
1046}
1047
1048void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1049 update_timestamp_end_ = value;
1050 LOG(INFO) << "Update Timestamp End = "
1051 << utils::ToString(update_timestamp_end_);
1052}
1053
1054TimeDelta PayloadState::GetUpdateDurationUptime() {
1055 return update_duration_uptime_;
1056}
1057
1058void PayloadState::LoadUpdateDurationUptime() {
1059 int64_t stored_value;
1060 TimeDelta stored_delta;
1061
1062 CHECK(prefs_);
1063
1064 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1065 // The preference missing is not unexpected - in that case, just
1066 // we'll use zero as the delta
1067 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1068 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1069 stored_delta = TimeDelta::FromSeconds(0);
1070 } else {
1071 stored_delta = TimeDelta::FromInternalValue(stored_value);
1072 }
1073
1074 // Sanity-check: Uptime can never be greater than the wall-clock
1075 // difference (modulo some slack). If it is, report and reset
1076 // to the wall-clock difference.
1077 TimeDelta diff = GetUpdateDuration() - stored_delta;
1078 if (diff < -kDurationSlack) {
1079 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001080 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001081 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001082 << utils::FormatTimeDelta(diff)
1083 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001084 stored_delta = update_duration_current_;
1085 }
1086
1087 SetUpdateDurationUptime(stored_delta);
1088}
1089
Chris Sosabe45bef2013-04-09 18:25:12 -07001090void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001091 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001092}
1093
1094void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001095 CHECK(powerwash_safe_prefs_);
1096 string rollback_version;
1097 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1098 &rollback_version)) {
1099 SetRollbackVersion(rollback_version);
1100 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001101}
1102
1103void PayloadState::SetRollbackVersion(const string& rollback_version) {
1104 CHECK(powerwash_safe_prefs_);
1105 LOG(INFO) << "Blacklisting version "<< rollback_version;
1106 rollback_version_ = rollback_version;
1107 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001108}
1109
David Zeuthen9a017f22013-04-11 16:10:26 -07001110void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1111 const Time& timestamp,
1112 bool use_logging) {
1113 CHECK(prefs_);
1114 update_duration_uptime_ = value;
1115 update_duration_uptime_timestamp_ = timestamp;
1116 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1117 update_duration_uptime_.ToInternalValue());
1118 if (use_logging) {
1119 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001120 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001121 }
1122}
1123
1124void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001125 Time now = system_state_->clock()->GetMonotonicTime();
1126 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001127}
1128
1129void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001130 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001131 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1132 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1133 // We're frequently called so avoid logging this write
1134 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1135}
1136
Jay Srinivasan19409b72013-04-12 19:23:36 -07001137string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1138 return prefix + "-from-" + utils::ToString(source);
1139}
1140
1141void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1142 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001143 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001144}
1145
1146void PayloadState::SetCurrentBytesDownloaded(
1147 DownloadSource source,
1148 uint64_t current_bytes_downloaded,
1149 bool log) {
1150 CHECK(prefs_);
1151
1152 if (source >= kNumDownloadSources)
1153 return;
1154
1155 // Update the in-memory value.
1156 current_bytes_downloaded_[source] = current_bytes_downloaded;
1157
1158 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1159 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1160 LOG_IF(INFO, log) << "Current bytes downloaded for "
1161 << utils::ToString(source) << " = "
1162 << GetCurrentBytesDownloaded(source);
1163}
1164
1165void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1166 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001167 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001168}
1169
1170void PayloadState::SetTotalBytesDownloaded(
1171 DownloadSource source,
1172 uint64_t total_bytes_downloaded,
1173 bool log) {
1174 CHECK(prefs_);
1175
1176 if (source >= kNumDownloadSources)
1177 return;
1178
1179 // Update the in-memory value.
1180 total_bytes_downloaded_[source] = total_bytes_downloaded;
1181
1182 // Persist.
1183 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1184 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1185 LOG_IF(INFO, log) << "Total bytes downloaded for "
1186 << utils::ToString(source) << " = "
1187 << GetTotalBytesDownloaded(source);
1188}
1189
David Zeuthena573d6f2013-06-14 16:13:36 -07001190void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001191 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001192}
1193
1194void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1195 CHECK(prefs_);
1196 num_responses_seen_ = num_responses_seen;
1197 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1198 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1199}
1200
Jay Srinivasan53173b92013-05-17 17:13:01 -07001201void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001202 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001203
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001204 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001205 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001206 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001207 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1208 } else {
1209 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1210 http_url_ok = true;
1211 }
1212
1213 candidate_urls_.clear();
Sen Jiang0affc2c2017-02-10 15:55:05 -08001214 for (const auto& package : response_.packages) {
1215 candidate_urls_.emplace_back();
1216 for (const string& candidate_url : package.payload_urls) {
1217 if (base::StartsWith(
1218 candidate_url, "http://", base::CompareCase::INSENSITIVE_ASCII) &&
1219 !http_url_ok) {
1220 continue;
1221 }
1222 candidate_urls_.back().push_back(candidate_url);
1223 LOG(INFO) << "Candidate Url" << (candidate_urls_.back().size() - 1)
1224 << ": " << candidate_url;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001225 }
Sen Jiang0affc2c2017-02-10 15:55:05 -08001226 LOG(INFO) << "Found " << candidate_urls_.back().size() << " candidate URLs "
1227 << "out of " << package.payload_urls.size()
1228 << " URLs supplied in package " << candidate_urls_.size() - 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001229 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001230}
1231
David Zeuthene4c58bf2013-06-18 17:26:50 -07001232void PayloadState::CreateSystemUpdatedMarkerFile() {
1233 CHECK(prefs_);
1234 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1235 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1236}
1237
1238void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1239 // Send |time_to_reboot| as a UMA stat.
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001240 system_state_->metrics_reporter()->ReportTimeToReboot(
1241 time_to_reboot.InMinutes());
David Zeuthene4c58bf2013-06-18 17:26:50 -07001242}
1243
1244void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001245 // Flush previous state from abnormal attempt failure, if any.
1246 ReportAndClearPersistedAttemptMetrics();
1247
Alex Deymo569c4242013-07-24 12:01:01 -07001248 // Avoid the UpdateEngineStarted actions if this is not the first time we
1249 // run the update engine since reboot.
1250 if (!system_state_->system_rebooted())
1251 return;
1252
David Zeuthene4c58bf2013-06-18 17:26:50 -07001253 // Figure out if we just booted into a new update
1254 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1255 int64_t stored_value;
1256 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1257 Time system_updated_at = Time::FromInternalValue(stored_value);
1258 if (!system_updated_at.is_null()) {
1259 TimeDelta time_to_reboot =
1260 system_state_->clock()->GetWallclockTime() - system_updated_at;
1261 if (time_to_reboot.ToInternalValue() < 0) {
1262 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1263 << utils::ToString(system_updated_at);
1264 } else {
1265 BootedIntoUpdate(time_to_reboot);
1266 }
1267 }
1268 }
1269 prefs_->Delete(kPrefsSystemUpdatedMarker);
1270 }
Alex Deymo42432912013-07-12 20:21:15 -07001271 // Check if it is needed to send metrics about a failed reboot into a new
1272 // version.
1273 ReportFailedBootIfNeeded();
1274}
1275
1276void PayloadState::ReportFailedBootIfNeeded() {
1277 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1278 // payload was marked as ready immediately before the last reboot, and we
1279 // need to check if such payload successfully rebooted or not.
1280 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001281 int64_t installed_from = 0;
1282 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001283 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1284 return;
1285 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001286 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1287 // partition number. We are now using slot numbers (0 or 1) instead, so
1288 // the following comparison will not match if we are comparing an old
1289 // partition number against a new slot number, which is the correct outcome
1290 // since we successfully booted the new update in that case. If the boot
1291 // failed, we will read this value from the same version, so it will always
1292 // be compatible.
1293 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001294 // A reboot was pending, but the chromebook is again in the same
1295 // BootDevice where the update was installed from.
1296 int64_t target_attempt;
1297 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1298 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1299 "TargetVersionInstalledFrom was present.";
1300 target_attempt = 1;
1301 }
1302
1303 // Report the UMA metric of the current boot failure.
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001304 system_state_->metrics_reporter()->ReportFailedUpdateCount(
1305 target_attempt);
Alex Deymo42432912013-07-12 20:21:15 -07001306 } else {
1307 prefs_->Delete(kPrefsTargetVersionAttempt);
1308 prefs_->Delete(kPrefsTargetVersionUniqueId);
1309 }
1310 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1311 }
1312}
1313
1314void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1315 // Expect to boot into the new partition in the next reboot setting the
1316 // TargetVersion* flags in the Prefs.
1317 string stored_target_version_uid;
1318 string target_version_id;
1319 string target_partition;
1320 int64_t target_attempt;
1321
1322 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1323 prefs_->GetString(kPrefsTargetVersionUniqueId,
1324 &stored_target_version_uid) &&
1325 stored_target_version_uid == target_version_uid) {
1326 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1327 target_attempt = 0;
1328 } else {
1329 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1330 target_attempt = 0;
1331 }
1332 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1333
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001334 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001335 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001336}
1337
1338void PayloadState::ResetUpdateStatus() {
1339 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1340 // rebooted the next boot is not flagged as failed to rebooted into the
1341 // new applied payload.
1342 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1343
1344 // Also decrement the attempt number if it exists.
1345 int64_t target_attempt;
1346 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001347 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001348}
1349
David Zeuthendcba8092013-08-06 12:16:35 -07001350int PayloadState::GetP2PNumAttempts() {
1351 return p2p_num_attempts_;
1352}
1353
1354void PayloadState::SetP2PNumAttempts(int value) {
1355 p2p_num_attempts_ = value;
1356 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1357 CHECK(prefs_);
1358 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1359}
1360
1361void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001362 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001363}
1364
1365Time PayloadState::GetP2PFirstAttemptTimestamp() {
1366 return p2p_first_attempt_timestamp_;
1367}
1368
1369void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1370 p2p_first_attempt_timestamp_ = time;
1371 LOG(INFO) << "p2p First Attempt Timestamp = "
1372 << utils::ToString(p2p_first_attempt_timestamp_);
1373 CHECK(prefs_);
1374 int64_t stored_value = time.ToInternalValue();
1375 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1376}
1377
1378void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001379 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001380 Time stored_time = Time::FromInternalValue(stored_value);
1381 SetP2PFirstAttemptTimestamp(stored_time);
1382}
1383
1384void PayloadState::P2PNewAttempt() {
1385 CHECK(prefs_);
1386 // Set timestamp, if it hasn't been set already
1387 if (p2p_first_attempt_timestamp_.is_null()) {
1388 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1389 }
1390 // Increase number of attempts
1391 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1392}
1393
1394bool PayloadState::P2PAttemptAllowed() {
1395 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1396 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1397 << " which is greater than "
1398 << kMaxP2PAttempts
1399 << " - disallowing p2p.";
1400 return false;
1401 }
1402
1403 if (!p2p_first_attempt_timestamp_.is_null()) {
1404 Time now = system_state_->clock()->GetWallclockTime();
1405 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1406 if (time_spent_attempting_p2p.InSeconds() < 0) {
1407 LOG(ERROR) << "Time spent attempting p2p is negative"
1408 << " - disallowing p2p.";
1409 return false;
1410 }
1411 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1412 LOG(INFO) << "Time spent attempting p2p is "
1413 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1414 << " which is greater than "
1415 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1416 kMaxP2PAttemptTimeSeconds))
1417 << " - disallowing p2p.";
1418 return false;
1419 }
1420 }
1421
1422 return true;
1423}
1424
Sen Jiang0affc2c2017-02-10 15:55:05 -08001425int64_t PayloadState::GetPayloadSize() {
1426 int64_t payload_size = 0;
1427 for (const auto& package : response_.packages)
1428 payload_size += package.size;
1429 return payload_size;
1430}
1431
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001432} // namespace chromeos_update_engine