PEL: Check if PEL pruning necessary on a new PEL

When a new PEL is added check if the size of all PELs is now more than
95% of the maximum capacity.  If it is, call the repository's prune()
function from the event loop to make more space.  Also delete the
OpenBMC event logs corresponding to the PELs that were just deleted.

It's called from the event loop so that the current D-Bus method
response that the code is in now can return to the caller first.

It tops out at 95% to ensure that we never go over.  It's possible this
can be tuned in the future, but at the current 20MB limit that still
allows 19MB before pruning will take it down to at most 18MB.

Signed-off-by: Matt Spinler <spinler@us.ibm.com>
Change-Id: I962866eceee89cd605fcd36ec08b20ff762fe6cd
diff --git a/extensions/openpower-pels/manager.cpp b/extensions/openpower-pels/manager.cpp
index 66f5ee5..fea2ba9 100644
--- a/extensions/openpower-pels/manager.cpp
+++ b/extensions/openpower-pels/manager.cpp
@@ -120,6 +120,11 @@
                               entry("PEL_ID=0x%X", pel->id()));
 
             _repo.add(pel);
+
+            if (_repo.sizeWarning())
+            {
+                scheduleRepoPrune();
+            }
         }
         catch (std::exception& e)
         {
@@ -281,6 +286,11 @@
 
         _repo.add(pel);
 
+        if (_repo.sizeWarning())
+        {
+            scheduleRepoPrune();
+        }
+
         auto src = pel->primarySRC();
         if (src)
         {
@@ -414,5 +424,25 @@
     }
 }
 
+void Manager::scheduleRepoPrune()
+{
+    sdeventplus::Event event = sdeventplus::Event::get_default();
+
+    _repoPrunerEventSource = std::make_unique<sdeventplus::source::Defer>(
+        event, std::bind(std::mem_fn(&Manager::pruneRepo), this,
+                         std::placeholders::_1));
+}
+
+void Manager::pruneRepo(sdeventplus::source::EventBase& source)
+{
+    auto idsToDelete = _repo.prune();
+
+    // Remove the OpenBMC event logs for the PELs that were just removed.
+    std::for_each(idsToDelete.begin(), idsToDelete.end(),
+                  [this](auto id) { this->_logManager.erase(id); });
+
+    _repoPrunerEventSource.reset();
+}
+
 } // namespace pels
 } // namespace openpower