You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kudu.apache.org by mp...@apache.org on 2016/07/15 00:57:45 UTC

[3/6] incubator-kudu git commit: Move the maintenance manager to util

Move the maintenance manager to util

This moves the maintenance manager to util, along with its required protobufs.
This move is required as we'll need a server-level MaintenanceMananager to
run garbage collection on the ResultTracker.

Change-Id: Ifcf072d443ac3d069bda15b9dc0f8c442b9ac5c0
Reviewed-on: http://gerrit.cloudera.org:8080/3656
Reviewed-by: Jean-Daniel Cryans <jd...@apache.org>
Tested-by: Kudu Jenkins


Project: http://git-wip-us.apache.org/repos/asf/incubator-kudu/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-kudu/commit/ee380939
Tree: http://git-wip-us.apache.org/repos/asf/incubator-kudu/tree/ee380939
Diff: http://git-wip-us.apache.org/repos/asf/incubator-kudu/diff/ee380939

Branch: refs/heads/master
Commit: ee38093949fd7ccb773025e6ec7e8e60daa31149
Parents: 257ba29
Author: dralves <dr...@apache.org>
Authored: Thu Jul 14 14:29:26 2016 -0700
Committer: David Ribeiro Alves <dr...@apache.org>
Committed: Thu Jul 14 23:48:30 2016 +0000

----------------------------------------------------------------------
 .../full_stack-insert-scan-test.cc              |   2 +-
 src/kudu/master/master.cc                       |   2 +-
 src/kudu/tablet/CMakeLists.txt                  |   2 -
 src/kudu/tablet/maintenance_manager-test.cc     | 287 -------------
 src/kudu/tablet/maintenance_manager.cc          | 419 -------------------
 src/kudu/tablet/maintenance_manager.h           | 280 -------------
 src/kudu/tablet/tablet.cc                       |   2 +-
 src/kudu/tablet/tablet.proto                    |  29 --
 src/kudu/tablet/tablet_mm_ops.h                 |   2 +-
 src/kudu/tablet/tablet_peer-test.cc             |   2 +-
 src/kudu/tablet/tablet_peer_mm_ops.cc           |   2 +-
 src/kudu/tablet/tablet_peer_mm_ops.h            |   2 +-
 src/kudu/tserver/mini_tablet_server.cc          |   2 +-
 src/kudu/tserver/tablet_server-test-base.h      |   2 +-
 src/kudu/tserver/tablet_server.cc               |   2 +-
 src/kudu/tserver/tserver-path-handlers.cc       |   8 +-
 src/kudu/util/CMakeLists.txt                    |  17 +
 src/kudu/util/maintenance_manager-test.cc       | 286 +++++++++++++
 src/kudu/util/maintenance_manager.cc            | 415 ++++++++++++++++++
 src/kudu/util/maintenance_manager.h             | 277 ++++++++++++
 src/kudu/util/maintenance_manager.proto         |  48 +++
 21 files changed, 1057 insertions(+), 1031 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/integration-tests/full_stack-insert-scan-test.cc
----------------------------------------------------------------------
diff --git a/src/kudu/integration-tests/full_stack-insert-scan-test.cc b/src/kudu/integration-tests/full_stack-insert-scan-test.cc
index 78f2f9d..5a1a61b 100644
--- a/src/kudu/integration-tests/full_stack-insert-scan-test.cc
+++ b/src/kudu/integration-tests/full_stack-insert-scan-test.cc
@@ -37,7 +37,6 @@
 #include "kudu/gutil/strings/substitute.h"
 #include "kudu/integration-tests/mini_cluster.h"
 #include "kudu/master/mini_master.h"
-#include "kudu/tablet/maintenance_manager.h"
 #include "kudu/tablet/tablet.h"
 #include "kudu/tablet/tablet_metrics.h"
 #include "kudu/tablet/tablet_peer.h"
@@ -47,6 +46,7 @@
 #include "kudu/util/async_util.h"
 #include "kudu/util/countdown_latch.h"
 #include "kudu/util/errno.h"
+#include "kudu/util/maintenance_manager.h"
 #include "kudu/util/stopwatch.h"
 #include "kudu/util/test_macros.h"
 #include "kudu/util/test_util.h"

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/master/master.cc
----------------------------------------------------------------------
diff --git a/src/kudu/master/master.cc b/src/kudu/master/master.cc
index adb9533..c42d7f0 100644
--- a/src/kudu/master/master.cc
+++ b/src/kudu/master/master.cc
@@ -36,9 +36,9 @@
 #include "kudu/rpc/service_if.h"
 #include "kudu/rpc/service_pool.h"
 #include "kudu/server/rpc_server.h"
-#include "kudu/tablet/maintenance_manager.h"
 #include "kudu/tserver/tablet_service.h"
 #include "kudu/util/flag_tags.h"
+#include "kudu/util/maintenance_manager.h"
 #include "kudu/util/net/net_util.h"
 #include "kudu/util/net/sockaddr.h"
 #include "kudu/util/status.h"

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/tablet/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/src/kudu/tablet/CMakeLists.txt b/src/kudu/tablet/CMakeLists.txt
index e7e94c9..c6baa67 100644
--- a/src/kudu/tablet/CMakeLists.txt
+++ b/src/kudu/tablet/CMakeLists.txt
@@ -33,7 +33,6 @@ set(TABLET_SRCS
   delta_key.cc
   diskrowset.cc
   lock_manager.cc
-  maintenance_manager.cc
   memrowset.cc
   multi_column_writer.cc
   mutation.cc
@@ -98,7 +97,6 @@ ADD_KUDU_TEST(cfile_set-test)
 ADD_KUDU_TEST(tablet-pushdown-test)
 ADD_KUDU_TEST(tablet-schema-test)
 ADD_KUDU_TEST(tablet_bootstrap-test)
-ADD_KUDU_TEST(maintenance_manager-test)
 ADD_KUDU_TEST(metadata-test)
 ADD_KUDU_TEST(mvcc-test)
 ADD_KUDU_TEST(compaction-test)

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/tablet/maintenance_manager-test.cc
----------------------------------------------------------------------
diff --git a/src/kudu/tablet/maintenance_manager-test.cc b/src/kudu/tablet/maintenance_manager-test.cc
deleted file mode 100644
index 663ed47..0000000
--- a/src/kudu/tablet/maintenance_manager-test.cc
+++ /dev/null
@@ -1,287 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you 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 <gflags/gflags.h>
-#include <gtest/gtest.h>
-#include <memory>
-#include <mutex>
-#include <vector>
-
-#include "kudu/gutil/strings/substitute.h"
-#include "kudu/tablet/maintenance_manager.h"
-#include "kudu/tablet/tablet.pb.h"
-#include "kudu/util/mem_tracker.h"
-#include "kudu/util/metrics.h"
-#include "kudu/util/test_macros.h"
-#include "kudu/util/test_util.h"
-#include "kudu/util/thread.h"
-
-using kudu::tablet::MaintenanceManagerStatusPB;
-using std::shared_ptr;
-using std::vector;
-using strings::Substitute;
-
-METRIC_DEFINE_entity(test);
-METRIC_DEFINE_gauge_uint32(test, maintenance_ops_running,
-                           "Number of Maintenance Operations Running",
-                           kudu::MetricUnit::kMaintenanceOperations,
-                           "The number of background maintenance operations currently running.");
-METRIC_DEFINE_histogram(test, maintenance_op_duration,
-                        "Maintenance Operation Duration",
-                        kudu::MetricUnit::kSeconds, "", 60000000LU, 2);
-
-namespace kudu {
-
-const int kHistorySize = 4;
-
-class MaintenanceManagerTest : public KuduTest {
- public:
-  MaintenanceManagerTest() {
-    test_tracker_ = MemTracker::CreateTracker(1000, "test");
-    MaintenanceManager::Options options;
-    options.num_threads = 2;
-    options.polling_interval_ms = 1;
-    options.history_size = kHistorySize;
-    options.parent_mem_tracker = test_tracker_;
-    manager_.reset(new MaintenanceManager(options));
-    manager_->Init();
-  }
-  ~MaintenanceManagerTest() {
-    manager_->Shutdown();
-  }
-
- protected:
-  shared_ptr<MemTracker> test_tracker_;
-  shared_ptr<MaintenanceManager> manager_;
-};
-
-// Just create the MaintenanceManager and then shut it down, to make sure
-// there are no race conditions there.
-TEST_F(MaintenanceManagerTest, TestCreateAndShutdown) {
-}
-
-enum TestMaintenanceOpState {
-  OP_DISABLED,
-  OP_RUNNABLE,
-  OP_RUNNING,
-  OP_FINISHED,
-};
-
-class TestMaintenanceOp : public MaintenanceOp {
- public:
-  TestMaintenanceOp(const std::string& name,
-                    IOUsage io_usage,
-                    TestMaintenanceOpState state,
-                    const shared_ptr<MemTracker>& tracker)
-    : MaintenanceOp(name, io_usage),
-      state_change_cond_(&lock_),
-      state_(state),
-      consumption_(tracker, 500),
-      logs_retained_bytes_(0),
-      perf_improvement_(0),
-      metric_entity_(METRIC_ENTITY_test.Instantiate(&metric_registry_, "test")),
-      maintenance_op_duration_(METRIC_maintenance_op_duration.Instantiate(metric_entity_)),
-      maintenance_ops_running_(METRIC_maintenance_ops_running.Instantiate(metric_entity_, 0)) {
-  }
-
-  virtual ~TestMaintenanceOp() {}
-
-  virtual bool Prepare() OVERRIDE {
-    std::lock_guard<Mutex> guard(lock_);
-    if (state_ != OP_RUNNABLE) {
-      return false;
-    }
-    state_ = OP_RUNNING;
-    state_change_cond_.Broadcast();
-    DLOG(INFO) << "Prepared op " << name();
-    return true;
-  }
-
-  virtual void Perform() OVERRIDE {
-    DLOG(INFO) << "Performing op " << name();
-    std::lock_guard<Mutex> guard(lock_);
-    CHECK_EQ(OP_RUNNING, state_);
-    state_ = OP_FINISHED;
-    state_change_cond_.Broadcast();
-  }
-
-  virtual void UpdateStats(MaintenanceOpStats* stats) OVERRIDE {
-    std::lock_guard<Mutex> guard(lock_);
-    stats->set_runnable(state_ == OP_RUNNABLE);
-    stats->set_ram_anchored(consumption_.consumption());
-    stats->set_logs_retained_bytes(logs_retained_bytes_);
-    stats->set_perf_improvement(perf_improvement_);
-  }
-
-  void Enable() {
-    std::lock_guard<Mutex> guard(lock_);
-    DCHECK((state_ == OP_DISABLED) || (state_ == OP_FINISHED));
-    state_ = OP_RUNNABLE;
-    state_change_cond_.Broadcast();
-  }
-
-  void WaitForState(TestMaintenanceOpState state) {
-    std::lock_guard<Mutex> guard(lock_);
-    while (true) {
-      if (state_ == state) {
-        return;
-      }
-      state_change_cond_.Wait();
-    }
-  }
-
-  bool WaitForStateWithTimeout(TestMaintenanceOpState state, int ms) {
-    MonoDelta to_wait = MonoDelta::FromMilliseconds(ms);
-    std::lock_guard<Mutex> guard(lock_);
-    while (true) {
-      if (state_ == state) {
-        return true;
-      }
-      if (!state_change_cond_.TimedWait(to_wait)) {
-        return false;
-      }
-    }
-  }
-
-  void set_ram_anchored(uint64_t ram_anchored) {
-    std::lock_guard<Mutex> guard(lock_);
-    consumption_.Reset(ram_anchored);
-  }
-
-  void set_logs_retained_bytes(uint64_t logs_retained_bytes) {
-    std::lock_guard<Mutex> guard(lock_);
-    logs_retained_bytes_ = logs_retained_bytes;
-  }
-
-  void set_perf_improvement(uint64_t perf_improvement) {
-    std::lock_guard<Mutex> guard(lock_);
-    perf_improvement_ = perf_improvement;
-  }
-
-  virtual scoped_refptr<Histogram> DurationHistogram() const OVERRIDE {
-    return maintenance_op_duration_;
-  }
-
-  virtual scoped_refptr<AtomicGauge<uint32_t> > RunningGauge() const OVERRIDE {
-    return maintenance_ops_running_;
-  }
-
- private:
-  Mutex lock_;
-  ConditionVariable state_change_cond_;
-  enum TestMaintenanceOpState state_;
-  ScopedTrackedConsumption consumption_;
-  uint64_t logs_retained_bytes_;
-  uint64_t perf_improvement_;
-  MetricRegistry metric_registry_;
-  scoped_refptr<MetricEntity> metric_entity_;
-  scoped_refptr<Histogram> maintenance_op_duration_;
-  scoped_refptr<AtomicGauge<uint32_t> > maintenance_ops_running_;
-};
-
-// Create an op and wait for it to start running.  Unregister it while it is
-// running and verify that UnregisterOp waits for it to finish before
-// proceeding.
-TEST_F(MaintenanceManagerTest, TestRegisterUnregister) {
-  TestMaintenanceOp op1("1", MaintenanceOp::HIGH_IO_USAGE, OP_DISABLED, test_tracker_);
-  op1.set_ram_anchored(1001);
-  manager_->RegisterOp(&op1);
-  scoped_refptr<kudu::Thread> thread;
-  CHECK_OK(Thread::Create("TestThread", "TestRegisterUnregister",
-        boost::bind(&TestMaintenanceOp::Enable, &op1), &thread));
-  op1.WaitForState(OP_FINISHED);
-  manager_->UnregisterOp(&op1);
-  ThreadJoiner(thread.get()).Join();
-}
-
-// Test that we'll run an operation that doesn't improve performance when memory
-// pressure gets high.
-TEST_F(MaintenanceManagerTest, TestMemoryPressure) {
-  TestMaintenanceOp op("op", MaintenanceOp::HIGH_IO_USAGE, OP_RUNNABLE, test_tracker_);
-  op.set_ram_anchored(100);
-  manager_->RegisterOp(&op);
-
-  // At first, we don't want to run this, since there is no perf_improvement.
-  CHECK_EQ(false, op.WaitForStateWithTimeout(OP_FINISHED, 20));
-
-  // set the ram_anchored by the high mem op so high that we'll have to run it.
-  scoped_refptr<kudu::Thread> thread;
-  CHECK_OK(Thread::Create("TestThread", "MaintenanceManagerTest",
-      boost::bind(&TestMaintenanceOp::set_ram_anchored, &op, 1100), &thread));
-  op.WaitForState(OP_FINISHED);
-  manager_->UnregisterOp(&op);
-  ThreadJoiner(thread.get()).Join();
-}
-
-// Test that ops are prioritized correctly when we add log retention.
-TEST_F(MaintenanceManagerTest, TestLogRetentionPrioritization) {
-  manager_->Shutdown();
-
-  TestMaintenanceOp op1("op1", MaintenanceOp::LOW_IO_USAGE, OP_RUNNABLE, test_tracker_);
-  op1.set_ram_anchored(0);
-  op1.set_logs_retained_bytes(100);
-
-  TestMaintenanceOp op2("op2", MaintenanceOp::HIGH_IO_USAGE, OP_RUNNABLE, test_tracker_);
-  op2.set_ram_anchored(100);
-  op2.set_logs_retained_bytes(100);
-
-  TestMaintenanceOp op3("op3", MaintenanceOp::HIGH_IO_USAGE, OP_RUNNABLE, test_tracker_);
-  op3.set_ram_anchored(200);
-  op3.set_logs_retained_bytes(100);
-
-  manager_->RegisterOp(&op1);
-  manager_->RegisterOp(&op2);
-  manager_->RegisterOp(&op3);
-
-  // We want to do the low IO op first since it clears up some log retention.
-  ASSERT_EQ(&op1, manager_->FindBestOp());
-
-  manager_->UnregisterOp(&op1);
-
-  // Low IO is taken care of, now we find the op clears the most log retention and ram.
-  ASSERT_EQ(&op3, manager_->FindBestOp());
-
-  manager_->UnregisterOp(&op3);
-
-  ASSERT_EQ(&op2, manager_->FindBestOp());
-
-  manager_->UnregisterOp(&op2);
-}
-
-// Test adding operations and make sure that the history of recently completed operations
-// is correct in that it wraps around and doesn't grow.
-TEST_F(MaintenanceManagerTest, TestCompletedOpsHistory) {
-  for (int i = 0; i < 5; i++) {
-    string name = Substitute("op$0", i);
-    TestMaintenanceOp op(name, MaintenanceOp::HIGH_IO_USAGE, OP_RUNNABLE, test_tracker_);
-    op.set_perf_improvement(1);
-    op.set_ram_anchored(100);
-    manager_->RegisterOp(&op);
-
-    CHECK_EQ(true, op.WaitForStateWithTimeout(OP_FINISHED, 200));
-    manager_->UnregisterOp(&op);
-
-    MaintenanceManagerStatusPB status_pb;
-    manager_->GetMaintenanceManagerStatusDump(&status_pb);
-    // The size should be at most the history_size.
-    ASSERT_GE(kHistorySize, status_pb.completed_operations_size());
-    // See that we have the right name, even if we wrap around.
-    ASSERT_EQ(name, status_pb.completed_operations(i % 4).name());
-  }
-}
-
-} // namespace kudu

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/tablet/maintenance_manager.cc
----------------------------------------------------------------------
diff --git a/src/kudu/tablet/maintenance_manager.cc b/src/kudu/tablet/maintenance_manager.cc
deleted file mode 100644
index b611e10..0000000
--- a/src/kudu/tablet/maintenance_manager.cc
+++ /dev/null
@@ -1,419 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you 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 "kudu/tablet/maintenance_manager.h"
-
-#include <gflags/gflags.h>
-#include <memory>
-#include <stdint.h>
-#include <string>
-#include <utility>
-
-#include "kudu/gutil/stringprintf.h"
-#include "kudu/gutil/strings/substitute.h"
-#include "kudu/util/debug/trace_event.h"
-#include "kudu/util/debug/trace_logging.h"
-#include "kudu/util/flag_tags.h"
-#include "kudu/util/mem_tracker.h"
-#include "kudu/util/metrics.h"
-#include "kudu/util/stopwatch.h"
-#include "kudu/util/thread.h"
-
-using std::pair;
-using std::shared_ptr;
-using strings::Substitute;
-
-DEFINE_int32(maintenance_manager_num_threads, 1,
-       "Size of the maintenance manager thread pool. Beyond a value of '1', one thread is "
-       "reserved for emergency flushes. For spinning disks, the number of threads should "
-       "not be above the number of devices.");
-TAG_FLAG(maintenance_manager_num_threads, stable);
-
-DEFINE_int32(maintenance_manager_polling_interval_ms, 250,
-       "Polling interval for the maintenance manager scheduler, "
-       "in milliseconds.");
-TAG_FLAG(maintenance_manager_polling_interval_ms, hidden);
-
-DEFINE_int32(maintenance_manager_history_size, 8,
-       "Number of completed operations the manager is keeping track of.");
-TAG_FLAG(maintenance_manager_history_size, hidden);
-
-DEFINE_bool(enable_maintenance_manager, true,
-       "Enable the maintenance manager, runs compaction and tablet cleaning tasks.");
-TAG_FLAG(enable_maintenance_manager, unsafe);
-
-namespace kudu {
-
-using kudu::tablet::MaintenanceManagerStatusPB;
-using kudu::tablet::MaintenanceManagerStatusPB_CompletedOpPB;
-using kudu::tablet::MaintenanceManagerStatusPB_MaintenanceOpPB;
-
-MaintenanceOpStats::MaintenanceOpStats() {
-  Clear();
-}
-
-void MaintenanceOpStats::Clear() {
-  valid_ = false;
-  runnable_ = false;
-  ram_anchored_ = 0;
-  logs_retained_bytes_ = 0;
-  perf_improvement_ = 0;
-}
-
-MaintenanceOp::MaintenanceOp(std::string name, IOUsage io_usage)
-    : name_(std::move(name)), running_(0), io_usage_(io_usage) {}
-
-MaintenanceOp::~MaintenanceOp() {
-  CHECK(!manager_.get()) << "You must unregister the " << name_
-         << " Op before destroying it.";
-}
-
-void MaintenanceOp::Unregister() {
-  CHECK(manager_.get()) << "Op " << name_ << " was never registered.";
-  manager_->UnregisterOp(this);
-}
-
-const MaintenanceManager::Options MaintenanceManager::DEFAULT_OPTIONS = {
-  0,
-  0,
-  0,
-  shared_ptr<MemTracker>(),
-};
-
-MaintenanceManager::MaintenanceManager(const Options& options)
-  : num_threads_(options.num_threads <= 0 ?
-      FLAGS_maintenance_manager_num_threads : options.num_threads),
-    cond_(&lock_),
-    shutdown_(false),
-    running_ops_(0),
-    polling_interval_ms_(options.polling_interval_ms <= 0 ?
-          FLAGS_maintenance_manager_polling_interval_ms :
-          options.polling_interval_ms),
-    completed_ops_count_(0),
-    parent_mem_tracker_(!options.parent_mem_tracker ?
-        MemTracker::GetRootTracker() : options.parent_mem_tracker) {
-  CHECK_OK(ThreadPoolBuilder("MaintenanceMgr").set_min_threads(num_threads_)
-               .set_max_threads(num_threads_).Build(&thread_pool_));
-  uint32_t history_size = options.history_size == 0 ?
-                          FLAGS_maintenance_manager_history_size :
-                          options.history_size;
-  completed_ops_.resize(history_size);
-}
-
-MaintenanceManager::~MaintenanceManager() {
-  Shutdown();
-}
-
-Status MaintenanceManager::Init() {
-  RETURN_NOT_OK(Thread::Create("maintenance", "maintenance_scheduler",
-      boost::bind(&MaintenanceManager::RunSchedulerThread, this),
-      &monitor_thread_));
-  return Status::OK();
-}
-
-void MaintenanceManager::Shutdown() {
-  {
-    std::lock_guard<Mutex> guard(lock_);
-    if (shutdown_) {
-      return;
-    }
-    shutdown_ = true;
-    cond_.Broadcast();
-  }
-  if (monitor_thread_.get()) {
-    CHECK_OK(ThreadJoiner(monitor_thread_.get()).Join());
-    monitor_thread_.reset();
-    thread_pool_->Shutdown();
-  }
-}
-
-void MaintenanceManager::RegisterOp(MaintenanceOp* op) {
-  std::lock_guard<Mutex> guard(lock_);
-  CHECK(!op->manager_.get()) << "Tried to register " << op->name()
-          << ", but it was already registered.";
-  pair<OpMapTy::iterator, bool> val
-    (ops_.insert(OpMapTy::value_type(op, MaintenanceOpStats())));
-  CHECK(val.second)
-      << "Tried to register " << op->name()
-      << ", but it already exists in ops_.";
-  op->manager_ = shared_from_this();
-  op->cond_.reset(new ConditionVariable(&lock_));
-  VLOG_AND_TRACE("maintenance", 1) << "Registered " << op->name();
-}
-
-void MaintenanceManager::UnregisterOp(MaintenanceOp* op) {
-  {
-    std::lock_guard<Mutex> guard(lock_);
-    CHECK(op->manager_.get() == this) << "Tried to unregister " << op->name()
-          << ", but it is not currently registered with this maintenance manager.";
-    auto iter = ops_.find(op);
-    CHECK(iter != ops_.end()) << "Tried to unregister " << op->name()
-        << ", but it was never registered";
-    // While the op is running, wait for it to be finished.
-    if (iter->first->running_ > 0) {
-      VLOG_AND_TRACE("maintenance", 1) << "Waiting for op " << op->name() << " to finish so "
-            << "we can unregister it.";
-    }
-    while (iter->first->running_ > 0) {
-      op->cond_->Wait();
-      iter = ops_.find(op);
-      CHECK(iter != ops_.end()) << "Tried to unregister " << op->name()
-          << ", but another thread unregistered it while we were "
-          << "waiting for it to complete";
-    }
-    ops_.erase(iter);
-  }
-  LOG(INFO) << "Unregistered op " << op->name();
-  op->cond_.reset();
-  // Remove the op's shared_ptr reference to us.  This might 'delete this'.
-  op->manager_.reset();
-}
-
-void MaintenanceManager::RunSchedulerThread() {
-  MonoDelta polling_interval = MonoDelta::FromMilliseconds(polling_interval_ms_);
-
-  std::unique_lock<Mutex> guard(lock_);
-  while (true) {
-    // Loop until we are shutting down or it is time to run another op.
-    cond_.TimedWait(polling_interval);
-    if (shutdown_) {
-      VLOG_AND_TRACE("maintenance", 1) << "Shutting down maintenance manager.";
-      return;
-    }
-
-    // Find the best op.
-    MaintenanceOp* op = FindBestOp();
-    if (!op) {
-      VLOG_AND_TRACE("maintenance", 2) << "No maintenance operations look worth doing.";
-      continue;
-    }
-
-    // Prepare the maintenance operation.
-    op->running_++;
-    running_ops_++;
-    guard.unlock();
-    bool ready = op->Prepare();
-    guard.lock();
-    if (!ready) {
-      LOG(INFO) << "Prepare failed for " << op->name()
-                << ".  Re-running scheduler.";
-      op->running_--;
-      op->cond_->Signal();
-      continue;
-    }
-
-    // Run the maintenance operation.
-    Status s = thread_pool_->SubmitFunc(boost::bind(
-          &MaintenanceManager::LaunchOp, this, op));
-    CHECK(s.ok());
-  }
-}
-
-// Finding the best operation goes through four filters:
-// - If there's an Op that we can run quickly that frees log retention, we run it.
-// - If we've hit the overall process memory limit (note: this includes memory that the Ops cannot
-//   free), we run the Op with the highest RAM usage.
-// - If there are Ops that retain logs, we run the one that has the highest retention (and if many
-//   qualify, then we run the one that also frees up the most RAM).
-// - Finally, if there's nothing else that we really need to do, we run the Op that will improve
-//   performance the most.
-//
-// The reason it's done this way is that we want to prioritize limiting the amount of resources we
-// hold on to. Low IO Ops go first since we can quickly run them, then we can look at memory usage.
-// Reversing those can starve the low IO Ops when the system is under intense memory pressure.
-//
-// In the third priority we're at a point where nothing's urgent and there's nothing we can run
-// quickly.
-// TODO We currently optimize for freeing log retention but we could consider having some sort of
-// sliding priority between log retention and RAM usage. For example, is an Op that frees
-// 128MB of log retention and 12MB of RAM always better than an op that frees 12MB of log retention
-// and 128MB of RAM? Maybe a more holistic approach would be better.
-MaintenanceOp* MaintenanceManager::FindBestOp() {
-  TRACE_EVENT0("maintenance", "MaintenanceManager::FindBestOp");
-
-  if (!FLAGS_enable_maintenance_manager) {
-    VLOG_AND_TRACE("maintenance", 1) << "Maintenance manager is disabled. Doing nothing";
-    return nullptr;
-  }
-  size_t free_threads = num_threads_ - running_ops_;
-  if (free_threads == 0) {
-    VLOG_AND_TRACE("maintenance", 1) << "there are no free threads, so we can't run anything.";
-    return nullptr;
-  }
-
-  int64_t low_io_most_logs_retained_bytes = 0;
-  MaintenanceOp* low_io_most_logs_retained_bytes_op = nullptr;
-
-  uint64_t most_mem_anchored = 0;
-  MaintenanceOp* most_mem_anchored_op = nullptr;
-
-  int64_t most_logs_retained_bytes = 0;
-  int64_t most_logs_retained_bytes_ram_anchored = 0;
-  MaintenanceOp* most_logs_retained_bytes_op = nullptr;
-
-  double best_perf_improvement = 0;
-  MaintenanceOp* best_perf_improvement_op = nullptr;
-  for (OpMapTy::value_type &val : ops_) {
-    MaintenanceOp* op(val.first);
-    MaintenanceOpStats& stats(val.second);
-    // Update op stats.
-    stats.Clear();
-    op->UpdateStats(&stats);
-    if (!stats.valid() || !stats.runnable()) {
-      continue;
-    }
-    if (stats.logs_retained_bytes() > low_io_most_logs_retained_bytes &&
-        op->io_usage_ == MaintenanceOp::LOW_IO_USAGE) {
-      low_io_most_logs_retained_bytes_op = op;
-      low_io_most_logs_retained_bytes = stats.logs_retained_bytes();
-    }
-
-    if (stats.ram_anchored() > most_mem_anchored) {
-      most_mem_anchored_op = op;
-      most_mem_anchored = stats.ram_anchored();
-    }
-    // We prioritize ops that can free more logs, but when it's the same we pick the one that
-    // also frees up the most memory.
-    if (stats.logs_retained_bytes() > 0 &&
-        (stats.logs_retained_bytes() > most_logs_retained_bytes ||
-            (stats.logs_retained_bytes() == most_logs_retained_bytes &&
-                stats.ram_anchored() > most_logs_retained_bytes_ram_anchored))) {
-      most_logs_retained_bytes_op = op;
-      most_logs_retained_bytes = stats.logs_retained_bytes();
-      most_logs_retained_bytes_ram_anchored = stats.ram_anchored();
-    }
-    if ((!best_perf_improvement_op) ||
-        (stats.perf_improvement() > best_perf_improvement)) {
-      best_perf_improvement_op = op;
-      best_perf_improvement = stats.perf_improvement();
-    }
-  }
-
-  // Look at ops that we can run quickly that free up log retention.
-  if (low_io_most_logs_retained_bytes_op) {
-    if (low_io_most_logs_retained_bytes > 0) {
-      VLOG_AND_TRACE("maintenance", 1)
-                    << "Performing " << low_io_most_logs_retained_bytes_op->name() << ", "
-                    << "because it can free up more logs "
-                    << "at " << low_io_most_logs_retained_bytes
-                    << " bytes with a low IO cost";
-      return low_io_most_logs_retained_bytes_op;
-    }
-  }
-
-  // Look at free memory. If it is dangerously low, we must select something
-  // that frees memory-- the op with the most anchored memory.
-  double capacity_pct;
-  if (parent_mem_tracker_->AnySoftLimitExceeded(&capacity_pct)) {
-    if (!most_mem_anchored_op) {
-      string msg = StringPrintf("we have exceeded our soft memory limit "
-          "(current capacity is %.2f%%).  However, there are no ops currently "
-          "runnable which would free memory.", capacity_pct);
-      LOG(INFO) << msg;
-      return nullptr;
-    }
-    VLOG_AND_TRACE("maintenance", 1) << "we have exceeded our soft memory limit "
-            << "(current capacity is " << capacity_pct << "%).  Running the op "
-            << "which anchors the most memory: " << most_mem_anchored_op->name();
-    return most_mem_anchored_op;
-  }
-
-  if (most_logs_retained_bytes_op) {
-    VLOG_AND_TRACE("maintenance", 1)
-            << "Performing " << most_logs_retained_bytes_op->name() << ", "
-            << "because it can free up more logs " << "at " << most_logs_retained_bytes
-            << " bytes";
-    return most_logs_retained_bytes_op;
-  }
-
-  if (best_perf_improvement_op) {
-    if (best_perf_improvement > 0) {
-      VLOG_AND_TRACE("maintenance", 1) << "Performing " << best_perf_improvement_op->name() << ", "
-                 << "because it had the best perf_improvement score, "
-                 << "at " << best_perf_improvement;
-      return best_perf_improvement_op;
-    }
-  }
-  return nullptr;
-}
-
-void MaintenanceManager::LaunchOp(MaintenanceOp* op) {
-  MonoTime start_time(MonoTime::Now(MonoTime::FINE));
-  op->RunningGauge()->Increment();
-  LOG_TIMING(INFO, Substitute("running $0", op->name())) {
-    TRACE_EVENT1("maintenance", "MaintenanceManager::LaunchOp",
-                 "name", op->name());
-    op->Perform();
-  }
-  op->RunningGauge()->Decrement();
-  MonoTime end_time(MonoTime::Now(MonoTime::FINE));
-  MonoDelta delta(end_time.GetDeltaSince(start_time));
-  std::lock_guard<Mutex> guard(lock_);
-
-  CompletedOp& completed_op = completed_ops_[completed_ops_count_ % completed_ops_.size()];
-  completed_op.name = op->name();
-  completed_op.duration = delta;
-  completed_op.start_mono_time = start_time;
-  completed_ops_count_++;
-
-  op->DurationHistogram()->Increment(delta.ToMilliseconds());
-
-  running_ops_--;
-  op->running_--;
-  op->cond_->Signal();
-}
-
-void MaintenanceManager::GetMaintenanceManagerStatusDump(MaintenanceManagerStatusPB* out_pb) {
-  DCHECK(out_pb != nullptr);
-  std::lock_guard<Mutex> guard(lock_);
-  MaintenanceOp* best_op = FindBestOp();
-  for (MaintenanceManager::OpMapTy::value_type& val : ops_) {
-    MaintenanceManagerStatusPB_MaintenanceOpPB* op_pb = out_pb->add_registered_operations();
-    MaintenanceOp* op(val.first);
-    MaintenanceOpStats& stat(val.second);
-    op_pb->set_name(op->name());
-    op_pb->set_running(op->running());
-    if (stat.valid()) {
-      op_pb->set_runnable(stat.runnable());
-      op_pb->set_ram_anchored_bytes(stat.ram_anchored());
-      op_pb->set_logs_retained_bytes(stat.logs_retained_bytes());
-      op_pb->set_perf_improvement(stat.perf_improvement());
-    } else {
-      op_pb->set_runnable(false);
-      op_pb->set_ram_anchored_bytes(0);
-      op_pb->set_logs_retained_bytes(0);
-      op_pb->set_perf_improvement(0.0);
-    }
-
-    if (best_op == op) {
-      out_pb->mutable_best_op()->CopyFrom(*op_pb);
-    }
-  }
-
-  for (const CompletedOp& completed_op : completed_ops_) {
-    if (!completed_op.name.empty()) {
-      MaintenanceManagerStatusPB_CompletedOpPB* completed_pb = out_pb->add_completed_operations();
-      completed_pb->set_name(completed_op.name);
-      completed_pb->set_duration_millis(completed_op.duration.ToMilliseconds());
-
-      MonoDelta delta(MonoTime::Now(MonoTime::FINE).GetDeltaSince(completed_op.start_mono_time));
-      completed_pb->set_secs_since_start(delta.ToSeconds());
-    }
-  }
-}
-
-} // namespace kudu

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/tablet/maintenance_manager.h
----------------------------------------------------------------------
diff --git a/src/kudu/tablet/maintenance_manager.h b/src/kudu/tablet/maintenance_manager.h
deleted file mode 100644
index 1d1a609..0000000
--- a/src/kudu/tablet/maintenance_manager.h
+++ /dev/null
@@ -1,280 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you 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.
-#ifndef KUDU_TABLET_MAINTENANCE_MANAGER_H
-#define KUDU_TABLET_MAINTENANCE_MANAGER_H
-
-#include <stdint.h>
-
-#include <map>
-#include <memory>
-#include <set>
-#include <string>
-#include <vector>
-
-#include "kudu/gutil/macros.h"
-#include "kudu/tablet/mvcc.h"
-#include "kudu/tablet/tablet.pb.h"
-#include "kudu/util/condition_variable.h"
-#include "kudu/util/monotime.h"
-#include "kudu/util/mutex.h"
-#include "kudu/util/countdown_latch.h"
-#include "kudu/util/thread.h"
-#include "kudu/util/threadpool.h"
-
-namespace kudu {
-
-template<class T>
-class AtomicGauge;
-class Histogram;
-class MaintenanceManager;
-class MemTracker;
-
-class MaintenanceOpStats {
- public:
-  MaintenanceOpStats();
-
-  // Zero all stats. They are invalid until the first setter is called.
-  void Clear();
-
-  bool runnable() const {
-    DCHECK(valid_);
-    return runnable_;
-  }
-
-  void set_runnable(bool runnable) {
-    UpdateLastModified();
-    runnable_ = runnable;
-  }
-
-  uint64_t ram_anchored() const {
-    DCHECK(valid_);
-    return ram_anchored_;
-  }
-
-  void set_ram_anchored(uint64_t ram_anchored) {
-    UpdateLastModified();
-    ram_anchored_ = ram_anchored;
-  }
-
-  int64_t logs_retained_bytes() const {
-    DCHECK(valid_);
-    return logs_retained_bytes_;
-  }
-
-  void set_logs_retained_bytes(int64_t logs_retained_bytes) {
-    UpdateLastModified();
-    logs_retained_bytes_ = logs_retained_bytes;
-  }
-
-  double perf_improvement() const {
-    DCHECK(valid_);
-    return perf_improvement_;
-  }
-
-  void set_perf_improvement(double perf_improvement) {
-    UpdateLastModified();
-    perf_improvement_ = perf_improvement;
-  }
-
-  const MonoTime& last_modified() const {
-    DCHECK(valid_);
-    return last_modified_;
-  }
-
-  bool valid() const {
-    return valid_;
-  }
-
- private:
-  void UpdateLastModified() {
-    valid_ = true;
-    last_modified_ = MonoTime::Now(MonoTime::FINE);
-  }
-
-  // True if these stats are valid.
-  bool valid_;
-
-  // True if this op can be run now.
-  bool runnable_;
-
-  // The approximate amount of memory that not doing this operation keeps
-  // around.  This number is used to decide when to start freeing memory, so it
-  // should be fairly accurate.  May be 0.
-  uint64_t ram_anchored_;
-
-  // The approximate amount of disk space that not doing this operation keeps us from GCing from
-  // the logs. May be 0.
-  int64_t logs_retained_bytes_;
-
-  // The estimated performance improvement-- how good it is to do this on some
-  // absolute scale (yet TBD).
-  double perf_improvement_;
-
-  // The last time that the stats were modified.
-  MonoTime last_modified_;
-};
-
-// MaintenanceOp objects represent background operations that the
-// MaintenanceManager can schedule.  Once a MaintenanceOp is registered, the
-// manager will periodically poll it for statistics.  The registrant is
-// responsible for managing the memory associated with the MaintenanceOp object.
-// Op objects should be unregistered before being de-allocated.
-class MaintenanceOp {
- public:
-  friend class MaintenanceManager;
-
-  // General indicator of how much IO the Op will use.
-  enum IOUsage {
-    LOW_IO_USAGE, // Low impact operations like removing a file, updating metadata.
-    HIGH_IO_USAGE // Everything else.
-  };
-
-  explicit MaintenanceOp(std::string name, IOUsage io_usage);
-  virtual ~MaintenanceOp();
-
-  // Unregister this op, if it is currently registered.
-  void Unregister();
-
-  // Update the op statistics.  This will be called every scheduling period
-  // (about a few times a second), so it should not be too expensive.  It's
-  // possible for the returned statistics to be invalid; the caller should
-  // call MaintenanceOpStats::valid() before using them.  This will be run
-  // under the MaintenanceManager lock.
-  virtual void UpdateStats(MaintenanceOpStats* stats) = 0;
-
-  // Prepare to perform the operation.  This will be run without holding the
-  // maintenance manager lock.  It should be short, since it is run from the
-  // context of the maintenance op scheduler thread rather than a worker thread.
-  // If this returns false, we will abort the operation.
-  virtual bool Prepare() = 0;
-
-  // Perform the operation.  This will be run without holding the maintenance
-  // manager lock, and may take a long time.
-  virtual void Perform() = 0;
-
-  // Returns the histogram for this op that tracks duration. Cannot be NULL.
-  virtual scoped_refptr<Histogram> DurationHistogram() const = 0;
-
-  // Returns the gauge for this op that tracks when this op is running. Cannot be NULL.
-  virtual scoped_refptr<AtomicGauge<uint32_t> > RunningGauge() const = 0;
-
-  uint32_t running() { return running_; }
-
-  std::string name() const { return name_; }
-
-  IOUsage io_usage() const { return io_usage_; }
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(MaintenanceOp);
-
-  // The name of the operation.  Op names must be unique.
-  const std::string name_;
-
-  // The number of times that this op is currently running.
-  uint32_t running_;
-
-  // Condition variable which the UnregisterOp function can wait on.
-  //
-  // Note: 'cond_' is used with the MaintenanceManager's mutex. As such,
-  // it only exists when the op is registered.
-  gscoped_ptr<ConditionVariable> cond_;
-
-  // The MaintenanceManager with which this op is registered, or null
-  // if it is not registered.
-  std::shared_ptr<MaintenanceManager> manager_;
-
-  IOUsage io_usage_;
-};
-
-struct MaintenanceOpComparator {
-  bool operator() (const MaintenanceOp* lhs,
-                   const MaintenanceOp* rhs) const {
-    return lhs->name().compare(rhs->name()) < 0;
-  }
-};
-
-// Holds the information regarding a recently completed operation.
-struct CompletedOp {
-  std::string name;
-  MonoDelta duration;
-  MonoTime start_mono_time;
-};
-
-// The MaintenanceManager manages the scheduling of background operations such
-// as flushes or compactions.  It runs these operations in the background, in a
-// thread pool.  It uses information provided in MaintenanceOpStats objects to
-// decide which operations, if any, to run.
-class MaintenanceManager : public std::enable_shared_from_this<MaintenanceManager> {
- public:
-  struct Options {
-    int32_t num_threads;
-    int32_t polling_interval_ms;
-    uint32_t history_size;
-    std::shared_ptr<MemTracker> parent_mem_tracker;
-  };
-
-  explicit MaintenanceManager(const Options& options);
-  ~MaintenanceManager();
-
-  Status Init();
-  void Shutdown();
-
-  // Register an op with the manager.
-  void RegisterOp(MaintenanceOp* op);
-
-  // Unregister an op with the manager.
-  // If the Op is currently running, it will not be interrupted.  However, this
-  // function will block until the Op is finished.
-  void UnregisterOp(MaintenanceOp* op);
-
-  void GetMaintenanceManagerStatusDump(tablet::MaintenanceManagerStatusPB* out_pb);
-
-  static const Options DEFAULT_OPTIONS;
-
- private:
-  FRIEND_TEST(MaintenanceManagerTest, TestLogRetentionPrioritization);
-  typedef std::map<MaintenanceOp*, MaintenanceOpStats,
-          MaintenanceOpComparator> OpMapTy;
-
-  void RunSchedulerThread();
-
-  // find the best op, or null if there is nothing we want to run
-  MaintenanceOp* FindBestOp();
-
-  void LaunchOp(MaintenanceOp* op);
-
-  const int32_t num_threads_;
-  OpMapTy ops_; // registered operations
-  Mutex lock_;
-  scoped_refptr<kudu::Thread> monitor_thread_;
-  gscoped_ptr<ThreadPool> thread_pool_;
-  ConditionVariable cond_;
-  bool shutdown_;
-  uint64_t running_ops_;
-  int32_t polling_interval_ms_;
-  // Vector used as a circular buffer for recently completed ops. Elements need to be added at
-  // the completed_ops_count_ % the vector's size and then the count needs to be incremented.
-  std::vector<CompletedOp> completed_ops_;
-  int64_t completed_ops_count_;
-  std::shared_ptr<MemTracker> parent_mem_tracker_;
-
-  DISALLOW_COPY_AND_ASSIGN(MaintenanceManager);
-};
-
-} // namespace kudu
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/tablet/tablet.cc
----------------------------------------------------------------------
diff --git a/src/kudu/tablet/tablet.cc b/src/kudu/tablet/tablet.cc
index ff63aef..383e739 100644
--- a/src/kudu/tablet/tablet.cc
+++ b/src/kudu/tablet/tablet.cc
@@ -45,7 +45,6 @@
 #include "kudu/tablet/compaction_policy.h"
 #include "kudu/tablet/delta_compaction.h"
 #include "kudu/tablet/diskrowset.h"
-#include "kudu/tablet/maintenance_manager.h"
 #include "kudu/tablet/row_op.h"
 #include "kudu/tablet/rowset_info.h"
 #include "kudu/tablet/rowset_tree.h"
@@ -61,6 +60,7 @@
 #include "kudu/util/flag_tags.h"
 #include "kudu/util/locks.h"
 #include "kudu/util/logging.h"
+#include "kudu/util/maintenance_manager.h"
 #include "kudu/util/mem_tracker.h"
 #include "kudu/util/metrics.h"
 #include "kudu/util/stopwatch.h"

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/tablet/tablet.proto
----------------------------------------------------------------------
diff --git a/src/kudu/tablet/tablet.proto b/src/kudu/tablet/tablet.proto
index ae02e35..18ebe50 100644
--- a/src/kudu/tablet/tablet.proto
+++ b/src/kudu/tablet/tablet.proto
@@ -96,32 +96,3 @@ message TabletStatusPB {
   optional PartitionPB partition = 9;
   optional int64 estimated_on_disk_size = 7;
 }
-
-// Used to present the maintenance manager's internal state.
-message MaintenanceManagerStatusPB {
-  message MaintenanceOpPB {
-    required string name = 1;
-    // Number of times this operation is currently running.
-    required uint32 running = 2;
-    required bool runnable = 3;
-    required uint64 ram_anchored_bytes = 4;
-    required int64 logs_retained_bytes = 5;
-    required double perf_improvement = 6;
-  }
-
-  message CompletedOpPB {
-    required string name = 1;
-    required int32 duration_millis = 2;
-    // Number of seconds since this operation started.
-    required int32 secs_since_start = 3;
-  }
-
-  // The next operation that would run.
-  optional MaintenanceOpPB best_op = 1;
-
-  // List of all the operations.
-  repeated MaintenanceOpPB registered_operations = 2;
-
-  // This list isn't in order of anything. Can contain the same operation mutiple times.
-  repeated CompletedOpPB completed_operations = 3;
-}

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/tablet/tablet_mm_ops.h
----------------------------------------------------------------------
diff --git a/src/kudu/tablet/tablet_mm_ops.h b/src/kudu/tablet/tablet_mm_ops.h
index cecf443..f4ee1c3 100644
--- a/src/kudu/tablet/tablet_mm_ops.h
+++ b/src/kudu/tablet/tablet_mm_ops.h
@@ -18,7 +18,7 @@
 #ifndef KUDU_TABLET_TABLET_MM_OPS_H_
 #define KUDU_TABLET_TABLET_MM_OPS_H_
 
-#include "kudu/tablet/maintenance_manager.h"
+#include "kudu/util/maintenance_manager.h"
 
 namespace kudu {
 

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/tablet/tablet_peer-test.cc
----------------------------------------------------------------------
diff --git a/src/kudu/tablet/tablet_peer-test.cc b/src/kudu/tablet/tablet_peer-test.cc
index ca43117..b1c03ef 100644
--- a/src/kudu/tablet/tablet_peer-test.cc
+++ b/src/kudu/tablet/tablet_peer-test.cc
@@ -32,7 +32,6 @@
 #include "kudu/rpc/messenger.h"
 #include "kudu/server/clock.h"
 #include "kudu/server/logical_clock.h"
-#include "kudu/tablet/maintenance_manager.h"
 #include "kudu/tablet/transactions/transaction.h"
 #include "kudu/tablet/transactions/transaction_driver.h"
 #include "kudu/tablet/transactions/write_transaction.h"
@@ -40,6 +39,7 @@
 #include "kudu/tablet/tablet_peer_mm_ops.h"
 #include "kudu/tablet/tablet-test-util.h"
 #include "kudu/tserver/tserver.pb.h"
+#include "kudu/util/maintenance_manager.h"
 #include "kudu/util/metrics.h"
 #include "kudu/util/test_util.h"
 #include "kudu/util/test_macros.h"

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/tablet/tablet_peer_mm_ops.cc
----------------------------------------------------------------------
diff --git a/src/kudu/tablet/tablet_peer_mm_ops.cc b/src/kudu/tablet/tablet_peer_mm_ops.cc
index 3520d1b..d116cda 100644
--- a/src/kudu/tablet/tablet_peer_mm_ops.cc
+++ b/src/kudu/tablet/tablet_peer_mm_ops.cc
@@ -24,9 +24,9 @@
 #include <string>
 
 #include "kudu/gutil/strings/substitute.h"
-#include "kudu/tablet/maintenance_manager.h"
 #include "kudu/tablet/tablet_metrics.h"
 #include "kudu/util/flag_tags.h"
+#include "kudu/util/maintenance_manager.h"
 #include "kudu/util/metrics.h"
 
 DEFINE_int32(flush_threshold_mb, 1024,

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/tablet/tablet_peer_mm_ops.h
----------------------------------------------------------------------
diff --git a/src/kudu/tablet/tablet_peer_mm_ops.h b/src/kudu/tablet/tablet_peer_mm_ops.h
index a4b475d..a985802 100644
--- a/src/kudu/tablet/tablet_peer_mm_ops.h
+++ b/src/kudu/tablet/tablet_peer_mm_ops.h
@@ -18,8 +18,8 @@
 #ifndef KUDU_TABLET_TABLET_PEER_MM_OPS_H_
 #define KUDU_TABLET_TABLET_PEER_MM_OPS_H_
 
-#include "kudu/tablet/maintenance_manager.h"
 #include "kudu/tablet/tablet_peer.h"
+#include "kudu/util/maintenance_manager.h"
 #include "kudu/util/stopwatch.h"
 
 namespace kudu {

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/tserver/mini_tablet_server.cc
----------------------------------------------------------------------
diff --git a/src/kudu/tserver/mini_tablet_server.cc b/src/kudu/tserver/mini_tablet_server.cc
index 380946d..92f1ad2 100644
--- a/src/kudu/tserver/mini_tablet_server.cc
+++ b/src/kudu/tserver/mini_tablet_server.cc
@@ -31,12 +31,12 @@
 #include "kudu/gutil/strings/substitute.h"
 #include "kudu/server/rpc_server.h"
 #include "kudu/server/webserver.h"
-#include "kudu/tablet/maintenance_manager.h"
 #include "kudu/tablet/tablet.h"
 #include "kudu/tablet/tablet_peer.h"
 #include "kudu/tablet/tablet-test-util.h"
 #include "kudu/tserver/tablet_server.h"
 #include "kudu/tserver/ts_tablet_manager.h"
+#include "kudu/util/maintenance_manager.h"
 #include "kudu/util/net/sockaddr.h"
 #include "kudu/util/status.h"
 

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/tserver/tablet_server-test-base.h
----------------------------------------------------------------------
diff --git a/src/kudu/tserver/tablet_server-test-base.h b/src/kudu/tserver/tablet_server-test-base.h
index 1d5022e..3bcf34a 100644
--- a/src/kudu/tserver/tablet_server-test-base.h
+++ b/src/kudu/tserver/tablet_server-test-base.h
@@ -40,7 +40,6 @@
 #include "kudu/rpc/messenger.h"
 #include "kudu/server/server_base.proxy.h"
 #include "kudu/tablet/local_tablet_writer.h"
-#include "kudu/tablet/maintenance_manager.h"
 #include "kudu/tablet/tablet.h"
 #include "kudu/tablet/tablet_peer.h"
 #include "kudu/tserver/mini_tablet_server.h"
@@ -51,6 +50,7 @@
 #include "kudu/tserver/tserver_admin.proxy.h"
 #include "kudu/tserver/tserver_service.proxy.h"
 #include "kudu/tserver/ts_tablet_manager.h"
+#include "kudu/util/maintenance_manager.h"
 #include "kudu/util/metrics.h"
 #include "kudu/util/test_graph.h"
 #include "kudu/util/test_util.h"

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/tserver/tablet_server.cc
----------------------------------------------------------------------
diff --git a/src/kudu/tserver/tablet_server.cc b/src/kudu/tserver/tablet_server.cc
index ea3faad..d933491 100644
--- a/src/kudu/tserver/tablet_server.cc
+++ b/src/kudu/tserver/tablet_server.cc
@@ -27,13 +27,13 @@
 #include "kudu/rpc/service_if.h"
 #include "kudu/server/rpc_server.h"
 #include "kudu/server/webserver.h"
-#include "kudu/tablet/maintenance_manager.h"
 #include "kudu/tserver/heartbeater.h"
 #include "kudu/tserver/scanners.h"
 #include "kudu/tserver/tablet_service.h"
 #include "kudu/tserver/ts_tablet_manager.h"
 #include "kudu/tserver/tserver-path-handlers.h"
 #include "kudu/tserver/remote_bootstrap_service.h"
+#include "kudu/util/maintenance_manager.h"
 #include "kudu/util/net/net_util.h"
 #include "kudu/util/net/sockaddr.h"
 #include "kudu/util/status.h"

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/tserver/tserver-path-handlers.cc
----------------------------------------------------------------------
diff --git a/src/kudu/tserver/tserver-path-handlers.cc b/src/kudu/tserver/tserver-path-handlers.cc
index 67afcb6..6cad63f 100644
--- a/src/kudu/tserver/tserver-path-handlers.cc
+++ b/src/kudu/tserver/tserver-path-handlers.cc
@@ -32,13 +32,13 @@
 #include "kudu/gutil/strings/numbers.h"
 #include "kudu/gutil/strings/substitute.h"
 #include "kudu/server/webui_util.h"
-#include "kudu/tablet/maintenance_manager.h"
 #include "kudu/tablet/tablet.pb.h"
 #include "kudu/tablet/tablet_bootstrap.h"
 #include "kudu/tablet/tablet_peer.h"
 #include "kudu/tserver/scanners.h"
 #include "kudu/tserver/tablet_server.h"
 #include "kudu/tserver/ts_tablet_manager.h"
+#include "kudu/util/maintenance_manager.h"
 #include "kudu/util/url-coding.h"
 
 using kudu::consensus::GetConsensusRole;
@@ -46,9 +46,9 @@ using kudu::consensus::CONSENSUS_CONFIG_COMMITTED;
 using kudu::consensus::ConsensusStatePB;
 using kudu::consensus::RaftPeerPB;
 using kudu::consensus::TransactionStatusPB;
-using kudu::tablet::MaintenanceManagerStatusPB;
-using kudu::tablet::MaintenanceManagerStatusPB_CompletedOpPB;
-using kudu::tablet::MaintenanceManagerStatusPB_MaintenanceOpPB;
+using kudu::MaintenanceManagerStatusPB;
+using kudu::MaintenanceManagerStatusPB_CompletedOpPB;
+using kudu::MaintenanceManagerStatusPB_MaintenanceOpPB;
 using kudu::tablet::Tablet;
 using kudu::tablet::TabletPeer;
 using kudu::tablet::TabletStatusPB;

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/util/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/src/kudu/util/CMakeLists.txt b/src/kudu/util/CMakeLists.txt
index 01f9b1a..a924f38 100644
--- a/src/kudu/util/CMakeLists.txt
+++ b/src/kudu/util/CMakeLists.txt
@@ -30,6 +30,20 @@ ADD_EXPORTABLE_LIBRARY(histogram_proto
   NONLINK_DEPS ${HISTOGRAM_PROTO_TGTS})
 
 #######################################
+# maintenance_manager_proto
+#######################################
+
+PROTOBUF_GENERATE_CPP(
+    MAINTENANCE_MANAGER_PROTO_SRCS MAINTENANCE_MANAGER_PROTO_HDRS MAINTENANCE_MANAGER_PROTO_TGTS
+    SOURCE_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../..
+    BINARY_ROOT ${CMAKE_CURRENT_BINARY_DIR}/../..
+    PROTO_FILES maintenance_manager.proto)
+ADD_EXPORTABLE_LIBRARY(maintenance_manager_proto
+    SRCS ${MAINTENANCE_MANAGER_PROTO_SRCS}
+    DEPS protobuf
+    NONLINK_DEPS ${MAINTENANCE_MANAGER_PROTO_TGTS})
+
+#######################################
 # pb_util_proto
 #######################################
 
@@ -118,6 +132,7 @@ set(UTIL_SRCS
   kernel_stack_watchdog.cc
   locks.cc
   logging.cc
+  maintenance_manager.cc
   malloc.cc
   memcmpable_varint.cc
   memory/arena.cc
@@ -181,6 +196,7 @@ set(UTIL_LIBS
   glog
   gutil
   histogram_proto
+  maintenance_manager_proto
   pb_util_proto
   protobuf
   version_info_proto
@@ -279,6 +295,7 @@ ADD_KUDU_TEST(interval_tree-test)
 ADD_KUDU_TEST(jsonreader-test)
 ADD_KUDU_TEST(knapsack_solver-test)
 ADD_KUDU_TEST(logging-test)
+ADD_KUDU_TEST(maintenance_manager-test)
 ADD_KUDU_TEST(map-util-test)
 ADD_KUDU_TEST(mem_tracker-test)
 ADD_KUDU_TEST(memcmpable_varint-test LABELS no_tsan)

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/util/maintenance_manager-test.cc
----------------------------------------------------------------------
diff --git a/src/kudu/util/maintenance_manager-test.cc b/src/kudu/util/maintenance_manager-test.cc
new file mode 100644
index 0000000..87023dc
--- /dev/null
+++ b/src/kudu/util/maintenance_manager-test.cc
@@ -0,0 +1,286 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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 <gflags/gflags.h>
+#include <gtest/gtest.h>
+#include <memory>
+#include <mutex>
+#include <vector>
+
+#include "kudu/gutil/strings/substitute.h"
+#include "kudu/tablet/tablet.pb.h"
+#include "kudu/util/maintenance_manager.h"
+#include "kudu/util/mem_tracker.h"
+#include "kudu/util/metrics.h"
+#include "kudu/util/test_macros.h"
+#include "kudu/util/test_util.h"
+#include "kudu/util/thread.h"
+
+using std::shared_ptr;
+using std::vector;
+using strings::Substitute;
+
+METRIC_DEFINE_entity(test);
+METRIC_DEFINE_gauge_uint32(test, maintenance_ops_running,
+                           "Number of Maintenance Operations Running",
+                           kudu::MetricUnit::kMaintenanceOperations,
+                           "The number of background maintenance operations currently running.");
+METRIC_DEFINE_histogram(test, maintenance_op_duration,
+                        "Maintenance Operation Duration",
+                        kudu::MetricUnit::kSeconds, "", 60000000LU, 2);
+
+namespace kudu {
+
+const int kHistorySize = 4;
+
+class MaintenanceManagerTest : public KuduTest {
+ public:
+  MaintenanceManagerTest() {
+    test_tracker_ = MemTracker::CreateTracker(1000, "test");
+    MaintenanceManager::Options options;
+    options.num_threads = 2;
+    options.polling_interval_ms = 1;
+    options.history_size = kHistorySize;
+    options.parent_mem_tracker = test_tracker_;
+    manager_.reset(new MaintenanceManager(options));
+    manager_->Init();
+  }
+  ~MaintenanceManagerTest() {
+    manager_->Shutdown();
+  }
+
+ protected:
+  shared_ptr<MemTracker> test_tracker_;
+  shared_ptr<MaintenanceManager> manager_;
+};
+
+// Just create the MaintenanceManager and then shut it down, to make sure
+// there are no race conditions there.
+TEST_F(MaintenanceManagerTest, TestCreateAndShutdown) {
+}
+
+enum TestMaintenanceOpState {
+  OP_DISABLED,
+  OP_RUNNABLE,
+  OP_RUNNING,
+  OP_FINISHED,
+};
+
+class TestMaintenanceOp : public MaintenanceOp {
+ public:
+  TestMaintenanceOp(const std::string& name,
+                    IOUsage io_usage,
+                    TestMaintenanceOpState state,
+                    const shared_ptr<MemTracker>& tracker)
+    : MaintenanceOp(name, io_usage),
+      state_change_cond_(&lock_),
+      state_(state),
+      consumption_(tracker, 500),
+      logs_retained_bytes_(0),
+      perf_improvement_(0),
+      metric_entity_(METRIC_ENTITY_test.Instantiate(&metric_registry_, "test")),
+      maintenance_op_duration_(METRIC_maintenance_op_duration.Instantiate(metric_entity_)),
+      maintenance_ops_running_(METRIC_maintenance_ops_running.Instantiate(metric_entity_, 0)) {
+  }
+
+  virtual ~TestMaintenanceOp() {}
+
+  virtual bool Prepare() OVERRIDE {
+    std::lock_guard<Mutex> guard(lock_);
+    if (state_ != OP_RUNNABLE) {
+      return false;
+    }
+    state_ = OP_RUNNING;
+    state_change_cond_.Broadcast();
+    DLOG(INFO) << "Prepared op " << name();
+    return true;
+  }
+
+  virtual void Perform() OVERRIDE {
+    DLOG(INFO) << "Performing op " << name();
+    std::lock_guard<Mutex> guard(lock_);
+    CHECK_EQ(OP_RUNNING, state_);
+    state_ = OP_FINISHED;
+    state_change_cond_.Broadcast();
+  }
+
+  virtual void UpdateStats(MaintenanceOpStats* stats) OVERRIDE {
+    std::lock_guard<Mutex> guard(lock_);
+    stats->set_runnable(state_ == OP_RUNNABLE);
+    stats->set_ram_anchored(consumption_.consumption());
+    stats->set_logs_retained_bytes(logs_retained_bytes_);
+    stats->set_perf_improvement(perf_improvement_);
+  }
+
+  void Enable() {
+    std::lock_guard<Mutex> guard(lock_);
+    DCHECK((state_ == OP_DISABLED) || (state_ == OP_FINISHED));
+    state_ = OP_RUNNABLE;
+    state_change_cond_.Broadcast();
+  }
+
+  void WaitForState(TestMaintenanceOpState state) {
+    std::lock_guard<Mutex> guard(lock_);
+    while (true) {
+      if (state_ == state) {
+        return;
+      }
+      state_change_cond_.Wait();
+    }
+  }
+
+  bool WaitForStateWithTimeout(TestMaintenanceOpState state, int ms) {
+    MonoDelta to_wait = MonoDelta::FromMilliseconds(ms);
+    std::lock_guard<Mutex> guard(lock_);
+    while (true) {
+      if (state_ == state) {
+        return true;
+      }
+      if (!state_change_cond_.TimedWait(to_wait)) {
+        return false;
+      }
+    }
+  }
+
+  void set_ram_anchored(uint64_t ram_anchored) {
+    std::lock_guard<Mutex> guard(lock_);
+    consumption_.Reset(ram_anchored);
+  }
+
+  void set_logs_retained_bytes(uint64_t logs_retained_bytes) {
+    std::lock_guard<Mutex> guard(lock_);
+    logs_retained_bytes_ = logs_retained_bytes;
+  }
+
+  void set_perf_improvement(uint64_t perf_improvement) {
+    std::lock_guard<Mutex> guard(lock_);
+    perf_improvement_ = perf_improvement;
+  }
+
+  virtual scoped_refptr<Histogram> DurationHistogram() const OVERRIDE {
+    return maintenance_op_duration_;
+  }
+
+  virtual scoped_refptr<AtomicGauge<uint32_t> > RunningGauge() const OVERRIDE {
+    return maintenance_ops_running_;
+  }
+
+ private:
+  Mutex lock_;
+  ConditionVariable state_change_cond_;
+  enum TestMaintenanceOpState state_;
+  ScopedTrackedConsumption consumption_;
+  uint64_t logs_retained_bytes_;
+  uint64_t perf_improvement_;
+  MetricRegistry metric_registry_;
+  scoped_refptr<MetricEntity> metric_entity_;
+  scoped_refptr<Histogram> maintenance_op_duration_;
+  scoped_refptr<AtomicGauge<uint32_t> > maintenance_ops_running_;
+};
+
+// Create an op and wait for it to start running.  Unregister it while it is
+// running and verify that UnregisterOp waits for it to finish before
+// proceeding.
+TEST_F(MaintenanceManagerTest, TestRegisterUnregister) {
+  TestMaintenanceOp op1("1", MaintenanceOp::HIGH_IO_USAGE, OP_DISABLED, test_tracker_);
+  op1.set_ram_anchored(1001);
+  manager_->RegisterOp(&op1);
+  scoped_refptr<kudu::Thread> thread;
+  CHECK_OK(Thread::Create("TestThread", "TestRegisterUnregister",
+        boost::bind(&TestMaintenanceOp::Enable, &op1), &thread));
+  op1.WaitForState(OP_FINISHED);
+  manager_->UnregisterOp(&op1);
+  ThreadJoiner(thread.get()).Join();
+}
+
+// Test that we'll run an operation that doesn't improve performance when memory
+// pressure gets high.
+TEST_F(MaintenanceManagerTest, TestMemoryPressure) {
+  TestMaintenanceOp op("op", MaintenanceOp::HIGH_IO_USAGE, OP_RUNNABLE, test_tracker_);
+  op.set_ram_anchored(100);
+  manager_->RegisterOp(&op);
+
+  // At first, we don't want to run this, since there is no perf_improvement.
+  CHECK_EQ(false, op.WaitForStateWithTimeout(OP_FINISHED, 20));
+
+  // set the ram_anchored by the high mem op so high that we'll have to run it.
+  scoped_refptr<kudu::Thread> thread;
+  CHECK_OK(Thread::Create("TestThread", "MaintenanceManagerTest",
+      boost::bind(&TestMaintenanceOp::set_ram_anchored, &op, 1100), &thread));
+  op.WaitForState(OP_FINISHED);
+  manager_->UnregisterOp(&op);
+  ThreadJoiner(thread.get()).Join();
+}
+
+// Test that ops are prioritized correctly when we add log retention.
+TEST_F(MaintenanceManagerTest, TestLogRetentionPrioritization) {
+  manager_->Shutdown();
+
+  TestMaintenanceOp op1("op1", MaintenanceOp::LOW_IO_USAGE, OP_RUNNABLE, test_tracker_);
+  op1.set_ram_anchored(0);
+  op1.set_logs_retained_bytes(100);
+
+  TestMaintenanceOp op2("op2", MaintenanceOp::HIGH_IO_USAGE, OP_RUNNABLE, test_tracker_);
+  op2.set_ram_anchored(100);
+  op2.set_logs_retained_bytes(100);
+
+  TestMaintenanceOp op3("op3", MaintenanceOp::HIGH_IO_USAGE, OP_RUNNABLE, test_tracker_);
+  op3.set_ram_anchored(200);
+  op3.set_logs_retained_bytes(100);
+
+  manager_->RegisterOp(&op1);
+  manager_->RegisterOp(&op2);
+  manager_->RegisterOp(&op3);
+
+  // We want to do the low IO op first since it clears up some log retention.
+  ASSERT_EQ(&op1, manager_->FindBestOp());
+
+  manager_->UnregisterOp(&op1);
+
+  // Low IO is taken care of, now we find the op clears the most log retention and ram.
+  ASSERT_EQ(&op3, manager_->FindBestOp());
+
+  manager_->UnregisterOp(&op3);
+
+  ASSERT_EQ(&op2, manager_->FindBestOp());
+
+  manager_->UnregisterOp(&op2);
+}
+
+// Test adding operations and make sure that the history of recently completed operations
+// is correct in that it wraps around and doesn't grow.
+TEST_F(MaintenanceManagerTest, TestCompletedOpsHistory) {
+  for (int i = 0; i < 5; i++) {
+    string name = Substitute("op$0", i);
+    TestMaintenanceOp op(name, MaintenanceOp::HIGH_IO_USAGE, OP_RUNNABLE, test_tracker_);
+    op.set_perf_improvement(1);
+    op.set_ram_anchored(100);
+    manager_->RegisterOp(&op);
+
+    CHECK_EQ(true, op.WaitForStateWithTimeout(OP_FINISHED, 200));
+    manager_->UnregisterOp(&op);
+
+    MaintenanceManagerStatusPB status_pb;
+    manager_->GetMaintenanceManagerStatusDump(&status_pb);
+    // The size should be at most the history_size.
+    ASSERT_GE(kHistorySize, status_pb.completed_operations_size());
+    // See that we have the right name, even if we wrap around.
+    ASSERT_EQ(name, status_pb.completed_operations(i % 4).name());
+  }
+}
+
+} // namespace kudu

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/util/maintenance_manager.cc
----------------------------------------------------------------------
diff --git a/src/kudu/util/maintenance_manager.cc b/src/kudu/util/maintenance_manager.cc
new file mode 100644
index 0000000..1060bf8
--- /dev/null
+++ b/src/kudu/util/maintenance_manager.cc
@@ -0,0 +1,415 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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 "kudu/util/maintenance_manager.h"
+
+#include <gflags/gflags.h>
+#include <memory>
+#include <stdint.h>
+#include <string>
+#include <utility>
+
+#include "kudu/gutil/stringprintf.h"
+#include "kudu/gutil/strings/substitute.h"
+#include "kudu/util/debug/trace_event.h"
+#include "kudu/util/debug/trace_logging.h"
+#include "kudu/util/flag_tags.h"
+#include "kudu/util/mem_tracker.h"
+#include "kudu/util/metrics.h"
+#include "kudu/util/stopwatch.h"
+#include "kudu/util/thread.h"
+
+using std::pair;
+using std::shared_ptr;
+using strings::Substitute;
+
+DEFINE_int32(maintenance_manager_num_threads, 1,
+       "Size of the maintenance manager thread pool. Beyond a value of '1', one thread is "
+       "reserved for emergency flushes. For spinning disks, the number of threads should "
+       "not be above the number of devices.");
+TAG_FLAG(maintenance_manager_num_threads, stable);
+
+DEFINE_int32(maintenance_manager_polling_interval_ms, 250,
+       "Polling interval for the maintenance manager scheduler, "
+       "in milliseconds.");
+TAG_FLAG(maintenance_manager_polling_interval_ms, hidden);
+
+DEFINE_int32(maintenance_manager_history_size, 8,
+       "Number of completed operations the manager is keeping track of.");
+TAG_FLAG(maintenance_manager_history_size, hidden);
+
+DEFINE_bool(enable_maintenance_manager, true,
+       "Enable the maintenance manager, runs compaction and tablet cleaning tasks.");
+TAG_FLAG(enable_maintenance_manager, unsafe);
+
+namespace kudu {
+
+MaintenanceOpStats::MaintenanceOpStats() {
+  Clear();
+}
+
+void MaintenanceOpStats::Clear() {
+  valid_ = false;
+  runnable_ = false;
+  ram_anchored_ = 0;
+  logs_retained_bytes_ = 0;
+  perf_improvement_ = 0;
+}
+
+MaintenanceOp::MaintenanceOp(std::string name, IOUsage io_usage)
+    : name_(std::move(name)), running_(0), io_usage_(io_usage) {}
+
+MaintenanceOp::~MaintenanceOp() {
+  CHECK(!manager_.get()) << "You must unregister the " << name_
+         << " Op before destroying it.";
+}
+
+void MaintenanceOp::Unregister() {
+  CHECK(manager_.get()) << "Op " << name_ << " was never registered.";
+  manager_->UnregisterOp(this);
+}
+
+const MaintenanceManager::Options MaintenanceManager::DEFAULT_OPTIONS = {
+  0,
+  0,
+  0,
+  shared_ptr<MemTracker>(),
+};
+
+MaintenanceManager::MaintenanceManager(const Options& options)
+  : num_threads_(options.num_threads <= 0 ?
+      FLAGS_maintenance_manager_num_threads : options.num_threads),
+    cond_(&lock_),
+    shutdown_(false),
+    running_ops_(0),
+    polling_interval_ms_(options.polling_interval_ms <= 0 ?
+          FLAGS_maintenance_manager_polling_interval_ms :
+          options.polling_interval_ms),
+    completed_ops_count_(0),
+    parent_mem_tracker_(!options.parent_mem_tracker ?
+        MemTracker::GetRootTracker() : options.parent_mem_tracker) {
+  CHECK_OK(ThreadPoolBuilder("MaintenanceMgr").set_min_threads(num_threads_)
+               .set_max_threads(num_threads_).Build(&thread_pool_));
+  uint32_t history_size = options.history_size == 0 ?
+                          FLAGS_maintenance_manager_history_size :
+                          options.history_size;
+  completed_ops_.resize(history_size);
+}
+
+MaintenanceManager::~MaintenanceManager() {
+  Shutdown();
+}
+
+Status MaintenanceManager::Init() {
+  RETURN_NOT_OK(Thread::Create("maintenance", "maintenance_scheduler",
+      boost::bind(&MaintenanceManager::RunSchedulerThread, this),
+      &monitor_thread_));
+  return Status::OK();
+}
+
+void MaintenanceManager::Shutdown() {
+  {
+    std::lock_guard<Mutex> guard(lock_);
+    if (shutdown_) {
+      return;
+    }
+    shutdown_ = true;
+    cond_.Broadcast();
+  }
+  if (monitor_thread_.get()) {
+    CHECK_OK(ThreadJoiner(monitor_thread_.get()).Join());
+    monitor_thread_.reset();
+    thread_pool_->Shutdown();
+  }
+}
+
+void MaintenanceManager::RegisterOp(MaintenanceOp* op) {
+  std::lock_guard<Mutex> guard(lock_);
+  CHECK(!op->manager_.get()) << "Tried to register " << op->name()
+          << ", but it was already registered.";
+  pair<OpMapTy::iterator, bool> val
+    (ops_.insert(OpMapTy::value_type(op, MaintenanceOpStats())));
+  CHECK(val.second)
+      << "Tried to register " << op->name()
+      << ", but it already exists in ops_.";
+  op->manager_ = shared_from_this();
+  op->cond_.reset(new ConditionVariable(&lock_));
+  VLOG_AND_TRACE("maintenance", 1) << "Registered " << op->name();
+}
+
+void MaintenanceManager::UnregisterOp(MaintenanceOp* op) {
+  {
+    std::lock_guard<Mutex> guard(lock_);
+    CHECK(op->manager_.get() == this) << "Tried to unregister " << op->name()
+          << ", but it is not currently registered with this maintenance manager.";
+    auto iter = ops_.find(op);
+    CHECK(iter != ops_.end()) << "Tried to unregister " << op->name()
+        << ", but it was never registered";
+    // While the op is running, wait for it to be finished.
+    if (iter->first->running_ > 0) {
+      VLOG_AND_TRACE("maintenance", 1) << "Waiting for op " << op->name() << " to finish so "
+            << "we can unregister it.";
+    }
+    while (iter->first->running_ > 0) {
+      op->cond_->Wait();
+      iter = ops_.find(op);
+      CHECK(iter != ops_.end()) << "Tried to unregister " << op->name()
+          << ", but another thread unregistered it while we were "
+          << "waiting for it to complete";
+    }
+    ops_.erase(iter);
+  }
+  LOG(INFO) << "Unregistered op " << op->name();
+  op->cond_.reset();
+  // Remove the op's shared_ptr reference to us.  This might 'delete this'.
+  op->manager_.reset();
+}
+
+void MaintenanceManager::RunSchedulerThread() {
+  MonoDelta polling_interval = MonoDelta::FromMilliseconds(polling_interval_ms_);
+
+  std::unique_lock<Mutex> guard(lock_);
+  while (true) {
+    // Loop until we are shutting down or it is time to run another op.
+    cond_.TimedWait(polling_interval);
+    if (shutdown_) {
+      VLOG_AND_TRACE("maintenance", 1) << "Shutting down maintenance manager.";
+      return;
+    }
+
+    // Find the best op.
+    MaintenanceOp* op = FindBestOp();
+    if (!op) {
+      VLOG_AND_TRACE("maintenance", 2) << "No maintenance operations look worth doing.";
+      continue;
+    }
+
+    // Prepare the maintenance operation.
+    op->running_++;
+    running_ops_++;
+    guard.unlock();
+    bool ready = op->Prepare();
+    guard.lock();
+    if (!ready) {
+      LOG(INFO) << "Prepare failed for " << op->name()
+                << ".  Re-running scheduler.";
+      op->running_--;
+      op->cond_->Signal();
+      continue;
+    }
+
+    // Run the maintenance operation.
+    Status s = thread_pool_->SubmitFunc(boost::bind(
+          &MaintenanceManager::LaunchOp, this, op));
+    CHECK(s.ok());
+  }
+}
+
+// Finding the best operation goes through four filters:
+// - If there's an Op that we can run quickly that frees log retention, we run it.
+// - If we've hit the overall process memory limit (note: this includes memory that the Ops cannot
+//   free), we run the Op with the highest RAM usage.
+// - If there are Ops that retain logs, we run the one that has the highest retention (and if many
+//   qualify, then we run the one that also frees up the most RAM).
+// - Finally, if there's nothing else that we really need to do, we run the Op that will improve
+//   performance the most.
+//
+// The reason it's done this way is that we want to prioritize limiting the amount of resources we
+// hold on to. Low IO Ops go first since we can quickly run them, then we can look at memory usage.
+// Reversing those can starve the low IO Ops when the system is under intense memory pressure.
+//
+// In the third priority we're at a point where nothing's urgent and there's nothing we can run
+// quickly.
+// TODO We currently optimize for freeing log retention but we could consider having some sort of
+// sliding priority between log retention and RAM usage. For example, is an Op that frees
+// 128MB of log retention and 12MB of RAM always better than an op that frees 12MB of log retention
+// and 128MB of RAM? Maybe a more holistic approach would be better.
+MaintenanceOp* MaintenanceManager::FindBestOp() {
+  TRACE_EVENT0("maintenance", "MaintenanceManager::FindBestOp");
+
+  if (!FLAGS_enable_maintenance_manager) {
+    VLOG_AND_TRACE("maintenance", 1) << "Maintenance manager is disabled. Doing nothing";
+    return nullptr;
+  }
+  size_t free_threads = num_threads_ - running_ops_;
+  if (free_threads == 0) {
+    VLOG_AND_TRACE("maintenance", 1) << "there are no free threads, so we can't run anything.";
+    return nullptr;
+  }
+
+  int64_t low_io_most_logs_retained_bytes = 0;
+  MaintenanceOp* low_io_most_logs_retained_bytes_op = nullptr;
+
+  uint64_t most_mem_anchored = 0;
+  MaintenanceOp* most_mem_anchored_op = nullptr;
+
+  int64_t most_logs_retained_bytes = 0;
+  int64_t most_logs_retained_bytes_ram_anchored = 0;
+  MaintenanceOp* most_logs_retained_bytes_op = nullptr;
+
+  double best_perf_improvement = 0;
+  MaintenanceOp* best_perf_improvement_op = nullptr;
+  for (OpMapTy::value_type &val : ops_) {
+    MaintenanceOp* op(val.first);
+    MaintenanceOpStats& stats(val.second);
+    // Update op stats.
+    stats.Clear();
+    op->UpdateStats(&stats);
+    if (!stats.valid() || !stats.runnable()) {
+      continue;
+    }
+    if (stats.logs_retained_bytes() > low_io_most_logs_retained_bytes &&
+        op->io_usage_ == MaintenanceOp::LOW_IO_USAGE) {
+      low_io_most_logs_retained_bytes_op = op;
+      low_io_most_logs_retained_bytes = stats.logs_retained_bytes();
+    }
+
+    if (stats.ram_anchored() > most_mem_anchored) {
+      most_mem_anchored_op = op;
+      most_mem_anchored = stats.ram_anchored();
+    }
+    // We prioritize ops that can free more logs, but when it's the same we pick the one that
+    // also frees up the most memory.
+    if (stats.logs_retained_bytes() > 0 &&
+        (stats.logs_retained_bytes() > most_logs_retained_bytes ||
+            (stats.logs_retained_bytes() == most_logs_retained_bytes &&
+                stats.ram_anchored() > most_logs_retained_bytes_ram_anchored))) {
+      most_logs_retained_bytes_op = op;
+      most_logs_retained_bytes = stats.logs_retained_bytes();
+      most_logs_retained_bytes_ram_anchored = stats.ram_anchored();
+    }
+    if ((!best_perf_improvement_op) ||
+        (stats.perf_improvement() > best_perf_improvement)) {
+      best_perf_improvement_op = op;
+      best_perf_improvement = stats.perf_improvement();
+    }
+  }
+
+  // Look at ops that we can run quickly that free up log retention.
+  if (low_io_most_logs_retained_bytes_op) {
+    if (low_io_most_logs_retained_bytes > 0) {
+      VLOG_AND_TRACE("maintenance", 1)
+                    << "Performing " << low_io_most_logs_retained_bytes_op->name() << ", "
+                    << "because it can free up more logs "
+                    << "at " << low_io_most_logs_retained_bytes
+                    << " bytes with a low IO cost";
+      return low_io_most_logs_retained_bytes_op;
+    }
+  }
+
+  // Look at free memory. If it is dangerously low, we must select something
+  // that frees memory-- the op with the most anchored memory.
+  double capacity_pct;
+  if (parent_mem_tracker_->AnySoftLimitExceeded(&capacity_pct)) {
+    if (!most_mem_anchored_op) {
+      string msg = StringPrintf("we have exceeded our soft memory limit "
+          "(current capacity is %.2f%%).  However, there are no ops currently "
+          "runnable which would free memory.", capacity_pct);
+      LOG(INFO) << msg;
+      return nullptr;
+    }
+    VLOG_AND_TRACE("maintenance", 1) << "we have exceeded our soft memory limit "
+            << "(current capacity is " << capacity_pct << "%).  Running the op "
+            << "which anchors the most memory: " << most_mem_anchored_op->name();
+    return most_mem_anchored_op;
+  }
+
+  if (most_logs_retained_bytes_op) {
+    VLOG_AND_TRACE("maintenance", 1)
+            << "Performing " << most_logs_retained_bytes_op->name() << ", "
+            << "because it can free up more logs " << "at " << most_logs_retained_bytes
+            << " bytes";
+    return most_logs_retained_bytes_op;
+  }
+
+  if (best_perf_improvement_op) {
+    if (best_perf_improvement > 0) {
+      VLOG_AND_TRACE("maintenance", 1) << "Performing " << best_perf_improvement_op->name() << ", "
+                 << "because it had the best perf_improvement score, "
+                 << "at " << best_perf_improvement;
+      return best_perf_improvement_op;
+    }
+  }
+  return nullptr;
+}
+
+void MaintenanceManager::LaunchOp(MaintenanceOp* op) {
+  MonoTime start_time(MonoTime::Now(MonoTime::FINE));
+  op->RunningGauge()->Increment();
+  LOG_TIMING(INFO, Substitute("running $0", op->name())) {
+    TRACE_EVENT1("maintenance", "MaintenanceManager::LaunchOp",
+                 "name", op->name());
+    op->Perform();
+  }
+  op->RunningGauge()->Decrement();
+  MonoTime end_time(MonoTime::Now(MonoTime::FINE));
+  MonoDelta delta(end_time.GetDeltaSince(start_time));
+  std::lock_guard<Mutex> guard(lock_);
+
+  CompletedOp& completed_op = completed_ops_[completed_ops_count_ % completed_ops_.size()];
+  completed_op.name = op->name();
+  completed_op.duration = delta;
+  completed_op.start_mono_time = start_time;
+  completed_ops_count_++;
+
+  op->DurationHistogram()->Increment(delta.ToMilliseconds());
+
+  running_ops_--;
+  op->running_--;
+  op->cond_->Signal();
+}
+
+void MaintenanceManager::GetMaintenanceManagerStatusDump(MaintenanceManagerStatusPB* out_pb) {
+  DCHECK(out_pb != nullptr);
+  std::lock_guard<Mutex> guard(lock_);
+  MaintenanceOp* best_op = FindBestOp();
+  for (MaintenanceManager::OpMapTy::value_type& val : ops_) {
+    MaintenanceManagerStatusPB_MaintenanceOpPB* op_pb = out_pb->add_registered_operations();
+    MaintenanceOp* op(val.first);
+    MaintenanceOpStats& stat(val.second);
+    op_pb->set_name(op->name());
+    op_pb->set_running(op->running());
+    if (stat.valid()) {
+      op_pb->set_runnable(stat.runnable());
+      op_pb->set_ram_anchored_bytes(stat.ram_anchored());
+      op_pb->set_logs_retained_bytes(stat.logs_retained_bytes());
+      op_pb->set_perf_improvement(stat.perf_improvement());
+    } else {
+      op_pb->set_runnable(false);
+      op_pb->set_ram_anchored_bytes(0);
+      op_pb->set_logs_retained_bytes(0);
+      op_pb->set_perf_improvement(0.0);
+    }
+
+    if (best_op == op) {
+      out_pb->mutable_best_op()->CopyFrom(*op_pb);
+    }
+  }
+
+  for (const CompletedOp& completed_op : completed_ops_) {
+    if (!completed_op.name.empty()) {
+      MaintenanceManagerStatusPB_CompletedOpPB* completed_pb = out_pb->add_completed_operations();
+      completed_pb->set_name(completed_op.name);
+      completed_pb->set_duration_millis(completed_op.duration.ToMilliseconds());
+
+      MonoDelta delta(MonoTime::Now(MonoTime::FINE).GetDeltaSince(completed_op.start_mono_time));
+      completed_pb->set_secs_since_start(delta.ToSeconds());
+    }
+  }
+}
+
+} // namespace kudu

http://git-wip-us.apache.org/repos/asf/incubator-kudu/blob/ee380939/src/kudu/util/maintenance_manager.h
----------------------------------------------------------------------
diff --git a/src/kudu/util/maintenance_manager.h b/src/kudu/util/maintenance_manager.h
new file mode 100644
index 0000000..ef3229e
--- /dev/null
+++ b/src/kudu/util/maintenance_manager.h
@@ -0,0 +1,277 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+#pragma once
+
+#include <stdint.h>
+
+#include <map>
+#include <memory>
+#include <set>
+#include <string>
+#include <vector>
+
+#include "kudu/gutil/macros.h"
+#include "kudu/util/condition_variable.h"
+#include "kudu/util/maintenance_manager.pb.h"
+#include "kudu/util/monotime.h"
+#include "kudu/util/mutex.h"
+#include "kudu/util/countdown_latch.h"
+#include "kudu/util/thread.h"
+#include "kudu/util/threadpool.h"
+
+namespace kudu {
+
+template<class T>
+class AtomicGauge;
+class Histogram;
+class MaintenanceManager;
+class MemTracker;
+
+class MaintenanceOpStats {
+ public:
+  MaintenanceOpStats();
+
+  // Zero all stats. They are invalid until the first setter is called.
+  void Clear();
+
+  bool runnable() const {
+    DCHECK(valid_);
+    return runnable_;
+  }
+
+  void set_runnable(bool runnable) {
+    UpdateLastModified();
+    runnable_ = runnable;
+  }
+
+  uint64_t ram_anchored() const {
+    DCHECK(valid_);
+    return ram_anchored_;
+  }
+
+  void set_ram_anchored(uint64_t ram_anchored) {
+    UpdateLastModified();
+    ram_anchored_ = ram_anchored;
+  }
+
+  int64_t logs_retained_bytes() const {
+    DCHECK(valid_);
+    return logs_retained_bytes_;
+  }
+
+  void set_logs_retained_bytes(int64_t logs_retained_bytes) {
+    UpdateLastModified();
+    logs_retained_bytes_ = logs_retained_bytes;
+  }
+
+  double perf_improvement() const {
+    DCHECK(valid_);
+    return perf_improvement_;
+  }
+
+  void set_perf_improvement(double perf_improvement) {
+    UpdateLastModified();
+    perf_improvement_ = perf_improvement;
+  }
+
+  const MonoTime& last_modified() const {
+    DCHECK(valid_);
+    return last_modified_;
+  }
+
+  bool valid() const {
+    return valid_;
+  }
+
+ private:
+  void UpdateLastModified() {
+    valid_ = true;
+    last_modified_ = MonoTime::Now(MonoTime::FINE);
+  }
+
+  // True if these stats are valid.
+  bool valid_;
+
+  // True if this op can be run now.
+  bool runnable_;
+
+  // The approximate amount of memory that not doing this operation keeps
+  // around.  This number is used to decide when to start freeing memory, so it
+  // should be fairly accurate.  May be 0.
+  uint64_t ram_anchored_;
+
+  // The approximate amount of disk space that not doing this operation keeps us from GCing from
+  // the logs. May be 0.
+  int64_t logs_retained_bytes_;
+
+  // The estimated performance improvement-- how good it is to do this on some
+  // absolute scale (yet TBD).
+  double perf_improvement_;
+
+  // The last time that the stats were modified.
+  MonoTime last_modified_;
+};
+
+// MaintenanceOp objects represent background operations that the
+// MaintenanceManager can schedule.  Once a MaintenanceOp is registered, the
+// manager will periodically poll it for statistics.  The registrant is
+// responsible for managing the memory associated with the MaintenanceOp object.
+// Op objects should be unregistered before being de-allocated.
+class MaintenanceOp {
+ public:
+  friend class MaintenanceManager;
+
+  // General indicator of how much IO the Op will use.
+  enum IOUsage {
+    LOW_IO_USAGE, // Low impact operations like removing a file, updating metadata.
+    HIGH_IO_USAGE // Everything else.
+  };
+
+  explicit MaintenanceOp(std::string name, IOUsage io_usage);
+  virtual ~MaintenanceOp();
+
+  // Unregister this op, if it is currently registered.
+  void Unregister();
+
+  // Update the op statistics.  This will be called every scheduling period
+  // (about a few times a second), so it should not be too expensive.  It's
+  // possible for the returned statistics to be invalid; the caller should
+  // call MaintenanceOpStats::valid() before using them.  This will be run
+  // under the MaintenanceManager lock.
+  virtual void UpdateStats(MaintenanceOpStats* stats) = 0;
+
+  // Prepare to perform the operation.  This will be run without holding the
+  // maintenance manager lock.  It should be short, since it is run from the
+  // context of the maintenance op scheduler thread rather than a worker thread.
+  // If this returns false, we will abort the operation.
+  virtual bool Prepare() = 0;
+
+  // Perform the operation.  This will be run without holding the maintenance
+  // manager lock, and may take a long time.
+  virtual void Perform() = 0;
+
+  // Returns the histogram for this op that tracks duration. Cannot be NULL.
+  virtual scoped_refptr<Histogram> DurationHistogram() const = 0;
+
+  // Returns the gauge for this op that tracks when this op is running. Cannot be NULL.
+  virtual scoped_refptr<AtomicGauge<uint32_t> > RunningGauge() const = 0;
+
+  uint32_t running() { return running_; }
+
+  std::string name() const { return name_; }
+
+  IOUsage io_usage() const { return io_usage_; }
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(MaintenanceOp);
+
+  // The name of the operation.  Op names must be unique.
+  const std::string name_;
+
+  // The number of times that this op is currently running.
+  uint32_t running_;
+
+  // Condition variable which the UnregisterOp function can wait on.
+  //
+  // Note: 'cond_' is used with the MaintenanceManager's mutex. As such,
+  // it only exists when the op is registered.
+  gscoped_ptr<ConditionVariable> cond_;
+
+  // The MaintenanceManager with which this op is registered, or null
+  // if it is not registered.
+  std::shared_ptr<MaintenanceManager> manager_;
+
+  IOUsage io_usage_;
+};
+
+struct MaintenanceOpComparator {
+  bool operator() (const MaintenanceOp* lhs,
+                   const MaintenanceOp* rhs) const {
+    return lhs->name().compare(rhs->name()) < 0;
+  }
+};
+
+// Holds the information regarding a recently completed operation.
+struct CompletedOp {
+  std::string name;
+  MonoDelta duration;
+  MonoTime start_mono_time;
+};
+
+// The MaintenanceManager manages the scheduling of background operations such
+// as flushes or compactions.  It runs these operations in the background, in a
+// thread pool.  It uses information provided in MaintenanceOpStats objects to
+// decide which operations, if any, to run.
+class MaintenanceManager : public std::enable_shared_from_this<MaintenanceManager> {
+ public:
+  struct Options {
+    int32_t num_threads;
+    int32_t polling_interval_ms;
+    uint32_t history_size;
+    std::shared_ptr<MemTracker> parent_mem_tracker;
+  };
+
+  explicit MaintenanceManager(const Options& options);
+  ~MaintenanceManager();
+
+  Status Init();
+  void Shutdown();
+
+  // Register an op with the manager.
+  void RegisterOp(MaintenanceOp* op);
+
+  // Unregister an op with the manager.
+  // If the Op is currently running, it will not be interrupted.  However, this
+  // function will block until the Op is finished.
+  void UnregisterOp(MaintenanceOp* op);
+
+  void GetMaintenanceManagerStatusDump(MaintenanceManagerStatusPB* out_pb);
+
+  static const Options DEFAULT_OPTIONS;
+
+ private:
+  FRIEND_TEST(MaintenanceManagerTest, TestLogRetentionPrioritization);
+  typedef std::map<MaintenanceOp*, MaintenanceOpStats,
+          MaintenanceOpComparator> OpMapTy;
+
+  void RunSchedulerThread();
+
+  // find the best op, or null if there is nothing we want to run
+  MaintenanceOp* FindBestOp();
+
+  void LaunchOp(MaintenanceOp* op);
+
+  const int32_t num_threads_;
+  OpMapTy ops_; // registered operations
+  Mutex lock_;
+  scoped_refptr<kudu::Thread> monitor_thread_;
+  gscoped_ptr<ThreadPool> thread_pool_;
+  ConditionVariable cond_;
+  bool shutdown_;
+  uint64_t running_ops_;
+  int32_t polling_interval_ms_;
+  // Vector used as a circular buffer for recently completed ops. Elements need to be added at
+  // the completed_ops_count_ % the vector's size and then the count needs to be incremented.
+  std::vector<CompletedOp> completed_ops_;
+  int64_t completed_ops_count_;
+  std::shared_ptr<MemTracker> parent_mem_tracker_;
+
+  DISALLOW_COPY_AND_ASSIGN(MaintenanceManager);
+};
+
+} // namespace kudu