Implement Android UE daemon using brillo::Daemon.

The setup logic for Brillo and Android devices is very similar despite
the differences in the daemon logic and exposed service interface.
This patch reuses the brillo::Daemon derived class and the main()
function from Brillo to implement the daemon and service setup in
Android as well.

Bug: 25631949
TEST=`mmma system/update_engine` on edison-eng and aosp_arm-eng

Change-Id: I15b2c2990a8055619dd407b2996ea92216c602a2
diff --git a/Android.mk b/Android.mk
index aa63dd1..6e7d200 100644
--- a/Android.mk
+++ b/Android.mk
@@ -20,7 +20,7 @@
 # by setting BRILLO_USE_* values. Note that we define local variables like
 # local_use_* to prevent leaking our default setting for other packages.
 local_use_binder := $(if $(BRILLO_USE_BINDER),$(BRILLO_USE_BINDER),1)
-local_use_dbus := $(if $(BRILLO_USE_DBUS),$(BRILLO_USE_DBUS),1)
+local_use_dbus := $(if $(BRILLO_USE_DBUS),$(BRILLO_USE_DBUS),0)
 local_use_hwid_override := \
     $(if $(BRILLO_USE_HWID_OVERRIDE),$(BRILLO_USE_HWID_OVERRIDE),0)
 local_use_mtd := $(if $(BRILLO_USE_MTD),$(BRILLO_USE_MTD),0)
@@ -259,6 +259,12 @@
 ue_libupdate_engine_exported_shared_libraries += \
     libweaved
 endif  # local_use_weave == 1
+ifeq ($(local_use_binder),1)
+ue_libupdate_engine_exported_shared_libraries += \
+    libbinder \
+    libbrillo-binder \
+    libutils
+endif  # local_use_binder == 1
 
 include $(CLEAR_VARS)
 LOCAL_MODULE := libupdate_engine
@@ -330,16 +336,11 @@
 
 ifeq ($(local_use_binder),1)
 LOCAL_AIDL_INCLUDES += $(LOCAL_PATH)/binder_bindings
-
 LOCAL_SRC_FILES += \
     binder_bindings/android/brillo/IUpdateEngine.aidl \
     binder_bindings/android/brillo/IUpdateEngineStatusCallback.aidl \
     binder_service.cc \
     parcelable_update_engine_status.cc
-
-LOCAL_SHARED_LIBRARIES += \
-    libbinder \
-    libutils
 endif  # local_use_binder == 1
 
 include $(BUILD_STATIC_LIBRARY)
@@ -365,38 +366,40 @@
 LOCAL_LDFLAGS := $(ue_common_ldflags)
 LOCAL_C_INCLUDES := \
     $(ue_common_c_includes)
+LOCAL_SHARED_LIBRARIES := \
+    $(ue_common_shared_libraries)
+LOCAL_SRC_FILES := \
+    main.cc
 
 ifdef BRILLO
-
 LOCAL_C_INCLUDES += \
     $(ue_libupdate_engine_exported_c_includes)
 LOCAL_STATIC_LIBRARIES := \
     libupdate_engine \
     $(ue_libupdate_engine_exported_static_libraries:-host=)
-LOCAL_SHARED_LIBRARIES := \
-    $(ue_common_shared_libraries) \
+LOCAL_SHARED_LIBRARIES += \
     $(ue_libupdate_engine_exported_shared_libraries:-host=)
-LOCAL_SRC_FILES := \
-    main.cc
-
 else  # !defined(BRILLO)
-
 LOCAL_AIDL_INCLUDES := $(LOCAL_PATH)/binder_bindings
-LOCAL_SHARED_LIBRARIES := \
+LOCAL_STATIC_LIBRARIES := \
+    libpayload_consumer \
+    $(ue_libpayload_consumer_exported_static_libraries:-host=)
+LOCAL_SHARED_LIBRARIES += \
+    $(ue_libpayload_consumer_exported_shared_libraries:-host=) \
     libbinder \
-    liblog \
+    libbrillo-binder \
     libutils
-LOCAL_SRC_FILES := \
+LOCAL_SRC_FILES += \
     binder_bindings/android/os/IUpdateEngine.aidl \
     binder_bindings/android/os/IUpdateEngineCallback.aidl \
-    binder_main.cc \
-    binder_service_android.cc
-
+    binder_service_android.cc \
+    daemon.cc
 endif  # defined(BRILLO)
 
 ifeq ($(local_use_binder),1)
 LOCAL_SHARED_LIBRARIES += \
     libbinder \
+    libbinderwrapper \
     libutils
 endif  # local_use_binder == 1
 
diff --git a/binder_main.cc b/binder_main.cc
deleted file mode 100644
index a4817b4..0000000
--- a/binder_main.cc
+++ /dev/null
@@ -1,91 +0,0 @@
-//
-// Copyright (C) 2015 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 <binder/IPCThreadState.h>
-#include <binder/IServiceManager.h>
-#include <binder/ProcessState.h>
-#include <utils/Errors.h>
-#include <utils/Log.h>
-#include <utils/Looper.h>
-#include <utils/StrongPointer.h>
-
-#include "update_engine/binder_service_android.h"
-
-// Log to logcat as update_engine.
-#undef LOG_TAG
-#define LOG_TAG "update_engine"
-
-namespace android {
-namespace {
-
-class BinderCallback : public LooperCallback {
- public:
-  BinderCallback() {}
-  ~BinderCallback() override {}
-
-  int handleEvent(int /* fd */, int /* events */, void* /* data */) override {
-    IPCThreadState::self()->handlePolledCommands();
-    return 1;  // Continue receiving callbacks.
-  }
-};
-
-bool run(const sp<IBinder>& service) {
-  sp<Looper> looper(Looper::prepare(0 /* opts */));
-
-  ALOGD("Connecting to binder driver");
-  int binder_fd = -1;
-  ProcessState::self()->setThreadPoolMaxThreadCount(0);
-  IPCThreadState::self()->disableBackgroundScheduling(true);
-  IPCThreadState::self()->setupPolling(&binder_fd);
-  if (binder_fd < 0) {
-    return false;
-  }
-
-  sp<BinderCallback> cb(new BinderCallback);
-  if (looper->addFd(binder_fd, Looper::POLL_CALLBACK, Looper::EVENT_INPUT, cb,
-                    nullptr) != 1) {
-    ALOGE("Failed to add binder FD to Looper");
-    return false;
-  }
-
-  ALOGD("Registering update_engine with the service manager");
-  status_t status = defaultServiceManager()->addService(
-      service->getInterfaceDescriptor(), service);
-  if (status != android::OK) {
-    ALOGE("Failed to register update_engine with the service manager.");
-    return false;
-  }
-
-  ALOGD("Entering update_engine mainloop");
-  while (true) {
-    const int result = looper->pollAll(-1 /* timeoutMillis */);
-    ALOGD("Looper returned %d", result);
-  }
-  // We should never get here.
-  return false;
-}
-
-}  // namespace
-}  // namespace android
-
-int main(int argc, char** argv) {
-  android::sp<android::IBinder> service(
-      new chromeos_update_engine::BinderService);
-  if (!android::run(service)) {
-    return 1;
-  }
-  return 0;
-}
diff --git a/binder_service_android.cc b/binder_service_android.cc
index df0f0c6..c512697 100644
--- a/binder_service_android.cc
+++ b/binder_service_android.cc
@@ -24,26 +24,28 @@
 
 namespace chromeos_update_engine {
 
-Status BinderService::bind(const sp<IUpdateEngineCallback>& callback,
-                           bool* return_value) {
+Status BinderUpdateEngineAndroidService::bind(
+    const sp<IUpdateEngineCallback>& callback,
+    bool* return_value) {
   *return_value = true;
   return Status::ok();
 }
 
-Status BinderService::applyPayload(const String16& url,
-                                   const vector<String16>& header_kv_pairs) {
+Status BinderUpdateEngineAndroidService::applyPayload(
+    const String16& url,
+    const vector<String16>& header_kv_pairs) {
   return Status::ok();
 }
 
-Status BinderService::suspend() {
+Status BinderUpdateEngineAndroidService::suspend() {
   return Status::ok();
 }
 
-Status BinderService::resume() {
+Status BinderUpdateEngineAndroidService::resume() {
   return Status::ok();
 }
 
-Status BinderService::cancel() {
+Status BinderUpdateEngineAndroidService::cancel() {
   return Status::ok();
 }
 
diff --git a/binder_service_android.h b/binder_service_android.h
index 3c4939a..224ab07 100644
--- a/binder_service_android.h
+++ b/binder_service_android.h
@@ -28,10 +28,10 @@
 
 namespace chromeos_update_engine {
 
-class BinderService : public android::os::BnUpdateEngine {
+class BinderUpdateEngineAndroidService : public android::os::BnUpdateEngine {
  public:
-  BinderService() = default;
-  virtual ~BinderService() = default;
+  BinderUpdateEngineAndroidService() = default;
+  ~BinderUpdateEngineAndroidService() override = default;
 
   android::binder::Status applyPayload(
       const android::String16& url,
@@ -46,7 +46,7 @@
   android::binder::Status resume() override;
 
   android::binder::Status cancel() override;
-};  // class BinderService
+};
 
 }  // namespace chromeos_update_engine
 
diff --git a/daemon.cc b/daemon.cc
index cc528a4..838c407 100644
--- a/daemon.cc
+++ b/daemon.cc
@@ -24,15 +24,16 @@
 #if USE_WEAVE || USE_BINDER
 #include <binderwrapper/binder_wrapper.h>
 #endif  // USE_WEAVE || USE_BINDER
-#include <brillo/message_loops/message_loop.h>
 
+#ifdef __BRILLO__
 #include "update_engine/update_attempter.h"
+#endif  // __BRILLO__
 
-using brillo::MessageLoop;
-
+#if USE_DBUS
 namespace {
 const int kDBusSystemMaxWaitSeconds = 2 * 60;
 }  // namespace
+#endif // USE_DBUS
 
 namespace chromeos_update_engine {
 
@@ -50,6 +51,7 @@
   binder_watcher_.Init();
 #endif  // USE_WEAVE || USE_BINDER
 
+#if USE_DBUS
   // We wait for the D-Bus connection for up two minutes to avoid re-spawning
   // the daemon too fast causing thrashing if dbus-daemon is not running.
   scoped_refptr<dbus::Bus> bus = dbus_connection_.ConnectWithTimeout(
@@ -63,26 +65,34 @@
   }
 
   CHECK(bus->SetUpAsyncOperations());
+#endif // USE_DBUS
 
+#ifdef __BRILLO__
   // Initialize update engine global state but continue if something fails.
   real_system_state_.reset(new RealSystemState(bus));
   LOG_IF(ERROR, !real_system_state_->Initialize())
       << "Failed to initialize system state.";
   UpdateAttempter* update_attempter = real_system_state_->update_attempter();
   CHECK(update_attempter);
+#else  // !defined(__BRILLO__)
+  //TODO(deymo): Initialize non-Brillo state.
+#endif // defined(__BRILLO__)
 
 #if USE_BINDER
-  // Create the Binder Service
+  // Create the Binder Service.
+#ifdef __BRILLO__
   service_ = new BinderUpdateEngineService{real_system_state_.get()};
+#else  // !defined(__BRILLO__)
+  service_ = new BinderUpdateEngineAndroidService{};
+#endif // defined(__BRILLO__)
   auto binder_wrapper = android::BinderWrapper::Get();
-  sleep(10);
   if (!binder_wrapper->RegisterService("android.brillo.UpdateEngineService",
                                        service_)) {
     LOG(ERROR) << "Failed to register binder service.";
   }
-
 #endif  // USE_BINDER
 
+#if USE_DBUS
   // Create the DBus service.
   dbus_adaptor_.reset(new UpdateEngineAdaptor(real_system_state_.get(), bus));
   update_attempter->set_dbus_adaptor(dbus_adaptor_.get());
@@ -90,9 +100,17 @@
   dbus_adaptor_->RegisterAsync(base::Bind(&UpdateEngineDaemon::OnDBusRegistered,
                                           base::Unretained(this)));
   LOG(INFO) << "Waiting for DBus object to be registered.";
+#else  // !USE_DBUS
+#ifdef __BRILLO__
+  real_system_state_->StartUpdater();
+#else  // !defined(__BRILLO__)
+  // TODO(deymo): Start non-Brillo service.
+#endif // defined(__BRILLO__)
+#endif // USE_DBUS
   return EX_OK;
 }
 
+#if USE_DBUS
 void UpdateEngineDaemon::OnDBusRegistered(bool succeeded) {
   if (!succeeded) {
     LOG(ERROR) << "Registering the UpdateEngineAdaptor";
@@ -109,30 +127,8 @@
     QuitWithExitCode(1);
     return;
   }
-
-  // Initiate update checks.
-  UpdateAttempter* update_attempter = real_system_state_->update_attempter();
-  update_attempter->ScheduleUpdates();
-
-  // Update boot flags after 45 seconds.
-  MessageLoop::current()->PostDelayedTask(
-      FROM_HERE,
-      base::Bind(&UpdateAttempter::UpdateBootFlags,
-                 base::Unretained(update_attempter)),
-      base::TimeDelta::FromSeconds(45));
-
-  // Broadcast the update engine status on startup to ensure consistent system
-  // state on crashes.
-  MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
-      &UpdateAttempter::BroadcastStatus,
-      base::Unretained(update_attempter)));
-
-  // Run the UpdateEngineStarted() method on |update_attempter|.
-  MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
-      &UpdateAttempter::UpdateEngineStarted,
-      base::Unretained(update_attempter)));
-
-  LOG(INFO) << "Finished initialization. Now running the loop.";
+  real_system_state_->StartUpdater();
 }
+#endif  // USE_DBUS
 
 }  // namespace chromeos_update_engine
diff --git a/daemon.h b/daemon.h
index 6233064..89137ed 100644
--- a/daemon.h
+++ b/daemon.h
@@ -24,14 +24,24 @@
 #include <brillo/binder_watcher.h>
 #endif  // USE_WEAVE || USE_BINDER
 #include <brillo/daemons/daemon.h>
+#if USE_DBUS
 #include <brillo/dbus/dbus_connection.h>
+#endif  // USE_DBUS
 
 #if USE_BINDER
+#ifdef __BRILLO__
 #include "update_engine/binder_service.h"
+#else  // !defined(__BRILLO__)
+#include "update_engine/binder_service_android.h"
+#endif  // defined(__BRILLO__)
 #endif  // USE_BINDER
 #include "update_engine/common/subprocess.h"
+#if USE_DBUS
 #include "update_engine/dbus_service.h"
+#endif  // USE_DBUS
+#ifdef __BRILLO__
 #include "update_engine/real_system_state.h"
+#endif  // defined(__BRILLO__)
 
 namespace chromeos_update_engine {
 
@@ -43,6 +53,7 @@
   int OnInit() override;
 
  private:
+#if USE_DBUS
   // Run from the main loop when the |dbus_adaptor_| object is registered. At
   // this point we can request ownership of the DBus service name and continue
   // initialization.
@@ -51,6 +62,7 @@
   // Main D-Bus connection and service adaptor.
   brillo::DBusConnection dbus_connection_;
   std::unique_ptr<UpdateEngineAdaptor> dbus_adaptor_;
+#endif  // USE_DBUS
 
   // The Subprocess singleton class requires a brillo::MessageLoop in the
   // current thread, so we need to initialize it from this class instead of
@@ -62,11 +74,19 @@
 #endif  // USE_WEAVE || USE_BINDER
 
 #if USE_BINDER
+#ifdef __BRILLO__
   android::sp<BinderUpdateEngineService> service_;
+#else  // !defined(__BRILLO__)
+  android::sp<BinderUpdateEngineAndroidService> service_;
+#endif  // defined(__BRILLO__)
 #endif  // USE_BINDER
 
+#ifdef __BRILLO__
   // The RealSystemState uses the previous classes so it should be defined last.
   std::unique_ptr<RealSystemState> real_system_state_;
+#else  // !defined(__BRILLO__)
+  //TODO(deymo): Define non-Brillo state.
+#endif  // defined(__BRILLO__)
 
   DISALLOW_COPY_AND_ASSIGN(UpdateEngineDaemon);
 };
diff --git a/main.cc b/main.cc
index 8e88f23..4275bc1 100644
--- a/main.cc
+++ b/main.cc
@@ -28,7 +28,6 @@
 #include <base/strings/string_util.h>
 #include <base/strings/stringprintf.h>
 #include <brillo/flag_helper.h>
-#include <brillo/message_loops/base_message_loop.h>
 
 #include "update_engine/common/terminator.h"
 #include "update_engine/common/utils.h"
diff --git a/real_system_state.cc b/real_system_state.cc
index 906ec97..f415b90 100644
--- a/real_system_state.cc
+++ b/real_system_state.cc
@@ -18,9 +18,12 @@
 
 #include <string>
 
+#include <base/bind.h>
 #include <base/files/file_util.h>
+#include <base/location.h>
 #include <base/time/time.h>
 #include <brillo/make_unique_ptr.h>
+#include <brillo/message_loops/message_loop.h>
 
 #include "update_engine/common/boot_control.h"
 #include "update_engine/common/boot_control_stub.h"
@@ -30,6 +33,8 @@
 #include "update_engine/update_manager/state_factory.h"
 #include "update_engine/weave_service_factory.h"
 
+using brillo::MessageLoop;
+
 namespace chromeos_update_engine {
 
 RealSystemState::RealSystemState(const scoped_refptr<dbus::Bus>& bus)
@@ -160,4 +165,27 @@
   return true;
 }
 
+void RealSystemState::StartUpdater() {
+  // Initiate update checks.
+  update_attempter_->ScheduleUpdates();
+
+  // Update boot flags after 45 seconds.
+  MessageLoop::current()->PostDelayedTask(
+      FROM_HERE,
+      base::Bind(&UpdateAttempter::UpdateBootFlags,
+                 base::Unretained(update_attempter_.get())),
+      base::TimeDelta::FromSeconds(45));
+
+  // Broadcast the update engine status on startup to ensure consistent system
+  // state on crashes.
+  MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
+      &UpdateAttempter::BroadcastStatus,
+      base::Unretained(update_attempter_.get())));
+
+  // Run the UpdateEngineStarted() method on |update_attempter|.
+  MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
+      &UpdateAttempter::UpdateEngineStarted,
+      base::Unretained(update_attempter_.get())));
+}
+
 }  // namespace chromeos_update_engine
diff --git a/real_system_state.h b/real_system_state.h
index a1fe8c6..f65f706 100644
--- a/real_system_state.h
+++ b/real_system_state.h
@@ -55,6 +55,10 @@
   // separately from construction. Returns |true| on success.
   bool Initialize();
 
+  // Start the periodic update attempts. Must be called at the beginning of the
+  // program to start the periodic update check process.
+  void StartUpdater();
+
   inline void set_device_policy(
       const policy::DevicePolicy* device_policy) override {
     device_policy_ = device_policy;