update_attempter.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. #ifndef UPDATE_ENGINE_UPDATE_ATTEMPTER_H_
  17. #define UPDATE_ENGINE_UPDATE_ATTEMPTER_H_
  18. #include <time.h>
  19. #include <memory>
  20. #include <set>
  21. #include <string>
  22. #include <utility>
  23. #include <vector>
  24. #include <base/bind.h>
  25. #include <base/time/time.h>
  26. #include <gtest/gtest_prod.h> // for FRIEND_TEST
  27. #if USE_CHROME_NETWORK_PROXY
  28. #include "update_engine/chrome_browser_proxy_resolver.h"
  29. #endif // USE_CHROME_NETWORK_PROXY
  30. #include "update_engine/certificate_checker.h"
  31. #include "update_engine/client_library/include/update_engine/update_status.h"
  32. #include "update_engine/common/action_processor.h"
  33. #include "update_engine/common/cpu_limiter.h"
  34. #include "update_engine/common/proxy_resolver.h"
  35. #include "update_engine/omaha_request_params.h"
  36. #include "update_engine/omaha_response_handler_action.h"
  37. #include "update_engine/payload_consumer/download_action.h"
  38. #include "update_engine/payload_consumer/postinstall_runner_action.h"
  39. #include "update_engine/service_observer_interface.h"
  40. #include "update_engine/system_state.h"
  41. #include "update_engine/update_manager/policy.h"
  42. #include "update_engine/update_manager/staging_utils.h"
  43. #include "update_engine/update_manager/update_manager.h"
  44. namespace policy {
  45. class PolicyProvider;
  46. }
  47. namespace chromeos_update_engine {
  48. class UpdateAttempter : public ActionProcessorDelegate,
  49. public DownloadActionDelegate,
  50. public CertificateChecker::Observer,
  51. public PostinstallRunnerAction::DelegateInterface {
  52. public:
  53. using UpdateStatus = update_engine::UpdateStatus;
  54. using UpdateAttemptFlags = update_engine::UpdateAttemptFlags;
  55. static const int kMaxDeltaUpdateFailures;
  56. UpdateAttempter(SystemState* system_state, CertificateChecker* cert_checker);
  57. ~UpdateAttempter() override;
  58. // Further initialization to be done post construction.
  59. void Init();
  60. // Initiates scheduling of update checks.
  61. // Returns true if update check is scheduled.
  62. virtual bool ScheduleUpdates();
  63. // Checks for update and, if a newer version is available, attempts to update
  64. // the system. Non-empty |in_app_version| or |in_update_url| prevents
  65. // automatic detection of the parameter. |target_channel| denotes a
  66. // policy-mandated channel we are updating to, if not empty. If |obey_proxies|
  67. // is true, the update will likely respect Chrome's proxy setting. For
  68. // security reasons, we may still not honor them. |interactive| should be true
  69. // if this was called from the user (ie dbus).
  70. virtual void Update(const std::string& app_version,
  71. const std::string& omaha_url,
  72. const std::string& target_channel,
  73. const std::string& target_version_prefix,
  74. bool rollback_allowed,
  75. bool obey_proxies,
  76. bool interactive);
  77. // ActionProcessorDelegate methods:
  78. void ProcessingDone(const ActionProcessor* processor,
  79. ErrorCode code) override;
  80. void ProcessingStopped(const ActionProcessor* processor) override;
  81. void ActionCompleted(ActionProcessor* processor,
  82. AbstractAction* action,
  83. ErrorCode code) override;
  84. // PostinstallRunnerAction::DelegateInterface
  85. void ProgressUpdate(double progress) override;
  86. // Resets the current state to UPDATE_STATUS_IDLE.
  87. // Used by update_engine_client for restarting a new update without
  88. // having to reboot once the previous update has reached
  89. // UPDATE_STATUS_UPDATED_NEED_REBOOT state. This is used only
  90. // for testing purposes.
  91. virtual bool ResetStatus();
  92. // Returns the current status in the out param. Returns true on success.
  93. virtual bool GetStatus(update_engine::UpdateEngineStatus* out_status);
  94. UpdateStatus status() const { return status_; }
  95. int http_response_code() const { return http_response_code_; }
  96. void set_http_response_code(int code) { http_response_code_ = code; }
  97. // Set flags that influence how updates and checks are performed. These
  98. // influence all future checks and updates until changed or the device
  99. // reboots.
  100. void SetUpdateAttemptFlags(UpdateAttemptFlags flags) {
  101. update_attempt_flags_ = flags;
  102. }
  103. // Returns the update attempt flags that are in place for the current update
  104. // attempt. These are cached at the start of an update attempt so that they
  105. // remain constant throughout the process.
  106. virtual UpdateAttemptFlags GetCurrentUpdateAttemptFlags() const {
  107. return current_update_attempt_flags_;
  108. }
  109. // This is the internal entry point for going through an
  110. // update. If the current status is idle invokes Update.
  111. // This is called by the DBus implementation.
  112. // This returns true if an update check was started, false if a check or an
  113. // update was already in progress.
  114. virtual bool CheckForUpdate(const std::string& app_version,
  115. const std::string& omaha_url,
  116. UpdateAttemptFlags flags);
  117. // This is the version of CheckForUpdate called by AttemptInstall API.
  118. virtual bool CheckForInstall(const std::vector<std::string>& dlc_module_ids,
  119. const std::string& omaha_url);
  120. // This is the internal entry point for going through a rollback. This will
  121. // attempt to run the postinstall on the non-active partition and set it as
  122. // the partition to boot from. If |powerwash| is True, perform a powerwash
  123. // as part of rollback. Returns True on success.
  124. bool Rollback(bool powerwash);
  125. // This is the internal entry point for checking if we can rollback.
  126. bool CanRollback() const;
  127. // This is the internal entry point for getting a rollback partition name,
  128. // if one exists. It returns the bootable rollback kernel device partition
  129. // name or empty string if none is available.
  130. BootControlInterface::Slot GetRollbackSlot() const;
  131. // Initiates a reboot if the current state is
  132. // UPDATED_NEED_REBOOT. Returns true on success, false otherwise.
  133. bool RebootIfNeeded();
  134. // DownloadActionDelegate methods:
  135. void BytesReceived(uint64_t bytes_progressed,
  136. uint64_t bytes_received,
  137. uint64_t total) override;
  138. // Returns that the update should be canceled when the download channel was
  139. // changed.
  140. bool ShouldCancel(ErrorCode* cancel_reason) override;
  141. void DownloadComplete() override;
  142. // Broadcasts the current status to all observers.
  143. void BroadcastStatus();
  144. ErrorCode GetAttemptErrorCode() const { return attempt_error_code_; }
  145. // Called at update_engine startup to do various house-keeping.
  146. void UpdateEngineStarted();
  147. // Reloads the device policy from libbrillo. Note: This method doesn't
  148. // cause a real-time policy fetch from the policy server. It just reloads the
  149. // latest value that libbrillo has cached. libbrillo fetches the policies
  150. // from the server asynchronously at its own frequency.
  151. virtual void RefreshDevicePolicy();
  152. // Stores in |out_boot_time| the boottime (CLOCK_BOOTTIME) recorded at the
  153. // time of the last successful update in the current boot. Returns false if
  154. // there wasn't a successful update in the current boot.
  155. virtual bool GetBootTimeAtUpdate(base::Time* out_boot_time);
  156. // Returns a version OS version that was being used before the last reboot,
  157. // and if that reboot happened to be into an update (current version).
  158. // This will return an empty string otherwise.
  159. const std::string& GetPrevVersion() const { return prev_version_; }
  160. // Returns the number of consecutive failed update checks.
  161. virtual unsigned int consecutive_failed_update_checks() const {
  162. return consecutive_failed_update_checks_;
  163. }
  164. // Returns the poll interval dictated by Omaha, if provided; zero otherwise.
  165. virtual unsigned int server_dictated_poll_interval() const {
  166. return server_dictated_poll_interval_;
  167. }
  168. // Sets a callback to be used when either a forced update request is received
  169. // (first argument set to true) or cleared by an update attempt (first
  170. // argument set to false). The callback further encodes whether the forced
  171. // check is an interactive one (second argument set to true). Takes ownership
  172. // of the callback object. A null value disables callback on these events.
  173. // Note that only one callback can be set, so effectively at most one client
  174. // can be notified.
  175. virtual void set_forced_update_pending_callback(
  176. base::Callback<void(bool, bool)>* callback) {
  177. forced_update_pending_callback_.reset(callback);
  178. }
  179. // Returns true if we should allow updates from any source. In official builds
  180. // we want to restrict updates to known safe sources, but under certain
  181. // conditions it's useful to allow updating from anywhere (e.g. to allow
  182. // 'cros flash' to function properly).
  183. bool IsAnyUpdateSourceAllowed() const;
  184. // Add and remove a service observer.
  185. void AddObserver(ServiceObserverInterface* observer) {
  186. service_observers_.insert(observer);
  187. }
  188. void RemoveObserver(ServiceObserverInterface* observer) {
  189. service_observers_.erase(observer);
  190. }
  191. const std::set<ServiceObserverInterface*>& service_observers() {
  192. return service_observers_;
  193. }
  194. // Remove all the observers.
  195. void ClearObservers() { service_observers_.clear(); }
  196. private:
  197. // Friend declarations for testing purposes.
  198. friend class UpdateAttempterUnderTest;
  199. friend class UpdateAttempterTest;
  200. FRIEND_TEST(UpdateAttempterTest, ActionCompletedDownloadTest);
  201. FRIEND_TEST(UpdateAttempterTest, ActionCompletedErrorTest);
  202. FRIEND_TEST(UpdateAttempterTest, ActionCompletedOmahaRequestTest);
  203. FRIEND_TEST(UpdateAttempterTest, BootTimeInUpdateMarkerFile);
  204. FRIEND_TEST(UpdateAttempterTest, BroadcastCompleteDownloadTest);
  205. FRIEND_TEST(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest);
  206. FRIEND_TEST(UpdateAttempterTest, CheckForUpdateAUDlcTest);
  207. FRIEND_TEST(UpdateAttempterTest, CreatePendingErrorEventTest);
  208. FRIEND_TEST(UpdateAttempterTest, CreatePendingErrorEventResumedTest);
  209. FRIEND_TEST(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest);
  210. FRIEND_TEST(UpdateAttempterTest, DownloadProgressAccumulationTest);
  211. FRIEND_TEST(UpdateAttempterTest, InstallSetsStatusIdle);
  212. FRIEND_TEST(UpdateAttempterTest, MarkDeltaUpdateFailureTest);
  213. FRIEND_TEST(UpdateAttempterTest, PingOmahaTest);
  214. FRIEND_TEST(UpdateAttempterTest, ReportDailyMetrics);
  215. FRIEND_TEST(UpdateAttempterTest, RollbackNotAllowed);
  216. FRIEND_TEST(UpdateAttempterTest, RollbackAfterInstall);
  217. FRIEND_TEST(UpdateAttempterTest, RollbackAllowed);
  218. FRIEND_TEST(UpdateAttempterTest, RollbackAllowedSetAndReset);
  219. FRIEND_TEST(UpdateAttempterTest, RollbackMetricsNotRollbackFailure);
  220. FRIEND_TEST(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess);
  221. FRIEND_TEST(UpdateAttempterTest, RollbackMetricsRollbackFailure);
  222. FRIEND_TEST(UpdateAttempterTest, RollbackMetricsRollbackSuccess);
  223. FRIEND_TEST(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest);
  224. FRIEND_TEST(UpdateAttempterTest, ScheduleErrorEventActionTest);
  225. FRIEND_TEST(UpdateAttempterTest, SetRollbackHappenedNotRollback);
  226. FRIEND_TEST(UpdateAttempterTest, SetRollbackHappenedRollback);
  227. FRIEND_TEST(UpdateAttempterTest, TargetVersionPrefixSetAndReset);
  228. FRIEND_TEST(UpdateAttempterTest, UpdateAfterInstall);
  229. FRIEND_TEST(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart);
  230. FRIEND_TEST(UpdateAttempterTest, UpdateDeferredByPolicyTest);
  231. FRIEND_TEST(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable);
  232. // Returns the special flags to be added to ErrorCode values based on the
  233. // parameters used in the current update attempt.
  234. uint32_t GetErrorCodeFlags();
  235. // CertificateChecker::Observer method.
  236. // Report metrics about the certificate being checked.
  237. void CertificateChecked(ServerToCheck server_to_check,
  238. CertificateCheckResult result) override;
  239. // Checks if it's more than 24 hours since daily metrics were last
  240. // reported and, if so, reports daily metrics. Returns |true| if
  241. // metrics were reported, |false| otherwise.
  242. bool CheckAndReportDailyMetrics();
  243. // Calculates and reports the age of the currently running OS. This
  244. // is defined as the age of the /etc/lsb-release file.
  245. void ReportOSAge();
  246. // Sets the status to the given status and notifies a status update over dbus.
  247. void SetStatusAndNotify(UpdateStatus status);
  248. // Creates an error event object in |error_event_| to be included in an
  249. // OmahaRequestAction once the current action processor is done.
  250. void CreatePendingErrorEvent(AbstractAction* action, ErrorCode code);
  251. // If there's a pending error event allocated in |error_event_|, schedules an
  252. // OmahaRequestAction with that event in the current processor, clears the
  253. // pending event, updates the status and returns true. Returns false
  254. // otherwise.
  255. bool ScheduleErrorEventAction();
  256. // Schedules an event loop callback to start the action processor. This is
  257. // scheduled asynchronously to unblock the event loop.
  258. void ScheduleProcessingStart();
  259. // Checks if a full update is needed and forces it by updating the Omaha
  260. // request params.
  261. void DisableDeltaUpdateIfNeeded();
  262. // If this was a delta update attempt that failed, count it so that a full
  263. // update can be tried when needed.
  264. void MarkDeltaUpdateFailure();
  265. ProxyResolver* GetProxyResolver() {
  266. #if USE_CHROME_NETWORK_PROXY
  267. if (obeying_proxies_)
  268. return &chrome_proxy_resolver_;
  269. #endif // USE_CHROME_NETWORK_PROXY
  270. return &direct_proxy_resolver_;
  271. }
  272. // Sends a ping to Omaha.
  273. // This is used after an update has been applied and we're waiting for the
  274. // user to reboot. This ping helps keep the number of actives count
  275. // accurate in case a user takes a long time to reboot the device after an
  276. // update has been applied.
  277. void PingOmaha();
  278. // Helper method of Update() to calculate the update-related parameters
  279. // from various sources and set the appropriate state. Please refer to
  280. // Update() method for the meaning of the parameters.
  281. bool CalculateUpdateParams(const std::string& app_version,
  282. const std::string& omaha_url,
  283. const std::string& target_channel,
  284. const std::string& target_version_prefix,
  285. bool rollback_allowed,
  286. bool obey_proxies,
  287. bool interactive);
  288. // Calculates all the scattering related parameters (such as waiting period,
  289. // which type of scattering is enabled, etc.) and also updates/deletes
  290. // the corresponding prefs file used in scattering. Should be called
  291. // only after the device policy has been loaded and set in the system_state_.
  292. void CalculateScatteringParams(bool interactive);
  293. // Sets a random value for the waiting period to wait for before downloading
  294. // an update, if one available. This value will be upperbounded by the
  295. // scatter factor value specified from policy.
  296. void GenerateNewWaitingPeriod();
  297. // Helper method of Update() to construct the sequence of actions to
  298. // be performed for an update check. Please refer to
  299. // Update() method for the meaning of the parameters.
  300. void BuildUpdateActions(bool interactive);
  301. // Decrements the count in the kUpdateCheckCountFilePath.
  302. // Returns True if successfully decremented, false otherwise.
  303. bool DecrementUpdateCheckCount();
  304. // Starts p2p and performs housekeeping. Returns true only if p2p is
  305. // running and housekeeping was done.
  306. bool StartP2PAndPerformHousekeeping();
  307. // Calculates whether peer-to-peer should be used. Sets the
  308. // |use_p2p_to_download_| and |use_p2p_to_share_| parameters
  309. // on the |omaha_request_params_| object.
  310. void CalculateP2PParams(bool interactive);
  311. // Starts P2P if it's enabled and there are files to actually share.
  312. // Called only at program startup. Returns true only if p2p was
  313. // started and housekeeping was performed.
  314. bool StartP2PAtStartup();
  315. // Writes to the processing completed marker. Does nothing if
  316. // |update_completed_marker_| is empty.
  317. void WriteUpdateCompletedMarker();
  318. // Reboots the system directly by calling /sbin/shutdown. Returns true on
  319. // success.
  320. bool RebootDirectly();
  321. // Callback for the async UpdateCheckAllowed policy request. If |status| is
  322. // |EvalStatus::kSucceeded|, either runs or suppresses periodic update checks,
  323. // based on the content of |params|. Otherwise, retries the policy request.
  324. void OnUpdateScheduled(
  325. chromeos_update_manager::EvalStatus status,
  326. const chromeos_update_manager::UpdateCheckParams& params);
  327. // Updates the time an update was last attempted to the current time.
  328. void UpdateLastCheckedTime();
  329. // Checks whether we need to clear the rollback-happened preference after
  330. // policy is available again.
  331. void UpdateRollbackHappened();
  332. // Returns whether an update is currently running or scheduled.
  333. bool IsUpdateRunningOrScheduled();
  334. void CalculateStagingParams(bool interactive);
  335. // Reports a metric that tracks the time from when the update was first seen
  336. // to the time when the update was finally downloaded and applied. This metric
  337. // will only be reported for enterprise enrolled devices.
  338. void ReportTimeToUpdateAppliedMetric();
  339. // Last status notification timestamp used for throttling. Use monotonic
  340. // TimeTicks to ensure that notifications are sent even if the system clock is
  341. // set back in the middle of an update.
  342. base::TimeTicks last_notify_time_;
  343. // Our two proxy resolvers
  344. DirectProxyResolver direct_proxy_resolver_;
  345. #if USE_CHROME_NETWORK_PROXY
  346. ChromeBrowserProxyResolver chrome_proxy_resolver_;
  347. #endif // USE_CHROME_NETWORK_PROXY
  348. std::unique_ptr<ActionProcessor> processor_;
  349. // External state of the system outside the update_engine process
  350. // carved out separately to mock out easily in unit tests.
  351. SystemState* system_state_;
  352. // Pointer to the certificate checker instance to use.
  353. CertificateChecker* cert_checker_;
  354. // The list of services observing changes in the updater.
  355. std::set<ServiceObserverInterface*> service_observers_;
  356. // The install plan.
  357. std::unique_ptr<InstallPlan> install_plan_;
  358. // Pointer to the preferences store interface. This is just a cached
  359. // copy of system_state->prefs() because it's used in many methods and
  360. // is convenient this way.
  361. PrefsInterface* prefs_ = nullptr;
  362. // Pending error event, if any.
  363. std::unique_ptr<OmahaEvent> error_event_;
  364. // If we should request a reboot even tho we failed the update
  365. bool fake_update_success_ = false;
  366. // HTTP server response code from the last HTTP request action.
  367. int http_response_code_ = 0;
  368. // The attempt error code when the update attempt finished.
  369. ErrorCode attempt_error_code_ = ErrorCode::kSuccess;
  370. // CPU limiter during the update.
  371. CPULimiter cpu_limiter_;
  372. // For status:
  373. UpdateStatus status_{UpdateStatus::IDLE};
  374. double download_progress_ = 0.0;
  375. int64_t last_checked_time_ = 0;
  376. std::string prev_version_;
  377. std::string new_version_ = "0.0.0.0";
  378. std::string new_system_version_;
  379. uint64_t new_payload_size_ = 0;
  380. // Flags influencing all periodic update checks
  381. UpdateAttemptFlags update_attempt_flags_ = UpdateAttemptFlags::kNone;
  382. // Flags influencing the currently in-progress check (cached at the start of
  383. // the update check).
  384. UpdateAttemptFlags current_update_attempt_flags_ = UpdateAttemptFlags::kNone;
  385. // Common parameters for all Omaha requests.
  386. OmahaRequestParams* omaha_request_params_ = nullptr;
  387. // Number of consecutive manual update checks we've had where we obeyed
  388. // Chrome's proxy settings.
  389. int proxy_manual_checks_ = 0;
  390. // If true, this update cycle we are obeying proxies
  391. bool obeying_proxies_ = true;
  392. // Used for fetching information about the device policy.
  393. std::unique_ptr<policy::PolicyProvider> policy_provider_;
  394. // The current scatter factor as found in the policy setting.
  395. base::TimeDelta scatter_factor_;
  396. // The number of consecutive failed update checks. Needed for calculating the
  397. // next update check interval.
  398. unsigned int consecutive_failed_update_checks_ = 0;
  399. // The poll interval (in seconds) that was dictated by Omaha, if any; zero
  400. // otherwise. This is needed for calculating the update check interval.
  401. unsigned int server_dictated_poll_interval_ = 0;
  402. // Tracks whether we have scheduled update checks.
  403. bool waiting_for_scheduled_check_ = false;
  404. // A callback to use when a forced update request is either received (true) or
  405. // cleared by an update attempt (false). The second argument indicates whether
  406. // this is an interactive update, and its value is significant iff the first
  407. // argument is true.
  408. std::unique_ptr<base::Callback<void(bool, bool)>>
  409. forced_update_pending_callback_;
  410. // The |app_version| and |omaha_url| parameters received during the latest
  411. // forced update request. They are retrieved for use once the update is
  412. // actually scheduled.
  413. std::string forced_app_version_;
  414. std::string forced_omaha_url_;
  415. // A list of DLC module IDs.
  416. std::vector<std::string> dlc_module_ids_;
  417. // Whether the operation is install (write to the current slot not the
  418. // inactive slot).
  419. bool is_install_;
  420. // If this is not TimeDelta(), then that means staging is turned on.
  421. base::TimeDelta staging_wait_time_;
  422. chromeos_update_manager::StagingSchedule staging_schedule_;
  423. DISALLOW_COPY_AND_ASSIGN(UpdateAttempter);
  424. };
  425. // Turns a generic ErrorCode::kError to a generic error code specific
  426. // to |action| (e.g., ErrorCode::kFilesystemVerifierError). If |code| is
  427. // not ErrorCode::kError, or the action is not matched, returns |code|
  428. // unchanged.
  429. ErrorCode GetErrorCodeForAction(AbstractAction* action, ErrorCode code);
  430. } // namespace chromeos_update_engine
  431. #endif // UPDATE_ENGINE_UPDATE_ATTEMPTER_H_