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