update_engine: Make SystemState accessible from everywhere

SystemState is supposed to be a global context and is used lamost
everywhere. So instead of passing it to functions and keeping multiple
pointers to it, its better to do what we did in dlcservice and make it a
singleton class with a getter that can be get from everywhere.

BUG=b:171829801
TEST=unittests

Change-Id: I3b2de9394b7769b3911195ca52d61dbe49afd4dd
Reviewed-on: https://chromium-review.googlesource.com/c/aosp/platform/system/update_engine/+/2521792
Commit-Queue: Amin Hassani <ahassani@chromium.org>
Tested-by: Amin Hassani <ahassani@chromium.org>
Reviewed-by: Jae Hoon Kim <kimjae@chromium.org>
diff --git a/cros/payload_state.cc b/cros/payload_state.cc
index d2e6851..d7de6e6 100644
--- a/cros/payload_state.cc
+++ b/cros/payload_state.cc
@@ -78,11 +78,10 @@
     total_bytes_downloaded_[i] = current_bytes_downloaded_[i] = 0;
 }
 
-bool PayloadState::Initialize(SystemState* system_state) {
-  system_state_ = system_state;
-  prefs_ = system_state_->prefs();
-  powerwash_safe_prefs_ = system_state_->powerwash_safe_prefs();
-  excluder_ = system_state_->update_attempter()->GetExcluder();
+bool PayloadState::Initialize() {
+  prefs_ = SystemState::Get()->prefs();
+  powerwash_safe_prefs_ = SystemState::Get()->powerwash_safe_prefs();
+  excluder_ = SystemState::Get()->update_attempter()->GetExcluder();
   LoadResponseSignature();
   LoadPayloadAttemptNumber();
   LoadFullPayloadAttemptNumber();
@@ -197,7 +196,7 @@
 
   attempt_type_ = attempt_type;
 
-  ClockInterface* clock = system_state_->clock();
+  ClockInterface* clock = SystemState::Get()->clock();
   attempt_start_time_boot_ = clock->GetBootTime();
   attempt_start_time_monotonic_ = clock->GetMonotonicTime();
   attempt_num_bytes_downloaded_ = 0;
@@ -206,7 +205,7 @@
   ConnectionType network_connection_type;
   ConnectionTethering tethering;
   ConnectionManagerInterface* connection_manager =
-      system_state_->connection_manager();
+      SystemState::Get()->connection_manager();
   if (!connection_manager->GetConnectionProperties(&network_connection_type,
                                                    &tethering)) {
     LOG(ERROR) << "Failed to determine connection type.";
@@ -236,7 +235,7 @@
 void PayloadState::UpdateSucceeded() {
   // Send the relevant metrics that are tracked in this class to UMA.
   CalculateUpdateDurationUptime();
-  SetUpdateTimestampEnd(system_state_->clock()->GetWallclockTime());
+  SetUpdateTimestampEnd(SystemState::Get()->clock()->GetWallclockTime());
 
   switch (attempt_type_) {
     case AttemptType::kUpdate:
@@ -246,7 +245,7 @@
       break;
 
     case AttemptType::kRollback:
-      system_state_->metrics_reporter()->ReportRollbackMetrics(
+      SystemState::Get()->metrics_reporter()->ReportRollbackMetrics(
           metrics::RollbackResult::kSuccess);
       break;
   }
@@ -256,7 +255,7 @@
   SetNumResponsesSeen(0);
   SetPayloadIndex(0);
 
-  metrics_utils::SetSystemUpdatedMarker(system_state_->clock(), prefs_);
+  metrics_utils::SetSystemUpdatedMarker(SystemState::Get()->clock(), prefs_);
 }
 
 void PayloadState::UpdateFailed(ErrorCode error) {
@@ -279,7 +278,7 @@
       break;
 
     case AttemptType::kRollback:
-      system_state_->metrics_reporter()->ReportRollbackMetrics(
+      SystemState::Get()->metrics_reporter()->ReportRollbackMetrics(
           metrics::RollbackResult::kFailed);
       break;
   }
@@ -409,7 +408,7 @@
               << "will happen from local peer (via p2p).";
     return false;
   }
-  if (system_state_->request_params()->interactive()) {
+  if (SystemState::Get()->request_params()->interactive()) {
     LOG(INFO) << "Payload backoff disabled for interactive update checks.";
     return false;
   }
@@ -425,7 +424,7 @@
     }
   }
 
-  if (!system_state_->hardware()->IsOfficialBuild() &&
+  if (!SystemState::Get()->hardware()->IsOfficialBuild() &&
       !prefs_->Exists(kPrefsNoIgnoreBackoff)) {
     // Backoffs are needed only for official builds. We do not want any delays
     // or update failures due to backoffs during testing or development. Unless
@@ -454,7 +453,7 @@
 }
 
 void PayloadState::Rollback() {
-  SetRollbackVersion(system_state_->request_params()->app_version());
+  SetRollbackVersion(SystemState::Get()->request_params()->app_version());
   AttemptStarted(AttemptType::kRollback);
 }
 
@@ -612,7 +611,7 @@
       return kPayloadTypeDelta;
     }
   }
-  OmahaRequestParams* params = system_state_->request_params();
+  OmahaRequestParams* params = SystemState::Get()->request_params();
   if (params->delta_okay()) {
     return kPayloadTypeFull;
   }
@@ -629,7 +628,7 @@
 
   int64_t payload_bytes_downloaded = attempt_num_bytes_downloaded_;
 
-  ClockInterface* clock = system_state_->clock();
+  ClockInterface* clock = SystemState::Get()->clock();
   TimeDelta duration = clock->GetBootTime() - attempt_start_time_boot_;
   TimeDelta duration_uptime =
       clock->GetMonotonicTime() - attempt_start_time_monotonic_;
@@ -680,8 +679,7 @@
       break;
   }
 
-  system_state_->metrics_reporter()->ReportUpdateAttemptMetrics(
-      system_state_,
+  SystemState::Get()->metrics_reporter()->ReportUpdateAttemptMetrics(
       attempt_number,
       payload_type,
       duration,
@@ -690,7 +688,7 @@
       attempt_result,
       internal_error_code);
 
-  system_state_->metrics_reporter()->ReportUpdateAttemptDownloadMetrics(
+  SystemState::Get()->metrics_reporter()->ReportUpdateAttemptDownloadMetrics(
       payload_bytes_downloaded,
       payload_download_speed_bps,
       download_source,
@@ -720,7 +718,8 @@
   if (!attempt_in_progress)
     return;
 
-  system_state_->metrics_reporter()
+  SystemState::Get()
+      ->metrics_reporter()
       ->ReportAbnormallyTerminatedUpdateAttemptMetrics();
 
   ClearPersistedAttemptMetrics();
@@ -784,7 +783,7 @@
 
   int updates_abandoned_count = num_responses_seen_ - 1;
 
-  system_state_->metrics_reporter()->ReportSuccessfulUpdateMetrics(
+  SystemState::Get()->metrics_reporter()->ReportSuccessfulUpdateMetrics(
       attempt_count,
       updates_abandoned_count,
       payload_type,
@@ -800,7 +799,7 @@
 void PayloadState::UpdateNumReboots() {
   // We only update the reboot count when the system has been detected to have
   // been rebooted.
-  if (!system_state_->system_rebooted()) {
+  if (!SystemState::Get()->system_rebooted()) {
     return;
   }
 
@@ -820,7 +819,7 @@
   SetUrlFailureCount(0);
   SetUrlSwitchCount(0);
   UpdateBackoffExpiryTime();  // This will reset the backoff expiry time.
-  SetUpdateTimestampStart(system_state_->clock()->GetWallclockTime());
+  SetUpdateTimestampStart(SystemState::Get()->clock()->GetWallclockTime());
   SetUpdateTimestampEnd(Time());  // Set to null time
   SetUpdateDurationUptime(TimeDelta::FromSeconds(0));
   ResetDownloadSourcesOnNewUpdate();
@@ -1040,7 +1039,7 @@
 
 TimeDelta PayloadState::GetUpdateDuration() {
   Time end_time = update_timestamp_end_.is_null()
-                      ? system_state_->clock()->GetWallclockTime()
+                      ? SystemState::Get()->clock()->GetWallclockTime()
                       : update_timestamp_end_;
   return end_time - update_timestamp_start_;
 }
@@ -1051,7 +1050,7 @@
 
   CHECK(prefs_);
 
-  Time now = system_state_->clock()->GetWallclockTime();
+  Time now = SystemState::Get()->clock()->GetWallclockTime();
 
   if (!prefs_->Exists(kPrefsUpdateTimestampStart)) {
     // The preference missing is not unexpected - in that case, just
@@ -1180,12 +1179,12 @@
 }
 
 void PayloadState::SetUpdateDurationUptime(const TimeDelta& value) {
-  Time now = system_state_->clock()->GetMonotonicTime();
+  Time now = SystemState::Get()->clock()->GetMonotonicTime();
   SetUpdateDurationUptimeExtended(value, now, true);
 }
 
 void PayloadState::CalculateUpdateDurationUptime() {
-  Time now = system_state_->clock()->GetMonotonicTime();
+  Time now = SystemState::Get()->clock()->GetMonotonicTime();
   TimeDelta uptime_since_last_update = now - update_duration_uptime_timestamp_;
 
   if (uptime_since_last_update > TimeDelta::FromSeconds(kUptimeResolution)) {
@@ -1259,8 +1258,8 @@
 void PayloadState::ComputeCandidateUrls() {
   bool http_url_ok = true;
 
-  if (system_state_->hardware()->IsOfficialBuild()) {
-    const policy::DevicePolicy* policy = system_state_->device_policy();
+  if (SystemState::Get()->hardware()->IsOfficialBuild()) {
+    const policy::DevicePolicy* policy = SystemState::Get()->device_policy();
     if (policy && policy->GetHttpDownloadsEnabled(&http_url_ok) && !http_url_ok)
       LOG(INFO) << "Downloads via HTTP Url are not enabled by device policy";
   } else {
@@ -1293,12 +1292,14 @@
 
   // Avoid the UpdateEngineStarted actions if this is not the first time we
   // run the update engine since reboot.
-  if (!system_state_->system_rebooted())
+  if (!SystemState::Get()->system_rebooted())
     return;
 
   // Report time_to_reboot if we booted into a new update.
   metrics_utils::LoadAndReportTimeToReboot(
-      system_state_->metrics_reporter(), prefs_, system_state_->clock());
+      SystemState::Get()->metrics_reporter(),
+      prefs_,
+      SystemState::Get()->clock());
   prefs_->Delete(kPrefsSystemUpdatedMarker);
 
   // Check if it is needed to send metrics about a failed reboot into a new
@@ -1323,7 +1324,8 @@
     // since we successfully booted the new update in that case. If the boot
     // failed, we will read this value from the same version, so it will always
     // be compatible.
-    if (installed_from == system_state_->boot_control()->GetCurrentSlot()) {
+    if (installed_from ==
+        SystemState::Get()->boot_control()->GetCurrentSlot()) {
       // A reboot was pending, but the chromebook is again in the same
       // BootDevice where the update was installed from.
       int64_t target_attempt;
@@ -1334,7 +1336,7 @@
       }
 
       // Report the UMA metric of the current boot failure.
-      system_state_->metrics_reporter()->ReportFailedUpdateCount(
+      SystemState::Get()->metrics_reporter()->ReportFailedUpdateCount(
           target_attempt);
     } else {
       prefs_->Delete(kPrefsTargetVersionAttempt);
@@ -1365,7 +1367,7 @@
   prefs_->SetInt64(kPrefsTargetVersionAttempt, target_attempt + 1);
 
   prefs_->SetInt64(kPrefsTargetVersionInstalledFrom,
-                   system_state_->boot_control()->GetCurrentSlot());
+                   SystemState::Get()->boot_control()->GetCurrentSlot());
 }
 
 void PayloadState::ResetUpdateStatus() {
@@ -1419,7 +1421,8 @@
   CHECK(prefs_);
   // Set timestamp, if it hasn't been set already
   if (p2p_first_attempt_timestamp_.is_null()) {
-    SetP2PFirstAttemptTimestamp(system_state_->clock()->GetWallclockTime());
+    SetP2PFirstAttemptTimestamp(
+        SystemState::Get()->clock()->GetWallclockTime());
   }
   // Increase number of attempts
   SetP2PNumAttempts(GetP2PNumAttempts() + 1);
@@ -1434,7 +1437,7 @@
   }
 
   if (!p2p_first_attempt_timestamp_.is_null()) {
-    Time now = system_state_->clock()->GetWallclockTime();
+    Time now = SystemState::Get()->clock()->GetWallclockTime();
     TimeDelta time_spent_attempting_p2p = now - p2p_first_attempt_timestamp_;
     if (time_spent_attempting_p2p.InSeconds() < 0) {
       LOG(ERROR) << "Time spent attempting p2p is negative"