blob: d82f7b98332a110497898e69105d1eaccd5a545e [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>
Jiaqing Zhaof4766832022-02-28 14:28:18 +080026#include <unordered_map>
Vernon Maueryba2c0832020-07-15 10:02:38 -070027
28std::unique_ptr<boost::asio::steady_timer> timer = nullptr;
29std::unique_ptr<boost::asio::steady_timer> initTimer = nullptr;
30std::map<std::string, std::shared_ptr<phosphor::service::ServiceConfig>>
31 srvMgrObjects;
32static bool unitQueryStarted = false;
33
Andrew Geissler67e41862025-04-22 09:50:30 -050034static constexpr const char* srvCfgMgrFileOld = "/etc/srvcfg-mgr.json";
35static constexpr const char* srvCfgMgrFile = "srvcfg-mgr.json";
George Liuf2744892022-01-05 17:54:45 +080036static constexpr const char* tmpFileBad = "/tmp/srvcfg-mgr.json.bad";
Vernon Maueryba2c0832020-07-15 10:02:38 -070037
38// Base service name list. All instance of these services and
39// units(service/socket) will be managed by this daemon.
Jiaqing Zhaof4766832022-02-28 14:28:18 +080040static std::unordered_map<std::string /* unitName */,
41 bool /* isSocketActivated */>
42 managedServices = {{"phosphor-ipmi-net", false}, {"bmcweb", false},
Mohammed Javith Akthar Maaca0572024-06-27 17:31:02 -040043 {"phosphor-ipmi-kcs", false}, {"obmc-ikvm", false},
Jiaqing Zhaoef5cece2021-12-10 00:44:11 +080044 {"obmc-console", false}, {"dropbear", true},
leonhuang25c93aa2025-03-10 20:41:56 -070045 {"obmc-console-ssh", true}, {"ssifbridge", false}};
Vernon Maueryba2c0832020-07-15 10:02:38 -070046
47enum class UnitType
48{
49 service,
50 socket,
51 target,
52 device,
53 invalid
54};
55
56using MonitorListMap =
57 std::unordered_map<std::string, std::tuple<std::string, std::string,
58 std::string, std::string>>;
59MonitorListMap unitsToMonitor;
60
61enum class monitorElement
62{
63 unitName,
64 instanceName,
65 serviceObjPath,
66 socketObjPath
67};
68
Patrick Williams3c9cecf2025-02-01 08:23:15 -050069std::tuple<std::string, UnitType, std::string> getUnitNameTypeAndInstance(
70 const std::string& fullUnitName)
Vernon Maueryba2c0832020-07-15 10:02:38 -070071{
72 UnitType type = UnitType::invalid;
73 std::string instanceName;
74 std::string unitName;
75 // get service type
76 auto typePos = fullUnitName.rfind(".");
77 if (typePos != std::string::npos)
78 {
79 const auto& typeStr = fullUnitName.substr(typePos + 1);
80 // Ignore types other than service and socket
81 if (typeStr == "service")
82 {
83 type = UnitType::service;
84 }
85 else if (typeStr == "socket")
86 {
87 type = UnitType::socket;
88 }
89 // get instance name if available
90 auto instancePos = fullUnitName.rfind("@");
91 if (instancePos != std::string::npos)
92 {
Patrick Williamsde879722024-08-16 15:21:46 -040093 instanceName =
94 fullUnitName.substr(instancePos + 1, typePos - instancePos - 1);
Vernon Maueryba2c0832020-07-15 10:02:38 -070095 unitName = fullUnitName.substr(0, instancePos);
96 }
97 else
98 {
99 unitName = fullUnitName.substr(0, typePos);
100 }
101 }
102 return std::make_tuple(unitName, type, instanceName);
103}
104
Patrick Williamsde879722024-08-16 15:21:46 -0400105static inline void handleListUnitsResponse(
106 sdbusplus::asio::object_server& server,
107 std::shared_ptr<sdbusplus::asio::connection>& conn,
108 boost::system::error_code /*ec*/,
109 const std::vector<ListUnitsType>& listUnits)
Vernon Maueryba2c0832020-07-15 10:02:38 -0700110{
111 // Loop through all units, and mark all units, which has to be
112 // managed, irrespective of instance name.
113 for (const auto& unit : listUnits)
114 {
Jiaqing Zhaod2a99a42022-02-25 17:26:30 +0800115 // Ignore non-existent units
116 if (std::get<static_cast<int>(ListUnitElements::loadState)>(unit) ==
117 loadStateNotFound)
118 {
119 continue;
120 }
121
Vernon Maueryba2c0832020-07-15 10:02:38 -0700122 const auto& fullUnitName =
123 std::get<static_cast<int>(ListUnitElements::name)>(unit);
Patrick Williamsdfc72702023-05-10 07:51:18 -0500124 auto [unitName, type,
125 instanceName] = getUnitNameTypeAndInstance(fullUnitName);
Jiaqing Zhaof4766832022-02-28 14:28:18 +0800126 if (managedServices.count(unitName))
Vernon Maueryba2c0832020-07-15 10:02:38 -0700127 {
Jiaqing Zhaof4766832022-02-28 14:28:18 +0800128 // For socket-activated units, ignore all its instances
129 if (managedServices.at(unitName) == true && !instanceName.empty())
130 {
131 continue;
132 }
133
Vernon Maueryba2c0832020-07-15 10:02:38 -0700134 std::string instantiatedUnitName =
Jiaqing Zhao4b8637d2022-04-01 21:25:12 +0800135 unitName + addInstanceName(instanceName, "@");
Vernon Maueryba2c0832020-07-15 10:02:38 -0700136 const sdbusplus::message::object_path& objectPath =
137 std::get<static_cast<int>(ListUnitElements::objectPath)>(unit);
Manojkiran Eda23ecbb62024-06-17 14:28:01 +0530138 // Group the service & socket units together.. Same services
Vernon Maueryba2c0832020-07-15 10:02:38 -0700139 // are managed together.
140 auto it = unitsToMonitor.find(instantiatedUnitName);
141 if (it != unitsToMonitor.end())
142 {
143 auto& value = it->second;
144 if (type == UnitType::service)
145 {
Vernon Maueryba2c0832020-07-15 10:02:38 -0700146 std::get<static_cast<int>(monitorElement::serviceObjPath)>(
Jiaqing Zhaoaa41e672021-12-14 15:14:30 +0800147 value) = objectPath.str;
Vernon Maueryba2c0832020-07-15 10:02:38 -0700148 }
149 else if (type == UnitType::socket)
150 {
151 std::get<static_cast<int>(monitorElement::socketObjPath)>(
Jiaqing Zhaoaa41e672021-12-14 15:14:30 +0800152 value) = objectPath.str;
Vernon Maueryba2c0832020-07-15 10:02:38 -0700153 }
Jiaqing Zhaoaa41e672021-12-14 15:14:30 +0800154 continue;
Vernon Maueryba2c0832020-07-15 10:02:38 -0700155 }
Jiaqing Zhaoaa41e672021-12-14 15:14:30 +0800156 // If not grouped with any existing entry, create a new one
Vernon Maueryba2c0832020-07-15 10:02:38 -0700157 if (type == UnitType::service)
158 {
159 unitsToMonitor.emplace(instantiatedUnitName,
160 std::make_tuple(unitName, instanceName,
161 objectPath.str, ""));
162 }
163 else if (type == UnitType::socket)
164 {
Jiaqing Zhaoaa41e672021-12-14 15:14:30 +0800165 unitsToMonitor.emplace(instantiatedUnitName,
166 std::make_tuple(unitName, instanceName,
167 "", objectPath.str));
Vernon Maueryba2c0832020-07-15 10:02:38 -0700168 }
169 }
170 }
171
172 bool updateRequired = false;
Andrew Geissler67e41862025-04-22 09:50:30 -0500173
174 // Determine if we need to create our persistent config dir
175 if (!std::filesystem::exists(srvDataBaseDir))
176 {
177 std::filesystem::create_directories(srvDataBaseDir);
178 }
179
180 std::string srvCfgMgrFilePath = std::string(srvDataBaseDir) + srvCfgMgrFile;
181
182 // First check if our config manager file is in the old spot.
183 // If it is, then move it to the new spot
184 if ((std::filesystem::exists(srvCfgMgrFileOld)) &&
185 (!std::filesystem::exists(srvCfgMgrFilePath)))
186 {
187 lg2::info("Moving {OLDFILEPATH} to new location, {FILEPATH}",
188 "OLDFILEPATH", srvCfgMgrFileOld, "FILEPATH",
189 srvCfgMgrFilePath);
190 std::filesystem::rename(srvCfgMgrFileOld, srvCfgMgrFilePath);
191 }
192
193 bool jsonExist = std::filesystem::exists(srvCfgMgrFilePath);
Vernon Maueryba2c0832020-07-15 10:02:38 -0700194 if (jsonExist)
195 {
George Liuf2744892022-01-05 17:54:45 +0800196 try
Vernon Maueryba2c0832020-07-15 10:02:38 -0700197 {
Andrew Geissler67e41862025-04-22 09:50:30 -0500198 std::ifstream file(srvCfgMgrFilePath);
George Liuf2744892022-01-05 17:54:45 +0800199 cereal::JSONInputArchive archive(file);
200 MonitorListMap savedMonitorList;
201 archive(savedMonitorList);
202
203 // compare the unit list read from systemd1 and the save list.
204 MonitorListMap diffMap;
205 std::set_difference(begin(unitsToMonitor), end(unitsToMonitor),
206 begin(savedMonitorList), end(savedMonitorList),
207 std::inserter(diffMap, begin(diffMap)));
208 for (auto& unitIt : diffMap)
Vernon Maueryba2c0832020-07-15 10:02:38 -0700209 {
George Liuf2744892022-01-05 17:54:45 +0800210 auto it = savedMonitorList.find(unitIt.first);
211 if (it == savedMonitorList.end())
212 {
213 savedMonitorList.insert(unitIt);
214 updateRequired = true;
215 }
Vernon Maueryba2c0832020-07-15 10:02:38 -0700216 }
George Liuf2744892022-01-05 17:54:45 +0800217 unitsToMonitor = savedMonitorList;
Vernon Maueryba2c0832020-07-15 10:02:38 -0700218 }
George Liuf2744892022-01-05 17:54:45 +0800219 catch (const std::exception& e)
220 {
221 lg2::error(
222 "Failed to load {FILEPATH} file, need to rewrite: {ERROR}.",
Andrew Geissler67e41862025-04-22 09:50:30 -0500223 "FILEPATH", srvCfgMgrFilePath, "ERROR", e);
George Liuf2744892022-01-05 17:54:45 +0800224
225 // The "bad" files need to be moved to /tmp/ so that we can try to
226 // find out the cause of the file corruption. If we encounter this
227 // failure multiple times, we will only overwrite it to ensure that
228 // we don't accidentally fill up /tmp/.
229 std::error_code ec;
230 std::filesystem::copy_file(
Andrew Geissler67e41862025-04-22 09:50:30 -0500231 srvCfgMgrFilePath, tmpFileBad,
George Liuf2744892022-01-05 17:54:45 +0800232 std::filesystem::copy_options::overwrite_existing, ec);
233 if (ec)
234 {
235 lg2::error("Failed to copy {SRCFILE} file to {DSTFILE}.",
Andrew Geissler67e41862025-04-22 09:50:30 -0500236 "SRCFILE", srvCfgMgrFilePath, "DSTFILE", tmpFileBad);
George Liuf2744892022-01-05 17:54:45 +0800237 }
238
239 updateRequired = true;
240 }
Vernon Maueryba2c0832020-07-15 10:02:38 -0700241 }
242 if (!jsonExist || updateRequired)
243 {
Andrew Geissler67e41862025-04-22 09:50:30 -0500244 std::ofstream file(srvCfgMgrFilePath);
Vernon Maueryba2c0832020-07-15 10:02:38 -0700245 cereal::JSONOutputArchive archive(file);
246 archive(CEREAL_NVP(unitsToMonitor));
247 }
248
Chicago Duan25a0f632021-11-11 16:32:07 +0800249#ifdef USB_CODE_UPDATE
250 unitsToMonitor.emplace(
Jiaqing Zhao4b8637d2022-04-01 21:25:12 +0800251 "phosphor-usb-code-update",
Chicago Duan25a0f632021-11-11 16:32:07 +0800252 std::make_tuple(
Jiaqing Zhao430d7ea2022-04-01 23:23:25 +0800253 phosphor::service::usbCodeUpdateUnitName, "",
Chicago Duan25a0f632021-11-11 16:32:07 +0800254 "/org/freedesktop/systemd1/unit/usb_2dcode_2dupdate_2eservice",
255 ""));
256#endif
257
Vernon Maueryba2c0832020-07-15 10:02:38 -0700258 // create objects for needed services
259 for (auto& it : unitsToMonitor)
260 {
Jiaqing Zhao4b8637d2022-04-01 21:25:12 +0800261 sdbusplus::message::object_path basePath(
262 phosphor::service::srcCfgMgrBasePath);
263 std::string objPath(basePath / it.first);
Vernon Maueryba2c0832020-07-15 10:02:38 -0700264 auto srvCfgObj = std::make_unique<phosphor::service::ServiceConfig>(
265 server, conn, objPath,
266 std::get<static_cast<int>(monitorElement::unitName)>(it.second),
267 std::get<static_cast<int>(monitorElement::instanceName)>(it.second),
268 std::get<static_cast<int>(monitorElement::serviceObjPath)>(
269 it.second),
270 std::get<static_cast<int>(monitorElement::socketObjPath)>(
271 it.second));
272 srvMgrObjects.emplace(
273 std::make_pair(std::move(objPath), std::move(srvCfgObj)));
274 }
275}
276
277void init(sdbusplus::asio::object_server& server,
278 std::shared_ptr<sdbusplus::asio::connection>& conn)
279{
280 // Go through all systemd units, and dynamically detect and manage
281 // the service daemons
282 conn->async_method_call(
283 [&server, &conn](boost::system::error_code ec,
284 const std::vector<ListUnitsType>& listUnits) {
Patrick Williamsde879722024-08-16 15:21:46 -0400285 if (ec)
286 {
287 lg2::error("async_method_call error: ListUnits failed: {EC}",
288 "EC", ec.value());
289 return;
290 }
291 handleListUnitsResponse(server, conn, ec, listUnits);
292 },
Vernon Maueryba2c0832020-07-15 10:02:38 -0700293 sysdService, sysdObjPath, sysdMgrIntf, "ListUnits");
294}
295
296void checkAndInit(sdbusplus::asio::object_server& server,
297 std::shared_ptr<sdbusplus::asio::connection>& conn)
298{
299 // Check whether systemd completed all the loading before initializing
300 conn->async_method_call(
301 [&server, &conn](boost::system::error_code ec,
302 const std::variant<uint64_t>& value) {
Patrick Williamsde879722024-08-16 15:21:46 -0400303 if (ec)
Vernon Maueryba2c0832020-07-15 10:02:38 -0700304 {
Patrick Williamsde879722024-08-16 15:21:46 -0400305 lg2::error("async_method_call error: ListUnits failed: {EC}",
306 "EC", ec.value());
307 return;
Vernon Maueryba2c0832020-07-15 10:02:38 -0700308 }
Patrick Williamsde879722024-08-16 15:21:46 -0400309 if (std::get<uint64_t>(value))
310 {
311 if (!unitQueryStarted)
Vernon Maueryba2c0832020-07-15 10:02:38 -0700312 {
Patrick Williamsde879722024-08-16 15:21:46 -0400313 unitQueryStarted = true;
314 init(server, conn);
Vernon Maueryba2c0832020-07-15 10:02:38 -0700315 }
Patrick Williamsde879722024-08-16 15:21:46 -0400316 }
317 else
318 {
319 // FIX-ME: Latest up-stream sync caused issue in receiving
320 // StartupFinished signal. Unable to get StartupFinished signal
321 // from systemd1 hence using poll method too, to trigger it
322 // properly.
323 constexpr size_t pollTimeout = 10; // seconds
324 initTimer->expires_after(std::chrono::seconds(pollTimeout));
325 initTimer->async_wait([&server, &conn](
326 const boost::system::error_code& ec) {
327 if (ec == boost::asio::error::operation_aborted)
328 {
329 // Timer reset.
330 return;
331 }
332 if (ec)
333 {
334 lg2::error(
335 "service config mgr - init - async wait error: {EC}",
336 "EC", ec.value());
337 return;
338 }
339 checkAndInit(server, conn);
340 });
341 }
342 },
Vernon Maueryba2c0832020-07-15 10:02:38 -0700343 sysdService, sysdObjPath, dBusPropIntf, dBusGetMethod, sysdMgrIntf,
344 "FinishTimestamp");
345}
346
347int main()
348{
Ed Tanousba287d82023-03-01 10:42:28 -0800349 boost::asio::io_context io;
Vernon Maueryba2c0832020-07-15 10:02:38 -0700350 auto conn = std::make_shared<sdbusplus::asio::connection>(io);
351 timer = std::make_unique<boost::asio::steady_timer>(io);
352 initTimer = std::make_unique<boost::asio::steady_timer>(io);
353 conn->request_name(phosphor::service::serviceConfigSrvName);
354 auto server = sdbusplus::asio::object_server(conn, true);
Vernon Maueryba2c0832020-07-15 10:02:38 -0700355 server.add_manager(phosphor::service::srcCfgMgrBasePath);
356 // Initialize the objects after systemd indicated startup finished.
Patrick Williams2ff37282022-07-22 19:26:57 -0500357 auto userUpdatedSignal = std::make_unique<sdbusplus::bus::match_t>(
358 static_cast<sdbusplus::bus_t&>(*conn),
Vernon Maueryba2c0832020-07-15 10:02:38 -0700359 "type='signal',"
360 "member='StartupFinished',path='/org/freedesktop/systemd1',"
361 "interface='org.freedesktop.systemd1.Manager'",
Patrick Williams2ff37282022-07-22 19:26:57 -0500362 [&server, &conn](sdbusplus::message_t& /*msg*/) {
Patrick Williamsde879722024-08-16 15:21:46 -0400363 if (!unitQueryStarted)
364 {
365 unitQueryStarted = true;
366 init(server, conn);
367 }
368 });
Vernon Maueryba2c0832020-07-15 10:02:38 -0700369 // this will make sure to initialize the objects, when daemon is
370 // restarted.
371 checkAndInit(server, conn);
372
373 io.run();
374
375 return 0;
376}