From 2c0ce576e35a4191743672b5051a07016fc8475c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Simon=20D=C3=A9saulniers?= <sim.desaulniers@gmail.com>
Date: Sun, 21 Aug 2016 21:29:17 -0400
Subject: [PATCH] dht: enable data persistence

---
 include/opendht/dht.h |  1 +
 src/dht.cpp           | 14 +++++++++++++-
 2 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/include/opendht/dht.h b/include/opendht/dht.h
index d52e9b6c..6fe39bae 100644
--- a/include/opendht/dht.h
+++ b/include/opendht/dht.h
@@ -364,6 +364,7 @@ private:
     // timing
     Scheduler scheduler {};
     std::shared_ptr<Scheduler::Job> nextNodesConfirmation {};
+    std::shared_ptr<Scheduler::Job> nextStorageMaintenance {};
     time_point mybucket_grow_time {time_point::min()}, mybucket6_grow_time {time_point::min()};
 
     NetworkEngine network_engine;
diff --git a/src/dht.cpp b/src/dht.cpp
index 74c90f4d..10656b0e 100644
--- a/src/dht.cpp
+++ b/src/dht.cpp
@@ -2144,6 +2144,12 @@ Dht::storageStore(const InfoHash& id, const std::shared_ptr<Value>& value, time_
         total_values += std::get<2>(store);
         storageChanged(*(*st), *std::get<0>(store));
     }
+
+    if (not nextStorageMaintenance)
+        /* activate storage maintenance for the first time */
+        nextStorageMaintenance = scheduler.add(now + MAX_STORAGE_MAINTENANCE_EXPIRE_TIME,
+                                               std::bind(&Dht::dataPersistence, this));
+
     return std::get<0>(store);
 }
 
@@ -2706,12 +2712,18 @@ Dht::dataPersistence() {
     auto storage_maintenance_time = time_point::max();
     for (auto &str : store) {
         if (now > str->maintenance_time) {
+            DHT_LOG.WARN("[storage %s] maintenance (%u values, %u bytes)",
+                    str->id.toString().c_str(), str->valueCount(), str->totalSize());
             maintainStorage(str->id);
             str->maintenance_time = now + MAX_STORAGE_MAINTENANCE_EXPIRE_TIME;
         }
         storage_maintenance_time = std::min(storage_maintenance_time, str->maintenance_time);
     }
-    scheduler.add(storage_maintenance_time, std::bind(&Dht::dataPersistence, this));
+    DHT_LOG.WARN("[store] next maintenance in %u minutes",
+            std::chrono::duration_cast<std::chrono::minutes>(storage_maintenance_time-now));
+    nextStorageMaintenance = storage_maintenance_time != time_point::max() ?
+                                scheduler.add(storage_maintenance_time, std::bind(&Dht::dataPersistence, this)) :
+                                nullptr;
 }
 
 size_t
-- 
GitLab