blob: 5b643b7edbd85efe1e7d5c2a47389d0f4f8aca98 [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
Tianjie Xu90aaa102017-10-10 17:39:03 -070048using metrics_utils::GetPersistedValue;
49
David Zeuthen9a017f22013-04-11 16:10:26 -070050const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
51
Jay Srinivasan08262882012-12-28 19:29:43 -080052// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070053static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080054
Jay Srinivasan08262882012-12-28 19:29:43 -080055// We want to randomize retry attempts after the backoff by +/- 6 hours.
56static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080057
Jay Srinivasan19409b72013-04-12 19:23:36 -070058PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070059 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070060 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070061 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070062 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070063 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070064 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070065 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070066 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070067 attempt_num_bytes_downloaded_(0),
68 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070069 attempt_type_(AttemptType::kUpdate) {
70 for (int i = 0; i <= kNumDownloadSources; i++)
71 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070072}
73
74bool PayloadState::Initialize(SystemState* system_state) {
75 system_state_ = system_state;
76 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070077 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080078 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080079 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070080 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080081 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080082 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070083 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080084 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070085 LoadUpdateTimestampStart();
86 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
87 // being called before it. Don't reorder.
88 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070089 for (int i = 0; i < kNumDownloadSources; i++) {
90 DownloadSource source = static_cast<DownloadSource>(i);
91 LoadCurrentBytesDownloaded(source);
92 LoadTotalBytesDownloaded(source);
93 }
Chris Sosabe45bef2013-04-09 18:25:12 -070094 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070095 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070096 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070097 LoadP2PFirstAttemptTimestamp();
98 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080099 return true;
100}
101
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800102void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800103 // Always store the latest response.
104 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800105
Jay Srinivasan53173b92013-05-17 17:13:01 -0700106 // Compute the candidate URLs first as they are used to calculate the
107 // response signature so that a change in enterprise policy for
108 // HTTP downloads being enabled or not could be honored as soon as the
109 // next update check happens.
110 ComputeCandidateUrls();
111
Jay Srinivasan08262882012-12-28 19:29:43 -0800112 // Check if the "signature" of this response (i.e. the fields we care about)
113 // has changed.
114 string new_response_signature = CalculateResponseSignature();
115 bool has_response_changed = (response_signature_ != new_response_signature);
116
117 // If the response has changed, we should persist the new signature and
118 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800119 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800120 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700121 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800122 SetResponseSignature(new_response_signature);
123 ResetPersistedState();
124 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800125 }
126
Sen Jiang97eba342017-05-22 14:34:11 -0700127 // Always start from payload index 0, even for resume, to download partition
128 // info from previous payloads.
129 payload_index_ = 0;
130
Jay Srinivasan08262882012-12-28 19:29:43 -0800131 // This is the earliest point at which we can validate whether the URL index
132 // we loaded from the persisted state is a valid value. If the response
133 // hasn't changed but the URL index is invalid, it's indicative of some
134 // tampering of the persisted state.
Sen Jiang0affc2c2017-02-10 15:55:05 -0800135 if (payload_index_ >= candidate_urls_.size() ||
136 url_index_ >= candidate_urls_[payload_index_].size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800137 LOG(INFO) << "Resetting all payload state as the url index seems to have "
138 "been tampered with";
139 ResetPersistedState();
140 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800141 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700142
143 // Update the current download source which depends on the latest value of
144 // the response.
145 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800146}
147
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700148void PayloadState::SetUsingP2PForDownloading(bool value) {
149 using_p2p_for_downloading_ = value;
150 // Update the current download source which depends on whether we are
151 // using p2p or not.
152 UpdateCurrentDownloadSource();
153}
154
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800155void PayloadState::DownloadComplete() {
156 LOG(INFO) << "Payload downloaded successfully";
157 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700158 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800159}
160
161void PayloadState::DownloadProgress(size_t count) {
162 if (count == 0)
163 return;
164
David Zeuthen9a017f22013-04-11 16:10:26 -0700165 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700166 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700167
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800168 // We've received non-zero bytes from a recent download operation. Since our
169 // URL failure count is meant to penalize a URL only for consecutive
170 // failures, downloading bytes successfully means we should reset the failure
171 // count (as we know at least that the URL is working). In future, we can
172 // design this to be more sophisticated to check for more intelligent failure
173 // patterns, but right now, even 1 byte downloaded will mark the URL to be
174 // good unless it hits 10 (or configured number of) consecutive failures
175 // again.
176
177 if (GetUrlFailureCount() == 0)
178 return;
179
180 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
181 << " to 0 as we received " << count << " bytes successfully";
182 SetUrlFailureCount(0);
183}
184
David Zeuthenafed4a12014-04-09 15:28:44 -0700185void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700186 // Flush previous state from abnormal attempt failure, if any.
187 ReportAndClearPersistedAttemptMetrics();
188
David Zeuthenafed4a12014-04-09 15:28:44 -0700189 attempt_type_ = attempt_type;
190
David Zeuthen33bae492014-02-25 16:16:18 -0800191 ClockInterface *clock = system_state_->clock();
192 attempt_start_time_boot_ = clock->GetBootTime();
193 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800194 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700195
196 metrics::ConnectionType type;
Sen Jiang255e22b2016-05-20 16:15:29 -0700197 ConnectionType network_connection_type;
198 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700199 ConnectionManagerInterface* connection_manager =
200 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700201 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700202 &tethering)) {
203 LOG(ERROR) << "Failed to determine connection type.";
204 type = metrics::ConnectionType::kUnknown;
205 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800206 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700207 }
208 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700209
210 if (attempt_type == AttemptType::kUpdate)
211 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800212}
213
Chris Sosabe45bef2013-04-09 18:25:12 -0700214void PayloadState::UpdateResumed() {
215 LOG(INFO) << "Resuming an update that was previously started.";
216 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700217 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700218}
219
Jay Srinivasan19409b72013-04-12 19:23:36 -0700220void PayloadState::UpdateRestarted() {
221 LOG(INFO) << "Starting a new update";
222 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700223 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700224 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700225}
226
David Zeuthen9a017f22013-04-11 16:10:26 -0700227void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700228 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700229 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700230 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800231
David Zeuthen96197df2014-04-16 12:22:39 -0700232 switch (attempt_type_) {
233 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700234 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700235 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700236 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700237 break;
238
239 case AttemptType::kRollback:
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700240 system_state_->metrics_reporter()->ReportRollbackMetrics(
241 metrics::RollbackResult::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700242 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700243 }
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
Tianjie Xu90aaa102017-10-10 17:39:03 -0700250 metrics_utils::SetSystemUpdatedMarker(system_state_->clock(), prefs_);
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) << ")";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800257
Jay Srinivasan53173b92013-05-17 17:13:01 -0700258 if (candidate_urls_.size() == 0) {
259 // This means we got this error even before we got a valid Omaha response
260 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800261 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800262 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
263 return;
264 }
265
David Zeuthen96197df2014-04-16 12:22:39 -0700266 switch (attempt_type_) {
267 case AttemptType::kUpdate:
268 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700269 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700270 break;
271
272 case AttemptType::kRollback:
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700273 system_state_->metrics_reporter()->ReportRollbackMetrics(
274 metrics::RollbackResult::kFailed);
David Zeuthen96197df2014-04-16 12:22:39 -0700275 break;
276 }
David Zeuthen33bae492014-02-25 16:16:18 -0800277
Shuqian Zhao29971732016-02-05 11:29:32 -0800278
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800279 switch (base_error) {
280 // Errors which are good indicators of a problem with a particular URL or
281 // the protocol used in the URL or entities in the communication channel
282 // (e.g. proxies). We should try the next available URL in the next update
283 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700284 case ErrorCode::kPayloadHashMismatchError:
285 case ErrorCode::kPayloadSizeMismatchError:
286 case ErrorCode::kDownloadPayloadVerificationError:
287 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
288 case ErrorCode::kSignedDeltaPayloadExpectedError:
289 case ErrorCode::kDownloadInvalidMetadataMagicString:
290 case ErrorCode::kDownloadSignatureMissingInManifest:
291 case ErrorCode::kDownloadManifestParseError:
292 case ErrorCode::kDownloadMetadataSignatureError:
293 case ErrorCode::kDownloadMetadataSignatureVerificationError:
294 case ErrorCode::kDownloadMetadataSignatureMismatch:
295 case ErrorCode::kDownloadOperationHashVerificationError:
296 case ErrorCode::kDownloadOperationExecutionError:
297 case ErrorCode::kDownloadOperationHashMismatch:
298 case ErrorCode::kDownloadInvalidMetadataSize:
299 case ErrorCode::kDownloadInvalidMetadataSignature:
300 case ErrorCode::kDownloadOperationHashMissingError:
301 case ErrorCode::kDownloadMetadataSignatureMissingError:
302 case ErrorCode::kPayloadMismatchedType:
303 case ErrorCode::kUnsupportedMajorPayloadVersion:
304 case ErrorCode::kUnsupportedMinorPayloadVersion:
Sen Jiang8e768e92017-06-28 17:13:19 -0700305 case ErrorCode::kPayloadTimestampError:
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:
Sen Jiangfe522822017-10-31 15:14:11 -0700358 case ErrorCode::kUpdatedButNotActive:
Sen Jiang89e24c12018-03-22 18:05:44 -0700359 case ErrorCode::kNoUpdate:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800360 LOG(INFO) << "Not incrementing URL index or failure count for this error";
361 break;
362
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700363 case ErrorCode::kSuccess: // success code
364 case ErrorCode::kUmaReportedMax: // not an error code
365 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
366 case ErrorCode::kDevModeFlag: // not an error code
367 case ErrorCode::kResumedFlag: // not an error code
368 case ErrorCode::kTestImageFlag: // not an error code
369 case ErrorCode::kTestOmahaUrlFlag: // not an error code
370 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800371 // These shouldn't happen. Enumerating these explicitly here so that we
372 // can let the compiler warn about new error codes that are added to
373 // action_processor.h but not added here.
374 LOG(WARNING) << "Unexpected error code for UpdateFailed";
375 break;
376
377 // Note: Not adding a default here so as to let the compiler warn us of
378 // any new enums that were added in the .h but not listed in this switch.
379 }
380}
381
Jay Srinivasan08262882012-12-28 19:29:43 -0800382bool PayloadState::ShouldBackoffDownload() {
383 if (response_.disable_payload_backoff) {
384 LOG(INFO) << "Payload backoff logic is disabled. "
385 "Can proceed with the download";
386 return false;
387 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700388 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700389 LOG(INFO) << "Payload backoff logic is disabled because download "
390 << "will happen from local peer (via p2p).";
391 return false;
392 }
393 if (system_state_->request_params()->interactive()) {
394 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
395 return false;
396 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700397 for (const auto& package : response_.packages) {
398 if (package.is_delta) {
399 // If delta payloads fail, we want to fallback quickly to full payloads as
400 // they are more likely to succeed. Exponential backoffs would greatly
401 // slow down the fallback to full payloads. So we don't backoff for delta
402 // payloads.
403 LOG(INFO) << "No backoffs for delta payloads. "
404 << "Can proceed with the download";
405 return false;
406 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800407 }
408
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700409 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800410 // Backoffs are needed only for official builds. We do not want any delays
411 // or update failures due to backoffs during testing or development.
412 LOG(INFO) << "No backoffs for test/dev images. "
413 << "Can proceed with the download";
414 return false;
415 }
416
417 if (backoff_expiry_time_.is_null()) {
418 LOG(INFO) << "No backoff expiry time has been set. "
419 << "Can proceed with the download";
420 return false;
421 }
422
423 if (backoff_expiry_time_ < Time::Now()) {
424 LOG(INFO) << "The backoff expiry time ("
425 << utils::ToString(backoff_expiry_time_)
426 << ") has elapsed. Can proceed with the download";
427 return false;
428 }
429
430 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
431 << utils::ToString(backoff_expiry_time_);
432 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800433}
434
Chris Sosaaa18e162013-06-20 13:20:30 -0700435void PayloadState::Rollback() {
436 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700437 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700438}
439
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800440void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700441 // Update the payload attempt number for both payload types: full and delta.
442 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
443}
444
445void PayloadState::IncrementFullPayloadAttemptNumber() {
446 // Update the payload attempt number for full payloads and the backoff time.
Sen Jiangcdd52062017-05-18 15:33:10 -0700447 if (response_.packages[payload_index_].is_delta) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800448 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
449 return;
450 }
451
Alex Deymo29b51d92013-07-09 15:26:24 -0700452 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700453 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800454 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800455}
456
457void PayloadState::IncrementUrlIndex() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800458 size_t next_url_index = url_index_ + 1;
459 size_t max_url_size = 0;
460 for (const auto& urls : candidate_urls_)
461 max_url_size = std::max(max_url_size, urls.size());
462 if (next_url_index < max_url_size) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800463 LOG(INFO) << "Incrementing the URL index for next attempt";
464 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800465 } else {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800466 LOG(INFO) << "Resetting the current URL index (" << url_index_ << ") to "
467 << "0 as we only have " << max_url_size << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800468 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700469 IncrementPayloadAttemptNumber();
470 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800471 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800472
David Zeuthencc6f9962013-04-18 11:57:24 -0700473 // If we have multiple URLs, record that we just switched to another one
Sen Jiang0affc2c2017-02-10 15:55:05 -0800474 if (max_url_size > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700475 SetUrlSwitchCount(url_switch_count_ + 1);
476
Jay Srinivasan08262882012-12-28 19:29:43 -0800477 // Whenever we update the URL index, we should also clear the URL failure
478 // count so we can start over fresh for the new URL.
479 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800480}
481
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800482void PayloadState::IncrementFailureCount() {
483 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800484 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800485 LOG(INFO) << "Incrementing the URL failure count";
486 SetUrlFailureCount(next_url_failure_count);
487 } else {
488 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
489 << ". Trying next available URL";
490 IncrementUrlIndex();
491 }
492}
493
Jay Srinivasan08262882012-12-28 19:29:43 -0800494void PayloadState::UpdateBackoffExpiryTime() {
495 if (response_.disable_payload_backoff) {
496 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
497 SetBackoffExpiryTime(Time());
498 return;
499 }
500
Alex Deymo820cc702013-06-28 15:43:46 -0700501 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800502 SetBackoffExpiryTime(Time());
503 return;
504 }
505
506 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700507 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800508 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700509 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700510 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800511
512 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
513 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700514 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800515
516 // The number of days is the minimum of 2 raised to (payload_attempt_number
517 // - 1) or kMaxBackoffDays.
518 num_days = min(num_days << power, kMaxBackoffDays);
519
520 // We don't want all retries to happen exactly at the same time when
521 // retrying after backoff. So add some random minutes to fuzz.
522 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
523 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
524 TimeDelta::FromMinutes(fuzz_minutes);
525 LOG(INFO) << "Incrementing the backoff expiry time by "
526 << utils::FormatTimeDelta(next_backoff_interval);
527 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
528}
529
Jay Srinivasan19409b72013-04-12 19:23:36 -0700530void PayloadState::UpdateCurrentDownloadSource() {
531 current_download_source_ = kNumDownloadSources;
532
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700533 if (using_p2p_for_downloading_) {
534 current_download_source_ = kDownloadSourceHttpPeer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800535 } else if (payload_index_ < candidate_urls_.size() &&
536 candidate_urls_[payload_index_].size() != 0) {
537 const string& current_url = candidate_urls_[payload_index_][GetUrlIndex()];
538 if (base::StartsWith(
539 current_url, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700540 current_download_source_ = kDownloadSourceHttpsServer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800541 } else if (base::StartsWith(current_url,
542 "http://",
Alex Vakulenko0103c362016-01-20 07:56:15 -0800543 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700544 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800545 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700546 }
547
548 LOG(INFO) << "Current download source: "
549 << utils::ToString(current_download_source_);
550}
551
552void PayloadState::UpdateBytesDownloaded(size_t count) {
553 SetCurrentBytesDownloaded(
554 current_download_source_,
555 GetCurrentBytesDownloaded(current_download_source_) + count,
556 false);
557 SetTotalBytesDownloaded(
558 current_download_source_,
559 GetTotalBytesDownloaded(current_download_source_) + count,
560 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800561
562 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700563}
564
David Zeuthen33bae492014-02-25 16:16:18 -0800565PayloadType PayloadState::CalculatePayloadType() {
Sen Jiangcdd52062017-05-18 15:33:10 -0700566 for (const auto& package : response_.packages) {
567 if (package.is_delta) {
568 return kPayloadTypeDelta;
569 }
David Zeuthen33bae492014-02-25 16:16:18 -0800570 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700571 OmahaRequestParams* params = system_state_->request_params();
572 if (params->delta_okay()) {
573 return kPayloadTypeFull;
574 }
575 // Full payload, delta was not allowed by request.
576 return kPayloadTypeForcedFull;
David Zeuthen33bae492014-02-25 16:16:18 -0800577}
578
579// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
580// metrics if the attempt ends abnormally, e.g. if the update_engine
581// process crashes or the device is rebooted. See
582// http://crbug.com/357676
583void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
584 int attempt_number = GetPayloadAttemptNumber();
585
586 PayloadType payload_type = CalculatePayloadType();
587
Sen Jiang0affc2c2017-02-10 15:55:05 -0800588 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800589
590 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
591
592 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700593 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
594 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800595 attempt_start_time_monotonic_;
596
597 int64_t payload_download_speed_bps = 0;
598 int64_t usec = duration_uptime.InMicroseconds();
599 if (usec > 0) {
600 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
601 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
602 payload_download_speed_bps = static_cast<int64_t>(bps);
603 }
604
605 DownloadSource download_source = current_download_source_;
606
607 metrics::DownloadErrorCode payload_download_error_code =
608 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700609 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800610 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800611
612 // Add additional detail to AttemptResult
613 switch (attempt_result) {
614 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800615 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800616 break;
617
618 case metrics::AttemptResult::kInternalError:
619 internal_error_code = code;
620 break;
621
622 // Explicit fall-through for cases where we do not have additional
623 // detail. We avoid the default keyword to force people adding new
624 // AttemptResult values to visit this code and examine whether
625 // additional detail is needed.
626 case metrics::AttemptResult::kUpdateSucceeded:
627 case metrics::AttemptResult::kMetadataMalformed:
628 case metrics::AttemptResult::kOperationMalformed:
629 case metrics::AttemptResult::kOperationExecutionError:
630 case metrics::AttemptResult::kMetadataVerificationFailed:
631 case metrics::AttemptResult::kPayloadVerificationFailed:
632 case metrics::AttemptResult::kVerificationFailed:
633 case metrics::AttemptResult::kPostInstallFailed:
634 case metrics::AttemptResult::kAbnormalTermination:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800635 case metrics::AttemptResult::kUpdateCanceled:
Sen Jiangfe522822017-10-31 15:14:11 -0700636 case metrics::AttemptResult::kUpdateSucceededNotActive:
David Zeuthen33bae492014-02-25 16:16:18 -0800637 case metrics::AttemptResult::kNumConstants:
638 case metrics::AttemptResult::kUnset:
639 break;
640 }
641
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700642 system_state_->metrics_reporter()->ReportUpdateAttemptMetrics(
643 system_state_,
644 attempt_number,
645 payload_type,
646 duration,
647 duration_uptime,
648 payload_size,
Tianjie Xu1f93d092017-10-09 12:13:29 -0700649 attempt_result,
650 internal_error_code);
651
652 system_state_->metrics_reporter()->ReportUpdateAttemptDownloadMetrics(
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700653 payload_bytes_downloaded,
654 payload_download_speed_bps,
655 download_source,
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700656 payload_download_error_code,
657 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800658}
659
David Zeuthen4e1d1492014-04-25 13:12:27 -0700660void PayloadState::PersistAttemptMetrics() {
661 // TODO(zeuthen): For now we only persist whether an attempt was in
662 // progress and not values/metrics related to the attempt. This
663 // means that when this happens, of all the UpdateEngine.Attempt.*
664 // metrics, only UpdateEngine.Attempt.Result is reported (with the
665 // value |kAbnormalTermination|). In the future we might want to
666 // persist more data so we can report other metrics in the
667 // UpdateEngine.Attempt.* namespace when this happens.
668 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
669}
670
671void PayloadState::ClearPersistedAttemptMetrics() {
672 prefs_->Delete(kPrefsAttemptInProgress);
673}
674
675void PayloadState::ReportAndClearPersistedAttemptMetrics() {
676 bool attempt_in_progress = false;
677 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
678 return;
679 if (!attempt_in_progress)
680 return;
681
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700682 system_state_->metrics_reporter()
683 ->ReportAbnormallyTerminatedUpdateAttemptMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700684
685 ClearPersistedAttemptMetrics();
686}
687
David Zeuthen33bae492014-02-25 16:16:18 -0800688void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700689 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800690
691 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800692 int64_t total_bytes_by_source[kNumDownloadSources];
693 int64_t successful_bytes = 0;
694 int64_t total_bytes = 0;
695 int64_t successful_mbs = 0;
696 int64_t total_mbs = 0;
697
Jay Srinivasan19409b72013-04-12 19:23:36 -0700698 for (int i = 0; i < kNumDownloadSources; i++) {
699 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800700 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700701
David Zeuthen44848602013-06-24 13:32:14 -0700702 // Only consider this download source (and send byte counts) as
703 // having been used if we downloaded a non-trivial amount of bytes
704 // (e.g. at least 1 MiB) that contributed to the final success of
705 // the update. Otherwise we're going to end up with a lot of
706 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700707
David Zeuthen33bae492014-02-25 16:16:18 -0800708 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800709 successful_bytes += bytes;
710 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700711 SetCurrentBytesDownloaded(source, 0, true);
712
David Zeuthen33bae492014-02-25 16:16:18 -0800713 bytes = GetTotalBytesDownloaded(source);
714 total_bytes_by_source[i] = bytes;
715 total_bytes += bytes;
716 total_mbs += bytes / kNumBytesInOneMiB;
717 SetTotalBytesDownloaded(source, 0, true);
718 }
719
720 int download_overhead_percentage = 0;
721 if (successful_bytes > 0) {
722 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
723 successful_bytes;
724 }
725
726 int url_switch_count = static_cast<int>(url_switch_count_);
727
728 int reboot_count = GetNumReboots();
729
730 SetNumReboots(0);
731
732 TimeDelta duration = GetUpdateDuration();
David Zeuthen33bae492014-02-25 16:16:18 -0800733
734 prefs_->Delete(kPrefsUpdateTimestampStart);
735 prefs_->Delete(kPrefsUpdateDurationUptime);
736
737 PayloadType payload_type = CalculatePayloadType();
738
Sen Jiang0affc2c2017-02-10 15:55:05 -0800739 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800740
741 int attempt_count = GetPayloadAttemptNumber();
742
743 int updates_abandoned_count = num_responses_seen_ - 1;
744
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700745 system_state_->metrics_reporter()->ReportSuccessfulUpdateMetrics(
746 attempt_count,
747 updates_abandoned_count,
748 payload_type,
749 payload_size,
750 total_bytes_by_source,
751 download_overhead_percentage,
752 duration,
753 reboot_count,
754 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700755}
756
757void PayloadState::UpdateNumReboots() {
758 // We only update the reboot count when the system has been detected to have
759 // been rebooted.
760 if (!system_state_->system_rebooted()) {
761 return;
762 }
763
764 SetNumReboots(GetNumReboots() + 1);
765}
766
767void PayloadState::SetNumReboots(uint32_t num_reboots) {
Chris Sosabe45bef2013-04-09 18:25:12 -0700768 num_reboots_ = num_reboots;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700769 metrics_utils::SetNumReboots(num_reboots, prefs_);
Chris Sosabe45bef2013-04-09 18:25:12 -0700770}
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
Jay Srinivasan08262882012-12-28 19:29:43 -0800806string PayloadState::CalculateResponseSignature() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800807 string response_sign;
808 for (size_t i = 0; i < response_.packages.size(); i++) {
809 const auto& package = response_.packages[i];
810 response_sign += base::StringPrintf(
811 "Payload %zu:\n"
812 " Size = %ju\n"
813 " Sha256 Hash = %s\n"
814 " Metadata Size = %ju\n"
815 " Metadata Signature = %s\n"
Sen Jiangcdd52062017-05-18 15:33:10 -0700816 " Is Delta = %d\n"
Sen Jiang0affc2c2017-02-10 15:55:05 -0800817 " NumURLs = %zu\n",
818 i,
819 static_cast<uintmax_t>(package.size),
820 package.hash.c_str(),
821 static_cast<uintmax_t>(package.metadata_size),
822 package.metadata_signature.c_str(),
Sen Jiangcdd52062017-05-18 15:33:10 -0700823 package.is_delta,
Sen Jiang0affc2c2017-02-10 15:55:05 -0800824 candidate_urls_[i].size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800825
Sen Jiang0affc2c2017-02-10 15:55:05 -0800826 for (size_t j = 0; j < candidate_urls_[i].size(); j++)
827 response_sign += base::StringPrintf(
828 " Candidate Url%zu = %s\n", j, candidate_urls_[i][j].c_str());
829 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800830
Alex Vakulenko75039d72014-03-25 12:36:28 -0700831 response_sign += base::StringPrintf(
Alex Vakulenko75039d72014-03-25 12:36:28 -0700832 "Max Failure Count Per Url = %d\n"
833 "Disable Payload Backoff = %d\n",
Alex Vakulenko75039d72014-03-25 12:36:28 -0700834 response_.max_failure_count_per_url,
835 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800836 return response_sign;
837}
838
839void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800840 CHECK(prefs_);
841 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800842 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
843 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
844 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800845 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800846}
847
Jay Srinivasan19409b72013-04-12 19:23:36 -0700848void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800849 CHECK(prefs_);
850 response_signature_ = response_signature;
851 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
852 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
853}
854
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800855void PayloadState::LoadPayloadAttemptNumber() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700856 SetPayloadAttemptNumber(
857 GetPersistedValue(kPrefsPayloadAttemptNumber, prefs_));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800858}
859
Alex Deymo820cc702013-06-28 15:43:46 -0700860void PayloadState::LoadFullPayloadAttemptNumber() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700861 SetFullPayloadAttemptNumber(
862 GetPersistedValue(kPrefsFullPayloadAttemptNumber, prefs_));
Alex Deymo820cc702013-06-28 15:43:46 -0700863}
864
865void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800866 payload_attempt_number_ = payload_attempt_number;
Tianjie Xu90aaa102017-10-10 17:39:03 -0700867 metrics_utils::SetPayloadAttemptNumber(payload_attempt_number, prefs_);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800868}
869
Alex Deymo820cc702013-06-28 15:43:46 -0700870void PayloadState::SetFullPayloadAttemptNumber(
871 int full_payload_attempt_number) {
872 CHECK(prefs_);
873 full_payload_attempt_number_ = full_payload_attempt_number;
874 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
875 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
876 full_payload_attempt_number_);
877}
878
Sen Jiang5ae865b2017-04-18 14:24:40 -0700879void PayloadState::SetPayloadIndex(size_t payload_index) {
880 CHECK(prefs_);
881 payload_index_ = payload_index;
882 LOG(INFO) << "Payload Index = " << payload_index_;
883 prefs_->SetInt64(kPrefsUpdateStatePayloadIndex, payload_index_);
884}
885
886bool PayloadState::NextPayload() {
887 if (payload_index_ + 1 >= candidate_urls_.size())
888 return false;
889 SetPayloadIndex(payload_index_ + 1);
890 return true;
891}
892
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800893void PayloadState::LoadUrlIndex() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700894 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex, prefs_));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800895}
896
897void PayloadState::SetUrlIndex(uint32_t url_index) {
898 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800899 url_index_ = url_index;
900 LOG(INFO) << "Current URL Index = " << url_index_;
901 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700902
903 // Also update the download source, which is purely dependent on the
904 // current URL index alone.
905 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800906}
907
Gilad Arnold519cfc72014-10-02 10:34:54 -0700908void PayloadState::LoadScatteringWaitPeriod() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700909 SetScatteringWaitPeriod(TimeDelta::FromSeconds(
910 GetPersistedValue(kPrefsWallClockWaitPeriod, prefs_)));
Gilad Arnold519cfc72014-10-02 10:34:54 -0700911}
912
Alex Deymof329b932014-10-30 01:37:48 -0700913void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700914 CHECK(prefs_);
915 scattering_wait_period_ = wait_period;
916 LOG(INFO) << "Scattering Wait Period (seconds) = "
917 << scattering_wait_period_.InSeconds();
918 if (scattering_wait_period_.InSeconds() > 0) {
919 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
920 scattering_wait_period_.InSeconds());
921 } else {
922 prefs_->Delete(kPrefsWallClockWaitPeriod);
923 }
924}
925
David Zeuthencc6f9962013-04-18 11:57:24 -0700926void PayloadState::LoadUrlSwitchCount() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700927 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount, prefs_));
David Zeuthencc6f9962013-04-18 11:57:24 -0700928}
929
930void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
931 CHECK(prefs_);
932 url_switch_count_ = url_switch_count;
933 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
934 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
935}
936
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800937void PayloadState::LoadUrlFailureCount() {
Tianjie Xu90aaa102017-10-10 17:39:03 -0700938 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount, prefs_));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800939}
940
941void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
942 CHECK(prefs_);
943 url_failure_count_ = url_failure_count;
944 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
945 << ")'s Failure Count = " << url_failure_count_;
946 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800947}
948
Jay Srinivasan08262882012-12-28 19:29:43 -0800949void PayloadState::LoadBackoffExpiryTime() {
950 CHECK(prefs_);
951 int64_t stored_value;
952 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
953 return;
954
955 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
956 return;
957
958 Time stored_time = Time::FromInternalValue(stored_value);
959 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
960 LOG(ERROR) << "Invalid backoff expiry time ("
961 << utils::ToString(stored_time)
962 << ") in persisted state. Resetting.";
963 stored_time = Time();
964 }
965 SetBackoffExpiryTime(stored_time);
966}
967
968void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
969 CHECK(prefs_);
970 backoff_expiry_time_ = new_time;
971 LOG(INFO) << "Backoff Expiry Time = "
972 << utils::ToString(backoff_expiry_time_);
973 prefs_->SetInt64(kPrefsBackoffExpiryTime,
974 backoff_expiry_time_.ToInternalValue());
975}
976
David Zeuthen9a017f22013-04-11 16:10:26 -0700977TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700978 Time end_time = update_timestamp_end_.is_null()
979 ? system_state_->clock()->GetWallclockTime() :
980 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700981 return end_time - update_timestamp_start_;
982}
983
984void PayloadState::LoadUpdateTimestampStart() {
985 int64_t stored_value;
986 Time stored_time;
987
988 CHECK(prefs_);
989
David Zeuthenf413fe52013-04-22 14:04:39 -0700990 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700991
992 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
993 // The preference missing is not unexpected - in that case, just
994 // use the current time as start time
995 stored_time = now;
996 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
997 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
998 stored_time = now;
999 } else {
1000 stored_time = Time::FromInternalValue(stored_value);
1001 }
1002
1003 // Sanity check: If the time read from disk is in the future
1004 // (modulo some slack to account for possible NTP drift
1005 // adjustments), something is fishy and we should report and
1006 // reset.
1007 TimeDelta duration_according_to_stored_time = now - stored_time;
1008 if (duration_according_to_stored_time < -kDurationSlack) {
1009 LOG(ERROR) << "The UpdateTimestampStart value ("
1010 << utils::ToString(stored_time)
1011 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001012 << utils::FormatTimeDelta(duration_according_to_stored_time)
1013 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001014 stored_time = now;
1015 }
1016
1017 SetUpdateTimestampStart(stored_time);
1018}
1019
1020void PayloadState::SetUpdateTimestampStart(const Time& value) {
David Zeuthen9a017f22013-04-11 16:10:26 -07001021 update_timestamp_start_ = value;
Tianjie Xu90aaa102017-10-10 17:39:03 -07001022 metrics_utils::SetUpdateTimestampStart(value, prefs_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001023}
1024
1025void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1026 update_timestamp_end_ = value;
1027 LOG(INFO) << "Update Timestamp End = "
1028 << utils::ToString(update_timestamp_end_);
1029}
1030
1031TimeDelta PayloadState::GetUpdateDurationUptime() {
1032 return update_duration_uptime_;
1033}
1034
1035void PayloadState::LoadUpdateDurationUptime() {
1036 int64_t stored_value;
1037 TimeDelta stored_delta;
1038
1039 CHECK(prefs_);
1040
1041 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1042 // The preference missing is not unexpected - in that case, just
1043 // we'll use zero as the delta
1044 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1045 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1046 stored_delta = TimeDelta::FromSeconds(0);
1047 } else {
1048 stored_delta = TimeDelta::FromInternalValue(stored_value);
1049 }
1050
1051 // Sanity-check: Uptime can never be greater than the wall-clock
1052 // difference (modulo some slack). If it is, report and reset
1053 // to the wall-clock difference.
1054 TimeDelta diff = GetUpdateDuration() - stored_delta;
1055 if (diff < -kDurationSlack) {
1056 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001057 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001058 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001059 << utils::FormatTimeDelta(diff)
1060 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001061 stored_delta = update_duration_current_;
1062 }
1063
1064 SetUpdateDurationUptime(stored_delta);
1065}
1066
Chris Sosabe45bef2013-04-09 18:25:12 -07001067void PayloadState::LoadNumReboots() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001068 SetNumReboots(GetPersistedValue(kPrefsNumReboots, prefs_));
Chris Sosaaa18e162013-06-20 13:20:30 -07001069}
1070
1071void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001072 CHECK(powerwash_safe_prefs_);
1073 string rollback_version;
1074 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1075 &rollback_version)) {
1076 SetRollbackVersion(rollback_version);
1077 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001078}
1079
1080void PayloadState::SetRollbackVersion(const string& rollback_version) {
1081 CHECK(powerwash_safe_prefs_);
1082 LOG(INFO) << "Blacklisting version "<< rollback_version;
1083 rollback_version_ = rollback_version;
1084 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001085}
1086
David Zeuthen9a017f22013-04-11 16:10:26 -07001087void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1088 const Time& timestamp,
1089 bool use_logging) {
1090 CHECK(prefs_);
1091 update_duration_uptime_ = value;
1092 update_duration_uptime_timestamp_ = timestamp;
1093 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1094 update_duration_uptime_.ToInternalValue());
1095 if (use_logging) {
1096 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001097 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001098 }
1099}
1100
1101void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001102 Time now = system_state_->clock()->GetMonotonicTime();
1103 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001104}
1105
1106void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001107 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001108 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1109 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1110 // We're frequently called so avoid logging this write
1111 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1112}
1113
Jay Srinivasan19409b72013-04-12 19:23:36 -07001114string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1115 return prefix + "-from-" + utils::ToString(source);
1116}
1117
1118void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1119 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001120 SetCurrentBytesDownloaded(source, GetPersistedValue(key, prefs_), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001121}
1122
1123void PayloadState::SetCurrentBytesDownloaded(
1124 DownloadSource source,
1125 uint64_t current_bytes_downloaded,
1126 bool log) {
1127 CHECK(prefs_);
1128
1129 if (source >= kNumDownloadSources)
1130 return;
1131
1132 // Update the in-memory value.
1133 current_bytes_downloaded_[source] = current_bytes_downloaded;
1134
1135 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1136 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1137 LOG_IF(INFO, log) << "Current bytes downloaded for "
1138 << utils::ToString(source) << " = "
1139 << GetCurrentBytesDownloaded(source);
1140}
1141
1142void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1143 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Tianjie Xu90aaa102017-10-10 17:39:03 -07001144 SetTotalBytesDownloaded(source, GetPersistedValue(key, prefs_), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001145}
1146
1147void PayloadState::SetTotalBytesDownloaded(
1148 DownloadSource source,
1149 uint64_t total_bytes_downloaded,
1150 bool log) {
1151 CHECK(prefs_);
1152
1153 if (source >= kNumDownloadSources)
1154 return;
1155
1156 // Update the in-memory value.
1157 total_bytes_downloaded_[source] = total_bytes_downloaded;
1158
1159 // Persist.
1160 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1161 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1162 LOG_IF(INFO, log) << "Total bytes downloaded for "
1163 << utils::ToString(source) << " = "
1164 << GetTotalBytesDownloaded(source);
1165}
1166
David Zeuthena573d6f2013-06-14 16:13:36 -07001167void PayloadState::LoadNumResponsesSeen() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001168 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen, prefs_));
David Zeuthena573d6f2013-06-14 16:13:36 -07001169}
1170
1171void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1172 CHECK(prefs_);
1173 num_responses_seen_ = num_responses_seen;
1174 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1175 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1176}
1177
Jay Srinivasan53173b92013-05-17 17:13:01 -07001178void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001179 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001180
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001181 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001182 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001183 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001184 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1185 } else {
1186 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1187 http_url_ok = true;
1188 }
1189
1190 candidate_urls_.clear();
Sen Jiang0affc2c2017-02-10 15:55:05 -08001191 for (const auto& package : response_.packages) {
1192 candidate_urls_.emplace_back();
1193 for (const string& candidate_url : package.payload_urls) {
1194 if (base::StartsWith(
1195 candidate_url, "http://", base::CompareCase::INSENSITIVE_ASCII) &&
1196 !http_url_ok) {
1197 continue;
1198 }
1199 candidate_urls_.back().push_back(candidate_url);
1200 LOG(INFO) << "Candidate Url" << (candidate_urls_.back().size() - 1)
1201 << ": " << candidate_url;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001202 }
Sen Jiang0affc2c2017-02-10 15:55:05 -08001203 LOG(INFO) << "Found " << candidate_urls_.back().size() << " candidate URLs "
1204 << "out of " << package.payload_urls.size()
1205 << " URLs supplied in package " << candidate_urls_.size() - 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001206 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001207}
1208
David Zeuthene4c58bf2013-06-18 17:26:50 -07001209void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001210 // Flush previous state from abnormal attempt failure, if any.
1211 ReportAndClearPersistedAttemptMetrics();
1212
Alex Deymo569c4242013-07-24 12:01:01 -07001213 // Avoid the UpdateEngineStarted actions if this is not the first time we
1214 // run the update engine since reboot.
1215 if (!system_state_->system_rebooted())
1216 return;
1217
Tianjie Xu90aaa102017-10-10 17:39:03 -07001218 // Report time_to_reboot if we booted into a new update.
1219 metrics_utils::LoadAndReportTimeToReboot(
1220 system_state_->metrics_reporter(), prefs_, system_state_->clock());
1221 prefs_->Delete(kPrefsSystemUpdatedMarker);
1222
Alex Deymo42432912013-07-12 20:21:15 -07001223 // Check if it is needed to send metrics about a failed reboot into a new
1224 // version.
1225 ReportFailedBootIfNeeded();
1226}
1227
1228void PayloadState::ReportFailedBootIfNeeded() {
1229 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1230 // payload was marked as ready immediately before the last reboot, and we
1231 // need to check if such payload successfully rebooted or not.
1232 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001233 int64_t installed_from = 0;
1234 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001235 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1236 return;
1237 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001238 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1239 // partition number. We are now using slot numbers (0 or 1) instead, so
1240 // the following comparison will not match if we are comparing an old
1241 // partition number against a new slot number, which is the correct outcome
1242 // since we successfully booted the new update in that case. If the boot
1243 // failed, we will read this value from the same version, so it will always
1244 // be compatible.
1245 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001246 // A reboot was pending, but the chromebook is again in the same
1247 // BootDevice where the update was installed from.
1248 int64_t target_attempt;
1249 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1250 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1251 "TargetVersionInstalledFrom was present.";
1252 target_attempt = 1;
1253 }
1254
1255 // Report the UMA metric of the current boot failure.
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001256 system_state_->metrics_reporter()->ReportFailedUpdateCount(
1257 target_attempt);
Alex Deymo42432912013-07-12 20:21:15 -07001258 } else {
1259 prefs_->Delete(kPrefsTargetVersionAttempt);
1260 prefs_->Delete(kPrefsTargetVersionUniqueId);
1261 }
1262 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1263 }
1264}
1265
1266void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1267 // Expect to boot into the new partition in the next reboot setting the
1268 // TargetVersion* flags in the Prefs.
1269 string stored_target_version_uid;
1270 string target_version_id;
1271 string target_partition;
1272 int64_t target_attempt;
1273
1274 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1275 prefs_->GetString(kPrefsTargetVersionUniqueId,
1276 &stored_target_version_uid) &&
1277 stored_target_version_uid == target_version_uid) {
1278 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1279 target_attempt = 0;
1280 } else {
1281 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1282 target_attempt = 0;
1283 }
1284 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1285
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001286 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001287 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001288}
1289
1290void PayloadState::ResetUpdateStatus() {
1291 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1292 // rebooted the next boot is not flagged as failed to rebooted into the
1293 // new applied payload.
1294 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1295
1296 // Also decrement the attempt number if it exists.
1297 int64_t target_attempt;
1298 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001299 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001300}
1301
David Zeuthendcba8092013-08-06 12:16:35 -07001302int PayloadState::GetP2PNumAttempts() {
1303 return p2p_num_attempts_;
1304}
1305
1306void PayloadState::SetP2PNumAttempts(int value) {
1307 p2p_num_attempts_ = value;
1308 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1309 CHECK(prefs_);
1310 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1311}
1312
1313void PayloadState::LoadP2PNumAttempts() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001314 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts, prefs_));
David Zeuthendcba8092013-08-06 12:16:35 -07001315}
1316
1317Time PayloadState::GetP2PFirstAttemptTimestamp() {
1318 return p2p_first_attempt_timestamp_;
1319}
1320
1321void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1322 p2p_first_attempt_timestamp_ = time;
1323 LOG(INFO) << "p2p First Attempt Timestamp = "
1324 << utils::ToString(p2p_first_attempt_timestamp_);
1325 CHECK(prefs_);
1326 int64_t stored_value = time.ToInternalValue();
1327 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1328}
1329
1330void PayloadState::LoadP2PFirstAttemptTimestamp() {
Tianjie Xu90aaa102017-10-10 17:39:03 -07001331 int64_t stored_value =
1332 GetPersistedValue(kPrefsP2PFirstAttemptTimestamp, prefs_);
David Zeuthendcba8092013-08-06 12:16:35 -07001333 Time stored_time = Time::FromInternalValue(stored_value);
1334 SetP2PFirstAttemptTimestamp(stored_time);
1335}
1336
1337void PayloadState::P2PNewAttempt() {
1338 CHECK(prefs_);
1339 // Set timestamp, if it hasn't been set already
1340 if (p2p_first_attempt_timestamp_.is_null()) {
1341 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1342 }
1343 // Increase number of attempts
1344 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1345}
1346
1347bool PayloadState::P2PAttemptAllowed() {
1348 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1349 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1350 << " which is greater than "
1351 << kMaxP2PAttempts
1352 << " - disallowing p2p.";
1353 return false;
1354 }
1355
1356 if (!p2p_first_attempt_timestamp_.is_null()) {
1357 Time now = system_state_->clock()->GetWallclockTime();
1358 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1359 if (time_spent_attempting_p2p.InSeconds() < 0) {
1360 LOG(ERROR) << "Time spent attempting p2p is negative"
1361 << " - disallowing p2p.";
1362 return false;
1363 }
1364 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1365 LOG(INFO) << "Time spent attempting p2p is "
1366 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1367 << " which is greater than "
1368 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1369 kMaxP2PAttemptTimeSeconds))
1370 << " - disallowing p2p.";
1371 return false;
1372 }
1373 }
1374
1375 return true;
1376}
1377
Sen Jiang0affc2c2017-02-10 15:55:05 -08001378int64_t PayloadState::GetPayloadSize() {
1379 int64_t payload_size = 0;
1380 for (const auto& package : response_.packages)
1381 payload_size += package.size;
1382 return payload_size;
1383}
1384
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001385} // namespace chromeos_update_engine