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/Android.bp b/Android.bp
index 8f465f6..e5f8c31 100644
--- a/Android.bp
+++ b/Android.bp
@@ -160,7 +160,6 @@
"common/subprocess.cc",
"common/terminator.cc",
"common/utils.cc",
- "download_action.cc",
"payload_consumer/bzip_extent_writer.cc",
"payload_consumer/cached_file_descriptor.cc",
"payload_consumer/certificate_parser_android.cc",
@@ -297,6 +296,7 @@
srcs: [
":libupdate_engine_aidl",
+ "common/system_state.cc",
"aosp/binder_service_android.cc",
"aosp/binder_service_stable_android.cc",
"aosp/daemon_android.cc",
@@ -306,6 +306,7 @@
"aosp/network_selector_android.cc",
"aosp/update_attempter_android.cc",
"certificate_checker.cc",
+ "download_action.cc",
"libcurl_http_fetcher.cc",
"metrics_utils.cc",
"update_boot_flags_action.cc",
@@ -360,6 +361,8 @@
"aosp/update_attempter_android.cc",
"common/metrics_reporter_stub.cc",
"common/network_selector_stub.cc",
+ "common/system_state.cc",
+ "download_action.cc",
"metrics_utils.cc",
"update_boot_flags_action.cc",
"update_status_utils.cc",
@@ -491,6 +494,8 @@
host_supported: true,
srcs: [
+ "common/system_state.cc",
+ "download_action.cc",
"payload_generator/ab_generator.cc",
"payload_generator/annotated_operation.cc",
"payload_generator/blob_file_writer.cc",
diff --git a/BUILD.gn b/BUILD.gn
index 1f5dc7f..5ac0a3f 100644
--- a/BUILD.gn
+++ b/BUILD.gn
@@ -146,7 +146,6 @@
"common/terminator.cc",
"common/utils.cc",
"cros/platform_constants_chromeos.cc",
- "download_action.cc",
"payload_consumer/bzip_extent_writer.cc",
"payload_consumer/cached_file_descriptor.cc",
"payload_consumer/certificate_parser_stub.cc",
@@ -194,6 +193,7 @@
sources = [
"certificate_checker.cc",
"common/connection_utils.cc",
+ "common/system_state.cc",
"cros/boot_control_chromeos.cc",
"cros/common_service.cc",
"cros/connection_manager.cc",
@@ -216,6 +216,7 @@
"cros/requisition_util.cc",
"cros/shill_proxy.cc",
"cros/update_attempter.cc",
+ "download_action.cc",
"libcurl_http_fetcher.cc",
"metrics_utils.cc",
"update_boot_flags_action.cc",
@@ -331,6 +332,9 @@
static_library("libpayload_generator") {
sources = [
"common/file_fetcher.cc",
+ "common/system_state.cc",
+ "cros/real_system_state.cc",
+ "download_action.cc",
"payload_generator/ab_generator.cc",
"payload_generator/annotated_operation.cc",
"payload_generator/blob_file_writer.cc",
diff --git a/aosp/metrics_reporter_android.cc b/aosp/metrics_reporter_android.cc
index ea3bb6d..22ebf0d 100644
--- a/aosp/metrics_reporter_android.cc
+++ b/aosp/metrics_reporter_android.cc
@@ -61,7 +61,6 @@
} // namespace metrics
void MetricsReporterAndroid::ReportUpdateAttemptMetrics(
- SystemState* /* system_state */,
int attempt_number,
PayloadType payload_type,
base::TimeDelta duration,
diff --git a/aosp/metrics_reporter_android.h b/aosp/metrics_reporter_android.h
index 4a173bf..729542e 100644
--- a/aosp/metrics_reporter_android.h
+++ b/aosp/metrics_reporter_android.h
@@ -39,13 +39,11 @@
void ReportDailyMetrics(base::TimeDelta os_age) override {}
void ReportUpdateCheckMetrics(
- SystemState* system_state,
metrics::CheckResult result,
metrics::CheckReaction reaction,
metrics::DownloadErrorCode download_error_code) override {}
- void ReportUpdateAttemptMetrics(SystemState* system_state,
- int attempt_number,
+ void ReportUpdateAttemptMetrics(int attempt_number,
PayloadType payload_type,
base::TimeDelta duration,
base::TimeDelta duration_uptime,
diff --git a/aosp/update_attempter_android.cc b/aosp/update_attempter_android.cc
index 57430fe..d48293a 100644
--- a/aosp/update_attempter_android.cc
+++ b/aosp/update_attempter_android.cc
@@ -733,7 +733,6 @@
std::make_unique<DownloadAction>(prefs_,
boot_control_,
hardware_,
- nullptr, // system_state, not used.
fetcher, // passes ownership
true /* interactive */);
download_action->set_delegate(this);
@@ -804,7 +803,6 @@
TimeDelta duration_uptime = clock_->GetMonotonicTime() - monotonic_time_start;
metrics_reporter_->ReportUpdateAttemptMetrics(
- nullptr, // system_state
static_cast<int>(attempt_number),
payload_type,
duration,
diff --git a/aosp/update_attempter_android_unittest.cc b/aosp/update_attempter_android_unittest.cc
index bb44450..fc30268 100644
--- a/aosp/update_attempter_android_unittest.cc
+++ b/aosp/update_attempter_android_unittest.cc
@@ -138,8 +138,7 @@
TimeDelta duration_uptime = up_time - Time::FromInternalValue(12345);
EXPECT_CALL(
*metrics_reporter_,
- ReportUpdateAttemptMetrics(_,
- 2,
+ ReportUpdateAttemptMetrics(2,
_,
duration,
duration_uptime,
diff --git a/common/download_action.h b/common/download_action.h
index c167c2d..18e5853 100644
--- a/common/download_action.h
+++ b/common/download_action.h
@@ -28,7 +28,6 @@
#include "update_engine/common/boot_control_interface.h"
#include "update_engine/common/http_fetcher.h"
#include "update_engine/common/multi_range_http_fetcher.h"
-#include "update_engine/common/system_state.h"
#include "update_engine/payload_consumer/delta_performer.h"
#include "update_engine/payload_consumer/install_plan.h"
@@ -71,12 +70,11 @@
// Takes ownership of the passed in HttpFetcher. Useful for testing.
// A good calling pattern is:
- // DownloadAction(prefs, boot_contol, hardware, system_state,
+ // DownloadAction(prefs, boot_contol, hardware,
// new WhateverHttpFetcher, false);
DownloadAction(PrefsInterface* prefs,
BootControlInterface* boot_control,
HardwareInterface* hardware,
- SystemState* system_state,
HttpFetcher* http_fetcher,
bool interactive);
~DownloadAction() override;
@@ -141,14 +139,11 @@
// Pointer to the current payload in install_plan_.payloads.
InstallPlan::Payload* payload_{nullptr};
- // SystemState required pointers.
+ // Required pointers.
PrefsInterface* prefs_;
BootControlInterface* boot_control_;
HardwareInterface* hardware_;
- // Global context for the system.
- SystemState* system_state_;
-
// Pointer to the MultiRangeHttpFetcher that does the http work.
std::unique_ptr<MultiRangeHttpFetcher> http_fetcher_;
diff --git a/common/metrics_reporter_interface.h b/common/metrics_reporter_interface.h
index d7c5347..08636e3 100644
--- a/common/metrics_reporter_interface.h
+++ b/common/metrics_reporter_interface.h
@@ -25,19 +25,12 @@
#include "update_engine/common/constants.h"
#include "update_engine/common/error_code.h"
#include "update_engine/common/metrics_constants.h"
-#include "update_engine/common/system_state.h"
namespace chromeos_update_engine {
enum class ServerToCheck;
enum class CertificateCheckResult;
-namespace metrics {
-
-std::unique_ptr<MetricsReporterInterface> CreateMetricsReporter();
-
-} // namespace metrics
-
class MetricsReporterInterface {
public:
virtual ~MetricsReporterInterface() = default;
@@ -92,7 +85,6 @@
// if it's set, |kMetricCheckRollbackTargetVersion| reports the same, but only
// if rollback is also allowed using enterprise policy.
virtual void ReportUpdateCheckMetrics(
- SystemState* system_state,
metrics::CheckResult result,
metrics::CheckReaction reaction,
metrics::DownloadErrorCode download_error_code) = 0;
@@ -120,8 +112,7 @@
// |kMetricAttemptTimeSinceLastAttemptUptimeMinutes| metrics are
// automatically calculated and reported by maintaining persistent and
// process-local state variables.
- virtual void ReportUpdateAttemptMetrics(SystemState* system_state,
- int attempt_number,
+ virtual void ReportUpdateAttemptMetrics(int attempt_number,
PayloadType payload_type,
base::TimeDelta duration,
base::TimeDelta duration_uptime,
@@ -242,6 +233,12 @@
bool has_time_restriction_policy, int time_to_update_days) = 0;
};
+namespace metrics {
+
+std::unique_ptr<MetricsReporterInterface> CreateMetricsReporter();
+
+} // namespace metrics
+
} // namespace chromeos_update_engine
#endif // UPDATE_ENGINE_COMMON_METRICS_REPORTER_INTERFACE_H_
diff --git a/common/metrics_reporter_stub.h b/common/metrics_reporter_stub.h
index 1470aaa..80cf469 100644
--- a/common/metrics_reporter_stub.h
+++ b/common/metrics_reporter_stub.h
@@ -39,13 +39,11 @@
void ReportDailyMetrics(base::TimeDelta os_age) override {}
void ReportUpdateCheckMetrics(
- SystemState* system_state,
metrics::CheckResult result,
metrics::CheckReaction reaction,
metrics::DownloadErrorCode download_error_code) override {}
- void ReportUpdateAttemptMetrics(SystemState* system_state,
- int attempt_number,
+ void ReportUpdateAttemptMetrics(int attempt_number,
PayloadType payload_type,
base::TimeDelta duration,
base::TimeDelta duration_uptime,
diff --git a/common/mock_metrics_reporter.h b/common/mock_metrics_reporter.h
index 922d1ee..1bb1e84 100644
--- a/common/mock_metrics_reporter.h
+++ b/common/mock_metrics_reporter.h
@@ -36,15 +36,13 @@
MOCK_METHOD1(ReportDailyMetrics, void(base::TimeDelta os_age));
- MOCK_METHOD4(ReportUpdateCheckMetrics,
- void(SystemState* system_state,
- metrics::CheckResult result,
+ MOCK_METHOD3(ReportUpdateCheckMetrics,
+ void(metrics::CheckResult result,
metrics::CheckReaction reaction,
metrics::DownloadErrorCode download_error_code));
- MOCK_METHOD8(ReportUpdateAttemptMetrics,
- void(SystemState* system_state,
- int attempt_number,
+ MOCK_METHOD7(ReportUpdateAttemptMetrics,
+ void(int attempt_number,
PayloadType payload_type,
base::TimeDelta duration,
base::TimeDelta duration_uptime,
diff --git a/common/system_state.cc b/common/system_state.cc
new file mode 100644
index 0000000..40bf760
--- /dev/null
+++ b/common/system_state.cc
@@ -0,0 +1,23 @@
+//
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include "update_engine/common/system_state.h"
+
+namespace chromeos_update_engine {
+
+std::unique_ptr<SystemState> SystemState::g_instance_;
+
+} // namespace chromeos_update_engine
diff --git a/common/system_state.h b/common/system_state.h
index 7a67046..dc40d36 100644
--- a/common/system_state.h
+++ b/common/system_state.h
@@ -17,6 +17,10 @@
#ifndef UPDATE_ENGINE_COMMON_SYSTEM_STATE_H_
#define UPDATE_ENGINE_COMMON_SYSTEM_STATE_H_
+#include <memory>
+
+#include <base/logging.h>
+
namespace chromeos_update_manager {
class UpdateManager;
@@ -51,13 +55,14 @@
// the current state of the system, high-level objects whose lifetime is same
// as main, system interfaces, etc.
// Carved out separately so it can be mocked for unit tests.
-// Currently it has only one method, but we should start migrating other
-// methods to use this as and when needed to unit test them.
-// TODO(jaysri): Consider renaming this to something like GlobalContext.
class SystemState {
public:
- // Destructs this object.
- virtual ~SystemState() {}
+ virtual ~SystemState() = default;
+
+ static SystemState* Get() {
+ CHECK(g_instance_);
+ return g_instance_.get();
+ }
// Sets or gets the latest device policy.
virtual void set_device_policy(const policy::DevicePolicy* device_policy) = 0;
@@ -113,6 +118,9 @@
// Returns a pointer to the DlcServiceInterface singleton.
virtual DlcServiceInterface* dlcservice() = 0;
+
+ protected:
+ static std::unique_ptr<SystemState> g_instance_;
};
} // namespace chromeos_update_engine
diff --git a/cros/common_service.cc b/cros/common_service.cc
index aecad8b..0318999 100644
--- a/cros/common_service.cc
+++ b/cros/common_service.cc
@@ -29,6 +29,7 @@
#include "update_engine/common/clock_interface.h"
#include "update_engine/common/hardware_interface.h"
#include "update_engine/common/prefs.h"
+#include "update_engine/common/system_state.h"
#include "update_engine/common/utils.h"
#include "update_engine/cros/connection_manager_interface.h"
#include "update_engine/cros/omaha_request_params.h"
@@ -66,8 +67,7 @@
const char* const UpdateEngineService::kErrorFailed =
"org.chromium.UpdateEngine.Error.Failed";
-UpdateEngineService::UpdateEngineService(SystemState* system_state)
- : system_state_(system_state) {}
+UpdateEngineService::UpdateEngineService() = default;
// org::chromium::UpdateEngineInterfaceInterface methods implementation.
@@ -79,7 +79,7 @@
<< "RestrictDownload="
<< ((flags & UpdateAttemptFlags::kFlagRestrictDownload) ? "yes"
: "no");
- system_state_->update_attempter()->SetUpdateAttemptFlags(flags);
+ SystemState::Get()->update_attempter()->SetUpdateAttemptFlags(flags);
return true;
}
@@ -98,7 +98,7 @@
<< "interactive=" << (interactive ? "yes " : "no ")
<< "RestrictDownload=" << (restrict_downloads ? "yes " : "no ");
- *out_result = system_state_->update_attempter()->CheckForUpdate(
+ *out_result = SystemState::Get()->update_attempter()->CheckForUpdate(
in_app_version, in_omaha_url, flags);
return true;
}
@@ -106,7 +106,8 @@
bool UpdateEngineService::AttemptInstall(brillo::ErrorPtr* error,
const string& omaha_url,
const vector<string>& dlc_ids) {
- if (!system_state_->update_attempter()->CheckForInstall(dlc_ids, omaha_url)) {
+ if (!SystemState::Get()->update_attempter()->CheckForInstall(dlc_ids,
+ omaha_url)) {
// TODO(xiaochu): support more detailed error messages.
LogAndSetError(error, FROM_HERE, "Could not schedule install operation.");
return false;
@@ -117,7 +118,7 @@
bool UpdateEngineService::AttemptRollback(ErrorPtr* error, bool in_powerwash) {
LOG(INFO) << "Attempting rollback to non-active partitions.";
- if (!system_state_->update_attempter()->Rollback(in_powerwash)) {
+ if (!SystemState::Get()->update_attempter()->Rollback(in_powerwash)) {
// TODO(dgarrett): Give a more specific error code/reason.
LogAndSetError(error, FROM_HERE, "Rollback attempt failed.");
return false;
@@ -127,14 +128,14 @@
bool UpdateEngineService::CanRollback(ErrorPtr* /* error */,
bool* out_can_rollback) {
- bool can_rollback = system_state_->update_attempter()->CanRollback();
+ bool can_rollback = SystemState::Get()->update_attempter()->CanRollback();
LOG(INFO) << "Checking to see if we can rollback . Result: " << can_rollback;
*out_can_rollback = can_rollback;
return true;
}
bool UpdateEngineService::ResetStatus(ErrorPtr* error) {
- if (!system_state_->update_attempter()->ResetStatus()) {
+ if (!SystemState::Get()->update_attempter()->ResetStatus()) {
// TODO(dgarrett): Give a more specific error code/reason.
LogAndSetError(error, FROM_HERE, "ResetStatus failed.");
return false;
@@ -145,8 +146,8 @@
bool UpdateEngineService::SetDlcActiveValue(brillo::ErrorPtr* error,
bool is_active,
const string& dlc_id) {
- if (!system_state_->update_attempter()->SetDlcActiveValue(is_active,
- dlc_id)) {
+ if (!SystemState::Get()->update_attempter()->SetDlcActiveValue(is_active,
+ dlc_id)) {
LogAndSetError(error, FROM_HERE, "SetDlcActiveValue failed.");
return false;
}
@@ -155,7 +156,7 @@
bool UpdateEngineService::GetStatus(ErrorPtr* error,
UpdateEngineStatus* out_status) {
- if (!system_state_->update_attempter()->GetStatus(out_status)) {
+ if (!SystemState::Get()->update_attempter()->GetStatus(out_status)) {
LogAndSetError(error, FROM_HERE, "GetStatus failed.");
return false;
}
@@ -163,7 +164,7 @@
}
bool UpdateEngineService::RebootIfNeeded(ErrorPtr* error) {
- if (!system_state_->update_attempter()->RebootIfNeeded()) {
+ if (!SystemState::Get()->update_attempter()->RebootIfNeeded()) {
// TODO(dgarrett): Give a more specific error code/reason.
LogAndSetError(error, FROM_HERE, "Reboot not needed, or attempt failed.");
return false;
@@ -174,15 +175,16 @@
bool UpdateEngineService::SetChannel(ErrorPtr* error,
const string& in_target_channel,
bool in_is_powerwash_allowed) {
- const policy::DevicePolicy* device_policy = system_state_->device_policy();
+ const policy::DevicePolicy* device_policy =
+ SystemState::Get()->device_policy();
// The device_policy is loaded in a lazy way before an update check. Load it
// now from the libbrillo cache if it wasn't already loaded.
if (!device_policy) {
- UpdateAttempter* update_attempter = system_state_->update_attempter();
+ UpdateAttempter* update_attempter = SystemState::Get()->update_attempter();
if (update_attempter) {
update_attempter->RefreshDevicePolicy();
- device_policy = system_state_->device_policy();
+ device_policy = SystemState::Get()->device_policy();
}
}
@@ -198,7 +200,7 @@
LOG(INFO) << "Setting destination channel to: " << in_target_channel;
string error_message;
- if (!system_state_->request_params()->SetTargetChannel(
+ if (!SystemState::Get()->request_params()->SetTargetChannel(
in_target_channel, in_is_powerwash_allowed, &error_message)) {
LogAndSetError(error, FROM_HERE, error_message);
return false;
@@ -209,7 +211,7 @@
bool UpdateEngineService::GetChannel(ErrorPtr* /* error */,
bool in_get_current_channel,
string* out_channel) {
- OmahaRequestParams* rp = system_state_->request_params();
+ OmahaRequestParams* rp = SystemState::Get()->request_params();
*out_channel =
(in_get_current_channel ? rp->current_channel() : rp->target_channel());
return true;
@@ -217,7 +219,7 @@
bool UpdateEngineService::SetCohortHint(ErrorPtr* error,
const string& in_cohort_hint) {
- PrefsInterface* prefs = system_state_->prefs();
+ PrefsInterface* prefs = SystemState::Get()->prefs();
// It is ok to override the cohort hint with an invalid value since it is
// stored in stateful partition. The code reading it should sanitize it
@@ -235,7 +237,7 @@
bool UpdateEngineService::GetCohortHint(ErrorPtr* error,
string* out_cohort_hint) {
- PrefsInterface* prefs = system_state_->prefs();
+ PrefsInterface* prefs = SystemState::Get()->prefs();
*out_cohort_hint = "";
if (prefs->Exists(kPrefsOmahaCohortHint) &&
@@ -248,7 +250,7 @@
bool UpdateEngineService::SetP2PUpdatePermission(ErrorPtr* error,
bool in_enabled) {
- PrefsInterface* prefs = system_state_->prefs();
+ PrefsInterface* prefs = SystemState::Get()->prefs();
if (!prefs->SetBoolean(kPrefsP2PEnabled, in_enabled)) {
LogAndSetError(
@@ -263,7 +265,7 @@
bool UpdateEngineService::GetP2PUpdatePermission(ErrorPtr* error,
bool* out_enabled) {
- PrefsInterface* prefs = system_state_->prefs();
+ PrefsInterface* prefs = SystemState::Get()->prefs();
bool p2p_pref = false; // Default if no setting is present.
if (prefs->Exists(kPrefsP2PEnabled) &&
@@ -279,7 +281,7 @@
bool UpdateEngineService::SetUpdateOverCellularPermission(ErrorPtr* error,
bool in_allowed) {
ConnectionManagerInterface* connection_manager =
- system_state_->connection_manager();
+ SystemState::Get()->connection_manager();
// Check if this setting is allowed by the device policy.
if (connection_manager->IsAllowedConnectionTypesForUpdateSet()) {
@@ -293,7 +295,7 @@
// If the policy wasn't loaded yet, then it is still OK to change the local
// setting because the policy will be checked again during the update check.
- PrefsInterface* prefs = system_state_->prefs();
+ PrefsInterface* prefs = SystemState::Get()->prefs();
if (!prefs ||
!prefs->SetBoolean(kPrefsUpdateOverCellularPermission, in_allowed)) {
@@ -311,7 +313,7 @@
const std::string& target_version,
int64_t target_size) {
ConnectionManagerInterface* connection_manager =
- system_state_->connection_manager();
+ SystemState::Get()->connection_manager();
// Check if this setting is allowed by the device policy.
if (connection_manager->IsAllowedConnectionTypesForUpdateSet()) {
@@ -325,7 +327,7 @@
// If the policy wasn't loaded yet, then it is still OK to change the local
// setting because the policy will be checked again during the update check.
- PrefsInterface* prefs = system_state_->prefs();
+ PrefsInterface* prefs = SystemState::Get()->prefs();
if (!prefs ||
!prefs->SetString(kPrefsUpdateOverCellularTargetVersion,
@@ -341,14 +343,14 @@
bool UpdateEngineService::GetUpdateOverCellularPermission(ErrorPtr* error,
bool* out_allowed) {
ConnectionManagerInterface* connection_manager =
- system_state_->connection_manager();
+ SystemState::Get()->connection_manager();
if (connection_manager->IsAllowedConnectionTypesForUpdateSet()) {
// We have device policy, so ignore the user preferences.
*out_allowed = connection_manager->IsUpdateAllowedOver(
ConnectionType::kCellular, ConnectionTethering::kUnknown);
} else {
- PrefsInterface* prefs = system_state_->prefs();
+ PrefsInterface* prefs = SystemState::Get()->prefs();
if (!prefs || !prefs->Exists(kPrefsUpdateOverCellularPermission)) {
// Update is not allowed as user preference is not set or not available.
@@ -372,26 +374,26 @@
bool UpdateEngineService::GetDurationSinceUpdate(ErrorPtr* error,
int64_t* out_usec_wallclock) {
base::Time time;
- if (!system_state_->update_attempter()->GetBootTimeAtUpdate(&time)) {
+ if (!SystemState::Get()->update_attempter()->GetBootTimeAtUpdate(&time)) {
LogAndSetError(error, FROM_HERE, "No pending update.");
return false;
}
- ClockInterface* clock = system_state_->clock();
+ ClockInterface* clock = SystemState::Get()->clock();
*out_usec_wallclock = (clock->GetBootTime() - time).InMicroseconds();
return true;
}
bool UpdateEngineService::GetPrevVersion(ErrorPtr* /* error */,
string* out_prev_version) {
- *out_prev_version = system_state_->update_attempter()->GetPrevVersion();
+ *out_prev_version = SystemState::Get()->update_attempter()->GetPrevVersion();
return true;
}
bool UpdateEngineService::GetRollbackPartition(
ErrorPtr* /* error */, string* out_rollback_partition_name) {
BootControlInterface::Slot rollback_slot =
- system_state_->update_attempter()->GetRollbackSlot();
+ SystemState::Get()->update_attempter()->GetRollbackSlot();
if (rollback_slot == BootControlInterface::kInvalidSlot) {
out_rollback_partition_name->clear();
@@ -399,7 +401,7 @@
}
string name;
- if (!system_state_->boot_control()->GetPartitionDevice(
+ if (!SystemState::Get()->boot_control()->GetPartitionDevice(
"KERNEL", rollback_slot, &name)) {
LOG(ERROR) << "Invalid rollback device";
return false;
@@ -413,7 +415,7 @@
bool UpdateEngineService::GetLastAttemptError(ErrorPtr* /* error */,
int32_t* out_last_attempt_error) {
ErrorCode error_code =
- system_state_->update_attempter()->GetAttemptErrorCode();
+ SystemState::Get()->update_attempter()->GetAttemptErrorCode();
*out_last_attempt_error = static_cast<int>(error_code);
return true;
}
diff --git a/cros/common_service.h b/cros/common_service.h
index 6169d9c..2c176c5 100644
--- a/cros/common_service.h
+++ b/cros/common_service.h
@@ -26,7 +26,6 @@
#include <brillo/errors/error.h>
#include "update_engine/client_library/include/update_engine/update_status.h"
-#include "update_engine/common/system_state.h"
namespace chromeos_update_engine {
@@ -38,7 +37,7 @@
// Generic service error.
static const char* const kErrorFailed;
- explicit UpdateEngineService(SystemState* system_state);
+ UpdateEngineService();
virtual ~UpdateEngineService() = default;
// Set flags that influence how updates and checks are performed. These
@@ -160,9 +159,6 @@
// Returns the last UpdateAttempt error.
bool GetLastAttemptError(brillo::ErrorPtr* error,
int32_t* out_last_attempt_error);
-
- private:
- SystemState* system_state_;
};
} // namespace chromeos_update_engine
diff --git a/cros/common_service_unittest.cc b/cros/common_service_unittest.cc
index 733ec0a..a6b0014 100644
--- a/cros/common_service_unittest.cc
+++ b/cros/common_service_unittest.cc
@@ -39,17 +39,14 @@
class UpdateEngineServiceTest : public ::testing::Test {
protected:
- UpdateEngineServiceTest()
- : mock_update_attempter_(fake_system_state_.mock_update_attempter()),
- common_service_(&fake_system_state_) {}
+ UpdateEngineServiceTest() = default;
- void SetUp() override { fake_system_state_.set_device_policy(nullptr); }
+ void SetUp() override {
+ FakeSystemState::CreateInstance();
+ FakeSystemState::Get()->set_device_policy(nullptr);
+ mock_update_attempter_ = FakeSystemState::Get()->mock_update_attempter();
+ }
- // Fake/mock infrastructure.
- FakeSystemState fake_system_state_;
- policy::MockDevicePolicy mock_device_policy_;
-
- // Shortcut for fake_system_state_.mock_update_attempter().
MockUpdateAttempter* mock_update_attempter_;
brillo::ErrorPtr error_;
@@ -119,7 +116,7 @@
TEST_F(UpdateEngineServiceTest, SetChannelWithNoPolicy) {
EXPECT_CALL(*mock_update_attempter_, RefreshDevicePolicy());
// If SetTargetChannel is called it means the policy check passed.
- EXPECT_CALL(*fake_system_state_.mock_request_params(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_request_params(),
SetTargetChannel("stable-channel", true, _))
.WillOnce(Return(true));
EXPECT_TRUE(common_service_.SetChannel(&error_, "stable-channel", true));
@@ -129,10 +126,10 @@
// When the policy is present, the delegated value should be checked.
TEST_F(UpdateEngineServiceTest, SetChannelWithDelegatedPolicy) {
policy::MockDevicePolicy mock_device_policy;
- fake_system_state_.set_device_policy(&mock_device_policy);
+ FakeSystemState::Get()->set_device_policy(&mock_device_policy);
EXPECT_CALL(mock_device_policy, GetReleaseChannelDelegated(_))
.WillOnce(DoAll(SetArgPointee<0>(true), Return(true)));
- EXPECT_CALL(*fake_system_state_.mock_request_params(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_request_params(),
SetTargetChannel("beta-channel", true, _))
.WillOnce(Return(true));
@@ -144,7 +141,7 @@
// raised.
TEST_F(UpdateEngineServiceTest, SetChannelWithInvalidChannel) {
EXPECT_CALL(*mock_update_attempter_, RefreshDevicePolicy());
- EXPECT_CALL(*fake_system_state_.mock_request_params(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_request_params(),
SetTargetChannel("foo-channel", true, _))
.WillOnce(Return(false));
@@ -155,8 +152,8 @@
}
TEST_F(UpdateEngineServiceTest, GetChannel) {
- fake_system_state_.mock_request_params()->set_current_channel("current");
- fake_system_state_.mock_request_params()->set_target_channel("target");
+ FakeSystemState::Get()->mock_request_params()->set_current_channel("current");
+ FakeSystemState::Get()->mock_request_params()->set_target_channel("target");
string channel;
EXPECT_TRUE(common_service_.GetChannel(
&error_, true /* get_current_channel */, &channel));
diff --git a/cros/connection_manager.cc b/cros/connection_manager.cc
index 331f76b..6a5c63b 100644
--- a/cros/connection_manager.cc
+++ b/cros/connection_manager.cc
@@ -41,16 +41,14 @@
namespace chromeos_update_engine {
namespace connection_manager {
-std::unique_ptr<ConnectionManagerInterface> CreateConnectionManager(
- SystemState* system_state) {
+std::unique_ptr<ConnectionManagerInterface> CreateConnectionManager() {
return std::unique_ptr<ConnectionManagerInterface>(
- new ConnectionManager(new ShillProxy(), system_state));
+ new ConnectionManager(new ShillProxy()));
}
} // namespace connection_manager
-ConnectionManager::ConnectionManager(ShillProxyInterface* shill_proxy,
- SystemState* system_state)
- : shill_proxy_(shill_proxy), system_state_(system_state) {}
+ConnectionManager::ConnectionManager(ShillProxyInterface* shill_proxy)
+ : shill_proxy_(shill_proxy) {}
bool ConnectionManager::IsUpdateAllowedOver(
ConnectionType type, ConnectionTethering tethering) const {
@@ -64,15 +62,16 @@
<< "Current connection is confirmed tethered, using Cellular setting.";
}
- const policy::DevicePolicy* device_policy = system_state_->device_policy();
+ const policy::DevicePolicy* device_policy =
+ SystemState::Get()->device_policy();
// The device_policy is loaded in a lazy way before an update check. Load
// it now from the libbrillo cache if it wasn't already loaded.
if (!device_policy) {
- UpdateAttempter* update_attempter = system_state_->update_attempter();
+ UpdateAttempter* update_attempter = SystemState::Get()->update_attempter();
if (update_attempter) {
update_attempter->RefreshDevicePolicy();
- device_policy = system_state_->device_policy();
+ device_policy = SystemState::Get()->device_policy();
}
}
@@ -109,7 +108,8 @@
}
bool ConnectionManager::IsAllowedConnectionTypesForUpdateSet() const {
- const policy::DevicePolicy* device_policy = system_state_->device_policy();
+ const policy::DevicePolicy* device_policy =
+ SystemState::Get()->device_policy();
if (!device_policy) {
LOG(INFO) << "There's no device policy loaded yet.";
return false;
diff --git a/cros/connection_manager.h b/cros/connection_manager.h
index b1fb961..bb54ff7 100644
--- a/cros/connection_manager.h
+++ b/cros/connection_manager.h
@@ -35,8 +35,7 @@
public:
// Constructs a new ConnectionManager object initialized with the
// given system state.
- ConnectionManager(ShillProxyInterface* shill_proxy,
- SystemState* system_state);
+ explicit ConnectionManager(ShillProxyInterface* shill_proxy);
~ConnectionManager() override = default;
// ConnectionManagerInterface overrides.
@@ -58,9 +57,6 @@
// The mockable interface to access the shill DBus proxies.
std::unique_ptr<ShillProxyInterface> shill_proxy_;
- // The global context for update_engine.
- SystemState* system_state_;
-
DISALLOW_COPY_AND_ASSIGN(ConnectionManager);
};
diff --git a/cros/connection_manager_interface.h b/cros/connection_manager_interface.h
index 6dd9fbd..dc6c983 100644
--- a/cros/connection_manager_interface.h
+++ b/cros/connection_manager_interface.h
@@ -25,8 +25,6 @@
namespace chromeos_update_engine {
-class SystemState;
-
// This class exposes a generic interface to the connection manager
// (e.g FlimFlam, Shill, etc.) to consolidate all connection-related
// logic in update_engine.
@@ -59,8 +57,7 @@
namespace connection_manager {
// Factory function which creates a ConnectionManager.
-std::unique_ptr<ConnectionManagerInterface> CreateConnectionManager(
- SystemState* system_state);
+std::unique_ptr<ConnectionManagerInterface> CreateConnectionManager();
} // namespace connection_manager
} // namespace chromeos_update_engine
diff --git a/cros/connection_manager_unittest.cc b/cros/connection_manager_unittest.cc
index 3f1ee5a..46da8cc 100644
--- a/cros/connection_manager_unittest.cc
+++ b/cros/connection_manager_unittest.cc
@@ -52,7 +52,8 @@
void SetUp() override {
loop_.SetAsCurrent();
- fake_system_state_.set_connection_manager(&cmut_);
+ FakeSystemState::CreateInstance();
+ FakeSystemState::Get()->set_connection_manager(&cmut_);
}
void TearDown() override { EXPECT_FALSE(loop_.PendingTasks()); }
@@ -81,11 +82,10 @@
ConnectionTethering expected_tethering);
brillo::FakeMessageLoop loop_{nullptr};
- FakeSystemState fake_system_state_;
FakeShillProxy* fake_shill_proxy_;
// ConnectionManager under test.
- ConnectionManager cmut_{fake_shill_proxy_, &fake_system_state_};
+ ConnectionManager cmut_{fake_shill_proxy_};
};
void ConnectionManagerTest::SetManagerReply(const char* default_service,
@@ -227,7 +227,7 @@
TEST_F(ConnectionManagerTest, AllowUpdatesOnlyOver3GPerPolicyTest) {
policy::MockDevicePolicy allow_3g_policy;
- fake_system_state_.set_device_policy(&allow_3g_policy);
+ FakeSystemState::Get()->set_device_policy(&allow_3g_policy);
// This test tests cellular (3G) being the only connection type being allowed.
set<string> allowed_set;
@@ -244,7 +244,7 @@
TEST_F(ConnectionManagerTest, AllowUpdatesOver3GAndOtherTypesPerPolicyTest) {
policy::MockDevicePolicy allow_3g_policy;
- fake_system_state_.set_device_policy(&allow_3g_policy);
+ FakeSystemState::Get()->set_device_policy(&allow_3g_policy);
// This test tests multiple connection types being allowed, with
// 3G one among them. Only Cellular is currently enforced by the policy
@@ -276,7 +276,7 @@
TEST_F(ConnectionManagerTest, AllowUpdatesOverCellularByDefaultTest) {
policy::MockDevicePolicy device_policy;
// Set an empty device policy.
- fake_system_state_.set_device_policy(&device_policy);
+ FakeSystemState::Get()->set_device_policy(&device_policy);
EXPECT_TRUE(cmut_.IsUpdateAllowedOver(ConnectionType::kCellular,
ConnectionTethering::kUnknown));
@@ -285,7 +285,7 @@
TEST_F(ConnectionManagerTest, AllowUpdatesOverTetheredNetworkByDefaultTest) {
policy::MockDevicePolicy device_policy;
// Set an empty device policy.
- fake_system_state_.set_device_policy(&device_policy);
+ FakeSystemState::Get()->set_device_policy(&device_policy);
EXPECT_TRUE(cmut_.IsUpdateAllowedOver(ConnectionType::kWifi,
ConnectionTethering::kConfirmed));
@@ -298,7 +298,7 @@
TEST_F(ConnectionManagerTest, BlockUpdatesOver3GPerPolicyTest) {
policy::MockDevicePolicy block_3g_policy;
- fake_system_state_.set_device_policy(&block_3g_policy);
+ FakeSystemState::Get()->set_device_policy(&block_3g_policy);
// Test that updates for 3G are blocked while updates are allowed
// over several other types.
@@ -317,7 +317,7 @@
TEST_F(ConnectionManagerTest, AllowUpdatesOver3GIfPolicyIsNotSet) {
policy::MockDevicePolicy device_policy;
- fake_system_state_.set_device_policy(&device_policy);
+ FakeSystemState::Get()->set_device_policy(&device_policy);
// Return false for GetAllowedConnectionTypesForUpdate and see
// that updates are allowed as device policy is not set. Further
@@ -331,7 +331,7 @@
}
TEST_F(ConnectionManagerTest, AllowUpdatesOverCellularIfPolicyFailsToBeLoaded) {
- fake_system_state_.set_device_policy(nullptr);
+ FakeSystemState::Get()->set_device_policy(nullptr);
EXPECT_TRUE(cmut_.IsUpdateAllowedOver(ConnectionType::kCellular,
ConnectionTethering::kUnknown));
diff --git a/cros/daemon_chromeos.cc b/cros/daemon_chromeos.cc
index 1e0e6d6..5fa24ea 100644
--- a/cros/daemon_chromeos.cc
+++ b/cros/daemon_chromeos.cc
@@ -41,18 +41,15 @@
if (exit_code != EX_OK)
return exit_code;
- // Initialize update engine global state but continue if something fails.
- // TODO(deymo): Move the daemon_state_ initialization to a factory method
- // avoiding the explicit re-usage of the |bus| instance, shared between
- // D-Bus service and D-Bus client calls.
- RealSystemState* real_system_state = new RealSystemState();
- LOG_IF(ERROR, !real_system_state->Initialize())
- << "Failed to initialize system state.";
- system_state_.reset(real_system_state);
+ // Initialize update engine global state.
+ // TODO(deymo): Move the initialization to a factory method avoiding the
+ // explicit re-usage of the |bus| instance, shared between D-Bus service and
+ // D-Bus client calls.
+ RealSystemState::CreateInstance();
// Create the DBus service.
- dbus_adaptor_.reset(new UpdateEngineAdaptor(real_system_state));
- system_state_->update_attempter()->AddObserver(dbus_adaptor_.get());
+ dbus_adaptor_.reset(new UpdateEngineAdaptor());
+ SystemState::Get()->update_attempter()->AddObserver(dbus_adaptor_.get());
dbus_adaptor_->RegisterAsync(
base::Bind(&DaemonChromeOS::OnDBusRegistered, base::Unretained(this)));
@@ -76,7 +73,7 @@
QuitWithExitCode(1);
return;
}
- system_state_->update_attempter()->StartUpdater();
+ SystemState::Get()->update_attempter()->StartUpdater();
}
} // namespace chromeos_update_engine
diff --git a/cros/daemon_chromeos.h b/cros/daemon_chromeos.h
index 3b9c8de..ab9d4b2 100644
--- a/cros/daemon_chromeos.h
+++ b/cros/daemon_chromeos.h
@@ -47,9 +47,6 @@
// the main() function.
Subprocess subprocess_;
- // The global context sysetm state.
- std::unique_ptr<SystemState> system_state_;
-
DISALLOW_COPY_AND_ASSIGN(DaemonChromeOS);
};
diff --git a/cros/dbus_service.cc b/cros/dbus_service.cc
index d115195..1eb7b3c 100644
--- a/cros/dbus_service.cc
+++ b/cros/dbus_service.cc
@@ -52,8 +52,8 @@
}
} // namespace
-DBusUpdateEngineService::DBusUpdateEngineService(SystemState* system_state)
- : common_(new UpdateEngineService{system_state}) {}
+DBusUpdateEngineService::DBusUpdateEngineService()
+ : common_(new UpdateEngineService()) {}
// org::chromium::UpdateEngineInterfaceInterface methods implementation.
@@ -192,10 +192,10 @@
return common_->GetLastAttemptError(error, out_last_attempt_error);
}
-UpdateEngineAdaptor::UpdateEngineAdaptor(SystemState* system_state)
+UpdateEngineAdaptor::UpdateEngineAdaptor()
: org::chromium::UpdateEngineInterfaceAdaptor(&dbus_service_),
bus_(DBusConnection::Get()->GetDBus()),
- dbus_service_(system_state),
+ dbus_service_(),
dbus_object_(nullptr,
bus_,
dbus::ObjectPath(update_engine::kUpdateEngineServicePath)) {}
diff --git a/cros/dbus_service.h b/cros/dbus_service.h
index 9e4457f..3ad6589 100644
--- a/cros/dbus_service.h
+++ b/cros/dbus_service.h
@@ -38,7 +38,7 @@
class DBusUpdateEngineService
: public org::chromium::UpdateEngineInterfaceInterface {
public:
- explicit DBusUpdateEngineService(SystemState* system_state);
+ DBusUpdateEngineService();
virtual ~DBusUpdateEngineService() = default;
// Implementation of org::chromium::UpdateEngineInterfaceInterface.
@@ -165,7 +165,7 @@
class UpdateEngineAdaptor : public org::chromium::UpdateEngineInterfaceAdaptor,
public ServiceObserverInterface {
public:
- explicit UpdateEngineAdaptor(SystemState* system_state);
+ UpdateEngineAdaptor();
~UpdateEngineAdaptor() = default;
// Register the DBus object with the update engine service asynchronously.
diff --git a/cros/fake_system_state.cc b/cros/fake_system_state.cc
index 9dfdc5b..81fa957 100644
--- a/cros/fake_system_state.cc
+++ b/cros/fake_system_state.cc
@@ -21,8 +21,8 @@
// Mock the SystemStateInterface so that we could lie that
// OOBE is completed even when there's no such marker file, etc.
FakeSystemState::FakeSystemState()
- : mock_update_attempter_(this, nullptr),
- mock_request_params_(this),
+ : mock_update_attempter_(nullptr),
+ mock_request_params_(),
fake_update_manager_(&fake_clock_),
clock_(&fake_clock_),
connection_manager_(&mock_connection_manager_),
@@ -37,7 +37,7 @@
update_manager_(&fake_update_manager_),
device_policy_(nullptr),
fake_system_rebooted_(false) {
- mock_payload_state_.Initialize(this);
+ mock_payload_state_.Initialize();
}
} // namespace chromeos_update_engine
diff --git a/cros/fake_system_state.h b/cros/fake_system_state.h
index 2f92b7c..b1d5952 100644
--- a/cros/fake_system_state.h
+++ b/cros/fake_system_state.h
@@ -42,7 +42,11 @@
// OOBE is completed even when there's no such marker file, etc.
class FakeSystemState : public SystemState {
public:
- FakeSystemState();
+ static void CreateInstance() { g_instance_.reset(new FakeSystemState()); }
+
+ static FakeSystemState* Get() {
+ return reinterpret_cast<FakeSystemState*>(g_instance_.get());
+ }
// Base class overrides. All getters return the current implementation of
// various members, either the default (fake/mock) or the one set to override
@@ -237,6 +241,9 @@
}
private:
+ // Don't allow for direct initialization of this class.
+ FakeSystemState();
+
// Default mock/fake implementations (owned).
FakeBootControl fake_boot_control_;
FakeClock fake_clock_;
diff --git a/cros/image_properties.h b/cros/image_properties.h
index 4957d12..1297547 100644
--- a/cros/image_properties.h
+++ b/cros/image_properties.h
@@ -25,8 +25,6 @@
namespace chromeos_update_engine {
-class SystemState;
-
// The read-only system properties of the running image.
struct ImageProperties {
// The product id of the image used for all channels, except canary.
@@ -77,16 +75,15 @@
// Loads all the image properties from the running system. In case of error
// loading any of these properties from the read-only system image a default
// value may be returned instead.
-ImageProperties LoadImageProperties(SystemState* system_state);
+ImageProperties LoadImageProperties();
// Loads the mutable image properties from the stateful partition if found or
// the system image otherwise.
-MutableImageProperties LoadMutableImageProperties(SystemState* system_state);
+MutableImageProperties LoadMutableImageProperties();
// Stores the mutable image properties in the stateful partition. Returns
// whether the operation succeeded.
-bool StoreMutableImageProperties(SystemState* system_state,
- const MutableImageProperties& properties);
+bool StoreMutableImageProperties(const MutableImageProperties& properties);
// Logs the image properties.
void LogImageProperties();
diff --git a/cros/image_properties_chromeos.cc b/cros/image_properties_chromeos.cc
index c22da7c..79155b5 100644
--- a/cros/image_properties_chromeos.cc
+++ b/cros/image_properties_chromeos.cc
@@ -86,7 +86,7 @@
}
} // namespace test
-ImageProperties LoadImageProperties(SystemState* system_state) {
+ImageProperties LoadImageProperties() {
ImageProperties result;
brillo::KeyValueStore lsb_release;
@@ -97,7 +97,7 @@
// In dev-mode and unofficial build we can override the image properties set
// in the system image with the ones from the stateful partition, except the
// channel of the current image.
- HardwareInterface* const hardware = system_state->hardware();
+ HardwareInterface* const hardware = SystemState::Get()->hardware();
if (!hardware->IsOfficialBuild() || !hardware->IsNormalBootMode())
LoadLsbRelease(LsbReleaseSource::kStateful, &lsb_release);
@@ -124,7 +124,7 @@
return result;
}
-MutableImageProperties LoadMutableImageProperties(SystemState* system_state) {
+MutableImageProperties LoadMutableImageProperties() {
MutableImageProperties result;
brillo::KeyValueStore lsb_release;
LoadLsbRelease(LsbReleaseSource::kSystem, &lsb_release);
@@ -137,8 +137,7 @@
return result;
}
-bool StoreMutableImageProperties(SystemState* system_state,
- const MutableImageProperties& properties) {
+bool StoreMutableImageProperties(const MutableImageProperties& properties) {
brillo::KeyValueStore lsb_release;
LoadLsbRelease(LsbReleaseSource::kStateful, &lsb_release);
lsb_release.SetString(kLsbReleaseUpdateChannelKey, properties.target_channel);
diff --git a/cros/image_properties_chromeos_unittest.cc b/cros/image_properties_chromeos_unittest.cc
index 4822995..497554e 100644
--- a/cros/image_properties_chromeos_unittest.cc
+++ b/cros/image_properties_chromeos_unittest.cc
@@ -40,16 +40,15 @@
EXPECT_TRUE(base::CreateDirectory(base::FilePath(
tempdir_.GetPath().value() + kStatefulPartition + "/etc")));
test::SetImagePropertiesRootPrefix(tempdir_.GetPath().value().c_str());
+ FakeSystemState::CreateInstance();
SetLockDown(false);
}
void SetLockDown(bool locked_down) {
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(locked_down);
- fake_system_state_.fake_hardware()->SetIsNormalBootMode(locked_down);
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(locked_down);
+ FakeSystemState::Get()->fake_hardware()->SetIsNormalBootMode(locked_down);
}
- FakeSystemState fake_system_state_;
-
base::ScopedTempDir tempdir_;
};
@@ -61,7 +60,7 @@
"CHROMEOS_RELEASE_VERSION=0.2.2.3\n"
"CHROMEOS_RELEASE_TRACK=dev-channel\n"
"CHROMEOS_AUSERVER=http://www.google.com"));
- ImageProperties props = LoadImageProperties(&fake_system_state_);
+ ImageProperties props = LoadImageProperties();
EXPECT_EQ("arm-generic", props.board);
EXPECT_EQ("{87efface-864d-49a5-9bb3-4b050a7c227a}", props.product_id);
EXPECT_EQ("0.2.2.3", props.version);
@@ -73,7 +72,7 @@
ASSERT_TRUE(WriteFileString(
tempdir_.GetPath().Append("etc/lsb-release").value(),
"CHROMEOS_RELEASE_APPID={58c35cef-9d30-476e-9098-ce20377d535d}"));
- ImageProperties props = LoadImageProperties(&fake_system_state_);
+ ImageProperties props = LoadImageProperties();
EXPECT_EQ("{58c35cef-9d30-476e-9098-ce20377d535d}", props.product_id);
}
@@ -82,12 +81,12 @@
WriteFileString(tempdir_.GetPath().Append("etc/lsb-release").value(),
"CHROMEOS_RELEASE_FOO=CHROMEOS_RELEASE_VERSION=1.2.3.4\n"
"CHROMEOS_RELEASE_VERSION=0.2.2.3"));
- ImageProperties props = LoadImageProperties(&fake_system_state_);
+ ImageProperties props = LoadImageProperties();
EXPECT_EQ("0.2.2.3", props.version);
}
TEST_F(ImagePropertiesTest, MissingVersionTest) {
- ImageProperties props = LoadImageProperties(&fake_system_state_);
+ ImageProperties props = LoadImageProperties();
EXPECT_EQ("", props.version);
}
@@ -103,12 +102,11 @@
"CHROMEOS_RELEASE_BOARD=x86-generic\n"
"CHROMEOS_RELEASE_TRACK=beta-channel\n"
"CHROMEOS_AUSERVER=https://www.google.com"));
- ImageProperties props = LoadImageProperties(&fake_system_state_);
+ ImageProperties props = LoadImageProperties();
EXPECT_EQ("x86-generic", props.board);
EXPECT_EQ("dev-channel", props.current_channel);
EXPECT_EQ("https://www.google.com", props.omaha_url);
- MutableImageProperties mutable_props =
- LoadMutableImageProperties(&fake_system_state_);
+ MutableImageProperties mutable_props = LoadMutableImageProperties();
EXPECT_EQ("beta-channel", mutable_props.target_channel);
}
@@ -125,12 +123,11 @@
"CHROMEOS_RELEASE_TRACK=stable-channel\n"
"CHROMEOS_AUSERVER=http://www.google.com"));
SetLockDown(true);
- ImageProperties props = LoadImageProperties(&fake_system_state_);
+ ImageProperties props = LoadImageProperties();
EXPECT_EQ("arm-generic", props.board);
EXPECT_EQ("dev-channel", props.current_channel);
EXPECT_EQ("https://www.google.com", props.omaha_url);
- MutableImageProperties mutable_props =
- LoadMutableImageProperties(&fake_system_state_);
+ MutableImageProperties mutable_props = LoadMutableImageProperties();
EXPECT_EQ("stable-channel", mutable_props.target_channel);
}
@@ -141,7 +138,7 @@
"CHROMEOS_BOARD_APPID=b\n"
"CHROMEOS_CANARY_APPID=c\n"
"CHROMEOS_RELEASE_TRACK=stable-channel\n"));
- ImageProperties props = LoadImageProperties(&fake_system_state_);
+ ImageProperties props = LoadImageProperties();
EXPECT_EQ("stable-channel", props.current_channel);
EXPECT_EQ("b", props.product_id);
}
@@ -153,7 +150,7 @@
"CHROMEOS_BOARD_APPID=b\n"
"CHROMEOS_CANARY_APPID=c\n"
"CHROMEOS_RELEASE_TRACK=canary-channel\n"));
- ImageProperties props = LoadImageProperties(&fake_system_state_);
+ ImageProperties props = LoadImageProperties();
EXPECT_EQ("canary-channel", props.current_channel);
EXPECT_EQ("c", props.canary_product_id);
}
@@ -164,7 +161,7 @@
"CHROMEOS_RELEASE_APPID=r\n"
"CHROMEOS_CANARY_APPID=c\n"
"CHROMEOS_RELEASE_TRACK=stable-channel\n"));
- ImageProperties props = LoadImageProperties(&fake_system_state_);
+ ImageProperties props = LoadImageProperties();
EXPECT_EQ("stable-channel", props.current_channel);
EXPECT_EQ("r", props.product_id);
}
diff --git a/cros/metrics_reporter_omaha.cc b/cros/metrics_reporter_omaha.cc
index 2cc0de5..65093a1 100644
--- a/cros/metrics_reporter_omaha.cc
+++ b/cros/metrics_reporter_omaha.cc
@@ -155,7 +155,6 @@
}
void MetricsReporterOmaha::ReportUpdateCheckMetrics(
- SystemState* system_state,
metrics::CheckResult result,
metrics::CheckReaction reaction,
metrics::DownloadErrorCode download_error_code) {
@@ -182,8 +181,7 @@
}
base::TimeDelta time_since_last;
- if (WallclockDurationHelper(system_state,
- kPrefsMetricsCheckLastReportingTime,
+ if (WallclockDurationHelper(kPrefsMetricsCheckLastReportingTime,
&time_since_last)) {
metric = metrics::kMetricCheckTimeSinceLastCheckMinutes;
metrics_lib_->SendToUMA(metric,
@@ -195,8 +193,7 @@
base::TimeDelta uptime_since_last;
static int64_t uptime_since_last_storage = 0;
- if (MonotonicDurationHelper(
- system_state, &uptime_since_last_storage, &uptime_since_last)) {
+ if (MonotonicDurationHelper(&uptime_since_last_storage, &uptime_since_last)) {
metric = metrics::kMetricCheckTimeSinceLastCheckUptimeMinutes;
metrics_lib_->SendToUMA(metric,
uptime_since_last.InMinutes(),
@@ -206,14 +203,14 @@
}
// First section of target version specified for the update.
- if (system_state && system_state->request_params()) {
+ if (SystemState::Get()->request_params()) {
string target_version =
- system_state->request_params()->target_version_prefix();
+ SystemState::Get()->request_params()->target_version_prefix();
value = utils::VersionPrefix(target_version);
if (value != 0) {
metric = metrics::kMetricCheckTargetVersion;
metrics_lib_->SendSparseToUMA(metric, value);
- if (system_state->request_params()->rollback_allowed()) {
+ if (SystemState::Get()->request_params()->rollback_allowed()) {
metric = metrics::kMetricCheckRollbackTargetVersion;
metrics_lib_->SendSparseToUMA(metric, value);
}
@@ -233,7 +230,6 @@
}
void MetricsReporterOmaha::ReportUpdateAttemptMetrics(
- SystemState* system_state,
int attempt_number,
PayloadType payload_type,
base::TimeDelta duration,
@@ -284,8 +280,7 @@
}
base::TimeDelta time_since_last;
- if (WallclockDurationHelper(system_state,
- kPrefsMetricsAttemptLastReportingTime,
+ if (WallclockDurationHelper(kPrefsMetricsAttemptLastReportingTime,
&time_since_last)) {
metric = metrics::kMetricAttemptTimeSinceLastAttemptMinutes;
metrics_lib_->SendToUMA(metric,
@@ -297,8 +292,7 @@
static int64_t uptime_since_last_storage = 0;
base::TimeDelta uptime_since_last;
- if (MonotonicDurationHelper(
- system_state, &uptime_since_last_storage, &uptime_since_last)) {
+ if (MonotonicDurationHelper(&uptime_since_last_storage, &uptime_since_last)) {
metric = metrics::kMetricAttemptTimeSinceLastAttemptUptimeMinutes;
metrics_lib_->SendToUMA(metric,
uptime_since_last.InMinutes(),
@@ -557,13 +551,13 @@
}
bool MetricsReporterOmaha::WallclockDurationHelper(
- SystemState* system_state,
const std::string& state_variable_key,
TimeDelta* out_duration) {
bool ret = false;
- Time now = system_state->clock()->GetWallclockTime();
+ Time now = SystemState::Get()->clock()->GetWallclockTime();
int64_t stored_value;
- if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
+ if (SystemState::Get()->prefs()->GetInt64(state_variable_key,
+ &stored_value)) {
Time stored_time = Time::FromInternalValue(stored_value);
if (stored_time > now) {
LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
@@ -574,19 +568,18 @@
}
}
- if (!system_state->prefs()->SetInt64(state_variable_key,
- now.ToInternalValue())) {
+ if (!SystemState::Get()->prefs()->SetInt64(state_variable_key,
+ now.ToInternalValue())) {
LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
}
return ret;
}
-bool MetricsReporterOmaha::MonotonicDurationHelper(SystemState* system_state,
- int64_t* storage,
+bool MetricsReporterOmaha::MonotonicDurationHelper(int64_t* storage,
TimeDelta* out_duration) {
bool ret = false;
- Time now = system_state->clock()->GetMonotonicTime();
+ Time now = SystemState::Get()->clock()->GetMonotonicTime();
if (*storage != 0) {
Time stored_time = Time::FromInternalValue(*storage);
*out_duration = now - stored_time;
diff --git a/cros/metrics_reporter_omaha.h b/cros/metrics_reporter_omaha.h
index 5b3fdb1..b6ffcce 100644
--- a/cros/metrics_reporter_omaha.h
+++ b/cros/metrics_reporter_omaha.h
@@ -29,7 +29,6 @@
#include "update_engine/common/error_code.h"
#include "update_engine/common/metrics_constants.h"
#include "update_engine/common/metrics_reporter_interface.h"
-#include "update_engine/common/system_state.h"
namespace chromeos_update_engine {
@@ -117,13 +116,11 @@
void ReportDailyMetrics(base::TimeDelta os_age) override;
void ReportUpdateCheckMetrics(
- SystemState* system_state,
metrics::CheckResult result,
metrics::CheckReaction reaction,
metrics::DownloadErrorCode download_error_code) override;
- void ReportUpdateAttemptMetrics(SystemState* system_state,
- int attempt_number,
+ void ReportUpdateAttemptMetrics(int attempt_number,
PayloadType payload_type,
base::TimeDelta duration,
base::TimeDelta duration_uptime,
@@ -181,8 +178,7 @@
// If the function returns |true|, the duration (always non-negative)
// is returned in |out_duration|. If the function returns |false|
// something went wrong or there was no previous measurement.
- bool WallclockDurationHelper(SystemState* system_state,
- const std::string& state_variable_key,
+ bool WallclockDurationHelper(const std::string& state_variable_key,
base::TimeDelta* out_duration);
// This function returns the duration on the monotonic clock since the
@@ -194,9 +190,7 @@
// If the function returns |true|, the duration (always non-negative)
// is returned in |out_duration|. If the function returns |false|
// something went wrong or there was no previous measurement.
- bool MonotonicDurationHelper(SystemState* system_state,
- int64_t* storage,
- base::TimeDelta* out_duration);
+ bool MonotonicDurationHelper(int64_t* storage, base::TimeDelta* out_duration);
std::unique_ptr<MetricsLibraryInterface> metrics_lib_;
diff --git a/cros/metrics_reporter_omaha_unittest.cc b/cros/metrics_reporter_omaha_unittest.cc
index a25472a..b161137 100644
--- a/cros/metrics_reporter_omaha_unittest.cc
+++ b/cros/metrics_reporter_omaha_unittest.cc
@@ -40,6 +40,7 @@
// Reset the metrics_lib_ to a mock library.
void SetUp() override {
+ FakeSystemState::CreateInstance();
mock_metrics_lib_ = new testing::NiceMock<MetricsLibraryMock>();
reporter_.metrics_lib_.reset(mock_metrics_lib_);
}
@@ -58,13 +59,12 @@
}
TEST_F(MetricsReporterOmahaTest, ReportUpdateCheckMetrics) {
- FakeSystemState fake_system_state;
FakeClock fake_clock;
FakePrefs fake_prefs;
// We need to execute the report twice to test the time since last report.
- fake_system_state.set_clock(&fake_clock);
- fake_system_state.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_clock(&fake_clock);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
fake_clock.SetWallclockTime(base::Time::FromInternalValue(1000000));
fake_clock.SetMonotonicTime(base::Time::FromInternalValue(1000000));
@@ -104,24 +104,20 @@
metrics::kMetricCheckTimeSinceLastCheckUptimeMinutes, 1, _, _, _))
.Times(1);
- reporter_.ReportUpdateCheckMetrics(
- &fake_system_state, result, reaction, error_code);
+ reporter_.ReportUpdateCheckMetrics(result, reaction, error_code);
// Advance the clock by 1 minute and report the same metrics again.
fake_clock.SetWallclockTime(base::Time::FromInternalValue(61000000));
fake_clock.SetMonotonicTime(base::Time::FromInternalValue(61000000));
// Allow rollback
- reporter_.ReportUpdateCheckMetrics(
- &fake_system_state, result, reaction, error_code);
+ reporter_.ReportUpdateCheckMetrics(result, reaction, error_code);
}
TEST_F(MetricsReporterOmahaTest, ReportUpdateCheckMetricsPinned) {
- FakeSystemState fake_system_state;
-
- OmahaRequestParams params(&fake_system_state);
+ OmahaRequestParams params;
params.set_target_version_prefix("10575.");
params.set_rollback_allowed(false);
- fake_system_state.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
metrics::CheckResult result = metrics::CheckResult::kUpdateAvailable;
metrics::CheckReaction reaction = metrics::CheckReaction::kIgnored;
@@ -138,17 +134,14 @@
SendSparseToUMA(metrics::kMetricCheckRollbackTargetVersion, _))
.Times(0);
- reporter_.ReportUpdateCheckMetrics(
- &fake_system_state, result, reaction, error_code);
+ reporter_.ReportUpdateCheckMetrics(result, reaction, error_code);
}
TEST_F(MetricsReporterOmahaTest, ReportUpdateCheckMetricsRollback) {
- FakeSystemState fake_system_state;
-
- OmahaRequestParams params(&fake_system_state);
+ OmahaRequestParams params;
params.set_target_version_prefix("10575.");
params.set_rollback_allowed(true);
- fake_system_state.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
metrics::CheckResult result = metrics::CheckResult::kUpdateAvailable;
metrics::CheckReaction reaction = metrics::CheckReaction::kIgnored;
@@ -166,8 +159,7 @@
SendSparseToUMA(metrics::kMetricCheckRollbackTargetVersion, 10575))
.Times(1);
- reporter_.ReportUpdateCheckMetrics(
- &fake_system_state, result, reaction, error_code);
+ reporter_.ReportUpdateCheckMetrics(result, reaction, error_code);
}
TEST_F(MetricsReporterOmahaTest,
@@ -183,12 +175,10 @@
}
TEST_F(MetricsReporterOmahaTest, ReportUpdateAttemptMetrics) {
- FakeSystemState fake_system_state;
FakeClock fake_clock;
FakePrefs fake_prefs;
-
- fake_system_state.set_clock(&fake_clock);
- fake_system_state.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_clock(&fake_clock);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
fake_clock.SetWallclockTime(base::Time::FromInternalValue(1000000));
fake_clock.SetMonotonicTime(base::Time::FromInternalValue(1000000));
@@ -252,8 +242,7 @@
metrics::kMetricAttemptTimeSinceLastAttemptUptimeMinutes, 1, _, _, _))
.Times(1);
- reporter_.ReportUpdateAttemptMetrics(&fake_system_state,
- attempt_number,
+ reporter_.ReportUpdateAttemptMetrics(attempt_number,
payload_type,
duration,
duration_uptime,
@@ -264,8 +253,7 @@
// Advance the clock by 1 minute and report the same metrics again.
fake_clock.SetWallclockTime(base::Time::FromInternalValue(61000000));
fake_clock.SetMonotonicTime(base::Time::FromInternalValue(61000000));
- reporter_.ReportUpdateAttemptMetrics(&fake_system_state,
- attempt_number,
+ reporter_.ReportUpdateAttemptMetrics(attempt_number,
payload_type,
duration,
duration_uptime,
@@ -539,113 +527,95 @@
}
TEST_F(MetricsReporterOmahaTest, WallclockDurationHelper) {
- FakeSystemState fake_system_state;
FakeClock fake_clock;
base::TimeDelta duration;
const std::string state_variable_key = "test-prefs";
FakePrefs fake_prefs;
- fake_system_state.set_clock(&fake_clock);
- fake_system_state.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_clock(&fake_clock);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
// Initialize wallclock to 1 sec.
fake_clock.SetWallclockTime(base::Time::FromInternalValue(1000000));
// First time called so no previous measurement available.
- EXPECT_FALSE(reporter_.WallclockDurationHelper(
- &fake_system_state, state_variable_key, &duration));
+ EXPECT_FALSE(
+ reporter_.WallclockDurationHelper(state_variable_key, &duration));
// Next time, we should get zero since the clock didn't advance.
- EXPECT_TRUE(reporter_.WallclockDurationHelper(
- &fake_system_state, state_variable_key, &duration));
+ EXPECT_TRUE(reporter_.WallclockDurationHelper(state_variable_key, &duration));
EXPECT_EQ(duration.InSeconds(), 0);
// We can also call it as many times as we want with it being
// considered a failure.
- EXPECT_TRUE(reporter_.WallclockDurationHelper(
- &fake_system_state, state_variable_key, &duration));
+ EXPECT_TRUE(reporter_.WallclockDurationHelper(state_variable_key, &duration));
EXPECT_EQ(duration.InSeconds(), 0);
- EXPECT_TRUE(reporter_.WallclockDurationHelper(
- &fake_system_state, state_variable_key, &duration));
+ EXPECT_TRUE(reporter_.WallclockDurationHelper(state_variable_key, &duration));
EXPECT_EQ(duration.InSeconds(), 0);
// Advance the clock one second, then we should get 1 sec on the
// next call and 0 sec on the subsequent call.
fake_clock.SetWallclockTime(base::Time::FromInternalValue(2000000));
- EXPECT_TRUE(reporter_.WallclockDurationHelper(
- &fake_system_state, state_variable_key, &duration));
+ EXPECT_TRUE(reporter_.WallclockDurationHelper(state_variable_key, &duration));
EXPECT_EQ(duration.InSeconds(), 1);
- EXPECT_TRUE(reporter_.WallclockDurationHelper(
- &fake_system_state, state_variable_key, &duration));
+ EXPECT_TRUE(reporter_.WallclockDurationHelper(state_variable_key, &duration));
EXPECT_EQ(duration.InSeconds(), 0);
// Advance clock two seconds and we should get 2 sec and then 0 sec.
fake_clock.SetWallclockTime(base::Time::FromInternalValue(4000000));
- EXPECT_TRUE(reporter_.WallclockDurationHelper(
- &fake_system_state, state_variable_key, &duration));
+ EXPECT_TRUE(reporter_.WallclockDurationHelper(state_variable_key, &duration));
EXPECT_EQ(duration.InSeconds(), 2);
- EXPECT_TRUE(reporter_.WallclockDurationHelper(
- &fake_system_state, state_variable_key, &duration));
+ EXPECT_TRUE(reporter_.WallclockDurationHelper(state_variable_key, &duration));
EXPECT_EQ(duration.InSeconds(), 0);
// There's a possibility that the wallclock can go backwards (NTP
// adjustments, for example) so check that we properly handle this
// case.
fake_clock.SetWallclockTime(base::Time::FromInternalValue(3000000));
- EXPECT_FALSE(reporter_.WallclockDurationHelper(
- &fake_system_state, state_variable_key, &duration));
+ EXPECT_FALSE(
+ reporter_.WallclockDurationHelper(state_variable_key, &duration));
fake_clock.SetWallclockTime(base::Time::FromInternalValue(4000000));
- EXPECT_TRUE(reporter_.WallclockDurationHelper(
- &fake_system_state, state_variable_key, &duration));
+ EXPECT_TRUE(reporter_.WallclockDurationHelper(state_variable_key, &duration));
EXPECT_EQ(duration.InSeconds(), 1);
}
TEST_F(MetricsReporterOmahaTest, MonotonicDurationHelper) {
int64_t storage = 0;
- FakeSystemState fake_system_state;
FakeClock fake_clock;
base::TimeDelta duration;
- fake_system_state.set_clock(&fake_clock);
+ FakeSystemState::Get()->set_clock(&fake_clock);
// Initialize monotonic clock to 1 sec.
fake_clock.SetMonotonicTime(base::Time::FromInternalValue(1000000));
// First time called so no previous measurement available.
- EXPECT_FALSE(reporter_.MonotonicDurationHelper(
- &fake_system_state, &storage, &duration));
+ EXPECT_FALSE(reporter_.MonotonicDurationHelper(&storage, &duration));
// Next time, we should get zero since the clock didn't advance.
- EXPECT_TRUE(reporter_.MonotonicDurationHelper(
- &fake_system_state, &storage, &duration));
+ EXPECT_TRUE(reporter_.MonotonicDurationHelper(&storage, &duration));
EXPECT_EQ(duration.InSeconds(), 0);
// We can also call it as many times as we want with it being
// considered a failure.
- EXPECT_TRUE(reporter_.MonotonicDurationHelper(
- &fake_system_state, &storage, &duration));
+ EXPECT_TRUE(reporter_.MonotonicDurationHelper(&storage, &duration));
EXPECT_EQ(duration.InSeconds(), 0);
- EXPECT_TRUE(reporter_.MonotonicDurationHelper(
- &fake_system_state, &storage, &duration));
+ EXPECT_TRUE(reporter_.MonotonicDurationHelper(&storage, &duration));
EXPECT_EQ(duration.InSeconds(), 0);
// Advance the clock one second, then we should get 1 sec on the
// next call and 0 sec on the subsequent call.
fake_clock.SetMonotonicTime(base::Time::FromInternalValue(2000000));
- EXPECT_TRUE(reporter_.MonotonicDurationHelper(
- &fake_system_state, &storage, &duration));
+ EXPECT_TRUE(reporter_.MonotonicDurationHelper(&storage, &duration));
EXPECT_EQ(duration.InSeconds(), 1);
- EXPECT_TRUE(reporter_.MonotonicDurationHelper(
- &fake_system_state, &storage, &duration));
+ EXPECT_TRUE(reporter_.MonotonicDurationHelper(&storage, &duration));
EXPECT_EQ(duration.InSeconds(), 0);
// Advance clock two seconds and we should get 2 sec and then 0 sec.
fake_clock.SetMonotonicTime(base::Time::FromInternalValue(4000000));
- EXPECT_TRUE(reporter_.MonotonicDurationHelper(
- &fake_system_state, &storage, &duration));
+ EXPECT_TRUE(reporter_.MonotonicDurationHelper(&storage, &duration));
EXPECT_EQ(duration.InSeconds(), 2);
- EXPECT_TRUE(reporter_.MonotonicDurationHelper(
- &fake_system_state, &storage, &duration));
+ EXPECT_TRUE(reporter_.MonotonicDurationHelper(&storage, &duration));
EXPECT_EQ(duration.InSeconds(), 0);
}
diff --git a/cros/mock_omaha_request_params.h b/cros/mock_omaha_request_params.h
index 6072d22..1e21812 100644
--- a/cros/mock_omaha_request_params.h
+++ b/cros/mock_omaha_request_params.h
@@ -27,8 +27,7 @@
class MockOmahaRequestParams : public OmahaRequestParams {
public:
- explicit MockOmahaRequestParams(SystemState* system_state)
- : OmahaRequestParams(system_state) {
+ MockOmahaRequestParams() : OmahaRequestParams() {
// Delegate all calls to the parent instance by default. This helps the
// migration from tests using the real RequestParams when they should have
// use a fake or mock.
diff --git a/cros/mock_payload_state.h b/cros/mock_payload_state.h
index 56094e6..211b96d 100644
--- a/cros/mock_payload_state.h
+++ b/cros/mock_payload_state.h
@@ -21,14 +21,13 @@
#include <gmock/gmock.h>
-#include "update_engine/common/system_state.h"
#include "update_engine/cros/payload_state_interface.h"
namespace chromeos_update_engine {
class MockPayloadState : public PayloadStateInterface {
public:
- bool Initialize(SystemState* system_state) { return true; }
+ bool Initialize() { return true; }
// Significant methods.
MOCK_METHOD1(SetResponse, void(const OmahaResponse& response));
diff --git a/cros/omaha_request_action.cc b/cros/omaha_request_action.cc
index cad0c67..c3a1a11 100644
--- a/cros/omaha_request_action.cc
+++ b/cros/omaha_request_action.cc
@@ -48,6 +48,7 @@
#include "update_engine/common/platform_constants.h"
#include "update_engine/common/prefs.h"
#include "update_engine/common/prefs_interface.h"
+#include "update_engine/common/system_state.h"
#include "update_engine/common/utils.h"
#include "update_engine/cros/connection_manager_interface.h"
#include "update_engine/cros/omaha_request_builder_xml.h"
@@ -275,13 +276,11 @@
} // namespace
OmahaRequestAction::OmahaRequestAction(
- SystemState* system_state,
OmahaEvent* event,
std::unique_ptr<HttpFetcher> http_fetcher,
bool ping_only,
const string& session_id)
- : system_state_(system_state),
- params_(system_state->request_params()),
+ : params_(SystemState::Get()->request_params()),
event_(event),
http_fetcher_(std::move(http_fetcher)),
policy_provider_(std::make_unique<policy::PolicyProvider>()),
@@ -298,7 +297,8 @@
int OmahaRequestAction::CalculatePingDays(const string& key) {
int days = kPingNeverPinged;
int64_t last_ping = 0;
- if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
+ if (SystemState::Get()->prefs()->GetInt64(key, &last_ping) &&
+ last_ping >= 0) {
days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
if (days < 0) {
// If |days| is negative, then the system clock must have jumped
@@ -329,13 +329,13 @@
bool OmahaRequestAction::ShouldPing() const {
if (ping_active_days_ == kPingNeverPinged &&
ping_roll_call_days_ == kPingNeverPinged) {
- int powerwash_count = system_state_->hardware()->GetPowerwashCount();
+ int powerwash_count = SystemState::Get()->hardware()->GetPowerwashCount();
if (powerwash_count > 0) {
LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
<< "powerwash_count is " << powerwash_count;
return false;
}
- if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
+ if (SystemState::Get()->hardware()->GetFirstActiveOmahaPingSent()) {
LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
<< "the first_active_omaha_ping_sent is true.";
return false;
@@ -346,8 +346,8 @@
}
// static
-int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
- PrefsInterface* prefs = system_state->prefs();
+int OmahaRequestAction::GetInstallDate() {
+ PrefsInterface* prefs = SystemState::Get()->prefs();
if (prefs == nullptr)
return -1;
@@ -383,8 +383,8 @@
// inspecting the timestamp of when OOBE happened.
Time time_of_oobe;
- if (!system_state->hardware()->IsOOBEEnabled() ||
- !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
+ if (!SystemState::Get()->hardware()->IsOOBEEnabled() ||
+ !SystemState::Get()->hardware()->IsOOBEComplete(&time_of_oobe)) {
LOG(INFO) << "Not generating Omaha InstallData as we have "
<< "no prefs file and OOBE is not complete or not enabled.";
return -1;
@@ -399,8 +399,8 @@
}
// Persist this to disk, for future use.
- if (!OmahaRequestAction::PersistInstallDate(
- system_state, num_days, kProvisionedFromOOBEMarker))
+ if (!OmahaRequestAction::PersistInstallDate(num_days,
+ kProvisionedFromOOBEMarker))
return -1;
LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to " << num_days
@@ -422,7 +422,7 @@
if (!dlc_params.send_ping)
continue;
- PrefsInterface* prefs = system_state_->prefs();
+ PrefsInterface* prefs = SystemState::Get()->prefs();
// Reset the active metadata value to |kPingInactiveValue|.
auto active_key =
prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
@@ -462,8 +462,8 @@
ShouldPing(), // include_ping
ping_active_days_,
ping_roll_call_days_,
- GetInstallDate(system_state_),
- system_state_->prefs(),
+ GetInstallDate(),
+ SystemState::Get()->prefs(),
session_id_);
string request_post = omaha_request.GetRequest();
@@ -742,16 +742,14 @@
// element. This is the number of days since Jan 1 2007, 0:00
// PST. If we don't have a persisted value of the Omaha InstallDate,
// we'll use it to calculate it and then persist it.
- if (ParseInstallDate(parser_data, output_object) &&
- !HasInstallDate(system_state_)) {
+ if (ParseInstallDate(parser_data, output_object) && !HasInstallDate()) {
// Since output_object->install_date_days is never negative, the
// elapsed_days -> install-date calculation is reduced to simply
// rounding down to the nearest number divisible by 7.
int remainder = output_object->install_date_days % 7;
int install_date_days_rounded =
output_object->install_date_days - remainder;
- if (PersistInstallDate(system_state_,
- install_date_days_rounded,
+ if (PersistInstallDate(install_date_days_rounded,
kProvisionedFromOmahaResponse)) {
LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
<< install_date_days_rounded << " days.";
@@ -908,7 +906,8 @@
string current_response(response_buffer_.begin(), response_buffer_.end());
LOG(INFO) << "Omaha request response: " << current_response;
- PayloadStateInterface* const payload_state = system_state_->payload_state();
+ PayloadStateInterface* const payload_state =
+ SystemState::Get()->payload_state();
// Set the max kernel key version based on whether rollback is allowed.
SetMaxKernelKeyVersionForRollback();
@@ -924,8 +923,7 @@
if (aux_error_code != ErrorCode::kSuccess) {
metrics::DownloadErrorCode download_error_code =
metrics_utils::GetDownloadErrorCode(aux_error_code);
- system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
- system_state_,
+ SystemState::Get()->metrics_reporter()->ReportUpdateCheckMetrics(
metrics::CheckResult::kUnset,
metrics::CheckReaction::kUnset,
download_error_code);
@@ -976,7 +974,7 @@
// Update the last ping day preferences based on the server daystart response
// even if we didn't send a ping. Omaha always includes the daystart in the
// response, but log the error if it didn't.
- LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
+ LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, SystemState::Get()->prefs()))
<< "Failed to update the last ping day preferences!";
// Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
@@ -985,9 +983,9 @@
// need to check if a=-1 has been sent because older devices have already sent
// their a=-1 in the past and we have to set first_active_omaha_ping_sent for
// future checks.
- if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
- if (!system_state_->hardware()->SetFirstActiveOmahaPingSent()) {
- system_state_->metrics_reporter()->ReportInternalErrorCode(
+ if (!SystemState::Get()->hardware()->GetFirstActiveOmahaPingSent()) {
+ if (!SystemState::Get()->hardware()->SetFirstActiveOmahaPingSent()) {
+ SystemState::Get()->metrics_reporter()->ReportInternalErrorCode(
ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
}
}
@@ -1006,8 +1004,8 @@
if (!ParseResponse(&parser_data, &output_object, &completer))
return;
ProcessExclusions(&output_object,
- system_state_->request_params(),
- system_state_->update_attempter()->GetExcluder());
+ SystemState::Get()->request_params(),
+ SystemState::Get()->update_attempter()->GetExcluder());
output_object.update_exists = true;
SetOutputObject(output_object);
@@ -1071,7 +1069,7 @@
void OmahaRequestAction::CompleteProcessing() {
ScopedActionCompleter completer(processor_, this);
OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
- PayloadStateInterface* payload_state = system_state_->payload_state();
+ PayloadStateInterface* payload_state = SystemState::Get()->payload_state();
if (ShouldDeferDownload(&output_object)) {
output_object.update_exists = false;
@@ -1093,11 +1091,11 @@
void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
if (!url.empty()) {
- system_state_->payload_state()->SetP2PUrl(url);
+ SystemState::Get()->payload_state()->SetP2PUrl(url);
} else {
LOG(INFO) << "Forcibly disabling use of p2p for downloading "
<< "because no suitable peer could be found.";
- system_state_->payload_state()->SetUsingP2PForDownloading(false);
+ SystemState::Get()->payload_state()->SetUsingP2PForDownloading(false);
}
CompleteProcessing();
}
@@ -1121,18 +1119,17 @@
int64_t manifest_signature_size = 0;
int64_t next_data_offset = 0;
int64_t next_data_length = 0;
- if (system_state_ &&
- system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
- &manifest_metadata_size) &&
+ if (SystemState::Get()->prefs()->GetInt64(kPrefsManifestMetadataSize,
+ &manifest_metadata_size) &&
manifest_metadata_size != -1 &&
- system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
- &manifest_signature_size) &&
+ SystemState::Get()->prefs()->GetInt64(kPrefsManifestSignatureSize,
+ &manifest_signature_size) &&
manifest_signature_size != -1 &&
- system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
- &next_data_offset) &&
+ SystemState::Get()->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
+ &next_data_offset) &&
next_data_offset != -1 &&
- system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
- &next_data_length)) {
+ SystemState::Get()->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
+ &next_data_length)) {
minimum_size = manifest_metadata_size + manifest_signature_size +
next_data_offset + next_data_length;
}
@@ -1143,10 +1140,10 @@
return;
string file_id =
utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
- if (system_state_->p2p_manager()) {
+ if (SystemState::Get()->p2p_manager()) {
LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
<< " minimum_size=" << minimum_size;
- system_state_->p2p_manager()->LookupUrlForFile(
+ SystemState::Get()->p2p_manager()->LookupUrlForFile(
file_id,
minimum_size,
TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
@@ -1165,7 +1162,8 @@
// defer the download. This is because the download will always
// happen from a peer on the LAN and we've been waiting in line for
// our turn.
- const PayloadStateInterface* payload_state = system_state_->payload_state();
+ const PayloadStateInterface* payload_state =
+ SystemState::Get()->payload_state();
if (payload_state->GetUsingP2PForDownloading() &&
!payload_state->GetP2PUrl().empty()) {
LOG(INFO) << "Download not deferred because download "
@@ -1222,13 +1220,13 @@
}
TimeDelta elapsed_time =
- system_state_->clock()->GetWallclockTime() - update_first_seen_at;
+ SystemState::Get()->clock()->GetWallclockTime() - update_first_seen_at;
TimeDelta max_scatter_period =
TimeDelta::FromDays(output_object->max_days_to_scatter);
int64_t staging_wait_time_in_days = 0;
// Use staging and its default max value if staging is on.
- if (system_state_->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
- &staging_wait_time_in_days) &&
+ if (SystemState::Get()->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
+ &staging_wait_time_in_days) &&
staging_wait_time_in_days > 0)
max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
@@ -1287,9 +1285,9 @@
bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
int64_t update_check_count_value;
- if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
- if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
- &update_check_count_value)) {
+ if (SystemState::Get()->prefs()->Exists(kPrefsUpdateCheckCount)) {
+ if (!SystemState::Get()->prefs()->GetInt64(kPrefsUpdateCheckCount,
+ &update_check_count_value)) {
// We are unable to read the update check count from file for some reason.
// So let's proceed anyway so as to not stall the update.
LOG(ERROR) << "Unable to read update check count. "
@@ -1307,8 +1305,8 @@
<< update_check_count_value;
// Write out the initial value of update_check_count_value.
- if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
- update_check_count_value)) {
+ if (!SystemState::Get()->prefs()->SetInt64(kPrefsUpdateCheckCount,
+ update_check_count_value)) {
// We weren't able to write the update check count file for some reason.
// So let's proceed anyway so as to not stall the update.
LOG(ERROR) << "Unable to write update check count. "
@@ -1353,8 +1351,8 @@
}
// static
-bool OmahaRequestAction::HasInstallDate(SystemState* system_state) {
- PrefsInterface* prefs = system_state->prefs();
+bool OmahaRequestAction::HasInstallDate() {
+ PrefsInterface* prefs = SystemState::Get()->prefs();
if (prefs == nullptr)
return false;
@@ -1363,19 +1361,18 @@
// static
bool OmahaRequestAction::PersistInstallDate(
- SystemState* system_state,
int install_date_days,
InstallDateProvisioningSource source) {
TEST_AND_RETURN_FALSE(install_date_days >= 0);
- PrefsInterface* prefs = system_state->prefs();
+ PrefsInterface* prefs = SystemState::Get()->prefs();
if (prefs == nullptr)
return false;
if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
return false;
- system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
+ SystemState::Get()->metrics_reporter()->ReportInstallDateProvisioningSource(
static_cast<int>(source), // Sample.
kProvisionedMax); // Maximum.
return true;
@@ -1386,13 +1383,13 @@
if (!new_value)
return;
const string& value = new_value.value();
- if (value.empty() && system_state_->prefs()->Exists(prefs_key)) {
- if (!system_state_->prefs()->Delete(prefs_key))
+ if (value.empty() && SystemState::Get()->prefs()->Exists(prefs_key)) {
+ if (!SystemState::Get()->prefs()->Delete(prefs_key))
LOG(ERROR) << "Failed to remove stored " << prefs_key << "value.";
else
LOG(INFO) << "Removed stored " << prefs_key << " value.";
} else if (!value.empty()) {
- if (!system_state_->prefs()->SetString(prefs_key, value))
+ if (!SystemState::Get()->prefs()->SetString(prefs_key, value))
LOG(INFO) << "Failed to store new setting " << prefs_key << " as "
<< value;
else
@@ -1414,7 +1411,7 @@
<< " as it is not in the request params.";
continue;
}
- PrefsInterface* prefs = system_state_->prefs();
+ PrefsInterface* prefs = SystemState::Get()->prefs();
PersistCohortData(
prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohort}),
app.cohort);
@@ -1436,7 +1433,7 @@
auto eol_date_attr = attrs.find(kAttrEolDate);
if (eol_date_attr != attrs.end()) {
const auto& eol_date = eol_date_attr->second;
- if (!system_state_->prefs()->SetString(kPrefsOmahaEolDate, eol_date)) {
+ if (!SystemState::Get()->prefs()->SetString(kPrefsOmahaEolDate, eol_date)) {
LOG(ERROR) << "Setting EOL date failed.";
return false;
}
@@ -1504,15 +1501,15 @@
break;
}
- system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
- system_state_, result, reaction, download_error_code);
+ SystemState::Get()->metrics_reporter()->ReportUpdateCheckMetrics(
+ result, reaction, download_error_code);
}
bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
ErrorCode* error) const {
// Note: policy decision to not update to a version we rolled back from.
string rollback_version =
- system_state_->payload_state()->GetRollbackVersion();
+ SystemState::Get()->payload_state()->GetRollbackVersion();
if (!rollback_version.empty()) {
LOG(INFO) << "Detected previous rollback from version " << rollback_version;
if (rollback_version == response.version) {
@@ -1522,10 +1519,10 @@
}
}
- if (system_state_->hardware()->IsOOBEEnabled() &&
- !system_state_->hardware()->IsOOBEComplete(nullptr) &&
+ if (SystemState::Get()->hardware()->IsOOBEEnabled() &&
+ !SystemState::Get()->hardware()->IsOOBEComplete(nullptr) &&
(response.deadline.empty() ||
- system_state_->payload_state()->GetRollbackHappened()) &&
+ SystemState::Get()->payload_state()->GetRollbackHappened()) &&
params_->app_version() != "ForcedUpdate") {
LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
*error = ErrorCode::kNonCriticalUpdateInOOBE;
@@ -1557,7 +1554,7 @@
bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
const OmahaResponse& response) const {
- PrefsInterface* prefs = system_state_->prefs();
+ PrefsInterface* prefs = SystemState::Get()->prefs();
if (!prefs) {
LOG(INFO) << "Disabling updates over cellular as the preferences are "
@@ -1614,7 +1611,7 @@
ConnectionType type;
ConnectionTethering tethering;
ConnectionManagerInterface* connection_manager =
- system_state_->connection_manager();
+ SystemState::Get()->connection_manager();
if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
LOG(INFO) << "We could not determine our connection type. "
<< "Defaulting to allow updates.";
@@ -1677,7 +1674,8 @@
void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
int max_kernel_rollforward;
- int min_kernel_version = system_state_->hardware()->GetMinKernelKeyVersion();
+ int min_kernel_version =
+ SystemState::Get()->hardware()->GetMinKernelKeyVersion();
if (IsRollbackEnabled()) {
// If rollback is enabled, set the max kernel key version to the current
// kernel key version. This has the effect of freezing kernel key roll
@@ -1703,22 +1701,22 @@
}
bool max_rollforward_set =
- system_state_->hardware()->SetMaxKernelKeyRollforward(
+ SystemState::Get()->hardware()->SetMaxKernelKeyRollforward(
max_kernel_rollforward);
if (!max_rollforward_set) {
LOG(ERROR) << "Failed to set kernel_max_rollforward";
}
// Report metrics
- system_state_->metrics_reporter()->ReportKeyVersionMetrics(
+ SystemState::Get()->metrics_reporter()->ReportKeyVersionMetrics(
min_kernel_version, max_kernel_rollforward, max_rollforward_set);
}
base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
Time update_first_seen_at;
int64_t update_first_seen_at_int;
- if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
- if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
- &update_first_seen_at_int)) {
+ if (SystemState::Get()->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
+ if (SystemState::Get()->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
+ &update_first_seen_at_int)) {
// Note: This timestamp could be that of ANY update we saw in the past
// (not necessarily this particular update we're considering to apply)
// but never got to apply because of some reason (e.g. stop AU policy,
@@ -1738,10 +1736,10 @@
return base::Time();
}
} else {
- update_first_seen_at = system_state_->clock()->GetWallclockTime();
+ update_first_seen_at = SystemState::Get()->clock()->GetWallclockTime();
update_first_seen_at_int = update_first_seen_at.ToInternalValue();
- if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
- update_first_seen_at_int)) {
+ if (SystemState::Get()->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
+ update_first_seen_at_int)) {
LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
<< utils::ToString(update_first_seen_at);
} else {
diff --git a/cros/omaha_request_action.h b/cros/omaha_request_action.h
index 9576a05..cdfcede 100644
--- a/cros/omaha_request_action.h
+++ b/cros/omaha_request_action.h
@@ -34,7 +34,6 @@
#include "update_engine/common/action.h"
#include "update_engine/common/http_fetcher.h"
-#include "update_engine/common/system_state.h"
#include "update_engine/cros/omaha_request_builder_xml.h"
#include "update_engine/cros/omaha_response.h"
@@ -102,8 +101,7 @@
// OmahaRequestAction(..., new OmahaEvent(...), new WhateverHttpFetcher);
// or
// OmahaRequestAction(..., nullptr, new WhateverHttpFetcher);
- OmahaRequestAction(SystemState* system_state,
- OmahaEvent* event,
+ OmahaRequestAction(OmahaEvent* event,
std::unique_ptr<HttpFetcher> http_fetcher,
bool ping_only,
const std::string& session_id);
@@ -157,7 +155,7 @@
// Gets the install date, expressed as the number of PST8PDT
// calendar weeks since January 1st 2007, times seven. Returns -1 if
// unknown. See http://crbug.com/336838 for details about this value.
- static int GetInstallDate(SystemState* system_state);
+ static int GetInstallDate();
// Parses the Omaha Response in |doc| and sets the
// |install_date_days| field of |output_object| to the value of the
@@ -168,13 +166,12 @@
// Returns True if the kPrefsInstallDateDays state variable is set,
// False otherwise.
- static bool HasInstallDate(SystemState* system_state);
+ static bool HasInstallDate();
// Writes |install_date_days| into the kPrefsInstallDateDays state
// variable and emits an UMA stat for the |source| used. Returns
// True if the value was written, False if an error occurred.
- static bool PersistInstallDate(SystemState* system_state,
- int install_date_days,
+ static bool PersistInstallDate(int install_date_days,
InstallDateProvisioningSource source);
// Persist the new cohort value received in the XML file in the |prefs_key|
@@ -289,9 +286,6 @@
// kPrefsUpdateFirstSeenAt pref and returns it as a base::Time object.
base::Time LoadOrPersistUpdateFirstSeenAtPref() const;
- // Global system context.
- SystemState* system_state_;
-
// Contains state that is relevant in the processing of the Omaha request.
OmahaRequestParams* params_;
diff --git a/cros/omaha_request_action_fuzzer.cc b/cros/omaha_request_action_fuzzer.cc
index dd02467..995de8c 100644
--- a/cros/omaha_request_action_fuzzer.cc
+++ b/cros/omaha_request_action_fuzzer.cc
@@ -31,10 +31,9 @@
brillo::FakeMessageLoop loop(nullptr);
loop.SetAsCurrent();
- chromeos_update_engine::FakeSystemState fake_system_state;
+ chromeos_update_engine::FakeSystemState::CreateInstance();
auto omaha_request_action =
std::make_unique<chromeos_update_engine::OmahaRequestAction>(
- &fake_system_state,
nullptr,
std::make_unique<chromeos_update_engine::MockHttpFetcher>(
data, size, nullptr),
diff --git a/cros/omaha_request_action_unittest.cc b/cros/omaha_request_action_unittest.cc
index 9f9c75f..a3799b4 100644
--- a/cros/omaha_request_action_unittest.cc
+++ b/cros/omaha_request_action_unittest.cc
@@ -135,7 +135,7 @@
}
string GetUpdateResponse() const {
- chromeos_update_engine::OmahaRequestParams request_params{nullptr};
+ chromeos_update_engine::OmahaRequestParams request_params;
request_params.set_app_id(app_id);
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response "
"protocol=\"3.0\">"
@@ -379,6 +379,8 @@
class OmahaRequestActionTest : public ::testing::Test {
protected:
void SetUp() override {
+ FakeSystemState::CreateInstance();
+
request_params_.set_os_sp("service_pack");
request_params_.set_os_board("x86-generic");
request_params_.set_app_id(kTestAppId);
@@ -396,8 +398,8 @@
request_params_.set_is_install(false);
request_params_.set_dlc_apps_params({});
- fake_system_state_.set_request_params(&request_params_);
- fake_system_state_.set_prefs(&fake_prefs_);
+ FakeSystemState::Get()->set_request_params(&request_params_);
+ FakeSystemState::Get()->set_prefs(&fake_prefs_);
// Setting the default update check params. Lookup |TestUpdateCheck()|.
tuc_params_ = {
@@ -413,7 +415,7 @@
.expected_download_error_code = metrics::DownloadErrorCode::kUnset,
};
- ON_CALL(*fake_system_state_.mock_update_attempter(), GetExcluder())
+ ON_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetExcluder())
.WillByDefault(Return(&mock_excluder_));
}
@@ -456,10 +458,9 @@
const string& expected_p2p_url);
StrictMock<MockExcluder> mock_excluder_;
- FakeSystemState fake_system_state_;
FakeUpdateResponse fake_update_response_;
// Used by all tests.
- OmahaRequestParams request_params_{&fake_system_state_};
+ OmahaRequestParams request_params_;
FakePrefs fake_prefs_;
@@ -514,13 +515,12 @@
if (tuc_params_.fail_http_response_code >= 0) {
fetcher->FailTransfer(tuc_params_.fail_http_response_code);
}
- // This ensures the tests didn't forget to update fake_system_state_ if they
+ // This ensures the tests didn't forget to update |FakeSystemState| if they
// are not using the default request_params_.
- EXPECT_EQ(&request_params_, fake_system_state_.request_params());
+ EXPECT_EQ(&request_params_, FakeSystemState::Get()->request_params());
auto omaha_request_action =
- std::make_unique<OmahaRequestAction>(&fake_system_state_,
- nullptr,
+ std::make_unique<OmahaRequestAction>(nullptr,
std::move(fetcher),
tuc_params_.ping_only,
tuc_params_.session_id);
@@ -557,14 +557,13 @@
processor.EnqueueAction(std::move(omaha_request_action));
processor.EnqueueAction(std::move(collector_action));
- EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
- ReportUpdateCheckMetrics(_, _, _, _))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
+ ReportUpdateCheckMetrics(_, _, _))
.Times(AnyNumber());
EXPECT_CALL(
- *fake_system_state_.mock_metrics_reporter(),
- ReportUpdateCheckMetrics(_,
- tuc_params_.expected_check_result,
+ *FakeSystemState::Get()->mock_metrics_reporter(),
+ ReportUpdateCheckMetrics(tuc_params_.expected_check_result,
tuc_params_.expected_check_reaction,
tuc_params_.expected_download_error_code))
.Times(tuc_params_.ping_only ? 0 : 1);
@@ -589,7 +588,6 @@
loop.SetAsCurrent();
auto action = std::make_unique<OmahaRequestAction>(
- &fake_system_state_,
event,
std::make_unique<MockHttpFetcher>(
http_response.data(), http_response.size(), nullptr),
@@ -833,7 +831,7 @@
// Set up a connection manager that doesn't allow a valid update over
// the current ethernet connection.
MockConnectionManager mock_cm;
- fake_system_state_.set_connection_manager(&mock_cm);
+ FakeSystemState::Get()->set_connection_manager(&mock_cm);
EXPECT_CALL(mock_cm, GetConnectionProperties(_, _))
.WillRepeatedly(DoAll(SetArgPointee<0>(ConnectionType::kEthernet),
@@ -855,7 +853,7 @@
// This test tests that update over cellular is allowed as device policy
// says yes.
MockConnectionManager mock_cm;
- fake_system_state_.set_connection_manager(&mock_cm);
+ FakeSystemState::Get()->set_connection_manager(&mock_cm);
EXPECT_CALL(mock_cm, GetConnectionProperties(_, _))
.WillRepeatedly(DoAll(SetArgPointee<0>(ConnectionType::kCellular),
@@ -877,7 +875,7 @@
// This test tests that update over cellular is blocked as device policy
// says no.
MockConnectionManager mock_cm;
- fake_system_state_.set_connection_manager(&mock_cm);
+ FakeSystemState::Get()->set_connection_manager(&mock_cm);
EXPECT_CALL(mock_cm, GetConnectionProperties(_, _))
.WillRepeatedly(DoAll(SetArgPointee<0>(ConnectionType::kCellular),
@@ -903,7 +901,7 @@
// is allowed as permission for update over cellular is set to true.
MockConnectionManager mock_cm;
fake_prefs_.SetBoolean(kPrefsUpdateOverCellularPermission, true);
- fake_system_state_.set_connection_manager(&mock_cm);
+ FakeSystemState::Get()->set_connection_manager(&mock_cm);
EXPECT_CALL(mock_cm, GetConnectionProperties(_, _))
.WillRepeatedly(DoAll(SetArgPointee<0>(ConnectionType::kCellular),
@@ -935,7 +933,7 @@
fake_prefs_.SetString(kPrefsUpdateOverCellularTargetVersion, diff_version);
fake_prefs_.SetInt64(kPrefsUpdateOverCellularTargetSize, diff_size);
// This test tests cellular (3G) being the only connection type being allowed.
- fake_system_state_.set_connection_manager(&mock_cm);
+ FakeSystemState::Get()->set_connection_manager(&mock_cm);
EXPECT_CALL(mock_cm, GetConnectionProperties(_, _))
.WillRepeatedly(DoAll(SetArgPointee<0>(ConnectionType::kCellular),
@@ -968,7 +966,7 @@
fake_prefs_.SetString(kPrefsUpdateOverCellularTargetVersion, new_version);
fake_prefs_.SetInt64(kPrefsUpdateOverCellularTargetSize, new_size);
- fake_system_state_.set_connection_manager(&mock_cm);
+ FakeSystemState::Get()->set_connection_manager(&mock_cm);
EXPECT_CALL(mock_cm, GetConnectionProperties(_, _))
.WillRepeatedly(DoAll(SetArgPointee<0>(ConnectionType::kCellular),
@@ -989,7 +987,7 @@
TEST_F(OmahaRequestActionTest, ValidUpdateBlockedByRollback) {
string rollback_version = "1234.0.0";
MockPayloadState mock_payload_state;
- fake_system_state_.set_payload_state(&mock_payload_state);
+ FakeSystemState::Get()->set_payload_state(&mock_payload_state);
fake_update_response_.version = rollback_version;
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
tuc_params_.expected_code = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
@@ -1006,7 +1004,7 @@
// Verify that update checks called during OOBE will not try to download an
// update if the response doesn't include the deadline field.
TEST_F(OmahaRequestActionTest, SkipNonCriticalUpdatesBeforeOOBE) {
- fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
+ FakeSystemState::Get()->fake_hardware()->UnsetIsOOBEComplete();
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
tuc_params_.expected_code = ErrorCode::kNonCriticalUpdateInOOBE;
tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
@@ -1022,8 +1020,8 @@
// Verify that the IsOOBEComplete() value is ignored when the OOBE flow is not
// enabled.
TEST_F(OmahaRequestActionTest, SkipNonCriticalUpdatesBeforeOOBEDisabled) {
- fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
- fake_system_state_.fake_hardware()->SetIsOOBEEnabled(false);
+ FakeSystemState::Get()->fake_hardware()->UnsetIsOOBEComplete();
+ FakeSystemState::Get()->fake_hardware()->SetIsOOBEEnabled(false);
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
ASSERT_TRUE(TestUpdateCheck());
@@ -1034,7 +1032,7 @@
// Verify that update checks called during OOBE will still try to download an
// update if the response includes the deadline field.
TEST_F(OmahaRequestActionTest, SkipNonCriticalUpdatesBeforeOOBEDeadlineSet) {
- fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
+ FakeSystemState::Get()->fake_hardware()->UnsetIsOOBEComplete();
fake_update_response_.deadline = "20101020";
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
@@ -1047,14 +1045,15 @@
// update if a rollback happened, even when the response includes the deadline
// field.
TEST_F(OmahaRequestActionTest, SkipNonCriticalUpdatesBeforeOOBERollback) {
- fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
+ FakeSystemState::Get()->fake_hardware()->UnsetIsOOBEComplete();
fake_update_response_.deadline = "20101020";
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
tuc_params_.expected_code = ErrorCode::kNonCriticalUpdateInOOBE;
tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
- EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetRollbackHappened())
+ EXPECT_CALL(*(FakeSystemState::Get()->mock_payload_state()),
+ GetRollbackHappened())
.WillOnce(Return(true));
ASSERT_FALSE(TestUpdateCheck());
@@ -1068,10 +1067,10 @@
// kOmahaUpdateIgnoredOverCellular error in this case might cause undesired UX
// in OOBE (warning the user about an update that will be skipped).
TEST_F(OmahaRequestActionTest, SkipNonCriticalUpdatesInOOBEOverCellular) {
- fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
+ FakeSystemState::Get()->fake_hardware()->UnsetIsOOBEComplete();
MockConnectionManager mock_cm;
- fake_system_state_.set_connection_manager(&mock_cm);
+ FakeSystemState::Get()->set_connection_manager(&mock_cm);
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
tuc_params_.expected_code = ErrorCode::kNonCriticalUpdateInOOBE;
tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
@@ -1093,7 +1092,7 @@
request_params_.set_wall_clock_based_wait_enabled(true);
request_params_.set_update_check_count_wait_enabled(false);
request_params_.set_waiting_period(TimeDelta::FromDays(2));
- fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
+ FakeSystemState::Get()->fake_clock()->SetWallclockTime(Time::Now());
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
tuc_params_.expected_code = ErrorCode::kOmahaUpdateDeferredPerPolicy;
tuc_params_.expected_check_reaction = metrics::CheckReaction::kDeferring;
@@ -1109,7 +1108,7 @@
request_params_.set_update_check_count_wait_enabled(false);
request_params_.set_waiting_period(TimeDelta::FromDays(2));
request_params_.set_interactive(true);
- fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
+ FakeSystemState::Get()->fake_clock()->SetWallclockTime(Time::Now());
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
// Verify if we are interactive check we don't defer.
@@ -1151,7 +1150,7 @@
request_params_.set_update_check_count_wait_enabled(true);
request_params_.set_min_update_checks_needed(0);
request_params_.set_max_update_checks_allowed(0);
- fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
+ FakeSystemState::Get()->fake_clock()->SetWallclockTime(Time::Now());
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
ASSERT_TRUE(TestUpdateCheck());
@@ -1168,7 +1167,7 @@
request_params_.set_update_check_count_wait_enabled(true);
request_params_.set_min_update_checks_needed(1);
request_params_.set_max_update_checks_allowed(8);
- fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
+ FakeSystemState::Get()->fake_clock()->SetWallclockTime(Time::Now());
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
tuc_params_.expected_code = ErrorCode::kOmahaUpdateDeferredPerPolicy;
tuc_params_.expected_check_reaction = metrics::CheckReaction::kDeferring;
@@ -1189,7 +1188,7 @@
request_params_.set_min_update_checks_needed(1);
request_params_.set_max_update_checks_allowed(8);
request_params_.set_interactive(true);
- fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
+ FakeSystemState::Get()->fake_clock()->SetWallclockTime(Time::Now());
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
// Verify if we are interactive check we don't defer.
@@ -1204,7 +1203,7 @@
request_params_.set_update_check_count_wait_enabled(true);
request_params_.set_min_update_checks_needed(1);
request_params_.set_max_update_checks_allowed(8);
- fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
+ FakeSystemState::Get()->fake_clock()->SetWallclockTime(Time::Now());
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
tuc_params_.expected_code = ErrorCode::kOmahaUpdateDeferredPerPolicy;
tuc_params_.expected_check_reaction = metrics::CheckReaction::kDeferring;
@@ -1228,7 +1227,7 @@
request_params_.set_min_update_checks_needed(1);
request_params_.set_max_update_checks_allowed(8);
request_params_.set_interactive(true);
- fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
+ FakeSystemState::Get()->fake_clock()->SetWallclockTime(Time::Now());
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
ASSERT_TRUE(fake_prefs_.SetInt64(kPrefsUpdateCheckCount, 5));
@@ -1244,7 +1243,7 @@
request_params_.set_wall_clock_based_wait_enabled(true);
request_params_.set_waiting_period(TimeDelta::FromDays(6));
request_params_.set_update_check_count_wait_enabled(false);
- fake_system_state_.fake_clock()->SetWallclockTime(Time::Now());
+ FakeSystemState::Get()->fake_clock()->SetWallclockTime(Time::Now());
ASSERT_TRUE(fake_prefs_.SetInt64(kPrefsWallClockStagingWaitPeriod, 6));
// This should not prevent scattering due to staging.
@@ -1478,7 +1477,6 @@
loop.SetAsCurrent();
auto action = std::make_unique<OmahaRequestAction>(
- &fake_system_state_,
nullptr,
std::make_unique<MockHttpFetcher>(
http_response.data(), http_response.size(), nullptr),
@@ -1614,7 +1612,6 @@
string http_response("doesn't matter");
auto action = std::make_unique<OmahaRequestAction>(
- &fake_system_state_,
nullptr,
std::make_unique<MockHttpFetcher>(
http_response.data(), http_response.size(), nullptr),
@@ -1693,7 +1690,7 @@
TEST_F(OmahaRequestActionTest, FormatUpdateCheckOutputTest) {
NiceMock<MockPrefs> prefs;
- fake_system_state_.set_prefs(&prefs);
+ FakeSystemState::Get()->set_prefs(&prefs);
tuc_params_.http_response = "invalid xml>";
tuc_params_.expected_code = ErrorCode::kOmahaRequestXMLParseError;
tuc_params_.expected_check_result = metrics::CheckResult::kParsingError;
@@ -1748,7 +1745,6 @@
TEST_F(OmahaRequestActionTest, IsEventTest) {
string http_response("doesn't matter");
OmahaRequestAction update_check_action(
- &fake_system_state_,
nullptr,
std::make_unique<MockHttpFetcher>(
http_response.data(), http_response.size(), nullptr),
@@ -1757,7 +1753,6 @@
EXPECT_FALSE(update_check_action.IsEvent());
OmahaRequestAction event_action(
- &fake_system_state_,
new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
std::make_unique<MockHttpFetcher>(
http_response.data(), http_response.size(), nullptr),
@@ -1923,7 +1918,7 @@
void OmahaRequestActionTest::PingTest(bool ping_only) {
NiceMock<MockPrefs> prefs;
- fake_system_state_.set_prefs(&prefs);
+ FakeSystemState::Get()->set_prefs(&prefs);
EXPECT_CALL(prefs, GetInt64(kPrefsMetricsCheckLastReportingTime, _))
.Times(AnyNumber());
EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
@@ -1967,7 +1962,7 @@
TEST_F(OmahaRequestActionTest, ActivePingTest) {
NiceMock<MockPrefs> prefs;
- fake_system_state_.set_prefs(&prefs);
+ FakeSystemState::Get()->set_prefs(&prefs);
EXPECT_CALL(prefs, GetInt64(kPrefsMetricsCheckLastReportingTime, _))
.Times(AnyNumber());
EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
@@ -1992,7 +1987,7 @@
TEST_F(OmahaRequestActionTest, RollCallPingTest) {
NiceMock<MockPrefs> prefs;
- fake_system_state_.set_prefs(&prefs);
+ FakeSystemState::Get()->set_prefs(&prefs);
EXPECT_CALL(prefs, GetInt64(kPrefsMetricsCheckLastReportingTime, _))
.Times(AnyNumber());
EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
@@ -2018,7 +2013,7 @@
TEST_F(OmahaRequestActionTest, NoPingTest) {
NiceMock<MockPrefs> prefs;
- fake_system_state_.set_prefs(&prefs);
+ FakeSystemState::Get()->set_prefs(&prefs);
EXPECT_CALL(prefs, GetInt64(kPrefsMetricsCheckLastReportingTime, _))
.Times(AnyNumber());
EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
@@ -2049,7 +2044,7 @@
TEST_F(OmahaRequestActionTest, IgnoreEmptyPingTest) {
// This test ensures that we ignore empty ping only requests.
NiceMock<MockPrefs> prefs;
- fake_system_state_.set_prefs(&prefs);
+ FakeSystemState::Get()->set_prefs(&prefs);
int64_t now = Time::Now().ToInternalValue();
EXPECT_CALL(prefs, GetInt64(kPrefsLastActivePingDay, _))
.WillOnce(DoAll(SetArgPointee<1>(now), Return(true)));
@@ -2069,7 +2064,7 @@
TEST_F(OmahaRequestActionTest, BackInTimePingTest) {
NiceMock<MockPrefs> prefs;
- fake_system_state_.set_prefs(&prefs);
+ FakeSystemState::Get()->set_prefs(&prefs);
EXPECT_CALL(prefs, GetInt64(kPrefsMetricsCheckLastReportingTime, _))
.Times(AnyNumber());
EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
@@ -2108,7 +2103,7 @@
int64_t midnight_slack =
(Time::Now() - TimeDelta::FromSeconds(195)).ToInternalValue();
NiceMock<MockPrefs> prefs;
- fake_system_state_.set_prefs(&prefs);
+ FakeSystemState::Get()->set_prefs(&prefs);
EXPECT_CALL(prefs, GetInt64(_, _)).Times(AnyNumber());
EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
EXPECT_CALL(prefs,
@@ -2133,7 +2128,7 @@
TEST_F(OmahaRequestActionTest, NoElapsedSecondsTest) {
NiceMock<MockPrefs> prefs;
- fake_system_state_.set_prefs(&prefs);
+ FakeSystemState::Get()->set_prefs(&prefs);
EXPECT_CALL(prefs, GetInt64(_, _)).Times(AnyNumber());
EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
EXPECT_CALL(prefs, SetInt64(kPrefsLastActivePingDay, _)).Times(0);
@@ -2152,7 +2147,7 @@
TEST_F(OmahaRequestActionTest, BadElapsedSecondsTest) {
NiceMock<MockPrefs> prefs;
- fake_system_state_.set_prefs(&prefs);
+ FakeSystemState::Get()->set_prefs(&prefs);
EXPECT_CALL(prefs, GetInt64(_, _)).Times(AnyNumber());
EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
EXPECT_CALL(prefs, SetInt64(kPrefsLastActivePingDay, _)).Times(0);
@@ -2218,7 +2213,7 @@
Time arbitrary_date;
ASSERT_TRUE(Time::FromString("6/4/1989", &arbitrary_date));
- fake_system_state_.fake_clock()->SetWallclockTime(arbitrary_date);
+ FakeSystemState::Get()->fake_clock()->SetWallclockTime(arbitrary_date);
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
tuc_params_.expected_code = ErrorCode::kOmahaUpdateDeferredPerPolicy;
@@ -2250,7 +2245,7 @@
ASSERT_TRUE(Time::FromString("1/3/2012", &t2));
ASSERT_TRUE(
fake_prefs_.SetInt64(kPrefsUpdateFirstSeenAt, t1.ToInternalValue()));
- fake_system_state_.fake_clock()->SetWallclockTime(t2);
+ FakeSystemState::Get()->fake_clock()->SetWallclockTime(t2);
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
@@ -2330,7 +2325,7 @@
fake_prefs_.SetString(kPrefsPreviousVersion, "");
// Flag that the device was powerwashed in the past.
- fake_system_state_.fake_hardware()->SetPowerwashCount(1);
+ FakeSystemState::Get()->fake_hardware()->SetPowerwashCount(1);
tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
@@ -2347,10 +2342,10 @@
fake_prefs_.SetString(kPrefsPreviousVersion, "");
// Flag that the device was not powerwashed in the past.
- fake_system_state_.fake_hardware()->SetPowerwashCount(0);
+ FakeSystemState::Get()->fake_hardware()->SetPowerwashCount(0);
// Flag that the device has sent first active ping in the past.
- fake_system_state_.fake_hardware()->SetFirstActiveOmahaPingSent();
+ FakeSystemState::Get()->fake_hardware()->SetFirstActiveOmahaPingSent();
tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
@@ -2404,7 +2399,7 @@
string actual_p2p_url;
MockPayloadState mock_payload_state;
- fake_system_state_.set_payload_state(&mock_payload_state);
+ FakeSystemState::Get()->set_payload_state(&mock_payload_state);
EXPECT_CALL(mock_payload_state, P2PAttemptAllowed())
.WillRepeatedly(Return(payload_state_allow_p2p_attempt));
EXPECT_CALL(mock_payload_state, GetUsingP2PForDownloading())
@@ -2419,7 +2414,7 @@
.WillRepeatedly(SaveArg<0>(&actual_p2p_url));
MockP2PManager mock_p2p_manager;
- fake_system_state_.set_p2p_manager(&mock_p2p_manager);
+ FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
mock_p2p_manager.fake().SetLookupUrlForFileResult(p2p_client_result_url);
TimeDelta timeout = TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds);
@@ -2537,7 +2532,7 @@
// deadline in the response is needed to force the update attempt to
// occur; responses without a deadline seen during OOBE will normally
// return ErrorCode::kNonCriticalUpdateInOOBE.
- fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
+ FakeSystemState::Get()->fake_hardware()->UnsetIsOOBEComplete();
fake_update_response_.deadline = "20101020";
// Check that we parse elapsed_days in the Omaha Response correctly.
@@ -2577,8 +2572,8 @@
// If there is no prefs and OOBE is not complete, we should not
// report anything to Omaha.
TEST_F(OmahaRequestActionTest, GetInstallDateWhenNoPrefsNorOOBE) {
- fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
- EXPECT_EQ(OmahaRequestAction::GetInstallDate(&fake_system_state_), -1);
+ FakeSystemState::Get()->fake_hardware()->UnsetIsOOBEComplete();
+ EXPECT_EQ(OmahaRequestAction::GetInstallDate(), -1);
EXPECT_FALSE(fake_prefs_.Exists(kPrefsInstallDateDays));
}
@@ -2588,8 +2583,8 @@
// nothing.
TEST_F(OmahaRequestActionTest, GetInstallDateWhenOOBECompletedWithInvalidDate) {
Time oobe_date = Time::FromTimeT(42); // Dec 31, 1969 16:00:42 PST.
- fake_system_state_.fake_hardware()->SetIsOOBEComplete(oobe_date);
- EXPECT_EQ(OmahaRequestAction::GetInstallDate(&fake_system_state_), -1);
+ FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(oobe_date);
+ EXPECT_EQ(OmahaRequestAction::GetInstallDate(), -1);
EXPECT_FALSE(fake_prefs_.Exists(kPrefsInstallDateDays));
}
@@ -2597,8 +2592,8 @@
// should yield an InstallDate of 14.
TEST_F(OmahaRequestActionTest, GetInstallDateWhenOOBECompletedWithValidDate) {
Time oobe_date = Time::FromTimeT(1169280000); // Jan 20, 2007 0:00 PST.
- fake_system_state_.fake_hardware()->SetIsOOBEComplete(oobe_date);
- EXPECT_EQ(OmahaRequestAction::GetInstallDate(&fake_system_state_), 14);
+ FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(oobe_date);
+ EXPECT_EQ(OmahaRequestAction::GetInstallDate(), 14);
EXPECT_TRUE(fake_prefs_.Exists(kPrefsInstallDateDays));
int64_t prefs_days;
@@ -2615,8 +2610,8 @@
EXPECT_TRUE(fake_prefs_.SetInt64(kPrefsInstallDateDays, 14));
Time oobe_date = Time::FromTimeT(1170144000); // Jan 30, 2007 0:00 PST.
- fake_system_state_.fake_hardware()->SetIsOOBEComplete(oobe_date);
- EXPECT_EQ(OmahaRequestAction::GetInstallDate(&fake_system_state_), 14);
+ FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(oobe_date);
+ EXPECT_EQ(OmahaRequestAction::GetInstallDate(), 14);
int64_t prefs_days;
EXPECT_TRUE(fake_prefs_.GetInt64(kPrefsInstallDateDays, &prefs_days));
@@ -2624,7 +2619,7 @@
// If we delete the prefs file, we should get 28 days.
EXPECT_TRUE(fake_prefs_.Delete(kPrefsInstallDateDays));
- EXPECT_EQ(OmahaRequestAction::GetInstallDate(&fake_system_state_), 28);
+ EXPECT_EQ(OmahaRequestAction::GetInstallDate(), 28);
EXPECT_TRUE(fake_prefs_.GetInt64(kPrefsInstallDateDays, &prefs_days));
EXPECT_EQ(prefs_days, 28);
}
@@ -2633,7 +2628,7 @@
// device sets the max kernel key version to the current version.
// ie. the same behavior as if rollback is enabled.
TEST_F(OmahaRequestActionTest, NoPolicyEnterpriseDevicesSetMaxRollback) {
- FakeHardware* fake_hw = fake_system_state_.fake_hardware();
+ FakeHardware* fake_hw = FakeSystemState::Get()->fake_hardware();
// Setup and verify some initial default values for the kernel TPM
// values that control verified boot and rollback.
@@ -2644,7 +2639,7 @@
EXPECT_EQ(kRollforwardInfinity, fake_hw->GetMaxKernelKeyRollforward());
EXPECT_CALL(
- *fake_system_state_.mock_metrics_reporter(),
+ *FakeSystemState::Get()->mock_metrics_reporter(),
ReportKeyVersionMetrics(min_kernel_version, min_kernel_version, true))
.Times(1);
@@ -2669,7 +2664,7 @@
// max kernel key version to the current version. ie. the same
// behavior as if rollback is enabled.
TEST_F(OmahaRequestActionTest, NoPolicyConsumerDevicesSetMaxRollback) {
- FakeHardware* fake_hw = fake_system_state_.fake_hardware();
+ FakeHardware* fake_hw = FakeSystemState::Get()->fake_hardware();
// Setup and verify some initial default values for the kernel TPM
// values that control verified boot and rollback.
@@ -2680,7 +2675,7 @@
EXPECT_EQ(kRollforwardInfinity, fake_hw->GetMaxKernelKeyRollforward());
EXPECT_CALL(
- *fake_system_state_.mock_metrics_reporter(),
+ *FakeSystemState::Get()->mock_metrics_reporter(),
ReportKeyVersionMetrics(min_kernel_version, kRollforwardInfinity, true))
.Times(1);
@@ -2703,7 +2698,7 @@
// Verifies that a device with rollback enabled sets kernel_max_rollforward
// in the TPM to prevent roll forward.
TEST_F(OmahaRequestActionTest, RollbackEnabledDevicesSetMaxRollback) {
- FakeHardware* fake_hw = fake_system_state_.fake_hardware();
+ FakeHardware* fake_hw = FakeSystemState::Get()->fake_hardware();
// Setup and verify some initial default values for the kernel TPM
// values that control verified boot and rollback.
@@ -2715,7 +2710,7 @@
EXPECT_EQ(kRollforwardInfinity, fake_hw->GetMaxKernelKeyRollforward());
EXPECT_CALL(
- *fake_system_state_.mock_metrics_reporter(),
+ *FakeSystemState::Get()->mock_metrics_reporter(),
ReportKeyVersionMetrics(min_kernel_version, min_kernel_version, true))
.Times(1);
@@ -2740,7 +2735,7 @@
// Verifies that a device with rollback disabled sets kernel_max_rollforward
// in the TPM to logical infinity, to allow roll forward.
TEST_F(OmahaRequestActionTest, RollbackDisabledDevicesSetMaxRollback) {
- FakeHardware* fake_hw = fake_system_state_.fake_hardware();
+ FakeHardware* fake_hw = FakeSystemState::Get()->fake_hardware();
// Setup and verify some initial default values for the kernel TPM
// values that control verified boot and rollback.
@@ -2752,7 +2747,7 @@
EXPECT_EQ(kRollforwardInfinity, fake_hw->GetMaxKernelKeyRollforward());
EXPECT_CALL(
- *fake_system_state_.mock_metrics_reporter(),
+ *FakeSystemState::Get()->mock_metrics_reporter(),
ReportKeyVersionMetrics(min_kernel_version, kRollforwardInfinity, true))
.Times(1);
@@ -2808,7 +2803,7 @@
FakeClock fake_clock;
Time now = Time::Now();
fake_clock.SetWallclockTime(now);
- fake_system_state_.set_clock(&fake_clock);
+ FakeSystemState::Get()->set_clock(&fake_clock);
tuc_params_.http_response = fake_update_response_.GetUpdateResponse();
ASSERT_TRUE(TestUpdateCheck());
@@ -2827,7 +2822,7 @@
FakeClock fake_clock;
Time now = Time::Now();
fake_clock.SetWallclockTime(now);
- fake_system_state_.set_clock(&fake_clock);
+ FakeSystemState::Get()->set_clock(&fake_clock);
tuc_params_.http_response = fake_update_response_.GetNoUpdateResponse();
tuc_params_.expected_check_result = metrics::CheckResult::kNoUpdateAvailable;
@@ -3053,8 +3048,8 @@
ASSERT_TRUE(TestUpdateCheck());
string eol_date;
- EXPECT_TRUE(
- fake_system_state_.prefs()->GetString(kPrefsOmahaEolDate, &eol_date));
+ EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetString(kPrefsOmahaEolDate,
+ &eol_date));
EXPECT_EQ("200", eol_date);
}
@@ -3068,13 +3063,13 @@
tuc_params_.expected_check_reaction = metrics::CheckReaction::kUnset;
const string kDate = "123";
- fake_system_state_.prefs()->SetString(kPrefsOmahaEolDate, kDate);
+ FakeSystemState::Get()->prefs()->SetString(kPrefsOmahaEolDate, kDate);
ASSERT_TRUE(TestUpdateCheck());
string eol_date;
- EXPECT_TRUE(
- fake_system_state_.prefs()->GetString(kPrefsOmahaEolDate, &eol_date));
+ EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetString(kPrefsOmahaEolDate,
+ &eol_date));
EXPECT_EQ(kDate, eol_date);
}
@@ -3090,8 +3085,8 @@
ASSERT_TRUE(TestUpdateCheck());
string eol_date;
- EXPECT_TRUE(
- fake_system_state_.prefs()->GetString(kPrefsOmahaEolDate, &eol_date));
+ EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetString(kPrefsOmahaEolDate,
+ &eol_date));
EXPECT_EQ(kEolDateInvalid, StringToEolDate(eol_date));
}
diff --git a/cros/omaha_request_builder_xml.h b/cros/omaha_request_builder_xml.h
index 0aca7f3..6bbc84e 100644
--- a/cros/omaha_request_builder_xml.h
+++ b/cros/omaha_request_builder_xml.h
@@ -33,7 +33,6 @@
#include "update_engine/common/action.h"
#include "update_engine/common/http_fetcher.h"
-#include "update_engine/common/system_state.h"
#include "update_engine/cros/omaha_request_params.h"
#include "update_engine/cros/omaha_response.h"
diff --git a/cros/omaha_request_builder_xml_unittest.cc b/cros/omaha_request_builder_xml_unittest.cc
index c04c994..74d616d 100644
--- a/cros/omaha_request_builder_xml_unittest.cc
+++ b/cros/omaha_request_builder_xml_unittest.cc
@@ -61,10 +61,9 @@
class OmahaRequestBuilderXmlTest : public ::testing::Test {
protected:
- void SetUp() override {}
+ void SetUp() override { FakeSystemState::CreateInstance(); }
void TearDown() override {}
- FakeSystemState fake_system_state_;
static constexpr size_t kGuidSize = 36;
};
@@ -94,7 +93,7 @@
}
TEST_F(OmahaRequestBuilderXmlTest, PlatformGetAppTest) {
- OmahaRequestParams omaha_request_params{&fake_system_state_};
+ OmahaRequestParams omaha_request_params;
omaha_request_params.set_device_requisition("device requisition");
OmahaRequestBuilderXml omaha_request{nullptr,
&omaha_request_params,
@@ -103,7 +102,7 @@
0,
0,
0,
- fake_system_state_.prefs(),
+ FakeSystemState::Get()->prefs(),
""};
OmahaAppData dlc_app_data = {.id = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
.version = "",
@@ -118,7 +117,7 @@
}
TEST_F(OmahaRequestBuilderXmlTest, DlcGetAppTest) {
- OmahaRequestParams omaha_request_params{&fake_system_state_};
+ OmahaRequestParams omaha_request_params;
omaha_request_params.set_device_requisition("device requisition");
OmahaRequestBuilderXml omaha_request{nullptr,
&omaha_request_params,
@@ -127,7 +126,7 @@
0,
0,
0,
- fake_system_state_.prefs(),
+ FakeSystemState::Get()->prefs(),
""};
OmahaAppData dlc_app_data = {
.id = "_dlc_id", .version = "", .skip_update = false, .is_dlc = true};
@@ -140,7 +139,7 @@
}
TEST_F(OmahaRequestBuilderXmlTest, GetRequestXmlRequestIdTest) {
- OmahaRequestParams omaha_request_params{&fake_system_state_};
+ OmahaRequestParams omaha_request_params;
OmahaRequestBuilderXml omaha_request{nullptr,
&omaha_request_params,
false,
@@ -148,7 +147,7 @@
0,
0,
0,
- fake_system_state_.prefs(),
+ FakeSystemState::Get()->prefs(),
""};
const string request_xml = omaha_request.GetRequest();
const string key = "requestid";
@@ -161,7 +160,7 @@
TEST_F(OmahaRequestBuilderXmlTest, GetRequestXmlSessionIdTest) {
const string gen_session_id = base::GenerateGUID();
- OmahaRequestParams omaha_request_params{&fake_system_state_};
+ OmahaRequestParams omaha_request_params;
OmahaRequestBuilderXml omaha_request{nullptr,
&omaha_request_params,
false,
@@ -169,7 +168,7 @@
0,
0,
0,
- fake_system_state_.prefs(),
+ FakeSystemState::Get()->prefs(),
gen_session_id};
const string request_xml = omaha_request.GetRequest();
const string key = "sessionid";
@@ -183,7 +182,7 @@
}
TEST_F(OmahaRequestBuilderXmlTest, GetRequestXmlPlatformUpdateTest) {
- OmahaRequestParams omaha_request_params{&fake_system_state_};
+ OmahaRequestParams omaha_request_params;
OmahaRequestBuilderXml omaha_request{nullptr,
&omaha_request_params,
false,
@@ -191,7 +190,7 @@
0,
0,
0,
- fake_system_state_.prefs(),
+ FakeSystemState::Get()->prefs(),
""};
const string request_xml = omaha_request.GetRequest();
EXPECT_EQ(1, CountSubstringInString(request_xml, "<updatecheck"))
@@ -199,7 +198,7 @@
}
TEST_F(OmahaRequestBuilderXmlTest, GetRequestXmlPlatformUpdateWithDlcsTest) {
- OmahaRequestParams omaha_request_params{&fake_system_state_};
+ OmahaRequestParams omaha_request_params;
omaha_request_params.set_dlc_apps_params(
{{omaha_request_params.GetDlcAppId("dlc_no_0"), {.name = "dlc_no_0"}},
{omaha_request_params.GetDlcAppId("dlc_no_1"), {.name = "dlc_no_1"}}});
@@ -210,7 +209,7 @@
0,
0,
0,
- fake_system_state_.prefs(),
+ FakeSystemState::Get()->prefs(),
""};
const string request_xml = omaha_request.GetRequest();
EXPECT_EQ(3, CountSubstringInString(request_xml, "<updatecheck"))
@@ -218,7 +217,7 @@
}
TEST_F(OmahaRequestBuilderXmlTest, GetRequestXmlDlcInstallationTest) {
- OmahaRequestParams omaha_request_params{&fake_system_state_};
+ OmahaRequestParams omaha_request_params;
const std::map<std::string, OmahaRequestParams::AppParams> dlcs = {
{omaha_request_params.GetDlcAppId("dlc_no_0"), {.name = "dlc_no_0"}},
{omaha_request_params.GetDlcAppId("dlc_no_1"), {.name = "dlc_no_1"}}};
@@ -231,7 +230,7 @@
0,
0,
0,
- fake_system_state_.prefs(),
+ FakeSystemState::Get()->prefs(),
""};
const string request_xml = omaha_request.GetRequest();
EXPECT_EQ(2, CountSubstringInString(request_xml, "<updatecheck"))
@@ -257,7 +256,7 @@
}
TEST_F(OmahaRequestBuilderXmlTest, GetRequestXmlDlcNoPing) {
- OmahaRequestParams omaha_request_params{&fake_system_state_};
+ OmahaRequestParams omaha_request_params;
omaha_request_params.set_dlc_apps_params(
{{omaha_request_params.GetDlcAppId("dlc_no_0"), {.name = "dlc_no_0"}}});
OmahaRequestBuilderXml omaha_request{nullptr,
@@ -267,14 +266,14 @@
0,
0,
0,
- fake_system_state_.prefs(),
+ FakeSystemState::Get()->prefs(),
""};
const string request_xml = omaha_request.GetRequest();
EXPECT_EQ(0, CountSubstringInString(request_xml, "<ping")) << request_xml;
}
TEST_F(OmahaRequestBuilderXmlTest, GetRequestXmlDlcPingRollCallNoActive) {
- OmahaRequestParams omaha_request_params{&fake_system_state_};
+ OmahaRequestParams omaha_request_params;
omaha_request_params.set_dlc_apps_params(
{{omaha_request_params.GetDlcAppId("dlc_no_0"),
{.active_counting_type = OmahaRequestParams::kDateBased,
@@ -289,7 +288,7 @@
0,
0,
0,
- fake_system_state_.prefs(),
+ FakeSystemState::Get()->prefs(),
""};
const string request_xml = omaha_request.GetRequest();
EXPECT_EQ(1, CountSubstringInString(request_xml, "<ping rd=\"36\""))
@@ -297,7 +296,7 @@
}
TEST_F(OmahaRequestBuilderXmlTest, GetRequestXmlDlcPingRollCallAndActive) {
- OmahaRequestParams omaha_request_params{&fake_system_state_};
+ OmahaRequestParams omaha_request_params;
omaha_request_params.set_dlc_apps_params(
{{omaha_request_params.GetDlcAppId("dlc_no_0"),
{.active_counting_type = OmahaRequestParams::kDateBased,
@@ -313,7 +312,7 @@
0,
0,
0,
- fake_system_state_.prefs(),
+ FakeSystemState::Get()->prefs(),
""};
const string request_xml = omaha_request.GetRequest();
EXPECT_EQ(1,
@@ -323,7 +322,7 @@
}
TEST_F(OmahaRequestBuilderXmlTest, GetRequestXmlUpdateCompleteEvent) {
- OmahaRequestParams omaha_request_params{&fake_system_state_};
+ OmahaRequestParams omaha_request_params;
OmahaEvent event(OmahaEvent::kTypeUpdateComplete);
OmahaRequestBuilderXml omaha_request{&event,
&omaha_request_params,
@@ -332,7 +331,7 @@
0,
0,
0,
- fake_system_state_.prefs(),
+ FakeSystemState::Get()->prefs(),
""};
const string request_xml = omaha_request.GetRequest();
LOG(INFO) << request_xml;
@@ -345,7 +344,7 @@
TEST_F(OmahaRequestBuilderXmlTest,
GetRequestXmlUpdateCompleteEventSomeDlcsExcluded) {
- OmahaRequestParams omaha_request_params{&fake_system_state_};
+ OmahaRequestParams omaha_request_params;
omaha_request_params.set_dlc_apps_params({
{omaha_request_params.GetDlcAppId("dlc_1"), {.updated = true}},
{omaha_request_params.GetDlcAppId("dlc_2"), {.updated = false}},
@@ -358,7 +357,7 @@
0,
0,
0,
- fake_system_state_.prefs(),
+ FakeSystemState::Get()->prefs(),
""};
const string request_xml = omaha_request.GetRequest();
EXPECT_EQ(
@@ -376,7 +375,7 @@
TEST_F(OmahaRequestBuilderXmlTest,
GetRequestXmlUpdateCompleteEventAllDlcsExcluded) {
- OmahaRequestParams omaha_request_params{&fake_system_state_};
+ OmahaRequestParams omaha_request_params;
omaha_request_params.set_dlc_apps_params({
{omaha_request_params.GetDlcAppId("dlc_1"), {.updated = false}},
{omaha_request_params.GetDlcAppId("dlc_2"), {.updated = false}},
@@ -389,7 +388,7 @@
0,
0,
0,
- fake_system_state_.prefs(),
+ FakeSystemState::Get()->prefs(),
""};
const string request_xml = omaha_request.GetRequest();
EXPECT_EQ(
@@ -406,11 +405,11 @@
}
TEST_F(OmahaRequestBuilderXmlTest, GetRequestXmlDlcCohortMissingCheck) {
- OmahaRequestParams omaha_request_params{&fake_system_state_};
+ OmahaRequestParams omaha_request_params;
constexpr char kDlcId[] = "test-dlc-id";
omaha_request_params.set_dlc_apps_params(
{{omaha_request_params.GetDlcAppId(kDlcId), {.name = kDlcId}}});
- auto* mock_prefs = fake_system_state_.mock_prefs();
+ auto* mock_prefs = FakeSystemState::Get()->mock_prefs();
OmahaEvent event(OmahaEvent::kTypeUpdateDownloadStarted);
OmahaRequestBuilderXml omaha_request{
&event, &omaha_request_params, false, false, 0, 0, 0, mock_prefs, ""};
@@ -439,12 +438,12 @@
}
TEST_F(OmahaRequestBuilderXmlTest, GetRequestXmlDlcCohortCheck) {
- OmahaRequestParams omaha_request_params{&fake_system_state_};
+ OmahaRequestParams omaha_request_params;
const string kDlcId = "test-dlc-id";
omaha_request_params.set_dlc_apps_params(
{{omaha_request_params.GetDlcAppId(kDlcId), {.name = kDlcId}}});
FakePrefs fake_prefs;
- fake_system_state_.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
OmahaEvent event(OmahaEvent::kTypeUpdateDownloadStarted);
OmahaRequestBuilderXml omaha_request{
&event, &omaha_request_params, false, false, 0, 0, 0, &fake_prefs, ""};
diff --git a/cros/omaha_request_params.cc b/cros/omaha_request_params.cc
index e7e719b..0d69b24 100644
--- a/cros/omaha_request_params.cc
+++ b/cros/omaha_request_params.cc
@@ -65,8 +65,8 @@
const string& update_url,
const UpdateCheckParams& params) {
LOG(INFO) << "Initializing parameters for this update attempt";
- image_props_ = LoadImageProperties(system_state_);
- mutable_image_props_ = LoadMutableImageProperties(system_state_);
+ image_props_ = LoadImageProperties();
+ mutable_image_props_ = LoadMutableImageProperties();
// Validation check the channel names.
if (!IsValidChannel(image_props_.current_channel))
@@ -84,8 +84,8 @@
os_sp_ = image_props_.version + "_" + GetMachineType();
app_lang_ = "en-US";
- hwid_ = system_state_->hardware()->GetHardwareClass();
- device_requisition_ = system_state_->hardware()->GetDeviceRequisition();
+ hwid_ = SystemState::Get()->hardware()->GetHardwareClass();
+ device_requisition_ = SystemState::Get()->hardware()->GetDeviceRequisition();
if (image_props_.current_channel == mutable_image_props_.target_channel) {
// deltas are only okay if the /.nodelta file does not exist. if we don't
@@ -177,7 +177,7 @@
new_props.target_channel = new_target_channel;
new_props.is_powerwash_allowed = is_powerwash_allowed;
- if (!StoreMutableImageProperties(system_state_, new_props)) {
+ if (!StoreMutableImageProperties(new_props)) {
if (error_message)
*error_message = "Error storing the new channel value.";
return false;
diff --git a/cros/omaha_request_params.h b/cros/omaha_request_params.h
index fa452ce..fd4c2e2 100644
--- a/cros/omaha_request_params.h
+++ b/cros/omaha_request_params.h
@@ -37,8 +37,6 @@
namespace chromeos_update_engine {
-class SystemState;
-
// This class encapsulates the data Omaha gets for the request, along with
// essential state needed for the processing of the request/response. The
// strings in this struct should not be XML escaped.
@@ -47,9 +45,8 @@
// reflect its lifetime more appropriately.
class OmahaRequestParams {
public:
- explicit OmahaRequestParams(SystemState* system_state)
- : system_state_(system_state),
- os_platform_(constants::kOmahaPlatformName),
+ OmahaRequestParams()
+ : os_platform_(constants::kOmahaPlatformName),
os_version_(kOsVersion),
delta_okay_(true),
interactive_(false),
@@ -327,9 +324,6 @@
// Gets the machine type (e.g. "i686").
std::string GetMachineType() const;
- // Global system context.
- SystemState* system_state_;
-
// The system image properties.
ImageProperties image_props_;
MutableImageProperties mutable_image_props_;
diff --git a/cros/omaha_request_params_unittest.cc b/cros/omaha_request_params_unittest.cc
index ff52fc2..fbcd1a3 100644
--- a/cros/omaha_request_params_unittest.cc
+++ b/cros/omaha_request_params_unittest.cc
@@ -38,24 +38,24 @@
class OmahaRequestParamsTest : public ::testing::Test {
public:
- OmahaRequestParamsTest() : params_(&fake_system_state_) {}
+ OmahaRequestParamsTest() : params_() {}
protected:
void SetUp() override {
// Create a uniquely named test directory.
ASSERT_TRUE(tempdir_.CreateUniqueTempDir());
params_.set_root(tempdir_.GetPath().value());
+ FakeSystemState::CreateInstance();
+ FakeSystemState::Get()->set_prefs(&fake_prefs_);
SetLockDown(false);
- fake_system_state_.set_prefs(&fake_prefs_);
}
void SetLockDown(bool locked_down) {
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(locked_down);
- fake_system_state_.fake_hardware()->SetIsNormalBootMode(locked_down);
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(locked_down);
+ FakeSystemState::Get()->fake_hardware()->SetIsNormalBootMode(locked_down);
}
- FakeSystemState fake_system_state_;
- OmahaRequestParams params_{&fake_system_state_};
+ OmahaRequestParams params_;
FakePrefs fake_prefs_;
base::ScopedTempDir tempdir_;
@@ -110,7 +110,7 @@
TEST_F(OmahaRequestParamsTest, SetTargetChannelTest) {
{
- OmahaRequestParams params(&fake_system_state_);
+ OmahaRequestParams params;
params.set_root(tempdir_.GetPath().value());
EXPECT_TRUE(params.Init("", "", {}));
EXPECT_TRUE(params.SetTargetChannel("canary-channel", false, nullptr));
@@ -124,7 +124,7 @@
TEST_F(OmahaRequestParamsTest, SetIsPowerwashAllowedTest) {
{
- OmahaRequestParams params(&fake_system_state_);
+ OmahaRequestParams params;
params.set_root(tempdir_.GetPath().value());
EXPECT_TRUE(params.Init("", "", {}));
EXPECT_TRUE(params.SetTargetChannel("canary-channel", true, nullptr));
@@ -138,7 +138,7 @@
TEST_F(OmahaRequestParamsTest, SetTargetChannelInvalidTest) {
{
- OmahaRequestParams params(&fake_system_state_);
+ OmahaRequestParams params;
params.set_root(tempdir_.GetPath().value());
SetLockDown(true);
EXPECT_TRUE(params.Init("", "", {}));
diff --git a/cros/omaha_response_handler_action.cc b/cros/omaha_response_handler_action.cc
index 52142a3..6a51c77 100644
--- a/cros/omaha_response_handler_action.cc
+++ b/cros/omaha_response_handler_action.cc
@@ -27,6 +27,7 @@
#include "update_engine/common/constants.h"
#include "update_engine/common/hardware_interface.h"
#include "update_engine/common/prefs_interface.h"
+#include "update_engine/common/system_state.h"
#include "update_engine/common/utils.h"
#include "update_engine/cros/connection_manager_interface.h"
#include "update_engine/cros/omaha_request_params.h"
@@ -43,10 +44,8 @@
namespace chromeos_update_engine {
-OmahaResponseHandlerAction::OmahaResponseHandlerAction(
- SystemState* system_state)
- : system_state_(system_state),
- deadline_file_(constants::kOmahaResponseDeadlineFile) {}
+OmahaResponseHandlerAction::OmahaResponseHandlerAction()
+ : deadline_file_(constants::kOmahaResponseDeadlineFile) {}
void OmahaResponseHandlerAction::PerformAction() {
CHECK(HasInputObject());
@@ -60,7 +59,7 @@
// All decisions as to which URL should be used have already been done. So,
// make the current URL as the download URL.
- string current_url = system_state_->payload_state()->GetCurrentUrl();
+ string current_url = SystemState::Get()->payload_state()->GetCurrentUrl();
if (current_url.empty()) {
// This shouldn't happen as we should always supply the HTTPS backup URL.
// Handling this anyway, just in case.
@@ -76,8 +75,9 @@
install_plan_.download_url = current_url;
install_plan_.version = response.version;
- OmahaRequestParams* const params = system_state_->request_params();
- PayloadStateInterface* const payload_state = system_state_->payload_state();
+ OmahaRequestParams* const params = SystemState::Get()->request_params();
+ PayloadStateInterface* const payload_state =
+ SystemState::Get()->payload_state();
// If we're using p2p to download and there is a local peer, use it.
if (payload_state->GetUsingP2PForDownloading() &&
@@ -114,25 +114,28 @@
install_plan_.public_key_rsa = response.public_key_rsa;
install_plan_.hash_checks_mandatory = AreHashChecksMandatory(response);
install_plan_.is_resume = DeltaPerformer::CanResumeUpdate(
- system_state_->prefs(), update_check_response_hash);
+ SystemState::Get()->prefs(), update_check_response_hash);
if (install_plan_.is_resume) {
payload_state->UpdateResumed();
} else {
payload_state->UpdateRestarted();
LOG_IF(WARNING,
- !DeltaPerformer::ResetUpdateProgress(system_state_->prefs(), false))
+ !DeltaPerformer::ResetUpdateProgress(SystemState::Get()->prefs(),
+ false))
<< "Unable to reset the update progress.";
LOG_IF(WARNING,
- !system_state_->prefs()->SetString(kPrefsUpdateCheckResponseHash,
- update_check_response_hash))
+ !SystemState::Get()->prefs()->SetString(
+ kPrefsUpdateCheckResponseHash, update_check_response_hash))
<< "Unable to save the update check response hash.";
}
if (params->is_install()) {
- install_plan_.target_slot = system_state_->boot_control()->GetCurrentSlot();
+ install_plan_.target_slot =
+ SystemState::Get()->boot_control()->GetCurrentSlot();
install_plan_.source_slot = BootControlInterface::kInvalidSlot;
} else {
- install_plan_.source_slot = system_state_->boot_control()->GetCurrentSlot();
+ install_plan_.source_slot =
+ SystemState::Get()->boot_control()->GetCurrentSlot();
install_plan_.target_slot = install_plan_.source_slot == 0 ? 1 : 0;
}
@@ -142,8 +145,8 @@
// downloaded from.
string current_channel_key =
kPrefsChannelOnSlotPrefix + std::to_string(install_plan_.target_slot);
- system_state_->prefs()->SetString(current_channel_key,
- params->download_channel());
+ SystemState::Get()->prefs()->SetString(current_channel_key,
+ params->download_channel());
// Checking whether device is able to boot up the returned rollback image.
if (response.is_rollback) {
@@ -155,9 +158,9 @@
// Calculate the values on the version values on current device.
auto min_kernel_key_version = static_cast<uint32_t>(
- system_state_->hardware()->GetMinKernelKeyVersion());
+ SystemState::Get()->hardware()->GetMinKernelKeyVersion());
auto min_firmware_key_version = static_cast<uint32_t>(
- system_state_->hardware()->GetMinFirmwareKeyVersion());
+ SystemState::Get()->hardware()->GetMinFirmwareKeyVersion());
uint32_t kernel_key_version =
static_cast<uint32_t>(response.rollback_key_version.kernel_key) << 16 |
@@ -210,8 +213,8 @@
install_plan_.powerwash_required = true;
// Always try to preserve enrollment and wifi data for enrolled devices.
install_plan_.rollback_data_save_requested =
- system_state_ && system_state_->device_policy() &&
- system_state_->device_policy()->IsEnterpriseEnrolled();
+ SystemState::Get()->device_policy() &&
+ SystemState::Get()->device_policy()->IsEnterpriseEnrolled();
}
}
@@ -244,7 +247,7 @@
// Check the generated install-plan with the Policy to confirm that
// it can be applied at this time (or at all).
- UpdateManager* const update_manager = system_state_->update_manager();
+ UpdateManager* const update_manager = SystemState::Get()->update_manager();
CHECK(update_manager);
auto ec = ErrorCode::kSuccess;
update_manager->PolicyRequest(
@@ -285,7 +288,7 @@
<< " max_firmware_rollforward=" << max_firmware_rollforward
<< " rollback_allowed_milestones="
<< params->rollback_allowed_milestones();
- system_state_->hardware()->SetMaxKernelKeyRollforward(
+ SystemState::Get()->hardware()->SetMaxKernelKeyRollforward(
max_kernel_rollforward);
// TODO(crbug/783998): Set max firmware rollforward when implemented.
}
@@ -294,7 +297,8 @@
<< " to infinity";
// When rollback is not allowed, explicitly set the max roll forward to
// infinity.
- system_state_->hardware()->SetMaxKernelKeyRollforward(kRollforwardInfinity);
+ SystemState::Get()->hardware()->SetMaxKernelKeyRollforward(
+ kRollforwardInfinity);
// TODO(crbug/783998): Set max firmware rollforward when implemented.
}
}
@@ -314,8 +318,8 @@
// devmode/debugd checks pass, in which case the hash is waived.
// * Dev/test image:
// - Any URL is allowed through with no hash checking.
- if (!system_state_->request_params()->IsUpdateUrlOfficial() ||
- !system_state_->hardware()->IsOfficialBuild()) {
+ if (!SystemState::Get()->request_params()->IsUpdateUrlOfficial() ||
+ !SystemState::Get()->hardware()->IsOfficialBuild()) {
// Still do a hash check if a public key is included.
if (!response.public_key_rsa.empty()) {
// The autoupdate_CatchBadSignatures test checks for this string
diff --git a/cros/omaha_response_handler_action.h b/cros/omaha_response_handler_action.h
index f3b821e..9842c94 100644
--- a/cros/omaha_response_handler_action.h
+++ b/cros/omaha_response_handler_action.h
@@ -22,7 +22,6 @@
#include <gtest/gtest_prod.h> // for FRIEND_TEST
#include "update_engine/common/action.h"
-#include "update_engine/common/system_state.h"
#include "update_engine/cros/omaha_request_action.h"
#include "update_engine/payload_consumer/install_plan.h"
@@ -42,7 +41,7 @@
class OmahaResponseHandlerAction : public Action<OmahaResponseHandlerAction> {
public:
- explicit OmahaResponseHandlerAction(SystemState* system_state);
+ OmahaResponseHandlerAction();
typedef ActionTraits<OmahaResponseHandlerAction>::InputObjectType
InputObjectType;
@@ -65,9 +64,6 @@
// of the system and the contents of the Omaha response. False otherwise.
bool AreHashChecksMandatory(const OmahaResponse& response);
- // Global system context.
- SystemState* system_state_;
-
// The install plan, if we have an update.
InstallPlan install_plan_;
diff --git a/cros/omaha_response_handler_action_unittest.cc b/cros/omaha_response_handler_action_unittest.cc
index 74f4d04..8750724 100644
--- a/cros/omaha_response_handler_action_unittest.cc
+++ b/cros/omaha_response_handler_action_unittest.cc
@@ -80,7 +80,9 @@
class OmahaResponseHandlerActionTest : public ::testing::Test {
protected:
void SetUp() override {
- FakeBootControl* fake_boot_control = fake_system_state_.fake_boot_control();
+ FakeSystemState::CreateInstance();
+ FakeBootControl* fake_boot_control =
+ FakeSystemState::Get()->fake_boot_control();
fake_boot_control->SetPartitionDevice(kPartitionNameKernel, 0, "/dev/sdz2");
fake_boot_control->SetPartitionDevice(kPartitionNameRoot, 0, "/dev/sdz3");
fake_boot_control->SetPartitionDevice(kPartitionNameKernel, 1, "/dev/sdz4");
@@ -100,7 +102,6 @@
// it in non-success cases.
ErrorCode action_result_code_;
- FakeSystemState fake_system_state_;
// "Hash+"
const brillo::Blob expected_hash_ = {0x48, 0x61, 0x73, 0x68, 0x2b};
};
@@ -136,25 +137,25 @@
string expected_hash;
for (const auto& package : in.packages)
expected_hash += package.hash + ":";
- EXPECT_CALL(*(fake_system_state_.mock_prefs()),
+ EXPECT_CALL(*(FakeSystemState::Get()->mock_prefs()),
SetString(kPrefsUpdateCheckResponseHash, expected_hash))
.WillOnce(Return(true));
int slot =
- fake_system_state_.request_params()->is_install()
- ? fake_system_state_.fake_boot_control()->GetCurrentSlot()
- : 1 - fake_system_state_.fake_boot_control()->GetCurrentSlot();
+ FakeSystemState::Get()->request_params()->is_install()
+ ? FakeSystemState::Get()->fake_boot_control()->GetCurrentSlot()
+ : 1 - FakeSystemState::Get()->fake_boot_control()->GetCurrentSlot();
string key = kPrefsChannelOnSlotPrefix + std::to_string(slot);
- EXPECT_CALL(*(fake_system_state_.mock_prefs()), SetString(key, testing::_))
+ EXPECT_CALL(*(FakeSystemState::Get()->mock_prefs()),
+ SetString(key, testing::_))
.WillOnce(Return(true));
}
string current_url = in.packages.size() ? in.packages[0].payload_urls[0] : "";
- EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetCurrentUrl())
+ EXPECT_CALL(*(FakeSystemState::Get()->mock_payload_state()), GetCurrentUrl())
.WillRepeatedly(Return(current_url));
- auto response_handler_action =
- std::make_unique<OmahaResponseHandlerAction>(&fake_system_state_);
+ auto response_handler_action = std::make_unique<OmahaResponseHandlerAction>();
if (!test_deadline_file.empty())
response_handler_action->deadline_file_ = test_deadline_file;
@@ -225,7 +226,7 @@
in.prompt = true;
InstallPlan install_plan;
// Set the other slot as current.
- fake_system_state_.fake_boot_control()->SetCurrentSlot(1);
+ FakeSystemState::Get()->fake_boot_control()->SetCurrentSlot(1);
EXPECT_TRUE(DoTest(in, test_deadline_file.path(), &install_plan));
EXPECT_EQ(in.packages[0].payload_urls[0], install_plan.download_url);
EXPECT_EQ(expected_hash_, install_plan.payloads[0].hash);
@@ -250,10 +251,10 @@
in.prompt = true;
in.deadline = "some-deadline";
InstallPlan install_plan;
- fake_system_state_.fake_boot_control()->SetCurrentSlot(0);
+ FakeSystemState::Get()->fake_boot_control()->SetCurrentSlot(0);
// Because rollback happened, the deadline shouldn't be written into the
// file.
- EXPECT_CALL(*(fake_system_state_.mock_payload_state()),
+ EXPECT_CALL(*(FakeSystemState::Get()->mock_payload_state()),
GetRollbackHappened())
.WillOnce(Return(true));
EXPECT_TRUE(DoTest(in, test_deadline_file.path(), &install_plan));
@@ -280,8 +281,8 @@
in.prompt = true;
in.deadline = "some-deadline";
InstallPlan install_plan;
- fake_system_state_.fake_boot_control()->SetCurrentSlot(0);
- EXPECT_CALL(*(fake_system_state_.mock_payload_state()),
+ FakeSystemState::Get()->fake_boot_control()->SetCurrentSlot(0);
+ EXPECT_CALL(*(FakeSystemState::Get()->mock_payload_state()),
GetRollbackHappened())
.WillOnce(Return(false));
EXPECT_TRUE(DoTest(in, test_deadline_file.path(), &install_plan));
@@ -315,10 +316,10 @@
{.payload_urls = {kLongName}, .size = 2, .hash = kPayloadHashHex});
in.more_info_url = "http://more/info";
- OmahaRequestParams params(&fake_system_state_);
+ OmahaRequestParams params;
params.set_is_install(true);
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
InstallPlan install_plan;
EXPECT_TRUE(DoTest(in, "", &install_plan));
EXPECT_EQ(install_plan.source_slot, UINT_MAX);
@@ -366,7 +367,7 @@
.fp = kPayloadFp1});
in.more_info_url = "http://more/info";
// Hash checks are always skipped for non-official update URLs.
- EXPECT_CALL(*(fake_system_state_.mock_request_params()),
+ EXPECT_CALL(*(FakeSystemState::Get()->mock_request_params()),
IsUpdateUrlOfficial())
.WillRepeatedly(Return(true));
InstallPlan install_plan;
@@ -390,7 +391,7 @@
.app_id = kPayloadAppId,
.fp = kPayloadFp1});
in.more_info_url = "http://more/info";
- EXPECT_CALL(*(fake_system_state_.mock_request_params()),
+ EXPECT_CALL(*(FakeSystemState::Get()->mock_request_params()),
IsUpdateUrlOfficial())
.WillRepeatedly(Return(false));
InstallPlan install_plan;
@@ -416,10 +417,10 @@
.app_id = kPayloadAppId,
.fp = kPayloadFp1});
in.more_info_url = "http://more/info";
- EXPECT_CALL(*(fake_system_state_.mock_request_params()),
+ EXPECT_CALL(*(FakeSystemState::Get()->mock_request_params()),
IsUpdateUrlOfficial())
.WillRepeatedly(Return(true));
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(false);
InstallPlan install_plan;
EXPECT_TRUE(DoTest(in, "", &install_plan));
EXPECT_EQ(in.packages[0].payload_urls[0], install_plan.download_url);
@@ -441,7 +442,7 @@
.app_id = kPayloadAppId,
.fp = kPayloadFp1});
in.more_info_url = "http://more/info";
- EXPECT_CALL(*(fake_system_state_.mock_request_params()),
+ EXPECT_CALL(*(FakeSystemState::Get()->mock_request_params()),
IsUpdateUrlOfficial())
.WillRepeatedly(Return(true));
InstallPlan install_plan;
@@ -466,7 +467,7 @@
.app_id = kPayloadAppId,
.fp = kPayloadFp1});
in.more_info_url = "http://more/info";
- EXPECT_CALL(*(fake_system_state_.mock_request_params()),
+ EXPECT_CALL(*(FakeSystemState::Get()->mock_request_params()),
IsUpdateUrlOfficial())
.WillRepeatedly(Return(true));
InstallPlan install_plan;
@@ -493,15 +494,15 @@
base::ScopedTempDir tempdir;
ASSERT_TRUE(tempdir.CreateUniqueTempDir());
- OmahaRequestParams params(&fake_system_state_);
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
+ OmahaRequestParams params;
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(false);
params.set_root(tempdir.GetPath().value());
params.set_current_channel("canary-channel");
EXPECT_TRUE(params.SetTargetChannel("stable-channel", true, nullptr));
params.UpdateDownloadChannel();
params.set_app_version("2.0.0.0");
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
InstallPlan install_plan;
EXPECT_TRUE(DoTest(in, "", &install_plan));
EXPECT_TRUE(install_plan.powerwash_required);
@@ -521,15 +522,15 @@
base::ScopedTempDir tempdir;
ASSERT_TRUE(tempdir.CreateUniqueTempDir());
- OmahaRequestParams params(&fake_system_state_);
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
+ OmahaRequestParams params;
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(false);
params.set_root(tempdir.GetPath().value());
params.set_current_channel("canary-channel");
EXPECT_TRUE(params.SetTargetChannel("stable-channel", false, nullptr));
params.UpdateDownloadChannel();
params.set_app_version("2.0.0.0");
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
InstallPlan install_plan;
EXPECT_TRUE(DoTest(in, "", &install_plan));
EXPECT_FALSE(install_plan.powerwash_required);
@@ -549,15 +550,15 @@
base::ScopedTempDir tempdir;
ASSERT_TRUE(tempdir.CreateUniqueTempDir());
- OmahaRequestParams params(&fake_system_state_);
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
+ OmahaRequestParams params;
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(false);
params.set_root(tempdir.GetPath().value());
params.set_current_channel("beta-channel");
EXPECT_TRUE(params.SetTargetChannel("stable-channel", true, nullptr));
params.UpdateDownloadChannel();
params.set_app_version("12345.48.0.0");
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
InstallPlan install_plan;
EXPECT_TRUE(DoTest(in, "", &install_plan));
EXPECT_FALSE(install_plan.powerwash_required);
@@ -577,15 +578,15 @@
base::ScopedTempDir tempdir;
ASSERT_TRUE(tempdir.CreateUniqueTempDir());
- OmahaRequestParams params(&fake_system_state_);
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
+ OmahaRequestParams params;
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(false);
params.set_root(tempdir.GetPath().value());
params.set_current_channel("beta-channel");
EXPECT_TRUE(params.SetTargetChannel("stable-channel", true, nullptr));
params.UpdateDownloadChannel();
params.set_app_version("12345.0.0.0");
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
InstallPlan install_plan;
EXPECT_TRUE(DoTest(in, "", &install_plan));
EXPECT_FALSE(install_plan.powerwash_required);
@@ -608,8 +609,8 @@
base::ScopedTempDir tempdir;
ASSERT_TRUE(tempdir.CreateUniqueTempDir());
- OmahaRequestParams params(&fake_system_state_);
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
+ OmahaRequestParams params;
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
params.set_root(tempdir.GetPath().value());
params.set_current_channel("beta-channel");
EXPECT_TRUE(params.SetTargetChannel("stable-channel", true, nullptr));
@@ -619,9 +620,9 @@
testing::NiceMock<policy::MockDevicePolicy> mock_device_policy;
EXPECT_CALL(mock_device_policy, IsEnterpriseEnrolled())
.WillOnce(Return(true));
- fake_system_state_.set_device_policy(&mock_device_policy);
+ FakeSystemState::Get()->set_device_policy(&mock_device_policy);
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
InstallPlan install_plan;
EXPECT_TRUE(DoTest(in, "", &install_plan));
EXPECT_TRUE(install_plan.rollback_data_save_requested);
@@ -642,8 +643,8 @@
base::ScopedTempDir tempdir;
ASSERT_TRUE(tempdir.CreateUniqueTempDir());
- OmahaRequestParams params(&fake_system_state_);
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
+ OmahaRequestParams params;
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
params.set_root(tempdir.GetPath().value());
params.set_current_channel("beta-channel");
EXPECT_TRUE(params.SetTargetChannel("stable-channel", true, nullptr));
@@ -653,9 +654,9 @@
testing::NiceMock<policy::MockDevicePolicy> mock_device_policy;
EXPECT_CALL(mock_device_policy, IsEnterpriseEnrolled())
.WillOnce(Return(false));
- fake_system_state_.set_device_policy(&mock_device_policy);
+ FakeSystemState::Get()->set_device_policy(&mock_device_policy);
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
InstallPlan install_plan;
EXPECT_TRUE(DoTest(in, "", &install_plan));
EXPECT_FALSE(install_plan.rollback_data_save_requested);
@@ -675,15 +676,15 @@
base::ScopedTempDir tempdir;
ASSERT_TRUE(tempdir.CreateUniqueTempDir());
- OmahaRequestParams params(&fake_system_state_);
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
+ OmahaRequestParams params;
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
params.set_root(tempdir.GetPath().value());
params.set_current_channel("beta-channel");
EXPECT_TRUE(params.SetTargetChannel("stable-channel", false, nullptr));
params.UpdateDownloadChannel();
params.set_app_version("12347.48.0.0");
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
InstallPlan install_plan;
EXPECT_TRUE(DoTest(in, "", &install_plan));
EXPECT_FALSE(install_plan.rollback_data_save_requested);
@@ -703,15 +704,15 @@
base::ScopedTempDir tempdir;
ASSERT_TRUE(tempdir.CreateUniqueTempDir());
- OmahaRequestParams params(&fake_system_state_);
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
+ OmahaRequestParams params;
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(false);
params.set_root(tempdir.GetPath().value());
params.set_current_channel("stable-channel");
EXPECT_TRUE(params.SetTargetChannel("canary-channel", false, nullptr));
params.UpdateDownloadChannel();
params.set_app_version("1.0.0.0");
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
InstallPlan install_plan;
EXPECT_TRUE(DoTest(in, "", &install_plan));
EXPECT_FALSE(install_plan.powerwash_required);
@@ -729,20 +730,20 @@
.fp = kPayloadFp1});
in.more_info_url = "http://more/info";
- OmahaRequestParams params(&fake_system_state_);
+ OmahaRequestParams params;
// We're using a real OmahaRequestParams object here so we can't mock
// IsUpdateUrlOfficial(), but setting the update URL to the AutoUpdate test
// server will cause IsUpdateUrlOfficial() to return true.
params.set_update_url(constants::kOmahaDefaultAUTestURL);
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
- EXPECT_CALL(*fake_system_state_.mock_payload_state(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
SetUsingP2PForDownloading(true));
string p2p_url = "http://9.8.7.6/p2p";
- EXPECT_CALL(*fake_system_state_.mock_payload_state(), GetP2PUrl())
+ EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), GetP2PUrl())
.WillRepeatedly(Return(p2p_url));
- EXPECT_CALL(*fake_system_state_.mock_payload_state(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
GetUsingP2PForDownloading())
.WillRepeatedly(Return(true));
@@ -777,17 +778,18 @@
in.past_rollback_key_version = m4;
- fake_system_state_.fake_hardware()->SetMinKernelKeyVersion(0x00010002);
- fake_system_state_.fake_hardware()->SetMinFirmwareKeyVersion(0x00030004);
+ FakeSystemState::Get()->fake_hardware()->SetMinKernelKeyVersion(0x00010002);
+ FakeSystemState::Get()->fake_hardware()->SetMinFirmwareKeyVersion(0x00030004);
- fake_system_state_.fake_hardware()->SetMaxKernelKeyRollforward(0xaaaaaaaa);
+ FakeSystemState::Get()->fake_hardware()->SetMaxKernelKeyRollforward(
+ 0xaaaaaaaa);
// TODO(crbug/783998): Add support for firmware when implemented.
- OmahaRequestParams params(&fake_system_state_);
+ OmahaRequestParams params;
params.set_rollback_allowed(true);
params.set_rollback_allowed_milestones(4);
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
InstallPlan install_plan;
EXPECT_TRUE(DoTest(in, "", &install_plan));
EXPECT_TRUE(install_plan.is_rollback);
@@ -797,8 +799,9 @@
const uint32_t expected_max_kernel_rollforward =
static_cast<uint32_t>(m4.kernel_key) << 16 |
static_cast<uint32_t>(m4.kernel);
- EXPECT_EQ(expected_max_kernel_rollforward,
- fake_system_state_.fake_hardware()->GetMaxKernelKeyRollforward());
+ EXPECT_EQ(
+ expected_max_kernel_rollforward,
+ FakeSystemState::Get()->fake_hardware()->GetMaxKernelKeyRollforward());
// TODO(crbug/783998): Add support for firmware when implemented.
}
@@ -821,23 +824,24 @@
m4.kernel = 13;
in.past_rollback_key_version = m4;
- fake_system_state_.fake_hardware()->SetMinKernelKeyVersion(0x00010002);
- fake_system_state_.fake_hardware()->SetMinFirmwareKeyVersion(0x00030004);
+ FakeSystemState::Get()->fake_hardware()->SetMinKernelKeyVersion(0x00010002);
+ FakeSystemState::Get()->fake_hardware()->SetMinFirmwareKeyVersion(0x00030004);
const uint32_t current_kernel_max_rollforward = 0xaaaaaaaa;
- fake_system_state_.fake_hardware()->SetMaxKernelKeyRollforward(
+ FakeSystemState::Get()->fake_hardware()->SetMaxKernelKeyRollforward(
current_kernel_max_rollforward);
- OmahaRequestParams params(&fake_system_state_);
+ OmahaRequestParams params;
params.set_rollback_allowed(true);
params.set_rollback_allowed_milestones(4);
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
InstallPlan install_plan;
EXPECT_FALSE(DoTest(in, "", &install_plan));
// Max rollforward is not changed in error cases.
- EXPECT_EQ(current_kernel_max_rollforward,
- fake_system_state_.fake_hardware()->GetMaxKernelKeyRollforward());
+ EXPECT_EQ(
+ current_kernel_max_rollforward,
+ FakeSystemState::Get()->fake_hardware()->GetMaxKernelKeyRollforward());
// TODO(crbug/783998): Add support for firmware when implemented.
}
@@ -855,14 +859,14 @@
in.rollback_key_version.firmware_key = 3;
in.rollback_key_version.firmware = 3; // This is lower than the minimum.
- fake_system_state_.fake_hardware()->SetMinKernelKeyVersion(0x00010002);
- fake_system_state_.fake_hardware()->SetMinFirmwareKeyVersion(0x00030004);
+ FakeSystemState::Get()->fake_hardware()->SetMinKernelKeyVersion(0x00010002);
+ FakeSystemState::Get()->fake_hardware()->SetMinFirmwareKeyVersion(0x00030004);
- OmahaRequestParams params(&fake_system_state_);
+ OmahaRequestParams params;
params.set_rollback_allowed(true);
params.set_rollback_allowed_milestones(4);
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
InstallPlan install_plan;
EXPECT_FALSE(DoTest(in, "", &install_plan));
}
@@ -876,21 +880,22 @@
in.is_rollback = false;
const uint32_t current_kernel_max_rollforward = 0xaaaaaaaa;
- fake_system_state_.fake_hardware()->SetMaxKernelKeyRollforward(
+ FakeSystemState::Get()->fake_hardware()->SetMaxKernelKeyRollforward(
current_kernel_max_rollforward);
- OmahaRequestParams params(&fake_system_state_);
+ OmahaRequestParams params;
params.set_rollback_allowed(true);
params.set_rollback_allowed_milestones(4);
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
InstallPlan install_plan;
EXPECT_TRUE(DoTest(in, "", &install_plan));
EXPECT_FALSE(install_plan.is_rollback);
// Max rollforward is not changed for non-rollback cases.
- EXPECT_EQ(current_kernel_max_rollforward,
- fake_system_state_.fake_hardware()->GetMaxKernelKeyRollforward());
+ EXPECT_EQ(
+ current_kernel_max_rollforward,
+ FakeSystemState::Get()->fake_hardware()->GetMaxKernelKeyRollforward());
// TODO(crbug/783998): Add support for firmware when implemented.
}
@@ -902,21 +907,22 @@
.hash = kPayloadHashHex});
in.is_rollback = true;
- OmahaRequestParams params(&fake_system_state_);
+ OmahaRequestParams params;
params.set_rollback_allowed(false);
params.set_rollback_allowed_milestones(4);
const uint32_t current_kernel_max_rollforward = 0xaaaaaaaa;
- fake_system_state_.fake_hardware()->SetMaxKernelKeyRollforward(
+ FakeSystemState::Get()->fake_hardware()->SetMaxKernelKeyRollforward(
current_kernel_max_rollforward);
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
InstallPlan install_plan;
EXPECT_FALSE(DoTest(in, "", &install_plan));
// This case generates an error so, do not update max rollforward.
- EXPECT_EQ(current_kernel_max_rollforward,
- fake_system_state_.fake_hardware()->GetMaxKernelKeyRollforward());
+ EXPECT_EQ(
+ current_kernel_max_rollforward,
+ FakeSystemState::Get()->fake_hardware()->GetMaxKernelKeyRollforward());
// TODO(crbug/783998): Add support for firmware when implemented.
}
@@ -928,21 +934,22 @@
.hash = kPayloadHashHex});
in.is_rollback = false;
- OmahaRequestParams params(&fake_system_state_);
+ OmahaRequestParams params;
params.set_rollback_allowed(true);
params.set_rollback_allowed_milestones(0);
const uint32_t current_kernel_max_rollforward = 0xaaaaaaaa;
- fake_system_state_.fake_hardware()->SetMaxKernelKeyRollforward(
+ FakeSystemState::Get()->fake_hardware()->SetMaxKernelKeyRollforward(
current_kernel_max_rollforward);
- fake_system_state_.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
InstallPlan install_plan;
EXPECT_TRUE(DoTest(in, "", &install_plan));
// When allowed_milestones is 0, this is set to infinity.
- EXPECT_EQ(kRollforwardInfinity,
- fake_system_state_.fake_hardware()->GetMaxKernelKeyRollforward());
+ EXPECT_EQ(
+ kRollforwardInfinity,
+ FakeSystemState::Get()->fake_hardware()->GetMaxKernelKeyRollforward());
// TODO(crbug/783998): Add support for firmware when implemented.
}
@@ -989,7 +996,7 @@
FakeClock fake_clock;
MockPolicy* mock_policy = new MockPolicy(&fake_clock);
FakeUpdateManager* fake_update_manager =
- fake_system_state_.fake_update_manager();
+ FakeSystemState::Get()->fake_update_manager();
fake_update_manager->set_policy(mock_policy);
EXPECT_CALL(*mock_policy, UpdateCanBeApplied(_, _, _, _, _))
.WillOnce(
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"
diff --git a/cros/payload_state.h b/cros/payload_state.h
index 0827273..ad19074 100644
--- a/cros/payload_state.h
+++ b/cros/payload_state.h
@@ -48,7 +48,7 @@
// It performs the initial loading of all persisted state into memory and
// dumps the initial state for debugging purposes. Note: the other methods
// should be called only after calling Initialize on this object.
- bool Initialize(SystemState* system_state);
+ bool Initialize();
// Implementation of PayloadStateInterface methods.
void SetResponse(const OmahaResponse& response) override;
@@ -429,9 +429,6 @@
// Get the total size of all payloads.
int64_t GetPayloadSize();
- // The global state of the system.
- SystemState* system_state_;
-
// Interface object with which we read/write persisted state. This must
// be set by calling the Initialize method before calling any other method.
PrefsInterface* prefs_;
diff --git a/cros/payload_state_unittest.cc b/cros/payload_state_unittest.cc
index 107c6e2..edcb9d6 100644
--- a/cros/payload_state_unittest.cc
+++ b/cros/payload_state_unittest.cc
@@ -106,12 +106,14 @@
EXPECT_EQ(expected_response_sign, stored_response_sign);
}
-class PayloadStateTest : public ::testing::Test {};
+class PayloadStateTest : public ::testing::Test {
+ public:
+ void SetUp() { FakeSystemState::CreateInstance(); }
+};
TEST_F(PayloadStateTest, SetResponseWorksWithEmptyResponse) {
OmahaResponse response;
- FakeSystemState fake_system_state;
- NiceMock<MockPrefs>* prefs = fake_system_state.mock_prefs();
+ NiceMock<MockPrefs>* prefs = FakeSystemState::Get()->mock_prefs();
EXPECT_CALL(*prefs, SetInt64(_, _)).Times(AnyNumber());
EXPECT_CALL(*prefs, SetInt64(kPrefsPayloadAttemptNumber, 0))
.Times(AtLeast(1));
@@ -133,7 +135,7 @@
.Times(AtLeast(1));
EXPECT_CALL(*prefs, SetInt64(kPrefsNumReboots, 0)).Times(AtLeast(1));
PayloadState payload_state;
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
payload_state.SetResponse(response);
string stored_response_sign = payload_state.GetResponseSignature();
string expected_response_sign =
@@ -153,8 +155,7 @@
.metadata_size = 58123,
.metadata_signature = "msign",
.hash = "hash"});
- FakeSystemState fake_system_state;
- NiceMock<MockPrefs>* prefs = fake_system_state.mock_prefs();
+ NiceMock<MockPrefs>* prefs = FakeSystemState::Get()->mock_prefs();
EXPECT_CALL(*prefs, SetInt64(_, _)).Times(AnyNumber());
EXPECT_CALL(*prefs, SetInt64(kPrefsPayloadAttemptNumber, 0))
.Times(AtLeast(1));
@@ -176,7 +177,7 @@
.Times(AtLeast(1));
EXPECT_CALL(*prefs, SetInt64(kPrefsNumReboots, 0)).Times(AtLeast(1));
PayloadState payload_state;
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
payload_state.SetResponse(response);
string stored_response_sign = payload_state.GetResponseSignature();
string expected_response_sign =
@@ -205,8 +206,7 @@
.metadata_size = 558123,
.metadata_signature = "metasign",
.hash = "rhash"});
- FakeSystemState fake_system_state;
- NiceMock<MockPrefs>* prefs = fake_system_state.mock_prefs();
+ NiceMock<MockPrefs>* prefs = FakeSystemState::Get()->mock_prefs();
EXPECT_CALL(*prefs, SetInt64(_, _)).Times(AnyNumber());
EXPECT_CALL(*prefs, SetInt64(kPrefsPayloadAttemptNumber, 0))
.Times(AtLeast(1));
@@ -225,7 +225,7 @@
EXPECT_CALL(*prefs, SetInt64(kPrefsNumReboots, 0)).Times(AtLeast(1));
PayloadState payload_state;
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
payload_state.SetResponse(response);
string stored_response_sign = payload_state.GetResponseSignature();
string expected_response_sign =
@@ -249,8 +249,7 @@
TEST_F(PayloadStateTest, CanAdvanceUrlIndexCorrectly) {
OmahaResponse response;
- FakeSystemState fake_system_state;
- NiceMock<MockPrefs>* prefs = fake_system_state.mock_prefs();
+ NiceMock<MockPrefs>* prefs = FakeSystemState::Get()->mock_prefs();
PayloadState payload_state;
EXPECT_CALL(*prefs, SetInt64(_, _)).Times(AnyNumber());
@@ -277,7 +276,7 @@
EXPECT_CALL(*prefs, SetInt64(kPrefsCurrentUrlFailureCount, 0))
.Times(AtLeast(4));
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
// This does a SetResponse which causes all the states to be set to 0 for
// the first time.
@@ -304,10 +303,9 @@
TEST_F(PayloadStateTest, NewResponseResetsPayloadState) {
OmahaResponse response;
- FakeSystemState fake_system_state;
PayloadState payload_state;
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
// Set the first response.
SetupPayloadStateWith2Urls(
@@ -352,9 +350,8 @@
TEST_F(PayloadStateTest, AllCountersGetUpdatedProperlyOnErrorCodesAndEvents) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
int progress_bytes = 100;
- NiceMock<MockPrefs>* prefs = fake_system_state.mock_prefs();
+ NiceMock<MockPrefs>* prefs = FakeSystemState::Get()->mock_prefs();
EXPECT_CALL(*prefs, SetInt64(_, _)).Times(AnyNumber());
EXPECT_CALL(*prefs, SetInt64(kPrefsPayloadAttemptNumber, 0))
@@ -400,7 +397,7 @@
.Times(AtLeast(1));
EXPECT_CALL(*prefs, SetInt64(kPrefsNumReboots, 0)).Times(AtLeast(1));
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash5873", true, false, &payload_state, &response);
@@ -499,8 +496,7 @@
PayloadAttemptNumberIncreasesOnSuccessfulFullDownload) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
- NiceMock<MockPrefs>* prefs = fake_system_state.mock_prefs();
+ NiceMock<MockPrefs>* prefs = FakeSystemState::Get()->mock_prefs();
EXPECT_CALL(*prefs, SetInt64(_, _)).Times(AnyNumber());
EXPECT_CALL(*prefs, SetInt64(kPrefsPayloadAttemptNumber, 0))
@@ -519,7 +515,7 @@
EXPECT_CALL(*prefs, SetInt64(kPrefsCurrentUrlFailureCount, 0))
.Times(AtLeast(1));
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash8593", true, false, &payload_state, &response);
@@ -539,8 +535,7 @@
PayloadAttemptNumberIncreasesOnSuccessfulDeltaDownload) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
- NiceMock<MockPrefs>* prefs = fake_system_state.mock_prefs();
+ NiceMock<MockPrefs>* prefs = FakeSystemState::Get()->mock_prefs();
EXPECT_CALL(*prefs, SetInt64(_, _)).Times(AnyNumber());
EXPECT_CALL(*prefs, SetInt64(kPrefsPayloadAttemptNumber, 0))
@@ -558,7 +553,7 @@
EXPECT_CALL(*prefs, SetInt64(kPrefsCurrentUrlFailureCount, 0))
.Times(AtLeast(1));
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls("Hash8593", true, true, &payload_state, &response);
@@ -576,9 +571,8 @@
TEST_F(PayloadStateTest, SetResponseResetsInvalidUrlIndex) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash4427", true, false, &payload_state, &response);
@@ -596,8 +590,7 @@
// Now, simulate a corrupted url index on persisted store which gets
// loaded when update_engine restarts. Using a different prefs object
// so as to not bother accounting for the uninteresting calls above.
- FakeSystemState fake_system_state2;
- NiceMock<MockPrefs>* prefs2 = fake_system_state2.mock_prefs();
+ NiceMock<MockPrefs>* prefs2 = FakeSystemState::Get()->mock_prefs();
EXPECT_CALL(*prefs2, Exists(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*prefs2, GetInt64(_, _)).Times(AtLeast(1));
EXPECT_CALL(*prefs2, GetInt64(kPrefsPayloadAttemptNumber, _))
@@ -614,7 +607,7 @@
// have the same hash as before so as to not trivially reset because the
// response was different. We want to specifically test that even if the
// response is same, we should reset the state if we find it corrupted.
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state2));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash4427", true, false, &payload_state, &response);
@@ -630,12 +623,11 @@
TEST_F(PayloadStateTest, NoBackoffInteractiveChecks) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
- OmahaRequestParams params(&fake_system_state);
+ OmahaRequestParams params;
params.Init("", "", {.interactive = true});
- fake_system_state.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash6437", true, false, &payload_state, &response);
@@ -653,12 +645,11 @@
TEST_F(PayloadStateTest, NoBackoffForP2PUpdates) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
- OmahaRequestParams params(&fake_system_state);
+ OmahaRequestParams params;
params.Init("", "", {});
- fake_system_state.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash6437", true, false, &payload_state, &response);
@@ -684,9 +675,8 @@
TEST_F(PayloadStateTest, NoBackoffForDeltaPayloads) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls("Hash6437", true, true, &payload_state, &response);
// Simulate a successful download and see that we're ready to download
@@ -728,9 +718,8 @@
TEST_F(PayloadStateTest, BackoffPeriodsAreInCorrectRange) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash8939", true, false, &payload_state, &response);
@@ -750,9 +739,8 @@
OmahaResponse response;
response.disable_payload_backoff = true;
PayloadState payload_state;
- FakeSystemState fake_system_state;
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash8939", true, false, &payload_state, &response);
@@ -777,11 +765,10 @@
OmahaResponse response;
response.disable_payload_backoff = true;
PayloadState payload_state;
- FakeSystemState fake_system_state;
uint64_t https_total = 0;
uint64_t http_total = 0;
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash3286", true, false, &payload_state, &response);
EXPECT_EQ(1, payload_state.GetNumResponsesSeen());
@@ -864,7 +851,7 @@
EXPECT_EQ(p2p_total,
payload_state.GetTotalBytesDownloaded(kDownloadSourceHttpPeer));
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportSuccessfulUpdateMetrics(
1, _, kPayloadTypeFull, _, _, 314, _, _, _, 3));
@@ -885,9 +872,8 @@
TEST_F(PayloadStateTest, DownloadSourcesUsedIsCorrect) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash3286", true, false, &payload_state, &response);
@@ -905,7 +891,7 @@
int64_t total_bytes[kNumDownloadSources] = {};
total_bytes[kDownloadSourceHttpServer] = num_bytes;
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportSuccessfulUpdateMetrics(
_,
_,
@@ -924,10 +910,9 @@
TEST_F(PayloadStateTest, RestartingUpdateResetsMetrics) {
OmahaResponse response;
- FakeSystemState fake_system_state;
PayloadState payload_state;
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
// Set the first response.
SetupPayloadStateWith2Urls(
@@ -953,24 +938,23 @@
}
TEST_F(PayloadStateTest, NumRebootsIncrementsCorrectly) {
- FakeSystemState fake_system_state;
PayloadState payload_state;
- NiceMock<MockPrefs>* prefs = fake_system_state.mock_prefs();
+ NiceMock<MockPrefs>* prefs = FakeSystemState::Get()->mock_prefs();
EXPECT_CALL(*prefs, SetInt64(_, _)).Times(AtLeast(0));
EXPECT_CALL(*prefs, SetInt64(kPrefsNumReboots, 1)).Times(AtLeast(1));
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
payload_state.UpdateRestarted();
EXPECT_EQ(0U, payload_state.GetNumReboots());
- fake_system_state.set_system_rebooted(true);
+ FakeSystemState::Get()->set_system_rebooted(true);
payload_state.UpdateResumed();
// Num reboots should be incremented because system rebooted detected.
EXPECT_EQ(1U, payload_state.GetNumReboots());
- fake_system_state.set_system_rebooted(false);
+ FakeSystemState::Get()->set_system_rebooted(false);
payload_state.UpdateResumed();
// Num reboots should now be 1 as reboot was not detected.
EXPECT_EQ(1U, payload_state.GetNumReboots());
@@ -981,12 +965,11 @@
}
TEST_F(PayloadStateTest, RollbackHappened) {
- FakeSystemState fake_system_state;
PayloadState payload_state;
NiceMock<MockPrefs>* mock_powerwash_safe_prefs =
- fake_system_state.mock_powerwash_safe_prefs();
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ FakeSystemState::Get()->mock_powerwash_safe_prefs();
+ EXPECT_TRUE(payload_state.Initialize());
// Verify pre-conditions are good.
EXPECT_FALSE(payload_state.GetRollbackHappened());
@@ -1012,19 +995,18 @@
}
TEST_F(PayloadStateTest, RollbackVersion) {
- FakeSystemState fake_system_state;
PayloadState payload_state;
NiceMock<MockPrefs>* mock_powerwash_safe_prefs =
- fake_system_state.mock_powerwash_safe_prefs();
+ FakeSystemState::Get()->mock_powerwash_safe_prefs();
// Mock out the os version and make sure it's excluded correctly.
string rollback_version = "2345.0.0";
- OmahaRequestParams params(&fake_system_state);
+ OmahaRequestParams params;
params.Init(rollback_version, "", {});
- fake_system_state.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
// Verify pre-conditions are good.
EXPECT_TRUE(payload_state.GetRollbackVersion().empty());
@@ -1047,7 +1029,7 @@
// Check that we report only UpdateEngine.Rollback.* metrics in
// UpdateSucceeded().
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportRollbackMetrics(metrics::RollbackResult::kSuccess))
.Times(1);
@@ -1058,7 +1040,6 @@
OmahaResponse response;
response.packages.resize(1);
PayloadState payload_state;
- FakeSystemState fake_system_state;
FakeClock fake_clock;
FakePrefs fake_prefs;
@@ -1067,9 +1048,9 @@
fake_clock.SetWallclockTime(Time::FromInternalValue(1000000));
fake_clock.SetMonotonicTime(Time::FromInternalValue(2000000));
- fake_system_state.set_clock(&fake_clock);
- fake_system_state.set_prefs(&fake_prefs);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ FakeSystemState::Get()->set_clock(&fake_clock);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
+ EXPECT_TRUE(payload_state.Initialize());
// Check that durations are correct for a successful update where
// time has advanced 7 seconds on the wall clock and 4 seconds on
@@ -1101,7 +1082,7 @@
// durations correctly (e.g. they are the same as before).
fake_clock.SetMonotonicTime(Time::FromInternalValue(5000));
PayloadState payload_state2;
- EXPECT_TRUE(payload_state2.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state2.Initialize());
payload_state2.SetResponse(response);
EXPECT_EQ(payload_state2.GetUpdateDuration().InMicroseconds(), 10000000);
EXPECT_EQ(payload_state2.GetUpdateDurationUptime().InMicroseconds(),
@@ -1120,7 +1101,6 @@
TEST_F(PayloadStateTest, RebootAfterSuccessfulUpdateTest) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
FakeClock fake_clock;
FakePrefs fake_prefs;
@@ -1128,9 +1108,9 @@
fake_clock.SetMonotonicTime(
Time::FromInternalValue(30 * Time::kMicrosecondsPerSecond));
- fake_system_state.set_clock(&fake_clock);
- fake_system_state.set_prefs(&fake_prefs);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ FakeSystemState::Get()->set_clock(&fake_clock);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
+ EXPECT_TRUE(payload_state.Initialize());
// Make the update succeed.
SetupPayloadStateWith2Urls(
@@ -1147,12 +1127,12 @@
fake_clock.SetMonotonicTime(
Time::FromInternalValue(500 * Time::kMicrosecondsPerSecond));
PayloadState payload_state2;
- EXPECT_TRUE(payload_state2.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state2.Initialize());
// Expect 500 - 30 seconds = 470 seconds ~= 7 min 50 sec
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportTimeToReboot(7));
- fake_system_state.set_system_rebooted(true);
+ FakeSystemState::Get()->set_system_rebooted(true);
payload_state2.UpdateEngineStarted();
@@ -1162,12 +1142,11 @@
TEST_F(PayloadStateTest, RestartAfterCrash) {
PayloadState payload_state;
- FakeSystemState fake_system_state;
testing::StrictMock<MockMetricsReporter> mock_metrics_reporter;
- fake_system_state.set_metrics_reporter(&mock_metrics_reporter);
- NiceMock<MockPrefs>* prefs = fake_system_state.mock_prefs();
+ FakeSystemState::Get()->set_metrics_reporter(&mock_metrics_reporter);
+ NiceMock<MockPrefs>* prefs = FakeSystemState::Get()->mock_prefs();
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
// Only the |kPrefsAttemptInProgress| state variable should be read.
EXPECT_CALL(*prefs, Exists(_)).Times(0);
@@ -1180,18 +1159,17 @@
EXPECT_CALL(*prefs, GetBoolean(kPrefsAttemptInProgress, _));
// Simulate an update_engine restart without a reboot.
- fake_system_state.set_system_rebooted(false);
+ FakeSystemState::Get()->set_system_rebooted(false);
payload_state.UpdateEngineStarted();
}
TEST_F(PayloadStateTest, AbnormalTerminationAttemptMetricsNoReporting) {
PayloadState payload_state;
- FakeSystemState fake_system_state;
// If there's no marker at startup, ensure we don't report a metric.
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_TRUE(payload_state.Initialize());
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportAbnormallyTerminatedUpdateAttemptMetrics())
.Times(0);
payload_state.UpdateEngineStarted();
@@ -1199,17 +1177,16 @@
TEST_F(PayloadStateTest, AbnormalTerminationAttemptMetricsReported) {
PayloadState payload_state;
- FakeSystemState fake_system_state;
FakePrefs fake_prefs;
// If we have a marker at startup, ensure it's reported and the
// marker is then cleared.
- fake_system_state.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
fake_prefs.SetBoolean(kPrefsAttemptInProgress, true);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportAbnormallyTerminatedUpdateAttemptMetrics())
.Times(1);
payload_state.UpdateEngineStarted();
@@ -1219,19 +1196,18 @@
TEST_F(PayloadStateTest, AbnormalTerminationAttemptMetricsClearedOnSucceess) {
PayloadState payload_state;
- FakeSystemState fake_system_state;
FakePrefs fake_prefs;
// Make sure the marker is written and cleared during an attempt and
// also that we DO NOT emit the metric (since the attempt didn't end
// abnormally).
- fake_system_state.set_prefs(&fake_prefs);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
+ EXPECT_TRUE(payload_state.Initialize());
OmahaResponse response;
response.packages.resize(1);
payload_state.SetResponse(response);
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportAbnormallyTerminatedUpdateAttemptMetrics())
.Times(0);
@@ -1251,12 +1227,11 @@
TEST_F(PayloadStateTest, CandidateUrlsComputedCorrectly) {
OmahaResponse response;
- FakeSystemState fake_system_state;
PayloadState payload_state;
policy::MockDevicePolicy disable_http_policy;
- fake_system_state.set_device_policy(&disable_http_policy);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ FakeSystemState::Get()->set_device_policy(&disable_http_policy);
+ EXPECT_TRUE(payload_state.Initialize());
// Test with no device policy. Should default to allowing http.
EXPECT_CALL(disable_http_policy, GetHttpDownloadsEnabled(_))
@@ -1299,7 +1274,7 @@
// Now, pretend that the HTTP policy is turned on. We want to make sure
// the new policy is honored.
policy::MockDevicePolicy enable_http_policy;
- fake_system_state.set_device_policy(&enable_http_policy);
+ FakeSystemState::Get()->set_device_policy(&enable_http_policy);
EXPECT_CALL(enable_http_policy, GetHttpDownloadsEnabled(_))
.WillRepeatedly(DoAll(SetArgPointee<0>(true), Return(true)));
@@ -1325,30 +1300,29 @@
TEST_F(PayloadStateTest, PayloadTypeMetricWhenTypeIsDelta) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls("Hash6437", true, true, &payload_state, &response);
// Simulate a successful download and update.
payload_state.DownloadComplete();
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportSuccessfulUpdateMetrics(
_, _, kPayloadTypeDelta, _, _, _, _, _, _, _));
payload_state.UpdateSucceeded();
// Mock the request to a request where the delta was disabled but Omaha sends
// a delta anyway and test again.
- OmahaRequestParams params(&fake_system_state);
+ OmahaRequestParams params;
params.set_delta_okay(false);
- fake_system_state.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls("Hash6437", true, true, &payload_state, &response);
payload_state.DownloadComplete();
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportSuccessfulUpdateMetrics(
_, _, kPayloadTypeDelta, _, _, _, _, _, _, _));
payload_state.UpdateSucceeded();
@@ -1357,21 +1331,20 @@
TEST_F(PayloadStateTest, PayloadTypeMetricWhenTypeIsForcedFull) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
// Mock the request to a request where the delta was disabled.
- OmahaRequestParams params(&fake_system_state);
+ OmahaRequestParams params;
params.set_delta_okay(false);
- fake_system_state.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash6437", true, false, &payload_state, &response);
// Simulate a successful download and update.
payload_state.DownloadComplete();
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportSuccessfulUpdateMetrics(
_, _, kPayloadTypeForcedFull, _, _, _, _, _, _, _));
payload_state.UpdateSucceeded();
@@ -1380,35 +1353,33 @@
TEST_F(PayloadStateTest, PayloadTypeMetricWhenTypeIsFull) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash6437", true, false, &payload_state, &response);
// Mock the request to a request where the delta is enabled, although the
// result is full.
- OmahaRequestParams params(&fake_system_state);
+ OmahaRequestParams params;
params.set_delta_okay(true);
- fake_system_state.set_request_params(¶ms);
+ FakeSystemState::Get()->set_request_params(¶ms);
// Simulate a successful download and update.
payload_state.DownloadComplete();
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportSuccessfulUpdateMetrics(
_, _, kPayloadTypeFull, _, _, _, _, _, _, _));
payload_state.UpdateSucceeded();
}
TEST_F(PayloadStateTest, RebootAfterUpdateFailedMetric) {
- FakeSystemState fake_system_state;
OmahaResponse response;
PayloadState payload_state;
FakePrefs fake_prefs;
- fake_system_state.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash3141", true, false, &payload_state, &response);
@@ -1418,40 +1389,43 @@
payload_state.ExpectRebootInNewVersion("Version:12345678");
// Reboot into the same environment to get an UMA metric with a value of 1.
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportFailedUpdateCount(1));
payload_state.ReportFailedBootIfNeeded();
- Mock::VerifyAndClearExpectations(fake_system_state.mock_metrics_reporter());
+ Mock::VerifyAndClearExpectations(
+ FakeSystemState::Get()->mock_metrics_reporter());
// Simulate a second update and reboot into the same environment, this should
// send a value of 2.
payload_state.ExpectRebootInNewVersion("Version:12345678");
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportFailedUpdateCount(2));
payload_state.ReportFailedBootIfNeeded();
- Mock::VerifyAndClearExpectations(fake_system_state.mock_metrics_reporter());
+ Mock::VerifyAndClearExpectations(
+ FakeSystemState::Get()->mock_metrics_reporter());
// Simulate a third failed reboot to new version, but this time for a
// different payload. This should send a value of 1 this time.
payload_state.ExpectRebootInNewVersion("Version:3141592");
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportFailedUpdateCount(1));
payload_state.ReportFailedBootIfNeeded();
- Mock::VerifyAndClearExpectations(fake_system_state.mock_metrics_reporter());
+ Mock::VerifyAndClearExpectations(
+ FakeSystemState::Get()->mock_metrics_reporter());
}
TEST_F(PayloadStateTest, RebootAfterUpdateSucceed) {
- FakeSystemState fake_system_state;
OmahaResponse response;
PayloadState payload_state;
FakePrefs fake_prefs;
- fake_system_state.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
- FakeBootControl* fake_boot_control = fake_system_state.fake_boot_control();
+ FakeBootControl* fake_boot_control =
+ FakeSystemState::Get()->fake_boot_control();
fake_boot_control->SetCurrentSlot(0);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash3141", true, false, &payload_state, &response);
@@ -1463,7 +1437,7 @@
// Change the BootDevice to a different one, no metric should be sent.
fake_boot_control->SetCurrentSlot(1);
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportFailedUpdateCount(_))
.Times(0);
payload_state.ReportFailedBootIfNeeded();
@@ -1475,13 +1449,12 @@
}
TEST_F(PayloadStateTest, RebootAfterCanceledUpdate) {
- FakeSystemState fake_system_state;
OmahaResponse response;
PayloadState payload_state;
FakePrefs fake_prefs;
- fake_system_state.set_prefs(&fake_prefs);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash3141", true, false, &payload_state, &response);
@@ -1490,7 +1463,7 @@
payload_state.UpdateSucceeded();
payload_state.ExpectRebootInNewVersion("Version:12345678");
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportFailedUpdateCount(_))
.Times(0);
@@ -1502,14 +1475,13 @@
}
TEST_F(PayloadStateTest, UpdateSuccessWithWipedPrefs) {
- FakeSystemState fake_system_state;
PayloadState payload_state;
FakePrefs fake_prefs;
- fake_system_state.set_prefs(&fake_prefs);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
+ EXPECT_TRUE(payload_state.Initialize());
- EXPECT_CALL(*fake_system_state.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportFailedUpdateCount(_))
.Times(0);
@@ -1520,11 +1492,10 @@
TEST_F(PayloadStateTest, DisallowP2PAfterTooManyAttempts) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
FakePrefs fake_prefs;
- fake_system_state.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash8593", true, false, &payload_state, &response);
@@ -1541,13 +1512,12 @@
TEST_F(PayloadStateTest, DisallowP2PAfterDeadline) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
FakeClock fake_clock;
FakePrefs fake_prefs;
- fake_system_state.set_clock(&fake_clock);
- fake_system_state.set_prefs(&fake_prefs);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ FakeSystemState::Get()->set_clock(&fake_clock);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash8593", true, false, &payload_state, &response);
@@ -1587,11 +1557,10 @@
TEST_F(PayloadStateTest, P2PStateVarsInitialValue) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
FakePrefs fake_prefs;
- fake_system_state.set_prefs(&fake_prefs);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash8593", true, false, &payload_state, &response);
@@ -1603,12 +1572,11 @@
TEST_F(PayloadStateTest, P2PStateVarsArePersisted) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
FakeClock fake_clock;
FakePrefs fake_prefs;
- fake_system_state.set_clock(&fake_clock);
- fake_system_state.set_prefs(&fake_prefs);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ FakeSystemState::Get()->set_clock(&fake_clock);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash8593", true, false, &payload_state, &response);
@@ -1624,7 +1592,7 @@
// Now create a new PayloadState and check that it loads the state
// vars correctly.
PayloadState payload_state2;
- EXPECT_TRUE(payload_state2.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state2.Initialize());
EXPECT_EQ(1, payload_state2.GetP2PNumAttempts());
EXPECT_EQ(time, payload_state2.GetP2PFirstAttemptTimestamp());
}
@@ -1632,13 +1600,12 @@
TEST_F(PayloadStateTest, P2PStateVarsAreClearedOnNewResponse) {
OmahaResponse response;
PayloadState payload_state;
- FakeSystemState fake_system_state;
FakeClock fake_clock;
FakePrefs fake_prefs;
- fake_system_state.set_clock(&fake_clock);
- fake_system_state.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_clock(&fake_clock);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
SetupPayloadStateWith2Urls(
"Hash8593", true, false, &payload_state, &response);
@@ -1663,11 +1630,10 @@
TEST_F(PayloadStateTest, NextPayloadResetsUrlIndex) {
PayloadState payload_state;
- FakeSystemState fake_system_state;
StrictMock<MockExcluder> mock_excluder;
- EXPECT_CALL(*fake_system_state.mock_update_attempter(), GetExcluder())
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetExcluder())
.WillOnce(Return(&mock_excluder));
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
OmahaResponse response;
response.packages.push_back(
@@ -1693,11 +1659,10 @@
TEST_F(PayloadStateTest, ExcludeNoopForNonExcludables) {
PayloadState payload_state;
- FakeSystemState fake_system_state;
StrictMock<MockExcluder> mock_excluder;
- EXPECT_CALL(*fake_system_state.mock_update_attempter(), GetExcluder())
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetExcluder())
.WillOnce(Return(&mock_excluder));
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
OmahaResponse response;
response.packages.push_back(
@@ -1715,11 +1680,10 @@
TEST_F(PayloadStateTest, ExcludeOnlyCanExcludables) {
PayloadState payload_state;
- FakeSystemState fake_system_state;
StrictMock<MockExcluder> mock_excluder;
- EXPECT_CALL(*fake_system_state.mock_update_attempter(), GetExcluder())
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetExcluder())
.WillOnce(Return(&mock_excluder));
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
OmahaResponse response;
response.packages.push_back(
@@ -1738,11 +1702,10 @@
TEST_F(PayloadStateTest, IncrementFailureExclusionTest) {
PayloadState payload_state;
- FakeSystemState fake_system_state;
StrictMock<MockExcluder> mock_excluder;
- EXPECT_CALL(*fake_system_state.mock_update_attempter(), GetExcluder())
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetExcluder())
.WillOnce(Return(&mock_excluder));
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
OmahaResponse response;
// Critical package.
@@ -1782,11 +1745,10 @@
TEST_F(PayloadStateTest, HaltExclusionPostPayloadExhaustion) {
PayloadState payload_state;
- FakeSystemState fake_system_state;
StrictMock<MockExcluder> mock_excluder;
- EXPECT_CALL(*fake_system_state.mock_update_attempter(), GetExcluder())
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetExcluder())
.WillOnce(Return(&mock_excluder));
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
OmahaResponse response;
// Non-critical package.
@@ -1813,8 +1775,7 @@
TEST_F(PayloadStateTest, NonInfinitePayloadIndexIncrement) {
PayloadState payload_state;
- FakeSystemState fake_system_state;
- EXPECT_TRUE(payload_state.Initialize(&fake_system_state));
+ EXPECT_TRUE(payload_state.Initialize());
payload_state.SetResponse({});
diff --git a/cros/real_system_state.cc b/cros/real_system_state.cc
index aff9863..0b2b49d 100644
--- a/cros/real_system_state.cc
+++ b/cros/real_system_state.cc
@@ -61,7 +61,7 @@
LOG_IF(INFO, !hardware_->IsNormalBootMode()) << "Booted in dev mode.";
LOG_IF(INFO, !hardware_->IsOfficialBuild()) << "Booted non-official build.";
- connection_manager_ = connection_manager::CreateConnectionManager(this);
+ connection_manager_ = connection_manager::CreateConnectionManager();
if (!connection_manager_) {
LOG(ERROR) << "Error initializing the ConnectionManagerInterface.";
return false;
@@ -133,8 +133,7 @@
new CertificateChecker(prefs_.get(), &openssl_wrapper_));
certificate_checker_->Init();
- update_attempter_.reset(
- new UpdateAttempter(this, certificate_checker_.get()));
+ update_attempter_.reset(new UpdateAttempter(certificate_checker_.get()));
// Initialize the UpdateAttempter before the UpdateManager.
update_attempter_->Init();
@@ -142,8 +141,7 @@
// Initialize the Update Manager using the default state factory.
chromeos_update_manager::State* um_state =
chromeos_update_manager::DefaultStateFactory(&policy_provider_,
- kiosk_app_proxy_.get(),
- this);
+ kiosk_app_proxy_.get());
if (!um_state) {
LOG(ERROR) << "Failed to initialize the Update Manager.";
@@ -164,7 +162,7 @@
kMaxP2PFilesToKeep,
base::TimeDelta::FromDays(kMaxP2PFileAgeDays)));
- if (!payload_state_.Initialize(this)) {
+ if (!payload_state_.Initialize()) {
LOG(ERROR) << "Failed to initialize the payload state object.";
return false;
}
diff --git a/cros/real_system_state.h b/cros/real_system_state.h
index 1e45dc1..348c31b 100644
--- a/cros/real_system_state.h
+++ b/cros/real_system_state.h
@@ -47,14 +47,14 @@
// used by the actual product code.
class RealSystemState : public SystemState {
public:
- // Constructs all system objects that do not require separate initialization;
- // see Initialize() below for the remaining ones.
- RealSystemState() = default;
~RealSystemState() = default;
- // Initializes and sets systems objects that require an initialization
- // separately from construction. Returns |true| on success.
- bool Initialize();
+ static void CreateInstance() {
+ CHECK(!g_instance_) << "SystemState has been previously created.";
+ RealSystemState* rss = new RealSystemState();
+ g_instance_.reset(rss);
+ LOG_IF(FATAL, !rss->Initialize()) << "Failed to initialize system state.";
+ }
// SystemState overrides.
void set_device_policy(const policy::DevicePolicy* device_policy) override {
@@ -108,6 +108,14 @@
DlcServiceInterface* dlcservice() override { return dlcservice_.get(); }
private:
+ // Constructs all system objects that do not require separate initialization;
+ // see Initialize() below for the remaining ones.
+ RealSystemState() = default;
+
+ // Initializes and sets systems objects that require an initialization
+ // separately from construction. Returns |true| on success.
+ bool Initialize();
+
// Real DBus proxies using the DBus connection.
std::unique_ptr<org::chromium::KioskAppServiceInterfaceProxy>
kiosk_app_proxy_;
@@ -155,7 +163,7 @@
std::unique_ptr<UpdateAttempter> update_attempter_;
// Common parameters for all Omaha requests.
- OmahaRequestParams request_params_{this};
+ OmahaRequestParams request_params_;
std::unique_ptr<P2PManager> p2p_manager_;
diff --git a/cros/update_attempter.cc b/cros/update_attempter.cc
index 5c21d04..745272c 100644
--- a/cros/update_attempter.cc
+++ b/cros/update_attempter.cc
@@ -126,10 +126,8 @@
return code;
}
-UpdateAttempter::UpdateAttempter(SystemState* system_state,
- CertificateChecker* cert_checker)
+UpdateAttempter::UpdateAttempter(CertificateChecker* cert_checker)
: processor_(new ActionProcessor()),
- system_state_(system_state),
cert_checker_(cert_checker),
is_install_(false) {}
@@ -150,8 +148,8 @@
// Pulling from the SystemState can only be done after construction, since
// this is an aggregate of various objects (such as the UpdateAttempter),
// which requires them all to be constructed prior to it being used.
- prefs_ = system_state_->prefs();
- omaha_request_params_ = system_state_->request_params();
+ prefs_ = SystemState::Get()->prefs();
+ omaha_request_params_ = SystemState::Get()->request_params();
if (cert_checker_)
cert_checker_->SetObserver(this);
@@ -171,7 +169,7 @@
return false;
chromeos_update_manager::UpdateManager* const update_manager =
- system_state_->update_manager();
+ SystemState::Get()->update_manager();
CHECK(update_manager);
Callback<void(EvalStatus, const UpdateCheckParams&)> callback =
Bind(&UpdateAttempter::OnUpdateScheduled, base::Unretained(this));
@@ -187,8 +185,8 @@
// Initiate update checks.
ScheduleUpdates();
- auto update_boot_flags_action =
- std::make_unique<UpdateBootFlagsAction>(system_state_->boot_control());
+ auto update_boot_flags_action = std::make_unique<UpdateBootFlagsAction>(
+ SystemState::Get()->boot_control());
processor_->EnqueueAction(std::move(update_boot_flags_action));
// Update boot flags after 45 seconds.
MessageLoop::current()->PostDelayedTask(
@@ -212,16 +210,16 @@
void UpdateAttempter::CertificateChecked(ServerToCheck server_to_check,
CertificateCheckResult result) {
- system_state_->metrics_reporter()->ReportCertificateCheckMetrics(
+ SystemState::Get()->metrics_reporter()->ReportCertificateCheckMetrics(
server_to_check, result);
}
bool UpdateAttempter::CheckAndReportDailyMetrics() {
int64_t stored_value;
- Time now = system_state_->clock()->GetWallclockTime();
- if (system_state_->prefs()->Exists(kPrefsDailyMetricsLastReportedAt) &&
- system_state_->prefs()->GetInt64(kPrefsDailyMetricsLastReportedAt,
- &stored_value)) {
+ Time now = SystemState::Get()->clock()->GetWallclockTime();
+ if (SystemState::Get()->prefs()->Exists(kPrefsDailyMetricsLastReportedAt) &&
+ SystemState::Get()->prefs()->GetInt64(kPrefsDailyMetricsLastReportedAt,
+ &stored_value)) {
Time last_reported_at = Time::FromInternalValue(stored_value);
TimeDelta time_reported_since = now - last_reported_at;
if (time_reported_since.InSeconds() < 0) {
@@ -244,8 +242,8 @@
}
LOG(INFO) << "Reporting daily metrics.";
- system_state_->prefs()->SetInt64(kPrefsDailyMetricsLastReportedAt,
- now.ToInternalValue());
+ SystemState::Get()->prefs()->SetInt64(kPrefsDailyMetricsLastReportedAt,
+ now.ToInternalValue());
ReportOSAge();
@@ -254,10 +252,6 @@
void UpdateAttempter::ReportOSAge() {
struct stat sb;
-
- if (system_state_ == nullptr)
- return;
-
if (stat("/etc/lsb-release", &sb) != 0) {
PLOG(ERROR) << "Error getting file status for /etc/lsb-release "
<< "(Note: this may happen in some unit tests)";
@@ -265,7 +259,7 @@
}
Time lsb_release_timestamp = Time::FromTimeSpec(sb.st_ctim);
- Time now = system_state_->clock()->GetWallclockTime();
+ Time now = SystemState::Get()->clock()->GetWallclockTime();
TimeDelta age = now - lsb_release_timestamp;
if (age.InSeconds() < 0) {
LOG(ERROR) << "The OS age (" << utils::FormatTimeDelta(age)
@@ -274,7 +268,7 @@
return;
}
- system_state_->metrics_reporter()->ReportDailyMetrics(age);
+ SystemState::Get()->metrics_reporter()->ReportDailyMetrics(age);
}
void UpdateAttempter::Update(const UpdateCheckParams& params) {
@@ -293,8 +287,7 @@
// not performing an update check because of this.
LOG(INFO) << "Not updating b/c we already updated and we're waiting for "
<< "reboot, we'll ping Omaha instead";
- system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
- system_state_,
+ SystemState::Get()->metrics_reporter()->ReportUpdateCheckMetrics(
metrics::CheckResult::kRebootPending,
metrics::CheckReaction::kUnset,
metrics::DownloadErrorCode::kUnset);
@@ -337,8 +330,8 @@
else
LOG(INFO) << "No device policies/settings present.";
- system_state_->set_device_policy(device_policy);
- system_state_->p2p_manager()->SetDevicePolicy(device_policy);
+ SystemState::Get()->set_device_policy(device_policy);
+ SystemState::Get()->p2p_manager()->SetDevicePolicy(device_policy);
}
void UpdateAttempter::CalculateP2PParams(bool interactive) {
@@ -351,31 +344,31 @@
// (Why would a developer want to opt in? If they are working on the
// update_engine or p2p codebases so they can actually test their code.)
- if (system_state_ != nullptr) {
- if (!system_state_->p2p_manager()->IsP2PEnabled()) {
- LOG(INFO) << "p2p is not enabled - disallowing p2p for both"
- << " downloading and sharing.";
+ if (!SystemState::Get()->p2p_manager()->IsP2PEnabled()) {
+ LOG(INFO) << "p2p is not enabled - disallowing p2p for both"
+ << " downloading and sharing.";
+ } else {
+ // Allow p2p for sharing, even in interactive checks.
+ use_p2p_for_sharing = true;
+ if (!interactive) {
+ LOG(INFO) << "Non-interactive check - allowing p2p for downloading";
+ use_p2p_for_downloading = true;
} else {
- // Allow p2p for sharing, even in interactive checks.
- use_p2p_for_sharing = true;
- if (!interactive) {
- LOG(INFO) << "Non-interactive check - allowing p2p for downloading";
- use_p2p_for_downloading = true;
- } else {
- LOG(INFO) << "Forcibly disabling use of p2p for downloading "
- << "since this update attempt is interactive.";
- }
+ LOG(INFO) << "Forcibly disabling use of p2p for downloading "
+ << "since this update attempt is interactive.";
}
}
- PayloadStateInterface* const payload_state = system_state_->payload_state();
+ PayloadStateInterface* const payload_state =
+ SystemState::Get()->payload_state();
payload_state->SetUsingP2PForDownloading(use_p2p_for_downloading);
payload_state->SetUsingP2PForSharing(use_p2p_for_sharing);
}
bool UpdateAttempter::CalculateUpdateParams(const UpdateCheckParams& params) {
http_response_code_ = 0;
- PayloadStateInterface* const payload_state = system_state_->payload_state();
+ PayloadStateInterface* const payload_state =
+ SystemState::Get()->payload_state();
// Refresh the policy before computing all the update parameters.
RefreshDevicePolicy();
@@ -419,8 +412,9 @@
// Set Quick Fix Build token if policy is set and the device is enterprise
// enrolled.
string token;
- if (system_state_ && system_state_->device_policy()) {
- if (!system_state_->device_policy()->GetDeviceQuickFixBuildToken(&token))
+ if (SystemState::Get()->device_policy()) {
+ if (!SystemState::Get()->device_policy()->GetDeviceQuickFixBuildToken(
+ &token))
token.clear();
}
omaha_request_params_->set_autoupdate_token(token);
@@ -470,7 +464,8 @@
// Take a copy of the old scatter value before we update it, as
// we need to update the waiting period if this value changes.
TimeDelta old_scatter_factor = scatter_factor_;
- const policy::DevicePolicy* device_policy = system_state_->device_policy();
+ const policy::DevicePolicy* device_policy =
+ SystemState::Get()->device_policy();
if (device_policy) {
int64_t new_scatter_factor_in_secs = 0;
device_policy->GetScatterFactorInSeconds(&new_scatter_factor_in_secs);
@@ -484,8 +479,8 @@
LOG(INFO) << "Scattering disabled since scatter factor is set to 0";
} else if (interactive) {
LOG(INFO) << "Scattering disabled as this is an interactive update check";
- } else if (system_state_->hardware()->IsOOBEEnabled() &&
- !system_state_->hardware()->IsOOBEComplete(nullptr)) {
+ } else if (SystemState::Get()->hardware()->IsOOBEEnabled() &&
+ !SystemState::Get()->hardware()->IsOOBEComplete(nullptr)) {
LOG(INFO) << "Scattering disabled since OOBE is enabled but not complete "
"yet";
} else {
@@ -587,14 +582,14 @@
// fails, we'll still be able to scatter based on our in-memory value.
// The persistence only helps in ensuring a good overall distribution
// across multiple devices if they tend to reboot too often.
- system_state_->payload_state()->SetScatteringWaitPeriod(
+ SystemState::Get()->payload_state()->SetScatteringWaitPeriod(
omaha_request_params_->waiting_period());
}
void UpdateAttempter::CalculateStagingParams(bool interactive) {
- bool oobe_complete = system_state_->hardware()->IsOOBEEnabled() &&
- system_state_->hardware()->IsOOBEComplete(nullptr);
- auto device_policy = system_state_->device_policy();
+ bool oobe_complete = SystemState::Get()->hardware()->IsOOBEEnabled() &&
+ SystemState::Get()->hardware()->IsOOBEComplete(nullptr);
+ auto device_policy = SystemState::Get()->device_policy();
StagingCase staging_case = StagingCase::kOff;
if (device_policy && !interactive && oobe_complete) {
staging_wait_time_ = omaha_request_params_->waiting_period();
@@ -634,7 +629,7 @@
bool UpdateAttempter::ResetDlcPrefs(const string& dlc_id) {
vector<string> failures;
- PrefsInterface* prefs = system_state_->prefs();
+ PrefsInterface* prefs = SystemState::Get()->prefs();
for (auto& sub_key :
{kPrefsPingActive, kPrefsPingLastActive, kPrefsPingLastRollcall}) {
auto key = prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
@@ -669,7 +664,7 @@
}
LOG(INFO) << "Set DLC (" << dlc_id << ") to "
<< (is_active ? "Active" : "Inactive");
- PrefsInterface* prefs = system_state_->prefs();
+ PrefsInterface* prefs = SystemState::Get()->prefs();
if (is_active) {
auto ping_active_key =
prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
@@ -688,11 +683,11 @@
// The first time a ping is sent, the metadata files containing the values
// sent back by the server still don't exist. A value of -1 is used to
// indicate this.
- if (!system_state_->prefs()->Exists(metadata_key))
+ if (!SystemState::Get()->prefs()->Exists(metadata_key))
return kPingNeverPinged;
int64_t value;
- if (system_state_->prefs()->GetInt64(metadata_key, &value))
+ if (SystemState::Get()->prefs()->GetInt64(metadata_key, &value))
return value;
// Return -2 when the file exists and there is a problem reading from it, or
@@ -704,11 +699,11 @@
// Set the |dlc_ids_| only for an update. This is required to get the
// currently installed DLC(s).
if (!is_install_ &&
- !system_state_->dlcservice()->GetDlcsToUpdate(&dlc_ids_)) {
+ !SystemState::Get()->dlcservice()->GetDlcsToUpdate(&dlc_ids_)) {
LOG(INFO) << "Failed to retrieve DLC module IDs from dlcservice. Check the "
"state of dlcservice, will not update DLC modules.";
}
- PrefsInterface* prefs = system_state_->prefs();
+ PrefsInterface* prefs = SystemState::Get()->prefs();
map<string, OmahaRequestParams::AppParams> dlc_apps_params;
for (const auto& dlc_id : dlc_ids_) {
OmahaRequestParams::AppParams dlc_params{
@@ -760,64 +755,55 @@
// Actions:
auto update_check_fetcher = std::make_unique<LibcurlHttpFetcher>(
- GetProxyResolver(), system_state_->hardware());
+ GetProxyResolver(), SystemState::Get()->hardware());
update_check_fetcher->set_server_to_check(ServerToCheck::kUpdate);
// Try harder to connect to the network, esp when not interactive.
// See comment in libcurl_http_fetcher.cc.
update_check_fetcher->set_no_network_max_retries(interactive ? 1 : 3);
update_check_fetcher->set_is_update_check(true);
- auto update_check_action =
- std::make_unique<OmahaRequestAction>(system_state_,
- nullptr,
- std::move(update_check_fetcher),
- false,
- session_id_);
- auto response_handler_action =
- std::make_unique<OmahaResponseHandlerAction>(system_state_);
- auto update_boot_flags_action =
- std::make_unique<UpdateBootFlagsAction>(system_state_->boot_control());
+ auto update_check_action = std::make_unique<OmahaRequestAction>(
+ nullptr, std::move(update_check_fetcher), false, session_id_);
+ auto response_handler_action = std::make_unique<OmahaResponseHandlerAction>();
+ auto update_boot_flags_action = std::make_unique<UpdateBootFlagsAction>(
+ SystemState::Get()->boot_control());
auto download_started_action = std::make_unique<OmahaRequestAction>(
- system_state_,
new OmahaEvent(OmahaEvent::kTypeUpdateDownloadStarted),
std::make_unique<LibcurlHttpFetcher>(GetProxyResolver(),
- system_state_->hardware()),
+ SystemState::Get()->hardware()),
false,
session_id_);
- LibcurlHttpFetcher* download_fetcher =
- new LibcurlHttpFetcher(GetProxyResolver(), system_state_->hardware());
+ LibcurlHttpFetcher* download_fetcher = new LibcurlHttpFetcher(
+ GetProxyResolver(), SystemState::Get()->hardware());
download_fetcher->set_server_to_check(ServerToCheck::kDownload);
if (interactive)
download_fetcher->set_max_retry_count(kDownloadMaxRetryCountInteractive);
download_fetcher->SetHeader(kXGoogleUpdateSessionId, session_id_);
auto download_action =
std::make_unique<DownloadAction>(prefs_,
- system_state_->boot_control(),
- system_state_->hardware(),
- system_state_,
+ SystemState::Get()->boot_control(),
+ SystemState::Get()->hardware(),
download_fetcher, // passes ownership
interactive);
download_action->set_delegate(this);
auto download_finished_action = std::make_unique<OmahaRequestAction>(
- system_state_,
new OmahaEvent(OmahaEvent::kTypeUpdateDownloadFinished),
std::make_unique<LibcurlHttpFetcher>(GetProxyResolver(),
- system_state_->hardware()),
+ SystemState::Get()->hardware()),
false,
session_id_);
auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
- system_state_->boot_control()->GetDynamicPartitionControl());
+ SystemState::Get()->boot_control()->GetDynamicPartitionControl());
auto update_complete_action = std::make_unique<OmahaRequestAction>(
- system_state_,
new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
std::make_unique<LibcurlHttpFetcher>(GetProxyResolver(),
- system_state_->hardware()),
+ SystemState::Get()->hardware()),
false,
session_id_);
auto postinstall_runner_action = std::make_unique<PostinstallRunnerAction>(
- system_state_->boot_control(), system_state_->hardware());
+ SystemState::Get()->boot_control(), SystemState::Get()->hardware());
postinstall_runner_action->set_delegate(this);
// Bond them together. We have to use the leaf-types when calling
@@ -851,7 +837,8 @@
// Enterprise-enrolled devices have an empty owner in their device policy.
string owner;
RefreshDevicePolicy();
- const policy::DevicePolicy* device_policy = system_state_->device_policy();
+ const policy::DevicePolicy* device_policy =
+ SystemState::Get()->device_policy();
if (device_policy && (!device_policy->GetOwner(&owner) || owner.empty())) {
LOG(ERROR) << "Enterprise device detected. "
<< "Cannot perform a powerwash for enterprise devices.";
@@ -870,10 +857,11 @@
LOG(INFO) << "Setting rollback options.";
install_plan_.reset(new InstallPlan());
install_plan_->target_slot = GetRollbackSlot();
- install_plan_->source_slot = system_state_->boot_control()->GetCurrentSlot();
+ install_plan_->source_slot =
+ SystemState::Get()->boot_control()->GetCurrentSlot();
- TEST_AND_RETURN_FALSE(
- install_plan_->LoadPartitionsFromSlots(system_state_->boot_control()));
+ TEST_AND_RETURN_FALSE(install_plan_->LoadPartitionsFromSlots(
+ SystemState::Get()->boot_control()));
install_plan_->powerwash_required = powerwash;
LOG(INFO) << "Using this install plan:";
@@ -882,14 +870,14 @@
auto install_plan_action =
std::make_unique<InstallPlanAction>(*install_plan_);
auto postinstall_runner_action = std::make_unique<PostinstallRunnerAction>(
- system_state_->boot_control(), system_state_->hardware());
+ SystemState::Get()->boot_control(), SystemState::Get()->hardware());
postinstall_runner_action->set_delegate(this);
BondActions(install_plan_action.get(), postinstall_runner_action.get());
processor_->EnqueueAction(std::move(install_plan_action));
processor_->EnqueueAction(std::move(postinstall_runner_action));
// Update the payload state for Rollback.
- system_state_->payload_state()->Rollback();
+ SystemState::Get()->payload_state()->Rollback();
SetStatusAndNotify(UpdateStatus::ATTEMPTING_ROLLBACK);
@@ -906,9 +894,10 @@
BootControlInterface::Slot UpdateAttempter::GetRollbackSlot() const {
LOG(INFO) << "UpdateAttempter::GetRollbackSlot";
- const unsigned int num_slots = system_state_->boot_control()->GetNumSlots();
+ const unsigned int num_slots =
+ SystemState::Get()->boot_control()->GetNumSlots();
const BootControlInterface::Slot current_slot =
- system_state_->boot_control()->GetCurrentSlot();
+ SystemState::Get()->boot_control()->GetCurrentSlot();
LOG(INFO) << " Installed slots: " << num_slots;
LOG(INFO) << " Booted from slot: "
@@ -922,7 +911,7 @@
vector<BootControlInterface::Slot> bootable_slots;
for (BootControlInterface::Slot slot = 0; slot < num_slots; slot++) {
if (slot != current_slot &&
- system_state_->boot_control()->IsSlotBootable(slot)) {
+ SystemState::Get()->boot_control()->IsSlotBootable(slot)) {
LOG(INFO) << "Found bootable slot "
<< BootControlInterface::SlotName(slot);
return slot;
@@ -1028,7 +1017,7 @@
}
bool UpdateAttempter::RebootIfNeeded() {
- if (system_state_->power_manager()->RequestReboot())
+ if (SystemState::Get()->power_manager()->RequestReboot())
return true;
return RebootDirectly();
@@ -1040,7 +1029,7 @@
return;
prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
- int64_t value = system_state_->clock()->GetBootTime().ToInternalValue();
+ int64_t value = SystemState::Get()->clock()->GetBootTime().ToInternalValue();
prefs_->SetInt64(kPrefsUpdateCompletedBootTime, value);
}
@@ -1100,19 +1089,19 @@
}
void UpdateAttempter::UpdateLastCheckedTime() {
- last_checked_time_ = system_state_->clock()->GetWallclockTime().ToTimeT();
+ last_checked_time_ =
+ SystemState::Get()->clock()->GetWallclockTime().ToTimeT();
}
void UpdateAttempter::UpdateRollbackHappened() {
- DCHECK(system_state_);
- DCHECK(system_state_->payload_state());
+ DCHECK(SystemState::Get()->payload_state());
DCHECK(policy_provider_);
- if (system_state_->payload_state()->GetRollbackHappened() &&
+ if (SystemState::Get()->payload_state()->GetRollbackHappened() &&
(policy_provider_->device_policy_is_loaded() ||
policy_provider_->IsConsumerDevice())) {
// Rollback happened, but we already went through OOBE and policy is
// present or it's a consumer device.
- system_state_->payload_state()->SetRollbackHappened(false);
+ SystemState::Get()->payload_state()->SetRollbackHappened(false);
}
}
@@ -1155,7 +1144,7 @@
omaha_request_params_->app_version());
DeltaPerformer::ResetUpdateProgress(prefs_, false);
- system_state_->payload_state()->UpdateSucceeded();
+ SystemState::Get()->payload_state()->UpdateSucceeded();
// Since we're done with scattering fully at this point, this is the
// safest point delete the state files, as we're sure that the status is
@@ -1167,8 +1156,8 @@
// after reboot so that the same device is not favored or punished in any
// way.
prefs_->Delete(kPrefsUpdateCheckCount);
- system_state_->payload_state()->SetScatteringWaitPeriod(TimeDelta());
- system_state_->payload_state()->SetStagingWaitPeriod(TimeDelta());
+ SystemState::Get()->payload_state()->SetScatteringWaitPeriod(TimeDelta());
+ SystemState::Get()->payload_state()->SetStagingWaitPeriod(TimeDelta());
prefs_->Delete(kPrefsUpdateFirstSeenAt);
// Note: below this comment should only be on |ErrorCode::kSuccess|.
@@ -1189,7 +1178,8 @@
void UpdateAttempter::ProcessingDoneInstall(const ActionProcessor* processor,
ErrorCode code) {
- if (!system_state_->dlcservice()->InstallCompleted(GetSuccessfulDlcIds()))
+ if (!SystemState::Get()->dlcservice()->InstallCompleted(
+ GetSuccessfulDlcIds()))
LOG(WARNING) << "dlcservice didn't successfully handle install completion.";
SetStatusAndNotify(UpdateStatus::IDLE);
ScheduleUpdates();
@@ -1200,7 +1190,7 @@
ErrorCode code) {
WriteUpdateCompletedMarker();
- if (!system_state_->dlcservice()->UpdateCompleted(GetSuccessfulDlcIds()))
+ if (!SystemState::Get()->dlcservice()->UpdateCompleted(GetSuccessfulDlcIds()))
LOG(WARNING) << "dlcservice didn't successfully handle update completion.";
SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
ScheduleUpdates();
@@ -1222,19 +1212,19 @@
// If we just downloaded a rollback image, we should preserve this fact
// over the following powerwash.
if (install_plan_->is_rollback) {
- system_state_->payload_state()->SetRollbackHappened(true);
- system_state_->metrics_reporter()->ReportEnterpriseRollbackMetrics(
+ SystemState::Get()->payload_state()->SetRollbackHappened(true);
+ SystemState::Get()->metrics_reporter()->ReportEnterpriseRollbackMetrics(
/*success=*/true, install_plan_->version);
}
// Expect to reboot into the new version to send the proper metric during
// next boot.
- system_state_->payload_state()->ExpectRebootInNewVersion(
+ SystemState::Get()->payload_state()->ExpectRebootInNewVersion(
target_version_uid);
} else {
// If we just finished a rollback, then we expect to have no Omaha
// response. Otherwise, it's an error.
- if (system_state_->payload_state()->GetRollbackVersion().empty()) {
+ if (SystemState::Get()->payload_state()->GetRollbackVersion().empty()) {
LOG(ERROR) << "Can't send metrics because there was no Omaha response";
}
}
@@ -1382,7 +1372,7 @@
uint64_t total) {
// The PayloadState keeps track of how many bytes were actually downloaded
// from a given URL for the URL skipping logic.
- system_state_->payload_state()->DownloadProgress(bytes_progressed);
+ SystemState::Get()->payload_state()->DownloadProgress(bytes_progressed);
double progress = 0;
if (total)
@@ -1396,7 +1386,7 @@
}
void UpdateAttempter::DownloadComplete() {
- system_state_->payload_state()->DownloadComplete();
+ SystemState::Get()->payload_state()->DownloadComplete();
}
void UpdateAttempter::ProgressUpdate(double progress) {
@@ -1441,7 +1431,7 @@
ret_value = prefs_->Delete(kPrefsLastFp, {kDlcPrefsSubDir}) && ret_value;
// Update the boot flags so the current slot has higher priority.
- BootControlInterface* boot_control = system_state_->boot_control();
+ BootControlInterface* boot_control = SystemState::Get()->boot_control();
if (!boot_control->SetActiveBootSlot(boot_control->GetCurrentSlot()))
ret_value = false;
@@ -1452,7 +1442,7 @@
ret_value = false;
// Notify the PayloadState that the successful payload was canceled.
- system_state_->payload_state()->ResetUpdateStatus();
+ SystemState::Get()->payload_state()->ResetUpdateStatus();
// The previous version is used to report back to omaha after reboot that
// we actually rebooted into the new version from this "prev-version". We
@@ -1482,8 +1472,9 @@
out_status->is_install = is_install_;
string str_eol_date;
- if (system_state_->prefs()->Exists(kPrefsOmahaEolDate) &&
- !system_state_->prefs()->GetString(kPrefsOmahaEolDate, &str_eol_date))
+ if (SystemState::Get()->prefs()->Exists(kPrefsOmahaEolDate) &&
+ !SystemState::Get()->prefs()->GetString(kPrefsOmahaEolDate,
+ &str_eol_date))
LOG(ERROR) << "Failed to retrieve kPrefsOmahaEolDate pref.";
out_status->eol_date = StringToEolDate(str_eol_date);
@@ -1510,13 +1501,13 @@
uint32_t UpdateAttempter::GetErrorCodeFlags() {
uint32_t flags = 0;
- if (!system_state_->hardware()->IsNormalBootMode())
+ if (!SystemState::Get()->hardware()->IsNormalBootMode())
flags |= static_cast<uint32_t>(ErrorCode::kDevModeFlag);
if (install_plan_ && install_plan_->is_resume)
flags |= static_cast<uint32_t>(ErrorCode::kResumedFlag);
- if (!system_state_->hardware()->IsOfficialBuild())
+ if (!SystemState::Get()->hardware()->IsOfficialBuild())
flags |= static_cast<uint32_t>(ErrorCode::kTestImageFlag);
if (!omaha_request_params_->IsUpdateUrlOfficial()) {
@@ -1529,7 +1520,7 @@
bool UpdateAttempter::ShouldCancel(ErrorCode* cancel_reason) {
// Check if the channel we're attempting to update to is the same as the
// target channel currently chosen by the user.
- OmahaRequestParams* params = system_state_->request_params();
+ OmahaRequestParams* params = SystemState::Get()->request_params();
if (params->download_channel() != params->target_channel()) {
LOG(ERROR) << "Aborting download as target channel: "
<< params->target_channel()
@@ -1587,21 +1578,20 @@
return false;
LOG(ERROR) << "Update failed.";
- system_state_->payload_state()->UpdateFailed(error_event_->error_code);
+ SystemState::Get()->payload_state()->UpdateFailed(error_event_->error_code);
// Send metrics if it was a rollback.
if (install_plan_ && install_plan_->is_rollback) {
- system_state_->metrics_reporter()->ReportEnterpriseRollbackMetrics(
+ SystemState::Get()->metrics_reporter()->ReportEnterpriseRollbackMetrics(
/*success=*/false, install_plan_->version);
}
// Send it to Omaha.
LOG(INFO) << "Reporting the error event";
auto error_event_action = std::make_unique<OmahaRequestAction>(
- system_state_,
error_event_.release(), // Pass ownership.
std::make_unique<LibcurlHttpFetcher>(GetProxyResolver(),
- system_state_->hardware()),
+ SystemState::Get()->hardware()),
false,
session_id_);
processor_->EnqueueAction(std::move(error_event_action));
@@ -1644,10 +1634,9 @@
ResetInteractivityFlags();
auto ping_action = std::make_unique<OmahaRequestAction>(
- system_state_,
nullptr,
std::make_unique<LibcurlHttpFetcher>(GetProxyResolver(),
- system_state_->hardware()),
+ SystemState::Get()->hardware()),
true,
"" /* session_id */);
processor_->set_delegate(nullptr);
@@ -1730,9 +1719,9 @@
// in case we rebooted because of a crash of the old version, so we
// can do a proper crash report with correct information.
// This must be done before calling
- // system_state_->payload_state()->UpdateEngineStarted() since it will
+ // SystemState::Get()->payload_state()->UpdateEngineStarted() since it will
// delete SystemUpdated marker file.
- if (system_state_->system_rebooted() &&
+ if (SystemState::Get()->system_rebooted() &&
prefs_->Exists(kPrefsSystemUpdatedMarker)) {
if (!prefs_->GetString(kPrefsPreviousVersion, &prev_version_)) {
// If we fail to get the version string, make sure it stays empty.
@@ -1740,20 +1729,19 @@
}
}
- system_state_->payload_state()->UpdateEngineStarted();
+ SystemState::Get()->payload_state()->UpdateEngineStarted();
StartP2PAtStartup();
- excluder_ = CreateExcluder(system_state_->prefs());
+ excluder_ = CreateExcluder(SystemState::Get()->prefs());
}
bool UpdateAttempter::StartP2PAtStartup() {
- if (system_state_ == nullptr ||
- !system_state_->p2p_manager()->IsP2PEnabled()) {
+ if (!SystemState::Get()->p2p_manager()->IsP2PEnabled()) {
LOG(INFO) << "Not starting p2p at startup since it's not enabled.";
return false;
}
- if (system_state_->p2p_manager()->CountSharedFiles() < 1) {
+ if (SystemState::Get()->p2p_manager()->CountSharedFiles() < 1) {
LOG(INFO) << "Not starting p2p at startup since our application "
<< "is not sharing any files.";
return false;
@@ -1763,22 +1751,19 @@
}
bool UpdateAttempter::StartP2PAndPerformHousekeeping() {
- if (system_state_ == nullptr)
- return false;
-
- if (!system_state_->p2p_manager()->IsP2PEnabled()) {
+ if (!SystemState::Get()->p2p_manager()->IsP2PEnabled()) {
LOG(INFO) << "Not starting p2p since it's not enabled.";
return false;
}
LOG(INFO) << "Ensuring that p2p is running.";
- if (!system_state_->p2p_manager()->EnsureP2PRunning()) {
+ if (!SystemState::Get()->p2p_manager()->EnsureP2PRunning()) {
LOG(ERROR) << "Error starting p2p.";
return false;
}
LOG(INFO) << "Performing p2p housekeeping.";
- if (!system_state_->p2p_manager()->PerformHousekeeping()) {
+ if (!SystemState::Get()->p2p_manager()->PerformHousekeeping()) {
LOG(ERROR) << "Error performing housekeeping for p2p.";
return false;
}
@@ -1825,12 +1810,12 @@
// * The debugd dev features are accessible (i.e. in devmode with no owner).
// This protects users running a base image, while still allowing a specific
// window (gated by the debug dev features) where `cros flash` is usable.
- if (!system_state_->hardware()->IsOfficialBuild()) {
+ if (!SystemState::Get()->hardware()->IsOfficialBuild()) {
LOG(INFO) << "Non-official build; allowing any update source.";
return true;
}
- if (system_state_->hardware()->AreDevFeaturesEnabled()) {
+ if (SystemState::Get()->hardware()->AreDevFeaturesEnabled()) {
LOG(INFO) << "Developer features enabled; allowing custom update sources.";
return true;
}
@@ -1841,20 +1826,22 @@
}
void UpdateAttempter::ReportTimeToUpdateAppliedMetric() {
- const policy::DevicePolicy* device_policy = system_state_->device_policy();
+ const policy::DevicePolicy* device_policy =
+ SystemState::Get()->device_policy();
if (device_policy && device_policy->IsEnterpriseEnrolled()) {
vector<policy::DevicePolicy::WeeklyTimeInterval> parsed_intervals;
bool has_time_restrictions =
device_policy->GetDisallowedTimeIntervals(&parsed_intervals);
int64_t update_first_seen_at_int;
- if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
- if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
- &update_first_seen_at_int)) {
+ if (SystemState::Get()->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
+ if (SystemState::Get()->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
+ &update_first_seen_at_int)) {
TimeDelta update_delay =
- system_state_->clock()->GetWallclockTime() -
+ SystemState::Get()->clock()->GetWallclockTime() -
Time::FromInternalValue(update_first_seen_at_int);
- system_state_->metrics_reporter()
+ SystemState::Get()
+ ->metrics_reporter()
->ReportEnterpriseUpdateSeenToDownloadDays(has_time_restrictions,
update_delay.InDays());
}
diff --git a/cros/update_attempter.h b/cros/update_attempter.h
index 24c6f54..09e613f 100644
--- a/cros/update_attempter.h
+++ b/cros/update_attempter.h
@@ -65,7 +65,7 @@
using UpdateAttemptFlags = update_engine::UpdateAttemptFlags;
static const int kMaxDeltaUpdateFailures;
- UpdateAttempter(SystemState* system_state, CertificateChecker* cert_checker);
+ explicit UpdateAttempter(CertificateChecker* cert_checker);
~UpdateAttempter() override;
// Further initialization to be done post construction.
@@ -360,7 +360,7 @@
// Calculates all the scattering related parameters (such as waiting period,
// which type of scattering is enabled, etc.) and also updates/deletes
// the corresponding prefs file used in scattering. Should be called
- // only after the device policy has been loaded and set in the system_state_.
+ // only after the device policy has been loaded and set in the system state.
void CalculateScatteringParams(bool interactive);
// Sets a random value for the waiting period to wait for before downloading
@@ -460,10 +460,6 @@
std::unique_ptr<ActionProcessor> processor_;
- // External state of the system outside the update_engine process
- // carved out separately to mock out easily in unit tests.
- SystemState* system_state_;
-
// Pointer to the certificate checker instance to use.
CertificateChecker* cert_checker_;
@@ -474,7 +470,7 @@
std::unique_ptr<InstallPlan> install_plan_;
// Pointer to the preferences store interface. This is just a cached
- // copy of system_state->prefs() because it's used in many methods and
+ // copy of SystemState::Get()->prefs() because it's used in many methods and
// is convenient this way.
PrefsInterface* prefs_ = nullptr;
diff --git a/cros/update_attempter_unittest.cc b/cros/update_attempter_unittest.cc
index f3211a0..ab4a5f2 100644
--- a/cros/update_attempter_unittest.cc
+++ b/cros/update_attempter_unittest.cc
@@ -169,8 +169,7 @@
// methods.
class UpdateAttempterUnderTest : public UpdateAttempter {
public:
- explicit UpdateAttempterUnderTest(SystemState* system_state)
- : UpdateAttempter(system_state, nullptr) {}
+ UpdateAttempterUnderTest() : UpdateAttempter(nullptr) {}
void Update(const UpdateCheckParams& params) override {
update_called_ = true;
@@ -223,27 +222,24 @@
class UpdateAttempterTest : public ::testing::Test {
protected:
- UpdateAttempterTest()
- : certificate_checker_(fake_system_state_.mock_prefs(),
- &openssl_wrapper_) {
+ void SetUp() override {
// Override system state members.
- fake_system_state_.set_connection_manager(&mock_connection_manager);
- fake_system_state_.set_update_attempter(&attempter_);
- fake_system_state_.set_dlcservice(&mock_dlcservice_);
- fake_system_state_.set_update_manager(&mock_update_manager_);
+ FakeSystemState::CreateInstance();
+ FakeSystemState::Get()->set_connection_manager(&mock_connection_manager);
+ FakeSystemState::Get()->set_update_attempter(&attempter_);
+ FakeSystemState::Get()->set_dlcservice(&mock_dlcservice_);
+ FakeSystemState::Get()->set_update_manager(&mock_update_manager_);
loop_.SetAsCurrent();
- certificate_checker_.Init();
+ certificate_checker_.reset(new CertificateChecker(
+ FakeSystemState::Get()->mock_prefs(), &openssl_wrapper_));
+ certificate_checker_->Init();
attempter_.set_forced_update_pending_callback(
new base::Callback<void(bool, bool)>(base::Bind([](bool, bool) {})));
// Finish initializing the attempter.
attempter_.Init();
- }
- void SetUp() override {
- EXPECT_NE(nullptr, attempter_.system_state_);
- EXPECT_NE(nullptr, attempter_.system_state_->update_manager());
EXPECT_EQ(0, attempter_.http_response_code_);
EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
EXPECT_EQ(0.0, attempter_.download_progress_);
@@ -252,21 +248,21 @@
EXPECT_EQ(0ULL, attempter_.new_payload_size_);
processor_ = new NiceMock<MockActionProcessor>();
attempter_.processor_.reset(processor_); // Transfers ownership.
- prefs_ = fake_system_state_.mock_prefs();
+ prefs_ = FakeSystemState::Get()->mock_prefs();
// Setup store/load semantics of P2P properties via the mock |PayloadState|.
actual_using_p2p_for_downloading_ = false;
- EXPECT_CALL(*fake_system_state_.mock_payload_state(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
SetUsingP2PForDownloading(_))
.WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
- EXPECT_CALL(*fake_system_state_.mock_payload_state(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
GetUsingP2PForDownloading())
.WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
actual_using_p2p_for_sharing_ = false;
- EXPECT_CALL(*fake_system_state_.mock_payload_state(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
SetUsingP2PForSharing(_))
.WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
- EXPECT_CALL(*fake_system_state_.mock_payload_state(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
GetUsingP2PForDownloading())
.WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
}
@@ -320,16 +316,14 @@
base::SingleThreadTaskExecutor base_loop_{base::MessagePumpType::IO};
brillo::BaseMessageLoop loop_{base_loop_.task_runner()};
- FakeSystemState fake_system_state_;
- UpdateAttempterUnderTest attempter_{&fake_system_state_};
+ UpdateAttempterUnderTest attempter_;
OpenSSLWrapper openssl_wrapper_;
- CertificateChecker certificate_checker_;
+ std::unique_ptr<CertificateChecker> certificate_checker_;
MockDlcService mock_dlcservice_;
MockUpdateManager mock_update_manager_;
NiceMock<MockActionProcessor>* processor_;
- NiceMock<MockPrefs>*
- prefs_; // Shortcut to |fake_system_state_->mock_prefs()|.
+ NiceMock<MockPrefs>* prefs_;
NiceMock<MockConnectionManager> mock_connection_manager;
// |CheckForUpdate()| test params.
@@ -348,9 +342,9 @@
void UpdateAttempterTest::TestCheckForUpdate() {
// Setup
attempter_.status_ = cfu_params_.status;
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(
cfu_params_.is_official_build);
- fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(
+ FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(
cfu_params_.are_dev_features_enabled);
// Invocation
@@ -508,7 +502,6 @@
DownloadAction action(prefs_,
nullptr,
nullptr,
- nullptr,
fetcher.release(),
false /* interactive */);
EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
@@ -610,8 +603,7 @@
TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
fetcher->FailTransfer(500); // Sets the HTTP response code.
- OmahaRequestAction action(
- &fake_system_state_, nullptr, std::move(fetcher), false, "");
+ OmahaRequestAction action(nullptr, std::move(fetcher), false, "");
ObjectCollectorAction<OmahaResponse> collector_action;
BondActions(&action, &collector_action);
OmahaResponse response;
@@ -630,7 +622,7 @@
string boot_id;
EXPECT_TRUE(utils::GetBootId(&boot_id));
fake_prefs.SetString(kPrefsUpdateCompletedOnBootId, boot_id);
- fake_system_state_.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
attempter_.Init();
EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
}
@@ -639,12 +631,10 @@
EXPECT_EQ(ErrorCode::kSuccess,
GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
- FakeSystemState fake_system_state;
- OmahaRequestAction omaha_request_action(
- &fake_system_state, nullptr, nullptr, false, "");
+ OmahaRequestAction omaha_request_action(nullptr, nullptr, false, "");
EXPECT_EQ(ErrorCode::kOmahaRequestError,
GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
- OmahaResponseHandlerAction omaha_response_handler_action(&fake_system_state_);
+ OmahaResponseHandlerAction omaha_response_handler_action;
EXPECT_EQ(
ErrorCode::kOmahaResponseHandlerError,
GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
@@ -654,7 +644,8 @@
ErrorCode::kFilesystemVerifierError,
GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
PostinstallRunnerAction postinstall_runner_action(
- fake_system_state.fake_boot_control(), fake_system_state.fake_hardware());
+ FakeSystemState::Get()->fake_boot_control(),
+ FakeSystemState::Get()->fake_hardware());
EXPECT_EQ(
ErrorCode::kPostinstallRunnerError,
GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
@@ -709,16 +700,17 @@
TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
EXPECT_CALL(*processor_, StartProcessing()).Times(0);
- EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), UpdateFailed(_))
.Times(0);
OmahaResponse response;
string url1 = "http://url1";
response.packages.push_back({.payload_urls = {url1, "https://url"}});
- EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetCurrentUrl())
+ EXPECT_CALL(*(FakeSystemState::Get()->mock_payload_state()), GetCurrentUrl())
.WillRepeatedly(Return(url1));
- fake_system_state_.mock_payload_state()->SetResponse(response);
+ FakeSystemState::Get()->mock_payload_state()->SetResponse(response);
attempter_.ScheduleErrorEventAction();
- EXPECT_EQ(url1, fake_system_state_.mock_payload_state()->GetCurrentUrl());
+ EXPECT_EQ(url1,
+ FakeSystemState::Get()->mock_payload_state()->GetCurrentUrl());
}
TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
@@ -727,7 +719,7 @@
&AbstractAction::Type, OmahaRequestAction::StaticType()))));
EXPECT_CALL(*processor_, StartProcessing());
ErrorCode err = ErrorCode::kError;
- EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(err));
+ EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), UpdateFailed(err));
attempter_.error_event_.reset(new OmahaEvent(
OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
attempter_.ScheduleErrorEventAction();
@@ -799,7 +791,7 @@
// Create a device policy so that we can change settings.
auto device_policy = std::make_unique<policy::MockDevicePolicy>();
EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
- fake_system_state_.set_device_policy(device_policy.get());
+ FakeSystemState::Get()->set_device_policy(device_policy.get());
if (enterprise_rollback) {
// We return an empty owner as this is an enterprise.
EXPECT_CALL(*device_policy, GetOwner(_))
@@ -818,8 +810,8 @@
BootControlInterface::Slot rollback_slot = 1;
LOG(INFO) << "Test Mark Bootable: "
<< BootControlInterface::SlotName(rollback_slot);
- fake_system_state_.fake_boot_control()->SetSlotBootable(rollback_slot,
- true);
+ FakeSystemState::Get()->fake_boot_control()->SetSlotBootable(rollback_slot,
+ true);
}
bool is_rollback_allowed = false;
@@ -944,7 +936,7 @@
TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
MockP2PManager mock_p2p_manager;
- fake_system_state_.set_p2p_manager(&mock_p2p_manager);
+ FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
mock_p2p_manager.fake().SetP2PEnabled(false);
EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
attempter_.UpdateEngineStarted();
@@ -952,7 +944,7 @@
TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
MockP2PManager mock_p2p_manager;
- fake_system_state_.set_p2p_manager(&mock_p2p_manager);
+ FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
mock_p2p_manager.fake().SetP2PEnabled(true);
EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
attempter_.UpdateEngineStarted();
@@ -960,7 +952,7 @@
TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
MockP2PManager mock_p2p_manager;
- fake_system_state_.set_p2p_manager(&mock_p2p_manager);
+ FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
mock_p2p_manager.fake().SetP2PEnabled(true);
mock_p2p_manager.fake().SetCountSharedFilesResult(1);
EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
@@ -978,7 +970,7 @@
// If P2P is not enabled, check that we do not attempt housekeeping
// and do not convey that P2P is to be used.
MockP2PManager mock_p2p_manager;
- fake_system_state_.set_p2p_manager(&mock_p2p_manager);
+ FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
mock_p2p_manager.fake().SetP2PEnabled(false);
EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
attempter_.Update({});
@@ -998,7 +990,7 @@
// If P2P is enabled, but starting it fails ensure we don't do
// any housekeeping and do not convey that P2P should be used.
MockP2PManager mock_p2p_manager;
- fake_system_state_.set_p2p_manager(&mock_p2p_manager);
+ FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
mock_p2p_manager.fake().SetP2PEnabled(true);
mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
@@ -1021,7 +1013,7 @@
// If P2P is enabled, starting it works but housekeeping fails, ensure
// we do not convey P2P is to be used.
MockP2PManager mock_p2p_manager;
- fake_system_state_.set_p2p_manager(&mock_p2p_manager);
+ FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
mock_p2p_manager.fake().SetP2PEnabled(true);
mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
@@ -1041,7 +1033,7 @@
void UpdateAttempterTest::P2PEnabledStart() {
MockP2PManager mock_p2p_manager;
- fake_system_state_.set_p2p_manager(&mock_p2p_manager);
+ FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
// If P2P is enabled and starting it works, check that we performed
// housekeeping and that we convey P2P should be used.
mock_p2p_manager.fake().SetP2PEnabled(true);
@@ -1063,7 +1055,7 @@
void UpdateAttempterTest::P2PEnabledInteractiveStart() {
MockP2PManager mock_p2p_manager;
- fake_system_state_.set_p2p_manager(&mock_p2p_manager);
+ FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
// For an interactive check, if P2P is enabled and starting it
// works, check that we performed housekeeping and that we convey
// P2P should be used for sharing but NOT for downloading.
@@ -1092,7 +1084,7 @@
auto device_policy = std::make_unique<policy::MockDevicePolicy>();
EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
- fake_system_state_.set_device_policy(device_policy.get());
+ FakeSystemState::Get()->set_device_policy(device_policy.get());
EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
.WillRepeatedly(
@@ -1122,7 +1114,7 @@
FakePrefs fake_prefs;
attempter_.prefs_ = &fake_prefs;
- fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
+ FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
@@ -1130,7 +1122,7 @@
auto device_policy = std::make_unique<policy::MockDevicePolicy>();
EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
- fake_system_state_.set_device_policy(device_policy.get());
+ FakeSystemState::Get()->set_device_policy(device_policy.get());
EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
.WillRepeatedly(
@@ -1179,8 +1171,8 @@
FakePrefs fake_prefs;
attempter_.prefs_ = &fake_prefs;
- fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
- fake_system_state_.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
EXPECT_TRUE(
fake_prefs.SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
@@ -1192,7 +1184,7 @@
auto device_policy = std::make_unique<policy::MockDevicePolicy>();
EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
- fake_system_state_.set_device_policy(device_policy.get());
+ FakeSystemState::Get()->set_device_policy(device_policy.get());
EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
.WillRepeatedly(
@@ -1221,7 +1213,7 @@
void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule,
FakePrefs* prefs) {
attempter_.prefs_ = prefs;
- fake_system_state_.set_prefs(prefs);
+ FakeSystemState::Get()->set_prefs(prefs);
int64_t initial_value = 8;
EXPECT_TRUE(
@@ -1231,7 +1223,7 @@
auto device_policy = std::make_unique<policy::MockDevicePolicy>();
EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
- fake_system_state_.set_device_policy(device_policy.get());
+ FakeSystemState::Get()->set_device_policy(device_policy.get());
EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
.WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
@@ -1250,7 +1242,7 @@
void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
// Tests that staging sets its prefs properly and turns off scattering.
- fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
+ FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
FakePrefs fake_prefs;
SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
@@ -1307,7 +1299,7 @@
void UpdateAttempterTest::StagingOffIfInteractiveStart() {
// Tests that staging is turned off when an interactive update is requested.
- fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
+ FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
FakePrefs fake_prefs;
SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
@@ -1326,8 +1318,8 @@
void UpdateAttempterTest::StagingOffIfOobeStart() {
// Tests that staging is turned off if OOBE hasn't been completed.
- fake_system_state_.fake_hardware()->SetIsOOBEEnabled(true);
- fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
+ FakeSystemState::Get()->fake_hardware()->SetIsOOBEEnabled(true);
+ FakeSystemState::Get()->fake_hardware()->UnsetIsOOBEComplete();
FakePrefs fake_prefs;
SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
@@ -1342,8 +1334,8 @@
FakeClock fake_clock;
FakePrefs fake_prefs;
- fake_system_state_.set_clock(&fake_clock);
- fake_system_state_.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_clock(&fake_clock);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
Time epoch = Time::FromInternalValue(0);
fake_clock.SetWallclockTime(epoch);
@@ -1404,9 +1396,9 @@
TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
FakeClock fake_clock;
fake_clock.SetBootTime(Time::FromTimeT(42));
- fake_system_state_.set_clock(&fake_clock);
+ FakeSystemState::Get()->set_clock(&fake_clock);
FakePrefs fake_prefs;
- fake_system_state_.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
attempter_.Init();
Time boot_time;
@@ -1419,19 +1411,19 @@
}
TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(false);
EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
}
TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
- fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(true);
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
+ FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(true);
EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
}
TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
- fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
+ FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(false);
EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
}
@@ -1623,8 +1615,8 @@
}
TEST_F(UpdateAttempterTest, CheckForInstallTest) {
- fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
- fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
+ FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
+ FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(false);
attempter_.CheckForInstall({}, "autest");
EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
@@ -1662,19 +1654,21 @@
UpdateCheckParams params;
attempter_.CalculateUpdateParams({.target_version_prefix = "1234"});
EXPECT_EQ("1234",
- fake_system_state_.request_params()->target_version_prefix());
+ FakeSystemState::Get()->request_params()->target_version_prefix());
attempter_.CalculateUpdateParams({});
- EXPECT_TRUE(
- fake_system_state_.request_params()->target_version_prefix().empty());
+ EXPECT_TRUE(FakeSystemState::Get()
+ ->request_params()
+ ->target_version_prefix()
+ .empty());
}
TEST_F(UpdateAttempterTest, TargetChannelHintSetAndReset) {
attempter_.CalculateUpdateParams({.lts_tag = "hint"});
- EXPECT_EQ("hint", fake_system_state_.request_params()->lts_tag());
+ EXPECT_EQ("hint", FakeSystemState::Get()->request_params()->lts_tag());
attempter_.CalculateUpdateParams({});
- EXPECT_TRUE(fake_system_state_.request_params()->lts_tag().empty());
+ EXPECT_TRUE(FakeSystemState::Get()->request_params()->lts_tag().empty());
}
TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
@@ -1683,44 +1677,47 @@
.rollback_allowed = true,
.rollback_allowed_milestones = 4,
});
- EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
- EXPECT_EQ(4,
- fake_system_state_.request_params()->rollback_allowed_milestones());
+ EXPECT_TRUE(FakeSystemState::Get()->request_params()->rollback_allowed());
+ EXPECT_EQ(
+ 4,
+ FakeSystemState::Get()->request_params()->rollback_allowed_milestones());
attempter_.CalculateUpdateParams({
.target_version_prefix = "1234",
.rollback_allowed_milestones = 4,
});
- EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
- EXPECT_EQ(4,
- fake_system_state_.request_params()->rollback_allowed_milestones());
+ EXPECT_FALSE(FakeSystemState::Get()->request_params()->rollback_allowed());
+ EXPECT_EQ(
+ 4,
+ FakeSystemState::Get()->request_params()->rollback_allowed_milestones());
}
TEST_F(UpdateAttempterTest, ChannelDowngradeNoRollback) {
base::ScopedTempDir tempdir;
ASSERT_TRUE(tempdir.CreateUniqueTempDir());
- fake_system_state_.request_params()->set_root(tempdir.GetPath().value());
+ FakeSystemState::Get()->request_params()->set_root(tempdir.GetPath().value());
attempter_.CalculateUpdateParams({
.target_channel = "stable-channel",
});
- EXPECT_FALSE(fake_system_state_.request_params()->is_powerwash_allowed());
+ EXPECT_FALSE(
+ FakeSystemState::Get()->request_params()->is_powerwash_allowed());
}
TEST_F(UpdateAttempterTest, ChannelDowngradeRollback) {
base::ScopedTempDir tempdir;
ASSERT_TRUE(tempdir.CreateUniqueTempDir());
- fake_system_state_.request_params()->set_root(tempdir.GetPath().value());
+ FakeSystemState::Get()->request_params()->set_root(tempdir.GetPath().value());
attempter_.CalculateUpdateParams({
.rollback_on_channel_downgrade = true,
.target_channel = "stable-channel",
});
- EXPECT_TRUE(fake_system_state_.request_params()->is_powerwash_allowed());
+ EXPECT_TRUE(FakeSystemState::Get()->request_params()->is_powerwash_allowed());
}
TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
// Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
// but the update is being deferred by the Policy.
- OmahaResponseHandlerAction response_action(&fake_system_state_);
+ OmahaResponseHandlerAction response_action;
response_action.install_plan_.version = "a.b.c.d";
response_action.install_plan_.payloads.push_back(
{.size = 1234ULL, .type = InstallPayloadType::kFull});
@@ -1781,14 +1778,14 @@
UpdateCheckParams params = {.updates_enabled = true,
.rollback_allowed = false};
attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
- EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
+ EXPECT_FALSE(FakeSystemState::Get()->request_params()->rollback_allowed());
}
TEST_F(UpdateAttempterTest, RollbackAllowed) {
UpdateCheckParams params = {.updates_enabled = true,
.rollback_allowed = true};
attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
- EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
+ EXPECT_TRUE(FakeSystemState::Get()->request_params()->rollback_allowed());
}
TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
@@ -1815,7 +1812,8 @@
void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
bool is_policy_loaded,
bool expected_reset) {
- EXPECT_CALL(*fake_system_state_.mock_payload_state(), GetRollbackHappened())
+ EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
+ GetRollbackHappened())
.WillRepeatedly(Return(true));
auto mock_policy_provider =
std::make_unique<NiceMock<policy::MockPolicyProvider>>();
@@ -1826,7 +1824,7 @@
const policy::MockDevicePolicy device_policy;
EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
.WillRepeatedly(ReturnRef(device_policy));
- EXPECT_CALL(*fake_system_state_.mock_payload_state(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
SetRollbackHappened(false))
.Times(expected_reset ? 1 : 0);
attempter_.policy_provider_ = std::move(mock_policy_provider);
@@ -1868,7 +1866,7 @@
attempter_.install_plan_.reset(new InstallPlan);
attempter_.install_plan_->is_rollback = true;
- EXPECT_CALL(*fake_system_state_.mock_payload_state(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
SetRollbackHappened(true))
.Times(1);
attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
@@ -1878,7 +1876,7 @@
attempter_.install_plan_.reset(new InstallPlan);
attempter_.install_plan_->is_rollback = false;
- EXPECT_CALL(*fake_system_state_.mock_payload_state(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
SetRollbackHappened(true))
.Times(0);
attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
@@ -1889,7 +1887,7 @@
attempter_.install_plan_->is_rollback = true;
attempter_.install_plan_->version = kRollbackVersion;
- EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
.Times(1);
attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
@@ -1900,7 +1898,7 @@
attempter_.install_plan_->is_rollback = false;
attempter_.install_plan_->version = kRollbackVersion;
- EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportEnterpriseRollbackMetrics(_, _))
.Times(0);
attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
@@ -1911,7 +1909,7 @@
attempter_.install_plan_->is_rollback = true;
attempter_.install_plan_->version = kRollbackVersion;
- EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
.Times(1);
MockAction action;
@@ -1924,7 +1922,7 @@
attempter_.install_plan_->is_rollback = false;
attempter_.install_plan_->version = kRollbackVersion;
- EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportEnterpriseRollbackMetrics(_, _))
.Times(0);
MockAction action;
@@ -1933,7 +1931,7 @@
}
TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
- EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportEnterpriseUpdateSeenToDownloadDays(_, _))
.Times(0);
attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
@@ -1941,12 +1939,12 @@
TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
auto device_policy = std::make_unique<policy::MockDevicePolicy>();
- fake_system_state_.set_device_policy(device_policy.get());
+ FakeSystemState::Get()->set_device_policy(device_policy.get());
// Make device policy return that this is not enterprise enrolled
EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
// Ensure that the metric is not recorded.
- EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportEnterpriseUpdateSeenToDownloadDays(_, _))
.Times(0);
attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
@@ -1956,7 +1954,7 @@
TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
constexpr int kDaysToUpdate = 15;
auto device_policy = std::make_unique<policy::MockDevicePolicy>();
- fake_system_state_.set_device_policy(device_policy.get());
+ FakeSystemState::Get()->set_device_policy(device_policy.get());
// Make device policy return that this is enterprise enrolled
EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
// Pretend that there's a time restriction policy in place
@@ -1973,10 +1971,10 @@
update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
fake_clock.SetWallclockTime(update_finished_at);
- fake_system_state_.set_clock(&fake_clock);
- fake_system_state_.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_clock(&fake_clock);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
- EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
.Times(1);
attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
@@ -1986,7 +1984,7 @@
TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
constexpr int kDaysToUpdate = 15;
auto device_policy = std::make_unique<policy::MockDevicePolicy>();
- fake_system_state_.set_device_policy(device_policy.get());
+ FakeSystemState::Get()->set_device_policy(device_policy.get());
// Make device policy return that this is enterprise enrolled
EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
// Pretend that there's no time restriction policy in place
@@ -2003,10 +2001,10 @@
update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
fake_clock.SetWallclockTime(update_finished_at);
- fake_system_state_.set_clock(&fake_clock);
- fake_system_state_.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_clock(&fake_clock);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
- EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
.Times(1);
attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
@@ -2160,7 +2158,7 @@
// policy is set and the device is enterprise enrolled based on |set_token|.
string token = set_token ? "some_token" : "";
auto device_policy = std::make_unique<policy::MockDevicePolicy>();
- fake_system_state_.set_device_policy(device_policy.get());
+ FakeSystemState::Get()->set_device_policy(device_policy.get());
EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
if (set_token)
@@ -2372,12 +2370,12 @@
TEST_F(UpdateAttempterTest, CalculateDlcParamsInstallTest) {
string dlc_id = "dlc0";
FakePrefs fake_prefs;
- fake_system_state_.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
attempter_.is_install_ = true;
attempter_.dlc_ids_ = {dlc_id};
attempter_.CalculateDlcParams();
- OmahaRequestParams* params = fake_system_state_.request_params();
+ OmahaRequestParams* params = FakeSystemState::Get()->request_params();
EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
OmahaRequestParams::AppParams dlc_app_params =
params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
@@ -2387,16 +2385,16 @@
// the values sent by Omaha.
auto last_active_key = PrefsInterface::CreateSubKey(
{kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
- EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
+ EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
auto last_rollcall_key = PrefsInterface::CreateSubKey(
{kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
- EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
+ EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
}
TEST_F(UpdateAttempterTest, CalculateDlcParamsNoPrefFilesTest) {
string dlc_id = "dlc0";
FakePrefs fake_prefs;
- fake_system_state_.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
.WillOnce(
DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
@@ -2404,7 +2402,7 @@
attempter_.is_install_ = false;
attempter_.CalculateDlcParams();
- OmahaRequestParams* params = fake_system_state_.request_params();
+ OmahaRequestParams* params = FakeSystemState::Get()->request_params();
EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
OmahaRequestParams::AppParams dlc_app_params =
params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
@@ -2419,7 +2417,7 @@
TEST_F(UpdateAttempterTest, CalculateDlcParamsNonParseableValuesTest) {
string dlc_id = "dlc0";
MemoryPrefs prefs;
- fake_system_state_.set_prefs(&prefs);
+ FakeSystemState::Get()->set_prefs(&prefs);
EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
.WillOnce(
DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
@@ -2431,13 +2429,13 @@
{kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
auto last_rollcall_key = PrefsInterface::CreateSubKey(
{kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
- fake_system_state_.prefs()->SetString(active_key, "z2yz");
- fake_system_state_.prefs()->SetString(last_active_key, "z2yz");
- fake_system_state_.prefs()->SetString(last_rollcall_key, "z2yz");
+ FakeSystemState::Get()->prefs()->SetString(active_key, "z2yz");
+ FakeSystemState::Get()->prefs()->SetString(last_active_key, "z2yz");
+ FakeSystemState::Get()->prefs()->SetString(last_rollcall_key, "z2yz");
attempter_.is_install_ = false;
attempter_.CalculateDlcParams();
- OmahaRequestParams* params = fake_system_state_.request_params();
+ OmahaRequestParams* params = FakeSystemState::Get()->request_params();
EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
OmahaRequestParams::AppParams dlc_app_params =
params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
@@ -2452,7 +2450,7 @@
TEST_F(UpdateAttempterTest, CalculateDlcParamsValidValuesTest) {
string dlc_id = "dlc0";
MemoryPrefs fake_prefs;
- fake_system_state_.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
.WillOnce(
DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
@@ -2465,13 +2463,13 @@
auto last_rollcall_key = PrefsInterface::CreateSubKey(
{kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
- fake_system_state_.prefs()->SetInt64(active_key, 1);
- fake_system_state_.prefs()->SetInt64(last_active_key, 78);
- fake_system_state_.prefs()->SetInt64(last_rollcall_key, 99);
+ FakeSystemState::Get()->prefs()->SetInt64(active_key, 1);
+ FakeSystemState::Get()->prefs()->SetInt64(last_active_key, 78);
+ FakeSystemState::Get()->prefs()->SetInt64(last_rollcall_key, 99);
attempter_.is_install_ = false;
attempter_.CalculateDlcParams();
- OmahaRequestParams* params = fake_system_state_.request_params();
+ OmahaRequestParams* params = FakeSystemState::Get()->request_params();
EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
OmahaRequestParams::AppParams dlc_app_params =
params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
@@ -2486,61 +2484,61 @@
TEST_F(UpdateAttempterTest, CalculateDlcParamsRemoveStaleMetadata) {
string dlc_id = "dlc0";
FakePrefs fake_prefs;
- fake_system_state_.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
auto active_key =
PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
auto last_active_key = PrefsInterface::CreateSubKey(
{kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
auto last_rollcall_key = PrefsInterface::CreateSubKey(
{kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
- fake_system_state_.prefs()->SetInt64(active_key, kPingInactiveValue);
- fake_system_state_.prefs()->SetInt64(last_active_key, 0);
- fake_system_state_.prefs()->SetInt64(last_rollcall_key, 0);
- EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
- EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_active_key));
- EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_rollcall_key));
+ FakeSystemState::Get()->prefs()->SetInt64(active_key, kPingInactiveValue);
+ FakeSystemState::Get()->prefs()->SetInt64(last_active_key, 0);
+ FakeSystemState::Get()->prefs()->SetInt64(last_rollcall_key, 0);
+ EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
+ EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
+ EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
attempter_.dlc_ids_ = {dlc_id};
attempter_.is_install_ = true;
attempter_.CalculateDlcParams();
- EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
- EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
+ EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
+ EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
// Active key is set on install.
- EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
+ EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
int64_t temp_int;
- EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
+ EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetInt64(active_key, &temp_int));
EXPECT_EQ(temp_int, kPingActiveValue);
}
TEST_F(UpdateAttempterTest, SetDlcActiveValue) {
string dlc_id = "dlc0";
FakePrefs fake_prefs;
- fake_system_state_.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
attempter_.SetDlcActiveValue(true, dlc_id);
int64_t temp_int;
auto active_key =
PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
- EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
- EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
+ EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
+ EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetInt64(active_key, &temp_int));
EXPECT_EQ(temp_int, kPingActiveValue);
}
TEST_F(UpdateAttempterTest, SetDlcInactive) {
string dlc_id = "dlc0";
MemoryPrefs fake_prefs;
- fake_system_state_.set_prefs(&fake_prefs);
+ FakeSystemState::Get()->set_prefs(&fake_prefs);
auto sub_keys = {
kPrefsPingActive, kPrefsPingLastActive, kPrefsPingLastRollcall};
for (auto& sub_key : sub_keys) {
auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
- fake_system_state_.prefs()->SetInt64(key, 1);
- EXPECT_TRUE(fake_system_state_.prefs()->Exists(key));
+ FakeSystemState::Get()->prefs()->SetInt64(key, 1);
+ EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(key));
}
attempter_.SetDlcActiveValue(false, dlc_id);
for (auto& sub_key : sub_keys) {
auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
- EXPECT_FALSE(fake_system_state_.prefs()->Exists(key));
+ EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(key));
}
}
diff --git a/download_action.cc b/download_action.cc
index 10dffd2..adae128 100644
--- a/download_action.cc
+++ b/download_action.cc
@@ -29,6 +29,7 @@
#include "update_engine/common/boot_control_interface.h"
#include "update_engine/common/error_code_utils.h"
#include "update_engine/common/multi_range_http_fetcher.h"
+#include "update_engine/common/system_state.h"
#include "update_engine/common/utils.h"
#include "update_engine/cros/omaha_request_params.h"
#include "update_engine/cros/p2p_manager.h"
@@ -42,13 +43,11 @@
DownloadAction::DownloadAction(PrefsInterface* prefs,
BootControlInterface* boot_control,
HardwareInterface* hardware,
- SystemState* system_state,
HttpFetcher* http_fetcher,
bool interactive)
: prefs_(prefs),
boot_control_(boot_control),
hardware_(hardware),
- system_state_(system_state),
http_fetcher_(new MultiRangeHttpFetcher(http_fetcher)),
interactive_(interactive),
writer_(nullptr),
@@ -68,7 +67,8 @@
}
if (delete_p2p_file) {
- FilePath path = system_state_->p2p_manager()->FileGetPath(p2p_file_id_);
+ FilePath path =
+ SystemState::Get()->p2p_manager()->FileGetPath(p2p_file_id_);
if (unlink(path.value().c_str()) != 0) {
PLOG(ERROR) << "Error deleting p2p file " << path.value();
} else {
@@ -81,7 +81,7 @@
}
bool DownloadAction::SetupP2PSharingFd() {
- P2PManager* p2p_manager = system_state_->p2p_manager();
+ P2PManager* p2p_manager = SystemState::Get()->p2p_manager();
if (!p2p_manager->FileShare(p2p_file_id_, payload_->size)) {
LOG(ERROR) << "Unable to share file via p2p";
@@ -295,8 +295,9 @@
}
}
- if (system_state_ != nullptr) {
- const PayloadStateInterface* payload_state = system_state_->payload_state();
+ if (SystemState::Get() != nullptr) {
+ const PayloadStateInterface* payload_state =
+ SystemState::Get()->payload_state();
string file_id = utils::CalculateP2PFileId(payload_->hash, payload_->size);
if (payload_state->GetUsingP2PForSharing()) {
// If we're sharing the update, store the file_id to convey
@@ -309,7 +310,7 @@
// hash. If this is the case, we NEED to clean it up otherwise
// we're essentially timing out other peers downloading from us
// (since we're never going to complete the file).
- FilePath path = system_state_->p2p_manager()->FileGetPath(file_id);
+ FilePath path = SystemState::Get()->p2p_manager()->FileGetPath(file_id);
if (!path.empty()) {
if (unlink(path.value().c_str()) != 0) {
PLOG(ERROR) << "Error deleting p2p file " << path.value();
@@ -391,10 +392,10 @@
// Call p2p_manager_->FileMakeVisible() when we've successfully
// verified the manifest!
- if (!p2p_visible_ && system_state_ && delta_performer_.get() &&
+ if (!p2p_visible_ && SystemState::Get() && delta_performer_.get() &&
delta_performer_->IsManifestValid()) {
LOG(INFO) << "Manifest has been validated. Making p2p file visible.";
- system_state_->p2p_manager()->FileMakeVisible(p2p_file_id_);
+ SystemState::Get()->p2p_manager()->FileMakeVisible(p2p_file_id_);
p2p_visible_ = true;
}
return true;
@@ -416,7 +417,7 @@
code = delta_performer_->VerifyPayload(payload_->hash, payload_->size);
if (code == ErrorCode::kSuccess) {
if (payload_ < &install_plan_.payloads.back() &&
- system_state_->payload_state()->NextPayload()) {
+ SystemState::Get()->payload_state()->NextPayload()) {
LOG(INFO) << "Incrementing to next payload";
// No need to reset if this payload was already applied.
if (delta_performer_ && !payload_->already_applied)
@@ -425,7 +426,7 @@
bytes_received_previous_payloads_ += payload_->size;
payload_++;
install_plan_.download_url =
- system_state_->payload_state()->GetCurrentUrl();
+ SystemState::Get()->payload_state()->GetCurrentUrl();
StartDownloading();
return;
}
diff --git a/download_action_android_unittest.cc b/download_action_android_unittest.cc
index f222977..7db1c60 100644
--- a/download_action_android_unittest.cc
+++ b/download_action_android_unittest.cc
@@ -77,7 +77,6 @@
std::make_unique<DownloadAction>(&prefs,
&boot_control,
nullptr,
- nullptr,
http_fetcher,
false /* interactive */);
download_action->set_in_pipe(action_pipe);
diff --git a/download_action_unittest.cc b/download_action_unittest.cc
index 5264b0f..565c678 100644
--- a/download_action_unittest.cc
+++ b/download_action_unittest.cc
@@ -57,7 +57,9 @@
using testing::Return;
using testing::SetArgPointee;
-class DownloadActionTest : public ::testing::Test {};
+class DownloadActionTest : public ::testing::Test {
+ void SetUp() { FakeSystemState::CreateInstance(); }
+};
namespace {
@@ -128,9 +130,9 @@
void TestWithData(const brillo::Blob& data,
int fail_write,
bool use_download_delegate) {
+ FakeSystemState::CreateInstance();
brillo::FakeMessageLoop loop(nullptr);
loop.SetAsCurrent();
- FakeSystemState fake_system_state;
ScopedTempFile output_temp_file;
TestDirectFileWriter writer;
@@ -149,9 +151,9 @@
install_plan.target_slot = 1;
// We mark both slots as bootable. Only the target slot should be unbootable
// after the download starts.
- fake_system_state.fake_boot_control()->SetSlotBootable(
+ FakeSystemState::Get()->fake_boot_control()->SetSlotBootable(
install_plan.source_slot, true);
- fake_system_state.fake_boot_control()->SetSlotBootable(
+ FakeSystemState::Get()->fake_boot_control()->SetSlotBootable(
install_plan.target_slot, true);
auto feeder_action = std::make_unique<ObjectFeederAction<InstallPlan>>();
feeder_action->set_obj(install_plan);
@@ -161,9 +163,8 @@
// takes ownership of passed in HttpFetcher
auto download_action =
std::make_unique<DownloadAction>(&prefs,
- fake_system_state.boot_control(),
- fake_system_state.hardware(),
- &fake_system_state,
+ FakeSystemState::Get()->boot_control(),
+ FakeSystemState::Get()->hardware(),
http_fetcher,
false /* interactive */);
download_action->SetTestFileWriter(&writer);
@@ -194,9 +195,9 @@
loop.Run();
EXPECT_FALSE(loop.PendingTasks());
- EXPECT_TRUE(fake_system_state.fake_boot_control()->IsSlotBootable(
+ EXPECT_TRUE(FakeSystemState::Get()->fake_boot_control()->IsSlotBootable(
install_plan.source_slot));
- EXPECT_FALSE(fake_system_state.fake_boot_control()->IsSlotBootable(
+ EXPECT_FALSE(FakeSystemState::Get()->fake_boot_control()->IsSlotBootable(
install_plan.target_slot));
}
} // namespace
@@ -251,8 +252,7 @@
payload_datas.emplace_back(2 * kMockHttpFetcherChunkSize);
brillo::FakeMessageLoop loop(nullptr);
loop.SetAsCurrent();
- FakeSystemState fake_system_state;
- EXPECT_CALL(*fake_system_state.mock_payload_state(), NextPayload())
+ EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), NextPayload())
.WillOnce(Return(true));
MockFileWriter mock_file_writer;
@@ -277,9 +277,8 @@
// takes ownership of passed in HttpFetcher
auto download_action =
std::make_unique<DownloadAction>(&prefs,
- fake_system_state.boot_control(),
- fake_system_state.hardware(),
- &fake_system_state,
+ FakeSystemState::Get()->boot_control(),
+ FakeSystemState::Get()->hardware(),
http_fetcher,
false /* interactive */);
download_action->SetTestFileWriter(&mock_file_writer);
@@ -346,6 +345,7 @@
}
void TestTerminateEarly(bool use_download_delegate) {
+ FakeSystemState::CreateInstance();
brillo::FakeMessageLoop loop(nullptr);
loop.SetAsCurrent();
@@ -362,13 +362,12 @@
InstallPlan install_plan;
install_plan.payloads.resize(1);
feeder_action->set_obj(install_plan);
- FakeSystemState fake_system_state_;
+
MockPrefs prefs;
auto download_action = std::make_unique<DownloadAction>(
&prefs,
- fake_system_state_.boot_control(),
- fake_system_state_.hardware(),
- &fake_system_state_,
+ FakeSystemState::Get()->boot_control(),
+ FakeSystemState::Get()->hardware(),
new MockHttpFetcher(data.data(), data.size(), nullptr),
false /* interactive */);
download_action->SetTestFileWriter(&writer);
@@ -461,6 +460,7 @@
} // namespace
TEST(DownloadActionTest, PassObjectOutTest) {
+ FakeSystemState::CreateInstance();
brillo::FakeMessageLoop loop(nullptr);
loop.SetAsCurrent();
@@ -475,12 +475,10 @@
auto feeder_action = std::make_unique<ObjectFeederAction<InstallPlan>>();
feeder_action->set_obj(install_plan);
MockPrefs prefs;
- FakeSystemState fake_system_state_;
auto download_action =
std::make_unique<DownloadAction>(&prefs,
- fake_system_state_.boot_control(),
- fake_system_state_.hardware(),
- &fake_system_state_,
+ FakeSystemState::Get()->boot_control(),
+ FakeSystemState::Get()->hardware(),
new MockHttpFetcher("x", 1, nullptr),
false /* interactive */);
download_action->SetTestFileWriter(&writer);
@@ -512,12 +510,15 @@
class P2PDownloadActionTest : public testing::Test {
protected:
P2PDownloadActionTest()
- : start_at_offset_(0), fake_um_(fake_system_state_.fake_clock()) {}
+ : start_at_offset_(0), fake_um_(FakeSystemState::Get()->fake_clock()) {}
~P2PDownloadActionTest() override {}
// Derived from testing::Test.
- void SetUp() override { loop_.SetAsCurrent(); }
+ void SetUp() override {
+ loop_.SetAsCurrent();
+ FakeSystemState::CreateInstance();
+ }
// Derived from testing::Test.
void TearDown() override { EXPECT_FALSE(loop_.PendingTasks()); }
@@ -539,14 +540,14 @@
"cros_au",
3,
base::TimeDelta::FromDays(5)));
- fake_system_state_.set_p2p_manager(p2p_manager_.get());
+ FakeSystemState::Get()->set_p2p_manager(p2p_manager_.get());
}
// To be called by tests to perform the download. The
// |use_p2p_to_share| parameter is used to indicate whether the
// payload should be shared via p2p.
void StartDownload(bool use_p2p_to_share) {
- EXPECT_CALL(*fake_system_state_.mock_payload_state(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
GetUsingP2PForSharing())
.WillRepeatedly(Return(use_p2p_to_share));
@@ -564,9 +565,8 @@
// Note that DownloadAction takes ownership of the passed in HttpFetcher.
auto download_action = std::make_unique<DownloadAction>(
&prefs,
- fake_system_state_.boot_control(),
- fake_system_state_.hardware(),
- &fake_system_state_,
+ FakeSystemState::Get()->boot_control(),
+ FakeSystemState::Get()->hardware(),
new MockHttpFetcher(data_.c_str(), data_.length(), nullptr),
false /* interactive */);
auto http_fetcher = download_action->http_fetcher();
@@ -603,9 +603,6 @@
// The ActionProcessor used for running the actions.
ActionProcessor processor_;
- // A fake system state.
- FakeSystemState fake_system_state_;
-
// The data being downloaded.
string data_;
diff --git a/metrics_utils.h b/metrics_utils.h
index 5952ec3..3aac4e5 100644
--- a/metrics_utils.h
+++ b/metrics_utils.h
@@ -30,8 +30,6 @@
namespace chromeos_update_engine {
-class SystemState;
-
namespace metrics_utils {
// Transforms a ErrorCode value into a metrics::DownloadErrorCode.
diff --git a/payload_generator/generate_delta_main.cc b/payload_generator/generate_delta_main.cc
index 29ec290..7724c9c 100644
--- a/payload_generator/generate_delta_main.cc
+++ b/payload_generator/generate_delta_main.cc
@@ -220,7 +220,6 @@
std::make_unique<DownloadAction>(&prefs,
&fake_boot_control,
&fake_hardware,
- nullptr,
new FileFetcher(),
true /* interactive */);
auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
diff --git a/update_manager/real_system_provider.cc b/update_manager/real_system_provider.cc
index 8d30f7f..34397f3 100644
--- a/update_manager/real_system_provider.cc
+++ b/update_manager/real_system_provider.cc
@@ -24,11 +24,13 @@
#include "update_engine/common/boot_control_interface.h"
#include "update_engine/common/hardware_interface.h"
+#include "update_engine/common/system_state.h"
#include "update_engine/common/utils.h"
#include "update_engine/cros/omaha_request_params.h"
#include "update_engine/update_manager/generic_variables.h"
#include "update_engine/update_manager/variable.h"
+using chromeos_update_engine::SystemState;
using std::string;
namespace chromeos_update_manager {
@@ -98,19 +100,20 @@
bool RealSystemProvider::Init() {
var_is_normal_boot_mode_.reset(new ConstCopyVariable<bool>(
- "is_normal_boot_mode", system_state_->hardware()->IsNormalBootMode()));
+ "is_normal_boot_mode",
+ SystemState::Get()->hardware()->IsNormalBootMode()));
var_is_official_build_.reset(new ConstCopyVariable<bool>(
- "is_official_build", system_state_->hardware()->IsOfficialBuild()));
+ "is_official_build", SystemState::Get()->hardware()->IsOfficialBuild()));
var_is_oobe_complete_.reset(new CallCopyVariable<bool>(
"is_oobe_complete",
base::Bind(&chromeos_update_engine::HardwareInterface::IsOOBEComplete,
- base::Unretained(system_state_->hardware()),
+ base::Unretained(SystemState::Get()->hardware()),
nullptr)));
var_num_slots_.reset(new ConstCopyVariable<unsigned int>(
- "num_slots", system_state_->boot_control()->GetNumSlots()));
+ "num_slots", SystemState::Get()->boot_control()->GetNumSlots()));
var_kiosk_required_platform_version_.reset(new RetryPollVariable<string>(
"kiosk_required_platform_version",
@@ -120,7 +123,7 @@
var_chromeos_version_.reset(new ConstCopyVariable<base::Version>(
"chromeos_version",
- base::Version(system_state_->request_params()->app_version())));
+ base::Version(SystemState::Get()->request_params()->app_version())));
return true;
}
diff --git a/update_manager/real_system_provider.h b/update_manager/real_system_provider.h
index 91fee7f..558d3be 100644
--- a/update_manager/real_system_provider.h
+++ b/update_manager/real_system_provider.h
@@ -22,7 +22,6 @@
#include <base/version.h>
-#include "update_engine/common/system_state.h"
#include "update_engine/update_manager/system_provider.h"
namespace org {
@@ -37,10 +36,8 @@
class RealSystemProvider : public SystemProvider {
public:
RealSystemProvider(
- chromeos_update_engine::SystemState* system_state,
org::chromium::KioskAppServiceInterfaceProxyInterface* kiosk_app_proxy)
- : system_state_(system_state), kiosk_app_proxy_(kiosk_app_proxy) {
- }
+ : kiosk_app_proxy_(kiosk_app_proxy) {}
// Initializes the provider and returns whether it succeeded.
bool Init();
@@ -80,8 +77,6 @@
std::unique_ptr<Variable<std::string>> var_kiosk_required_platform_version_;
std::unique_ptr<Variable<base::Version>> var_chromeos_version_;
- chromeos_update_engine::SystemState* const system_state_;
-
org::chromium::KioskAppServiceInterfaceProxyInterface* const kiosk_app_proxy_;
DISALLOW_COPY_AND_ASSIGN(RealSystemProvider);
diff --git a/update_manager/real_system_provider_unittest.cc b/update_manager/real_system_provider_unittest.cc
index 3c77ac7..9abcad0 100644
--- a/update_manager/real_system_provider_unittest.cc
+++ b/update_manager/real_system_provider_unittest.cc
@@ -29,6 +29,7 @@
#include "update_engine/cros/fake_system_state.h"
#include "update_engine/update_manager/umtest_utils.h"
+using chromeos_update_engine::FakeSystemState;
using org::chromium::KioskAppServiceInterfaceProxyMock;
using std::unique_ptr;
using testing::_;
@@ -45,17 +46,16 @@
class UmRealSystemProviderTest : public ::testing::Test {
protected:
void SetUp() override {
+ FakeSystemState::CreateInstance();
kiosk_app_proxy_mock_.reset(new KioskAppServiceInterfaceProxyMock());
ON_CALL(*kiosk_app_proxy_mock_, GetRequiredPlatformVersion(_, _, _))
.WillByDefault(
DoAll(SetArgPointee<0>(kRequiredPlatformVersion), Return(true)));
- provider_.reset(new RealSystemProvider(&fake_system_state_,
- kiosk_app_proxy_mock_.get()));
+ provider_.reset(new RealSystemProvider(kiosk_app_proxy_mock_.get()));
EXPECT_TRUE(provider_->Init());
}
- chromeos_update_engine::FakeSystemState fake_system_state_;
unique_ptr<RealSystemProvider> provider_;
unique_ptr<KioskAppServiceInterfaceProxyMock> kiosk_app_proxy_mock_;
@@ -70,17 +70,17 @@
}
TEST_F(UmRealSystemProviderTest, IsOOBECompleteTrue) {
- fake_system_state_.fake_hardware()->SetIsOOBEComplete(base::Time());
+ FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(base::Time());
UmTestUtils::ExpectVariableHasValue(true, provider_->var_is_oobe_complete());
}
TEST_F(UmRealSystemProviderTest, IsOOBECompleteFalse) {
- fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
+ FakeSystemState::Get()->fake_hardware()->UnsetIsOOBEComplete();
UmTestUtils::ExpectVariableHasValue(false, provider_->var_is_oobe_complete());
}
TEST_F(UmRealSystemProviderTest, VersionFromRequestParams) {
- fake_system_state_.request_params()->set_app_version("1.2.3");
+ FakeSystemState::Get()->request_params()->set_app_version("1.2.3");
// Call |Init| again to pick up the version.
EXPECT_TRUE(provider_->Init());
diff --git a/update_manager/real_updater_provider.cc b/update_manager/real_updater_provider.cc
index e975b80..6da30c9 100644
--- a/update_manager/real_updater_provider.cc
+++ b/update_manager/real_updater_provider.cc
@@ -29,6 +29,7 @@
#include "update_engine/client_library/include/update_engine/update_status.h"
#include "update_engine/common/clock_interface.h"
#include "update_engine/common/prefs.h"
+#include "update_engine/common/system_state.h"
#include "update_engine/cros/omaha_request_params.h"
#include "update_engine/cros/update_attempter.h"
#include "update_engine/update_status_utils.h"
@@ -49,25 +50,16 @@
template <typename T>
class UpdaterVariableBase : public Variable<T> {
public:
- UpdaterVariableBase(const string& name,
- VariableMode mode,
- SystemState* system_state)
- : Variable<T>(name, mode), system_state_(system_state) {}
-
- protected:
- // The system state used for pulling information from the updater.
- inline SystemState* system_state() const { return system_state_; }
-
- private:
- SystemState* const system_state_;
+ UpdaterVariableBase(const string& name, VariableMode mode)
+ : Variable<T>(name, mode) {}
};
// Helper class for issuing a GetStatus() to the UpdateAttempter.
class GetStatusHelper {
public:
- GetStatusHelper(SystemState* system_state, string* errmsg) {
- is_success_ =
- system_state->update_attempter()->GetStatus(&update_engine_status_);
+ explicit GetStatusHelper(string* errmsg) {
+ is_success_ = SystemState::Get()->update_attempter()->GetStatus(
+ &update_engine_status_);
if (!is_success_ && errmsg) {
*errmsg = "Failed to get a status update from the update engine";
}
@@ -97,12 +89,12 @@
// A variable reporting the time when a last update check was issued.
class LastCheckedTimeVariable : public UpdaterVariableBase<Time> {
public:
- LastCheckedTimeVariable(const string& name, SystemState* system_state)
- : UpdaterVariableBase<Time>(name, kVariableModePoll, system_state) {}
+ explicit LastCheckedTimeVariable(const string& name)
+ : UpdaterVariableBase<Time>(name, kVariableModePoll) {}
private:
const Time* GetValue(TimeDelta /* timeout */, string* errmsg) override {
- GetStatusHelper raw(system_state(), errmsg);
+ GetStatusHelper raw(errmsg);
if (!raw.is_success())
return nullptr;
@@ -116,12 +108,12 @@
// between 0.0 and 1.0.
class ProgressVariable : public UpdaterVariableBase<double> {
public:
- ProgressVariable(const string& name, SystemState* system_state)
- : UpdaterVariableBase<double>(name, kVariableModePoll, system_state) {}
+ explicit ProgressVariable(const string& name)
+ : UpdaterVariableBase<double>(name, kVariableModePoll) {}
private:
const double* GetValue(TimeDelta /* timeout */, string* errmsg) override {
- GetStatusHelper raw(system_state(), errmsg);
+ GetStatusHelper raw(errmsg);
if (!raw.is_success())
return nullptr;
@@ -142,8 +134,8 @@
// A variable reporting the stage in which the update process is.
class StageVariable : public UpdaterVariableBase<Stage> {
public:
- StageVariable(const string& name, SystemState* system_state)
- : UpdaterVariableBase<Stage>(name, kVariableModePoll, system_state) {}
+ explicit StageVariable(const string& name)
+ : UpdaterVariableBase<Stage>(name, kVariableModePoll) {}
private:
struct CurrOpStrToStage {
@@ -175,7 +167,7 @@
};
const Stage* StageVariable::GetValue(TimeDelta /* timeout */, string* errmsg) {
- GetStatusHelper raw(system_state(), errmsg);
+ GetStatusHelper raw(errmsg);
if (!raw.is_success())
return nullptr;
@@ -191,12 +183,12 @@
// A variable reporting the version number that an update is updating to.
class NewVersionVariable : public UpdaterVariableBase<string> {
public:
- NewVersionVariable(const string& name, SystemState* system_state)
- : UpdaterVariableBase<string>(name, kVariableModePoll, system_state) {}
+ explicit NewVersionVariable(const string& name)
+ : UpdaterVariableBase<string>(name, kVariableModePoll) {}
private:
const string* GetValue(TimeDelta /* timeout */, string* errmsg) override {
- GetStatusHelper raw(system_state(), errmsg);
+ GetStatusHelper raw(errmsg);
if (!raw.is_success())
return nullptr;
@@ -209,12 +201,12 @@
// A variable reporting the size of the update being processed in bytes.
class PayloadSizeVariable : public UpdaterVariableBase<uint64_t> {
public:
- PayloadSizeVariable(const string& name, SystemState* system_state)
- : UpdaterVariableBase<uint64_t>(name, kVariableModePoll, system_state) {}
+ explicit PayloadSizeVariable(const string& name)
+ : UpdaterVariableBase<uint64_t>(name, kVariableModePoll) {}
private:
const uint64_t* GetValue(TimeDelta /* timeout */, string* errmsg) override {
- GetStatusHelper raw(system_state(), errmsg);
+ GetStatusHelper raw(errmsg);
if (!raw.is_success())
return nullptr;
@@ -233,20 +225,20 @@
// policy request.
class UpdateCompletedTimeVariable : public UpdaterVariableBase<Time> {
public:
- UpdateCompletedTimeVariable(const string& name, SystemState* system_state)
- : UpdaterVariableBase<Time>(name, kVariableModePoll, system_state) {}
+ explicit UpdateCompletedTimeVariable(const string& name)
+ : UpdaterVariableBase<Time>(name, kVariableModePoll) {}
private:
const Time* GetValue(TimeDelta /* timeout */, string* errmsg) override {
Time update_boottime;
- if (!system_state()->update_attempter()->GetBootTimeAtUpdate(
+ if (!SystemState::Get()->update_attempter()->GetBootTimeAtUpdate(
&update_boottime)) {
if (errmsg)
*errmsg = "Update completed time could not be read";
return nullptr;
}
- chromeos_update_engine::ClockInterface* clock = system_state()->clock();
+ chromeos_update_engine::ClockInterface* clock = SystemState::Get()->clock();
Time curr_boottime = clock->GetBootTime();
if (curr_boottime < update_boottime) {
if (errmsg)
@@ -263,12 +255,12 @@
// Variables reporting the current image channel.
class CurrChannelVariable : public UpdaterVariableBase<string> {
public:
- CurrChannelVariable(const string& name, SystemState* system_state)
- : UpdaterVariableBase<string>(name, kVariableModePoll, system_state) {}
+ explicit CurrChannelVariable(const string& name)
+ : UpdaterVariableBase<string>(name, kVariableModePoll) {}
private:
const string* GetValue(TimeDelta /* timeout */, string* errmsg) override {
- OmahaRequestParams* request_params = system_state()->request_params();
+ OmahaRequestParams* request_params = SystemState::Get()->request_params();
string channel = request_params->current_channel();
if (channel.empty()) {
if (errmsg)
@@ -284,12 +276,12 @@
// Variables reporting the new image channel.
class NewChannelVariable : public UpdaterVariableBase<string> {
public:
- NewChannelVariable(const string& name, SystemState* system_state)
- : UpdaterVariableBase<string>(name, kVariableModePoll, system_state) {}
+ explicit NewChannelVariable(const string& name)
+ : UpdaterVariableBase<string>(name, kVariableModePoll) {}
private:
const string* GetValue(TimeDelta /* timeout */, string* errmsg) override {
- OmahaRequestParams* request_params = system_state()->request_params();
+ OmahaRequestParams* request_params = SystemState::Get()->request_params();
string channel = request_params->target_channel();
if (channel.empty()) {
if (errmsg)
@@ -346,16 +338,16 @@
class ConsecutiveFailedUpdateChecksVariable
: public UpdaterVariableBase<unsigned int> {
public:
- ConsecutiveFailedUpdateChecksVariable(const string& name,
- SystemState* system_state)
- : UpdaterVariableBase<unsigned int>(
- name, kVariableModePoll, system_state) {}
+ explicit ConsecutiveFailedUpdateChecksVariable(const string& name)
+ : UpdaterVariableBase<unsigned int>(name, kVariableModePoll) {}
private:
const unsigned int* GetValue(TimeDelta /* timeout */,
string* /* errmsg */) override {
- return new unsigned int(
- system_state()->update_attempter()->consecutive_failed_update_checks());
+ // NOLINTNEXTLINE(readability/casting)
+ return new unsigned int(SystemState::Get()
+ ->update_attempter()
+ ->consecutive_failed_update_checks());
}
DISALLOW_COPY_AND_ASSIGN(ConsecutiveFailedUpdateChecksVariable);
@@ -365,16 +357,16 @@
class ServerDictatedPollIntervalVariable
: public UpdaterVariableBase<unsigned int> {
public:
- ServerDictatedPollIntervalVariable(const string& name,
- SystemState* system_state)
- : UpdaterVariableBase<unsigned int>(
- name, kVariableModePoll, system_state) {}
+ explicit ServerDictatedPollIntervalVariable(const string& name)
+ : UpdaterVariableBase<unsigned int>(name, kVariableModePoll) {}
private:
const unsigned int* GetValue(TimeDelta /* timeout */,
string* /* errmsg */) override {
- return new unsigned int(
- system_state()->update_attempter()->server_dictated_poll_interval());
+ // NOLINTNEXTLINE(readability/casting)
+ return new unsigned int(SystemState::Get()
+ ->update_attempter()
+ ->server_dictated_poll_interval());
}
DISALLOW_COPY_AND_ASSIGN(ServerDictatedPollIntervalVariable);
@@ -384,10 +376,10 @@
class ForcedUpdateRequestedVariable
: public UpdaterVariableBase<UpdateRequestStatus> {
public:
- ForcedUpdateRequestedVariable(const string& name, SystemState* system_state)
+ explicit ForcedUpdateRequestedVariable(const string& name)
: UpdaterVariableBase<UpdateRequestStatus>::UpdaterVariableBase(
- name, kVariableModeAsync, system_state) {
- system_state->update_attempter()->set_forced_update_pending_callback(
+ name, kVariableModeAsync) {
+ SystemState::Get()->update_attempter()->set_forced_update_pending_callback(
new base::Callback<void(bool, bool)>( // NOLINT(readability/function)
base::Bind(&ForcedUpdateRequestedVariable::Reset,
base::Unretained(this))));
@@ -419,15 +411,14 @@
class UpdateRestrictionsVariable
: public UpdaterVariableBase<UpdateRestrictions> {
public:
- UpdateRestrictionsVariable(const string& name, SystemState* system_state)
- : UpdaterVariableBase<UpdateRestrictions>(
- name, kVariableModePoll, system_state) {}
+ explicit UpdateRestrictionsVariable(const string& name)
+ : UpdaterVariableBase<UpdateRestrictions>(name, kVariableModePoll) {}
private:
const UpdateRestrictions* GetValue(TimeDelta /* timeout */,
string* /* errmsg */) override {
UpdateAttemptFlags attempt_flags =
- system_state()->update_attempter()->GetCurrentUpdateAttemptFlags();
+ SystemState::Get()->update_attempter()->GetCurrentUpdateAttemptFlags();
UpdateRestrictions restriction_flags = UpdateRestrictions::kNone;
// Don't blindly copy the whole value, test and set bits that should
// transfer from one set of flags to the other.
@@ -484,40 +475,40 @@
// RealUpdaterProvider methods.
-RealUpdaterProvider::RealUpdaterProvider(SystemState* system_state)
- : system_state_(system_state),
- var_updater_started_time_("updater_started_time",
- system_state->clock()->GetWallclockTime()),
- var_last_checked_time_(
- new LastCheckedTimeVariable("last_checked_time", system_state_)),
- var_update_completed_time_(new UpdateCompletedTimeVariable(
- "update_completed_time", system_state_)),
- var_progress_(new ProgressVariable("progress", system_state_)),
- var_stage_(new StageVariable("stage", system_state_)),
- var_new_version_(new NewVersionVariable("new_version", system_state_)),
- var_payload_size_(new PayloadSizeVariable("payload_size", system_state_)),
- var_curr_channel_(new CurrChannelVariable("curr_channel", system_state_)),
- var_new_channel_(new NewChannelVariable("new_channel", system_state_)),
+RealUpdaterProvider::RealUpdaterProvider()
+ : var_updater_started_time_(
+ "updater_started_time",
+ SystemState::Get()->clock()->GetWallclockTime()),
+ var_last_checked_time_(new LastCheckedTimeVariable("last_checked_time")),
+ var_update_completed_time_(
+ new UpdateCompletedTimeVariable("update_completed_time")),
+ var_progress_(new ProgressVariable("progress")),
+ var_stage_(new StageVariable("stage")),
+ var_new_version_(new NewVersionVariable("new_version")),
+ var_payload_size_(new PayloadSizeVariable("payload_size")),
+ var_curr_channel_(new CurrChannelVariable("curr_channel")),
+ var_new_channel_(new NewChannelVariable("new_channel")),
var_p2p_enabled_(
new BooleanPrefVariable("p2p_enabled",
- system_state_->prefs(),
+ SystemState::Get()->prefs(),
chromeos_update_engine::kPrefsP2PEnabled,
false)),
var_cellular_enabled_(new BooleanPrefVariable(
"cellular_enabled",
- system_state_->prefs(),
+ SystemState::Get()->prefs(),
chromeos_update_engine::kPrefsUpdateOverCellularPermission,
false)),
var_consecutive_failed_update_checks_(
new ConsecutiveFailedUpdateChecksVariable(
- "consecutive_failed_update_checks", system_state_)),
+ "consecutive_failed_update_checks")),
var_server_dictated_poll_interval_(new ServerDictatedPollIntervalVariable(
- "server_dictated_poll_interval", system_state_)),
- var_forced_update_requested_(new ForcedUpdateRequestedVariable(
- "forced_update_requested", system_state_)),
+ "server_dictated_poll_interval")),
+ var_forced_update_requested_(
+ new ForcedUpdateRequestedVariable("forced_update_requested")),
var_update_restrictions_(
- new UpdateRestrictionsVariable("update_restrictions", system_state_)),
+ new UpdateRestrictionsVariable("update_restrictions")),
var_test_update_check_interval_timeout_(
new TestUpdateCheckIntervalTimeoutVariable(
- "test_update_check_interval_timeout", system_state_->prefs())) {}
+ "test_update_check_interval_timeout",
+ SystemState::Get()->prefs())) {}
} // namespace chromeos_update_manager
diff --git a/update_manager/real_updater_provider.h b/update_manager/real_updater_provider.h
index a32e7e9..24298d7 100644
--- a/update_manager/real_updater_provider.h
+++ b/update_manager/real_updater_provider.h
@@ -20,7 +20,6 @@
#include <memory>
#include <string>
-#include "update_engine/common/system_state.h"
#include "update_engine/update_manager/generic_variables.h"
#include "update_engine/update_manager/updater_provider.h"
@@ -34,8 +33,7 @@
// guarantees that parts of the system state can be mocked out at any time
// during testing. We further assume that, by the time Init() is called, the
// system state object is fully populated and usable.
- explicit RealUpdaterProvider(
- chromeos_update_engine::SystemState* system_state);
+ RealUpdaterProvider();
// Initializes the provider and returns whether it succeeded.
bool Init() { return true; }
@@ -99,9 +97,6 @@
}
private:
- // A pointer to the update engine's system state aggregator.
- chromeos_update_engine::SystemState* system_state_;
-
// Variable implementations.
ConstCopyVariable<base::Time> var_updater_started_time_;
std::unique_ptr<Variable<base::Time>> var_last_checked_time_;
diff --git a/update_manager/real_updater_provider_unittest.cc b/update_manager/real_updater_provider_unittest.cc
index 0dc56ac..bde074e 100644
--- a/update_manager/real_updater_provider_unittest.cc
+++ b/update_manager/real_updater_provider_unittest.cc
@@ -100,10 +100,10 @@
class UmRealUpdaterProviderTest : public ::testing::Test {
protected:
void SetUp() override {
- fake_clock_ = fake_sys_state_.fake_clock();
- fake_sys_state_.set_prefs(&fake_prefs_);
- provider_.reset(new RealUpdaterProvider(&fake_sys_state_));
- ASSERT_NE(nullptr, provider_.get());
+ FakeSystemState::CreateInstance();
+ fake_clock_ = FakeSystemState::Get()->fake_clock();
+ FakeSystemState::Get()->set_prefs(&fake_prefs_);
+ provider_.reset(new RealUpdaterProvider());
// Check that provider initializes correctly.
ASSERT_TRUE(provider_->Init());
}
@@ -117,7 +117,7 @@
const Time kCurrBootTime = (valid ? kUpdateBootTime + kDurationSinceUpdate
: kUpdateBootTime - kDurationSinceUpdate);
const Time kCurrWallclockTime = FixedTime();
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(),
GetBootTimeAtUpdate(_))
.WillOnce(DoAll(SetArgPointee<0>(kUpdateBootTime), Return(true)));
fake_clock_->SetBootTime(kCurrBootTime);
@@ -125,8 +125,7 @@
return kCurrWallclockTime - kDurationSinceUpdate;
}
- FakeSystemState fake_sys_state_;
- FakeClock* fake_clock_; // Short for fake_sys_state_.fake_clock()
+ FakeClock* fake_clock_; // Short for FakeSystemState::Get()->fake_clock()
FakePrefs fake_prefs_;
unique_ptr<RealUpdaterProvider> provider_;
};
@@ -134,14 +133,15 @@
TEST_F(UmRealUpdaterProviderTest, UpdaterStartedTimeIsWallclockTime) {
fake_clock_->SetWallclockTime(Time::FromDoubleT(123.456));
fake_clock_->SetMonotonicTime(Time::FromDoubleT(456.123));
- // Run SetUp again to re-setup the provider under test to use these values.
- SetUp();
+ // Re-initialize to re-setup the provider under test to use these values.
+ provider_.reset(new RealUpdaterProvider());
+ ASSERT_TRUE(provider_->Init());
UmTestUtils::ExpectVariableHasValue(Time::FromDoubleT(123.456),
provider_->var_updater_started_time());
}
TEST_F(UmRealUpdaterProviderTest, GetLastCheckedTimeOkay) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(
ActionSetUpdateEngineStatusLastCheckedTime(FixedTime().ToTimeT()),
Return(true)));
@@ -150,49 +150,49 @@
}
TEST_F(UmRealUpdaterProviderTest, GetLastCheckedTimeFailNoValue) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(Return(false));
UmTestUtils::ExpectVariableNotSet(provider_->var_last_checked_time());
}
TEST_F(UmRealUpdaterProviderTest, GetProgressOkayMin) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(ActionSetUpdateEngineStatusProgress(0.0), Return(true)));
UmTestUtils::ExpectVariableHasValue(0.0, provider_->var_progress());
}
TEST_F(UmRealUpdaterProviderTest, GetProgressOkayMid) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(ActionSetUpdateEngineStatusProgress(0.3), Return(true)));
UmTestUtils::ExpectVariableHasValue(0.3, provider_->var_progress());
}
TEST_F(UmRealUpdaterProviderTest, GetProgressOkayMax) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(ActionSetUpdateEngineStatusProgress(1.0), Return(true)));
UmTestUtils::ExpectVariableHasValue(1.0, provider_->var_progress());
}
TEST_F(UmRealUpdaterProviderTest, GetProgressFailNoValue) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(Return(false));
UmTestUtils::ExpectVariableNotSet(provider_->var_progress());
}
TEST_F(UmRealUpdaterProviderTest, GetProgressFailTooSmall) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(ActionSetUpdateEngineStatusProgress(-2.0), Return(true)));
UmTestUtils::ExpectVariableNotSet(provider_->var_progress());
}
TEST_F(UmRealUpdaterProviderTest, GetProgressFailTooBig) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(ActionSetUpdateEngineStatusProgress(2.0), Return(true)));
UmTestUtils::ExpectVariableNotSet(provider_->var_progress());
}
TEST_F(UmRealUpdaterProviderTest, GetStageOkayIdle) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(
ActionSetUpdateEngineStatusStatus(update_engine::UpdateStatus::IDLE),
Return(true)));
@@ -200,7 +200,7 @@
}
TEST_F(UmRealUpdaterProviderTest, GetStageOkayCheckingForUpdate) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(ActionSetUpdateEngineStatusStatus(
update_engine::UpdateStatus::CHECKING_FOR_UPDATE),
Return(true)));
@@ -209,7 +209,7 @@
}
TEST_F(UmRealUpdaterProviderTest, GetStageOkayUpdateAvailable) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(ActionSetUpdateEngineStatusStatus(
update_engine::UpdateStatus::UPDATE_AVAILABLE),
Return(true)));
@@ -218,7 +218,7 @@
}
TEST_F(UmRealUpdaterProviderTest, GetStageOkayDownloading) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(ActionSetUpdateEngineStatusStatus(
update_engine::UpdateStatus::DOWNLOADING),
Return(true)));
@@ -227,7 +227,7 @@
}
TEST_F(UmRealUpdaterProviderTest, GetStageOkayVerifying) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(ActionSetUpdateEngineStatusStatus(
update_engine::UpdateStatus::VERIFYING),
Return(true)));
@@ -236,7 +236,7 @@
}
TEST_F(UmRealUpdaterProviderTest, GetStageOkayFinalizing) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(ActionSetUpdateEngineStatusStatus(
update_engine::UpdateStatus::FINALIZING),
Return(true)));
@@ -245,7 +245,7 @@
}
TEST_F(UmRealUpdaterProviderTest, GetStageOkayUpdatedNeedReboot) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(ActionSetUpdateEngineStatusStatus(
update_engine::UpdateStatus::UPDATED_NEED_REBOOT),
Return(true)));
@@ -254,7 +254,7 @@
}
TEST_F(UmRealUpdaterProviderTest, GetStageOkayReportingErrorEvent) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(ActionSetUpdateEngineStatusStatus(
update_engine::UpdateStatus::REPORTING_ERROR_EVENT),
Return(true)));
@@ -263,7 +263,7 @@
}
TEST_F(UmRealUpdaterProviderTest, GetStageOkayAttemptingRollback) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(ActionSetUpdateEngineStatusStatus(
update_engine::UpdateStatus::ATTEMPTING_ROLLBACK),
Return(true)));
@@ -272,13 +272,13 @@
}
TEST_F(UmRealUpdaterProviderTest, GetStageFailNoValue) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(Return(false));
UmTestUtils::ExpectVariableNotSet(provider_->var_stage());
}
TEST_F(UmRealUpdaterProviderTest, GetNewVersionOkay) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(
DoAll(ActionSetUpdateEngineStatusNewVersion("1.2.0"), Return(true)));
UmTestUtils::ExpectVariableHasValue(string("1.2.0"),
@@ -286,13 +286,13 @@
}
TEST_F(UmRealUpdaterProviderTest, GetNewVersionFailNoValue) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(Return(false));
UmTestUtils::ExpectVariableNotSet(provider_->var_new_version());
}
TEST_F(UmRealUpdaterProviderTest, GetPayloadSizeOkayZero) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(
ActionSetUpdateEngineStatusNewSizeBytes(static_cast<uint64_t>(0)),
Return(true)));
@@ -301,7 +301,7 @@
}
TEST_F(UmRealUpdaterProviderTest, GetPayloadSizeOkayArbitrary) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(ActionSetUpdateEngineStatusNewSizeBytes(
static_cast<uint64_t>(567890)),
Return(true)));
@@ -310,7 +310,7 @@
}
TEST_F(UmRealUpdaterProviderTest, GetPayloadSizeOkayTwoGigabytes) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(DoAll(ActionSetUpdateEngineStatusNewSizeBytes(
static_cast<uint64_t>(1) << 31),
Return(true)));
@@ -319,44 +319,44 @@
}
TEST_F(UmRealUpdaterProviderTest, GetPayloadSizeFailNoValue) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetStatus(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(), GetStatus(_))
.WillOnce(Return(false));
UmTestUtils::ExpectVariableNotSet(provider_->var_payload_size());
}
TEST_F(UmRealUpdaterProviderTest, GetCurrChannelOkay) {
const string kChannelName("foo-channel");
- OmahaRequestParams request_params(&fake_sys_state_);
+ OmahaRequestParams request_params;
request_params.Init("", "", {});
request_params.set_current_channel(kChannelName);
- fake_sys_state_.set_request_params(&request_params);
+ FakeSystemState::Get()->set_request_params(&request_params);
UmTestUtils::ExpectVariableHasValue(kChannelName,
provider_->var_curr_channel());
}
TEST_F(UmRealUpdaterProviderTest, GetCurrChannelFailEmpty) {
- OmahaRequestParams request_params(&fake_sys_state_);
+ OmahaRequestParams request_params;
request_params.Init("", "", {});
request_params.set_current_channel("");
- fake_sys_state_.set_request_params(&request_params);
+ FakeSystemState::Get()->set_request_params(&request_params);
UmTestUtils::ExpectVariableNotSet(provider_->var_curr_channel());
}
TEST_F(UmRealUpdaterProviderTest, GetNewChannelOkay) {
const string kChannelName("foo-channel");
- OmahaRequestParams request_params(&fake_sys_state_);
+ OmahaRequestParams request_params;
request_params.Init("", "", {});
request_params.set_target_channel(kChannelName);
- fake_sys_state_.set_request_params(&request_params);
+ FakeSystemState::Get()->set_request_params(&request_params);
UmTestUtils::ExpectVariableHasValue(kChannelName,
provider_->var_new_channel());
}
TEST_F(UmRealUpdaterProviderTest, GetNewChannelFailEmpty) {
- OmahaRequestParams request_params(&fake_sys_state_);
+ OmahaRequestParams request_params;
request_params.Init("", "", {});
request_params.set_target_channel("");
- fake_sys_state_.set_request_params(&request_params);
+ FakeSystemState::Get()->set_request_params(&request_params);
UmTestUtils::ExpectVariableNotSet(provider_->var_new_channel());
}
@@ -401,7 +401,8 @@
}
TEST_F(UmRealUpdaterProviderTest, GetUpdateCompletedTimeFailNoValue) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(), GetBootTimeAtUpdate(_))
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(),
+ GetBootTimeAtUpdate(_))
.WillOnce(Return(false));
UmTestUtils::ExpectVariableNotSet(provider_->var_update_completed_time());
}
@@ -413,7 +414,7 @@
TEST_F(UmRealUpdaterProviderTest, GetConsecutiveFailedUpdateChecks) {
const unsigned int kNumFailedChecks = 3;
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(),
consecutive_failed_update_checks())
.WillRepeatedly(Return(kNumFailedChecks));
UmTestUtils::ExpectVariableHasValue(
@@ -422,7 +423,7 @@
TEST_F(UmRealUpdaterProviderTest, GetServerDictatedPollInterval) {
const unsigned int kPollInterval = 2 * 60 * 60; // Two hours.
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(),
server_dictated_poll_interval())
.WillRepeatedly(Return(kPollInterval));
UmTestUtils::ExpectVariableHasValue(
@@ -430,7 +431,7 @@
}
TEST_F(UmRealUpdaterProviderTest, GetUpdateRestrictions) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(),
GetCurrentUpdateAttemptFlags())
.WillRepeatedly(Return(UpdateAttemptFlags::kFlagRestrictDownload |
UpdateAttemptFlags::kFlagNonInteractive));
@@ -439,7 +440,7 @@
}
TEST_F(UmRealUpdaterProviderTest, GetUpdateRestrictionsNone) {
- EXPECT_CALL(*fake_sys_state_.mock_update_attempter(),
+ EXPECT_CALL(*FakeSystemState::Get()->mock_update_attempter(),
GetCurrentUpdateAttemptFlags())
.WillRepeatedly(Return(UpdateAttemptFlags::kNone));
UmTestUtils::ExpectVariableHasValue(UpdateRestrictions::kNone,
diff --git a/update_manager/staging_utils.cc b/update_manager/staging_utils.cc
index e8f07bb..186da73 100644
--- a/update_manager/staging_utils.cc
+++ b/update_manager/staging_utils.cc
@@ -27,7 +27,6 @@
#include "update_engine/common/constants.h"
#include "update_engine/common/hardware_interface.h"
#include "update_engine/common/prefs_interface.h"
-#include "update_engine/common/system_state.h"
using base::TimeDelta;
using chromeos_update_engine::kPrefsWallClockStagingWaitPeriod;
diff --git a/update_manager/state_factory.cc b/update_manager/state_factory.cc
index 2168974..badbe23 100644
--- a/update_manager/state_factory.cc
+++ b/update_manager/state_factory.cc
@@ -27,6 +27,7 @@
#if USE_DBUS
#include "update_engine/cros/dbus_connection.h"
#endif // USE_DBUS
+#include "update_engine/common/system_state.h"
#include "update_engine/cros/shill_proxy.h"
#include "update_engine/update_manager/fake_shill_provider.h"
#include "update_engine/update_manager/real_config_provider.h"
@@ -38,17 +39,18 @@
#include "update_engine/update_manager/real_time_provider.h"
#include "update_engine/update_manager/real_updater_provider.h"
+using chromeos_update_engine::SystemState;
using std::unique_ptr;
namespace chromeos_update_manager {
State* DefaultStateFactory(
policy::PolicyProvider* policy_provider,
- org::chromium::KioskAppServiceInterfaceProxyInterface* kiosk_app_proxy,
- chromeos_update_engine::SystemState* system_state) {
- chromeos_update_engine::ClockInterface* const clock = system_state->clock();
+ org::chromium::KioskAppServiceInterfaceProxyInterface* kiosk_app_proxy) {
+ chromeos_update_engine::ClockInterface* const clock =
+ SystemState::Get()->clock();
unique_ptr<RealConfigProvider> config_provider(
- new RealConfigProvider(system_state->hardware()));
+ new RealConfigProvider(SystemState::Get()->hardware()));
#if USE_DBUS
scoped_refptr<dbus::Bus> bus =
chromeos_update_engine::DBusConnection::Get()->GetDBus();
@@ -64,11 +66,10 @@
new RealShillProvider(new chromeos_update_engine::ShillProxy(), clock));
unique_ptr<RealRandomProvider> random_provider(new RealRandomProvider());
unique_ptr<RealSystemProvider> system_provider(
- new RealSystemProvider(system_state, kiosk_app_proxy));
+ new RealSystemProvider(kiosk_app_proxy));
unique_ptr<RealTimeProvider> time_provider(new RealTimeProvider(clock));
- unique_ptr<RealUpdaterProvider> updater_provider(
- new RealUpdaterProvider(system_state));
+ unique_ptr<RealUpdaterProvider> updater_provider(new RealUpdaterProvider());
if (!(config_provider->Init() && device_policy_provider->Init() &&
random_provider->Init() &&
diff --git a/update_manager/state_factory.h b/update_manager/state_factory.h
index ac3bf6b..c53bb9c 100644
--- a/update_manager/state_factory.h
+++ b/update_manager/state_factory.h
@@ -17,7 +17,6 @@
#ifndef UPDATE_ENGINE_UPDATE_MANAGER_STATE_FACTORY_H_
#define UPDATE_ENGINE_UPDATE_MANAGER_STATE_FACTORY_H_
-#include "update_engine/common/system_state.h"
#include "update_engine/update_manager/state.h"
namespace org {
@@ -35,8 +34,7 @@
// to initialize.
State* DefaultStateFactory(
policy::PolicyProvider* policy_provider,
- org::chromium::KioskAppServiceInterfaceProxyInterface* kiosk_app_proxy,
- chromeos_update_engine::SystemState* system_state);
+ org::chromium::KioskAppServiceInterfaceProxyInterface* kiosk_app_proxy);
} // namespace chromeos_update_manager