version-handler: add version-handler, blob handler

Implement version-handler: a blob handler for retrieving version
information about a blob.

Problem: ipmi-flash(firmware-handler) provides a mechanism to transfer
firmware updates, verify them and perform updates but there is no
mechanism to interrogate the firmware for its version.

Solution: version-handler provides handlers for retrieving information
about firmware blobs. Adding "version" syntax to "/flash/blob" entries
in the json configuration file enables this feature.
The mechanism to retrieve version is identical to the mechanism used by
firmware-handler to perform preparation, verification and updates (kick
off systemd targets).

Signed-off-by: Jason Ling <jasonling@google.com>
Change-Id: I28868ca8dd76d63af668d2e46b9359401d45f0bc
diff --git a/bmc/version-handler/Makefile.am b/bmc/version-handler/Makefile.am
index 8370806..5f94379 100644
--- a/bmc/version-handler/Makefile.am
+++ b/bmc/version-handler/Makefile.am
@@ -5,6 +5,7 @@
 
 noinst_LTLIBRARIES = libversionblob_common.la
 libversionblob_common_la_SOURCES = \
+	version_handler.cpp \
 	version_handlers_builder.cpp
 
 libversionblob_common_la_CXXFLAGS = \
@@ -21,4 +22,23 @@
         -lstdc++fs
 libversionblob_common_la_LIBADD = $(top_builddir)/libfirmware_common.la
 libversionblob_common_la_LIBADD += $(top_builddir)/bmc/libbmc_common.la
+
+libversionblobdir = ${libdir}/ipmid-providers
+libversionblob_LTLIBRARIES = libversionblob.la
+libversionblob_la_SOURCES = \
+	main.cpp
+libversionblob_la_LIBADD = libversionblob_common.la
+libversionblob_la_LDFLAGS = \
+	$(SDBUSPLUS_LIBS) \
+	$(PHOSPHOR_LOGGING_LIBS) \
+	$(CODE_COVERAGE_LIBS) \
+	-lstdc++fs \
+	-version-info 0:0:0 -shared
+libversionblob_la_CXXFLAGS = \
+	-I$(top_srcdir) \
+	-I$(top_srcdir)/bmc \
+	$(SDBUSPLUS_CFLAGS) \
+	$(PHOSPHOR_LOGGING_CFLAGS) \
+	$(CODE_COVERAGE_CXXFLAGS) \
+	-flto
 SUBDIRS = . test
diff --git a/bmc/version-handler/main.cpp b/bmc/version-handler/main.cpp
new file mode 100644
index 0000000..aae27f7
--- /dev/null
+++ b/bmc/version-handler/main.cpp
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2018 Google Inc.
+ *
+ * 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 "config.h"
+
+#include "file_handler.hpp"
+#include "general_systemd.hpp"
+#include "image_handler.hpp"
+#include "status.hpp"
+#include "version_handler.hpp"
+#include "version_handlers_builder.hpp"
+
+#include <phosphor-logging/log.hpp>
+#include <sdbusplus/bus.hpp>
+
+#include <cstdint>
+#include <memory>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+namespace ipmi_flash
+{
+
+namespace
+{
+
+static constexpr const char* jsonConfigurationPath =
+    "/usr/share/phosphor-ipmi-flash/";
+} // namespace
+
+std::unique_ptr<blobs::GenericBlobInterface>
+    createHandlerFromJsons(VersionHandlersBuilder& builder,
+                           const char* configPath)
+{
+    std::vector<HandlerConfig<VersionActionPack>> configsFromJson =
+        builder.buildHandlerConfigs(configPath);
+
+    VersionInfoMap handlerMap;
+    for (auto& config : configsFromJson)
+    {
+        auto [it, inserted] = handlerMap.try_emplace(
+            config.blobId, config.blobId, std::move(config.actions),
+            std::move(config.handler));
+        if (inserted == false)
+        {
+            std::fprintf(stderr, "duplicate blob id %s, discarding\n",
+                         config.blobId.c_str());
+        }
+        else
+        {
+            std::fprintf(stderr, "config loaded: %s\n", config.blobId.c_str());
+        }
+    }
+    auto handler = VersionBlobHandler::create(std::move(handlerMap));
+    if (!handler)
+    {
+        std::fprintf(stderr, "Version Handler has an invalid configuration");
+        return nullptr;
+    }
+
+    return handler;
+}
+} // namespace ipmi_flash
+extern "C"
+{
+    std::unique_ptr<blobs::GenericBlobInterface> createHandler();
+}
+
+std::unique_ptr<blobs::GenericBlobInterface> createHandler()
+{
+    ipmi_flash::VersionHandlersBuilder builder;
+    return ipmi_flash::createHandlerFromJsons(
+        builder, ipmi_flash::jsonConfigurationPath);
+}
diff --git a/bmc/version-handler/test/Makefile.am b/bmc/version-handler/test/Makefile.am
index 94c398d..0c02ff0 100644
--- a/bmc/version-handler/test/Makefile.am
+++ b/bmc/version-handler/test/Makefile.am
@@ -3,6 +3,7 @@
 AM_CPPFLAGS = \
 	-I$(top_srcdir)/ \
 	-I$(top_srcdir)/bmc/ \
+	-I$(top_srcdir)/bmc/test \
 	-I$(top_srcdir)/bmc/version-handler \
 	$(GTEST_CFLAGS) \
 	$(GMOCK_CFLAGS) \
@@ -22,9 +23,29 @@
 
 # Run all 'check' test programs
 check_PROGRAMS = \
-	version_json_unittest
+	version_json_unittest \
+	version_canhandle_enumerate_unittest \
+	version_createhandler_unittest \
+	version_open_unittest \
+	version_close_unittest \
+	version_read_unittest
 
 TESTS = $(check_PROGRAMS)
 
 version_json_unittest_SOURCES = version_json_unittest.cpp
 version_json_unittest_LDADD = $(top_builddir)/bmc/version-handler/libversionblob_common.la
+
+version_canhandle_enumerate_unittest_SOURCES = version_canhandle_enumerate_unittest.cpp
+version_canhandle_enumerate_unittest_LDADD = $(top_builddir)/bmc/version-handler/libversionblob_common.la
+
+version_createhandler_unittest_SOURCES = version_createhandler_unittest.cpp
+version_createhandler_unittest_LDADD = $(top_builddir)/bmc/version-handler/libversionblob_common.la
+
+version_open_unittest_SOURCES = version_open_unittest.cpp
+version_open_unittest_LDADD = $(top_builddir)/bmc/version-handler/libversionblob_common.la
+
+version_close_unittest_SOURCES = version_close_unittest.cpp
+version_close_unittest_LDADD = $(top_builddir)/bmc/version-handler/libversionblob_common.la
+
+version_read_unittest_SOURCES = version_read_unittest.cpp
+version_read_unittest_LDADD = $(top_builddir)/bmc/version-handler/libversionblob_common.la
diff --git a/bmc/version-handler/test/version_canhandle_enumerate_unittest.cpp b/bmc/version-handler/test/version_canhandle_enumerate_unittest.cpp
new file mode 100644
index 0000000..3637c32
--- /dev/null
+++ b/bmc/version-handler/test/version_canhandle_enumerate_unittest.cpp
@@ -0,0 +1,52 @@
+#include "flags.hpp"
+#include "image_mock.hpp"
+#include "triggerable_mock.hpp"
+#include "util.hpp"
+#include "version_handler.hpp"
+
+#include <array>
+#include <string>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+namespace ipmi_flash
+{
+TEST(VersionHandlerCanHandleTest, VerifyGoodInfoMap)
+{
+    VersionInfoMap test;
+    std::array blobNames{"blob0", "blob1", "blob2", "blob3"};
+    for (const auto& blobName : blobNames)
+    {
+        test.try_emplace(blobName,
+                         VersionInfoPack(blobName,
+                                         std::make_unique<VersionActionPack>(
+                                             CreateTriggerMock()),
+                                         CreateImageMock()));
+    }
+    auto handler = VersionBlobHandler::create(std::move(test));
+    ASSERT_NE(handler, nullptr);
+    for (const auto& blobName : blobNames)
+    {
+        EXPECT_TRUE(handler->canHandleBlob(blobName));
+    }
+}
+
+TEST(VersionHandlerEnumerateTest, VerifyGoodInfoMap)
+{
+    VersionInfoMap test;
+    std::vector<std::string> blobNames{"blob0", "blob1", "blob2", "blob3"};
+    for (const auto& blobName : blobNames)
+    {
+        test.try_emplace(blobName,
+                         VersionInfoPack(blobName,
+                                         std::make_unique<VersionActionPack>(
+                                             CreateTriggerMock()),
+                                         CreateImageMock()));
+    }
+    auto handler = VersionBlobHandler::create(std::move(test));
+    ASSERT_NE(handler, nullptr);
+    EXPECT_THAT(handler->getBlobIds(),
+                ::testing::UnorderedElementsAreArray(blobNames));
+}
+} // namespace ipmi_flash
diff --git a/bmc/version-handler/test/version_close_unittest.cpp b/bmc/version-handler/test/version_close_unittest.cpp
new file mode 100644
index 0000000..68e6add
--- /dev/null
+++ b/bmc/version-handler/test/version_close_unittest.cpp
@@ -0,0 +1,97 @@
+#include "flags.hpp"
+#include "image_mock.hpp"
+#include "triggerable_mock.hpp"
+#include "util.hpp"
+#include "version_handler.hpp"
+
+#include <array>
+#include <string>
+#include <vector>
+
+#include <gtest/gtest.h>
+using ::testing::_;
+using ::testing::Return;
+namespace ipmi_flash
+{
+
+class VersionCloseExpireBlobTest : public ::testing::Test
+{
+  protected:
+    void SetUp() override
+    {
+        VersionInfoMap vim;
+        for (const auto& blobName : blobNames)
+        {
+            auto t = CreateTriggerMock();
+            auto i = CreateImageMock();
+            tm[blobName] = reinterpret_cast<TriggerMock*>(t.get());
+            im[blobName] = reinterpret_cast<ImageHandlerMock*>(i.get());
+            vim.try_emplace(
+                blobName,
+                VersionInfoPack(
+                    blobName, std::make_unique<VersionActionPack>(std::move(t)),
+                    std::move(i)));
+        }
+        h = VersionBlobHandler::create(std::move(vim));
+        ASSERT_NE(h, nullptr);
+        for (const auto& [key, val] : tm)
+        {
+            ON_CALL(*val, trigger()).WillByDefault(Return(true));
+        }
+    }
+    std::unique_ptr<blobs::GenericBlobInterface> h;
+    std::vector<std::string> blobNames{"blob0", "blob1", "blob2", "blob3"};
+    std::unordered_map<std::string, TriggerMock*> tm;
+    std::unordered_map<std::string, ImageHandlerMock*> im;
+};
+
+TEST_F(VersionCloseExpireBlobTest, VerifyOpenThenClose)
+{
+    EXPECT_CALL(*tm.at("blob0"), status())
+        .Times(1)
+        .WillOnce(Return(ActionStatus::success));
+    EXPECT_CALL(*tm.at("blob0"), abort()).Times(0);
+    EXPECT_TRUE(h->open(0, blobs::read, "blob0"));
+    EXPECT_TRUE(h->close(0));
+}
+
+TEST_F(VersionCloseExpireBlobTest, VerifyUnopenedBlobCloseFails)
+{
+    EXPECT_CALL(*tm.at("blob0"), status()).Times(0);
+    EXPECT_CALL(*tm.at("blob0"), abort()).Times(0);
+    EXPECT_FALSE(h->close(0));
+}
+
+TEST_F(VersionCloseExpireBlobTest, VerifyDoubleCloseFails)
+{
+    EXPECT_CALL(*tm.at("blob0"), status())
+        .Times(1)
+        .WillOnce(Return(ActionStatus::success));
+    EXPECT_CALL(*tm.at("blob0"), abort()).Times(0);
+    EXPECT_TRUE(h->open(0, blobs::read, "blob0"));
+    EXPECT_TRUE(h->close(0));
+    EXPECT_FALSE(h->close(0));
+}
+
+TEST_F(VersionCloseExpireBlobTest, VerifyBadSessionNumberCloseFails)
+{
+    EXPECT_CALL(*tm.at("blob0"), status())
+        .Times(1)
+        .WillOnce(Return(ActionStatus::success));
+    EXPECT_CALL(*tm.at("blob0"), abort()).Times(0);
+    EXPECT_TRUE(h->open(0, blobs::read, "blob0"));
+    EXPECT_FALSE(h->close(1));
+    EXPECT_TRUE(h->close(0));
+}
+
+TEST_F(VersionCloseExpireBlobTest, VerifyRunningActionIsAborted)
+{
+    EXPECT_CALL(*tm.at("blob0"), status())
+        .Times(1)
+        .WillOnce(Return(ActionStatus::running));
+    EXPECT_CALL(*tm.at("blob0"), abort()).Times(1);
+    EXPECT_TRUE(h->open(0, blobs::read, "blob0"));
+    EXPECT_TRUE(h->close(0));
+}
+
+} // namespace ipmi_flash
diff --git a/bmc/version-handler/test/version_createhandler_unittest.cpp b/bmc/version-handler/test/version_createhandler_unittest.cpp
new file mode 100644
index 0000000..8454ed0
--- /dev/null
+++ b/bmc/version-handler/test/version_createhandler_unittest.cpp
@@ -0,0 +1,70 @@
+#include "flags.hpp"
+#include "image_mock.hpp"
+#include "triggerable_mock.hpp"
+#include "util.hpp"
+#include "version_handler.hpp"
+
+#include <array>
+#include <string>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+namespace ipmi_flash
+{
+
+TEST(VersionHandlerCanHandleTest, VerifyGoodInfoMapPasses)
+{
+    VersionInfoMap test;
+    std::array blobNames{"blob0", "blob1", "blob2", "blob3"};
+    for (const auto& blobName : blobNames)
+    {
+        test.try_emplace(blobName,
+                         VersionInfoPack(blobName,
+                                         std::make_unique<VersionActionPack>(
+                                             CreateTriggerMock()),
+                                         CreateImageMock()));
+    }
+    auto handler = VersionBlobHandler::create(std::move(test));
+    EXPECT_NE(handler, nullptr);
+}
+
+TEST(VersionCreateHandlerTest, VerifyEmptyInfoMapFails)
+{
+    VersionInfoMap test;
+    auto handler = VersionBlobHandler::create(std::move(test));
+    EXPECT_EQ(handler, nullptr);
+}
+
+TEST(VersionHandlerCanHandleTest, VerifyInfoMapWithNullActionPackFails)
+{
+    VersionInfoMap test;
+    test.try_emplace("blob0",
+                     VersionInfoPack("blob0", nullptr, CreateImageMock()));
+    auto handler = VersionBlobHandler::create(std::move(test));
+    EXPECT_EQ(handler, nullptr);
+}
+
+TEST(VersionHandlerCanHandleTest, VerifyInfoMapWithNullTriggerableActionFails)
+{
+    VersionInfoMap test;
+    test.try_emplace(
+        "blob0",
+        VersionInfoPack("blob0", std::make_unique<VersionActionPack>(nullptr),
+                        CreateImageMock()));
+    auto handler = VersionBlobHandler::create(std::move(test));
+    EXPECT_EQ(handler, nullptr);
+}
+
+TEST(VersionHandlerCanHandleTest, VerifyInfoMapWithNullImageHandlerFails)
+{
+    VersionInfoMap test;
+    test.try_emplace(
+        "blob0",
+        VersionInfoPack(
+            "blob0", std::make_unique<VersionActionPack>(CreateTriggerMock()),
+            nullptr));
+    auto handler = VersionBlobHandler::create(std::move(test));
+    EXPECT_EQ(handler, nullptr);
+}
+} // namespace ipmi_flash
diff --git a/bmc/version-handler/test/version_handler_unittest.cpp b/bmc/version-handler/test/version_handler_unittest.cpp
new file mode 100644
index 0000000..f27f033
--- /dev/null
+++ b/bmc/version-handler/test/version_handler_unittest.cpp
@@ -0,0 +1,267 @@
+#include "version_handler.hpp"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+namespace ipmi_flash
+{
+namespace
+{
+using ::testing::IsEmpty;
+
+using json = nlohmann::json;
+
+TEST(VersionHandlerCreateTest, VerifyAllBlobHandlersPresent)
+{
+
+    // Need a triggerable mock
+    VersionInfoMap test;
+    test.try_emplace("blob0", "blob0",
+                     std::make_unique<VersionActionPackMock>(),
+                     std::make_unique<ImageHandlerMock>());
+    ASSERT_THAT(h, ::testing::SizeIs(1));
+    EXPECT_THAT(h[0].blobId, "/version/sink_seq");
+    EXPECT_FALSE(h[0].actions == nullptr);
+    EXPECT_FALSE(h[0].handler == nullptr);
+}
+
+TEST(VersionJsonTest, ValidConfigurationVersionBlobName)
+{
+    auto h = VersionHandlersBuilder().buildHandlerFromJson(j2);
+    ASSERT_THAT(h, ::testing::SizeIs(1));
+    EXPECT_THAT(h[0].blobId, "/version/sink_seq");
+    EXPECT_FALSE(h[0].actions == nullptr);
+    EXPECT_FALSE(h[0].handler == nullptr);
+}
+
+TEST(VersionJsonTest, MissingHandlerType)
+{
+    auto j2 = R"(
+        [{
+            "blob" : "/flash/image",
+            "version":{
+                "handler": {
+                   "path" : "/tmp/version_info"
+                 },
+                "actions": {
+                  "open" : {
+                  "type" : "systemd",
+                  "unit" : "absolute"}
+                 }
+            }
+         }]
+    )"_json;
+    EXPECT_THAT(VersionHandlersBuilder().buildHandlerFromJson(j2), IsEmpty());
+}
+
+TEST(VersionJsonTest, BadBlobName)
+{
+    auto j2 = R"(
+        [{
+            "blob" : "/bad/image",
+            "version":{
+                "handler": {
+                   "type" : "file",
+                   "path" : "/tmp/version_info"
+                 },
+                "actions": {
+                  "open" : {
+                  "type" : "systemd",
+                  "unit" : "absolute"}
+                 }
+            }
+         }]
+    )"_json;
+    EXPECT_THAT(VersionHandlersBuilder().buildHandlerFromJson(j2), IsEmpty());
+}
+
+TEST(VersionJsonTest, MissingActions)
+{
+    auto j2 = R"(
+        [{
+            "blob" : "/flash/image",
+            "version":{
+                "handler": {
+                   "type" : "file",
+                   "path" : "/tmp/version_info"
+                 }
+            }
+         }]
+    )"_json;
+    EXPECT_THAT(VersionHandlersBuilder().buildHandlerFromJson(j2), IsEmpty());
+}
+
+TEST(VersionJsonTest, MissingOpenAction)
+{
+    auto j2 = R"(
+        [{
+            "blob" : "/flash/image",
+            "version":{
+                "handler": {
+                   "type" : "file",
+                   "path" : "/tmp/version_info"
+                 },
+                "actions": {}
+            }
+         }]
+    )"_json;
+    EXPECT_THAT(VersionHandlersBuilder().buildHandlerFromJson(j2), IsEmpty());
+}
+
+TEST(VersionJsonTest, OneInvalidTwoValidSucceeds)
+{
+    auto j2 = R"(
+        [{
+            "blob" : "/flash/sink_seq0",
+            "version":{
+                "handler": {
+                   "type" : "file",
+                   "path" : "/tmp/version_info"
+                 },
+                "actions":{
+                    "open" :{
+                    "type" : "systemd",
+                    "unit" : "absolute"
+                    }
+                 }
+            }
+         },
+         {
+            "blob" : "/version/sink_seq1",
+            "version":{
+                "handler": {
+                   "type" : "file",
+                   "path" : "/tmp/version_info"
+                 },
+                "actions":{
+                    "open" :{
+                    "type" : "systemd",
+                    "unit" : "absolute"
+                    }
+                 }
+            }
+         },
+         {
+            "blob" : "/bad/sink_seq",
+            "version":{
+                "handler": {
+                   "type" : "file",
+                   "path" : "/tmp/version_info"
+                 },
+                "actions":{
+                    "open" :{
+                    "type" : "systemd",
+                    "unit" : "absolute"
+                    }
+                 }
+            }
+         }
+         ]
+    )"_json;
+    auto h = VersionHandlersBuilder().buildHandlerFromJson(j2);
+    ASSERT_THAT(h, ::testing::SizeIs(2));
+    EXPECT_THAT(h[0].blobId, "/version/sink_seq0");
+    EXPECT_THAT(h[1].blobId, "/version/sink_seq1");
+}
+
+TEST(VersionJsonTest, BlobNameIsTooShort)
+{
+    auto j2 = R"(
+        [{
+            "blob" : "/flash/",
+            "version":{
+                "handler": {
+                   "type" : "file",
+                   "path" : "/tmp/version_info"
+                 },
+                "actions":{
+                    "open" :{
+                    "type" : "systemd",
+                    "unit" : "absolute"
+                    }
+                 }
+            }
+         }]
+    )"_json;
+    EXPECT_THAT(VersionHandlersBuilder().buildHandlerFromJson(j2), IsEmpty());
+}
+
+TEST(VersionJsonTest, OpenSkipAction)
+{
+    auto j2 = R"(
+        [{
+            "blob" : "/flash/sink_seqs",
+            "version":{
+                "handler": {
+                   "type" : "file",
+                   "path" : "/tmp/version_info"
+                 },
+                "actions":{
+                    "open" :{
+                    "type" : "skip"
+                    }
+                 }
+            }
+         }]
+    )"_json;
+    auto h = VersionHandlersBuilder().buildHandlerFromJson(j2);
+    EXPECT_THAT(h, ::testing::SizeIs(1));
+    EXPECT_TRUE(h[0].blobId == "/version/sink_seqs");
+    ASSERT_FALSE(h[0].actions == nullptr);
+    EXPECT_FALSE(h[0].actions->onOpen == nullptr);
+}
+
+TEST(VersionJsonTest, OpenActionsWithDifferentModes)
+{
+    auto j2 = R"(
+        [{
+            "blob" : "/flash/blob1",
+            "version":{
+                "handler": {
+                   "type" : "file",
+                   "path" : "/tmp/version_info"
+                 },
+                "actions":{
+                    "open" :{
+                    "type" : "systemd",
+                    "unit" : "absolute",
+                    "mode" : "replace-nope"
+                    }
+                 }
+            }
+         },
+         {
+            "blob" : "/flash/blob2",
+            "version":{
+                "handler": {
+                   "type" : "file",
+                   "path" : "/tmp/version_info"
+                 },
+                "actions":{
+                    "open" :{
+                    "type" : "systemd",
+                    "unit" : "absolute",
+                    "mode" : "replace-fake"
+                    }
+                 }
+            }
+         }
+         ]
+    )"_json;
+    auto h = VersionHandlersBuilder().buildHandlerFromJson(j2);
+    ASSERT_THAT(h, ::testing::SizeIs(2));
+
+    EXPECT_FALSE(h[0].handler == nullptr);
+    EXPECT_FALSE(h[0].actions == nullptr);
+    EXPECT_THAT(h[0].blobId, "/version/blob1");
+    auto onOpen0 = reinterpret_cast<SystemdNoFile*>(h[0].actions->onOpen.get());
+    EXPECT_THAT(onOpen0->getMode(), "replace-nope");
+
+    EXPECT_FALSE(h[1].handler == nullptr);
+    EXPECT_FALSE(h[1].actions == nullptr);
+    EXPECT_THAT(h[1].blobId, "/version/blob2");
+    auto onOpen1 = reinterpret_cast<SystemdNoFile*>(h[1].actions->onOpen.get());
+    EXPECT_THAT(onOpen1->getMode(), "replace-fake");
+}
+} // namespace
+} // namespace ipmi_flash
diff --git a/bmc/version-handler/test/version_open_unittest.cpp b/bmc/version-handler/test/version_open_unittest.cpp
new file mode 100644
index 0000000..7e287e5
--- /dev/null
+++ b/bmc/version-handler/test/version_open_unittest.cpp
@@ -0,0 +1,124 @@
+#include "flags.hpp"
+#include "image_mock.hpp"
+#include "triggerable_mock.hpp"
+#include "util.hpp"
+#include "version_handler.hpp"
+
+#include <array>
+#include <string>
+#include <vector>
+
+#include <gtest/gtest.h>
+using ::testing::_;
+using ::testing::Return;
+namespace ipmi_flash
+{
+
+class VersionOpenBlobTest : public ::testing::Test
+{
+  protected:
+    void SetUp() override
+    {
+        VersionInfoMap vim;
+        for (const auto& blobName : blobNames)
+        {
+            auto t = CreateTriggerMock();
+            auto i = CreateImageMock();
+            tm[blobName] = reinterpret_cast<TriggerMock*>(t.get());
+            im[blobName] = reinterpret_cast<ImageHandlerMock*>(i.get());
+            vim.try_emplace(
+                blobName,
+                VersionInfoPack(
+                    blobName, std::make_unique<VersionActionPack>(std::move(t)),
+                    std::move(i)));
+        }
+        h = VersionBlobHandler::create(std::move(vim));
+        ASSERT_NE(h, nullptr);
+        for (const auto& [key, val] : tm)
+        {
+            /* by default no action triggers expected to be called */
+            EXPECT_CALL(*val, trigger()).Times(0);
+        }
+        for (const auto& [key, val] : im)
+        {
+            /* by default no image handler open is expected to be called */
+            EXPECT_CALL(*val, open(_, _)).Times(0);
+        }
+    }
+    std::unique_ptr<blobs::GenericBlobInterface> h;
+    std::vector<std::string> blobNames{"blob0", "blob1", "blob2", "blob3"};
+    std::unordered_map<std::string, TriggerMock*> tm;
+    std::unordered_map<std::string, ImageHandlerMock*> im;
+    const std::uint16_t defaultSessionNumber{0};
+};
+
+TEST_F(VersionOpenBlobTest, VerifySingleBlobOpen)
+{
+    EXPECT_CALL(*tm.at("blob0"), trigger()).Times(1).WillOnce(Return(true));
+    EXPECT_TRUE(h->open(defaultSessionNumber, blobs::read, "blob0"));
+}
+
+TEST_F(VersionOpenBlobTest, VerifyMultipleBlobOpens)
+{
+    for (const auto& [key, val] : tm)
+    {
+        /* set the expectation that every onOpen will be triggered */
+        EXPECT_CALL(*val, trigger()).Times(1).WillOnce(Return(true));
+    }
+    int i{defaultSessionNumber};
+    for (const auto& blob : blobNames)
+    {
+        EXPECT_TRUE(h->open(i++, blobs::read, blob));
+    }
+}
+
+TEST_F(VersionOpenBlobTest, VerifyOpenAfterClose)
+{
+    EXPECT_CALL(*tm.at("blob0"), trigger())
+        .Times(2)
+        .WillRepeatedly(Return(true));
+    EXPECT_TRUE(h->open(defaultSessionNumber, blobs::read, "blob0"));
+    EXPECT_TRUE(h->close(defaultSessionNumber));
+    EXPECT_TRUE(h->open(defaultSessionNumber, blobs::read, "blob0"));
+}
+
+TEST_F(VersionOpenBlobTest, VerifyDuplicateSessionNumberFails)
+{
+    EXPECT_CALL(*tm.at("blob0"), trigger()).Times(1).WillOnce(Return(true));
+    EXPECT_CALL(*tm.at("blob1"), trigger()).Times(1).WillOnce(Return(true));
+    EXPECT_TRUE(h->open(defaultSessionNumber, blobs::read, "blob1"));
+    /* the duplicate session number of 0
+     *  should cause a failure for the open of a different blob
+     */
+    EXPECT_FALSE(h->open(defaultSessionNumber, blobs::read, "blob0"));
+    /* open after fail due to seq number works */
+    EXPECT_TRUE(h->open(defaultSessionNumber + 1, blobs::read, "blob0"));
+}
+
+TEST_F(VersionOpenBlobTest, VerifyDoubleOpenFails)
+{
+    EXPECT_CALL(*tm.at("blob1"), trigger())
+        .Times(1)
+        .WillRepeatedly(Return(true));
+    EXPECT_TRUE(h->open(0, blobs::read, "blob1"));
+    EXPECT_FALSE(h->open(2, blobs::read, "blob1"));
+}
+
+TEST_F(VersionOpenBlobTest, VerifyFailedTriggerFails)
+{
+    EXPECT_CALL(*tm.at("blob1"), trigger())
+        .Times(2)
+        .WillOnce(Return(false))
+        .WillOnce(Return(true));
+    EXPECT_FALSE(h->open(0, blobs::read, "blob1"));
+    EXPECT_TRUE(h->open(0, blobs::read, "blob1"));
+}
+
+TEST_F(VersionOpenBlobTest, VerifyUnsupportedOpenFlagsFails)
+{
+    EXPECT_CALL(*tm.at("blob1"), trigger()).Times(1).WillOnce(Return(true));
+    EXPECT_FALSE(h->open(0, blobs::write, "blob1"));
+    EXPECT_TRUE(h->open(0, blobs::read, "blob1"));
+}
+
+} // namespace ipmi_flash
diff --git a/bmc/version-handler/test/version_read_unittest.cpp b/bmc/version-handler/test/version_read_unittest.cpp
new file mode 100644
index 0000000..2f15e03
--- /dev/null
+++ b/bmc/version-handler/test/version_read_unittest.cpp
@@ -0,0 +1,128 @@
+#include "flags.hpp"
+#include "image_mock.hpp"
+#include "triggerable_mock.hpp"
+#include "util.hpp"
+#include "version_handler.hpp"
+
+#include <array>
+#include <string>
+#include <vector>
+
+#include <gtest/gtest.h>
+using ::testing::_;
+using ::testing::IsEmpty;
+using ::testing::Return;
+namespace ipmi_flash
+{
+
+class VersionReadBlobTest : public ::testing::Test
+{
+  protected:
+    void SetUp() override
+    {
+        VersionInfoMap vim;
+        for (const auto& blobName : blobNames)
+        {
+            auto t = CreateTriggerMock();
+            auto i = CreateImageMock();
+            tm[blobName] = reinterpret_cast<TriggerMock*>(t.get());
+            im[blobName] = reinterpret_cast<ImageHandlerMock*>(i.get());
+            vim.try_emplace(
+                blobName,
+                VersionInfoPack(
+                    blobName, std::make_unique<VersionActionPack>(std::move(t)),
+                    std::move(i)));
+        }
+        h = VersionBlobHandler::create(std::move(vim));
+        ASSERT_NE(h, nullptr);
+        for (const auto& [key, val] : tm)
+        {
+            ON_CALL(*val, trigger()).WillByDefault(Return(true));
+        }
+    }
+    std::unique_ptr<blobs::GenericBlobInterface> h;
+    std::vector<std::string> blobNames{"blob0", "blob1", "blob2", "blob3"};
+    std::unordered_map<std::string, TriggerMock*> tm;
+    std::unordered_map<std::string, ImageHandlerMock*> im;
+    const std::uint16_t defaultSessionNumber{200};
+    std::vector<uint8_t> vector1{0xDE, 0xAD, 0xBE, 0xEF,
+                                 0xBA, 0xDF, 0xEE, 0x0D};
+};
+
+TEST_F(VersionReadBlobTest, VerifyValidRead)
+{
+    EXPECT_CALL(*tm.at("blob0"), status())
+        .Times(2)
+        .WillRepeatedly(Return(ActionStatus::success));
+    EXPECT_TRUE(h->open(defaultSessionNumber, blobs::read, "blob0"));
+    /* file path gets bound to file_handler on creation so path parameter
+     * doesn't actually matter
+     */
+    EXPECT_CALL(*im.at("blob0"), open(_, std::ios::in))
+        .Times(2)
+        .WillRepeatedly(Return(true));
+    EXPECT_CALL(*im.at("blob0"), read(0, 10)).WillOnce(Return(vector1));
+    EXPECT_CALL(*im.at("blob0"), read(2, 10)).WillOnce(Return(vector1));
+    EXPECT_CALL(*im.at("blob0"), close()).Times(2);
+
+    EXPECT_EQ(h->read(defaultSessionNumber, 0, 10), vector1);
+    EXPECT_EQ(h->read(defaultSessionNumber, 2, 10), vector1);
+}
+
+TEST_F(VersionReadBlobTest, VerifyUnopenedReadFails)
+{
+    EXPECT_CALL(*tm.at("blob0"), status()).Times(0);
+    EXPECT_CALL(*im.at("blob0"), open(_, _)).Times(0);
+    EXPECT_CALL(*im.at("blob0"), read(_, _)).Times(0);
+
+    EXPECT_THAT(h->read(defaultSessionNumber, 0, 10), IsEmpty());
+}
+
+TEST_F(VersionReadBlobTest, VerifyTriggerFailureReadFails)
+{
+    EXPECT_CALL(*tm.at("blob0"), status())
+        .Times(1)
+        .WillOnce(Return(ActionStatus::failed));
+    EXPECT_CALL(*im.at("blob0"), open(_, _)).Times(0);
+    EXPECT_TRUE(h->open(defaultSessionNumber, blobs::read, "blob0"));
+    EXPECT_THAT(h->read(defaultSessionNumber, 0, 10), IsEmpty());
+}
+
+TEST_F(VersionReadBlobTest, VerifyReadFailsOnFileReadFailure)
+{
+    EXPECT_CALL(*tm.at("blob0"), status())
+        .Times(1)
+        .WillOnce(Return(ActionStatus::success));
+    /* file path gets bound to file_handler on creation so path parameter
+     * doesn't actually matter
+     */
+    EXPECT_CALL(*im.at("blob0"), open(_, std::ios::in))
+        .Times(1)
+        .WillOnce(Return(true));
+    EXPECT_CALL(*im.at("blob0"), read(_, _))
+        .Times(1)
+        .WillOnce(Return(std::nullopt));
+    EXPECT_CALL(*im.at("blob0"), close()).Times(1);
+
+    EXPECT_TRUE(h->open(defaultSessionNumber, blobs::read, "blob0"));
+    EXPECT_THAT(h->read(defaultSessionNumber, 0, 10), IsEmpty());
+}
+
+TEST_F(VersionReadBlobTest, VerifyReadFailsOnFileOpenFailure)
+{
+    /* first call to trigger status fails, second succeeds */
+    EXPECT_CALL(*tm.at("blob0"), status())
+        .Times(1)
+        .WillOnce(Return(ActionStatus::success));
+    /* file path gets bound to file_handler on creation so path parameter
+     * doesn't actually matter
+     */
+    EXPECT_CALL(*im.at("blob0"), open(_, std::ios::in))
+        .Times(1)
+        .WillOnce(Return(false));
+
+    EXPECT_TRUE(h->open(defaultSessionNumber, blobs::read, "blob0"));
+    EXPECT_THAT(h->read(defaultSessionNumber, 0, 10), IsEmpty());
+}
+
+} // namespace ipmi_flash
diff --git a/bmc/version-handler/version_handler.cpp b/bmc/version-handler/version_handler.cpp
new file mode 100644
index 0000000..75ba940
--- /dev/null
+++ b/bmc/version-handler/version_handler.cpp
@@ -0,0 +1,182 @@
+#include "version_handler.hpp"
+
+#include <stdexcept>
+namespace ipmi_flash
+{
+std::unique_ptr<blobs::GenericBlobInterface>
+    VersionBlobHandler::create(VersionInfoMap&& versionMap)
+{
+    if (versionMap.empty())
+    {
+        return nullptr;
+    }
+    std::vector<std::string> blobList;
+    for (const auto& [key, val] : versionMap)
+    {
+        if (val.blobId != key || val.actionPack == nullptr ||
+            val.imageHandler == nullptr || val.actionPack->onOpen == nullptr)
+        {
+            return nullptr;
+        }
+        blobList.push_back(key);
+    }
+    return std::make_unique<VersionBlobHandler>(std::move(blobList),
+                                                std::move(versionMap));
+}
+
+bool VersionBlobHandler::canHandleBlob(const std::string& path)
+{
+    return (std::find(blobIds.begin(), blobIds.end(), path) != blobIds.end());
+}
+
+std::vector<std::string> VersionBlobHandler::getBlobIds()
+{
+    return blobIds;
+}
+
+/**
+ * deleteBlob - does nothing, always fails
+ */
+bool VersionBlobHandler::deleteBlob(const std::string& path)
+{
+    return false;
+}
+
+bool VersionBlobHandler::stat(const std::string& path, blobs::BlobMeta* meta)
+{
+    // TODO: stat should return the blob state and in the meta data information
+    // on whether a read is successful should be contained
+    // do things like determine if systemd target is triggered
+    // then check if file can be opened for read
+    return false; /* not yet implemented */
+}
+
+bool VersionBlobHandler::open(uint16_t session, uint16_t flags,
+                              const std::string& path)
+{
+    if (sessionToBlob.insert({session, path}).second == false)
+    {
+        fprintf(stderr, "open %s fail: session number %d assigned to %s\n",
+                path.c_str(), session, sessionToBlob.at(session).c_str());
+        return false;
+    }
+    /* only reads are supported, check if blob is handled and make sure
+     * the blob isn't already opened
+     */
+    if (flags != blobs::read)
+    {
+        fprintf(stderr, "open %s fail: unsupported flags(0x%04X.)\n",
+                path.c_str(), flags);
+        cleanup(session);
+        return false;
+    }
+    if (!canHandleBlob(path))
+    {
+        fprintf(stderr, "open %s fail: unrecognized blob\n", path.c_str());
+        cleanup(session);
+        return false;
+    }
+
+    try
+    {
+        auto& v = versionInfoMap.at(path);
+        if (v.blobState == blobs::StateFlags::open_read)
+        {
+            cleanup(session);
+            fprintf(stderr, "open %s fail: blob already opened for read\n",
+                    path.c_str());
+            return false;
+        }
+        if (v.actionPack->onOpen->trigger() == false)
+        {
+            fprintf(stderr, "open %s fail: onOpen trigger failed\n",
+                    path.c_str());
+            cleanup(session);
+            return false;
+        }
+        v.blobState = blobs::StateFlags::open_read;
+        return true;
+    }
+    catch (const std::out_of_range& e)
+    {
+        fprintf(stderr, "open %s fail, exception:%s\n", path.c_str(), e.what());
+        cleanup(session);
+        return false;
+    }
+}
+
+std::vector<uint8_t> VersionBlobHandler::read(uint16_t session, uint32_t offset,
+                                              uint32_t requestedSize)
+{
+    std::string* blobName;
+    VersionInfoPack* pack;
+    try
+    {
+        blobName = &sessionToBlob.at(session);
+        pack = &versionInfoMap.at(*blobName);
+    }
+    catch (const std::out_of_range& e)
+    {
+        return {};
+    }
+    /* onOpen trigger must be successful, otherwise potential
+     * for stale data to be read
+     */
+    if (pack->actionPack->onOpen->status() != ActionStatus::success)
+    {
+        fprintf(stderr, "read failed: onOpen trigger not successful\n");
+        return {};
+    }
+    if (!pack->imageHandler->open("don't care", std::ios::in))
+    {
+        fprintf(stderr, "read failed: file open unsuccessful blob=%s\n",
+                blobName->c_str());
+        return {};
+    }
+    auto d = pack->imageHandler->read(offset, requestedSize);
+    if (!d)
+    {
+        fprintf(stderr, "read failed: unable to read file for blob %s\n",
+                blobName->c_str());
+        pack->imageHandler->close();
+        return {};
+    }
+    pack->imageHandler->close();
+    return *d;
+}
+
+bool VersionBlobHandler::close(uint16_t session)
+{
+    return cleanup(session);
+}
+
+bool VersionBlobHandler::stat(uint16_t session, blobs::BlobMeta* meta)
+{
+    return false;
+}
+
+bool VersionBlobHandler::expire(uint16_t session)
+{
+    return cleanup(session);
+}
+
+bool VersionBlobHandler::cleanup(uint16_t session)
+{
+    try
+    {
+        const auto& blobName = sessionToBlob.at(session);
+        auto& pack = versionInfoMap.at(blobName);
+        if (pack.actionPack->onOpen->status() == ActionStatus::running)
+        {
+            pack.actionPack->onOpen->abort();
+        }
+        pack.blobState = static_cast<blobs::StateFlags>(0);
+        sessionToBlob.erase(session);
+        return true;
+    }
+    catch (const std::out_of_range& e)
+    {
+        return false;
+    }
+}
+} // namespace ipmi_flash
diff --git a/bmc/version-handler/version_handler.hpp b/bmc/version-handler/version_handler.hpp
index aefd3c4..336a869 100644
--- a/bmc/version-handler/version_handler.hpp
+++ b/bmc/version-handler/version_handler.hpp
@@ -1,10 +1,18 @@
 #pragma once
 #include "buildjson.hpp"
+#include "image_handler.hpp"
 #include "status.hpp"
+#include "util.hpp"
 
 #include <blobs-ipmid/blobs.hpp>
 
+#include <algorithm>
+#include <cstdint>
+#include <map>
 #include <memory>
+#include <string>
+#include <unordered_map>
+#include <vector>
 namespace ipmi_flash
 {
 struct VersionActionPack
@@ -16,4 +24,95 @@
     /** Only file operation action supported currently */
     std::unique_ptr<TriggerableActionInterface> onOpen;
 };
+
+/*
+ * All the information associated with a version blob
+ */
+struct VersionInfoPack
+{
+  public:
+    VersionInfoPack(const std::string& blobId,
+                    std::unique_ptr<VersionActionPack> actionPackIn,
+                    std::unique_ptr<ImageHandlerInterface> imageHandler) :
+        blobId(blobId),
+        actionPack(std::move(actionPackIn)),
+        imageHandler(std::move(imageHandler)),
+        blobState(static_cast<blobs::StateFlags>(0)){};
+    VersionInfoPack() = default;
+
+    std::string blobId;
+    std::unique_ptr<VersionActionPack> actionPack;
+    std::unique_ptr<ImageHandlerInterface> imageHandler;
+    blobs::StateFlags blobState;
+};
+
+/* convenience alias: the key (std::string) is blobId, same as
+ * VersionInfoPack.blobId */
+using VersionInfoMap = std::unordered_map<std::string, VersionInfoPack>;
+
+class VersionBlobHandler : public blobs::GenericBlobInterface
+{
+  public:
+    /**
+     * Factory to create a BlobHandler for use by phosphor-ipmi-blobs
+     *
+     * @param[in] versionMap - blob names to VersionInfoPack which contains
+     * triggers, file handlers, state and blobID.
+     *
+     * @returns a unique_ptr to a GenericBlobInterface which is used by
+     * phosphor-ipmi-blobs. The underlying implementation (VersionBlobHandler)
+     * implements all the blob operations for the blobs owned by
+     * VersionBlobHandler.
+     */
+    static std::unique_ptr<blobs::GenericBlobInterface>
+        create(VersionInfoMap&& versionMap);
+    /**
+     * Create a VersionBlobHandler.
+     *
+     * @param[in] blobs - list of blobs_ids to support
+     * @param[in] actions - a map of blobId to VersionInfoPack
+     */
+    VersionBlobHandler(std::vector<std::string>&& blobs,
+                       VersionInfoMap&& handlerMap) :
+        blobIds(blobs),
+        versionInfoMap(std::move(handlerMap))
+    {}
+    ~VersionBlobHandler() = default;
+    VersionBlobHandler(const VersionBlobHandler&) = delete;
+    VersionBlobHandler& operator=(const VersionBlobHandler&) = delete;
+    VersionBlobHandler(VersionBlobHandler&&) = default;
+    VersionBlobHandler& operator=(VersionBlobHandler&&) = default;
+
+    bool canHandleBlob(const std::string& path) override;
+    std::vector<std::string> getBlobIds() override;
+    bool deleteBlob(const std::string& path) override;
+    bool stat(const std::string&, blobs::BlobMeta* meta) override;
+    bool open(uint16_t session, uint16_t flags,
+              const std::string& path) override;
+    std::vector<uint8_t> read(uint16_t session, uint32_t offset,
+                              uint32_t requestedSize) override;
+    bool write(uint16_t session, uint32_t offset,
+               const std::vector<uint8_t>& data) override
+    {
+        return false; /* not supported */
+    };
+    bool writeMeta(uint16_t session, uint32_t offset,
+                   const std::vector<uint8_t>& data) override
+    {
+        return false; /* not supported */
+    }
+    bool commit(uint16_t session, const std::vector<uint8_t>& data) override
+    {
+        return false; // not supported
+    }
+    bool close(uint16_t session) override;
+    bool stat(uint16_t session, blobs::BlobMeta* meta) override;
+    bool expire(uint16_t session) override;
+    bool cleanup(uint16_t session);
+
+  private:
+    std::vector<std::string> blobIds;
+    VersionInfoMap versionInfoMap;
+    std::unordered_map<uint16_t, std::string> sessionToBlob;
+};
 } // namespace ipmi_flash