regulators: Add getMessages method

Add getMessages method. It gets the journal messages that have the
specified field set to the specified value.

Tested:
 * Get field "_PID" with value "1".
 * Get field "_SYSTEMD_UNIT" with value "init.scope".
 * Get a field that does not exist and return vector size is 0.
 * max parameter is 0 and return all messages.
 * max parameter is less than number of messages in journal
   and return max number of messages.
 * max parameter is more than number of messages in journal
   and return all messages

Signed-off-by: Bob King <Bob_King@wistron.com>
Change-Id: I6a9410b5509b3044c1de103e71276e8e7c241fa6
diff --git a/phosphor-regulators/src/journal.cpp b/phosphor-regulators/src/journal.cpp
new file mode 100644
index 0000000..be94275
--- /dev/null
+++ b/phosphor-regulators/src/journal.cpp
@@ -0,0 +1,150 @@
+
+/**
+ * Copyright © 2020 IBM Corporation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "journal.hpp"
+
+#include <string.h>
+#include <time.h>
+
+#include <cstdint>
+#include <ctime>
+#include <stdexcept>
+
+using namespace phosphor::logging;
+
+namespace phosphor::power::regulators
+{
+
+class JournalCloser
+{
+  public:
+    JournalCloser() = delete;
+    JournalCloser(const JournalCloser&) = delete;
+    JournalCloser(JournalCloser&&) = delete;
+    JournalCloser& operator=(const JournalCloser&) = delete;
+    JournalCloser& operator=(JournalCloser&&) = delete;
+
+    JournalCloser(sd_journal* journal) : journal{journal}
+    {
+    }
+    ~JournalCloser()
+    {
+        sd_journal_close(journal);
+    }
+
+  private:
+    sd_journal* journal{nullptr};
+};
+
+std::string SystemdJournal::getFieldValue(sd_journal* journal,
+                                          const char* field) const
+{
+    const char* data{nullptr};
+    size_t length{0};
+
+    // Get field data
+    int rc = sd_journal_get_data(journal, field, (const void**)&data, &length);
+    if (rc < 0)
+    {
+        throw std::runtime_error{
+            std::string{"Failed to read journal entry field: "} +
+            strerror(-rc)};
+    }
+
+    // Get field value
+    size_t prefix{0};
+    const void* eq = memchr(data, '=', length);
+    if (eq)
+    {
+        prefix = (const char*)eq - data + 1;
+    }
+    else
+    {
+        prefix = 0;
+    }
+
+    std::string value{data + prefix, length - prefix};
+
+    return value;
+}
+
+std::vector<std::string>
+    SystemdJournal::getMessages(const std::string& field,
+                                const std::string& fieldValue, unsigned int max)
+{
+    sd_journal* journal;
+    std::vector<std::string> messages;
+
+    int rc = sd_journal_open(&journal, SD_JOURNAL_LOCAL_ONLY);
+    if (rc < 0)
+    {
+        throw std::runtime_error{std::string{"Failed to open journal: "} +
+                                 strerror(-rc)};
+    }
+
+    JournalCloser closer{journal};
+
+    SD_JOURNAL_FOREACH_BACKWARDS(journal)
+    {
+        // Get input field
+        std::string value = getFieldValue(journal, field.c_str());
+
+        // Compare field value and read data
+        if (value == fieldValue)
+        {
+            // Get SYSLOG_IDENTIFIER field
+            std::string syslog = getFieldValue(journal, "SYSLOG_IDENTIFIER");
+
+            // Get _PID field
+            std::string pid = getFieldValue(journal, "_PID");
+
+            // Get MESSAGE field
+            std::string message = getFieldValue(journal, "MESSAGE");
+
+            // Get realtime
+            uint64_t usec{0};
+            rc = sd_journal_get_realtime_usec(journal, &usec);
+            if (rc < 0)
+            {
+                throw std::runtime_error{
+                    std::string{"Failed to get journal entry timestamp: "} +
+                    strerror(-rc)};
+            }
+
+            // Convert realtime microseconds to date format
+            char dateBuffer[80];
+            std::string date;
+            std::time_t timeInSecs = usec / 1000000;
+            strftime(dateBuffer, sizeof(dateBuffer), "%b %d %H:%M:%S",
+                     std::localtime(&timeInSecs));
+            date = dateBuffer;
+
+            // Store value to messages
+            value = date + " " + syslog + "[" + pid + "]: " + message;
+            messages.insert(messages.begin(), value);
+        }
+        // Set the maximum number of messages
+        if ((max != 0) && (messages.size() >= max))
+        {
+            break;
+        }
+    }
+
+    return messages;
+}
+
+} // namespace phosphor::power::regulators
\ No newline at end of file
diff --git a/phosphor-regulators/src/journal.hpp b/phosphor-regulators/src/journal.hpp
index 47dc347..4499aa6 100644
--- a/phosphor-regulators/src/journal.hpp
+++ b/phosphor-regulators/src/journal.hpp
@@ -15,6 +15,8 @@
  */
 #pragma once
 
+#include <systemd/sd-journal.h>
+
 #include <phosphor-logging/log.hpp>
 
 #include <string>
@@ -82,6 +84,21 @@
      * @param messages messages to log
      */
     virtual void logInfo(const std::vector<std::string>& messages) = 0;
+
+    /**
+     * Gets the journal messages that have the specified field set to the
+     * specified value.
+     *
+     * @param field journal field to use during search
+     * @param fieldValue expected field value
+     * @param max Maximum number of messages to return.
+     *        Specify 0 to return all matching messages.
+     *
+     * @return matching messages from the journal
+     */
+    virtual std::vector<std::string> getMessages(const std::string& field,
+                                                 const std::string& fieldValue,
+                                                 unsigned int max = 0) = 0;
 };
 
 /**
@@ -100,6 +117,11 @@
     SystemdJournal& operator=(SystemdJournal&&) = delete;
     virtual ~SystemdJournal() = default;
 
+    /** @copydoc Journal::getMessages() */
+    virtual std::vector<std::string> getMessages(const std::string& field,
+                                                 const std::string& fieldValue,
+                                                 unsigned int max) override;
+
     /** @copydoc Journal::logDebug(const std::string&) */
     virtual void logDebug(const std::string& message) override
     {
@@ -147,6 +169,16 @@
             logInfo(message);
         }
     }
+
+  private:
+    /**
+     * Gets the data object associated with a specific field from the
+     * current journal entry and return the data as string.
+     *
+     * @param journal the current journal entry
+     * @param field journal field to use during search
+     */
+    std::string getFieldValue(sd_journal* journal, const char* field) const;
 };
 
 } // namespace phosphor::power::regulators
diff --git a/phosphor-regulators/src/meson.build b/phosphor-regulators/src/meson.build
index ed22808..b20e0bd 100644
--- a/phosphor-regulators/src/meson.build
+++ b/phosphor-regulators/src/meson.build
@@ -13,6 +13,7 @@
     'exception_utils.cpp',
     'ffdc_file.cpp',
     'id_map.cpp',
+    'journal.cpp',
     'pmbus_utils.cpp',
     'rail.cpp',
     'sensor_monitoring.cpp',
diff --git a/phosphor-regulators/test/mock_journal.hpp b/phosphor-regulators/test/mock_journal.hpp
index d1ebe0b..fbb67a7 100644
--- a/phosphor-regulators/test/mock_journal.hpp
+++ b/phosphor-regulators/test/mock_journal.hpp
@@ -41,6 +41,10 @@
     MockJournal& operator=(MockJournal&&) = delete;
     virtual ~MockJournal() = default;
 
+    MOCK_METHOD(std::vector<std::string>, getMessages,
+                (const std::string& field, const std::string& fieldValue,
+                 unsigned int max),
+                (override));
     MOCK_METHOD(void, logDebug, (const std::string& message), (override));
     MOCK_METHOD(void, logDebug, (const std::vector<std::string>& messages),
                 (override));