blob: 8403dec1e537b88e1fdfa60453d3b3676c8aa5b8 [file] [log] [blame]
Alex Deymo5e3ea272016-01-28 13:42:23 -08001//
2// Copyright (C) 2016 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//
16
17#include "update_engine/update_attempter_android.h"
18
19#include <algorithm>
Alex Deymo218397f2016-02-04 23:55:10 -080020#include <map>
Alex Deymo5e3ea272016-01-28 13:42:23 -080021#include <utility>
22
23#include <base/bind.h>
24#include <base/logging.h>
Alex Deymo218397f2016-02-04 23:55:10 -080025#include <base/strings/string_number_conversions.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080026#include <brillo/bind_lambda.h>
27#include <brillo/message_loops/message_loop.h>
Alex Deymo218397f2016-02-04 23:55:10 -080028#include <brillo/strings/string_utils.h>
Alex Deymo5e3ea272016-01-28 13:42:23 -080029
30#include "update_engine/common/constants.h"
31#include "update_engine/common/libcurl_http_fetcher.h"
32#include "update_engine/common/multi_range_http_fetcher.h"
33#include "update_engine/common/utils.h"
34#include "update_engine/daemon_state_android.h"
35#include "update_engine/payload_consumer/download_action.h"
36#include "update_engine/payload_consumer/filesystem_verifier_action.h"
37#include "update_engine/payload_consumer/postinstall_runner_action.h"
Alex Deymo3b678db2016-02-09 11:50:06 -080038#include "update_engine/update_status_utils.h"
Alex Deymo5e3ea272016-01-28 13:42:23 -080039
40using base::Bind;
41using base::TimeDelta;
42using base::TimeTicks;
43using std::shared_ptr;
44using std::string;
45using std::vector;
46
47namespace chromeos_update_engine {
48
49namespace {
50
51const char* const kErrorDomain = "update_engine";
52// TODO(deymo): Convert the different errors to a numeric value to report them
53// back on the service error.
54const char* const kGenericError = "generic_error";
55
56// Log and set the error on the passed ErrorPtr.
57bool LogAndSetError(brillo::ErrorPtr* error,
58 const tracked_objects::Location& location,
59 const string& reason) {
60 brillo::Error::AddTo(error, location, kErrorDomain, kGenericError, reason);
61 LOG(ERROR) << "Replying with failure: " << location.ToString() << ": "
62 << reason;
63 return false;
64}
65
66} // namespace
67
68UpdateAttempterAndroid::UpdateAttempterAndroid(
69 DaemonStateAndroid* daemon_state,
70 PrefsInterface* prefs,
71 BootControlInterface* boot_control,
72 HardwareInterface* hardware)
73 : daemon_state_(daemon_state),
74 prefs_(prefs),
75 boot_control_(boot_control),
76 hardware_(hardware),
77 processor_(new ActionProcessor()) {
78}
79
80UpdateAttempterAndroid::~UpdateAttempterAndroid() {
81 // Release ourselves as the ActionProcessor's delegate to prevent
82 // re-scheduling the updates due to the processing stopped.
83 processor_->set_delegate(nullptr);
84}
85
86void UpdateAttempterAndroid::Init() {
87 // In case of update_engine restart without a reboot we need to restore the
88 // reboot needed state.
89 if (UpdateCompletedOnThisBoot())
Alex Deymo0e061ae2016-02-09 17:49:03 -080090 SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
Alex Deymo5e3ea272016-01-28 13:42:23 -080091 else
Alex Deymo0e061ae2016-02-09 17:49:03 -080092 SetStatusAndNotify(UpdateStatus::IDLE);
Alex Deymo5e3ea272016-01-28 13:42:23 -080093}
94
95bool UpdateAttempterAndroid::ApplyPayload(
96 const string& payload_url,
97 int64_t payload_offset,
98 int64_t payload_size,
99 const vector<string>& key_value_pair_headers,
100 brillo::ErrorPtr* error) {
101 if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
102 return LogAndSetError(
103 error, FROM_HERE, "An update already applied, waiting for reboot");
104 }
105 if (ongoing_update_) {
106 return LogAndSetError(
107 error, FROM_HERE, "Already processing an update, cancel it first.");
108 }
109 DCHECK(status_ == UpdateStatus::IDLE);
110
Alex Deymo218397f2016-02-04 23:55:10 -0800111 std::map<string, string> headers;
112 for (const string& key_value_pair : key_value_pair_headers) {
113 string key;
114 string value;
115 if (!brillo::string_utils::SplitAtFirst(
116 key_value_pair, "=", &key, &value, false)) {
117 return LogAndSetError(
118 error, FROM_HERE, "Passed invalid header: " + key_value_pair);
119 }
120 if (!headers.emplace(key, value).second)
121 return LogAndSetError(error, FROM_HERE, "Passed repeated key: " + key);
122 }
123
124 // Unique identifier for the payload. An empty string means that the payload
125 // can't be resumed.
126 string payload_id = (headers[kPayloadPropertyFileHash] +
127 headers[kPayloadPropertyMetadataHash]);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800128
129 // Setup the InstallPlan based on the request.
130 install_plan_ = InstallPlan();
131
132 install_plan_.download_url = payload_url;
133 install_plan_.version = "";
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800134 base_offset_ = payload_offset;
Alex Deymo218397f2016-02-04 23:55:10 -0800135 install_plan_.payload_size = payload_size;
136 if (!install_plan_.payload_size) {
137 if (!base::StringToUint64(headers[kPayloadPropertyFileSize],
138 &install_plan_.payload_size)) {
139 install_plan_.payload_size = 0;
140 }
141 }
142 install_plan_.payload_hash = headers[kPayloadPropertyFileHash];
143 if (!base::StringToUint64(headers[kPayloadPropertyMetadataSize],
144 &install_plan_.metadata_size)) {
145 install_plan_.metadata_size = 0;
146 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800147 install_plan_.metadata_signature = "";
148 // The |public_key_rsa| key would override the public key stored on disk.
149 install_plan_.public_key_rsa = "";
150
151 install_plan_.hash_checks_mandatory = hardware_->IsOfficialBuild();
152 install_plan_.is_resume = !payload_id.empty() &&
153 DeltaPerformer::CanResumeUpdate(prefs_, payload_id);
154 if (!install_plan_.is_resume) {
155 if (!DeltaPerformer::ResetUpdateProgress(prefs_, false)) {
156 LOG(WARNING) << "Unable to reset the update progress.";
157 }
158 if (!prefs_->SetString(kPrefsUpdateCheckResponseHash, payload_id)) {
159 LOG(WARNING) << "Unable to save the update check response hash.";
160 }
161 }
Alex Deymo64d98782016-02-05 18:03:48 -0800162 // The |payload_type| is not used anymore since minor_version 3.
163 install_plan_.payload_type = InstallPayloadType::kUnknown;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800164
165 install_plan_.source_slot = boot_control_->GetCurrentSlot();
166 install_plan_.target_slot = install_plan_.source_slot == 0 ? 1 : 0;
167 install_plan_.powerwash_required = false;
168
169 LOG(INFO) << "Using this install plan:";
170 install_plan_.Dump();
171
172 BuildUpdateActions();
173 SetupDownload();
Alex Deymo6f10c5f2016-03-03 22:35:43 -0800174 // Setup extra headers.
175 HttpFetcher* fetcher = download_action_->http_fetcher();
176 if (!headers[kPayloadPropertyAuthorization].empty())
177 fetcher->SetHeader("Authorization", headers[kPayloadPropertyAuthorization]);
178 if (!headers[kPayloadPropertyUserAgent].empty())
179 fetcher->SetHeader("User-Agent", headers[kPayloadPropertyUserAgent]);
180
Alex Deymo5e3ea272016-01-28 13:42:23 -0800181 cpu_limiter_.StartLimiter();
182 SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
183
184 // Just in case we didn't update boot flags yet, make sure they're updated
185 // before any update processing starts. This will start the update process.
186 UpdateBootFlags();
187 return true;
188}
189
190bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
191 // TODO(deymo): Implement suspend/resume.
192 return LogAndSetError(error, FROM_HERE, "Suspend/resume not implemented");
193}
194
195bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
196 // TODO(deymo): Implement suspend/resume.
197 return LogAndSetError(error, FROM_HERE, "Suspend/resume not implemented");
198}
199
200bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
201 if (status_ == UpdateStatus::IDLE ||
202 status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
203 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
204 }
205
206 // TODO(deymo): Implement cancel.
207 return LogAndSetError(error, FROM_HERE, "Cancel not implemented");
208}
209
Alex Deymo3b678db2016-02-09 11:50:06 -0800210bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
211 LOG(INFO) << "Attempting to reset state from "
212 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
213
214 switch (status_) {
215 case UpdateStatus::IDLE:
216 return true;
217
218 case UpdateStatus::UPDATED_NEED_REBOOT: {
219 // Remove the reboot marker so that if the machine is rebooted
220 // after resetting to idle state, it doesn't go back to
221 // UpdateStatus::UPDATED_NEED_REBOOT state.
222 bool ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId);
223
224 // Update the boot flags so the current slot has higher priority.
225 if (!boot_control_->SetActiveBootSlot(boot_control_->GetCurrentSlot()))
226 ret_value = false;
227
228 if (!ret_value) {
229 return LogAndSetError(
230 error,
231 FROM_HERE,
232 "Failed to reset the status to ");
233 }
234
235 SetStatusAndNotify(UpdateStatus::IDLE);
236 LOG(INFO) << "Reset status successful";
237 return true;
238 }
239
240 default:
241 return LogAndSetError(
242 error,
243 FROM_HERE,
244 "Reset not allowed in this state. Cancel the ongoing update first");
245 }
246}
247
Alex Deymo5e3ea272016-01-28 13:42:23 -0800248void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
249 ErrorCode code) {
250 LOG(INFO) << "Processing Done.";
251
252 if (code == ErrorCode::kSuccess) {
253 // Update succeeded.
254 WriteUpdateCompletedMarker();
255 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
256 DeltaPerformer::ResetUpdateProgress(prefs_, false);
257
258 LOG(INFO) << "Update successfully applied, waiting to reboot.";
259 }
260
261 TerminateUpdateAndNotify(code);
262}
263
264void UpdateAttempterAndroid::ProcessingStopped(
265 const ActionProcessor* processor) {
266 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
267}
268
269void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
270 AbstractAction* action,
271 ErrorCode code) {
272 // Reset download progress regardless of whether or not the download
273 // action succeeded.
274 const string type = action->Type();
275 if (type == DownloadAction::StaticType()) {
276 download_progress_ = 0.0;
277 }
278 if (code != ErrorCode::kSuccess) {
279 // If an action failed, the ActionProcessor will cancel the whole thing.
280 return;
281 }
282 if (type == DownloadAction::StaticType()) {
283 SetStatusAndNotify(UpdateStatus::FINALIZING);
284 }
285}
286
287void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
288 uint64_t bytes_received,
289 uint64_t total) {
290 double progress = 0.;
291 if (total)
292 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
293 // Self throttle based on progress. Also send notifications if
294 // progress is too slow.
295 const double kDeltaPercent = 0.01; // 1%
296 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total ||
297 progress - download_progress_ >= kDeltaPercent ||
298 TimeTicks::Now() - last_notify_time_ >= TimeDelta::FromSeconds(10)) {
299 download_progress_ = progress;
300 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
301 }
302}
303
304bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
305 // TODO(deymo): Notify the DownloadAction that it should cancel the update
306 // download.
307 return false;
308}
309
310void UpdateAttempterAndroid::DownloadComplete() {
311 // Nothing needs to be done when the download completes.
312}
313
314void UpdateAttempterAndroid::UpdateBootFlags() {
315 if (updated_boot_flags_) {
316 LOG(INFO) << "Already updated boot flags. Skipping.";
317 CompleteUpdateBootFlags(true);
318 return;
319 }
320 // This is purely best effort.
321 LOG(INFO) << "Marking booted slot as good.";
322 if (!boot_control_->MarkBootSuccessfulAsync(
323 Bind(&UpdateAttempterAndroid::CompleteUpdateBootFlags,
324 base::Unretained(this)))) {
325 LOG(ERROR) << "Failed to mark current boot as successful.";
326 CompleteUpdateBootFlags(false);
327 }
328}
329
330void UpdateAttempterAndroid::CompleteUpdateBootFlags(bool successful) {
331 updated_boot_flags_ = true;
332 ScheduleProcessingStart();
333}
334
335void UpdateAttempterAndroid::ScheduleProcessingStart() {
336 LOG(INFO) << "Scheduling an action processor start.";
337 brillo::MessageLoop::current()->PostTask(
338 FROM_HERE, Bind([this] { this->processor_->StartProcessing(); }));
339}
340
341void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
342 if (status_ == UpdateStatus::IDLE) {
343 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
344 return;
345 }
346
347 // Reset cpu shares back to normal.
348 cpu_limiter_.StopLimiter();
349 download_progress_ = 0.0;
350 actions_.clear();
351 UpdateStatus new_status =
352 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
353 : UpdateStatus::IDLE);
354 SetStatusAndNotify(new_status);
355 ongoing_update_ = false;
356
357 for (auto observer : daemon_state_->service_observers())
358 observer->SendPayloadApplicationComplete(error_code);
359}
360
361void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
362 status_ = status;
363 for (auto observer : daemon_state_->service_observers()) {
364 observer->SendStatusUpdate(
365 0, download_progress_, status_, "", install_plan_.payload_size);
366 }
367 last_notify_time_ = TimeTicks::Now();
368}
369
370void UpdateAttempterAndroid::BuildUpdateActions() {
371 CHECK(!processor_->IsRunning());
372 processor_->set_delegate(this);
373
374 // Actions:
375 shared_ptr<InstallPlanAction> install_plan_action(
376 new InstallPlanAction(install_plan_));
377
378 LibcurlHttpFetcher* download_fetcher =
379 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
380 download_fetcher->set_server_to_check(ServerToCheck::kDownload);
381 shared_ptr<DownloadAction> download_action(new DownloadAction(
382 prefs_,
383 boot_control_,
384 hardware_,
385 nullptr, // system_state, not used.
386 new MultiRangeHttpFetcher(download_fetcher))); // passes ownership
387 shared_ptr<FilesystemVerifierAction> dst_filesystem_verifier_action(
388 new FilesystemVerifierAction(boot_control_,
389 VerifierMode::kVerifyTargetHash));
390
391 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
392 new PostinstallRunnerAction(boot_control_));
393
394 download_action->set_delegate(this);
395 download_action_ = download_action;
396
397 actions_.push_back(shared_ptr<AbstractAction>(install_plan_action));
398 actions_.push_back(shared_ptr<AbstractAction>(download_action));
399 actions_.push_back(
400 shared_ptr<AbstractAction>(dst_filesystem_verifier_action));
401 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
402
403 // Bond them together. We have to use the leaf-types when calling
404 // BondActions().
405 BondActions(install_plan_action.get(), download_action.get());
406 BondActions(download_action.get(), dst_filesystem_verifier_action.get());
407 BondActions(dst_filesystem_verifier_action.get(),
408 postinstall_runner_action.get());
409
410 // Enqueue the actions.
411 for (const shared_ptr<AbstractAction>& action : actions_)
412 processor_->EnqueueAction(action.get());
413}
414
415void UpdateAttempterAndroid::SetupDownload() {
416 MultiRangeHttpFetcher* fetcher =
417 static_cast<MultiRangeHttpFetcher*>(download_action_->http_fetcher());
418 fetcher->ClearRanges();
419 if (install_plan_.is_resume) {
420 // Resuming an update so fetch the update manifest metadata first.
421 int64_t manifest_metadata_size = 0;
422 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800423 fetcher->AddRange(base_offset_, manifest_metadata_size);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800424 // If there're remaining unprocessed data blobs, fetch them. Be careful not
425 // to request data beyond the end of the payload to avoid 416 HTTP response
426 // error codes.
427 int64_t next_data_offset = 0;
428 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
429 uint64_t resume_offset = manifest_metadata_size + next_data_offset;
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800430 if (!install_plan_.payload_size) {
431 fetcher->AddRange(base_offset_ + resume_offset);
432 } else if (resume_offset < install_plan_.payload_size) {
433 fetcher->AddRange(base_offset_ + resume_offset,
434 install_plan_.payload_size - resume_offset);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800435 }
436 } else {
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800437 if (install_plan_.payload_size) {
438 fetcher->AddRange(base_offset_, install_plan_.payload_size);
439 } else {
440 // If no payload size is passed we assume we read until the end of the
441 // stream.
442 fetcher->AddRange(base_offset_);
443 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800444 }
445}
446
447bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
448 string boot_id;
449 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
450 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
451 return true;
452}
453
454bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
455 // In case of an update_engine restart without a reboot, we stored the boot_id
456 // when the update was completed by setting a pref, so we can check whether
457 // the last update was on this boot or a previous one.
458 string boot_id;
459 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
460
461 string update_completed_on_boot_id;
462 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
463 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
464 &update_completed_on_boot_id) &&
465 update_completed_on_boot_id == boot_id);
466}
467
468} // namespace chromeos_update_engine