blob: 846f9015aa77eaf827ca9d082a2e90c544d44c7e [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080016
17#include "update_engine/payload_state.h"
18
Jay Srinivasan08262882012-12-28 19:29:43 -080019#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070020#include <string>
Jay Srinivasan08262882012-12-28 19:29:43 -080021
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080022#include <base/logging.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070023#include <base/strings/string_util.h>
24#include <base/strings/stringprintf.h>
Alex Deymoa2591792015-11-17 00:39:40 -030025#include <metrics/metrics_library.h>
Gilad Arnold1f847232014-04-07 12:07:49 -070026#include <policy/device_policy.h>
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080027
Alex Deymo39910dc2015-11-09 17:04:30 -080028#include "update_engine/common/clock.h"
29#include "update_engine/common/constants.h"
Alex Deymoe88e9fe2016-02-03 16:38:00 -080030#include "update_engine/common/error_code_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080031#include "update_engine/common/hardware_interface.h"
32#include "update_engine/common/prefs.h"
33#include "update_engine/common/utils.h"
Sen Jiang255e22b2016-05-20 16:15:29 -070034#include "update_engine/connection_manager_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080035#include "update_engine/metrics_utils.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070036#include "update_engine/omaha_request_params.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080037#include "update_engine/payload_consumer/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070038#include "update_engine/system_state.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080039
Jay Srinivasan08262882012-12-28 19:29:43 -080040using base::Time;
41using base::TimeDelta;
42using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080043using std::string;
44
45namespace chromeos_update_engine {
46
David Zeuthen9a017f22013-04-11 16:10:26 -070047const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
48
Jay Srinivasan08262882012-12-28 19:29:43 -080049// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070050static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080051
Jay Srinivasan08262882012-12-28 19:29:43 -080052// We want to randomize retry attempts after the backoff by +/- 6 hours.
53static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080054
Jay Srinivasan19409b72013-04-12 19:23:36 -070055PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070056 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070057 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070058 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070059 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070060 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070061 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070062 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070063 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070064 attempt_num_bytes_downloaded_(0),
65 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Shuqian Zhao29971732016-02-05 11:29:32 -080066 attempt_error_code_(ErrorCode::kSuccess),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070067 attempt_type_(AttemptType::kUpdate) {
68 for (int i = 0; i <= kNumDownloadSources; i++)
69 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070070}
71
72bool PayloadState::Initialize(SystemState* system_state) {
73 system_state_ = system_state;
74 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070075 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080076 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080077 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070078 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080079 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080080 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070081 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080082 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070083 LoadUpdateTimestampStart();
84 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
85 // being called before it. Don't reorder.
86 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070087 for (int i = 0; i < kNumDownloadSources; i++) {
88 DownloadSource source = static_cast<DownloadSource>(i);
89 LoadCurrentBytesDownloaded(source);
90 LoadTotalBytesDownloaded(source);
91 }
Chris Sosabe45bef2013-04-09 18:25:12 -070092 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070093 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070094 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070095 LoadP2PFirstAttemptTimestamp();
96 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080097 return true;
98}
99
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800100void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800101 // Always store the latest response.
102 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800103
Jay Srinivasan53173b92013-05-17 17:13:01 -0700104 // Compute the candidate URLs first as they are used to calculate the
105 // response signature so that a change in enterprise policy for
106 // HTTP downloads being enabled or not could be honored as soon as the
107 // next update check happens.
108 ComputeCandidateUrls();
109
Jay Srinivasan08262882012-12-28 19:29:43 -0800110 // Check if the "signature" of this response (i.e. the fields we care about)
111 // has changed.
112 string new_response_signature = CalculateResponseSignature();
113 bool has_response_changed = (response_signature_ != new_response_signature);
114
115 // If the response has changed, we should persist the new signature and
116 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800117 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800118 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700119 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800120 SetResponseSignature(new_response_signature);
121 ResetPersistedState();
122 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800123 }
124
Jay Srinivasan08262882012-12-28 19:29:43 -0800125 // This is the earliest point at which we can validate whether the URL index
126 // we loaded from the persisted state is a valid value. If the response
127 // hasn't changed but the URL index is invalid, it's indicative of some
128 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700129 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800130 LOG(INFO) << "Resetting all payload state as the url index seems to have "
131 "been tampered with";
132 ResetPersistedState();
133 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800134 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700135
136 // Update the current download source which depends on the latest value of
137 // the response.
138 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800139}
140
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700141void PayloadState::SetUsingP2PForDownloading(bool value) {
142 using_p2p_for_downloading_ = value;
143 // Update the current download source which depends on whether we are
144 // using p2p or not.
145 UpdateCurrentDownloadSource();
146}
147
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800148void PayloadState::DownloadComplete() {
149 LOG(INFO) << "Payload downloaded successfully";
150 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700151 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800152}
153
154void PayloadState::DownloadProgress(size_t count) {
155 if (count == 0)
156 return;
157
David Zeuthen9a017f22013-04-11 16:10:26 -0700158 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700159 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700160
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800161 // We've received non-zero bytes from a recent download operation. Since our
162 // URL failure count is meant to penalize a URL only for consecutive
163 // failures, downloading bytes successfully means we should reset the failure
164 // count (as we know at least that the URL is working). In future, we can
165 // design this to be more sophisticated to check for more intelligent failure
166 // patterns, but right now, even 1 byte downloaded will mark the URL to be
167 // good unless it hits 10 (or configured number of) consecutive failures
168 // again.
169
170 if (GetUrlFailureCount() == 0)
171 return;
172
173 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
174 << " to 0 as we received " << count << " bytes successfully";
175 SetUrlFailureCount(0);
176}
177
David Zeuthenafed4a12014-04-09 15:28:44 -0700178void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700179 // Flush previous state from abnormal attempt failure, if any.
180 ReportAndClearPersistedAttemptMetrics();
181
David Zeuthenafed4a12014-04-09 15:28:44 -0700182 attempt_type_ = attempt_type;
183
David Zeuthen33bae492014-02-25 16:16:18 -0800184 ClockInterface *clock = system_state_->clock();
185 attempt_start_time_boot_ = clock->GetBootTime();
186 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800187 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700188
189 metrics::ConnectionType type;
Sen Jiang255e22b2016-05-20 16:15:29 -0700190 ConnectionType network_connection_type;
191 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700192 ConnectionManagerInterface* connection_manager =
193 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700194 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700195 &tethering)) {
196 LOG(ERROR) << "Failed to determine connection type.";
197 type = metrics::ConnectionType::kUnknown;
198 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800199 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700200 }
201 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700202
203 if (attempt_type == AttemptType::kUpdate)
204 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800205}
206
Chris Sosabe45bef2013-04-09 18:25:12 -0700207void PayloadState::UpdateResumed() {
208 LOG(INFO) << "Resuming an update that was previously started.";
209 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700210 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700211}
212
Jay Srinivasan19409b72013-04-12 19:23:36 -0700213void PayloadState::UpdateRestarted() {
214 LOG(INFO) << "Starting a new update";
215 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700216 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700217 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700218}
219
David Zeuthen9a017f22013-04-11 16:10:26 -0700220void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700221 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700222 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700223 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800224
David Zeuthen96197df2014-04-16 12:22:39 -0700225 switch (attempt_type_) {
226 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700227 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700228 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700229 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700230 break;
231
232 case AttemptType::kRollback:
233 metrics::ReportRollbackMetrics(system_state_,
234 metrics::RollbackResult::kSuccess);
235 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700236 }
Shuqian Zhao29971732016-02-05 11:29:32 -0800237 attempt_error_code_ = ErrorCode::kSuccess;
David Zeuthena573d6f2013-06-14 16:13:36 -0700238
239 // Reset the number of responses seen since it counts from the last
240 // successful update, e.g. now.
241 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700242
243 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700244}
245
David Zeuthena99981f2013-04-29 13:42:47 -0700246void PayloadState::UpdateFailed(ErrorCode error) {
247 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800248 LOG(INFO) << "Updating payload state for error code: " << base_error
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800249 << " (" << utils::ErrorCodeToString(base_error) << ")";
Shuqian Zhaocd486362016-03-04 19:07:40 -0800250 attempt_error_code_ = base_error;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800251
Jay Srinivasan53173b92013-05-17 17:13:01 -0700252 if (candidate_urls_.size() == 0) {
253 // This means we got this error even before we got a valid Omaha response
254 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800255 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800256 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
257 return;
258 }
259
David Zeuthen96197df2014-04-16 12:22:39 -0700260 switch (attempt_type_) {
261 case AttemptType::kUpdate:
262 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700263 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700264 break;
265
266 case AttemptType::kRollback:
267 metrics::ReportRollbackMetrics(system_state_,
268 metrics::RollbackResult::kFailed);
269 break;
270 }
David Zeuthen33bae492014-02-25 16:16:18 -0800271
Shuqian Zhao29971732016-02-05 11:29:32 -0800272
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800273 switch (base_error) {
274 // Errors which are good indicators of a problem with a particular URL or
275 // the protocol used in the URL or entities in the communication channel
276 // (e.g. proxies). We should try the next available URL in the next update
277 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700278 case ErrorCode::kPayloadHashMismatchError:
279 case ErrorCode::kPayloadSizeMismatchError:
280 case ErrorCode::kDownloadPayloadVerificationError:
281 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
282 case ErrorCode::kSignedDeltaPayloadExpectedError:
283 case ErrorCode::kDownloadInvalidMetadataMagicString:
284 case ErrorCode::kDownloadSignatureMissingInManifest:
285 case ErrorCode::kDownloadManifestParseError:
286 case ErrorCode::kDownloadMetadataSignatureError:
287 case ErrorCode::kDownloadMetadataSignatureVerificationError:
288 case ErrorCode::kDownloadMetadataSignatureMismatch:
289 case ErrorCode::kDownloadOperationHashVerificationError:
290 case ErrorCode::kDownloadOperationExecutionError:
291 case ErrorCode::kDownloadOperationHashMismatch:
292 case ErrorCode::kDownloadInvalidMetadataSize:
293 case ErrorCode::kDownloadInvalidMetadataSignature:
294 case ErrorCode::kDownloadOperationHashMissingError:
295 case ErrorCode::kDownloadMetadataSignatureMissingError:
296 case ErrorCode::kPayloadMismatchedType:
297 case ErrorCode::kUnsupportedMajorPayloadVersion:
298 case ErrorCode::kUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800299 IncrementUrlIndex();
300 break;
301
302 // Errors which seem to be just transient network/communication related
303 // failures and do not indicate any inherent problem with the URL itself.
304 // So, we should keep the current URL but just increment the
305 // failure count to give it more chances. This way, while we maximize our
306 // chances of downloading from the URLs that appear earlier in the response
307 // (because download from a local server URL that appears earlier in a
308 // response is preferable than downloading from the next URL which could be
309 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700310
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700311 case ErrorCode::kError:
312 case ErrorCode::kDownloadTransferError:
313 case ErrorCode::kDownloadWriteError:
314 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700315 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800316 IncrementFailureCount();
317 break;
318
319 // Errors which are not specific to a URL and hence shouldn't result in
320 // the URL being penalized. This can happen in two cases:
321 // 1. We haven't started downloading anything: These errors don't cost us
322 // anything in terms of actual payload bytes, so we should just do the
323 // regular retries at the next update check.
324 // 2. We have successfully downloaded the payload: In this case, the
325 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800326 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800327 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700328 case ErrorCode::kOmahaRequestError:
329 case ErrorCode::kOmahaResponseHandlerError:
330 case ErrorCode::kPostinstallRunnerError:
331 case ErrorCode::kFilesystemCopierError:
332 case ErrorCode::kInstallDeviceOpenError:
333 case ErrorCode::kKernelDeviceOpenError:
334 case ErrorCode::kDownloadNewPartitionInfoError:
335 case ErrorCode::kNewRootfsVerificationError:
336 case ErrorCode::kNewKernelVerificationError:
337 case ErrorCode::kPostinstallBootedFromFirmwareB:
338 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
339 case ErrorCode::kOmahaRequestEmptyResponseError:
340 case ErrorCode::kOmahaRequestXMLParseError:
341 case ErrorCode::kOmahaResponseInvalid:
342 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
343 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700344 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700345 case ErrorCode::kOmahaUpdateDeferredForBackoff:
346 case ErrorCode::kPostinstallPowerwashError:
347 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400348 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700349 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800350 case ErrorCode::kUserCanceled:
Weidong Guo4b0d6032017-04-17 10:08:38 -0700351 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800352 LOG(INFO) << "Not incrementing URL index or failure count for this error";
353 break;
354
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700355 case ErrorCode::kSuccess: // success code
356 case ErrorCode::kUmaReportedMax: // not an error code
357 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
358 case ErrorCode::kDevModeFlag: // not an error code
359 case ErrorCode::kResumedFlag: // not an error code
360 case ErrorCode::kTestImageFlag: // not an error code
361 case ErrorCode::kTestOmahaUrlFlag: // not an error code
362 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800363 // These shouldn't happen. Enumerating these explicitly here so that we
364 // can let the compiler warn about new error codes that are added to
365 // action_processor.h but not added here.
366 LOG(WARNING) << "Unexpected error code for UpdateFailed";
367 break;
368
369 // Note: Not adding a default here so as to let the compiler warn us of
370 // any new enums that were added in the .h but not listed in this switch.
371 }
372}
373
Jay Srinivasan08262882012-12-28 19:29:43 -0800374bool PayloadState::ShouldBackoffDownload() {
375 if (response_.disable_payload_backoff) {
376 LOG(INFO) << "Payload backoff logic is disabled. "
377 "Can proceed with the download";
378 return false;
379 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700380 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700381 LOG(INFO) << "Payload backoff logic is disabled because download "
382 << "will happen from local peer (via p2p).";
383 return false;
384 }
385 if (system_state_->request_params()->interactive()) {
386 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
387 return false;
388 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800389 if (response_.is_delta_payload) {
390 // If delta payloads fail, we want to fallback quickly to full payloads as
391 // they are more likely to succeed. Exponential backoffs would greatly
392 // slow down the fallback to full payloads. So we don't backoff for delta
393 // payloads.
394 LOG(INFO) << "No backoffs for delta payloads. "
395 << "Can proceed with the download";
396 return false;
397 }
398
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700399 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800400 // Backoffs are needed only for official builds. We do not want any delays
401 // or update failures due to backoffs during testing or development.
402 LOG(INFO) << "No backoffs for test/dev images. "
403 << "Can proceed with the download";
404 return false;
405 }
406
407 if (backoff_expiry_time_.is_null()) {
408 LOG(INFO) << "No backoff expiry time has been set. "
409 << "Can proceed with the download";
410 return false;
411 }
412
413 if (backoff_expiry_time_ < Time::Now()) {
414 LOG(INFO) << "The backoff expiry time ("
415 << utils::ToString(backoff_expiry_time_)
416 << ") has elapsed. Can proceed with the download";
417 return false;
418 }
419
420 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
421 << utils::ToString(backoff_expiry_time_);
422 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800423}
424
Chris Sosaaa18e162013-06-20 13:20:30 -0700425void PayloadState::Rollback() {
426 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700427 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700428}
429
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800430void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700431 // Update the payload attempt number for both payload types: full and delta.
432 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
433}
434
435void PayloadState::IncrementFullPayloadAttemptNumber() {
436 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800437 if (response_.is_delta_payload) {
438 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
439 return;
440 }
441
Alex Deymo29b51d92013-07-09 15:26:24 -0700442 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700443 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800444 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800445}
446
447void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800448 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700449 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800450 LOG(INFO) << "Incrementing the URL index for next attempt";
451 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800452 } else {
453 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700454 << "0 as we only have " << candidate_urls_.size()
455 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800456 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700457 IncrementPayloadAttemptNumber();
458 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800459 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800460
David Zeuthencc6f9962013-04-18 11:57:24 -0700461 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700462 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700463 SetUrlSwitchCount(url_switch_count_ + 1);
464
Jay Srinivasan08262882012-12-28 19:29:43 -0800465 // Whenever we update the URL index, we should also clear the URL failure
466 // count so we can start over fresh for the new URL.
467 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800468}
469
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800470void PayloadState::IncrementFailureCount() {
471 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800472 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800473 LOG(INFO) << "Incrementing the URL failure count";
474 SetUrlFailureCount(next_url_failure_count);
475 } else {
476 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
477 << ". Trying next available URL";
478 IncrementUrlIndex();
479 }
480}
481
Jay Srinivasan08262882012-12-28 19:29:43 -0800482void PayloadState::UpdateBackoffExpiryTime() {
483 if (response_.disable_payload_backoff) {
484 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
485 SetBackoffExpiryTime(Time());
486 return;
487 }
488
Alex Deymo820cc702013-06-28 15:43:46 -0700489 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800490 SetBackoffExpiryTime(Time());
491 return;
492 }
493
494 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700495 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800496 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700497 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700498 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800499
500 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
501 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700502 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800503
504 // The number of days is the minimum of 2 raised to (payload_attempt_number
505 // - 1) or kMaxBackoffDays.
506 num_days = min(num_days << power, kMaxBackoffDays);
507
508 // We don't want all retries to happen exactly at the same time when
509 // retrying after backoff. So add some random minutes to fuzz.
510 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
511 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
512 TimeDelta::FromMinutes(fuzz_minutes);
513 LOG(INFO) << "Incrementing the backoff expiry time by "
514 << utils::FormatTimeDelta(next_backoff_interval);
515 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
516}
517
Jay Srinivasan19409b72013-04-12 19:23:36 -0700518void PayloadState::UpdateCurrentDownloadSource() {
519 current_download_source_ = kNumDownloadSources;
520
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700521 if (using_p2p_for_downloading_) {
522 current_download_source_ = kDownloadSourceHttpPeer;
523 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700524 string current_url = candidate_urls_[GetUrlIndex()];
Alex Vakulenko0103c362016-01-20 07:56:15 -0800525 if (base::StartsWith(current_url, "https://",
526 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700527 current_download_source_ = kDownloadSourceHttpsServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800528 } else if (base::StartsWith(current_url, "http://",
529 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700530 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800531 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700532 }
533
534 LOG(INFO) << "Current download source: "
535 << utils::ToString(current_download_source_);
536}
537
538void PayloadState::UpdateBytesDownloaded(size_t count) {
539 SetCurrentBytesDownloaded(
540 current_download_source_,
541 GetCurrentBytesDownloaded(current_download_source_) + count,
542 false);
543 SetTotalBytesDownloaded(
544 current_download_source_,
545 GetTotalBytesDownloaded(current_download_source_) + count,
546 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800547
548 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700549}
550
David Zeuthen33bae492014-02-25 16:16:18 -0800551PayloadType PayloadState::CalculatePayloadType() {
552 PayloadType payload_type;
553 OmahaRequestParams* params = system_state_->request_params();
554 if (response_.is_delta_payload) {
555 payload_type = kPayloadTypeDelta;
556 } else if (params->delta_okay()) {
557 payload_type = kPayloadTypeFull;
558 } else { // Full payload, delta was not allowed by request.
559 payload_type = kPayloadTypeForcedFull;
560 }
561 return payload_type;
562}
563
564// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
565// metrics if the attempt ends abnormally, e.g. if the update_engine
566// process crashes or the device is rebooted. See
567// http://crbug.com/357676
568void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
569 int attempt_number = GetPayloadAttemptNumber();
570
571 PayloadType payload_type = CalculatePayloadType();
572
573 int64_t payload_size = response_.size;
574
575 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
576
577 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700578 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
579 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800580 attempt_start_time_monotonic_;
581
582 int64_t payload_download_speed_bps = 0;
583 int64_t usec = duration_uptime.InMicroseconds();
584 if (usec > 0) {
585 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
586 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
587 payload_download_speed_bps = static_cast<int64_t>(bps);
588 }
589
590 DownloadSource download_source = current_download_source_;
591
592 metrics::DownloadErrorCode payload_download_error_code =
593 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700594 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800595 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800596
597 // Add additional detail to AttemptResult
598 switch (attempt_result) {
599 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800600 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800601 break;
602
603 case metrics::AttemptResult::kInternalError:
604 internal_error_code = code;
605 break;
606
607 // Explicit fall-through for cases where we do not have additional
608 // detail. We avoid the default keyword to force people adding new
609 // AttemptResult values to visit this code and examine whether
610 // additional detail is needed.
611 case metrics::AttemptResult::kUpdateSucceeded:
612 case metrics::AttemptResult::kMetadataMalformed:
613 case metrics::AttemptResult::kOperationMalformed:
614 case metrics::AttemptResult::kOperationExecutionError:
615 case metrics::AttemptResult::kMetadataVerificationFailed:
616 case metrics::AttemptResult::kPayloadVerificationFailed:
617 case metrics::AttemptResult::kVerificationFailed:
618 case metrics::AttemptResult::kPostInstallFailed:
619 case metrics::AttemptResult::kAbnormalTermination:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800620 case metrics::AttemptResult::kUpdateCanceled:
David Zeuthen33bae492014-02-25 16:16:18 -0800621 case metrics::AttemptResult::kNumConstants:
622 case metrics::AttemptResult::kUnset:
623 break;
624 }
625
626 metrics::ReportUpdateAttemptMetrics(system_state_,
627 attempt_number,
628 payload_type,
629 duration,
630 duration_uptime,
631 payload_size,
632 payload_bytes_downloaded,
633 payload_download_speed_bps,
634 download_source,
635 attempt_result,
636 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700637 payload_download_error_code,
638 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800639}
640
David Zeuthen4e1d1492014-04-25 13:12:27 -0700641void PayloadState::PersistAttemptMetrics() {
642 // TODO(zeuthen): For now we only persist whether an attempt was in
643 // progress and not values/metrics related to the attempt. This
644 // means that when this happens, of all the UpdateEngine.Attempt.*
645 // metrics, only UpdateEngine.Attempt.Result is reported (with the
646 // value |kAbnormalTermination|). In the future we might want to
647 // persist more data so we can report other metrics in the
648 // UpdateEngine.Attempt.* namespace when this happens.
649 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
650}
651
652void PayloadState::ClearPersistedAttemptMetrics() {
653 prefs_->Delete(kPrefsAttemptInProgress);
654}
655
656void PayloadState::ReportAndClearPersistedAttemptMetrics() {
657 bool attempt_in_progress = false;
658 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
659 return;
660 if (!attempt_in_progress)
661 return;
662
663 metrics::ReportAbnormallyTerminatedUpdateAttemptMetrics(system_state_);
664
665 ClearPersistedAttemptMetrics();
666}
667
David Zeuthen33bae492014-02-25 16:16:18 -0800668void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700669 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800670
671 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800672 int64_t total_bytes_by_source[kNumDownloadSources];
673 int64_t successful_bytes = 0;
674 int64_t total_bytes = 0;
675 int64_t successful_mbs = 0;
676 int64_t total_mbs = 0;
677
Jay Srinivasan19409b72013-04-12 19:23:36 -0700678 for (int i = 0; i < kNumDownloadSources; i++) {
679 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800680 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700681
David Zeuthen44848602013-06-24 13:32:14 -0700682 // Only consider this download source (and send byte counts) as
683 // having been used if we downloaded a non-trivial amount of bytes
684 // (e.g. at least 1 MiB) that contributed to the final success of
685 // the update. Otherwise we're going to end up with a lot of
686 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700687
David Zeuthen33bae492014-02-25 16:16:18 -0800688 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800689 successful_bytes += bytes;
690 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700691 SetCurrentBytesDownloaded(source, 0, true);
692
David Zeuthen33bae492014-02-25 16:16:18 -0800693 bytes = GetTotalBytesDownloaded(source);
694 total_bytes_by_source[i] = bytes;
695 total_bytes += bytes;
696 total_mbs += bytes / kNumBytesInOneMiB;
697 SetTotalBytesDownloaded(source, 0, true);
698 }
699
700 int download_overhead_percentage = 0;
701 if (successful_bytes > 0) {
702 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
703 successful_bytes;
704 }
705
706 int url_switch_count = static_cast<int>(url_switch_count_);
707
708 int reboot_count = GetNumReboots();
709
710 SetNumReboots(0);
711
712 TimeDelta duration = GetUpdateDuration();
David Zeuthen33bae492014-02-25 16:16:18 -0800713
714 prefs_->Delete(kPrefsUpdateTimestampStart);
715 prefs_->Delete(kPrefsUpdateDurationUptime);
716
717 PayloadType payload_type = CalculatePayloadType();
718
719 int64_t payload_size = response_.size;
720
721 int attempt_count = GetPayloadAttemptNumber();
722
723 int updates_abandoned_count = num_responses_seen_ - 1;
724
725 metrics::ReportSuccessfulUpdateMetrics(system_state_,
726 attempt_count,
727 updates_abandoned_count,
728 payload_type,
729 payload_size,
730 total_bytes_by_source,
731 download_overhead_percentage,
732 duration,
733 reboot_count,
734 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700735}
736
737void PayloadState::UpdateNumReboots() {
738 // We only update the reboot count when the system has been detected to have
739 // been rebooted.
740 if (!system_state_->system_rebooted()) {
741 return;
742 }
743
744 SetNumReboots(GetNumReboots() + 1);
745}
746
747void PayloadState::SetNumReboots(uint32_t num_reboots) {
748 CHECK(prefs_);
749 num_reboots_ = num_reboots;
750 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
751 LOG(INFO) << "Number of Reboots during current update attempt = "
752 << num_reboots_;
753}
754
Jay Srinivasan08262882012-12-28 19:29:43 -0800755void PayloadState::ResetPersistedState() {
756 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700757 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800758 SetUrlIndex(0);
759 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700760 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700761 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700762 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700763 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700764 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700765 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700766 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700767 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700768 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700769 SetScatteringWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700770}
771
772void PayloadState::ResetRollbackVersion() {
773 CHECK(powerwash_safe_prefs_);
774 rollback_version_ = "";
775 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700776}
777
778void PayloadState::ResetDownloadSourcesOnNewUpdate() {
779 for (int i = 0; i < kNumDownloadSources; i++) {
780 DownloadSource source = static_cast<DownloadSource>(i);
781 SetCurrentBytesDownloaded(source, 0, true);
782 // Note: Not resetting the TotalBytesDownloaded as we want that metric
783 // to count the bytes downloaded across various update attempts until
784 // we have successfully applied the update.
785 }
786}
787
Chris Sosab3dcdb32013-09-04 15:22:12 -0700788int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700789 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700790 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700791 return 0;
792
793 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700794 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700795 return 0;
796
797 if (stored_value < 0) {
798 LOG(ERROR) << key << ": Invalid value (" << stored_value
799 << ") in persisted state. Defaulting to 0";
800 return 0;
801 }
802
803 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800804}
805
806string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700807 string response_sign = base::StringPrintf(
808 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800809
Jay Srinivasan53173b92013-05-17 17:13:01 -0700810 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700811 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
812 static_cast<int>(i),
813 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800814
Alex Vakulenko75039d72014-03-25 12:36:28 -0700815 response_sign += base::StringPrintf(
816 "Payload Size = %ju\n"
817 "Payload Sha256 Hash = %s\n"
818 "Metadata Size = %ju\n"
819 "Metadata Signature = %s\n"
820 "Is Delta Payload = %d\n"
821 "Max Failure Count Per Url = %d\n"
822 "Disable Payload Backoff = %d\n",
823 static_cast<uintmax_t>(response_.size),
824 response_.hash.c_str(),
825 static_cast<uintmax_t>(response_.metadata_size),
826 response_.metadata_signature.c_str(),
827 response_.is_delta_payload,
828 response_.max_failure_count_per_url,
829 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800830 return response_sign;
831}
832
833void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800834 CHECK(prefs_);
835 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800836 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
837 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
838 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800839 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800840}
841
Jay Srinivasan19409b72013-04-12 19:23:36 -0700842void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800843 CHECK(prefs_);
844 response_signature_ = response_signature;
845 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
846 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
847}
848
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800849void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700850 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800851}
852
Alex Deymo820cc702013-06-28 15:43:46 -0700853void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700854 SetFullPayloadAttemptNumber(GetPersistedValue(
855 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700856}
857
858void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800859 CHECK(prefs_);
860 payload_attempt_number_ = payload_attempt_number;
861 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
862 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
863}
864
Alex Deymo820cc702013-06-28 15:43:46 -0700865void PayloadState::SetFullPayloadAttemptNumber(
866 int full_payload_attempt_number) {
867 CHECK(prefs_);
868 full_payload_attempt_number_ = full_payload_attempt_number;
869 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
870 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
871 full_payload_attempt_number_);
872}
873
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800874void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700875 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800876}
877
878void PayloadState::SetUrlIndex(uint32_t url_index) {
879 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800880 url_index_ = url_index;
881 LOG(INFO) << "Current URL Index = " << url_index_;
882 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700883
884 // Also update the download source, which is purely dependent on the
885 // current URL index alone.
886 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800887}
888
Gilad Arnold519cfc72014-10-02 10:34:54 -0700889void PayloadState::LoadScatteringWaitPeriod() {
890 SetScatteringWaitPeriod(
891 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
892}
893
Alex Deymof329b932014-10-30 01:37:48 -0700894void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700895 CHECK(prefs_);
896 scattering_wait_period_ = wait_period;
897 LOG(INFO) << "Scattering Wait Period (seconds) = "
898 << scattering_wait_period_.InSeconds();
899 if (scattering_wait_period_.InSeconds() > 0) {
900 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
901 scattering_wait_period_.InSeconds());
902 } else {
903 prefs_->Delete(kPrefsWallClockWaitPeriod);
904 }
905}
906
David Zeuthencc6f9962013-04-18 11:57:24 -0700907void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700908 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700909}
910
911void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
912 CHECK(prefs_);
913 url_switch_count_ = url_switch_count;
914 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
915 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
916}
917
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800918void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700919 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800920}
921
922void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
923 CHECK(prefs_);
924 url_failure_count_ = url_failure_count;
925 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
926 << ")'s Failure Count = " << url_failure_count_;
927 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800928}
929
Jay Srinivasan08262882012-12-28 19:29:43 -0800930void PayloadState::LoadBackoffExpiryTime() {
931 CHECK(prefs_);
932 int64_t stored_value;
933 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
934 return;
935
936 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
937 return;
938
939 Time stored_time = Time::FromInternalValue(stored_value);
940 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
941 LOG(ERROR) << "Invalid backoff expiry time ("
942 << utils::ToString(stored_time)
943 << ") in persisted state. Resetting.";
944 stored_time = Time();
945 }
946 SetBackoffExpiryTime(stored_time);
947}
948
949void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
950 CHECK(prefs_);
951 backoff_expiry_time_ = new_time;
952 LOG(INFO) << "Backoff Expiry Time = "
953 << utils::ToString(backoff_expiry_time_);
954 prefs_->SetInt64(kPrefsBackoffExpiryTime,
955 backoff_expiry_time_.ToInternalValue());
956}
957
David Zeuthen9a017f22013-04-11 16:10:26 -0700958TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700959 Time end_time = update_timestamp_end_.is_null()
960 ? system_state_->clock()->GetWallclockTime() :
961 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700962 return end_time - update_timestamp_start_;
963}
964
965void PayloadState::LoadUpdateTimestampStart() {
966 int64_t stored_value;
967 Time stored_time;
968
969 CHECK(prefs_);
970
David Zeuthenf413fe52013-04-22 14:04:39 -0700971 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700972
973 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
974 // The preference missing is not unexpected - in that case, just
975 // use the current time as start time
976 stored_time = now;
977 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
978 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
979 stored_time = now;
980 } else {
981 stored_time = Time::FromInternalValue(stored_value);
982 }
983
984 // Sanity check: If the time read from disk is in the future
985 // (modulo some slack to account for possible NTP drift
986 // adjustments), something is fishy and we should report and
987 // reset.
988 TimeDelta duration_according_to_stored_time = now - stored_time;
989 if (duration_according_to_stored_time < -kDurationSlack) {
990 LOG(ERROR) << "The UpdateTimestampStart value ("
991 << utils::ToString(stored_time)
992 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700993 << utils::FormatTimeDelta(duration_according_to_stored_time)
994 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700995 stored_time = now;
996 }
997
998 SetUpdateTimestampStart(stored_time);
999}
1000
1001void PayloadState::SetUpdateTimestampStart(const Time& value) {
1002 CHECK(prefs_);
1003 update_timestamp_start_ = value;
1004 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1005 update_timestamp_start_.ToInternalValue());
1006 LOG(INFO) << "Update Timestamp Start = "
1007 << utils::ToString(update_timestamp_start_);
1008}
1009
1010void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1011 update_timestamp_end_ = value;
1012 LOG(INFO) << "Update Timestamp End = "
1013 << utils::ToString(update_timestamp_end_);
1014}
1015
1016TimeDelta PayloadState::GetUpdateDurationUptime() {
1017 return update_duration_uptime_;
1018}
1019
1020void PayloadState::LoadUpdateDurationUptime() {
1021 int64_t stored_value;
1022 TimeDelta stored_delta;
1023
1024 CHECK(prefs_);
1025
1026 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1027 // The preference missing is not unexpected - in that case, just
1028 // we'll use zero as the delta
1029 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1030 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1031 stored_delta = TimeDelta::FromSeconds(0);
1032 } else {
1033 stored_delta = TimeDelta::FromInternalValue(stored_value);
1034 }
1035
1036 // Sanity-check: Uptime can never be greater than the wall-clock
1037 // difference (modulo some slack). If it is, report and reset
1038 // to the wall-clock difference.
1039 TimeDelta diff = GetUpdateDuration() - stored_delta;
1040 if (diff < -kDurationSlack) {
1041 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001042 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001043 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001044 << utils::FormatTimeDelta(diff)
1045 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001046 stored_delta = update_duration_current_;
1047 }
1048
1049 SetUpdateDurationUptime(stored_delta);
1050}
1051
Chris Sosabe45bef2013-04-09 18:25:12 -07001052void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001053 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001054}
1055
1056void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001057 CHECK(powerwash_safe_prefs_);
1058 string rollback_version;
1059 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1060 &rollback_version)) {
1061 SetRollbackVersion(rollback_version);
1062 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001063}
1064
1065void PayloadState::SetRollbackVersion(const string& rollback_version) {
1066 CHECK(powerwash_safe_prefs_);
1067 LOG(INFO) << "Blacklisting version "<< rollback_version;
1068 rollback_version_ = rollback_version;
1069 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001070}
1071
David Zeuthen9a017f22013-04-11 16:10:26 -07001072void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1073 const Time& timestamp,
1074 bool use_logging) {
1075 CHECK(prefs_);
1076 update_duration_uptime_ = value;
1077 update_duration_uptime_timestamp_ = timestamp;
1078 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1079 update_duration_uptime_.ToInternalValue());
1080 if (use_logging) {
1081 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001082 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001083 }
1084}
1085
1086void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001087 Time now = system_state_->clock()->GetMonotonicTime();
1088 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001089}
1090
1091void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001092 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001093 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1094 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1095 // We're frequently called so avoid logging this write
1096 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1097}
1098
Jay Srinivasan19409b72013-04-12 19:23:36 -07001099string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1100 return prefix + "-from-" + utils::ToString(source);
1101}
1102
1103void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1104 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001105 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001106}
1107
1108void PayloadState::SetCurrentBytesDownloaded(
1109 DownloadSource source,
1110 uint64_t current_bytes_downloaded,
1111 bool log) {
1112 CHECK(prefs_);
1113
1114 if (source >= kNumDownloadSources)
1115 return;
1116
1117 // Update the in-memory value.
1118 current_bytes_downloaded_[source] = current_bytes_downloaded;
1119
1120 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1121 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1122 LOG_IF(INFO, log) << "Current bytes downloaded for "
1123 << utils::ToString(source) << " = "
1124 << GetCurrentBytesDownloaded(source);
1125}
1126
1127void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1128 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001129 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001130}
1131
1132void PayloadState::SetTotalBytesDownloaded(
1133 DownloadSource source,
1134 uint64_t total_bytes_downloaded,
1135 bool log) {
1136 CHECK(prefs_);
1137
1138 if (source >= kNumDownloadSources)
1139 return;
1140
1141 // Update the in-memory value.
1142 total_bytes_downloaded_[source] = total_bytes_downloaded;
1143
1144 // Persist.
1145 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1146 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1147 LOG_IF(INFO, log) << "Total bytes downloaded for "
1148 << utils::ToString(source) << " = "
1149 << GetTotalBytesDownloaded(source);
1150}
1151
David Zeuthena573d6f2013-06-14 16:13:36 -07001152void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001153 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001154}
1155
1156void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1157 CHECK(prefs_);
1158 num_responses_seen_ = num_responses_seen;
1159 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1160 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1161}
1162
Jay Srinivasan53173b92013-05-17 17:13:01 -07001163void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001164 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001165
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001166 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001167 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001168 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001169 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1170 } else {
1171 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1172 http_url_ok = true;
1173 }
1174
1175 candidate_urls_.clear();
1176 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1177 string candidate_url = response_.payload_urls[i];
Alex Vakulenko0103c362016-01-20 07:56:15 -08001178 if (base::StartsWith(candidate_url, "http://",
1179 base::CompareCase::INSENSITIVE_ASCII) &&
1180 !http_url_ok) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -07001181 continue;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001182 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001183 candidate_urls_.push_back(candidate_url);
1184 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1185 << ": " << candidate_url;
1186 }
1187
1188 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1189 << "out of " << response_.payload_urls.size() << " URLs supplied";
1190}
1191
David Zeuthene4c58bf2013-06-18 17:26:50 -07001192void PayloadState::CreateSystemUpdatedMarkerFile() {
1193 CHECK(prefs_);
1194 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1195 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1196}
1197
1198void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1199 // Send |time_to_reboot| as a UMA stat.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001200 string metric = metrics::kMetricTimeToRebootMinutes;
David Zeuthen33bae492014-02-25 16:16:18 -08001201 system_state_->metrics_lib()->SendToUMA(metric,
1202 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001203 0, // min: 0 minute
1204 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001205 kNumDefaultUmaBuckets);
1206 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1207 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001208}
1209
1210void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001211 // Flush previous state from abnormal attempt failure, if any.
1212 ReportAndClearPersistedAttemptMetrics();
1213
Alex Deymo569c4242013-07-24 12:01:01 -07001214 // Avoid the UpdateEngineStarted actions if this is not the first time we
1215 // run the update engine since reboot.
1216 if (!system_state_->system_rebooted())
1217 return;
1218
David Zeuthene4c58bf2013-06-18 17:26:50 -07001219 // Figure out if we just booted into a new update
1220 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1221 int64_t stored_value;
1222 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1223 Time system_updated_at = Time::FromInternalValue(stored_value);
1224 if (!system_updated_at.is_null()) {
1225 TimeDelta time_to_reboot =
1226 system_state_->clock()->GetWallclockTime() - system_updated_at;
1227 if (time_to_reboot.ToInternalValue() < 0) {
1228 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1229 << utils::ToString(system_updated_at);
1230 } else {
1231 BootedIntoUpdate(time_to_reboot);
1232 }
1233 }
1234 }
1235 prefs_->Delete(kPrefsSystemUpdatedMarker);
1236 }
Alex Deymo42432912013-07-12 20:21:15 -07001237 // Check if it is needed to send metrics about a failed reboot into a new
1238 // version.
1239 ReportFailedBootIfNeeded();
1240}
1241
1242void PayloadState::ReportFailedBootIfNeeded() {
1243 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1244 // payload was marked as ready immediately before the last reboot, and we
1245 // need to check if such payload successfully rebooted or not.
1246 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001247 int64_t installed_from = 0;
1248 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001249 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1250 return;
1251 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001252 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1253 // partition number. We are now using slot numbers (0 or 1) instead, so
1254 // the following comparison will not match if we are comparing an old
1255 // partition number against a new slot number, which is the correct outcome
1256 // since we successfully booted the new update in that case. If the boot
1257 // failed, we will read this value from the same version, so it will always
1258 // be compatible.
1259 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001260 // A reboot was pending, but the chromebook is again in the same
1261 // BootDevice where the update was installed from.
1262 int64_t target_attempt;
1263 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1264 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1265 "TargetVersionInstalledFrom was present.";
1266 target_attempt = 1;
1267 }
1268
1269 // Report the UMA metric of the current boot failure.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001270 string metric = metrics::kMetricFailedUpdateCount;
David Zeuthen33bae492014-02-25 16:16:18 -08001271 LOG(INFO) << "Uploading " << target_attempt
1272 << " (count) for metric " << metric;
1273 system_state_->metrics_lib()->SendToUMA(
1274 metric,
1275 target_attempt,
1276 1, // min value
1277 50, // max value
1278 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001279 } else {
1280 prefs_->Delete(kPrefsTargetVersionAttempt);
1281 prefs_->Delete(kPrefsTargetVersionUniqueId);
1282 }
1283 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1284 }
1285}
1286
1287void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1288 // Expect to boot into the new partition in the next reboot setting the
1289 // TargetVersion* flags in the Prefs.
1290 string stored_target_version_uid;
1291 string target_version_id;
1292 string target_partition;
1293 int64_t target_attempt;
1294
1295 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1296 prefs_->GetString(kPrefsTargetVersionUniqueId,
1297 &stored_target_version_uid) &&
1298 stored_target_version_uid == target_version_uid) {
1299 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1300 target_attempt = 0;
1301 } else {
1302 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1303 target_attempt = 0;
1304 }
1305 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1306
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001307 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001308 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001309}
1310
1311void PayloadState::ResetUpdateStatus() {
1312 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1313 // rebooted the next boot is not flagged as failed to rebooted into the
1314 // new applied payload.
1315 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1316
1317 // Also decrement the attempt number if it exists.
1318 int64_t target_attempt;
1319 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001320 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001321}
1322
David Zeuthendcba8092013-08-06 12:16:35 -07001323int PayloadState::GetP2PNumAttempts() {
1324 return p2p_num_attempts_;
1325}
1326
1327void PayloadState::SetP2PNumAttempts(int value) {
1328 p2p_num_attempts_ = value;
1329 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1330 CHECK(prefs_);
1331 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1332}
1333
1334void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001335 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001336}
1337
1338Time PayloadState::GetP2PFirstAttemptTimestamp() {
1339 return p2p_first_attempt_timestamp_;
1340}
1341
1342void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1343 p2p_first_attempt_timestamp_ = time;
1344 LOG(INFO) << "p2p First Attempt Timestamp = "
1345 << utils::ToString(p2p_first_attempt_timestamp_);
1346 CHECK(prefs_);
1347 int64_t stored_value = time.ToInternalValue();
1348 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1349}
1350
1351void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001352 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001353 Time stored_time = Time::FromInternalValue(stored_value);
1354 SetP2PFirstAttemptTimestamp(stored_time);
1355}
1356
1357void PayloadState::P2PNewAttempt() {
1358 CHECK(prefs_);
1359 // Set timestamp, if it hasn't been set already
1360 if (p2p_first_attempt_timestamp_.is_null()) {
1361 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1362 }
1363 // Increase number of attempts
1364 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1365}
1366
1367bool PayloadState::P2PAttemptAllowed() {
1368 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1369 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1370 << " which is greater than "
1371 << kMaxP2PAttempts
1372 << " - disallowing p2p.";
1373 return false;
1374 }
1375
1376 if (!p2p_first_attempt_timestamp_.is_null()) {
1377 Time now = system_state_->clock()->GetWallclockTime();
1378 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1379 if (time_spent_attempting_p2p.InSeconds() < 0) {
1380 LOG(ERROR) << "Time spent attempting p2p is negative"
1381 << " - disallowing p2p.";
1382 return false;
1383 }
1384 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1385 LOG(INFO) << "Time spent attempting p2p is "
1386 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1387 << " which is greater than "
1388 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1389 kMaxP2PAttemptTimeSeconds))
1390 << " - disallowing p2p.";
1391 return false;
1392 }
1393 }
1394
1395 return true;
1396}
1397
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001398} // namespace chromeos_update_engine