blob: af1ad0559376f3dab2c29f59fbf15fba7f877e7f [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"
Alex Deymo38429cf2015-11-11 18:27:22 -080034#include "update_engine/metrics_utils.h"
Gilad Arnold1f847232014-04-07 12:07:49 -070035#include "update_engine/omaha_request_params.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080036#include "update_engine/payload_consumer/install_plan.h"
Jay Srinivasan19409b72013-04-12 19:23:36 -070037#include "update_engine/system_state.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080038
Jay Srinivasan08262882012-12-28 19:29:43 -080039using base::Time;
40using base::TimeDelta;
41using std::min;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080042using std::string;
43
44namespace chromeos_update_engine {
45
David Zeuthen9a017f22013-04-11 16:10:26 -070046const TimeDelta PayloadState::kDurationSlack = TimeDelta::FromSeconds(600);
47
Jay Srinivasan08262882012-12-28 19:29:43 -080048// We want to upperbound backoffs to 16 days
Alex Deymo820cc702013-06-28 15:43:46 -070049static const int kMaxBackoffDays = 16;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080050
Jay Srinivasan08262882012-12-28 19:29:43 -080051// We want to randomize retry attempts after the backoff by +/- 6 hours.
52static const uint32_t kMaxBackoffFuzzMinutes = 12 * 60;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080053
Jay Srinivasan19409b72013-04-12 19:23:36 -070054PayloadState::PayloadState()
Alex Vakulenko88b591f2014-08-28 16:48:57 -070055 : prefs_(nullptr),
David Zeuthenbb8bdc72013-09-03 13:43:48 -070056 using_p2p_for_downloading_(false),
Gilad Arnold74b5f552014-10-07 08:17:16 -070057 p2p_num_attempts_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070058 payload_attempt_number_(0),
Alex Deymo820cc702013-06-28 15:43:46 -070059 full_payload_attempt_number_(0),
Jay Srinivasan19409b72013-04-12 19:23:36 -070060 url_index_(0),
David Zeuthencc6f9962013-04-18 11:57:24 -070061 url_failure_count_(0),
David Zeuthendcba8092013-08-06 12:16:35 -070062 url_switch_count_(0),
David Zeuthenafed4a12014-04-09 15:28:44 -070063 attempt_num_bytes_downloaded_(0),
64 attempt_connection_type_(metrics::ConnectionType::kUnknown),
Shuqian Zhao29971732016-02-05 11:29:32 -080065 attempt_error_code_(ErrorCode::kSuccess),
Alex Vakulenkod2779df2014-06-16 13:19:00 -070066 attempt_type_(AttemptType::kUpdate) {
67 for (int i = 0; i <= kNumDownloadSources; i++)
68 total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
Jay Srinivasan19409b72013-04-12 19:23:36 -070069}
70
71bool PayloadState::Initialize(SystemState* system_state) {
72 system_state_ = system_state;
73 prefs_ = system_state_->prefs();
Chris Sosaaa18e162013-06-20 13:20:30 -070074 powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
Jay Srinivasan08262882012-12-28 19:29:43 -080075 LoadResponseSignature();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080076 LoadPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -070077 LoadFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080078 LoadUrlIndex();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080079 LoadUrlFailureCount();
David Zeuthencc6f9962013-04-18 11:57:24 -070080 LoadUrlSwitchCount();
Jay Srinivasan08262882012-12-28 19:29:43 -080081 LoadBackoffExpiryTime();
David Zeuthen9a017f22013-04-11 16:10:26 -070082 LoadUpdateTimestampStart();
83 // The LoadUpdateDurationUptime() method relies on LoadUpdateTimestampStart()
84 // being called before it. Don't reorder.
85 LoadUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -070086 for (int i = 0; i < kNumDownloadSources; i++) {
87 DownloadSource source = static_cast<DownloadSource>(i);
88 LoadCurrentBytesDownloaded(source);
89 LoadTotalBytesDownloaded(source);
90 }
Chris Sosabe45bef2013-04-09 18:25:12 -070091 LoadNumReboots();
David Zeuthena573d6f2013-06-14 16:13:36 -070092 LoadNumResponsesSeen();
Chris Sosaaa18e162013-06-20 13:20:30 -070093 LoadRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -070094 LoadP2PFirstAttemptTimestamp();
95 LoadP2PNumAttempts();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080096 return true;
97}
98
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080099void PayloadState::SetResponse(const OmahaResponse& omaha_response) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800100 // Always store the latest response.
101 response_ = omaha_response;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800102
Jay Srinivasan53173b92013-05-17 17:13:01 -0700103 // Compute the candidate URLs first as they are used to calculate the
104 // response signature so that a change in enterprise policy for
105 // HTTP downloads being enabled or not could be honored as soon as the
106 // next update check happens.
107 ComputeCandidateUrls();
108
Jay Srinivasan08262882012-12-28 19:29:43 -0800109 // Check if the "signature" of this response (i.e. the fields we care about)
110 // has changed.
111 string new_response_signature = CalculateResponseSignature();
112 bool has_response_changed = (response_signature_ != new_response_signature);
113
114 // If the response has changed, we should persist the new signature and
115 // clear away all the existing state.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800116 if (has_response_changed) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800117 LOG(INFO) << "Resetting all persisted state as this is a new response";
David Zeuthena573d6f2013-06-14 16:13:36 -0700118 SetNumResponsesSeen(num_responses_seen_ + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800119 SetResponseSignature(new_response_signature);
120 ResetPersistedState();
121 return;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800122 }
123
Jay Srinivasan08262882012-12-28 19:29:43 -0800124 // This is the earliest point at which we can validate whether the URL index
125 // we loaded from the persisted state is a valid value. If the response
126 // hasn't changed but the URL index is invalid, it's indicative of some
127 // tampering of the persisted state.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700128 if (static_cast<uint32_t>(url_index_) >= candidate_urls_.size()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800129 LOG(INFO) << "Resetting all payload state as the url index seems to have "
130 "been tampered with";
131 ResetPersistedState();
132 return;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800133 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700134
135 // Update the current download source which depends on the latest value of
136 // the response.
137 UpdateCurrentDownloadSource();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800138}
139
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700140void PayloadState::SetUsingP2PForDownloading(bool value) {
141 using_p2p_for_downloading_ = value;
142 // Update the current download source which depends on whether we are
143 // using p2p or not.
144 UpdateCurrentDownloadSource();
145}
146
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800147void PayloadState::DownloadComplete() {
148 LOG(INFO) << "Payload downloaded successfully";
149 IncrementPayloadAttemptNumber();
Alex Deymo820cc702013-06-28 15:43:46 -0700150 IncrementFullPayloadAttemptNumber();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800151}
152
153void PayloadState::DownloadProgress(size_t count) {
154 if (count == 0)
155 return;
156
David Zeuthen9a017f22013-04-11 16:10:26 -0700157 CalculateUpdateDurationUptime();
Jay Srinivasan19409b72013-04-12 19:23:36 -0700158 UpdateBytesDownloaded(count);
David Zeuthen9a017f22013-04-11 16:10:26 -0700159
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800160 // We've received non-zero bytes from a recent download operation. Since our
161 // URL failure count is meant to penalize a URL only for consecutive
162 // failures, downloading bytes successfully means we should reset the failure
163 // count (as we know at least that the URL is working). In future, we can
164 // design this to be more sophisticated to check for more intelligent failure
165 // patterns, but right now, even 1 byte downloaded will mark the URL to be
166 // good unless it hits 10 (or configured number of) consecutive failures
167 // again.
168
169 if (GetUrlFailureCount() == 0)
170 return;
171
172 LOG(INFO) << "Resetting failure count of Url" << GetUrlIndex()
173 << " to 0 as we received " << count << " bytes successfully";
174 SetUrlFailureCount(0);
175}
176
David Zeuthenafed4a12014-04-09 15:28:44 -0700177void PayloadState::AttemptStarted(AttemptType attempt_type) {
David Zeuthen4e1d1492014-04-25 13:12:27 -0700178 // Flush previous state from abnormal attempt failure, if any.
179 ReportAndClearPersistedAttemptMetrics();
180
David Zeuthenafed4a12014-04-09 15:28:44 -0700181 attempt_type_ = attempt_type;
182
David Zeuthen33bae492014-02-25 16:16:18 -0800183 ClockInterface *clock = system_state_->clock();
184 attempt_start_time_boot_ = clock->GetBootTime();
185 attempt_start_time_monotonic_ = clock->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -0800186 attempt_num_bytes_downloaded_ = 0;
David Zeuthenb281f072014-04-02 10:20:19 -0700187
188 metrics::ConnectionType type;
189 NetworkConnectionType network_connection_type;
190 NetworkTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -0700191 ConnectionManagerInterface* connection_manager =
192 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -0700193 if (!connection_manager->GetConnectionProperties(&network_connection_type,
David Zeuthenb281f072014-04-02 10:20:19 -0700194 &tethering)) {
195 LOG(ERROR) << "Failed to determine connection type.";
196 type = metrics::ConnectionType::kUnknown;
197 } else {
Alex Deymo38429cf2015-11-11 18:27:22 -0800198 type = metrics_utils::GetConnectionType(network_connection_type, tethering);
David Zeuthenb281f072014-04-02 10:20:19 -0700199 }
200 attempt_connection_type_ = type;
David Zeuthen4e1d1492014-04-25 13:12:27 -0700201
202 if (attempt_type == AttemptType::kUpdate)
203 PersistAttemptMetrics();
David Zeuthen33bae492014-02-25 16:16:18 -0800204}
205
Chris Sosabe45bef2013-04-09 18:25:12 -0700206void PayloadState::UpdateResumed() {
207 LOG(INFO) << "Resuming an update that was previously started.";
208 UpdateNumReboots();
David Zeuthenafed4a12014-04-09 15:28:44 -0700209 AttemptStarted(AttemptType::kUpdate);
Chris Sosabe45bef2013-04-09 18:25:12 -0700210}
211
Jay Srinivasan19409b72013-04-12 19:23:36 -0700212void PayloadState::UpdateRestarted() {
213 LOG(INFO) << "Starting a new update";
214 ResetDownloadSourcesOnNewUpdate();
Chris Sosabe45bef2013-04-09 18:25:12 -0700215 SetNumReboots(0);
David Zeuthenafed4a12014-04-09 15:28:44 -0700216 AttemptStarted(AttemptType::kUpdate);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700217}
218
David Zeuthen9a017f22013-04-11 16:10:26 -0700219void PayloadState::UpdateSucceeded() {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700220 // Send the relevant metrics that are tracked in this class to UMA.
David Zeuthen9a017f22013-04-11 16:10:26 -0700221 CalculateUpdateDurationUptime();
David Zeuthenf413fe52013-04-22 14:04:39 -0700222 SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
David Zeuthen33bae492014-02-25 16:16:18 -0800223
David Zeuthen96197df2014-04-16 12:22:39 -0700224 switch (attempt_type_) {
225 case AttemptType::kUpdate:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700226 CollectAndReportAttemptMetrics(ErrorCode::kSuccess);
David Zeuthen96197df2014-04-16 12:22:39 -0700227 CollectAndReportSuccessfulUpdateMetrics();
David Zeuthen4e1d1492014-04-25 13:12:27 -0700228 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700229 break;
230
231 case AttemptType::kRollback:
232 metrics::ReportRollbackMetrics(system_state_,
233 metrics::RollbackResult::kSuccess);
234 break;
David Zeuthenafed4a12014-04-09 15:28:44 -0700235 }
Shuqian Zhao29971732016-02-05 11:29:32 -0800236 attempt_error_code_ = ErrorCode::kSuccess;
David Zeuthena573d6f2013-06-14 16:13:36 -0700237
238 // Reset the number of responses seen since it counts from the last
239 // successful update, e.g. now.
240 SetNumResponsesSeen(0);
David Zeuthene4c58bf2013-06-18 17:26:50 -0700241
242 CreateSystemUpdatedMarkerFile();
David Zeuthen9a017f22013-04-11 16:10:26 -0700243}
244
David Zeuthena99981f2013-04-29 13:42:47 -0700245void PayloadState::UpdateFailed(ErrorCode error) {
246 ErrorCode base_error = utils::GetBaseErrorCode(error);
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800247 LOG(INFO) << "Updating payload state for error code: " << base_error
Alex Deymoe88e9fe2016-02-03 16:38:00 -0800248 << " (" << utils::ErrorCodeToString(base_error) << ")";
Shuqian Zhaocd486362016-03-04 19:07:40 -0800249 attempt_error_code_ = base_error;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800250
Jay Srinivasan53173b92013-05-17 17:13:01 -0700251 if (candidate_urls_.size() == 0) {
252 // This means we got this error even before we got a valid Omaha response
253 // or don't have any valid candidates in the Omaha response.
Jay Srinivasan08262882012-12-28 19:29:43 -0800254 // So we should not advance the url_index_ in such cases.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800255 LOG(INFO) << "Ignoring failures until we get a valid Omaha response.";
256 return;
257 }
258
David Zeuthen96197df2014-04-16 12:22:39 -0700259 switch (attempt_type_) {
260 case AttemptType::kUpdate:
261 CollectAndReportAttemptMetrics(base_error);
David Zeuthen4e1d1492014-04-25 13:12:27 -0700262 ClearPersistedAttemptMetrics();
David Zeuthen96197df2014-04-16 12:22:39 -0700263 break;
264
265 case AttemptType::kRollback:
266 metrics::ReportRollbackMetrics(system_state_,
267 metrics::RollbackResult::kFailed);
268 break;
269 }
David Zeuthen33bae492014-02-25 16:16:18 -0800270
Shuqian Zhao29971732016-02-05 11:29:32 -0800271
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800272 switch (base_error) {
273 // Errors which are good indicators of a problem with a particular URL or
274 // the protocol used in the URL or entities in the communication channel
275 // (e.g. proxies). We should try the next available URL in the next update
276 // check to quickly recover from these errors.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700277 case ErrorCode::kPayloadHashMismatchError:
278 case ErrorCode::kPayloadSizeMismatchError:
279 case ErrorCode::kDownloadPayloadVerificationError:
280 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
281 case ErrorCode::kSignedDeltaPayloadExpectedError:
282 case ErrorCode::kDownloadInvalidMetadataMagicString:
283 case ErrorCode::kDownloadSignatureMissingInManifest:
284 case ErrorCode::kDownloadManifestParseError:
285 case ErrorCode::kDownloadMetadataSignatureError:
286 case ErrorCode::kDownloadMetadataSignatureVerificationError:
287 case ErrorCode::kDownloadMetadataSignatureMismatch:
288 case ErrorCode::kDownloadOperationHashVerificationError:
289 case ErrorCode::kDownloadOperationExecutionError:
290 case ErrorCode::kDownloadOperationHashMismatch:
291 case ErrorCode::kDownloadInvalidMetadataSize:
292 case ErrorCode::kDownloadInvalidMetadataSignature:
293 case ErrorCode::kDownloadOperationHashMissingError:
294 case ErrorCode::kDownloadMetadataSignatureMissingError:
295 case ErrorCode::kPayloadMismatchedType:
296 case ErrorCode::kUnsupportedMajorPayloadVersion:
297 case ErrorCode::kUnsupportedMinorPayloadVersion:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800298 IncrementUrlIndex();
299 break;
300
301 // Errors which seem to be just transient network/communication related
302 // failures and do not indicate any inherent problem with the URL itself.
303 // So, we should keep the current URL but just increment the
304 // failure count to give it more chances. This way, while we maximize our
305 // chances of downloading from the URLs that appear earlier in the response
306 // (because download from a local server URL that appears earlier in a
307 // response is preferable than downloading from the next URL which could be
308 // a internet URL and thus could be more expensive).
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700309
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700310 case ErrorCode::kError:
311 case ErrorCode::kDownloadTransferError:
312 case ErrorCode::kDownloadWriteError:
313 case ErrorCode::kDownloadStateInitializationError:
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700314 case ErrorCode::kOmahaErrorInHTTPResponse: // Aggregate for HTTP errors.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800315 IncrementFailureCount();
316 break;
317
318 // Errors which are not specific to a URL and hence shouldn't result in
319 // the URL being penalized. This can happen in two cases:
320 // 1. We haven't started downloading anything: These errors don't cost us
321 // anything in terms of actual payload bytes, so we should just do the
322 // regular retries at the next update check.
323 // 2. We have successfully downloaded the payload: In this case, the
324 // payload attempt number would have been incremented and would take care
Jay Srinivasan08262882012-12-28 19:29:43 -0800325 // of the backoff at the next update check.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800326 // In either case, there's no need to update URL index or failure count.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700327 case ErrorCode::kOmahaRequestError:
328 case ErrorCode::kOmahaResponseHandlerError:
329 case ErrorCode::kPostinstallRunnerError:
330 case ErrorCode::kFilesystemCopierError:
331 case ErrorCode::kInstallDeviceOpenError:
332 case ErrorCode::kKernelDeviceOpenError:
333 case ErrorCode::kDownloadNewPartitionInfoError:
334 case ErrorCode::kNewRootfsVerificationError:
335 case ErrorCode::kNewKernelVerificationError:
336 case ErrorCode::kPostinstallBootedFromFirmwareB:
337 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
338 case ErrorCode::kOmahaRequestEmptyResponseError:
339 case ErrorCode::kOmahaRequestXMLParseError:
340 case ErrorCode::kOmahaResponseInvalid:
341 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
342 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
Kevin Cernekee2494e282016-03-29 18:03:53 -0700343 case ErrorCode::kNonCriticalUpdateInOOBE:
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700344 case ErrorCode::kOmahaUpdateDeferredForBackoff:
345 case ErrorCode::kPostinstallPowerwashError:
346 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -0400347 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -0700348 case ErrorCode::kFilesystemVerifierError:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800349 case ErrorCode::kUserCanceled:
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800350 LOG(INFO) << "Not incrementing URL index or failure count for this error";
351 break;
352
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700353 case ErrorCode::kSuccess: // success code
354 case ErrorCode::kUmaReportedMax: // not an error code
355 case ErrorCode::kOmahaRequestHTTPResponseBase: // aggregated already
356 case ErrorCode::kDevModeFlag: // not an error code
357 case ErrorCode::kResumedFlag: // not an error code
358 case ErrorCode::kTestImageFlag: // not an error code
359 case ErrorCode::kTestOmahaUrlFlag: // not an error code
360 case ErrorCode::kSpecialFlags: // not an error code
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800361 // These shouldn't happen. Enumerating these explicitly here so that we
362 // can let the compiler warn about new error codes that are added to
363 // action_processor.h but not added here.
364 LOG(WARNING) << "Unexpected error code for UpdateFailed";
365 break;
366
367 // Note: Not adding a default here so as to let the compiler warn us of
368 // any new enums that were added in the .h but not listed in this switch.
369 }
370}
371
Jay Srinivasan08262882012-12-28 19:29:43 -0800372bool PayloadState::ShouldBackoffDownload() {
373 if (response_.disable_payload_backoff) {
374 LOG(INFO) << "Payload backoff logic is disabled. "
375 "Can proceed with the download";
376 return false;
377 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700378 if (GetUsingP2PForDownloading() && !GetP2PUrl().empty()) {
Chris Sosa20f005c2013-09-05 13:53:08 -0700379 LOG(INFO) << "Payload backoff logic is disabled because download "
380 << "will happen from local peer (via p2p).";
381 return false;
382 }
383 if (system_state_->request_params()->interactive()) {
384 LOG(INFO) << "Payload backoff disabled for interactive update checks.";
385 return false;
386 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800387 if (response_.is_delta_payload) {
388 // If delta payloads fail, we want to fallback quickly to full payloads as
389 // they are more likely to succeed. Exponential backoffs would greatly
390 // slow down the fallback to full payloads. So we don't backoff for delta
391 // payloads.
392 LOG(INFO) << "No backoffs for delta payloads. "
393 << "Can proceed with the download";
394 return false;
395 }
396
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700397 if (!system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800398 // Backoffs are needed only for official builds. We do not want any delays
399 // or update failures due to backoffs during testing or development.
400 LOG(INFO) << "No backoffs for test/dev images. "
401 << "Can proceed with the download";
402 return false;
403 }
404
405 if (backoff_expiry_time_.is_null()) {
406 LOG(INFO) << "No backoff expiry time has been set. "
407 << "Can proceed with the download";
408 return false;
409 }
410
411 if (backoff_expiry_time_ < Time::Now()) {
412 LOG(INFO) << "The backoff expiry time ("
413 << utils::ToString(backoff_expiry_time_)
414 << ") has elapsed. Can proceed with the download";
415 return false;
416 }
417
418 LOG(INFO) << "Cannot proceed with downloads as we need to backoff until "
419 << utils::ToString(backoff_expiry_time_);
420 return true;
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800421}
422
Chris Sosaaa18e162013-06-20 13:20:30 -0700423void PayloadState::Rollback() {
424 SetRollbackVersion(system_state_->request_params()->app_version());
David Zeuthenafed4a12014-04-09 15:28:44 -0700425 AttemptStarted(AttemptType::kRollback);
Chris Sosaaa18e162013-06-20 13:20:30 -0700426}
427
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800428void PayloadState::IncrementPayloadAttemptNumber() {
Alex Deymo820cc702013-06-28 15:43:46 -0700429 // Update the payload attempt number for both payload types: full and delta.
430 SetPayloadAttemptNumber(GetPayloadAttemptNumber() + 1);
431}
432
433void PayloadState::IncrementFullPayloadAttemptNumber() {
434 // Update the payload attempt number for full payloads and the backoff time.
Jay Srinivasan08262882012-12-28 19:29:43 -0800435 if (response_.is_delta_payload) {
436 LOG(INFO) << "Not incrementing payload attempt number for delta payloads";
437 return;
438 }
439
Alex Deymo29b51d92013-07-09 15:26:24 -0700440 LOG(INFO) << "Incrementing the full payload attempt number";
Alex Deymo820cc702013-06-28 15:43:46 -0700441 SetFullPayloadAttemptNumber(GetFullPayloadAttemptNumber() + 1);
Jay Srinivasan08262882012-12-28 19:29:43 -0800442 UpdateBackoffExpiryTime();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800443}
444
445void PayloadState::IncrementUrlIndex() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800446 uint32_t next_url_index = GetUrlIndex() + 1;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700447 if (next_url_index < candidate_urls_.size()) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800448 LOG(INFO) << "Incrementing the URL index for next attempt";
449 SetUrlIndex(next_url_index);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800450 } else {
451 LOG(INFO) << "Resetting the current URL index (" << GetUrlIndex() << ") to "
Jay Srinivasan53173b92013-05-17 17:13:01 -0700452 << "0 as we only have " << candidate_urls_.size()
453 << " candidate URL(s)";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800454 SetUrlIndex(0);
Alex Deymo29b51d92013-07-09 15:26:24 -0700455 IncrementPayloadAttemptNumber();
456 IncrementFullPayloadAttemptNumber();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800457 }
Jay Srinivasan08262882012-12-28 19:29:43 -0800458
David Zeuthencc6f9962013-04-18 11:57:24 -0700459 // If we have multiple URLs, record that we just switched to another one
Jay Srinivasan53173b92013-05-17 17:13:01 -0700460 if (candidate_urls_.size() > 1)
David Zeuthencc6f9962013-04-18 11:57:24 -0700461 SetUrlSwitchCount(url_switch_count_ + 1);
462
Jay Srinivasan08262882012-12-28 19:29:43 -0800463 // Whenever we update the URL index, we should also clear the URL failure
464 // count so we can start over fresh for the new URL.
465 SetUrlFailureCount(0);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800466}
467
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800468void PayloadState::IncrementFailureCount() {
469 uint32_t next_url_failure_count = GetUrlFailureCount() + 1;
Jay Srinivasan08262882012-12-28 19:29:43 -0800470 if (next_url_failure_count < response_.max_failure_count_per_url) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800471 LOG(INFO) << "Incrementing the URL failure count";
472 SetUrlFailureCount(next_url_failure_count);
473 } else {
474 LOG(INFO) << "Reached max number of failures for Url" << GetUrlIndex()
475 << ". Trying next available URL";
476 IncrementUrlIndex();
477 }
478}
479
Jay Srinivasan08262882012-12-28 19:29:43 -0800480void PayloadState::UpdateBackoffExpiryTime() {
481 if (response_.disable_payload_backoff) {
482 LOG(INFO) << "Resetting backoff expiry time as payload backoff is disabled";
483 SetBackoffExpiryTime(Time());
484 return;
485 }
486
Alex Deymo820cc702013-06-28 15:43:46 -0700487 if (GetFullPayloadAttemptNumber() == 0) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800488 SetBackoffExpiryTime(Time());
489 return;
490 }
491
492 // Since we're doing left-shift below, make sure we don't shift more
Alex Deymo820cc702013-06-28 15:43:46 -0700493 // than this. E.g. if int is 4-bytes, don't left-shift more than 30 bits,
Jay Srinivasan08262882012-12-28 19:29:43 -0800494 // since we don't expect value of kMaxBackoffDays to be more than 100 anyway.
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700495 int num_days = 1; // the value to be shifted.
Alex Deymo820cc702013-06-28 15:43:46 -0700496 const int kMaxShifts = (sizeof(num_days) * 8) - 2;
Jay Srinivasan08262882012-12-28 19:29:43 -0800497
498 // Normal backoff days is 2 raised to (payload_attempt_number - 1).
499 // E.g. if payload_attempt_number is over 30, limit power to 30.
Alex Deymo820cc702013-06-28 15:43:46 -0700500 int power = min(GetFullPayloadAttemptNumber() - 1, kMaxShifts);
Jay Srinivasan08262882012-12-28 19:29:43 -0800501
502 // The number of days is the minimum of 2 raised to (payload_attempt_number
503 // - 1) or kMaxBackoffDays.
504 num_days = min(num_days << power, kMaxBackoffDays);
505
506 // We don't want all retries to happen exactly at the same time when
507 // retrying after backoff. So add some random minutes to fuzz.
508 int fuzz_minutes = utils::FuzzInt(0, kMaxBackoffFuzzMinutes);
509 TimeDelta next_backoff_interval = TimeDelta::FromDays(num_days) +
510 TimeDelta::FromMinutes(fuzz_minutes);
511 LOG(INFO) << "Incrementing the backoff expiry time by "
512 << utils::FormatTimeDelta(next_backoff_interval);
513 SetBackoffExpiryTime(Time::Now() + next_backoff_interval);
514}
515
Jay Srinivasan19409b72013-04-12 19:23:36 -0700516void PayloadState::UpdateCurrentDownloadSource() {
517 current_download_source_ = kNumDownloadSources;
518
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700519 if (using_p2p_for_downloading_) {
520 current_download_source_ = kDownloadSourceHttpPeer;
521 } else if (GetUrlIndex() < candidate_urls_.size()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -0700522 string current_url = candidate_urls_[GetUrlIndex()];
Alex Vakulenko0103c362016-01-20 07:56:15 -0800523 if (base::StartsWith(current_url, "https://",
524 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700525 current_download_source_ = kDownloadSourceHttpsServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800526 } else if (base::StartsWith(current_url, "http://",
527 base::CompareCase::INSENSITIVE_ASCII)) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700528 current_download_source_ = kDownloadSourceHttpServer;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800529 }
Jay Srinivasan19409b72013-04-12 19:23:36 -0700530 }
531
532 LOG(INFO) << "Current download source: "
533 << utils::ToString(current_download_source_);
534}
535
536void PayloadState::UpdateBytesDownloaded(size_t count) {
537 SetCurrentBytesDownloaded(
538 current_download_source_,
539 GetCurrentBytesDownloaded(current_download_source_) + count,
540 false);
541 SetTotalBytesDownloaded(
542 current_download_source_,
543 GetTotalBytesDownloaded(current_download_source_) + count,
544 false);
David Zeuthen33bae492014-02-25 16:16:18 -0800545
546 attempt_num_bytes_downloaded_ += count;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700547}
548
David Zeuthen33bae492014-02-25 16:16:18 -0800549PayloadType PayloadState::CalculatePayloadType() {
550 PayloadType payload_type;
551 OmahaRequestParams* params = system_state_->request_params();
552 if (response_.is_delta_payload) {
553 payload_type = kPayloadTypeDelta;
554 } else if (params->delta_okay()) {
555 payload_type = kPayloadTypeFull;
556 } else { // Full payload, delta was not allowed by request.
557 payload_type = kPayloadTypeForcedFull;
558 }
559 return payload_type;
560}
561
562// TODO(zeuthen): Currently we don't report the UpdateEngine.Attempt.*
563// metrics if the attempt ends abnormally, e.g. if the update_engine
564// process crashes or the device is rebooted. See
565// http://crbug.com/357676
566void PayloadState::CollectAndReportAttemptMetrics(ErrorCode code) {
567 int attempt_number = GetPayloadAttemptNumber();
568
569 PayloadType payload_type = CalculatePayloadType();
570
571 int64_t payload_size = response_.size;
572
573 int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
574
575 ClockInterface *clock = system_state_->clock();
Alex Deymof329b932014-10-30 01:37:48 -0700576 TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
577 TimeDelta duration_uptime = clock->GetMonotonicTime() -
David Zeuthen33bae492014-02-25 16:16:18 -0800578 attempt_start_time_monotonic_;
579
580 int64_t payload_download_speed_bps = 0;
581 int64_t usec = duration_uptime.InMicroseconds();
582 if (usec > 0) {
583 double sec = static_cast<double>(usec) / Time::kMicrosecondsPerSecond;
584 double bps = static_cast<double>(payload_bytes_downloaded) / sec;
585 payload_download_speed_bps = static_cast<int64_t>(bps);
586 }
587
588 DownloadSource download_source = current_download_source_;
589
590 metrics::DownloadErrorCode payload_download_error_code =
591 metrics::DownloadErrorCode::kUnset;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700592 ErrorCode internal_error_code = ErrorCode::kSuccess;
Alex Deymo38429cf2015-11-11 18:27:22 -0800593 metrics::AttemptResult attempt_result = metrics_utils::GetAttemptResult(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800594
595 // Add additional detail to AttemptResult
596 switch (attempt_result) {
597 case metrics::AttemptResult::kPayloadDownloadError:
Alex Deymo38429cf2015-11-11 18:27:22 -0800598 payload_download_error_code = metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -0800599 break;
600
601 case metrics::AttemptResult::kInternalError:
602 internal_error_code = code;
603 break;
604
605 // Explicit fall-through for cases where we do not have additional
606 // detail. We avoid the default keyword to force people adding new
607 // AttemptResult values to visit this code and examine whether
608 // additional detail is needed.
609 case metrics::AttemptResult::kUpdateSucceeded:
610 case metrics::AttemptResult::kMetadataMalformed:
611 case metrics::AttemptResult::kOperationMalformed:
612 case metrics::AttemptResult::kOperationExecutionError:
613 case metrics::AttemptResult::kMetadataVerificationFailed:
614 case metrics::AttemptResult::kPayloadVerificationFailed:
615 case metrics::AttemptResult::kVerificationFailed:
616 case metrics::AttemptResult::kPostInstallFailed:
617 case metrics::AttemptResult::kAbnormalTermination:
Alex Deymo1f19dcc2016-02-03 09:22:17 -0800618 case metrics::AttemptResult::kUpdateCanceled:
David Zeuthen33bae492014-02-25 16:16:18 -0800619 case metrics::AttemptResult::kNumConstants:
620 case metrics::AttemptResult::kUnset:
621 break;
622 }
623
624 metrics::ReportUpdateAttemptMetrics(system_state_,
625 attempt_number,
626 payload_type,
627 duration,
628 duration_uptime,
629 payload_size,
630 payload_bytes_downloaded,
631 payload_download_speed_bps,
632 download_source,
633 attempt_result,
634 internal_error_code,
David Zeuthenb281f072014-04-02 10:20:19 -0700635 payload_download_error_code,
636 attempt_connection_type_);
David Zeuthen33bae492014-02-25 16:16:18 -0800637}
638
David Zeuthen4e1d1492014-04-25 13:12:27 -0700639void PayloadState::PersistAttemptMetrics() {
640 // TODO(zeuthen): For now we only persist whether an attempt was in
641 // progress and not values/metrics related to the attempt. This
642 // means that when this happens, of all the UpdateEngine.Attempt.*
643 // metrics, only UpdateEngine.Attempt.Result is reported (with the
644 // value |kAbnormalTermination|). In the future we might want to
645 // persist more data so we can report other metrics in the
646 // UpdateEngine.Attempt.* namespace when this happens.
647 prefs_->SetBoolean(kPrefsAttemptInProgress, true);
648}
649
650void PayloadState::ClearPersistedAttemptMetrics() {
651 prefs_->Delete(kPrefsAttemptInProgress);
652}
653
654void PayloadState::ReportAndClearPersistedAttemptMetrics() {
655 bool attempt_in_progress = false;
656 if (!prefs_->GetBoolean(kPrefsAttemptInProgress, &attempt_in_progress))
657 return;
658 if (!attempt_in_progress)
659 return;
660
661 metrics::ReportAbnormallyTerminatedUpdateAttemptMetrics(system_state_);
662
663 ClearPersistedAttemptMetrics();
664}
665
David Zeuthen33bae492014-02-25 16:16:18 -0800666void PayloadState::CollectAndReportSuccessfulUpdateMetrics() {
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700667 string metric;
David Zeuthen33bae492014-02-25 16:16:18 -0800668
669 // Report metrics collected from all known download sources to UMA.
David Zeuthen33bae492014-02-25 16:16:18 -0800670 int64_t total_bytes_by_source[kNumDownloadSources];
671 int64_t successful_bytes = 0;
672 int64_t total_bytes = 0;
673 int64_t successful_mbs = 0;
674 int64_t total_mbs = 0;
675
Jay Srinivasan19409b72013-04-12 19:23:36 -0700676 for (int i = 0; i < kNumDownloadSources; i++) {
677 DownloadSource source = static_cast<DownloadSource>(i);
David Zeuthen33bae492014-02-25 16:16:18 -0800678 int64_t bytes;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700679
David Zeuthen44848602013-06-24 13:32:14 -0700680 // Only consider this download source (and send byte counts) as
681 // having been used if we downloaded a non-trivial amount of bytes
682 // (e.g. at least 1 MiB) that contributed to the final success of
683 // the update. Otherwise we're going to end up with a lot of
684 // zero-byte events in the histogram.
Jay Srinivasandbd9ea22013-04-22 17:45:19 -0700685
David Zeuthen33bae492014-02-25 16:16:18 -0800686 bytes = GetCurrentBytesDownloaded(source);
David Zeuthen33bae492014-02-25 16:16:18 -0800687 successful_bytes += bytes;
688 successful_mbs += bytes / kNumBytesInOneMiB;
Jay Srinivasan19409b72013-04-12 19:23:36 -0700689 SetCurrentBytesDownloaded(source, 0, true);
690
David Zeuthen33bae492014-02-25 16:16:18 -0800691 bytes = GetTotalBytesDownloaded(source);
692 total_bytes_by_source[i] = bytes;
693 total_bytes += bytes;
694 total_mbs += bytes / kNumBytesInOneMiB;
695 SetTotalBytesDownloaded(source, 0, true);
696 }
697
698 int download_overhead_percentage = 0;
699 if (successful_bytes > 0) {
700 download_overhead_percentage = (total_bytes - successful_bytes) * 100ULL /
701 successful_bytes;
702 }
703
704 int url_switch_count = static_cast<int>(url_switch_count_);
705
706 int reboot_count = GetNumReboots();
707
708 SetNumReboots(0);
709
710 TimeDelta duration = GetUpdateDuration();
David Zeuthen33bae492014-02-25 16:16:18 -0800711
712 prefs_->Delete(kPrefsUpdateTimestampStart);
713 prefs_->Delete(kPrefsUpdateDurationUptime);
714
715 PayloadType payload_type = CalculatePayloadType();
716
717 int64_t payload_size = response_.size;
718
719 int attempt_count = GetPayloadAttemptNumber();
720
721 int updates_abandoned_count = num_responses_seen_ - 1;
722
723 metrics::ReportSuccessfulUpdateMetrics(system_state_,
724 attempt_count,
725 updates_abandoned_count,
726 payload_type,
727 payload_size,
728 total_bytes_by_source,
729 download_overhead_percentage,
730 duration,
731 reboot_count,
732 url_switch_count);
Chris Sosabe45bef2013-04-09 18:25:12 -0700733}
734
735void PayloadState::UpdateNumReboots() {
736 // We only update the reboot count when the system has been detected to have
737 // been rebooted.
738 if (!system_state_->system_rebooted()) {
739 return;
740 }
741
742 SetNumReboots(GetNumReboots() + 1);
743}
744
745void PayloadState::SetNumReboots(uint32_t num_reboots) {
746 CHECK(prefs_);
747 num_reboots_ = num_reboots;
748 prefs_->SetInt64(kPrefsNumReboots, num_reboots);
749 LOG(INFO) << "Number of Reboots during current update attempt = "
750 << num_reboots_;
751}
752
Jay Srinivasan08262882012-12-28 19:29:43 -0800753void PayloadState::ResetPersistedState() {
754 SetPayloadAttemptNumber(0);
Alex Deymo820cc702013-06-28 15:43:46 -0700755 SetFullPayloadAttemptNumber(0);
Jay Srinivasan08262882012-12-28 19:29:43 -0800756 SetUrlIndex(0);
757 SetUrlFailureCount(0);
David Zeuthencc6f9962013-04-18 11:57:24 -0700758 SetUrlSwitchCount(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700759 UpdateBackoffExpiryTime(); // This will reset the backoff expiry time.
David Zeuthenf413fe52013-04-22 14:04:39 -0700760 SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700761 SetUpdateTimestampEnd(Time()); // Set to null time
David Zeuthen9a017f22013-04-11 16:10:26 -0700762 SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
Jay Srinivasan19409b72013-04-12 19:23:36 -0700763 ResetDownloadSourcesOnNewUpdate();
Chris Sosaaa18e162013-06-20 13:20:30 -0700764 ResetRollbackVersion();
David Zeuthendcba8092013-08-06 12:16:35 -0700765 SetP2PNumAttempts(0);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700766 SetP2PFirstAttemptTimestamp(Time()); // Set to null time
Alex Deymof329b932014-10-30 01:37:48 -0700767 SetScatteringWaitPeriod(TimeDelta());
Chris Sosaaa18e162013-06-20 13:20:30 -0700768}
769
770void PayloadState::ResetRollbackVersion() {
771 CHECK(powerwash_safe_prefs_);
772 rollback_version_ = "";
773 powerwash_safe_prefs_->Delete(kPrefsRollbackVersion);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700774}
775
776void PayloadState::ResetDownloadSourcesOnNewUpdate() {
777 for (int i = 0; i < kNumDownloadSources; i++) {
778 DownloadSource source = static_cast<DownloadSource>(i);
779 SetCurrentBytesDownloaded(source, 0, true);
780 // Note: Not resetting the TotalBytesDownloaded as we want that metric
781 // to count the bytes downloaded across various update attempts until
782 // we have successfully applied the update.
783 }
784}
785
Chris Sosab3dcdb32013-09-04 15:22:12 -0700786int64_t PayloadState::GetPersistedValue(const string& key) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700787 CHECK(prefs_);
Chris Sosab3dcdb32013-09-04 15:22:12 -0700788 if (!prefs_->Exists(key))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700789 return 0;
790
791 int64_t stored_value;
Chris Sosab3dcdb32013-09-04 15:22:12 -0700792 if (!prefs_->GetInt64(key, &stored_value))
Jay Srinivasan19409b72013-04-12 19:23:36 -0700793 return 0;
794
795 if (stored_value < 0) {
796 LOG(ERROR) << key << ": Invalid value (" << stored_value
797 << ") in persisted state. Defaulting to 0";
798 return 0;
799 }
800
801 return stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800802}
803
804string PayloadState::CalculateResponseSignature() {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700805 string response_sign = base::StringPrintf(
806 "NumURLs = %d\n", static_cast<int>(candidate_urls_.size()));
Jay Srinivasan08262882012-12-28 19:29:43 -0800807
Jay Srinivasan53173b92013-05-17 17:13:01 -0700808 for (size_t i = 0; i < candidate_urls_.size(); i++)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700809 response_sign += base::StringPrintf("Candidate Url%d = %s\n",
810 static_cast<int>(i),
811 candidate_urls_[i].c_str());
Jay Srinivasan08262882012-12-28 19:29:43 -0800812
Alex Vakulenko75039d72014-03-25 12:36:28 -0700813 response_sign += base::StringPrintf(
814 "Payload Size = %ju\n"
815 "Payload Sha256 Hash = %s\n"
816 "Metadata Size = %ju\n"
817 "Metadata Signature = %s\n"
818 "Is Delta Payload = %d\n"
819 "Max Failure Count Per Url = %d\n"
820 "Disable Payload Backoff = %d\n",
821 static_cast<uintmax_t>(response_.size),
822 response_.hash.c_str(),
823 static_cast<uintmax_t>(response_.metadata_size),
824 response_.metadata_signature.c_str(),
825 response_.is_delta_payload,
826 response_.max_failure_count_per_url,
827 response_.disable_payload_backoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800828 return response_sign;
829}
830
831void PayloadState::LoadResponseSignature() {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800832 CHECK(prefs_);
833 string stored_value;
Jay Srinivasan08262882012-12-28 19:29:43 -0800834 if (prefs_->Exists(kPrefsCurrentResponseSignature) &&
835 prefs_->GetString(kPrefsCurrentResponseSignature, &stored_value)) {
836 SetResponseSignature(stored_value);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800837 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800838}
839
Jay Srinivasan19409b72013-04-12 19:23:36 -0700840void PayloadState::SetResponseSignature(const string& response_signature) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800841 CHECK(prefs_);
842 response_signature_ = response_signature;
843 LOG(INFO) << "Current Response Signature = \n" << response_signature_;
844 prefs_->SetString(kPrefsCurrentResponseSignature, response_signature_);
845}
846
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800847void PayloadState::LoadPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700848 SetPayloadAttemptNumber(GetPersistedValue(kPrefsPayloadAttemptNumber));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800849}
850
Alex Deymo820cc702013-06-28 15:43:46 -0700851void PayloadState::LoadFullPayloadAttemptNumber() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700852 SetFullPayloadAttemptNumber(GetPersistedValue(
853 kPrefsFullPayloadAttemptNumber));
Alex Deymo820cc702013-06-28 15:43:46 -0700854}
855
856void PayloadState::SetPayloadAttemptNumber(int payload_attempt_number) {
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800857 CHECK(prefs_);
858 payload_attempt_number_ = payload_attempt_number;
859 LOG(INFO) << "Payload Attempt Number = " << payload_attempt_number_;
860 prefs_->SetInt64(kPrefsPayloadAttemptNumber, payload_attempt_number_);
861}
862
Alex Deymo820cc702013-06-28 15:43:46 -0700863void PayloadState::SetFullPayloadAttemptNumber(
864 int full_payload_attempt_number) {
865 CHECK(prefs_);
866 full_payload_attempt_number_ = full_payload_attempt_number;
867 LOG(INFO) << "Full Payload Attempt Number = " << full_payload_attempt_number_;
868 prefs_->SetInt64(kPrefsFullPayloadAttemptNumber,
869 full_payload_attempt_number_);
870}
871
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800872void PayloadState::LoadUrlIndex() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700873 SetUrlIndex(GetPersistedValue(kPrefsCurrentUrlIndex));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800874}
875
876void PayloadState::SetUrlIndex(uint32_t url_index) {
877 CHECK(prefs_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800878 url_index_ = url_index;
879 LOG(INFO) << "Current URL Index = " << url_index_;
880 prefs_->SetInt64(kPrefsCurrentUrlIndex, url_index_);
Jay Srinivasan19409b72013-04-12 19:23:36 -0700881
882 // Also update the download source, which is purely dependent on the
883 // current URL index alone.
884 UpdateCurrentDownloadSource();
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800885}
886
Gilad Arnold519cfc72014-10-02 10:34:54 -0700887void PayloadState::LoadScatteringWaitPeriod() {
888 SetScatteringWaitPeriod(
889 TimeDelta::FromSeconds(GetPersistedValue(kPrefsWallClockWaitPeriod)));
890}
891
Alex Deymof329b932014-10-30 01:37:48 -0700892void PayloadState::SetScatteringWaitPeriod(TimeDelta wait_period) {
Gilad Arnold519cfc72014-10-02 10:34:54 -0700893 CHECK(prefs_);
894 scattering_wait_period_ = wait_period;
895 LOG(INFO) << "Scattering Wait Period (seconds) = "
896 << scattering_wait_period_.InSeconds();
897 if (scattering_wait_period_.InSeconds() > 0) {
898 prefs_->SetInt64(kPrefsWallClockWaitPeriod,
899 scattering_wait_period_.InSeconds());
900 } else {
901 prefs_->Delete(kPrefsWallClockWaitPeriod);
902 }
903}
904
David Zeuthencc6f9962013-04-18 11:57:24 -0700905void PayloadState::LoadUrlSwitchCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700906 SetUrlSwitchCount(GetPersistedValue(kPrefsUrlSwitchCount));
David Zeuthencc6f9962013-04-18 11:57:24 -0700907}
908
909void PayloadState::SetUrlSwitchCount(uint32_t url_switch_count) {
910 CHECK(prefs_);
911 url_switch_count_ = url_switch_count;
912 LOG(INFO) << "URL Switch Count = " << url_switch_count_;
913 prefs_->SetInt64(kPrefsUrlSwitchCount, url_switch_count_);
914}
915
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800916void PayloadState::LoadUrlFailureCount() {
Chris Sosab3dcdb32013-09-04 15:22:12 -0700917 SetUrlFailureCount(GetPersistedValue(kPrefsCurrentUrlFailureCount));
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800918}
919
920void PayloadState::SetUrlFailureCount(uint32_t url_failure_count) {
921 CHECK(prefs_);
922 url_failure_count_ = url_failure_count;
923 LOG(INFO) << "Current URL (Url" << GetUrlIndex()
924 << ")'s Failure Count = " << url_failure_count_;
925 prefs_->SetInt64(kPrefsCurrentUrlFailureCount, url_failure_count_);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800926}
927
Jay Srinivasan08262882012-12-28 19:29:43 -0800928void PayloadState::LoadBackoffExpiryTime() {
929 CHECK(prefs_);
930 int64_t stored_value;
931 if (!prefs_->Exists(kPrefsBackoffExpiryTime))
932 return;
933
934 if (!prefs_->GetInt64(kPrefsBackoffExpiryTime, &stored_value))
935 return;
936
937 Time stored_time = Time::FromInternalValue(stored_value);
938 if (stored_time > Time::Now() + TimeDelta::FromDays(kMaxBackoffDays)) {
939 LOG(ERROR) << "Invalid backoff expiry time ("
940 << utils::ToString(stored_time)
941 << ") in persisted state. Resetting.";
942 stored_time = Time();
943 }
944 SetBackoffExpiryTime(stored_time);
945}
946
947void PayloadState::SetBackoffExpiryTime(const Time& new_time) {
948 CHECK(prefs_);
949 backoff_expiry_time_ = new_time;
950 LOG(INFO) << "Backoff Expiry Time = "
951 << utils::ToString(backoff_expiry_time_);
952 prefs_->SetInt64(kPrefsBackoffExpiryTime,
953 backoff_expiry_time_.ToInternalValue());
954}
955
David Zeuthen9a017f22013-04-11 16:10:26 -0700956TimeDelta PayloadState::GetUpdateDuration() {
David Zeuthenf413fe52013-04-22 14:04:39 -0700957 Time end_time = update_timestamp_end_.is_null()
958 ? system_state_->clock()->GetWallclockTime() :
959 update_timestamp_end_;
David Zeuthen9a017f22013-04-11 16:10:26 -0700960 return end_time - update_timestamp_start_;
961}
962
963void PayloadState::LoadUpdateTimestampStart() {
964 int64_t stored_value;
965 Time stored_time;
966
967 CHECK(prefs_);
968
David Zeuthenf413fe52013-04-22 14:04:39 -0700969 Time now = system_state_->clock()->GetWallclockTime();
David Zeuthen9a017f22013-04-11 16:10:26 -0700970
971 if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
972 // The preference missing is not unexpected - in that case, just
973 // use the current time as start time
974 stored_time = now;
975 } else if (!prefs_->GetInt64(kPrefsUpdateTimestampStart, &stored_value)) {
976 LOG(ERROR) << "Invalid UpdateTimestampStart value. Resetting.";
977 stored_time = now;
978 } else {
979 stored_time = Time::FromInternalValue(stored_value);
980 }
981
982 // Sanity check: If the time read from disk is in the future
983 // (modulo some slack to account for possible NTP drift
984 // adjustments), something is fishy and we should report and
985 // reset.
986 TimeDelta duration_according_to_stored_time = now - stored_time;
987 if (duration_according_to_stored_time < -kDurationSlack) {
988 LOG(ERROR) << "The UpdateTimestampStart value ("
989 << utils::ToString(stored_time)
990 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -0700991 << utils::FormatTimeDelta(duration_according_to_stored_time)
992 << " in the future. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -0700993 stored_time = now;
994 }
995
996 SetUpdateTimestampStart(stored_time);
997}
998
999void PayloadState::SetUpdateTimestampStart(const Time& value) {
1000 CHECK(prefs_);
1001 update_timestamp_start_ = value;
1002 prefs_->SetInt64(kPrefsUpdateTimestampStart,
1003 update_timestamp_start_.ToInternalValue());
1004 LOG(INFO) << "Update Timestamp Start = "
1005 << utils::ToString(update_timestamp_start_);
1006}
1007
1008void PayloadState::SetUpdateTimestampEnd(const Time& value) {
1009 update_timestamp_end_ = value;
1010 LOG(INFO) << "Update Timestamp End = "
1011 << utils::ToString(update_timestamp_end_);
1012}
1013
1014TimeDelta PayloadState::GetUpdateDurationUptime() {
1015 return update_duration_uptime_;
1016}
1017
1018void PayloadState::LoadUpdateDurationUptime() {
1019 int64_t stored_value;
1020 TimeDelta stored_delta;
1021
1022 CHECK(prefs_);
1023
1024 if (!prefs_->Exists(kPrefsUpdateDurationUptime)) {
1025 // The preference missing is not unexpected - in that case, just
1026 // we'll use zero as the delta
1027 } else if (!prefs_->GetInt64(kPrefsUpdateDurationUptime, &stored_value)) {
1028 LOG(ERROR) << "Invalid UpdateDurationUptime value. Resetting.";
1029 stored_delta = TimeDelta::FromSeconds(0);
1030 } else {
1031 stored_delta = TimeDelta::FromInternalValue(stored_value);
1032 }
1033
1034 // Sanity-check: Uptime can never be greater than the wall-clock
1035 // difference (modulo some slack). If it is, report and reset
1036 // to the wall-clock difference.
1037 TimeDelta diff = GetUpdateDuration() - stored_delta;
1038 if (diff < -kDurationSlack) {
1039 LOG(ERROR) << "The UpdateDurationUptime value ("
David Zeuthen674c3182013-04-18 14:05:20 -07001040 << utils::FormatTimeDelta(stored_delta)
David Zeuthen9a017f22013-04-11 16:10:26 -07001041 << ") in persisted state is "
David Zeuthen674c3182013-04-18 14:05:20 -07001042 << utils::FormatTimeDelta(diff)
1043 << " larger than the wall-clock delta. Resetting.";
David Zeuthen9a017f22013-04-11 16:10:26 -07001044 stored_delta = update_duration_current_;
1045 }
1046
1047 SetUpdateDurationUptime(stored_delta);
1048}
1049
Chris Sosabe45bef2013-04-09 18:25:12 -07001050void PayloadState::LoadNumReboots() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001051 SetNumReboots(GetPersistedValue(kPrefsNumReboots));
Chris Sosaaa18e162013-06-20 13:20:30 -07001052}
1053
1054void PayloadState::LoadRollbackVersion() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001055 CHECK(powerwash_safe_prefs_);
1056 string rollback_version;
1057 if (powerwash_safe_prefs_->GetString(kPrefsRollbackVersion,
1058 &rollback_version)) {
1059 SetRollbackVersion(rollback_version);
1060 }
Chris Sosaaa18e162013-06-20 13:20:30 -07001061}
1062
1063void PayloadState::SetRollbackVersion(const string& rollback_version) {
1064 CHECK(powerwash_safe_prefs_);
1065 LOG(INFO) << "Blacklisting version "<< rollback_version;
1066 rollback_version_ = rollback_version;
1067 powerwash_safe_prefs_->SetString(kPrefsRollbackVersion, rollback_version);
Chris Sosabe45bef2013-04-09 18:25:12 -07001068}
1069
David Zeuthen9a017f22013-04-11 16:10:26 -07001070void PayloadState::SetUpdateDurationUptimeExtended(const TimeDelta& value,
1071 const Time& timestamp,
1072 bool use_logging) {
1073 CHECK(prefs_);
1074 update_duration_uptime_ = value;
1075 update_duration_uptime_timestamp_ = timestamp;
1076 prefs_->SetInt64(kPrefsUpdateDurationUptime,
1077 update_duration_uptime_.ToInternalValue());
1078 if (use_logging) {
1079 LOG(INFO) << "Update Duration Uptime = "
David Zeuthen674c3182013-04-18 14:05:20 -07001080 << utils::FormatTimeDelta(update_duration_uptime_);
David Zeuthen9a017f22013-04-11 16:10:26 -07001081 }
1082}
1083
1084void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
David Zeuthenf413fe52013-04-22 14:04:39 -07001085 Time now = system_state_->clock()->GetMonotonicTime();
1086 SetUpdateDurationUptimeExtended(value, now, true);
David Zeuthen9a017f22013-04-11 16:10:26 -07001087}
1088
1089void PayloadState::CalculateUpdateDurationUptime() {
David Zeuthenf413fe52013-04-22 14:04:39 -07001090 Time now = system_state_->clock()->GetMonotonicTime();
David Zeuthen9a017f22013-04-11 16:10:26 -07001091 TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
1092 TimeDelta new_uptime = update_duration_uptime_ + uptime_since_last_update;
1093 // We're frequently called so avoid logging this write
1094 SetUpdateDurationUptimeExtended(new_uptime, now, false);
1095}
1096
Jay Srinivasan19409b72013-04-12 19:23:36 -07001097string PayloadState::GetPrefsKey(const string& prefix, DownloadSource source) {
1098 return prefix + "-from-" + utils::ToString(source);
1099}
1100
1101void PayloadState::LoadCurrentBytesDownloaded(DownloadSource source) {
1102 string key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001103 SetCurrentBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001104}
1105
1106void PayloadState::SetCurrentBytesDownloaded(
1107 DownloadSource source,
1108 uint64_t current_bytes_downloaded,
1109 bool log) {
1110 CHECK(prefs_);
1111
1112 if (source >= kNumDownloadSources)
1113 return;
1114
1115 // Update the in-memory value.
1116 current_bytes_downloaded_[source] = current_bytes_downloaded;
1117
1118 string prefs_key = GetPrefsKey(kPrefsCurrentBytesDownloaded, source);
1119 prefs_->SetInt64(prefs_key, current_bytes_downloaded);
1120 LOG_IF(INFO, log) << "Current bytes downloaded for "
1121 << utils::ToString(source) << " = "
1122 << GetCurrentBytesDownloaded(source);
1123}
1124
1125void PayloadState::LoadTotalBytesDownloaded(DownloadSource source) {
1126 string key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
Chris Sosab3dcdb32013-09-04 15:22:12 -07001127 SetTotalBytesDownloaded(source, GetPersistedValue(key), true);
Jay Srinivasan19409b72013-04-12 19:23:36 -07001128}
1129
1130void PayloadState::SetTotalBytesDownloaded(
1131 DownloadSource source,
1132 uint64_t total_bytes_downloaded,
1133 bool log) {
1134 CHECK(prefs_);
1135
1136 if (source >= kNumDownloadSources)
1137 return;
1138
1139 // Update the in-memory value.
1140 total_bytes_downloaded_[source] = total_bytes_downloaded;
1141
1142 // Persist.
1143 string prefs_key = GetPrefsKey(kPrefsTotalBytesDownloaded, source);
1144 prefs_->SetInt64(prefs_key, total_bytes_downloaded);
1145 LOG_IF(INFO, log) << "Total bytes downloaded for "
1146 << utils::ToString(source) << " = "
1147 << GetTotalBytesDownloaded(source);
1148}
1149
David Zeuthena573d6f2013-06-14 16:13:36 -07001150void PayloadState::LoadNumResponsesSeen() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001151 SetNumResponsesSeen(GetPersistedValue(kPrefsNumResponsesSeen));
David Zeuthena573d6f2013-06-14 16:13:36 -07001152}
1153
1154void PayloadState::SetNumResponsesSeen(int num_responses_seen) {
1155 CHECK(prefs_);
1156 num_responses_seen_ = num_responses_seen;
1157 LOG(INFO) << "Num Responses Seen = " << num_responses_seen_;
1158 prefs_->SetInt64(kPrefsNumResponsesSeen, num_responses_seen_);
1159}
1160
Jay Srinivasan53173b92013-05-17 17:13:01 -07001161void PayloadState::ComputeCandidateUrls() {
Chris Sosaf7d80042013-08-22 16:45:17 -07001162 bool http_url_ok = true;
Jay Srinivasan53173b92013-05-17 17:13:01 -07001163
J. Richard Barnette056b0ab2013-10-29 15:24:56 -07001164 if (system_state_->hardware()->IsOfficialBuild()) {
Jay Srinivasan53173b92013-05-17 17:13:01 -07001165 const policy::DevicePolicy* policy = system_state_->device_policy();
Chris Sosaf7d80042013-08-22 16:45:17 -07001166 if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
Jay Srinivasan53173b92013-05-17 17:13:01 -07001167 LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
1168 } else {
1169 LOG(INFO) << "Allowing HTTP downloads for unofficial builds";
1170 http_url_ok = true;
1171 }
1172
1173 candidate_urls_.clear();
1174 for (size_t i = 0; i < response_.payload_urls.size(); i++) {
1175 string candidate_url = response_.payload_urls[i];
Alex Vakulenko0103c362016-01-20 07:56:15 -08001176 if (base::StartsWith(candidate_url, "http://",
1177 base::CompareCase::INSENSITIVE_ASCII) &&
1178 !http_url_ok) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -07001179 continue;
Alex Vakulenko0103c362016-01-20 07:56:15 -08001180 }
Jay Srinivasan53173b92013-05-17 17:13:01 -07001181 candidate_urls_.push_back(candidate_url);
1182 LOG(INFO) << "Candidate Url" << (candidate_urls_.size() - 1)
1183 << ": " << candidate_url;
1184 }
1185
1186 LOG(INFO) << "Found " << candidate_urls_.size() << " candidate URLs "
1187 << "out of " << response_.payload_urls.size() << " URLs supplied";
1188}
1189
David Zeuthene4c58bf2013-06-18 17:26:50 -07001190void PayloadState::CreateSystemUpdatedMarkerFile() {
1191 CHECK(prefs_);
1192 int64_t value = system_state_->clock()->GetWallclockTime().ToInternalValue();
1193 prefs_->SetInt64(kPrefsSystemUpdatedMarker, value);
1194}
1195
1196void PayloadState::BootedIntoUpdate(TimeDelta time_to_reboot) {
1197 // Send |time_to_reboot| as a UMA stat.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001198 string metric = metrics::kMetricTimeToRebootMinutes;
David Zeuthen33bae492014-02-25 16:16:18 -08001199 system_state_->metrics_lib()->SendToUMA(metric,
1200 time_to_reboot.InMinutes(),
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001201 0, // min: 0 minute
1202 30*24*60, // max: 1 month (approx)
David Zeuthen33bae492014-02-25 16:16:18 -08001203 kNumDefaultUmaBuckets);
1204 LOG(INFO) << "Uploading " << utils::FormatTimeDelta(time_to_reboot)
1205 << " for metric " << metric;
David Zeuthene4c58bf2013-06-18 17:26:50 -07001206}
1207
1208void PayloadState::UpdateEngineStarted() {
David Zeuthen4e1d1492014-04-25 13:12:27 -07001209 // Flush previous state from abnormal attempt failure, if any.
1210 ReportAndClearPersistedAttemptMetrics();
1211
Alex Deymo569c4242013-07-24 12:01:01 -07001212 // Avoid the UpdateEngineStarted actions if this is not the first time we
1213 // run the update engine since reboot.
1214 if (!system_state_->system_rebooted())
1215 return;
1216
David Zeuthene4c58bf2013-06-18 17:26:50 -07001217 // Figure out if we just booted into a new update
1218 if (prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1219 int64_t stored_value;
1220 if (prefs_->GetInt64(kPrefsSystemUpdatedMarker, &stored_value)) {
1221 Time system_updated_at = Time::FromInternalValue(stored_value);
1222 if (!system_updated_at.is_null()) {
1223 TimeDelta time_to_reboot =
1224 system_state_->clock()->GetWallclockTime() - system_updated_at;
1225 if (time_to_reboot.ToInternalValue() < 0) {
1226 LOG(ERROR) << "time_to_reboot is negative - system_updated_at: "
1227 << utils::ToString(system_updated_at);
1228 } else {
1229 BootedIntoUpdate(time_to_reboot);
1230 }
1231 }
1232 }
1233 prefs_->Delete(kPrefsSystemUpdatedMarker);
1234 }
Alex Deymo42432912013-07-12 20:21:15 -07001235 // Check if it is needed to send metrics about a failed reboot into a new
1236 // version.
1237 ReportFailedBootIfNeeded();
1238}
1239
1240void PayloadState::ReportFailedBootIfNeeded() {
1241 // If the kPrefsTargetVersionInstalledFrom is present, a successfully applied
1242 // payload was marked as ready immediately before the last reboot, and we
1243 // need to check if such payload successfully rebooted or not.
1244 if (prefs_->Exists(kPrefsTargetVersionInstalledFrom)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001245 int64_t installed_from = 0;
1246 if (!prefs_->GetInt64(kPrefsTargetVersionInstalledFrom, &installed_from)) {
Alex Deymo42432912013-07-12 20:21:15 -07001247 LOG(ERROR) << "Error reading TargetVersionInstalledFrom on reboot.";
1248 return;
1249 }
Alex Deymo763e7db2015-08-27 21:08:08 -07001250 // Old Chrome OS devices will write 2 or 4 in this setting, with the
1251 // partition number. We are now using slot numbers (0 or 1) instead, so
1252 // the following comparison will not match if we are comparing an old
1253 // partition number against a new slot number, which is the correct outcome
1254 // since we successfully booted the new update in that case. If the boot
1255 // failed, we will read this value from the same version, so it will always
1256 // be compatible.
1257 if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
Alex Deymo42432912013-07-12 20:21:15 -07001258 // A reboot was pending, but the chromebook is again in the same
1259 // BootDevice where the update was installed from.
1260 int64_t target_attempt;
1261 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt)) {
1262 LOG(ERROR) << "Error reading TargetVersionAttempt when "
1263 "TargetVersionInstalledFrom was present.";
1264 target_attempt = 1;
1265 }
1266
1267 // Report the UMA metric of the current boot failure.
Alex Deymoaf9a8632015-09-23 18:51:48 -07001268 string metric = metrics::kMetricFailedUpdateCount;
David Zeuthen33bae492014-02-25 16:16:18 -08001269 LOG(INFO) << "Uploading " << target_attempt
1270 << " (count) for metric " << metric;
1271 system_state_->metrics_lib()->SendToUMA(
1272 metric,
1273 target_attempt,
1274 1, // min value
1275 50, // max value
1276 kNumDefaultUmaBuckets);
Alex Deymo42432912013-07-12 20:21:15 -07001277 } else {
1278 prefs_->Delete(kPrefsTargetVersionAttempt);
1279 prefs_->Delete(kPrefsTargetVersionUniqueId);
1280 }
1281 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1282 }
1283}
1284
1285void PayloadState::ExpectRebootInNewVersion(const string& target_version_uid) {
1286 // Expect to boot into the new partition in the next reboot setting the
1287 // TargetVersion* flags in the Prefs.
1288 string stored_target_version_uid;
1289 string target_version_id;
1290 string target_partition;
1291 int64_t target_attempt;
1292
1293 if (prefs_->Exists(kPrefsTargetVersionUniqueId) &&
1294 prefs_->GetString(kPrefsTargetVersionUniqueId,
1295 &stored_target_version_uid) &&
1296 stored_target_version_uid == target_version_uid) {
1297 if (!prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
1298 target_attempt = 0;
1299 } else {
1300 prefs_->SetString(kPrefsTargetVersionUniqueId, target_version_uid);
1301 target_attempt = 0;
1302 }
1303 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
1304
Alex Vakulenko4f5b1442014-02-21 12:19:44 -08001305 prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
Alex Deymo763e7db2015-08-27 21:08:08 -07001306 system_state_->boot_control()->GetCurrentSlot());
Alex Deymo42432912013-07-12 20:21:15 -07001307}
1308
1309void PayloadState::ResetUpdateStatus() {
1310 // Remove the TargetVersionInstalledFrom pref so that if the machine is
1311 // rebooted the next boot is not flagged as failed to rebooted into the
1312 // new applied payload.
1313 prefs_->Delete(kPrefsTargetVersionInstalledFrom);
1314
1315 // Also decrement the attempt number if it exists.
1316 int64_t target_attempt;
1317 if (prefs_->GetInt64(kPrefsTargetVersionAttempt, &target_attempt))
Alex Deymo763e7db2015-08-27 21:08:08 -07001318 prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt - 1);
David Zeuthene4c58bf2013-06-18 17:26:50 -07001319}
1320
David Zeuthendcba8092013-08-06 12:16:35 -07001321int PayloadState::GetP2PNumAttempts() {
1322 return p2p_num_attempts_;
1323}
1324
1325void PayloadState::SetP2PNumAttempts(int value) {
1326 p2p_num_attempts_ = value;
1327 LOG(INFO) << "p2p Num Attempts = " << p2p_num_attempts_;
1328 CHECK(prefs_);
1329 prefs_->SetInt64(kPrefsP2PNumAttempts, value);
1330}
1331
1332void PayloadState::LoadP2PNumAttempts() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001333 SetP2PNumAttempts(GetPersistedValue(kPrefsP2PNumAttempts));
David Zeuthendcba8092013-08-06 12:16:35 -07001334}
1335
1336Time PayloadState::GetP2PFirstAttemptTimestamp() {
1337 return p2p_first_attempt_timestamp_;
1338}
1339
1340void PayloadState::SetP2PFirstAttemptTimestamp(const Time& time) {
1341 p2p_first_attempt_timestamp_ = time;
1342 LOG(INFO) << "p2p First Attempt Timestamp = "
1343 << utils::ToString(p2p_first_attempt_timestamp_);
1344 CHECK(prefs_);
1345 int64_t stored_value = time.ToInternalValue();
1346 prefs_->SetInt64(kPrefsP2PFirstAttemptTimestamp, stored_value);
1347}
1348
1349void PayloadState::LoadP2PFirstAttemptTimestamp() {
Chris Sosab3dcdb32013-09-04 15:22:12 -07001350 int64_t stored_value = GetPersistedValue(kPrefsP2PFirstAttemptTimestamp);
David Zeuthendcba8092013-08-06 12:16:35 -07001351 Time stored_time = Time::FromInternalValue(stored_value);
1352 SetP2PFirstAttemptTimestamp(stored_time);
1353}
1354
1355void PayloadState::P2PNewAttempt() {
1356 CHECK(prefs_);
1357 // Set timestamp, if it hasn't been set already
1358 if (p2p_first_attempt_timestamp_.is_null()) {
1359 SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
1360 }
1361 // Increase number of attempts
1362 SetP2PNumAttempts(GetP2PNumAttempts() + 1);
1363}
1364
1365bool PayloadState::P2PAttemptAllowed() {
1366 if (p2p_num_attempts_ > kMaxP2PAttempts) {
1367 LOG(INFO) << "Number of p2p attempts is " << p2p_num_attempts_
1368 << " which is greater than "
1369 << kMaxP2PAttempts
1370 << " - disallowing p2p.";
1371 return false;
1372 }
1373
1374 if (!p2p_first_attempt_timestamp_.is_null()) {
1375 Time now = system_state_->clock()->GetWallclockTime();
1376 TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
1377 if (time_spent_attempting_p2p.InSeconds() < 0) {
1378 LOG(ERROR) << "Time spent attempting p2p is negative"
1379 << " - disallowing p2p.";
1380 return false;
1381 }
1382 if (time_spent_attempting_p2p.InSeconds() > kMaxP2PAttemptTimeSeconds) {
1383 LOG(INFO) << "Time spent attempting p2p is "
1384 << utils::FormatTimeDelta(time_spent_attempting_p2p)
1385 << " which is greater than "
1386 << utils::FormatTimeDelta(TimeDelta::FromSeconds(
1387 kMaxP2PAttemptTimeSeconds))
1388 << " - disallowing p2p.";
1389 return false;
1390 }
1391 }
1392
1393 return true;
1394}
1395
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001396} // namespace chromeos_update_engine