Revert "Implement Android UE daemon using brillo::Daemon."

This reverts commit c180400937eac75e8b7119f68d44593713dd4557.

This breaks both AOSP and Chrome OS

Change-Id: Ie9686a4d03a8fd53a614ed1706e3268918c414fb
diff --git a/Android.mk b/Android.mk
index c6e5a4e..c8f310c 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),0)
+local_use_dbus := $(if $(BRILLO_USE_DBUS),$(BRILLO_USE_DBUS),1)
 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,12 +259,6 @@
 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
@@ -336,11 +330,16 @@
 
 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)
@@ -366,40 +365,38 @@
 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 += \
+LOCAL_SHARED_LIBRARIES := \
+    $(ue_common_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_STATIC_LIBRARIES := \
-    libpayload_consumer \
-    $(ue_libpayload_consumer_exported_static_libraries:-host=)
-LOCAL_SHARED_LIBRARIES += \
-    $(ue_libpayload_consumer_exported_shared_libraries:-host=) \
+LOCAL_SHARED_LIBRARIES := \
     libbinder \
-    libbrillo-binder \
+    liblog \
     libutils
-LOCAL_SRC_FILES += \
+LOCAL_SRC_FILES := \
     binder_bindings/android/os/IUpdateEngine.aidl \
     binder_bindings/android/os/IUpdateEngineCallback.aidl \
-    binder_service_android.cc \
-    daemon.cc
+    binder_main.cc \
+    binder_service_android.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
new file mode 100644
index 0000000..a4817b4
--- /dev/null
+++ b/binder_main.cc
@@ -0,0 +1,91 @@
+//
+// 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 c512697..df0f0c6 100644
--- a/binder_service_android.cc
+++ b/binder_service_android.cc
@@ -24,28 +24,26 @@
 
 namespace chromeos_update_engine {
 
-Status BinderUpdateEngineAndroidService::bind(
-    const sp<IUpdateEngineCallback>& callback,
-    bool* return_value) {
+Status BinderService::bind(const sp<IUpdateEngineCallback>& callback,
+                           bool* return_value) {
   *return_value = true;
   return Status::ok();
 }
 
-Status BinderUpdateEngineAndroidService::applyPayload(
-    const String16& url,
-    const vector<String16>& header_kv_pairs) {
+Status BinderService::applyPayload(const String16& url,
+                                   const vector<String16>& header_kv_pairs) {
   return Status::ok();
 }
 
-Status BinderUpdateEngineAndroidService::suspend() {
+Status BinderService::suspend() {
   return Status::ok();
 }
 
-Status BinderUpdateEngineAndroidService::resume() {
+Status BinderService::resume() {
   return Status::ok();
 }
 
-Status BinderUpdateEngineAndroidService::cancel() {
+Status BinderService::cancel() {
   return Status::ok();
 }
 
diff --git a/binder_service_android.h b/binder_service_android.h
index 224ab07..3c4939a 100644
--- a/binder_service_android.h
+++ b/binder_service_android.h
@@ -28,10 +28,10 @@
 
 namespace chromeos_update_engine {
 
-class BinderUpdateEngineAndroidService : public android::os::BnUpdateEngine {
+class BinderService : public android::os::BnUpdateEngine {
  public:
-  BinderUpdateEngineAndroidService() = default;
-  ~BinderUpdateEngineAndroidService() override = default;
+  BinderService() = default;
+  virtual ~BinderService() = 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 838c407..cc528a4 100644
--- a/daemon.cc
+++ b/daemon.cc
@@ -24,16 +24,15 @@
 #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__
 
-#if USE_DBUS
+using brillo::MessageLoop;
+
 namespace {
 const int kDBusSystemMaxWaitSeconds = 2 * 60;
 }  // namespace
-#endif // USE_DBUS
 
 namespace chromeos_update_engine {
 
@@ -51,7 +50,6 @@
   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(
@@ -65,34 +63,26 @@
   }
 
   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.
-#ifdef __BRILLO__
+  // Create the Binder Service
   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());
@@ -100,17 +90,9 @@
   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";
@@ -127,8 +109,30 @@
     QuitWithExitCode(1);
     return;
   }
-  real_system_state_->StartUpdater();
+
+  // 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.";
 }
-#endif  // USE_DBUS
 
 }  // namespace chromeos_update_engine
diff --git a/daemon.h b/daemon.h
index 89137ed..6233064 100644
--- a/daemon.h
+++ b/daemon.h
@@ -24,24 +24,14 @@
 #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 {
 
@@ -53,7 +43,6 @@
   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.
@@ -62,7 +51,6 @@
   // 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
@@ -74,19 +62,11 @@
 #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 4275bc1..8e88f23 100644
--- a/main.cc
+++ b/main.cc
@@ -28,6 +28,7 @@
 #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 f415b90..906ec97 100644
--- a/real_system_state.cc
+++ b/real_system_state.cc
@@ -18,12 +18,9 @@
 
 #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"
@@ -33,8 +30,6 @@
 #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)
@@ -165,27 +160,4 @@
   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 f65f706..a1fe8c6 100644
--- a/real_system_state.h
+++ b/real_system_state.h
@@ -55,10 +55,6 @@
   // 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;