1 //
2 // Copyright (C) 2016 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_ANDROID_H_
18 #define UPDATE_ENGINE_UPDATE_ATTEMPTER_ANDROID_H_
19 
20 #include <stdint.h>
21 
22 #include <memory>
23 #include <string>
24 #include <vector>
25 
26 #include <android-base/unique_fd.h>
27 #include <base/time/time.h>
28 
29 #include "update_engine/client_library/include/update_engine/update_status.h"
30 #include "update_engine/common/action_processor.h"
31 #include "update_engine/common/boot_control_interface.h"
32 #include "update_engine/common/clock.h"
33 #include "update_engine/common/hardware_interface.h"
34 #include "update_engine/common/prefs_interface.h"
35 #include "update_engine/daemon_state_interface.h"
36 #include "update_engine/metrics_reporter_interface.h"
37 #include "update_engine/metrics_utils.h"
38 #include "update_engine/network_selector_interface.h"
39 #include "update_engine/payload_consumer/download_action.h"
40 #include "update_engine/payload_consumer/postinstall_runner_action.h"
41 #include "update_engine/service_delegate_android_interface.h"
42 #include "update_engine/service_observer_interface.h"
43 
44 namespace chromeos_update_engine {
45 
46 class UpdateAttempterAndroid
47     : public ServiceDelegateAndroidInterface,
48       public ActionProcessorDelegate,
49       public DownloadActionDelegate,
50       public PostinstallRunnerAction::DelegateInterface,
51       public CleanupPreviousUpdateActionDelegateInterface {
52  public:
53   using UpdateStatus = update_engine::UpdateStatus;
54 
55   UpdateAttempterAndroid(DaemonStateInterface* daemon_state,
56                          PrefsInterface* prefs,
57                          BootControlInterface* boot_control_,
58                          HardwareInterface* hardware_);
59   ~UpdateAttempterAndroid() override;
60 
61   // Further initialization to be done post construction.
62   void Init();
63 
64   // ServiceDelegateAndroidInterface overrides.
65   bool ApplyPayload(const std::string& payload_url,
66                     int64_t payload_offset,
67                     int64_t payload_size,
68                     const std::vector<std::string>& key_value_pair_headers,
69                     brillo::ErrorPtr* error) override;
70   bool ApplyPayload(int fd,
71                     int64_t payload_offset,
72                     int64_t payload_size,
73                     const std::vector<std::string>& key_value_pair_headers,
74                     brillo::ErrorPtr* error) override;
75   bool SuspendUpdate(brillo::ErrorPtr* error) override;
76   bool ResumeUpdate(brillo::ErrorPtr* error) override;
77   bool CancelUpdate(brillo::ErrorPtr* error) override;
78   bool ResetStatus(brillo::ErrorPtr* error) override;
79   bool VerifyPayloadApplicable(const std::string& metadata_filename,
80                                brillo::ErrorPtr* error) override;
81   uint64_t AllocateSpaceForPayload(
82       const std::string& metadata_filename,
83       const std::vector<std::string>& key_value_pair_headers,
84       brillo::ErrorPtr* error) override;
85   void CleanupSuccessfulUpdate(
86       std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface> callback,
87       brillo::ErrorPtr* error) override;
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   // DownloadActionDelegate overrides.
98   void BytesReceived(uint64_t bytes_progressed,
99                      uint64_t bytes_received,
100                      uint64_t total) override;
101   bool ShouldCancel(ErrorCode* cancel_reason) override;
102   void DownloadComplete() override;
103 
104   // PostinstallRunnerAction::DelegateInterface
105   void ProgressUpdate(double progress) override;
106 
107   // CleanupPreviousUpdateActionDelegateInterface
108   void OnCleanupProgressUpdate(double progress) override;
109 
110  private:
111   friend class UpdateAttempterAndroidTest;
112 
113   // Schedules an event loop callback to start the action processor. This is
114   // scheduled asynchronously to unblock the event loop.
115   void ScheduleProcessingStart();
116 
117   // Notifies an update request completed with the given error |code| to all
118   // observers.
119   void TerminateUpdateAndNotify(ErrorCode error_code);
120 
121   // Sets the status to the given |status| and notifies a status update to
122   // all observers.
123   void SetStatusAndNotify(UpdateStatus status);
124 
125   // Helper method to construct the sequence of actions to be performed for
126   // applying an update using a given HttpFetcher. The ownership of |fetcher| is
127   // passed to this function.
128   void BuildUpdateActions(HttpFetcher* fetcher);
129 
130   // Writes to the processing completed marker. Does nothing if
131   // |update_completed_marker_| is empty.
132   bool WriteUpdateCompletedMarker();
133 
134   // Returns whether an update was completed in the current boot.
135   bool UpdateCompletedOnThisBoot();
136 
137   // Prefs to use for metrics report
138   // |kPrefsPayloadAttemptNumber|: number of update attempts for the current
139   // payload_id.
140   // |KprefsNumReboots|: number of reboots when applying the current update.
141   // |kPrefsSystemUpdatedMarker|: end timestamp of the last successful update.
142   // |kPrefsUpdateTimestampStart|: start timestamp in monotonic time of the
143   // current update.
144   // |kPrefsUpdateBootTimestampStart|: start timestamp in boot time of
145   // the current update.
146   // |kPrefsCurrentBytesDownloaded|: number of bytes downloaded for the current
147   // payload_id.
148   // |kPrefsTotalBytesDownloaded|: number of bytes downloaded in total since
149   // the last successful update.
150 
151   // Metrics report function to call:
152   //   |ReportUpdateAttemptMetrics|
153   //   |ReportSuccessfulUpdateMetrics|
154   // Prefs to update:
155   //   |kPrefsSystemUpdatedMarker|
156   void CollectAndReportUpdateMetricsOnUpdateFinished(ErrorCode error_code);
157 
158   // Metrics report function to call:
159   //   |ReportAbnormallyTerminatedUpdateAttemptMetrics|
160   //   |ReportTimeToRebootMetrics|
161   // Prefs to update:
162   //   |kPrefsBootId|, |kPrefsPreviousVersion|
163   void UpdatePrefsAndReportUpdateMetricsOnReboot();
164 
165   // Prefs to update:
166   //   |kPrefsPayloadAttemptNumber|, |kPrefsUpdateTimestampStart|,
167   //   |kPrefsUpdateBootTimestampStart|
168   void UpdatePrefsOnUpdateStart(bool is_resume);
169 
170   // Prefs to delete:
171   //   |kPrefsNumReboots|, |kPrefsCurrentBytesDownloaded|
172   //   |kPrefsSystemUpdatedMarker|, |kPrefsUpdateTimestampStart|,
173   //   |kPrefsUpdateBootTimestampStart|
174   void ClearMetricsPrefs();
175 
176   // Return source and target slots for update.
177   BootControlInterface::Slot GetCurrentSlot() const;
178   BootControlInterface::Slot GetTargetSlot() const;
179 
180   // Helper of public VerifyPayloadApplicable. Return the parsed manifest in
181   // |manifest|.
182   static bool VerifyPayloadParseManifest(const std::string& metadata_filename,
183                                          DeltaArchiveManifest* manifest,
184                                          brillo::ErrorPtr* error);
185 
186   // Enqueue and run a CleanupPreviousUpdateAction.
187   void ScheduleCleanupPreviousUpdate();
188 
189   // Notify and clear |cleanup_previous_update_callbacks_|.
190   void NotifyCleanupPreviousUpdateCallbacksAndClear();
191 
192   // Remove |callback| from |cleanup_previous_update_callbacks_|.
193   void RemoveCleanupPreviousUpdateCallback(
194       CleanupSuccessfulUpdateCallbackInterface* callback);
195 
196   DaemonStateInterface* daemon_state_;
197 
198   // DaemonStateAndroid pointers.
199   PrefsInterface* prefs_;
200   BootControlInterface* boot_control_;
201   HardwareInterface* hardware_;
202 
203   // Last status notification timestamp used for throttling. Use monotonic
204   // TimeTicks to ensure that notifications are sent even if the system clock is
205   // set back in the middle of an update.
206   base::TimeTicks last_notify_time_;
207 
208   // Only direct proxy supported.
209   DirectProxyResolver proxy_resolver_;
210 
211   // The processor for running Actions.
212   std::unique_ptr<ActionProcessor> processor_;
213 
214   // The InstallPlan used during the ongoing update.
215   InstallPlan install_plan_;
216 
217   // For status:
218   UpdateStatus status_{UpdateStatus::IDLE};
219   double download_progress_{0.0};
220 
221   // The offset in the payload file where the CrAU part starts.
222   int64_t base_offset_{0};
223 
224   // Helper class to select the network to use during the update.
225   std::unique_ptr<NetworkSelectorInterface> network_selector_;
226 
227   std::unique_ptr<ClockInterface> clock_;
228 
229   std::unique_ptr<MetricsReporterInterface> metrics_reporter_;
230 
231   ::android::base::unique_fd payload_fd_;
232 
233   std::vector<std::unique_ptr<CleanupSuccessfulUpdateCallbackInterface>>
234       cleanup_previous_update_callbacks_;
235   // Result of previous CleanupPreviousUpdateAction. Nullopt If
236   // CleanupPreviousUpdateAction has not been executed.
237   std::optional<ErrorCode> cleanup_previous_update_code_{std::nullopt};
238 
239   DISALLOW_COPY_AND_ASSIGN(UpdateAttempterAndroid);
240 };
241 
242 }  // namespace chromeos_update_engine
243 
244 #endif  // UPDATE_ENGINE_UPDATE_ATTEMPTER_ANDROID_H_
245