blob: 475efe637fa347849ee244ca396890f4b6f4dd0e [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:
Sen Jiang5011df62017-06-28 17:13:19 -0700306 case ErrorCode::kPayloadTimestampError:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800307 IncrementUrlIndex();
308 break;
309
310 // Errors which seem to be just transient network/communication related
311 // failures and do not indicate any inherent problem with the URL itself.
312 // So, we should keep the current URL but just increment the
313 // failure count to give it more chances. This way, while we maximize our
314 // chances of downloading from the URLs that appear earlier in the response
315 // (because download from a local server URL that appears earlier in a
316 // response is preferable than downloading from the next URL which could be
317 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700318
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700319 case ErrorCode::kError:
320 case ErrorCode::kDownloadTransferError:
321 case ErrorCode::kDownloadWriteError:
322 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700323 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800324 IncrementFailureCount();
325 break;
326
327 // Errors which are not specific to a URL and hence shouldn't result in
328 // the URL being penalized. This can happen in two cases:
329 // 1. We haven't started downloading anything: These errors don't cost us
330 // anything in terms of actual payload bytes, so we should just do the
331 // regular retries at the next update check.
332 // 2. We have successfully downloaded the payload: In this case, the
333 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800334 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800335 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700336 case ErrorCode::kOmahaRequestError:
337 case ErrorCode::kOmahaResponseHandlerError:
338 case ErrorCode::kPostinstallRunnerError:
339 case ErrorCode::kFilesystemCopierError:
340 case ErrorCode::kInstallDeviceOpenError:
341 case ErrorCode::kKernelDeviceOpenError:
342 case ErrorCode::kDownloadNewPartitionInfoError:
343 case ErrorCode::kNewRootfsVerificationError:
344 case ErrorCode::kNewKernelVerificationError:
345 case ErrorCode::kPostinstallBootedFromFirmwareB:
346 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
347 case ErrorCode::kOmahaRequestEmptyResponseError:
348 case ErrorCode::kOmahaRequestXMLParseError:
349 case ErrorCode::kOmahaResponseInvalid:
350 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
351 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700352 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700353 case ErrorCode::kOmahaUpdateDeferredForBackoff:
354 case ErrorCode::kPostinstallPowerwashError:
355 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400356 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700357 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800358 case ErrorCode::kUserCanceled:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800359 LOG(INFO) << "Not incrementing URL index or failure count for this error";
360 break;
361
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700362 case ErrorCode::kSuccess: // success code
363 case ErrorCode::kUmaReportedMax: // not an error code
364 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
365 case ErrorCode::kDevModeFlag: // not an error code
366 case ErrorCode::kResumedFlag: // not an error code
367 case ErrorCode::kTestImageFlag: // not an error code
368 case ErrorCode::kTestOmahaUrlFlag: // not an error code
369 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800370 // These shouldn't happen. Enumerating these explicitly here so that we
371 // can let the compiler warn about new error codes that are added to
372 // action_processor.h but not added here.
373 LOG(WARNING) << "Unexpected error code for UpdateFailed";
374 break;
375
376 // Note: Not adding a default here so as to let the compiler warn us of
377 // any new enums that were added in the .h but not listed in this switch.
378 }
379}
380
Jay Srinivasan08262882012-12-28 19:29:43 -0800381bool PayloadState::ShouldBackoffDownload() {
382 if (response_.disable_payload_backoff) {
383 LOG(INFO) << "Payload backoff logic is disabled. "
384 "Can proceed with the download";
385 return false;
386 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700387 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700388 LOG(INFO) << "Payload backoff logic is disabled because download "
389 << "will happen from local peer (via p2p).";
390 return false;
391 }
392 if (system_state_->request_params()->interactive()) {
393 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
394 return false;
395 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700396 for (const auto& package : response_.packages) {
397 if (package.is_delta) {
398 // If delta payloads fail, we want to fallback quickly to full payloads as
399 // they are more likely to succeed. Exponential backoffs would greatly
400 // slow down the fallback to full payloads. So we don't backoff for delta
401 // payloads.
402 LOG(INFO) << "No backoffs for delta payloads. "
403 << "Can proceed with the download";
404 return false;
405 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800406 }
407
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700408 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800409 // Backoffs are needed only for official builds. We do not want any delays
410 // or update failures due to backoffs during testing or development.
411 LOG(INFO) << "No backoffs for test/dev images. "
412 << "Can proceed with the download";
413 return false;
414 }
415
416 if (backoff_expiry_time_.is_null()) {
417 LOG(INFO) << "No backoff expiry time has been set. "
418 << "Can proceed with the download";
419 return false;
420 }
421
422 if (backoff_expiry_time_ < Time::Now()) {
423 LOG(INFO) << "The backoff expiry time ("
424 << utils::ToString(backoff_expiry_time_)
425 << ") has elapsed. Can proceed with the download";
426 return false;
427 }
428
429 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
430 << utils::ToString(backoff_expiry_time_);
431 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800432}
433
Chris Sosaaa18e162013-06-20 13:20:30 -0700434void PayloadState::Rollback() {
435 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700436 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700437}
438
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800439void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700440 // Update the payload attempt number for both payload types: full and delta.
441 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
442}
443
444void PayloadState::IncrementFullPayloadAttemptNumber() {
445 // Update the payload attempt number for full payloads and the backoff time.
Sen Jiangcdd52062017-05-18 15:33:10 -0700446 if (response_.packages[payload_index_].is_delta) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800447 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
448 return;
449 }
450
Alex Deymo29b51d92013-07-09 15:26:24 -0700451 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700452 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800453 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800454}
455
456void PayloadState::IncrementUrlIndex() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800457 size_t next_url_index = url_index_ + 1;
458 size_t max_url_size = 0;
459 for (const auto& urls : candidate_urls_)
460 max_url_size = std::max(max_url_size, urls.size());
461 if (next_url_index < max_url_size) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800462 LOG(INFO) << "Incrementing the URL index for next attempt";
463 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800464 } else {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800465 LOG(INFO) << "Resetting the current URL index (" << url_index_ << ") to "
466 << "0 as we only have " << max_url_size << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800467 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700468 IncrementPayloadAttemptNumber();
469 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800470 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800471
David Zeuthencc6f9962013-04-18 11:57:24 -0700472 // If we have multiple URLs, record that we just switched to another one
Sen Jiang0affc2c2017-02-10 15:55:05 -0800473 if (max_url_size > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700474 SetUrlSwitchCount(url_switch_count_ + 1);
475
Jay Srinivasan08262882012-12-28 19:29:43 -0800476 // Whenever we update the URL index, we should also clear the URL failure
477 // count so we can start over fresh for the new URL.
478 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800479}
480
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800481void PayloadState::IncrementFailureCount() {
482 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800483 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800484 LOG(INFO) << "Incrementing the URL failure count";
485 SetUrlFailureCount(next_url_failure_count);
486 } else {
487 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
488 << ". Trying next available URL";
489 IncrementUrlIndex();
490 }
491}
492
Jay Srinivasan08262882012-12-28 19:29:43 -0800493void PayloadState::UpdateBackoffExpiryTime() {
494 if (response_.disable_payload_backoff) {
495 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
496 SetBackoffExpiryTime(Time());
497 return;
498 }
499
Alex Deymo820cc702013-06-28 15:43:46 -0700500 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800501 SetBackoffExpiryTime(Time());
502 return;
503 }
504
505 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700506 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800507 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700508 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700509 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800510
511 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
512 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700513 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800514
515 // The number of days is the minimum of 2 raised to (payload_attempt_number
516 // - 1) or kMaxBackoffDays.
517 num_days = min(num_days << power, kMaxBackoffDays);
518
519 // We don't want all retries to happen exactly at the same time when
520 // retrying after backoff. So add some random minutes to fuzz.
521 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
522 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
523 TimeDelta::FromMinutes(fuzz_minutes);
524 LOG(INFO) << "Incrementing the backoff expiry time by "
525 << utils::FormatTimeDelta(next_backoff_interval);
526 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
527}
528
Jay Srinivasan19409b72013-04-12 19:23:36 -0700529void PayloadState::UpdateCurrentDownloadSource() {
530 current_download_source_ = kNumDownloadSources;
531
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700532 if (using_p2p_for_downloading_) {
533 current_download_source_ = kDownloadSourceHttpPeer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800534 } else if (payload_index_ < candidate_urls_.size() &&
535 candidate_urls_[payload_index_].size() != 0) {
536 const string& current_url = candidate_urls_[payload_index_][GetUrlIndex()];
537 if (base::StartsWith(
538 current_url, "https://", base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700539 current_download_source_ = kDownloadSourceHttpsServer;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800540 } else if (base::StartsWith(current_url,
541 "http://",
Alex Vakulenko0103c362016-01-20 07:56:15 -0800542 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700543 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800544 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700545 }
546
547 LOG(INFO) << "Current download source: "
548 << utils::ToString(current_download_source_);
549}
550
551void PayloadState::UpdateBytesDownloaded(size_t count) {
552 SetCurrentBytesDownloaded(
553 current_download_source_,
554 GetCurrentBytesDownloaded(current_download_source_) + count,
555 false);
556 SetTotalBytesDownloaded(
557 current_download_source_,
558 GetTotalBytesDownloaded(current_download_source_) + count,
559 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800560
561 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700562}
563
David Zeuthen33bae492014-02-25 16:16:18 -0800564PayloadType PayloadState::CalculatePayloadType() {
Sen Jiangcdd52062017-05-18 15:33:10 -0700565 for (const auto& package : response_.packages) {
566 if (package.is_delta) {
567 return kPayloadTypeDelta;
568 }
David Zeuthen33bae492014-02-25 16:16:18 -0800569 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700570 OmahaRequestParams* params = system_state_->request_params();
571 if (params->delta_okay()) {
572 return kPayloadTypeFull;
573 }
574 // Full payload, delta was not allowed by request.
575 return kPayloadTypeForcedFull;
David Zeuthen33bae492014-02-25 16:16:18 -0800576}
577
578// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
579// metrics if the attempt ends abnormally, e.g. if the update_engine
580// process crashes or the device is rebooted. See
581// http://crbug.com/357676
582void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
583 int attempt_number = GetPayloadAttemptNumber();
584
585 PayloadType payload_type = CalculatePayloadType();
586
Sen Jiang0affc2c2017-02-10 15:55:05 -0800587 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800588
589 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
590
591 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700592 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
593 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800594 attempt_start_time_monotonic_;
595
596 int64_t payload_download_speed_bps = 0;
597 int64_t usec = duration_uptime.InMicroseconds();
598 if (usec > 0) {
599 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
600 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
601 payload_download_speed_bps = static_cast<int64_t>(bps);
602 }
603
604 DownloadSource download_source = current_download_source_;
605
606 metrics::DownloadErrorCode payload_download_error_code =
607 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700608 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800609 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800610
611 // Add additional detail to AttemptResult
612 switch (attempt_result) {
613 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800614 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800615 break;
616
617 case metrics::AttemptResult::kInternalError:
618 internal_error_code = code;
619 break;
620
621 // Explicit fall-through for cases where we do not have additional
622 // detail. We avoid the default keyword to force people adding new
623 // AttemptResult values to visit this code and examine whether
624 // additional detail is needed.
625 case metrics::AttemptResult::kUpdateSucceeded:
626 case metrics::AttemptResult::kMetadataMalformed:
627 case metrics::AttemptResult::kOperationMalformed:
628 case metrics::AttemptResult::kOperationExecutionError:
629 case metrics::AttemptResult::kMetadataVerificationFailed:
630 case metrics::AttemptResult::kPayloadVerificationFailed:
631 case metrics::AttemptResult::kVerificationFailed:
632 case metrics::AttemptResult::kPostInstallFailed:
633 case metrics::AttemptResult::kAbnormalTermination:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800634 case metrics::AttemptResult::kUpdateCanceled:
David Zeuthen33bae492014-02-25 16:16:18 -0800635 case metrics::AttemptResult::kNumConstants:
636 case metrics::AttemptResult::kUnset:
637 break;
638 }
639
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700640 system_state_->metrics_reporter()->ReportUpdateAttemptMetrics(
641 system_state_,
642 attempt_number,
643 payload_type,
644 duration,
645 duration_uptime,
646 payload_size,
647 payload_bytes_downloaded,
648 payload_download_speed_bps,
649 download_source,
650 attempt_result,
651 internal_error_code,
652 payload_download_error_code,
653 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800654}
655
David Zeuthen4e1d1492014-04-25 13:12:27 -0700656void PayloadState::PersistAttemptMetrics() {
657 // TODO(zeuthen): For now we only persist whether an attempt was in
658 // progress and not values/metrics related to the attempt. This
659 // means that when this happens, of all the UpdateEngine.Attempt.*
660 // metrics, only UpdateEngine.Attempt.Result is reported (with the
661 // value |kAbnormalTermination|). In the future we might want to
662 // persist more data so we can report other metrics in the
663 // UpdateEngine.Attempt.* namespace when this happens.
664 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
665}
666
667void PayloadState::ClearPersistedAttemptMetrics() {
668 prefs_->Delete(kPrefsAttemptInProgress);
669}
670
671void PayloadState::ReportAndClearPersistedAttemptMetrics() {
672 bool attempt_in_progress = false;
673 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
674 return;
675 if (!attempt_in_progress)
676 return;
677
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700678 system_state_->metrics_reporter()
679 ->ReportAbnormallyTerminatedUpdateAttemptMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700680
681 ClearPersistedAttemptMetrics();
682}
683
David Zeuthen33bae492014-02-25 16:16:18 -0800684void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700685 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800686
687 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800688 int64_t total_bytes_by_source[kNumDownloadSources];
689 int64_t successful_bytes = 0;
690 int64_t total_bytes = 0;
691 int64_t successful_mbs = 0;
692 int64_t total_mbs = 0;
693
Jay Srinivasan19409b72013-04-12 19:23:36 -0700694 for (int i = 0; i < kNumDownloadSources; i++) {
695 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800696 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700697
David Zeuthen44848602013-06-24 13:32:14 -0700698 // Only consider this download source (and send byte counts) as
699 // having been used if we downloaded a non-trivial amount of bytes
700 // (e.g. at least 1 MiB) that contributed to the final success of
701 // the update. Otherwise we're going to end up with a lot of
702 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700703
David Zeuthen33bae492014-02-25 16:16:18 -0800704 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800705 successful_bytes += bytes;
706 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700707 SetCurrentBytesDownloaded(source, 0, true);
708
David Zeuthen33bae492014-02-25 16:16:18 -0800709 bytes = GetTotalBytesDownloaded(source);
710 total_bytes_by_source[i] = bytes;
711 total_bytes += bytes;
712 total_mbs += bytes / kNumBytesInOneMiB;
713 SetTotalBytesDownloaded(source, 0, true);
714 }
715
716 int download_overhead_percentage = 0;
717 if (successful_bytes > 0) {
718 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
719 successful_bytes;
720 }
721
722 int url_switch_count = static_cast<int>(url_switch_count_);
723
724 int reboot_count = GetNumReboots();
725
726 SetNumReboots(0);
727
728 TimeDelta duration = GetUpdateDuration();
David Zeuthen33bae492014-02-25 16:16:18 -0800729
730 prefs_->Delete(kPrefsUpdateTimestampStart);
731 prefs_->Delete(kPrefsUpdateDurationUptime);
732
733 PayloadType payload_type = CalculatePayloadType();
734
Sen Jiang0affc2c2017-02-10 15:55:05 -0800735 int64_t payload_size = GetPayloadSize();
David Zeuthen33bae492014-02-25 16:16:18 -0800736
737 int attempt_count = GetPayloadAttemptNumber();
738
739 int updates_abandoned_count = num_responses_seen_ - 1;
740
Tianjie Xu282aa1f2017-09-05 13:42:45 -0700741 system_state_->metrics_reporter()->ReportSuccessfulUpdateMetrics(
742 attempt_count,
743 updates_abandoned_count,
744 payload_type,
745 payload_size,
746 total_bytes_by_source,
747 download_overhead_percentage,
748 duration,
749 reboot_count,
750 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700751}
752
753void PayloadState::UpdateNumReboots() {
754 // We only update the reboot count when the system has been detected to have
755 // been rebooted.
756 if (!system_state_->system_rebooted()) {
757 return;
758 }
759
760 SetNumReboots(GetNumReboots() + 1);
761}
762
763void PayloadState::SetNumReboots(uint32_t num_reboots) {
764 CHECK(prefs_);
765 num_reboots_ = num_reboots;
766 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
767 LOG(INFO) << "Number of Reboots during current update attempt = "
768 << num_reboots_;
769}
770
Jay Srinivasan08262882012-12-28 19:29:43 -0800771void PayloadState::ResetPersistedState() {
772 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700773 SetFullPayloadAttemptNumber(0);
Sen Jiang97eba342017-05-22 14:34:11 -0700774 SetPayloadIndex(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800775 SetUrlIndex(0);
776 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700777 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700778 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700779 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700780 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700781 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700782 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700783 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700784 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700785 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700786 SetScatteringWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700787}
788
789void PayloadState::ResetRollbackVersion() {
790 CHECK(powerwash_safe_prefs_);
791 rollback_version_ = "";
792 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700793}
794
795void PayloadState::ResetDownloadSourcesOnNewUpdate() {
796 for (int i = 0; i < kNumDownloadSources; i++) {
797 DownloadSource source = static_cast<DownloadSource>(i);
798 SetCurrentBytesDownloaded(source, 0, true);
799 // Note: Not resetting the TotalBytesDownloaded as we want that metric
800 // to count the bytes downloaded across various update attempts until
801 // we have successfully applied the update.
802 }
803}
804
Chris Sosab3dcdb32013-09-04 15:22:12 -0700805int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700806 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700807 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700808 return 0;
809
810 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700811 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700812 return 0;
813
814 if (stored_value < 0) {
815 LOG(ERROR) << key << ": Invalid value (" << stored_value
816 << ") in persisted state. Defaulting to 0";
817 return 0;
818 }
819
820 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800821}
822
823string PayloadState::CalculateResponseSignature() {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800824 string response_sign;
825 for (size_t i = 0; i < response_.packages.size(); i++) {
826 const auto& package = response_.packages[i];
827 response_sign += base::StringPrintf(
828 "Payload %zu:\n"
829 " Size = %ju\n"
830 " Sha256 Hash = %s\n"
831 " Metadata Size = %ju\n"
832 " Metadata Signature = %s\n"
Sen Jiangcdd52062017-05-18 15:33:10 -0700833 " Is Delta = %d\n"
Sen Jiang0affc2c2017-02-10 15:55:05 -0800834 " NumURLs = %zu\n",
835 i,
836 static_cast<uintmax_t>(package.size),
837 package.hash.c_str(),
838 static_cast<uintmax_t>(package.metadata_size),
839 package.metadata_signature.c_str(),
Sen Jiangcdd52062017-05-18 15:33:10 -0700840 package.is_delta,
Sen Jiang0affc2c2017-02-10 15:55:05 -0800841 candidate_urls_[i].size());
Jay Srinivasan08262882012-12-28 19:29:43 -0800842
Sen Jiang0affc2c2017-02-10 15:55:05 -0800843 for (size_t j = 0; j < candidate_urls_[i].size(); j++)
844 response_sign += base::StringPrintf(
845 " Candidate Url%zu = %s\n", j, candidate_urls_[i][j].c_str());
846 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800847
Alex Vakulenko75039d72014-03-25 12:36:28 -0700848 response_sign += base::StringPrintf(
Alex Vakulenko75039d72014-03-25 12:36:28 -0700849 "Max Failure Count Per Url = %d\n"
850 "Disable Payload Backoff = %d\n",
Alex Vakulenko75039d72014-03-25 12:36:28 -0700851 response_.max_failure_count_per_url,
852 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800853 return response_sign;
854}
855
856void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800857 CHECK(prefs_);
858 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800859 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
860 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
861 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800862 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800863}
864
Jay Srinivasan19409b72013-04-12 19:23:36 -0700865void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800866 CHECK(prefs_);
867 response_signature_ = response_signature;
868 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
869 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
870}
871
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800872void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700873 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800874}
875
Alex Deymo820cc702013-06-28 15:43:46 -0700876void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700877 SetFullPayloadAttemptNumber(GetPersistedValue(
878 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700879}
880
881void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800882 CHECK(prefs_);
883 payload_attempt_number_ = payload_attempt_number;
884 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
885 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
886}
887
Alex Deymo820cc702013-06-28 15:43:46 -0700888void PayloadState::SetFullPayloadAttemptNumber(
889 int full_payload_attempt_number) {
890 CHECK(prefs_);
891 full_payload_attempt_number_ = full_payload_attempt_number;
892 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
893 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
894 full_payload_attempt_number_);
895}
896
Sen Jiang5ae865b2017-04-18 14:24:40 -0700897void PayloadState::SetPayloadIndex(size_t payload_index) {
898 CHECK(prefs_);
899 payload_index_ = payload_index;
900 LOG(INFO) << "Payload Index = " << payload_index_;
901 prefs_->SetInt64(kPrefsUpdateStatePayloadIndex, payload_index_);
902}
903
904bool PayloadState::NextPayload() {
905 if (payload_index_ + 1 >= candidate_urls_.size())
906 return false;
907 SetPayloadIndex(payload_index_ + 1);
908 return true;
909}
910
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800911void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700912 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800913}
914
915void PayloadState::SetUrlIndex(uint32_t url_index) {
916 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800917 url_index_ = url_index;
918 LOG(INFO) << "Current URL Index = " << url_index_;
919 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700920
921 // Also update the download source, which is purely dependent on the
922 // current URL index alone.
923 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800924}
925
Gilad Arnold519cfc72014-10-02 10:34:54 -0700926void PayloadState::LoadScatteringWaitPeriod() {
927 SetScatteringWaitPeriod(
928 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
929}
930
Alex Deymof329b932014-10-30 01:37:48 -0700931void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700932 CHECK(prefs_);
933 scattering_wait_period_ = wait_period;
934 LOG(INFO) << "Scattering Wait Period (seconds) = "
935 << scattering_wait_period_.InSeconds();
936 if (scattering_wait_period_.InSeconds() > 0) {
937 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
938 scattering_wait_period_.InSeconds());
939 } else {
940 prefs_->Delete(kPrefsWallClockWaitPeriod);
941 }
942}
943
David Zeuthencc6f9962013-04-18 11:57:24 -0700944void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700945 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700946}
947
948void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
949 CHECK(prefs_);
950 url_switch_count_ = url_switch_count;
951 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
952 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
953}
954
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800955void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700956 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800957}
958
959void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
960 CHECK(prefs_);
961 url_failure_count_ = url_failure_count;
962 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
963 << ")'s Failure Count = " << url_failure_count_;
964 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800965}
966
Jay Srinivasan08262882012-12-28 19:29:43 -0800967void PayloadState::LoadBackoffExpiryTime() {
968 CHECK(prefs_);
969 int64_t stored_value;
970 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
971 return;
972
973 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
974 return;
975
976 Time stored_time = Time::FromInternalValue(stored_value);
977 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
978 LOG(ERROR) << "Invalid backoff expiry time ("
979 << utils::ToString(stored_time)
980 << ") in persisted state. Resetting.";
981 stored_time = Time();
982 }
983 SetBackoffExpiryTime(stored_time);
984}
985
986void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
987 CHECK(prefs_);
988 backoff_expiry_time_ = new_time;
989 LOG(INFO) << "Backoff Expiry Time = "
990 << utils::ToString(backoff_expiry_time_);
991 prefs_->SetInt64(kPrefsBackoffExpiryTime,
992 backoff_expiry_time_.ToInternalValue());
993}
994
David Zeuthen9a017f22013-04-11 16:10:26 -0700995TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700996 Time end_time = update_timestamp_end_.is_null()
997 ? system_state_->clock()->GetWallclockTime() :
998 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700999 return end_time - update_timestamp_start_;
1000}
1001
1002void PayloadState::LoadUpdateTimestampStart() {
1003 int64_t stored_value;
1004 Time stored_time;
1005
1006 CHECK(prefs_);
1007
David Zeuthenf413fe52013-04-22 14:04:39 -07001008 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001009
1010 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
1011 // The preference missing is not unexpected - in that case, just
1012 // use the current time as start time
1013 stored_time = now;
1014 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
1015 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
1016 stored_time = now;
1017 } else {
1018 stored_time = Time::FromInternalValue(stored_value);
1019 }
1020
1021 // Sanity check: If the time read from disk is in the future
1022 // (modulo some slack to account for possible NTP drift
1023 // adjustments), something is fishy and we should report and
1024 // reset.
1025 TimeDelta duration_according_to_stored_time = now - stored_time;
1026 if (duration_according_to_stored_time < -kDurationSlack) {
1027 LOG(ERROR) << "The UpdateTimestampStart value ("
1028 << utils::ToString(stored_time)
1029 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001030 << utils::FormatTimeDelta(duration_according_to_stored_time)
1031 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001032 stored_time = now;
1033 }
1034
1035 SetUpdateTimestampStart(stored_time);
1036}
1037
1038void PayloadState::SetUpdateTimestampStart(const Time& value) {
1039 CHECK(prefs_);
1040 update_timestamp_start_ = value;
1041 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1042 update_timestamp_start_.ToInternalValue());
1043 LOG(INFO) << "Update Timestamp Start = "
1044 << utils::ToString(update_timestamp_start_);
1045}
1046
1047void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1048 update_timestamp_end_ = value;
1049 LOG(INFO) << "Update Timestamp End = "
1050 << utils::ToString(update_timestamp_end_);
1051}
1052
1053TimeDelta PayloadState::GetUpdateDurationUptime() {
1054 return update_duration_uptime_;
1055}
1056
1057void PayloadState::LoadUpdateDurationUptime() {
1058 int64_t stored_value;
1059 TimeDelta stored_delta;
1060
1061 CHECK(prefs_);
1062
1063 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1064 // The preference missing is not unexpected - in that case, just
1065 // we'll use zero as the delta
1066 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1067 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1068 stored_delta = TimeDelta::FromSeconds(0);
1069 } else {
1070 stored_delta = TimeDelta::FromInternalValue(stored_value);
1071 }
1072
1073 // Sanity-check: Uptime can never be greater than the wall-clock
1074 // difference (modulo some slack). If it is, report and reset
1075 // to the wall-clock difference.
1076 TimeDelta diff = GetUpdateDuration() - stored_delta;
1077 if (diff < -kDurationSlack) {
1078 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001079 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001080 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001081 << utils::FormatTimeDelta(diff)
1082 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001083 stored_delta = update_duration_current_;
1084 }
1085
1086 SetUpdateDurationUptime(stored_delta);
1087}
1088
Chris Sosabe45bef2013-04-09 18:25:12 -07001089void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001090 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001091}
1092
1093void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001094 CHECK(powerwash_safe_prefs_);
1095 string rollback_version;
1096 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1097 &rollback_version)) {
1098 SetRollbackVersion(rollback_version);
1099 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001100}
1101
1102void PayloadState::SetRollbackVersion(const string& rollback_version) {
1103 CHECK(powerwash_safe_prefs_);
1104 LOG(INFO) << "Blacklisting version "<< rollback_version;
1105 rollback_version_ = rollback_version;
1106 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001107}
1108
David Zeuthen9a017f22013-04-11 16:10:26 -07001109void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1110 const Time& timestamp,
1111 bool use_logging) {
1112 CHECK(prefs_);
1113 update_duration_uptime_ = value;
1114 update_duration_uptime_timestamp_ = timestamp;
1115 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1116 update_duration_uptime_.ToInternalValue());
1117 if (use_logging) {
1118 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001119 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001120 }
1121}
1122
1123void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001124 Time now = system_state_->clock()->GetMonotonicTime();
1125 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001126}
1127
1128void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001129 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001130 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1131 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1132 // We're frequently called so avoid logging this write
1133 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1134}
1135
Jay Srinivasan19409b72013-04-12 19:23:36 -07001136string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1137 return prefix + "-from-" + utils::ToString(source);
1138}
1139
1140void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1141 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001142 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001143}
1144
1145void PayloadState::SetCurrentBytesDownloaded(
1146 DownloadSource source,
1147 uint64_t current_bytes_downloaded,
1148 bool log) {
1149 CHECK(prefs_);
1150
1151 if (source >= kNumDownloadSources)
1152 return;
1153
1154 // Update the in-memory value.
1155 current_bytes_downloaded_[source] = current_bytes_downloaded;
1156
1157 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1158 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1159 LOG_IF(INFO, log) << "Current bytes downloaded for "
1160 << utils::ToString(source) << " = "
1161 << GetCurrentBytesDownloaded(source);
1162}
1163
1164void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1165 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001166 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001167}
1168
1169void PayloadState::SetTotalBytesDownloaded(
1170 DownloadSource source,
1171 uint64_t total_bytes_downloaded,
1172 bool log) {
1173 CHECK(prefs_);
1174
1175 if (source >= kNumDownloadSources)
1176 return;
1177
1178 // Update the in-memory value.
1179 total_bytes_downloaded_[source] = total_bytes_downloaded;
1180
1181 // Persist.
1182 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1183 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1184 LOG_IF(INFO, log) << "Total bytes downloaded for "
1185 << utils::ToString(source) << " = "
1186 << GetTotalBytesDownloaded(source);
1187}
1188
David Zeuthena573d6f2013-06-14 16:13:36 -07001189void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001190 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001191}
1192
1193void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1194 CHECK(prefs_);
1195 num_responses_seen_ = num_responses_seen;
1196 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1197 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1198}
1199
Jay Srinivasan53173b92013-05-17 17:13:01 -07001200void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001201 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001202
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001203 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001204 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001205 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001206 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1207 } else {
1208 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1209 http_url_ok = true;
1210 }
1211
1212 candidate_urls_.clear();
Sen Jiang0affc2c2017-02-10 15:55:05 -08001213 for (const auto& package : response_.packages) {
1214 candidate_urls_.emplace_back();
1215 for (const string& candidate_url : package.payload_urls) {
1216 if (base::StartsWith(
1217 candidate_url, "http://", base::CompareCase::INSENSITIVE_ASCII) &&
1218 !http_url_ok) {
1219 continue;
1220 }
1221 candidate_urls_.back().push_back(candidate_url);
1222 LOG(INFO) << "Candidate Url" << (candidate_urls_.back().size() - 1)
1223 << ": " << candidate_url;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001224 }
Sen Jiang0affc2c2017-02-10 15:55:05 -08001225 LOG(INFO) << "Found " << candidate_urls_.back().size() << " candidate URLs "
1226 << "out of " << package.payload_urls.size()
1227 << " URLs supplied in package " << candidate_urls_.size() - 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001228 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001229}
1230
David Zeuthene4c58bf2013-06-18 17:26:50 -07001231void PayloadState::CreateSystemUpdatedMarkerFile() {
1232 CHECK(prefs_);
1233 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1234 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1235}
1236
1237void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1238 // Send |time_to_reboot| as a UMA stat.
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001239 system_state_->metrics_reporter()->ReportTimeToReboot(
1240 time_to_reboot.InMinutes());
David Zeuthene4c58bf2013-06-18 17:26:50 -07001241}
1242
1243void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001244 // Flush previous state from abnormal attempt failure, if any.
1245 ReportAndClearPersistedAttemptMetrics();
1246
Alex Deymo569c4242013-07-24 12:01:01 -07001247 // Avoid the UpdateEngineStarted actions if this is not the first time we
1248 // run the update engine since reboot.
1249 if (!system_state_->system_rebooted())
1250 return;
1251
David Zeuthene4c58bf2013-06-18 17:26:50 -07001252 // Figure out if we just booted into a new update
1253 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1254 int64_t stored_value;
1255 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1256 Time system_updated_at = Time::FromInternalValue(stored_value);
1257 if (!system_updated_at.is_null()) {
1258 TimeDelta time_to_reboot =
1259 system_state_->clock()->GetWallclockTime() - system_updated_at;
1260 if (time_to_reboot.ToInternalValue() < 0) {
1261 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1262 << utils::ToString(system_updated_at);
1263 } else {
1264 BootedIntoUpdate(time_to_reboot);
1265 }
1266 }
1267 }
1268 prefs_->Delete(kPrefsSystemUpdatedMarker);
1269 }
Alex Deymo42432912013-07-12 20:21:15 -07001270 // Check if it is needed to send metrics about a failed reboot into a new
1271 // version.
1272 ReportFailedBootIfNeeded();
1273}
1274
1275void PayloadState::ReportFailedBootIfNeeded() {
1276 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1277 // payload was marked as ready immediately before the last reboot, and we
1278 // need to check if such payload successfully rebooted or not.
1279 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001280 int64_t installed_from = 0;
1281 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001282 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1283 return;
1284 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001285 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1286 // partition number. We are now using slot numbers (0 or 1) instead, so
1287 // the following comparison will not match if we are comparing an old
1288 // partition number against a new slot number, which is the correct outcome
1289 // since we successfully booted the new update in that case. If the boot
1290 // failed, we will read this value from the same version, so it will always
1291 // be compatible.
1292 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001293 // A reboot was pending, but the chromebook is again in the same
1294 // BootDevice where the update was installed from.
1295 int64_t target_attempt;
1296 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1297 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1298 "TargetVersionInstalledFrom was present.";
1299 target_attempt = 1;
1300 }
1301
1302 // Report the UMA metric of the current boot failure.
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001303 system_state_->metrics_reporter()->ReportFailedUpdateCount(
1304 target_attempt);
Alex Deymo42432912013-07-12 20:21:15 -07001305 } else {
1306 prefs_->Delete(kPrefsTargetVersionAttempt);
1307 prefs_->Delete(kPrefsTargetVersionUniqueId);
1308 }
1309 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1310 }
1311}
1312
1313void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1314 // Expect to boot into the new partition in the next reboot setting the
1315 // TargetVersion* flags in the Prefs.
1316 string stored_target_version_uid;
1317 string target_version_id;
1318 string target_partition;
1319 int64_t target_attempt;
1320
1321 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1322 prefs_->GetString(kPrefsTargetVersionUniqueId,
1323 &stored_target_version_uid) &&
1324 stored_target_version_uid == target_version_uid) {
1325 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1326 target_attempt = 0;
1327 } else {
1328 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1329 target_attempt = 0;
1330 }
1331 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1332
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001333 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001334 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001335}
1336
1337void PayloadState::ResetUpdateStatus() {
1338 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1339 // rebooted the next boot is not flagged as failed to rebooted into the
1340 // new applied payload.
1341 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1342
1343 // Also decrement the attempt number if it exists.
1344 int64_t target_attempt;
1345 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001346 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001347}
1348
David Zeuthendcba8092013-08-06 12:16:35 -07001349int PayloadState::GetP2PNumAttempts() {
1350 return p2p_num_attempts_;
1351}
1352
1353void PayloadState::SetP2PNumAttempts(int value) {
1354 p2p_num_attempts_ = value;
1355 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1356 CHECK(prefs_);
1357 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1358}
1359
1360void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001361 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001362}
1363
1364Time PayloadState::GetP2PFirstAttemptTimestamp() {
1365 return p2p_first_attempt_timestamp_;
1366}
1367
1368void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1369 p2p_first_attempt_timestamp_ = time;
1370 LOG(INFO) << "p2p First Attempt Timestamp = "
1371 << utils::ToString(p2p_first_attempt_timestamp_);
1372 CHECK(prefs_);
1373 int64_t stored_value = time.ToInternalValue();
1374 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1375}
1376
1377void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001378 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001379 Time stored_time = Time::FromInternalValue(stored_value);
1380 SetP2PFirstAttemptTimestamp(stored_time);
1381}
1382
1383void PayloadState::P2PNewAttempt() {
1384 CHECK(prefs_);
1385 // Set timestamp, if it hasn't been set already
1386 if (p2p_first_attempt_timestamp_.is_null()) {
1387 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1388 }
1389 // Increase number of attempts
1390 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1391}
1392
1393bool PayloadState::P2PAttemptAllowed() {
1394 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1395 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1396 << " which is greater than "
1397 << kMaxP2PAttempts
1398 << " - disallowing p2p.";
1399 return false;
1400 }
1401
1402 if (!p2p_first_attempt_timestamp_.is_null()) {
1403 Time now = system_state_->clock()->GetWallclockTime();
1404 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1405 if (time_spent_attempting_p2p.InSeconds() < 0) {
1406 LOG(ERROR) << "Time spent attempting p2p is negative"
1407 << " - disallowing p2p.";
1408 return false;
1409 }
1410 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1411 LOG(INFO) << "Time spent attempting p2p is "
1412 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1413 << " which is greater than "
1414 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1415 kMaxP2PAttemptTimeSeconds))
1416 << " - disallowing p2p.";
1417 return false;
1418 }
1419 }
1420
1421 return true;
1422}
1423
Sen Jiang0affc2c2017-02-10 15:55:05 -08001424int64_t PayloadState::GetPayloadSize() {
1425 int64_t payload_size = 0;
1426 for (const auto& package : response_.packages)
1427 payload_size += package.size;
1428 return payload_size;
1429}
1430
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001431} // namespace chromeos_update_engine