blob: b5d7cf20ae90f5f92752220c8775f0d6ec3087c3 [file] [log] [blame]
Vernon Maueryba2c0832020-07-15 10:02:38 -07001/*
2// Copyright (c) 2018 Intel Corporation
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 "srvcfg_manager.hpp"
17
18#include <boost/algorithm/string/replace.hpp>
19#include <cereal/archives/json.hpp>
20#include <cereal/types/tuple.hpp>
21#include <cereal/types/unordered_map.hpp>
22#include <sdbusplus/bus/match.hpp>
23
24#include <filesystem>
25#include <fstream>
26
27std::unique_ptr<boost::asio::steady_timer> timer = nullptr;
28std::unique_ptr<boost::asio::steady_timer> initTimer = nullptr;
29std::map<std::string, std::shared_ptr<phosphor::service::ServiceConfig>>
30 srvMgrObjects;
31static bool unitQueryStarted = false;
32
33static constexpr const char* srvCfgMgrFile = "/etc/srvcfg-mgr.json";
George Liuf2744892022-01-05 17:54:45 +080034static constexpr const char* tmpFileBad = "/tmp/srvcfg-mgr.json.bad";
Vernon Maueryba2c0832020-07-15 10:02:38 -070035
36// Base service name list. All instance of these services and
37// units(service/socket) will be managed by this daemon.
George Liua19b5092021-05-24 15:54:02 +080038static std::array<std::string, 6> serviceNames = {
39 "phosphor-ipmi-net", "bmcweb", "phosphor-ipmi-kcs",
40 "start-ipkvm", "obmc-console", "dropbear"};
Vernon Maueryba2c0832020-07-15 10:02:38 -070041
42enum class UnitType
43{
44 service,
45 socket,
46 target,
47 device,
48 invalid
49};
50
51using MonitorListMap =
52 std::unordered_map<std::string, std::tuple<std::string, std::string,
53 std::string, std::string>>;
54MonitorListMap unitsToMonitor;
55
56enum class monitorElement
57{
58 unitName,
59 instanceName,
60 serviceObjPath,
61 socketObjPath
62};
63
64std::tuple<std::string, UnitType, std::string>
65 getUnitNameTypeAndInstance(const std::string& fullUnitName)
66{
67 UnitType type = UnitType::invalid;
68 std::string instanceName;
69 std::string unitName;
70 // get service type
71 auto typePos = fullUnitName.rfind(".");
72 if (typePos != std::string::npos)
73 {
74 const auto& typeStr = fullUnitName.substr(typePos + 1);
75 // Ignore types other than service and socket
76 if (typeStr == "service")
77 {
78 type = UnitType::service;
79 }
80 else if (typeStr == "socket")
81 {
82 type = UnitType::socket;
83 }
84 // get instance name if available
85 auto instancePos = fullUnitName.rfind("@");
86 if (instancePos != std::string::npos)
87 {
88 instanceName =
89 fullUnitName.substr(instancePos + 1, typePos - instancePos - 1);
90 unitName = fullUnitName.substr(0, instancePos);
91 }
92 else
93 {
94 unitName = fullUnitName.substr(0, typePos);
95 }
96 }
97 return std::make_tuple(unitName, type, instanceName);
98}
99
100static inline void
101 handleListUnitsResponse(sdbusplus::asio::object_server& server,
102 std::shared_ptr<sdbusplus::asio::connection>& conn,
103 boost::system::error_code /*ec*/,
104 const std::vector<ListUnitsType>& listUnits)
105{
106 // Loop through all units, and mark all units, which has to be
107 // managed, irrespective of instance name.
108 for (const auto& unit : listUnits)
109 {
110 const auto& fullUnitName =
111 std::get<static_cast<int>(ListUnitElements::name)>(unit);
112 auto [unitName, type, instanceName] =
113 getUnitNameTypeAndInstance(fullUnitName);
114 if (std::find(serviceNames.begin(), serviceNames.end(), unitName) !=
115 serviceNames.end())
116 {
117 std::string instantiatedUnitName =
118 unitName + addInstanceName(instanceName, "_40");
119 boost::replace_all(instantiatedUnitName, "-", "_2d");
120 const sdbusplus::message::object_path& objectPath =
121 std::get<static_cast<int>(ListUnitElements::objectPath)>(unit);
122 // Group the service & socket units togther.. Same services
123 // are managed together.
124 auto it = unitsToMonitor.find(instantiatedUnitName);
125 if (it != unitsToMonitor.end())
126 {
127 auto& value = it->second;
128 if (type == UnitType::service)
129 {
Vernon Maueryba2c0832020-07-15 10:02:38 -0700130 std::get<static_cast<int>(monitorElement::serviceObjPath)>(
Jiaqing Zhaoaa41e672021-12-14 15:14:30 +0800131 value) = objectPath.str;
Vernon Maueryba2c0832020-07-15 10:02:38 -0700132 }
133 else if (type == UnitType::socket)
134 {
135 std::get<static_cast<int>(monitorElement::socketObjPath)>(
Jiaqing Zhaoaa41e672021-12-14 15:14:30 +0800136 value) = objectPath.str;
Vernon Maueryba2c0832020-07-15 10:02:38 -0700137 }
Jiaqing Zhaoaa41e672021-12-14 15:14:30 +0800138 continue;
Vernon Maueryba2c0832020-07-15 10:02:38 -0700139 }
Jiaqing Zhaoaa41e672021-12-14 15:14:30 +0800140 // If not grouped with any existing entry, create a new one
Vernon Maueryba2c0832020-07-15 10:02:38 -0700141 if (type == UnitType::service)
142 {
143 unitsToMonitor.emplace(instantiatedUnitName,
144 std::make_tuple(unitName, instanceName,
145 objectPath.str, ""));
146 }
147 else if (type == UnitType::socket)
148 {
Jiaqing Zhaoaa41e672021-12-14 15:14:30 +0800149 unitsToMonitor.emplace(instantiatedUnitName,
150 std::make_tuple(unitName, instanceName,
151 "", objectPath.str));
Vernon Maueryba2c0832020-07-15 10:02:38 -0700152 }
153 }
154 }
155
156 bool updateRequired = false;
157 bool jsonExist = std::filesystem::exists(srvCfgMgrFile);
158 if (jsonExist)
159 {
George Liuf2744892022-01-05 17:54:45 +0800160 try
Vernon Maueryba2c0832020-07-15 10:02:38 -0700161 {
George Liuf2744892022-01-05 17:54:45 +0800162 std::ifstream file(srvCfgMgrFile);
163 cereal::JSONInputArchive archive(file);
164 MonitorListMap savedMonitorList;
165 archive(savedMonitorList);
166
167 // compare the unit list read from systemd1 and the save list.
168 MonitorListMap diffMap;
169 std::set_difference(begin(unitsToMonitor), end(unitsToMonitor),
170 begin(savedMonitorList), end(savedMonitorList),
171 std::inserter(diffMap, begin(diffMap)));
172 for (auto& unitIt : diffMap)
Vernon Maueryba2c0832020-07-15 10:02:38 -0700173 {
George Liuf2744892022-01-05 17:54:45 +0800174 auto it = savedMonitorList.find(unitIt.first);
175 if (it == savedMonitorList.end())
176 {
177 savedMonitorList.insert(unitIt);
178 updateRequired = true;
179 }
Vernon Maueryba2c0832020-07-15 10:02:38 -0700180 }
George Liuf2744892022-01-05 17:54:45 +0800181 unitsToMonitor = savedMonitorList;
Vernon Maueryba2c0832020-07-15 10:02:38 -0700182 }
George Liuf2744892022-01-05 17:54:45 +0800183 catch (const std::exception& e)
184 {
185 lg2::error(
186 "Failed to load {FILEPATH} file, need to rewrite: {ERROR}.",
187 "FILEPATH", srvCfgMgrFile, "ERROR", e);
188
189 // The "bad" files need to be moved to /tmp/ so that we can try to
190 // find out the cause of the file corruption. If we encounter this
191 // failure multiple times, we will only overwrite it to ensure that
192 // we don't accidentally fill up /tmp/.
193 std::error_code ec;
194 std::filesystem::copy_file(
195 srvCfgMgrFile, tmpFileBad,
196 std::filesystem::copy_options::overwrite_existing, ec);
197 if (ec)
198 {
199 lg2::error("Failed to copy {SRCFILE} file to {DSTFILE}.",
200 "SRCFILE", srvCfgMgrFile, "DSTFILE", tmpFileBad);
201 }
202
203 updateRequired = true;
204 }
Vernon Maueryba2c0832020-07-15 10:02:38 -0700205 }
206 if (!jsonExist || updateRequired)
207 {
208 std::ofstream file(srvCfgMgrFile);
209 cereal::JSONOutputArchive archive(file);
210 archive(CEREAL_NVP(unitsToMonitor));
211 }
212
Chicago Duan25a0f632021-11-11 16:32:07 +0800213#ifdef USB_CODE_UPDATE
214 unitsToMonitor.emplace(
215 "phosphor_2dusb_2dcode_2dupdate",
216 std::make_tuple(
217 "phosphor_usb_code_update", "",
218 "/org/freedesktop/systemd1/unit/usb_2dcode_2dupdate_2eservice",
219 ""));
220#endif
221
Vernon Maueryba2c0832020-07-15 10:02:38 -0700222 // create objects for needed services
223 for (auto& it : unitsToMonitor)
224 {
225 std::string objPath(std::string(phosphor::service::srcCfgMgrBasePath) +
226 "/" + it.first);
227 std::string instanciatedUnitName =
228 std::get<static_cast<int>(monitorElement::unitName)>(it.second) +
229 addInstanceName(
230 std::get<static_cast<int>(monitorElement::instanceName)>(
231 it.second),
232 "@");
233 auto srvCfgObj = std::make_unique<phosphor::service::ServiceConfig>(
234 server, conn, objPath,
235 std::get<static_cast<int>(monitorElement::unitName)>(it.second),
236 std::get<static_cast<int>(monitorElement::instanceName)>(it.second),
237 std::get<static_cast<int>(monitorElement::serviceObjPath)>(
238 it.second),
239 std::get<static_cast<int>(monitorElement::socketObjPath)>(
240 it.second));
241 srvMgrObjects.emplace(
242 std::make_pair(std::move(objPath), std::move(srvCfgObj)));
243 }
244}
245
246void init(sdbusplus::asio::object_server& server,
247 std::shared_ptr<sdbusplus::asio::connection>& conn)
248{
249 // Go through all systemd units, and dynamically detect and manage
250 // the service daemons
251 conn->async_method_call(
252 [&server, &conn](boost::system::error_code ec,
253 const std::vector<ListUnitsType>& listUnits) {
254 if (ec)
255 {
George Liucb267c82022-01-05 17:53:28 +0800256 lg2::error("async_method_call error: ListUnits failed: {EC}",
257 "EC", ec.value());
Vernon Maueryba2c0832020-07-15 10:02:38 -0700258 return;
259 }
260 handleListUnitsResponse(server, conn, ec, listUnits);
261 },
262 sysdService, sysdObjPath, sysdMgrIntf, "ListUnits");
263}
264
265void checkAndInit(sdbusplus::asio::object_server& server,
266 std::shared_ptr<sdbusplus::asio::connection>& conn)
267{
268 // Check whether systemd completed all the loading before initializing
269 conn->async_method_call(
270 [&server, &conn](boost::system::error_code ec,
271 const std::variant<uint64_t>& value) {
272 if (ec)
273 {
George Liucb267c82022-01-05 17:53:28 +0800274 lg2::error("async_method_call error: ListUnits failed: {EC}",
275 "EC", ec.value());
Vernon Maueryba2c0832020-07-15 10:02:38 -0700276 return;
277 }
278 if (std::get<uint64_t>(value))
279 {
280 if (!unitQueryStarted)
281 {
282 unitQueryStarted = true;
283 init(server, conn);
284 }
285 }
286 else
287 {
288 // FIX-ME: Latest up-stream sync caused issue in receiving
289 // StartupFinished signal. Unable to get StartupFinished signal
290 // from systemd1 hence using poll method too, to trigger it
291 // properly.
292 constexpr size_t pollTimeout = 10; // seconds
293 initTimer->expires_after(std::chrono::seconds(pollTimeout));
294 initTimer->async_wait([&server, &conn](
295 const boost::system::error_code& ec) {
296 if (ec == boost::asio::error::operation_aborted)
297 {
298 // Timer reset.
299 return;
300 }
301 if (ec)
302 {
George Liucb267c82022-01-05 17:53:28 +0800303 lg2::error(
304 "service config mgr - init - async wait error: {EC}",
305 "EC", ec.value());
Vernon Maueryba2c0832020-07-15 10:02:38 -0700306 return;
307 }
308 checkAndInit(server, conn);
309 });
310 }
311 },
312 sysdService, sysdObjPath, dBusPropIntf, dBusGetMethod, sysdMgrIntf,
313 "FinishTimestamp");
314}
315
316int main()
317{
318 boost::asio::io_service io;
319 auto conn = std::make_shared<sdbusplus::asio::connection>(io);
320 timer = std::make_unique<boost::asio::steady_timer>(io);
321 initTimer = std::make_unique<boost::asio::steady_timer>(io);
322 conn->request_name(phosphor::service::serviceConfigSrvName);
323 auto server = sdbusplus::asio::object_server(conn, true);
Vernon Maueryba2c0832020-07-15 10:02:38 -0700324 server.add_manager(phosphor::service::srcCfgMgrBasePath);
325 // Initialize the objects after systemd indicated startup finished.
326 auto userUpdatedSignal = std::make_unique<sdbusplus::bus::match::match>(
327 static_cast<sdbusplus::bus::bus&>(*conn),
328 "type='signal',"
329 "member='StartupFinished',path='/org/freedesktop/systemd1',"
330 "interface='org.freedesktop.systemd1.Manager'",
331 [&server, &conn](sdbusplus::message::message& /*msg*/) {
332 if (!unitQueryStarted)
333 {
334 unitQueryStarted = true;
335 init(server, conn);
336 }
337 });
338 // this will make sure to initialize the objects, when daemon is
339 // restarted.
340 checkAndInit(server, conn);
341
342 io.run();
343
344 return 0;
345}