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