| // |
| // Copyright (C) 2012 The Android Open Source Project |
| // |
| // Licensed under the Apache License, Version 2.0 (the "License"); |
| // you may not use this file except in compliance with the License. |
| // You may obtain a copy of the License at |
| // |
| // http://www.apache.org/licenses/LICENSE-2.0 |
| // |
| // Unless required by applicable law or agreed to in writing, software |
| // distributed under the License is distributed on an "AS IS" BASIS, |
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| // See the License for the specific language governing permissions and |
| // limitations under the License. |
| // |
| |
| #include "update_engine/update_attempter_nestlabs.h" |
| |
| #include <stdint.h> |
| |
| #include <algorithm> |
| #include <memory> |
| #include <set> |
| #include <string> |
| #include <utility> |
| #include <vector> |
| |
| #include <base/bind.h> |
| #include <base/files/file_util.h> |
| #include <base/logging.h> |
| #include <base/rand_util.h> |
| #include <base/strings/string_util.h> |
| #include <base/strings/stringprintf.h> |
| #include <brillo/bind_lambda.h> |
| #include <brillo/errors/error_codes.h> |
| #include <brillo/make_unique_ptr.h> |
| #include <brillo/message_loops/message_loop.h> |
| #include <policy/device_policy.h> |
| #include <policy/libpolicy.h> |
| #include <update_engine/dbus-constants-nestlabs.h> |
| |
| #include "update_engine/certificate_checker.h" |
| #include "update_engine/common/boot_control_interface.h" |
| #include "update_engine/common/clock_interface.h" |
| #include "update_engine/common/constants.h" |
| #include "update_engine/common/hardware_interface.h" |
| #include "update_engine/common/multi_range_http_fetcher.h" |
| #include "update_engine/common/platform_constants.h" |
| #include "update_engine/common/prefs_interface.h" |
| #include "update_engine/common/subprocess.h" |
| #include "update_engine/common/utils.h" |
| #include "update_engine/libcurl_http_fetcher.h" |
| #include "update_engine/metrics.h" |
| #include "update_engine/payload_properties_request_action.h" |
| #include "update_engine/payload_properties_handler_action.h" |
| #include "update_engine/p2p_manager.h" |
| #include "update_engine/payload_consumer/download_action.h" |
| #include "update_engine/payload_consumer/filesystem_verifier_action.h" |
| #include "update_engine/payload_consumer/postinstall_runner_action.h" |
| #include "update_engine/payload_state_interface.h" |
| #include "update_engine/power_manager_interface.h" |
| #include "update_engine/system_state.h" |
| #include "update_engine/update_manager/policy.h" |
| #include "update_engine/update_manager/update_manager.h" |
| #include "update_engine/update_status_utils.h" |
| |
| #define PAYLOAD_PROPERTIES_OFFSET 0 |
| #define PAYLOAD_PROPERTIES_SIZE 512 |
| |
| |
| using base::Bind; |
| using base::Callback; |
| using base::Time; |
| using base::TimeDelta; |
| using base::TimeTicks; |
| using brillo::MessageLoop; |
| using chromeos_update_manager::EvalStatus; |
| using chromeos_update_manager::Policy; |
| using chromeos_update_manager::UpdateCheckParams; |
| using std::set; |
| using std::shared_ptr; |
| using std::string; |
| using std::vector; |
| |
| namespace chromeos_update_engine { |
| |
| const int UpdateAttempter::kMaxDeltaUpdateFailures = 3; |
| |
| namespace { |
| // Minimum threshold to broadcast an status update in progress and time. |
| const double kBroadcastThresholdProgress = 0.01; // 1% |
| const int kBroadcastThresholdSeconds = 10; |
| } // namespace |
| |
| UpdateAttempter::UpdateAttempter(SystemState* system_state, |
| CertificateChecker* cert_checker, |
| LibCrosProxy* libcros_proxy) |
| : processor_(new ActionProcessor()), |
| system_state_(system_state), |
| cert_checker_(cert_checker) { |
| } |
| |
| UpdateAttempter::~UpdateAttempter() { |
| // CertificateChecker might not be initialized in unittests. |
| if (cert_checker_) |
| cert_checker_->SetObserver(nullptr); |
| // Release ourselves as the ActionProcessor's delegate to prevent |
| // re-scheduling the updates due to the processing stopped. |
| processor_->set_delegate(nullptr); |
| } |
| |
| void UpdateAttempter::Init() { |
| // Pulling from the SystemState can only be done after construction, since |
| // this is an aggregate of various objects (such as the UpdateAttempter), |
| // which requires them all to be constructed prior to it being used. |
| prefs_ = system_state_->prefs(); |
| //omaha_request_params_ = system_state_->request_params(); |
| |
| if (cert_checker_) |
| cert_checker_->SetObserver(this); |
| |
| // In case of update_engine restart without a reboot we need to restore the |
| // reboot needed state. |
| if (GetBootTimeAtUpdate(nullptr)) |
| status_ = UpdateStatus::UPDATED_NEED_REBOOT; |
| else |
| status_ = UpdateStatus::IDLE; |
| } |
| |
| void UpdateAttempter::ScheduleUpdates() { |
| if (IsUpdateRunningOrScheduled()) |
| return; |
| |
| chromeos_update_manager::UpdateManager* const update_manager = |
| system_state_->update_manager(); |
| CHECK(update_manager); |
| Callback<void(EvalStatus, const UpdateCheckParams&)> callback = Bind( |
| &UpdateAttempter::OnUpdateScheduled, base::Unretained(this)); |
| // We limit the async policy request to a reasonably short time, to avoid a |
| // starvation due to a transient bug. |
| update_manager->AsyncPolicyRequest(callback, &Policy::UpdateCheckAllowed); |
| waiting_for_scheduled_check_ = true; |
| } |
| |
| void UpdateAttempter::CertificateChecked(ServerToCheck server_to_check, |
| CertificateCheckResult result) { |
| metrics::ReportCertificateCheckMetrics(system_state_, |
| server_to_check, |
| result); |
| } |
| |
| void UpdateAttempter::Update(const string& app_version, |
| const string& url, |
| const string& target_channel, |
| const string& target_version_prefix, |
| bool obey_proxies, |
| bool interactive) { |
| |
| // Notify of the new update attempt, clearing prior interactive requests. |
| if (forced_update_pending_callback_.get()) |
| forced_update_pending_callback_->Run(false, false); |
| |
| if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) { |
| // Although we have applied an update, we still want to ping Omaha |
| // to ensure the number of active statistics is accurate. |
| // |
| // Also convey to the UpdateEngine.Check.Result metric that we're |
| // not performing an update check because of this. |
| LOG(INFO) << "Not updating b/c we already updated and we're waiting for reboot"; |
| metrics::ReportUpdateCheckMetrics(system_state_, |
| metrics::CheckResult::kRebootPending, |
| metrics::CheckReaction::kUnset, |
| metrics::DownloadErrorCode::kUnset); |
| return; |
| } |
| if (status_ != UpdateStatus::IDLE) { |
| // Update in progress. Do nothing |
| return; |
| } |
| |
| // Update the last check time here; it may be re-updated when an Omaha |
| // response is received, but this will prevent us from repeatedly scheduling |
| // checks in the case where a response is not received. |
| UpdateLastCheckedTime(); |
| |
| if (!CalculateUpdateParams(app_version ,url)) { |
| return; |
| } |
| |
| BuildUpdateActions(interactive); |
| |
| SetStatusAndNotify(UpdateStatus::CHECKING_FOR_UPDATE); |
| |
| // Just in case we didn't update boot flags yet, make sure they're updated |
| // before any update processing starts. |
| start_action_processor_ = true; |
| UpdateBootFlags(); |
| } |
| |
| bool UpdateAttempter::CalculateUpdateParams(const string& version, |
| const string& url) { |
| |
| PayloadStateInterface* const payload_state = system_state_->payload_state(); |
| |
| // Refresh the policy before computing all the update parameters. |
| RefreshDevicePolicy(); |
| |
| payload_properties_.payload_urls.clear(); |
| |
| // Skip update if `url' is empty (update_engine was not asked for update via DBUS), |
| // and URL from payload_state is empty (there is no restored URL |
| // from previos update) |
| if (url != "") |
| { |
| payload_properties_.payload_urls.push_back(url); |
| } |
| else if (payload_state->GetCurrentUrl() != "") |
| { |
| payload_properties_.payload_urls.push_back(payload_state->GetCurrentUrl()); |
| } |
| else |
| { |
| LOG(INFO) |
| << "URL is not present. Nothing to do now. retrying."; |
| ScheduleUpdates(); |
| return false; |
| } |
| |
| // turn P2P off |
| payload_state->SetUsingP2PForDownloading(false); |
| payload_state->SetUsingP2PForSharing(false); |
| |
| // reset code |
| http_response_code_ = 0; |
| |
| return true; |
| } |
| |
| void UpdateAttempter::RefreshDevicePolicy() { |
| // Lazy initialize the policy provider, or reload the latest policy data. |
| if (!policy_provider_.get()) |
| policy_provider_.reset(new policy::PolicyProvider()); |
| policy_provider_->Reload(); |
| |
| const policy::DevicePolicy* device_policy = nullptr; |
| if (policy_provider_->device_policy_is_loaded()) |
| device_policy = &policy_provider_->GetDevicePolicy(); |
| |
| if (device_policy) |
| LOG(INFO) << "Device policies/settings present"; |
| else |
| LOG(INFO) << "No device policies/settings present."; |
| |
| system_state_->set_device_policy(device_policy); |
| system_state_->p2p_manager()->SetDevicePolicy(device_policy); |
| } |
| |
| void UpdateAttempter::BuildPostInstallActions( |
| InstallPlanAction* previous_action) { |
| shared_ptr<PostinstallRunnerAction> postinstall_runner_action( |
| new PostinstallRunnerAction(system_state_->boot_control(), |
| system_state_->hardware())); |
| postinstall_runner_action->set_delegate(this); |
| actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action)); |
| BondActions(previous_action, |
| postinstall_runner_action.get()); |
| } |
| |
| #define MAX_RETRIES 3 |
| |
| void UpdateAttempter::BuildUpdateActions(bool interactive) { |
| CHECK(!processor_->IsRunning()); |
| processor_->set_delegate(this); |
| |
| // Actions: |
| LibcurlHttpFetcher * pp_base_fetcher = |
| new LibcurlHttpFetcher(GetProxyResolver(), system_state_->hardware()); |
| MultiRangeHttpFetcher * payload_properties_fetcher = |
| new MultiRangeHttpFetcher(pp_base_fetcher); |
| |
| pp_base_fetcher->set_server_to_check(ServerToCheck::kDownload); |
| pp_base_fetcher->set_no_network_max_retries(MAX_RETRIES); |
| payload_properties_fetcher->AddRange(PAYLOAD_PROPERTIES_OFFSET, PAYLOAD_PROPERTIES_SIZE); |
| shared_ptr<PayloadPropertiesRequestAction> payload_properties_request_action( |
| new PayloadPropertiesRequestAction(system_state_, |
| &payload_properties_, |
| (LibcurlHttpFetcher *)payload_properties_fetcher)); |
| payload_properties_request_action_ = payload_properties_request_action; |
| |
| shared_ptr<PayloadPropertiesHandlerAction> payload_properties_handler_action( |
| new PayloadPropertiesHandlerAction(system_state_)); |
| payload_properties_handler_action_ = payload_properties_handler_action; |
| |
| LibcurlHttpFetcher* download_fetcher = |
| new LibcurlHttpFetcher(GetProxyResolver(), system_state_->hardware()); |
| download_fetcher->set_server_to_check(ServerToCheck::kDownload); |
| shared_ptr<DownloadAction> download_action(new DownloadAction( |
| prefs_, |
| system_state_->boot_control(), |
| system_state_->hardware(), |
| system_state_, |
| new MultiRangeHttpFetcher(download_fetcher))); // passes ownership |
| download_action->set_delegate(this); |
| download_action_ = download_action; |
| |
| shared_ptr<FilesystemVerifierAction> filesystem_verifier_action( |
| new FilesystemVerifierAction()); |
| |
| actions_.push_back(shared_ptr<AbstractAction>(payload_properties_request_action)); |
| actions_.push_back(shared_ptr<AbstractAction>(payload_properties_handler_action)); |
| actions_.push_back(shared_ptr<AbstractAction>(download_action)); |
| actions_.push_back(shared_ptr<AbstractAction>(filesystem_verifier_action)); |
| |
| // Bond them together. We have to use the leaf-types when calling |
| // BondActions(). |
| BondActions(payload_properties_request_action.get(), |
| payload_properties_handler_action.get()); |
| BondActions(payload_properties_handler_action.get(), |
| download_action.get()); |
| BondActions(download_action.get(), |
| filesystem_verifier_action.get()); |
| BuildPostInstallActions(filesystem_verifier_action.get()); |
| |
| // Enqueue the actions |
| for (const shared_ptr<AbstractAction>& action : actions_) { |
| processor_->EnqueueAction(action.get()); |
| } |
| } |
| |
| bool UpdateAttempter::Rollback(bool powerwash) { |
| if (!CanRollback()) { |
| return false; |
| } |
| |
| processor_->set_delegate(this); |
| |
| LOG(INFO) << "Setting rollback options."; |
| InstallPlan install_plan; |
| |
| install_plan.target_slot = GetRollbackSlot(); |
| install_plan.source_slot = system_state_->boot_control()->GetCurrentSlot(); |
| |
| TEST_AND_RETURN_FALSE( |
| install_plan.LoadPartitionsFromSlots(system_state_->boot_control())); |
| install_plan.powerwash_required = powerwash; |
| |
| LOG(INFO) << "Using this install plan:"; |
| install_plan.Dump(); |
| |
| shared_ptr<InstallPlanAction> install_plan_action( |
| new InstallPlanAction(install_plan)); |
| actions_.push_back(shared_ptr<AbstractAction>(install_plan_action)); |
| |
| BuildPostInstallActions(install_plan_action.get()); |
| |
| // Enqueue the actions |
| for (const shared_ptr<AbstractAction>& action : actions_) { |
| processor_->EnqueueAction(action.get()); |
| } |
| |
| // Update the payload state for Rollback. |
| system_state_->payload_state()->Rollback(); |
| |
| SetStatusAndNotify(UpdateStatus::ATTEMPTING_ROLLBACK); |
| |
| // Just in case we didn't update boot flags yet, make sure they're updated |
| // before any update processing starts. This also schedules the start of the |
| // actions we just posted. |
| start_action_processor_ = true; |
| UpdateBootFlags(); |
| return true; |
| } |
| |
| bool UpdateAttempter::CanRollback() const { |
| // We can only rollback if the update_engine isn't busy and we have a valid |
| // rollback partition. |
| return (status_ == UpdateStatus::IDLE && |
| GetRollbackSlot() != BootControlInterface::kInvalidSlot); |
| } |
| |
| BootControlInterface::Slot UpdateAttempter::GetRollbackSlot() const { |
| LOG(INFO) << "UpdateAttempter::GetRollbackSlot"; |
| const unsigned int num_slots = system_state_->boot_control()->GetNumSlots(); |
| const BootControlInterface::Slot current_slot = |
| system_state_->boot_control()->GetCurrentSlot(); |
| |
| LOG(INFO) << " Installed slots: " << num_slots; |
| LOG(INFO) << " Booted from slot: " |
| << BootControlInterface::SlotName(current_slot); |
| |
| if (current_slot == BootControlInterface::kInvalidSlot || num_slots < 2) { |
| LOG(INFO) << "Device is not updateable."; |
| return BootControlInterface::kInvalidSlot; |
| } |
| |
| vector<BootControlInterface::Slot> bootable_slots; |
| for (BootControlInterface::Slot slot = 0; slot < num_slots; slot++) { |
| if (slot != current_slot && |
| system_state_->boot_control()->IsSlotBootable(slot)) { |
| LOG(INFO) << "Found bootable slot " |
| << BootControlInterface::SlotName(slot); |
| return slot; |
| } |
| } |
| LOG(INFO) << "No other bootable slot found."; |
| return BootControlInterface::kInvalidSlot; |
| } |
| |
| void UpdateAttempter::CheckForUpdate(const string& app_version, |
| const string& url, |
| bool interactive) { |
| LOG(INFO) << "Update requested."; |
| app_version_ = app_version; |
| url_ = url; |
| |
| if (forced_update_pending_callback_.get()) { |
| // Make sure that a scheduling request is made prior to calling the forced |
| // update pending callback. |
| ScheduleUpdates(); |
| forced_update_pending_callback_->Run(true, interactive); |
| } |
| } |
| |
| bool UpdateAttempter::RebootIfNeeded() { |
| if (status_ != UpdateStatus::UPDATED_NEED_REBOOT) { |
| LOG(INFO) << "Reboot requested, but status is " |
| << UpdateStatusToString(status_) << ", so not rebooting."; |
| return false; |
| } |
| |
| if (system_state_->power_manager()->RequestReboot()) |
| return true; |
| |
| return RebootDirectly(); |
| } |
| |
| void UpdateAttempter::WriteUpdateCompletedMarker() { |
| string boot_id; |
| if (!utils::GetBootId(&boot_id)) |
| return; |
| prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id); |
| |
| int64_t value = system_state_->clock()->GetBootTime().ToInternalValue(); |
| prefs_->SetInt64(kPrefsUpdateCompletedBootTime, value); |
| } |
| |
| bool UpdateAttempter::RebootDirectly() { |
| vector<string> command; |
| command.push_back("/system/bin/reboot"); |
| LOG(INFO) << "Running \"" << base::JoinString(command, " ") << "\""; |
| int rc = 0; |
| Subprocess::SynchronousExec(command, &rc, nullptr); |
| return rc == 0; |
| } |
| |
| void UpdateAttempter::OnUpdateScheduled(EvalStatus status, |
| const UpdateCheckParams& params) { |
| waiting_for_scheduled_check_ = false; |
| |
| if (status == EvalStatus::kSucceeded) { |
| if (!params.updates_enabled) { |
| LOG(WARNING) << "Updates permanently disabled."; |
| // Signal disabled status, then switch right back to idle. This is |
| // necessary for ensuring that observers waiting for a signal change will |
| // actually notice one on subsequent calls. Note that we don't need to |
| // re-schedule a check in this case as updates are permanently disabled; |
| // further (forced) checks may still initiate a scheduling call. |
| SetStatusAndNotify(UpdateStatus::DISABLED); |
| SetStatusAndNotify(UpdateStatus::IDLE); |
| return; |
| } |
| |
| LOG(INFO) << "Running update."; |
| |
| Update(app_version_, url_); |
| // Always clear the forced app_version and url after an update attempt |
| // so the next update uses the defaults. |
| app_version_.clear(); |
| url_.clear(); |
| } else { |
| LOG(WARNING) |
| << "Update check scheduling failed (possibly timed out); retrying."; |
| ScheduleUpdates(); |
| } |
| |
| // This check ensures that future update checks will be or are already |
| // scheduled. The check should never fail. A check failure means that there's |
| // a bug that will most likely prevent further automatic update checks. It |
| // seems better to crash in such cases and restart the update_engine daemon |
| // into, hopefully, a known good state. |
| CHECK(IsUpdateRunningOrScheduled()); |
| } |
| |
| void UpdateAttempter::UpdateLastCheckedTime() { |
| last_checked_time_ = system_state_->clock()->GetWallclockTime().ToTimeT(); |
| } |
| |
| // Delegate methods: |
| void UpdateAttempter::ProcessingDone(const ActionProcessor* processor, |
| ErrorCode code) { |
| LOG(INFO) << "Processing Done."; |
| actions_.clear(); |
| |
| // Reset cpu shares back to normal. |
| cpu_limiter_.StopLimiter(); |
| |
| if (code != ErrorCode::kSuccess) { |
| // update metrics |
| system_state_->payload_state()->UpdateFailed(code); |
| DeltaPerformer::ResetUpdateProgress(prefs_, false); |
| // send ERROR event and go into IDLE state otherwise update_engine |
| // will not able to handle other requests |
| // REPORTING_ERROR_EVENT is recoverable state which is used just for |
| // notifying about error. |
| SetStatusAndNotify(UpdateStatus::REPORTING_ERROR_EVENT); |
| // go back to IDLE |
| SetStatusAndNotify(UpdateStatus::IDLE); |
| ScheduleUpdates(); |
| return; |
| } |
| |
| WriteUpdateCompletedMarker(); |
| prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0); |
| prefs_->SetString(kPrefsPreviousVersion, |
| payload_properties_.version); |
| DeltaPerformer::ResetUpdateProgress(prefs_, false); |
| |
| system_state_->payload_state()->UpdateSucceeded(); |
| |
| // Since we're done with scattering fully at this point, this is the |
| // safest point delete the state files, as we're sure that the status is |
| // set to reboot (which means no more updates will be applied until reboot) |
| // This deletion is required for correctness as we want the next update |
| // check to re-create a new random number for the update check count. |
| // Similarly, we also delete the wall-clock-wait period that was persisted |
| // so that we start with a new random value for the next update check |
| // after reboot so that the same device is not favored or punished in any |
| // way. |
| prefs_->Delete(kPrefsUpdateCheckCount); |
| system_state_->payload_state()->SetScatteringWaitPeriod(TimeDelta()); |
| prefs_->Delete(kPrefsUpdateFirstSeenAt); |
| |
| SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT); |
| LOG(INFO) << "Update successfully applied, waiting to reboot."; |
| return; |
| } |
| |
| void UpdateAttempter::ProcessingStopped(const ActionProcessor* processor) { |
| // Reset cpu shares back to normal. |
| cpu_limiter_.StopLimiter(); |
| download_progress_ = 0.0; |
| SetStatusAndNotify(UpdateStatus::IDLE); |
| ScheduleUpdates(); |
| actions_.clear(); |
| } |
| |
| // Called whenever an action has finished processing, either successfully |
| // or otherwise. |
| void UpdateAttempter::ActionCompleted(ActionProcessor* processor, |
| AbstractAction* action, |
| ErrorCode code) { |
| const string type = action->Type(); |
| |
| // Reset download progress regardless of whether or not the download |
| // action succeeded. Also, get the response code from HTTP request |
| // actions (update download as well as the initial update check |
| // actions). |
| if (type == DownloadAction::StaticType()) { |
| download_progress_ = 0.0; |
| http_response_code_ = download_action_->GetHTTPResponseCode(); |
| } |
| else if (type == PayloadPropertiesRequestAction::StaticType()) |
| { |
| http_response_code_ = payload_properties_request_action_->GetHTTPResponseCode(); |
| } |
| if (code != ErrorCode::kSuccess) { |
| // If the current state is at or past the download phase, count the failure |
| // in case a switch to full update becomes necessary. Ignore network |
| // transfer timeouts and failures. |
| if (status_ >= UpdateStatus::DOWNLOADING && |
| code != ErrorCode::kDownloadTransferError) { |
| MarkDeltaUpdateFailure(); |
| } |
| return; |
| } |
| |
| if (type == PayloadPropertiesHandlerAction::StaticType()) { |
| // Note that the status will be updated to DOWNLOADING when some bytes get |
| // actually downloaded from the server and the BytesReceived callback is |
| // invoked. This avoids notifying the user that a download has started in |
| // cases when the server and the client are unable to initiate the download. |
| CHECK(action == payload_properties_handler_action_.get()); |
| const InstallPlan& plan = payload_properties_handler_action_->install_plan(); |
| UpdateLastCheckedTime(); |
| new_version_ = plan.version; |
| new_payload_size_ = plan.payload_size; |
| SetupDownload(); |
| cpu_limiter_.StartLimiter(); |
| SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE); |
| } else if (type == DownloadAction::StaticType()) { |
| SetStatusAndNotify(UpdateStatus::FINALIZING); |
| } |
| } |
| |
| void UpdateAttempter::BytesReceived(uint64_t bytes_progressed, |
| uint64_t bytes_received, |
| uint64_t total) { |
| // The PayloadState keeps track of how many bytes were actually downloaded |
| // from a given URL for the URL skipping logic. |
| system_state_->payload_state()->DownloadProgress(bytes_progressed); |
| |
| double progress = 0; |
| if (total) |
| progress = static_cast<double>(bytes_received) / static_cast<double>(total); |
| if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) { |
| download_progress_ = progress; |
| SetStatusAndNotify(UpdateStatus::DOWNLOADING); |
| } else { |
| ProgressUpdate(progress); |
| } |
| } |
| |
| void UpdateAttempter::DownloadComplete() { |
| system_state_->payload_state()->DownloadComplete(); |
| } |
| |
| void UpdateAttempter::ProgressUpdate(double progress) { |
| // Self throttle based on progress. Also send notifications if progress is |
| // too slow. |
| if (progress == 1.0 || |
| progress - download_progress_ >= kBroadcastThresholdProgress || |
| TimeTicks::Now() - last_notify_time_ >= |
| TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) { |
| download_progress_ = progress; |
| BroadcastStatus(); |
| } |
| } |
| |
| bool UpdateAttempter::ResetStatus() { |
| LOG(INFO) << "Attempting to reset state from " |
| << UpdateStatusToString(status_) << " to UpdateStatus::IDLE"; |
| |
| switch (status_) { |
| case UpdateStatus::IDLE: |
| // no-op. |
| return true; |
| |
| case UpdateStatus::UPDATED_NEED_REBOOT: { |
| bool ret_value = true; |
| status_ = UpdateStatus::IDLE; |
| |
| // Remove the reboot marker so that if the machine is rebooted |
| // after resetting to idle state, it doesn't go back to |
| // UpdateStatus::UPDATED_NEED_REBOOT state. |
| ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId) && ret_value; |
| ret_value = prefs_->Delete(kPrefsUpdateCompletedBootTime) && ret_value; |
| |
| // Update the boot flags so the current slot has higher priority. |
| BootControlInterface* boot_control = system_state_->boot_control(); |
| if (!boot_control->SetActiveBootSlot(boot_control->GetCurrentSlot())) |
| ret_value = false; |
| |
| // Notify the PayloadState that the successful payload was canceled. |
| system_state_->payload_state()->ResetUpdateStatus(); |
| |
| // The previous version is used to report back to omaha after reboot that |
| // we actually rebooted into the new version from this "prev-version". We |
| // need to clear out this value now to prevent it being sent on the next |
| // updatecheck request. |
| ret_value = prefs_->SetString(kPrefsPreviousVersion, "") && ret_value; |
| |
| LOG(INFO) << "Reset status " << (ret_value ? "successful" : "failed"); |
| return ret_value; |
| } |
| |
| default: |
| LOG(ERROR) << "Reset not allowed in this state."; |
| return false; |
| } |
| } |
| |
| bool UpdateAttempter::GetStatus(int64_t* last_checked_time, |
| double* progress, |
| string* current_operation, |
| string* new_version, |
| int64_t* new_payload_size) { |
| *last_checked_time = last_checked_time_; |
| *progress = download_progress_; |
| *current_operation = UpdateStatusToString(status_); |
| *new_version = new_version_; |
| *new_payload_size = new_payload_size_; |
| return true; |
| } |
| |
| void UpdateAttempter::UpdateBootFlags() { |
| if (update_boot_flags_running_) { |
| LOG(INFO) << "Update boot flags running, nothing to do."; |
| return; |
| } |
| if (updated_boot_flags_) { |
| LOG(INFO) << "Already updated boot flags. Skipping."; |
| if (start_action_processor_) { |
| ScheduleProcessingStart(); |
| } |
| return; |
| } |
| // This is purely best effort. Failures should be logged by Subprocess. Run |
| // the script asynchronously to avoid blocking the event loop regardless of |
| // the script runtime. |
| update_boot_flags_running_ = true; |
| LOG(INFO) << "Marking booted slot as good."; |
| if (!system_state_->boot_control()->MarkBootSuccessfulAsync(Bind( |
| &UpdateAttempter::CompleteUpdateBootFlags, base::Unretained(this)))) { |
| LOG(ERROR) << "Failed to mark current boot as successful."; |
| CompleteUpdateBootFlags(false); |
| } |
| } |
| |
| void UpdateAttempter::CompleteUpdateBootFlags(bool successful) { |
| update_boot_flags_running_ = false; |
| updated_boot_flags_ = true; |
| if (start_action_processor_) { |
| ScheduleProcessingStart(); |
| } |
| } |
| |
| void UpdateAttempter::BroadcastStatus() { |
| for (const auto& observer : service_observers_) { |
| observer->SendStatusUpdate(last_checked_time_, |
| download_progress_, |
| status_, |
| new_version_, |
| new_payload_size_); |
| } |
| last_notify_time_ = TimeTicks::Now(); |
| } |
| |
| void UpdateAttempter::SetStatusAndNotify(UpdateStatus status) { |
| status_ = status; |
| BroadcastStatus(); |
| } |
| |
| void UpdateAttempter::ScheduleProcessingStart() { |
| LOG(INFO) << "Scheduling an action processor start."; |
| start_action_processor_ = false; |
| MessageLoop::current()->PostTask( |
| FROM_HERE, |
| Bind([](ActionProcessor* processor) { processor->StartProcessing(); }, |
| base::Unretained(processor_.get()))); |
| } |
| |
| void UpdateAttempter::MarkDeltaUpdateFailure() { |
| // Don't try to resume a failed delta update. |
| DeltaPerformer::ResetUpdateProgress(prefs_, false); |
| int64_t delta_failures; |
| if (!prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) || |
| delta_failures < 0) { |
| delta_failures = 0; |
| } |
| prefs_->SetInt64(kPrefsDeltaUpdateFailures, ++delta_failures); |
| } |
| |
| void UpdateAttempter::SetupDownload() { |
| MultiRangeHttpFetcher* fetcher = |
| static_cast<MultiRangeHttpFetcher*>(download_action_->http_fetcher()); |
| fetcher->ClearRanges(); |
| //if (response_handler_action_->install_plan().is_resume) { |
| if (payload_properties_handler_action_->install_plan().is_resume) { |
| // Resuming an update so fetch the update manifest metadata first. |
| int64_t manifest_metadata_size = 0; |
| int64_t manifest_signature_size = 0; |
| prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size); |
| prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size); |
| fetcher->AddRange(PAYLOAD_PROPERTIES_SIZE, manifest_metadata_size + manifest_signature_size); |
| // If there're remaining unprocessed data blobs, fetch them. Be careful not |
| // to request data beyond the end of the payload to avoid 416 HTTP response |
| // error codes. |
| int64_t next_data_offset = 0; |
| prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset); |
| uint64_t resume_offset = |
| manifest_metadata_size + manifest_signature_size + next_data_offset; |
| if (resume_offset < payload_properties_handler_action_->install_plan().payload_size) { |
| fetcher->AddRange(resume_offset); |
| } |
| } else { |
| fetcher->AddRange(PAYLOAD_PROPERTIES_SIZE); |
| } |
| } |
| |
| |
| void UpdateAttempter::UpdateEngineStarted() { |
| // If we just booted into a new update, keep the previous OS version |
| // in case we rebooted because of a crash of the old version, so we |
| // can do a proper crash report with correct information. |
| // This must be done before calling |
| // system_state_->payload_state()->UpdateEngineStarted() since it will |
| // delete SystemUpdated marker file. |
| if (system_state_->system_rebooted() && |
| prefs_->Exists(kPrefsSystemUpdatedMarker)) { |
| if (!prefs_->GetString(kPrefsPreviousVersion, &prev_version_)) { |
| // If we fail to get the version string, make sure it stays empty. |
| prev_version_.clear(); |
| } |
| } |
| |
| system_state_->payload_state()->UpdateEngineStarted(); |
| } |
| |
| bool UpdateAttempter::GetBootTimeAtUpdate(Time *out_boot_time) { |
| // In case of an update_engine restart without a reboot, we stored the boot_id |
| // when the update was completed by setting a pref, so we can check whether |
| // the last update was on this boot or a previous one. |
| string boot_id; |
| TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id)); |
| |
| string update_completed_on_boot_id; |
| if (!prefs_->Exists(kPrefsUpdateCompletedOnBootId) || |
| !prefs_->GetString(kPrefsUpdateCompletedOnBootId, |
| &update_completed_on_boot_id) || |
| update_completed_on_boot_id != boot_id) |
| return false; |
| |
| // Short-circuit avoiding the read in case out_boot_time is nullptr. |
| if (out_boot_time) { |
| int64_t boot_time = 0; |
| // Since the kPrefsUpdateCompletedOnBootId was correctly set, this pref |
| // should not fail. |
| TEST_AND_RETURN_FALSE( |
| prefs_->GetInt64(kPrefsUpdateCompletedBootTime, &boot_time)); |
| *out_boot_time = Time::FromInternalValue(boot_time); |
| } |
| return true; |
| } |
| |
| bool UpdateAttempter::IsUpdateRunningOrScheduled() { |
| return ((status_ != UpdateStatus::IDLE && |
| status_ != UpdateStatus::UPDATED_NEED_REBOOT) || |
| waiting_for_scheduled_check_); |
| } |
| |
| } // namespace chromeos_update_engine |