1 #include "system_configuration.hpp"
2 
3 #include <phosphor-logging/elog-errors.hpp>
4 #include <phosphor-logging/log.hpp>
5 #include <xyz/openbmc_project/Common/error.hpp>
6 
7 namespace phosphor
8 {
9 namespace network
10 {
11 
12 // systemd service to kick start a target.
13 constexpr auto HOSTNAMED_SERVICE = "org.freedesktop.hostname1";
14 constexpr auto HOSTNAMED_SERVICE_PATH = "/org/freedesktop/hostname1";
15 constexpr auto HOSTNAMED_INTERFACE = "org.freedesktop.hostname1";
16 constexpr auto PROPERTY_INTERFACE = "org.freedesktop.DBus.Properties";
17 constexpr auto METHOD_GET = "Get";
18 constexpr auto METHOD_SET = "SetStaticHostname";
19 
20 using namespace phosphor::logging;
21 using namespace sdbusplus::xyz::openbmc_project::Common::Error;
22 
23 using SystemConfigIntf =
24     sdbusplus::xyz::openbmc_project::Network::server::SystemConfiguration;
25 
26 SystemConfiguration::SystemConfiguration(sdbusplus::bus_t& bus,
27                                          stdplus::const_zstring objPath) :
28     Iface(bus, objPath.c_str(), Iface::action::defer_emit),
29     bus(bus)
30 {
31     SystemConfigIntf::hostName(getHostNameFromSystem());
32 
33     this->emit_object_added();
34 }
35 
36 std::string SystemConfiguration::hostName(std::string name)
37 {
38     if (SystemConfigIntf::hostName() == name)
39     {
40         return name;
41     }
42     auto method = bus.new_method_call(HOSTNAMED_SERVICE, HOSTNAMED_SERVICE_PATH,
43                                       HOSTNAMED_INTERFACE, METHOD_SET);
44 
45     method.append(name, true);
46 
47     if (!bus.call(method))
48     {
49         log<level::ERR>("Failed to set the hostname");
50         report<InternalFailure>();
51         return SystemConfigIntf::hostName();
52     }
53 
54     return SystemConfigIntf::hostName(name);
55 }
56 
57 std::string SystemConfiguration::getHostNameFromSystem() const
58 {
59     try
60     {
61         std::variant<std::string> name;
62         auto method =
63             bus.new_method_call(HOSTNAMED_SERVICE, HOSTNAMED_SERVICE_PATH,
64                                 PROPERTY_INTERFACE, METHOD_GET);
65 
66         method.append(HOSTNAMED_INTERFACE, "Hostname");
67 
68         auto reply = bus.call(method);
69 
70         reply.read(name);
71         return std::get<std::string>(name);
72     }
73     catch (const sdbusplus::exception_t& ex)
74     {
75         log<level::ERR>(
76             "Failed to get the hostname from systemd-hostnamed service",
77             entry("ERR=%s", ex.what()));
78     }
79     return "";
80 }
81 
82 } // namespace network
83 } // namespace phosphor
84