1 // 2 // Copyright (C) 2012 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 #ifndef UPDATE_ENGINE_UPDATE_ATTEMPTER_H_ 18 #define UPDATE_ENGINE_UPDATE_ATTEMPTER_H_ 19 20 #include <time.h> 21 22 #include <memory> 23 #include <set> 24 #include <string> 25 #include <utility> 26 #include <vector> 27 28 #include <base/bind.h> 29 #include <base/time/time.h> 30 #include <gtest/gtest_prod.h> // for FRIEND_TEST 31 32 #include "debugd/dbus-proxies.h" 33 #include "update_engine/chrome_browser_proxy_resolver.h" 34 #include "update_engine/certificate_checker.h" 35 #include "update_engine/client_library/include/update_engine/update_status.h" 36 #include "update_engine/common/action_processor.h" 37 #include "update_engine/common/cpu_limiter.h" 38 #include "update_engine/libcros_proxy.h" 39 #include "update_engine/omaha_request_params.h" 40 #include "update_engine/omaha_response_handler_action.h" 41 #include "update_engine/payload_consumer/download_action.h" 42 #include "update_engine/payload_consumer/postinstall_runner_action.h" 43 #include "update_engine/proxy_resolver.h" 44 #include "update_engine/service_observer_interface.h" 45 #include "update_engine/system_state.h" 46 #include "update_engine/update_manager/policy.h" 47 #include "update_engine/update_manager/update_manager.h" 48 #include "update_engine/weave_service_interface.h" 49 50 class MetricsLibraryInterface; 51 52 namespace policy { 53 class PolicyProvider; 54 } 55 56 namespace chromeos_update_engine { 57 58 class UpdateEngineAdaptor; 59 60 class UpdateAttempter : public ActionProcessorDelegate, 61 public DownloadActionDelegate, 62 public CertificateChecker::Observer, 63 public WeaveServiceInterface::DelegateInterface, 64 public PostinstallRunnerAction::DelegateInterface { 65 public: 66 using UpdateStatus = update_engine::UpdateStatus; 67 static const int kMaxDeltaUpdateFailures; 68 69 UpdateAttempter(SystemState* system_state, 70 CertificateChecker* cert_checker, 71 LibCrosProxy* libcros_proxy, 72 org::chromium::debugdProxyInterface* debugd_proxy); 73 ~UpdateAttempter() override; 74 75 // Further initialization to be done post construction. 76 void Init(); 77 78 // Initiates scheduling of update checks. 79 virtual void ScheduleUpdates(); 80 81 // Checks for update and, if a newer version is available, attempts to update 82 // the system. Non-empty |in_app_version| or |in_update_url| prevents 83 // automatic detection of the parameter. |target_channel| denotes a 84 // policy-mandated channel we are updating to, if not empty. If |obey_proxies| 85 // is true, the update will likely respect Chrome's proxy setting. For 86 // security reasons, we may still not honor them. |interactive| should be true 87 // if this was called from the user (ie dbus). 88 virtual void Update(const std::string& app_version, 89 const std::string& omaha_url, 90 const std::string& target_channel, 91 const std::string& target_version_prefix, 92 bool obey_proxies, 93 bool interactive); 94 95 // ActionProcessorDelegate methods: 96 void ProcessingDone(const ActionProcessor* processor, 97 ErrorCode code) override; 98 void ProcessingStopped(const ActionProcessor* processor) override; 99 void ActionCompleted(ActionProcessor* processor, 100 AbstractAction* action, 101 ErrorCode code) override; 102 103 // WeaveServiceInterface::DelegateInterface overrides. 104 bool OnCheckForUpdates(brillo::ErrorPtr* error) override; 105 bool OnTrackChannel(const std::string& channel, 106 brillo::ErrorPtr* error) override; 107 bool GetWeaveState(int64_t* last_checked_time, 108 double* progress, 109 UpdateStatus* update_status, 110 std::string* current_channel, 111 std::string* tracking_channel) override; 112 113 // PostinstallRunnerAction::DelegateInterface 114 void ProgressUpdate(double progress) override; 115 116 // Resets the current state to UPDATE_STATUS_IDLE. 117 // Used by update_engine_client for restarting a new update without 118 // having to reboot once the previous update has reached 119 // UPDATE_STATUS_UPDATED_NEED_REBOOT state. This is used only 120 // for testing purposes. 121 virtual bool ResetStatus(); 122 123 // Returns the current status in the out params. Returns true on success. 124 virtual bool GetStatus(int64_t* last_checked_time, 125 double* progress, 126 std::string* current_operation, 127 std::string* new_version, 128 int64_t* new_size); 129 130 // Runs chromeos-setgoodkernel, whose responsibility it is to mark the 131 // currently booted partition has high priority/permanent/etc. The execution 132 // is asynchronous. On completion, the action processor may be started 133 // depending on the |start_action_processor_| field. Note that every update 134 // attempt goes through this method. 135 void UpdateBootFlags(); 136 137 // Called when the boot flags have been updated. 138 void CompleteUpdateBootFlags(bool success); 139 140 UpdateStatus status() const { return status_; } 141 142 int http_response_code() const { return http_response_code_; } 143 void set_http_response_code(int code) { http_response_code_ = code; } 144 145 // This is the internal entry point for going through an 146 // update. If the current status is idle invokes Update. 147 // This is called by the DBus implementation. 148 virtual void CheckForUpdate(const std::string& app_version, 149 const std::string& omaha_url, 150 bool is_interactive); 151 152 // This is the internal entry point for going through a rollback. This will 153 // attempt to run the postinstall on the non-active partition and set it as 154 // the partition to boot from. If |powerwash| is True, perform a powerwash 155 // as part of rollback. Returns True on success. 156 bool Rollback(bool powerwash); 157 158 // This is the internal entry point for checking if we can rollback. 159 bool CanRollback() const; 160 161 // This is the internal entry point for getting a rollback partition name, 162 // if one exists. It returns the bootable rollback kernel device partition 163 // name or empty string if none is available. 164 BootControlInterface::Slot GetRollbackSlot() const; 165 166 // Initiates a reboot if the current state is 167 // UPDATED_NEED_REBOOT. Returns true on sucess, false otherwise. 168 bool RebootIfNeeded(); 169 170 // DownloadActionDelegate methods: 171 void BytesReceived(uint64_t bytes_progressed, 172 uint64_t bytes_received, 173 uint64_t total) override; 174 175 // Returns that the update should be canceled when the download channel was 176 // changed. 177 bool ShouldCancel(ErrorCode* cancel_reason) override; 178 179 void DownloadComplete() override; 180 181 // Broadcasts the current status to all observers. 182 void BroadcastStatus(); 183 184 // Broadcasts the current tracking channel to all observers. 185 void BroadcastChannel(); 186 187 // Returns the special flags to be added to ErrorCode values based on the 188 // parameters used in the current update attempt. 189 uint32_t GetErrorCodeFlags(); 190 191 // Called at update_engine startup to do various house-keeping. 192 void UpdateEngineStarted(); 193 194 // Reloads the device policy from libbrillo. Note: This method doesn't 195 // cause a real-time policy fetch from the policy server. It just reloads the 196 // latest value that libbrillo has cached. libbrillo fetches the policies 197 // from the server asynchronously at its own frequency. 198 virtual void RefreshDevicePolicy(); 199 200 // Stores in |out_boot_time| the boottime (CLOCK_BOOTTIME) recorded at the 201 // time of the last successful update in the current boot. Returns false if 202 // there wasn't a successful update in the current boot. 203 virtual bool GetBootTimeAtUpdate(base::Time *out_boot_time); 204 205 // Returns a version OS version that was being used before the last reboot, 206 // and if that reboot happended to be into an update (current version). 207 // This will return an empty string otherwise. 208 std::string const& GetPrevVersion() const { return prev_version_; } 209 210 // Returns the number of consecutive failed update checks. 211 virtual unsigned int consecutive_failed_update_checks() const { 212 return consecutive_failed_update_checks_; 213 } 214 215 // Returns the poll interval dictated by Omaha, if provided; zero otherwise. 216 virtual unsigned int server_dictated_poll_interval() const { 217 return server_dictated_poll_interval_; 218 } 219 220 // Sets a callback to be used when either a forced update request is received 221 // (first argument set to true) or cleared by an update attempt (first 222 // argument set to false). The callback further encodes whether the forced 223 // check is an interactive one (second argument set to true). Takes ownership 224 // of the callback object. A null value disables callback on these events. 225 // Note that only one callback can be set, so effectively at most one client 226 // can be notified. 227 virtual void set_forced_update_pending_callback( 228 base::Callback<void(bool, bool)>* // NOLINT(readability/function) 229 callback) { 230 forced_update_pending_callback_.reset(callback); 231 } 232 233 // Returns true if we should allow updates from any source. In official builds 234 // we want to restrict updates to known safe sources, but under certain 235 // conditions it's useful to allow updating from anywhere (e.g. to allow 236 // 'cros flash' to function properly). 237 virtual bool IsAnyUpdateSourceAllowed(); 238 239 // Add and remove a service observer. 240 void AddObserver(ServiceObserverInterface* observer) { 241 service_observers_.insert(observer); 242 } 243 void RemoveObserver(ServiceObserverInterface* observer) { 244 service_observers_.erase(observer); 245 } 246 247 const std::set<ServiceObserverInterface*>& service_observers() { 248 return service_observers_; 249 } 250 251 // Remove all the observers. 252 void ClearObservers() { service_observers_.clear(); } 253 254 private: 255 // Update server URL for automated lab test. 256 static const char* const kTestUpdateUrl; 257 258 // Friend declarations for testing purposes. 259 friend class UpdateAttempterUnderTest; 260 friend class UpdateAttempterTest; 261 FRIEND_TEST(UpdateAttempterTest, ActionCompletedDownloadTest); 262 FRIEND_TEST(UpdateAttempterTest, ActionCompletedErrorTest); 263 FRIEND_TEST(UpdateAttempterTest, ActionCompletedOmahaRequestTest); 264 FRIEND_TEST(UpdateAttempterTest, CreatePendingErrorEventTest); 265 FRIEND_TEST(UpdateAttempterTest, CreatePendingErrorEventResumedTest); 266 FRIEND_TEST(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest); 267 FRIEND_TEST(UpdateAttempterTest, MarkDeltaUpdateFailureTest); 268 FRIEND_TEST(UpdateAttempterTest, PingOmahaTest); 269 FRIEND_TEST(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest); 270 FRIEND_TEST(UpdateAttempterTest, ScheduleErrorEventActionTest); 271 FRIEND_TEST(UpdateAttempterTest, UpdateTest); 272 FRIEND_TEST(UpdateAttempterTest, ReportDailyMetrics); 273 FRIEND_TEST(UpdateAttempterTest, BootTimeInUpdateMarkerFile); 274 275 // CertificateChecker::Observer method. 276 // Report metrics about the certificate being checked. 277 void CertificateChecked(ServerToCheck server_to_check, 278 CertificateCheckResult result) override; 279 280 // Checks if it's more than 24 hours since daily metrics were last 281 // reported and, if so, reports daily metrics. Returns |true| if 282 // metrics were reported, |false| otherwise. 283 bool CheckAndReportDailyMetrics(); 284 285 // Calculates and reports the age of the currently running OS. This 286 // is defined as the age of the /etc/lsb-release file. 287 void ReportOSAge(); 288 289 // Sets the status to the given status and notifies a status update over dbus. 290 void SetStatusAndNotify(UpdateStatus status); 291 292 // Sets up the download parameters after receiving the update check response. 293 void SetupDownload(); 294 295 // Creates an error event object in |error_event_| to be included in an 296 // OmahaRequestAction once the current action processor is done. 297 void CreatePendingErrorEvent(AbstractAction* action, ErrorCode code); 298 299 // If there's a pending error event allocated in |error_event_|, schedules an 300 // OmahaRequestAction with that event in the current processor, clears the 301 // pending event, updates the status and returns true. Returns false 302 // otherwise. 303 bool ScheduleErrorEventAction(); 304 305 // Schedules an event loop callback to start the action processor. This is 306 // scheduled asynchronously to unblock the event loop. 307 void ScheduleProcessingStart(); 308 309 // Checks if a full update is needed and forces it by updating the Omaha 310 // request params. 311 void DisableDeltaUpdateIfNeeded(); 312 313 // If this was a delta update attempt that failed, count it so that a full 314 // update can be tried when needed. 315 void MarkDeltaUpdateFailure(); 316 317 ProxyResolver* GetProxyResolver() { 318 #if USE_LIBCROS 319 return obeying_proxies_ ? 320 reinterpret_cast<ProxyResolver*>(&chrome_proxy_resolver_) : 321 reinterpret_cast<ProxyResolver*>(&direct_proxy_resolver_); 322 #else 323 return &direct_proxy_resolver_; 324 #endif // USE_LIBCROS 325 } 326 327 // Sends a ping to Omaha. 328 // This is used after an update has been applied and we're waiting for the 329 // user to reboot. This ping helps keep the number of actives count 330 // accurate in case a user takes a long time to reboot the device after an 331 // update has been applied. 332 void PingOmaha(); 333 334 // Helper method of Update() to calculate the update-related parameters 335 // from various sources and set the appropriate state. Please refer to 336 // Update() method for the meaning of the parametes. 337 bool CalculateUpdateParams(const std::string& app_version, 338 const std::string& omaha_url, 339 const std::string& target_channel, 340 const std::string& target_version_prefix, 341 bool obey_proxies, 342 bool interactive); 343 344 // Calculates all the scattering related parameters (such as waiting period, 345 // which type of scattering is enabled, etc.) and also updates/deletes 346 // the corresponding prefs file used in scattering. Should be called 347 // only after the device policy has been loaded and set in the system_state_. 348 void CalculateScatteringParams(bool is_interactive); 349 350 // Sets a random value for the waiting period to wait for before downloading 351 // an update, if one available. This value will be upperbounded by the 352 // scatter factor value specified from policy. 353 void GenerateNewWaitingPeriod(); 354 355 // Helper method of Update() and Rollback() to construct the sequence of 356 // actions to be performed for the postinstall. 357 // |previous_action| is the previous action to get 358 // bonded with the install_plan that gets passed to postinstall. 359 void BuildPostInstallActions(InstallPlanAction* previous_action); 360 361 // Helper method of Update() to construct the sequence of actions to 362 // be performed for an update check. Please refer to 363 // Update() method for the meaning of the parameters. 364 void BuildUpdateActions(bool interactive); 365 366 // Decrements the count in the kUpdateCheckCountFilePath. 367 // Returns True if successfully decremented, false otherwise. 368 bool DecrementUpdateCheckCount(); 369 370 // Starts p2p and performs housekeeping. Returns true only if p2p is 371 // running and housekeeping was done. 372 bool StartP2PAndPerformHousekeeping(); 373 374 // Calculates whether peer-to-peer should be used. Sets the 375 // |use_p2p_to_download_| and |use_p2p_to_share_| parameters 376 // on the |omaha_request_params_| object. 377 void CalculateP2PParams(bool interactive); 378 379 // Starts P2P if it's enabled and there are files to actually share. 380 // Called only at program startup. Returns true only if p2p was 381 // started and housekeeping was performed. 382 bool StartP2PAtStartup(); 383 384 // Writes to the processing completed marker. Does nothing if 385 // |update_completed_marker_| is empty. 386 void WriteUpdateCompletedMarker(); 387 388 // Sends a D-Bus message to the Chrome OS power manager asking it to reboot 389 // the system. Returns true on success. 390 bool RequestPowerManagerReboot(); 391 392 // Reboots the system directly by calling /sbin/shutdown. Returns true on 393 // success. 394 bool RebootDirectly(); 395 396 // Callback for the async UpdateCheckAllowed policy request. If |status| is 397 // |EvalStatus::kSucceeded|, either runs or suppresses periodic update checks, 398 // based on the content of |params|. Otherwise, retries the policy request. 399 void OnUpdateScheduled( 400 chromeos_update_manager::EvalStatus status, 401 const chromeos_update_manager::UpdateCheckParams& params); 402 403 // Updates the time an update was last attempted to the current time. 404 void UpdateLastCheckedTime(); 405 406 // Returns whether an update is currently running or scheduled. 407 bool IsUpdateRunningOrScheduled(); 408 409 // Last status notification timestamp used for throttling. Use monotonic 410 // TimeTicks to ensure that notifications are sent even if the system clock is 411 // set back in the middle of an update. 412 base::TimeTicks last_notify_time_; 413 414 std::vector<std::shared_ptr<AbstractAction>> actions_; 415 std::unique_ptr<ActionProcessor> processor_; 416 417 // External state of the system outside the update_engine process 418 // carved out separately to mock out easily in unit tests. 419 SystemState* system_state_; 420 421 // Pointer to the certificate checker instance to use. 422 CertificateChecker* cert_checker_; 423 424 // The list of services observing changes in the updater. 425 std::set<ServiceObserverInterface*> service_observers_; 426 427 // Pointer to the OmahaResponseHandlerAction in the actions_ vector. 428 std::shared_ptr<OmahaResponseHandlerAction> response_handler_action_; 429 430 // Pointer to the DownloadAction in the actions_ vector. 431 std::shared_ptr<DownloadAction> download_action_; 432 433 // Pointer to the preferences store interface. This is just a cached 434 // copy of system_state->prefs() because it's used in many methods and 435 // is convenient this way. 436 PrefsInterface* prefs_ = nullptr; 437 438 // Pending error event, if any. 439 std::unique_ptr<OmahaEvent> error_event_; 440 441 // If we should request a reboot even tho we failed the update 442 bool fake_update_success_ = false; 443 444 // HTTP server response code from the last HTTP request action. 445 int http_response_code_ = 0; 446 447 // CPU limiter during the update. 448 CPULimiter cpu_limiter_; 449 450 // For status: 451 UpdateStatus status_{UpdateStatus::IDLE}; 452 double download_progress_ = 0.0; 453 int64_t last_checked_time_ = 0; 454 std::string prev_version_; 455 std::string new_version_ = "0.0.0.0"; 456 int64_t new_payload_size_ = 0; 457 458 // Common parameters for all Omaha requests. 459 OmahaRequestParams* omaha_request_params_ = nullptr; 460 461 // Number of consecutive manual update checks we've had where we obeyed 462 // Chrome's proxy settings. 463 int proxy_manual_checks_ = 0; 464 465 // If true, this update cycle we are obeying proxies 466 bool obeying_proxies_ = true; 467 468 // Our two proxy resolvers 469 DirectProxyResolver direct_proxy_resolver_; 470 #if USE_LIBCROS 471 ChromeBrowserProxyResolver chrome_proxy_resolver_; 472 #endif // USE_LIBCROS 473 474 // Originally, both of these flags are false. Once UpdateBootFlags is called, 475 // |update_boot_flags_running_| is set to true. As soon as UpdateBootFlags 476 // completes its asynchronous run, |update_boot_flags_running_| is reset to 477 // false and |updated_boot_flags_| is set to true. From that point on there 478 // will be no more changes to these flags. 479 // 480 // True if UpdateBootFlags has completed. 481 bool updated_boot_flags_ = false; 482 // True if UpdateBootFlags is running. 483 bool update_boot_flags_running_ = false; 484 485 // True if the action processor needs to be started by the boot flag updater. 486 bool start_action_processor_ = false; 487 488 // Used for fetching information about the device policy. 489 std::unique_ptr<policy::PolicyProvider> policy_provider_; 490 491 // The current scatter factor as found in the policy setting. 492 base::TimeDelta scatter_factor_; 493 494 // The number of consecutive failed update checks. Needed for calculating the 495 // next update check interval. 496 unsigned int consecutive_failed_update_checks_ = 0; 497 498 // The poll interval (in seconds) that was dictated by Omaha, if any; zero 499 // otherwise. This is needed for calculating the update check interval. 500 unsigned int server_dictated_poll_interval_ = 0; 501 502 // Tracks whether we have scheduled update checks. 503 bool waiting_for_scheduled_check_ = false; 504 505 // A callback to use when a forced update request is either received (true) or 506 // cleared by an update attempt (false). The second argument indicates whether 507 // this is an interactive update, and its value is significant iff the first 508 // argument is true. 509 std::unique_ptr<base::Callback<void(bool, bool)>> 510 forced_update_pending_callback_; 511 512 // The |app_version| and |omaha_url| parameters received during the latest 513 // forced update request. They are retrieved for use once the update is 514 // actually scheduled. 515 std::string forced_app_version_; 516 std::string forced_omaha_url_; 517 518 org::chromium::debugdProxyInterface* debugd_proxy_; 519 520 DISALLOW_COPY_AND_ASSIGN(UpdateAttempter); 521 }; 522 523 } // namespace chromeos_update_engine 524 525 #endif // UPDATE_ENGINE_UPDATE_ATTEMPTER_H_ 526