payload_state.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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_PAYLOAD_STATE_H_
  17. #define UPDATE_ENGINE_PAYLOAD_STATE_H_
  18. #include <algorithm>
  19. #include <string>
  20. #include <vector>
  21. #include <base/time/time.h>
  22. #include <gtest/gtest_prod.h> // for FRIEND_TEST
  23. #include "update_engine/common/prefs_interface.h"
  24. #include "update_engine/metrics_constants.h"
  25. #include "update_engine/payload_state_interface.h"
  26. namespace chromeos_update_engine {
  27. class SystemState;
  28. // Encapsulates all the payload state required for download. This includes the
  29. // state necessary for handling multiple URLs in Omaha response, the backoff
  30. // state, etc. All state is persisted so that we use the most recently saved
  31. // value when resuming the update_engine process. All state is also cached in
  32. // memory so that we ensure we always make progress based on last known good
  33. // state even when there's any issue in reading/writing from the file system.
  34. class PayloadState : public PayloadStateInterface {
  35. public:
  36. PayloadState();
  37. ~PayloadState() override {}
  38. // Initializes a payload state object using the given global system state.
  39. // It performs the initial loading of all persisted state into memory and
  40. // dumps the initial state for debugging purposes. Note: the other methods
  41. // should be called only after calling Initialize on this object.
  42. bool Initialize(SystemState* system_state);
  43. // Implementation of PayloadStateInterface methods.
  44. void SetResponse(const OmahaResponse& response) override;
  45. void DownloadComplete() override;
  46. void DownloadProgress(size_t count) override;
  47. void UpdateResumed() override;
  48. void UpdateRestarted() override;
  49. void UpdateSucceeded() override;
  50. void UpdateFailed(ErrorCode error) override;
  51. void ResetUpdateStatus() override;
  52. bool ShouldBackoffDownload() override;
  53. void Rollback() override;
  54. void ExpectRebootInNewVersion(const std::string& target_version_uid) override;
  55. void SetUsingP2PForDownloading(bool value) override;
  56. void SetUsingP2PForSharing(bool value) override {
  57. using_p2p_for_sharing_ = value;
  58. }
  59. inline std::string GetResponseSignature() override {
  60. return response_signature_;
  61. }
  62. inline int GetFullPayloadAttemptNumber() override {
  63. return full_payload_attempt_number_;
  64. }
  65. inline int GetPayloadAttemptNumber() override {
  66. return payload_attempt_number_;
  67. }
  68. inline std::string GetCurrentUrl() override {
  69. return (payload_index_ < candidate_urls_.size() &&
  70. url_index_ < candidate_urls_[payload_index_].size())
  71. ? candidate_urls_[payload_index_][url_index_]
  72. : "";
  73. }
  74. inline uint32_t GetUrlFailureCount() override { return url_failure_count_; }
  75. inline uint32_t GetUrlSwitchCount() override { return url_switch_count_; }
  76. inline int GetNumResponsesSeen() override { return num_responses_seen_; }
  77. inline base::Time GetBackoffExpiryTime() override {
  78. return backoff_expiry_time_;
  79. }
  80. base::TimeDelta GetUpdateDuration() override;
  81. base::TimeDelta GetUpdateDurationUptime() override;
  82. inline uint64_t GetCurrentBytesDownloaded(DownloadSource source) override {
  83. return source < kNumDownloadSources ? current_bytes_downloaded_[source] : 0;
  84. }
  85. inline uint64_t GetTotalBytesDownloaded(DownloadSource source) override {
  86. return source < kNumDownloadSources ? total_bytes_downloaded_[source] : 0;
  87. }
  88. inline uint32_t GetNumReboots() override { return num_reboots_; }
  89. void UpdateEngineStarted() override;
  90. inline bool GetRollbackHappened() override { return rollback_happened_; }
  91. void SetRollbackHappened(bool rollback_happened) override;
  92. inline std::string GetRollbackVersion() override { return rollback_version_; }
  93. int GetP2PNumAttempts() override;
  94. base::Time GetP2PFirstAttemptTimestamp() override;
  95. void P2PNewAttempt() override;
  96. bool P2PAttemptAllowed() override;
  97. bool GetUsingP2PForDownloading() const override {
  98. return using_p2p_for_downloading_;
  99. }
  100. bool GetUsingP2PForSharing() const override { return using_p2p_for_sharing_; }
  101. base::TimeDelta GetScatteringWaitPeriod() override {
  102. return scattering_wait_period_;
  103. }
  104. void SetScatteringWaitPeriod(base::TimeDelta wait_period) override;
  105. void SetStagingWaitPeriod(base::TimeDelta wait_period) override;
  106. void SetP2PUrl(const std::string& url) override { p2p_url_ = url; }
  107. std::string GetP2PUrl() const override { return p2p_url_; }
  108. bool NextPayload() override;
  109. private:
  110. enum class AttemptType {
  111. kUpdate,
  112. kRollback,
  113. };
  114. friend class PayloadStateTest;
  115. FRIEND_TEST(PayloadStateTest, RebootAfterUpdateFailedMetric);
  116. FRIEND_TEST(PayloadStateTest, RebootAfterUpdateSucceed);
  117. FRIEND_TEST(PayloadStateTest, RebootAfterCanceledUpdate);
  118. FRIEND_TEST(PayloadStateTest, RollbackHappened);
  119. FRIEND_TEST(PayloadStateTest, RollbackVersion);
  120. FRIEND_TEST(PayloadStateTest, UpdateSuccessWithWipedPrefs);
  121. // Helper called when an attempt has begun, is called by
  122. // UpdateResumed(), UpdateRestarted() and Rollback().
  123. void AttemptStarted(AttemptType attempt_type);
  124. // Increments the payload attempt number used for metrics.
  125. void IncrementPayloadAttemptNumber();
  126. // Increments the payload attempt number which governs the backoff behavior
  127. // at the time of the next update check.
  128. void IncrementFullPayloadAttemptNumber();
  129. // Advances the current URL index to the next available one. If all URLs have
  130. // been exhausted during the current payload download attempt (as indicated
  131. // by the payload attempt number), then it will increment the payload attempt
  132. // number and wrap around again with the first URL in the list. This also
  133. // updates the URL switch count, if needed.
  134. void IncrementUrlIndex();
  135. // Increments the failure count of the current URL. If the configured max
  136. // failure count is reached for this URL, it advances the current URL index
  137. // to the next URL and resets the failure count for that URL.
  138. void IncrementFailureCount();
  139. // Updates the backoff expiry time exponentially based on the current
  140. // payload attempt number.
  141. void UpdateBackoffExpiryTime();
  142. // Updates the value of current download source based on the current URL
  143. // index. If the download source is not one of the known sources, it's set
  144. // to kNumDownloadSources.
  145. void UpdateCurrentDownloadSource();
  146. // Updates the various metrics corresponding with the given number of bytes
  147. // that were downloaded recently.
  148. void UpdateBytesDownloaded(size_t count);
  149. // Calculates the PayloadType we're using.
  150. PayloadType CalculatePayloadType();
  151. // Collects and reports the various metrics related to an update attempt.
  152. void CollectAndReportAttemptMetrics(ErrorCode code);
  153. // Persists values related to the UpdateEngine.Attempt.* metrics so
  154. // we can identify later if an update attempt ends abnormally.
  155. void PersistAttemptMetrics();
  156. // Clears persistent state previously set using AttemptMetricsPersist().
  157. void ClearPersistedAttemptMetrics();
  158. // Checks if persistent state previously set using AttemptMetricsPersist()
  159. // exists and, if so, emits it with |attempt_result| set to
  160. // metrics::AttemptResult::kAbnormalTermination.
  161. void ReportAndClearPersistedAttemptMetrics();
  162. // Collects and reports the various metrics related to a successful update.
  163. void CollectAndReportSuccessfulUpdateMetrics();
  164. // Checks if we were expecting to be running in the new version but the
  165. // boot into the new version failed for some reason. If that's the case, an
  166. // UMA metric is sent reporting the number of attempts the same applied
  167. // payload was attempted to reboot. This function is called by UpdateAttempter
  168. // every time the update engine starts and there's no reboot pending.
  169. void ReportFailedBootIfNeeded();
  170. // Resets all the persisted state values which are maintained relative to the
  171. // current response signature. The response signature itself is not reset.
  172. void ResetPersistedState();
  173. // Resets the appropriate state related to download sources that need to be
  174. // reset on a new update.
  175. void ResetDownloadSourcesOnNewUpdate();
  176. // Calculates the response "signature", which is basically a string composed
  177. // of the subset of the fields in the current response that affect the
  178. // behavior of the PayloadState.
  179. std::string CalculateResponseSignature();
  180. // Initializes the current response signature from the persisted state.
  181. void LoadResponseSignature();
  182. // Sets the response signature to the given value. Also persists the value
  183. // being set so that we resume from the save value in case of a process
  184. // restart.
  185. void SetResponseSignature(const std::string& response_signature);
  186. // Initializes the payload attempt number from the persisted state.
  187. void LoadPayloadAttemptNumber();
  188. // Initializes the payload attempt number for full payloads from the persisted
  189. // state.
  190. void LoadFullPayloadAttemptNumber();
  191. // Sets the payload attempt number to the given value. Also persists the
  192. // value being set so that we resume from the same value in case of a process
  193. // restart.
  194. void SetPayloadAttemptNumber(int payload_attempt_number);
  195. // Sets the payload attempt number for full updates to the given value. Also
  196. // persists the value being set so that we resume from the same value in case
  197. // of a process restart.
  198. void SetFullPayloadAttemptNumber(int payload_attempt_number);
  199. // Sets the current payload index to the given value. Also persists the value
  200. // being set so that we resume from the same value in case of a process
  201. // restart.
  202. void SetPayloadIndex(size_t payload_index);
  203. // Initializes the current URL index from the persisted state.
  204. void LoadUrlIndex();
  205. // Sets the current URL index to the given value. Also persists the value
  206. // being set so that we resume from the same value in case of a process
  207. // restart.
  208. void SetUrlIndex(uint32_t url_index);
  209. // Initializes the current URL's failure count from the persisted stae.
  210. void LoadUrlFailureCount();
  211. // Sets the current URL's failure count to the given value. Also persists the
  212. // value being set so that we resume from the same value in case of a process
  213. // restart.
  214. void SetUrlFailureCount(uint32_t url_failure_count);
  215. // Sets |url_switch_count_| to the given value and persists the value.
  216. void SetUrlSwitchCount(uint32_t url_switch_count);
  217. // Initializes |url_switch_count_| from the persisted stae.
  218. void LoadUrlSwitchCount();
  219. // Initializes the backoff expiry time from the persisted state.
  220. void LoadBackoffExpiryTime();
  221. // Sets the backoff expiry time to the given value. Also persists the value
  222. // being set so that we resume from the same value in case of a process
  223. // restart.
  224. void SetBackoffExpiryTime(const base::Time& new_time);
  225. // Initializes |update_timestamp_start_| from the persisted state.
  226. void LoadUpdateTimestampStart();
  227. // Sets |update_timestamp_start_| to the given value and persists the value.
  228. void SetUpdateTimestampStart(const base::Time& value);
  229. // Sets |update_timestamp_end_| to the given value. This is not persisted
  230. // as it happens at the end of the update process where state is deleted
  231. // anyway.
  232. void SetUpdateTimestampEnd(const base::Time& value);
  233. // Initializes |update_duration_uptime_| from the persisted state.
  234. void LoadUpdateDurationUptime();
  235. // Helper method used in SetUpdateDurationUptime() and
  236. // CalculateUpdateDurationUptime().
  237. void SetUpdateDurationUptimeExtended(const base::TimeDelta& value,
  238. const base::Time& timestamp,
  239. bool use_logging);
  240. // Sets |update_duration_uptime_| to the given value and persists
  241. // the value and sets |update_duration_uptime_timestamp_| to the
  242. // current monotonic time.
  243. void SetUpdateDurationUptime(const base::TimeDelta& value);
  244. // Adds the difference between current monotonic time and
  245. // |update_duration_uptime_timestamp_| to |update_duration_uptime_| and
  246. // sets |update_duration_uptime_timestamp_| to current monotonic time.
  247. void CalculateUpdateDurationUptime();
  248. // Returns the full key for a download source given the prefix.
  249. std::string GetPrefsKey(const std::string& prefix, DownloadSource source);
  250. // Loads the number of bytes that have been currently downloaded through the
  251. // previous attempts from the persisted state for the given source. It's
  252. // reset to 0 every time we begin a full update and is continued from previous
  253. // attempt if we're resuming the update.
  254. void LoadCurrentBytesDownloaded(DownloadSource source);
  255. // Sets the number of bytes that have been currently downloaded for the
  256. // given source. This value is also persisted.
  257. void SetCurrentBytesDownloaded(DownloadSource source,
  258. uint64_t current_bytes_downloaded,
  259. bool log);
  260. // Loads the total number of bytes that have been downloaded (since the last
  261. // successful update) from the persisted state for the given source. It's
  262. // reset to 0 every time we successfully apply an update and counts the bytes
  263. // downloaded for both successful and failed attempts since then.
  264. void LoadTotalBytesDownloaded(DownloadSource source);
  265. // Sets the total number of bytes that have been downloaded so far for the
  266. // given source. This value is also persisted.
  267. void SetTotalBytesDownloaded(DownloadSource source,
  268. uint64_t total_bytes_downloaded,
  269. bool log);
  270. // Loads whether rollback has happened on this device since the last update
  271. // check where policy was available. This info is preserved over powerwash.
  272. void LoadRollbackHappened();
  273. // Loads the blacklisted version from our prefs file.
  274. void LoadRollbackVersion();
  275. // Blacklists this version from getting AU'd to until we receive a new update
  276. // response.
  277. void SetRollbackVersion(const std::string& rollback_version);
  278. // Clears any blacklisted version.
  279. void ResetRollbackVersion();
  280. inline uint32_t GetUrlIndex() {
  281. return (url_index_ != 0 && payload_index_ < candidate_urls_.size())
  282. ? std::min(candidate_urls_[payload_index_].size() - 1,
  283. url_index_)
  284. : 0;
  285. }
  286. // Computes the list of candidate URLs from the total list of payload URLs in
  287. // the Omaha response.
  288. void ComputeCandidateUrls();
  289. // Sets |num_responses_seen_| and persist it to disk.
  290. void SetNumResponsesSeen(int num_responses_seen);
  291. // Initializes |num_responses_seen_| from persisted state.
  292. void LoadNumResponsesSeen();
  293. // Initializes |num_reboots_| from the persisted state.
  294. void LoadNumReboots();
  295. // Sets |num_reboots| for the update attempt. Also persists the
  296. // value being set so that we resume from the same value in case of a process
  297. // restart.
  298. void SetNumReboots(uint32_t num_reboots);
  299. // Checks to see if the device rebooted since the last call and if so
  300. // increments num_reboots.
  301. void UpdateNumReboots();
  302. // Loads the |kPrefsP2PFirstAttemptTimestamp| state variable from disk
  303. // into |p2p_first_attempt_timestamp_|.
  304. void LoadP2PFirstAttemptTimestamp();
  305. // Loads the |kPrefsP2PNumAttempts| state variable into |p2p_num_attempts_|.
  306. void LoadP2PNumAttempts();
  307. // Sets the |kPrefsP2PNumAttempts| state variable to |value|.
  308. void SetP2PNumAttempts(int value);
  309. // Sets the |kPrefsP2PFirstAttemptTimestamp| state variable to |time|.
  310. void SetP2PFirstAttemptTimestamp(const base::Time& time);
  311. // Loads the persisted scattering wallclock-based wait period.
  312. void LoadScatteringWaitPeriod();
  313. // Loads the persisted staging wallclock-based wait period.
  314. void LoadStagingWaitPeriod();
  315. // Get the total size of all payloads.
  316. int64_t GetPayloadSize();
  317. // The global state of the system.
  318. SystemState* system_state_;
  319. // Interface object with which we read/write persisted state. This must
  320. // be set by calling the Initialize method before calling any other method.
  321. PrefsInterface* prefs_;
  322. // Interface object with which we read/write persisted state. This must
  323. // be set by calling the Initialize method before calling any other method.
  324. // This object persists across powerwashes.
  325. PrefsInterface* powerwash_safe_prefs_;
  326. // This is the current response object from Omaha.
  327. OmahaResponse response_;
  328. // Whether P2P is being used for downloading and sharing.
  329. bool using_p2p_for_downloading_;
  330. bool using_p2p_for_sharing_;
  331. // Stores the P2P download URL, if one is used.
  332. std::string p2p_url_;
  333. // The cached value of |kPrefsP2PFirstAttemptTimestamp|.
  334. base::Time p2p_first_attempt_timestamp_;
  335. // The cached value of |kPrefsP2PNumAttempts|.
  336. int p2p_num_attempts_;
  337. // This stores a "signature" of the current response. The signature here
  338. // refers to a subset of the current response from Omaha. Each update to
  339. // this value is persisted so we resume from the same value in case of a
  340. // process restart.
  341. std::string response_signature_;
  342. // The number of times we've tried to download the payload. This is
  343. // incremented each time we download the payload successsfully or when we
  344. // exhaust all failure limits for all URLs and are about to wrap around back
  345. // to the first URL. Each update to this value is persisted so we resume from
  346. // the same value in case of a process restart.
  347. int payload_attempt_number_;
  348. // The number of times we've tried to download the payload in full. This is
  349. // incremented each time we download the payload in full successsfully or
  350. // when we exhaust all failure limits for all URLs and are about to wrap
  351. // around back to the first URL. Each update to this value is persisted so
  352. // we resume from the same value in case of a process restart.
  353. int full_payload_attempt_number_;
  354. // The index of the current payload.
  355. size_t payload_index_ = 0;
  356. // The index of the current URL. This type is different from the one in the
  357. // accessor methods because PrefsInterface supports only int64_t but we want
  358. // to provide a stronger abstraction of uint32_t. Each update to this value
  359. // is persisted so we resume from the same value in case of a process
  360. // restart.
  361. size_t url_index_;
  362. // The count of failures encountered in the current attempt to download using
  363. // the current URL (specified by url_index_). Each update to this value is
  364. // persisted so we resume from the same value in case of a process restart.
  365. int64_t url_failure_count_;
  366. // The number of times we've switched URLs.
  367. int32_t url_switch_count_;
  368. // The current download source based on the current URL. This value is
  369. // not persisted as it can be recomputed every time we update the URL.
  370. // We're storing this so as not to recompute this on every few bytes of
  371. // data we read from the socket.
  372. DownloadSource current_download_source_;
  373. // The number of different Omaha responses seen. Increases every time
  374. // a new response is seen. Resets to 0 only when the system has been
  375. // successfully updated.
  376. int num_responses_seen_;
  377. // The number of system reboots during an update attempt. Technically since
  378. // we don't go out of our way to not update it when not attempting an update,
  379. // also records the number of reboots before the next update attempt starts.
  380. uint32_t num_reboots_;
  381. // The timestamp until which we've to wait before attempting to download the
  382. // payload again, so as to backoff repeated downloads.
  383. base::Time backoff_expiry_time_;
  384. // The most recently calculated value of the update duration.
  385. base::TimeDelta update_duration_current_;
  386. // The point in time (wall-clock) that the update was started.
  387. base::Time update_timestamp_start_;
  388. // The point in time (wall-clock) that the update ended. If the update
  389. // is still in progress, this is set to the Epoch (e.g. 0).
  390. base::Time update_timestamp_end_;
  391. // The update duration uptime
  392. base::TimeDelta update_duration_uptime_;
  393. // The monotonic time when |update_duration_uptime_| was last set
  394. base::Time update_duration_uptime_timestamp_;
  395. // The number of bytes that have been downloaded for each source for each new
  396. // update attempt. If we resume an update, we'll continue from the previous
  397. // value, but if we get a new response or if the previous attempt failed,
  398. // we'll reset this to 0 to start afresh. Each update to this value is
  399. // persisted so we resume from the same value in case of a process restart.
  400. // The extra index in the array is to no-op accidental access in case the
  401. // return value from GetCurrentDownloadSource is used without validation.
  402. uint64_t current_bytes_downloaded_[kNumDownloadSources + 1];
  403. // The number of bytes that have been downloaded for each source since the
  404. // the last successful update. This is used to compute the overhead we incur.
  405. // Each update to this value is persisted so we resume from the same value in
  406. // case of a process restart.
  407. // The extra index in the array is to no-op accidental access in case the
  408. // return value from GetCurrentDownloadSource is used without validation.
  409. uint64_t total_bytes_downloaded_[kNumDownloadSources + 1];
  410. // A small timespan used when comparing wall-clock times for coping
  411. // with the fact that clocks drift and consequently are adjusted
  412. // (either forwards or backwards) via NTP.
  413. static const base::TimeDelta kDurationSlack;
  414. // The ordered list of the subset of payload URL candidates which are
  415. // allowed as per device policy.
  416. std::vector<std::vector<std::string>> candidate_urls_;
  417. // This stores whether rollback has happened since the last time device policy
  418. // was available during update check. When this is set, we're preventing
  419. // forced updates to avoid update-rollback loops.
  420. bool rollback_happened_;
  421. // This stores a blacklisted version set as part of rollback. When we rollback
  422. // we store the version of the os from which we are rolling back from in order
  423. // to guarantee that we do not re-update to it on the next au attempt after
  424. // reboot.
  425. std::string rollback_version_;
  426. // The number of bytes downloaded per attempt.
  427. int64_t attempt_num_bytes_downloaded_;
  428. // The boot time when the attempt was started.
  429. base::Time attempt_start_time_boot_;
  430. // The monotonic time when the attempt was started.
  431. base::Time attempt_start_time_monotonic_;
  432. // The connection type when the attempt started.
  433. metrics::ConnectionType attempt_connection_type_;
  434. // Whether we're currently rolling back.
  435. AttemptType attempt_type_;
  436. // The current scattering wallclock-based wait period.
  437. base::TimeDelta scattering_wait_period_;
  438. // The current staging wallclock-based wait period.
  439. base::TimeDelta staging_wait_period_;
  440. DISALLOW_COPY_AND_ASSIGN(PayloadState);
  441. };
  442. } // namespace chromeos_update_engine
  443. #endif // UPDATE_ENGINE_PAYLOAD_STATE_H_