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