1 /* 2 * Copyright 2019 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 #include "buildjson.hpp" 17 18 #include "file_handler.hpp" 19 #include "fs.hpp" 20 21 #include <nlohmann/json.hpp> 22 #include <sdbusplus/bus.hpp> 23 24 #include <algorithm> 25 #include <cstdio> 26 #include <exception> 27 #include <fstream> 28 #include <string> 29 #include <vector> 30 31 namespace ipmi_flash 32 { 33 34 std::unique_ptr<TriggerableActionInterface> 35 buildFileSystemd(const nlohmann::json& data) 36 { 37 /* This type of action requires a path and unit, and optionally a mode. */ 38 const auto& path = data.at("path"); 39 const auto& unit = data.at("unit"); 40 41 /* the mode parameter is optional. */ 42 std::string systemdMode = "replace"; 43 const auto& mode = data.find("mode"); 44 if (mode != data.end()) 45 { 46 systemdMode = data.at("mode").get<std::string>(); 47 } 48 49 return SystemdWithStatusFile::CreateSystemdWithStatusFile( 50 sdbusplus::bus::new_default(), path, unit, systemdMode); 51 } 52 53 std::unique_ptr<TriggerableActionInterface> 54 buildSystemd(const nlohmann::json& data) 55 { 56 /* This type of action requires a unit, and optionally a mode. */ 57 const auto& unit = data.at("unit"); 58 59 /* the mode parameter is optional. */ 60 std::string systemdMode = "replace"; 61 const auto& mode = data.find("mode"); 62 if (mode != data.end()) 63 { 64 systemdMode = data.at("mode").get<std::string>(); 65 } 66 67 return SystemdNoFile::CreateSystemdNoFile(sdbusplus::bus::new_default(), 68 unit, systemdMode); 69 } 70 71 template <typename T> 72 std::vector<HandlerConfig<T>> 73 HandlersBuilderIfc<T>::buildHandlerConfigs(const std::string& directory) 74 { 75 std::vector<HandlerConfig<T>> output; 76 77 std::vector<std::string> jsonPaths = GetJsonList(directory); 78 79 for (const auto& path : jsonPaths) 80 { 81 std::ifstream jsonFile(path); 82 if (!jsonFile.is_open()) 83 { 84 std::fprintf(stderr, "Unable to open json file: %s\n", 85 path.c_str()); 86 continue; 87 } 88 89 auto data = nlohmann::json::parse(jsonFile, nullptr, false); 90 if (data.is_discarded()) 91 { 92 std::fprintf(stderr, "Parsing json failed: %s\n", path.c_str()); 93 } 94 95 std::vector<HandlerConfig<T>> configs = buildHandlerFromJson(data); 96 std::move(configs.begin(), configs.end(), std::back_inserter(output)); 97 } 98 return output; 99 } 100 101 } // namespace ipmi_flash 102