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