blob: bc9a698a1171b5954ac385d9d425d68111b320eb [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 Deymofdd6dec2016-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);
Alex Deymof2858572016-02-25 11:20:13 -0800183 ongoing_update_ = true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800184
185 // Just in case we didn't update boot flags yet, make sure they're updated
186 // before any update processing starts. This will start the update process.
187 UpdateBootFlags();
188 return true;
189}
190
191bool UpdateAttempterAndroid::SuspendUpdate(brillo::ErrorPtr* error) {
Alex Deymof2858572016-02-25 11:20:13 -0800192 if (!ongoing_update_)
193 return LogAndSetError(error, FROM_HERE, "No ongoing update to suspend.");
194 processor_->SuspendProcessing();
195 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800196}
197
198bool UpdateAttempterAndroid::ResumeUpdate(brillo::ErrorPtr* error) {
Alex Deymof2858572016-02-25 11:20:13 -0800199 if (!ongoing_update_)
200 return LogAndSetError(error, FROM_HERE, "No ongoing update to resume.");
201 processor_->ResumeProcessing();
202 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800203}
204
205bool UpdateAttempterAndroid::CancelUpdate(brillo::ErrorPtr* error) {
Alex Deymof2858572016-02-25 11:20:13 -0800206 if (!ongoing_update_)
Alex Deymo5e3ea272016-01-28 13:42:23 -0800207 return LogAndSetError(error, FROM_HERE, "No ongoing update to cancel.");
Alex Deymof2858572016-02-25 11:20:13 -0800208 processor_->StopProcessing();
209 return true;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800210}
211
Alex Deymo3b678db2016-02-09 11:50:06 -0800212bool UpdateAttempterAndroid::ResetStatus(brillo::ErrorPtr* error) {
213 LOG(INFO) << "Attempting to reset state from "
214 << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
215
216 switch (status_) {
217 case UpdateStatus::IDLE:
218 return true;
219
220 case UpdateStatus::UPDATED_NEED_REBOOT: {
221 // Remove the reboot marker so that if the machine is rebooted
222 // after resetting to idle state, it doesn't go back to
223 // UpdateStatus::UPDATED_NEED_REBOOT state.
224 bool ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId);
225
226 // Update the boot flags so the current slot has higher priority.
227 if (!boot_control_->SetActiveBootSlot(boot_control_->GetCurrentSlot()))
228 ret_value = false;
229
230 if (!ret_value) {
231 return LogAndSetError(
232 error,
233 FROM_HERE,
234 "Failed to reset the status to ");
235 }
236
237 SetStatusAndNotify(UpdateStatus::IDLE);
238 LOG(INFO) << "Reset status successful";
239 return true;
240 }
241
242 default:
243 return LogAndSetError(
244 error,
245 FROM_HERE,
246 "Reset not allowed in this state. Cancel the ongoing update first");
247 }
248}
249
Alex Deymo5e3ea272016-01-28 13:42:23 -0800250void UpdateAttempterAndroid::ProcessingDone(const ActionProcessor* processor,
251 ErrorCode code) {
252 LOG(INFO) << "Processing Done.";
253
254 if (code == ErrorCode::kSuccess) {
255 // Update succeeded.
256 WriteUpdateCompletedMarker();
257 prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
258 DeltaPerformer::ResetUpdateProgress(prefs_, false);
259
260 LOG(INFO) << "Update successfully applied, waiting to reboot.";
261 }
262
263 TerminateUpdateAndNotify(code);
264}
265
266void UpdateAttempterAndroid::ProcessingStopped(
267 const ActionProcessor* processor) {
268 TerminateUpdateAndNotify(ErrorCode::kUserCanceled);
269}
270
271void UpdateAttempterAndroid::ActionCompleted(ActionProcessor* processor,
272 AbstractAction* action,
273 ErrorCode code) {
274 // Reset download progress regardless of whether or not the download
275 // action succeeded.
276 const string type = action->Type();
277 if (type == DownloadAction::StaticType()) {
278 download_progress_ = 0.0;
279 }
280 if (code != ErrorCode::kSuccess) {
281 // If an action failed, the ActionProcessor will cancel the whole thing.
282 return;
283 }
284 if (type == DownloadAction::StaticType()) {
285 SetStatusAndNotify(UpdateStatus::FINALIZING);
286 }
287}
288
289void UpdateAttempterAndroid::BytesReceived(uint64_t bytes_progressed,
290 uint64_t bytes_received,
291 uint64_t total) {
292 double progress = 0.;
293 if (total)
294 progress = static_cast<double>(bytes_received) / static_cast<double>(total);
295 // Self throttle based on progress. Also send notifications if
296 // progress is too slow.
297 const double kDeltaPercent = 0.01; // 1%
298 if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total ||
299 progress - download_progress_ >= kDeltaPercent ||
300 TimeTicks::Now() - last_notify_time_ >= TimeDelta::FromSeconds(10)) {
301 download_progress_ = progress;
302 SetStatusAndNotify(UpdateStatus::DOWNLOADING);
303 }
304}
305
306bool UpdateAttempterAndroid::ShouldCancel(ErrorCode* cancel_reason) {
307 // TODO(deymo): Notify the DownloadAction that it should cancel the update
308 // download.
309 return false;
310}
311
312void UpdateAttempterAndroid::DownloadComplete() {
313 // Nothing needs to be done when the download completes.
314}
315
316void UpdateAttempterAndroid::UpdateBootFlags() {
317 if (updated_boot_flags_) {
318 LOG(INFO) << "Already updated boot flags. Skipping.";
319 CompleteUpdateBootFlags(true);
320 return;
321 }
322 // This is purely best effort.
323 LOG(INFO) << "Marking booted slot as good.";
324 if (!boot_control_->MarkBootSuccessfulAsync(
325 Bind(&UpdateAttempterAndroid::CompleteUpdateBootFlags,
326 base::Unretained(this)))) {
327 LOG(ERROR) << "Failed to mark current boot as successful.";
328 CompleteUpdateBootFlags(false);
329 }
330}
331
332void UpdateAttempterAndroid::CompleteUpdateBootFlags(bool successful) {
333 updated_boot_flags_ = true;
334 ScheduleProcessingStart();
335}
336
337void UpdateAttempterAndroid::ScheduleProcessingStart() {
338 LOG(INFO) << "Scheduling an action processor start.";
339 brillo::MessageLoop::current()->PostTask(
340 FROM_HERE, Bind([this] { this->processor_->StartProcessing(); }));
341}
342
343void UpdateAttempterAndroid::TerminateUpdateAndNotify(ErrorCode error_code) {
344 if (status_ == UpdateStatus::IDLE) {
345 LOG(ERROR) << "No ongoing update, but TerminatedUpdate() called.";
346 return;
347 }
348
349 // Reset cpu shares back to normal.
350 cpu_limiter_.StopLimiter();
351 download_progress_ = 0.0;
352 actions_.clear();
353 UpdateStatus new_status =
354 (error_code == ErrorCode::kSuccess ? UpdateStatus::UPDATED_NEED_REBOOT
355 : UpdateStatus::IDLE);
356 SetStatusAndNotify(new_status);
357 ongoing_update_ = false;
358
359 for (auto observer : daemon_state_->service_observers())
360 observer->SendPayloadApplicationComplete(error_code);
361}
362
363void UpdateAttempterAndroid::SetStatusAndNotify(UpdateStatus status) {
364 status_ = status;
365 for (auto observer : daemon_state_->service_observers()) {
366 observer->SendStatusUpdate(
367 0, download_progress_, status_, "", install_plan_.payload_size);
368 }
369 last_notify_time_ = TimeTicks::Now();
370}
371
372void UpdateAttempterAndroid::BuildUpdateActions() {
373 CHECK(!processor_->IsRunning());
374 processor_->set_delegate(this);
375
376 // Actions:
377 shared_ptr<InstallPlanAction> install_plan_action(
378 new InstallPlanAction(install_plan_));
379
380 LibcurlHttpFetcher* download_fetcher =
381 new LibcurlHttpFetcher(&proxy_resolver_, hardware_);
382 download_fetcher->set_server_to_check(ServerToCheck::kDownload);
383 shared_ptr<DownloadAction> download_action(new DownloadAction(
384 prefs_,
385 boot_control_,
386 hardware_,
387 nullptr, // system_state, not used.
388 new MultiRangeHttpFetcher(download_fetcher))); // passes ownership
389 shared_ptr<FilesystemVerifierAction> dst_filesystem_verifier_action(
390 new FilesystemVerifierAction(boot_control_,
391 VerifierMode::kVerifyTargetHash));
392
393 shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
394 new PostinstallRunnerAction(boot_control_));
395
396 download_action->set_delegate(this);
397 download_action_ = download_action;
398
399 actions_.push_back(shared_ptr<AbstractAction>(install_plan_action));
400 actions_.push_back(shared_ptr<AbstractAction>(download_action));
401 actions_.push_back(
402 shared_ptr<AbstractAction>(dst_filesystem_verifier_action));
403 actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
404
405 // Bond them together. We have to use the leaf-types when calling
406 // BondActions().
407 BondActions(install_plan_action.get(), download_action.get());
408 BondActions(download_action.get(), dst_filesystem_verifier_action.get());
409 BondActions(dst_filesystem_verifier_action.get(),
410 postinstall_runner_action.get());
411
412 // Enqueue the actions.
413 for (const shared_ptr<AbstractAction>& action : actions_)
414 processor_->EnqueueAction(action.get());
415}
416
417void UpdateAttempterAndroid::SetupDownload() {
418 MultiRangeHttpFetcher* fetcher =
419 static_cast<MultiRangeHttpFetcher*>(download_action_->http_fetcher());
420 fetcher->ClearRanges();
421 if (install_plan_.is_resume) {
422 // Resuming an update so fetch the update manifest metadata first.
423 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -0800424 int64_t manifest_signature_size = 0;
Alex Deymo5e3ea272016-01-28 13:42:23 -0800425 prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
Alex Deymof25eb492016-02-26 00:20:08 -0800426 prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size);
427 fetcher->AddRange(base_offset_,
428 manifest_metadata_size + manifest_signature_size);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800429 // If there're remaining unprocessed data blobs, fetch them. Be careful not
430 // to request data beyond the end of the payload to avoid 416 HTTP response
431 // error codes.
432 int64_t next_data_offset = 0;
433 prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
Alex Deymof25eb492016-02-26 00:20:08 -0800434 uint64_t resume_offset =
435 manifest_metadata_size + manifest_signature_size + next_data_offset;
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800436 if (!install_plan_.payload_size) {
437 fetcher->AddRange(base_offset_ + resume_offset);
438 } else if (resume_offset < install_plan_.payload_size) {
439 fetcher->AddRange(base_offset_ + resume_offset,
440 install_plan_.payload_size - resume_offset);
Alex Deymo5e3ea272016-01-28 13:42:23 -0800441 }
442 } else {
Alex Deymo0fd51ff2016-02-03 14:22:43 -0800443 if (install_plan_.payload_size) {
444 fetcher->AddRange(base_offset_, install_plan_.payload_size);
445 } else {
446 // If no payload size is passed we assume we read until the end of the
447 // stream.
448 fetcher->AddRange(base_offset_);
449 }
Alex Deymo5e3ea272016-01-28 13:42:23 -0800450 }
451}
452
453bool UpdateAttempterAndroid::WriteUpdateCompletedMarker() {
454 string boot_id;
455 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
456 prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
457 return true;
458}
459
460bool UpdateAttempterAndroid::UpdateCompletedOnThisBoot() {
461 // In case of an update_engine restart without a reboot, we stored the boot_id
462 // when the update was completed by setting a pref, so we can check whether
463 // the last update was on this boot or a previous one.
464 string boot_id;
465 TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
466
467 string update_completed_on_boot_id;
468 return (prefs_->Exists(kPrefsUpdateCompletedOnBootId) &&
469 prefs_->GetString(kPrefsUpdateCompletedOnBootId,
470 &update_completed_on_boot_id) &&
471 update_completed_on_boot_id == boot_id);
472}
473
474} // namespace chromeos_update_engine