xref: /openbmc/sdbusplus/example/asio-example.cpp (revision 98f141f9d1c553c154048effe86b667f8ed8cd1a)
1  #include <boost/asio/detached.hpp>
2  #include <boost/asio/io_context.hpp>
3  #include <boost/asio/spawn.hpp>
4  #include <sdbusplus/asio/connection.hpp>
5  #include <sdbusplus/asio/object_server.hpp>
6  #include <sdbusplus/asio/sd_event.hpp>
7  #include <sdbusplus/bus.hpp>
8  #include <sdbusplus/exception.hpp>
9  #include <sdbusplus/server.hpp>
10  #include <sdbusplus/timer.hpp>
11  
12  #include <chrono>
13  #include <ctime>
14  #include <iostream>
15  #include <variant>
16  
17  using variant = std::variant<int, std::string>;
18  
foo(int test)19  int foo(int test)
20  {
21      std::cout << "foo(" << test << ") -> " << (test + 1) << "\n";
22      return ++test;
23  }
24  
25  // called from coroutine context, can make yielding dbus calls
fooYield(boost::asio::yield_context yield,std::shared_ptr<sdbusplus::asio::connection> conn,int test)26  int fooYield(boost::asio::yield_context yield,
27               std::shared_ptr<sdbusplus::asio::connection> conn, int test)
28  {
29      // fetch the real value from testFunction
30      boost::system::error_code ec;
31      std::cout << "fooYield(yield, " << test << ")...\n";
32      int testCount = conn->yield_method_call<int>(
33          yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
34          "xyz.openbmc_project.test", "TestFunction", test);
35      if (ec || testCount != (test + 1))
36      {
37          std::cout << "call to foo failed: ec = " << ec << '\n';
38          return -1;
39      }
40      std::cout << "yielding call to foo OK! (-> " << testCount << ")\n";
41      return testCount;
42  }
43  
methodWithMessage(sdbusplus::message_t &,int test)44  int methodWithMessage(sdbusplus::message_t& /*m*/, int test)
45  {
46      std::cout << "methodWithMessage(m, " << test << ") -> " << (test + 1)
47                << "\n";
48      return ++test;
49  }
50  
voidBar(void)51  int voidBar(void)
52  {
53      std::cout << "voidBar() -> 42\n";
54      return 42;
55  }
56  
do_start_async_method_call_one(std::shared_ptr<sdbusplus::asio::connection> conn,boost::asio::yield_context yield)57  void do_start_async_method_call_one(
58      std::shared_ptr<sdbusplus::asio::connection> conn,
59      boost::asio::yield_context yield)
60  {
61      boost::system::error_code ec;
62      variant testValue;
63      conn->yield_method_call<>(
64          yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
65          "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.test",
66          "int", variant(24));
67      testValue = conn->yield_method_call<variant>(
68          yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
69          "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.test",
70          "int");
71      if (!ec && std::get<int>(testValue) == 24)
72      {
73          std::cout << "async call to Properties.Get serialized via yield OK!\n";
74      }
75      else
76      {
77          std::cout << "ec = " << ec << ": " << std::get<int>(testValue) << "\n";
78      }
79      conn->yield_method_call<void>(
80          yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
81          "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.test",
82          "int", variant(42));
83      testValue = conn->yield_method_call<variant>(
84          yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
85          "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.test",
86          "int");
87      if (!ec && std::get<int>(testValue) == 42)
88      {
89          std::cout << "async call to Properties.Get serialized via yield OK!\n";
90      }
91      else
92      {
93          std::cout << "ec = " << ec << ": " << std::get<int>(testValue) << "\n";
94      }
95  }
96  
do_start_async_ipmi_call(std::shared_ptr<sdbusplus::asio::connection> conn,boost::asio::yield_context yield)97  void do_start_async_ipmi_call(std::shared_ptr<sdbusplus::asio::connection> conn,
98                                boost::asio::yield_context yield)
99  {
100      auto method = conn->new_method_call("xyz.openbmc_project.asio-test",
101                                          "/xyz/openbmc_project/test",
102                                          "xyz.openbmc_project.test", "execute");
103      constexpr uint8_t netFn = 6;
104      constexpr uint8_t lun = 0;
105      constexpr uint8_t cmd = 1;
106      std::map<std::string, variant> options = {{"username", variant("admin")},
107                                                {"privilege", variant(4)}};
108      std::vector<uint8_t> commandData = {4, 3, 2, 1};
109      method.append(netFn, lun, cmd, commandData, options);
110      boost::system::error_code ec;
111      sdbusplus::message_t reply = conn->async_send_yield(method, yield[ec]);
112      std::tuple<uint8_t, uint8_t, uint8_t, uint8_t, std::vector<uint8_t>>
113          tupleOut;
114      try
115      {
116          reply.read(tupleOut);
117      }
118      catch (const sdbusplus::exception::exception& e)
119      {
120          std::cerr << "failed to unpack; sig is " << reply.get_signature()
121                    << "\n";
122      }
123      auto& [rnetFn, rlun, rcmd, cc, responseData] = tupleOut;
124      std::vector<uint8_t> expRsp = {1, 2, 3, 4};
125      if (rnetFn == uint8_t(netFn + 1) && rlun == lun && rcmd == cmd && cc == 0 &&
126          responseData == expRsp)
127      {
128          std::cerr << "ipmi call returns OK!\n";
129      }
130      else
131      {
132          std::cerr << "ipmi call returns unexpected response\n";
133      }
134  }
135  
ipmiInterface(boost::asio::yield_context,uint8_t netFn,uint8_t lun,uint8_t cmd,std::vector<uint8_t> &,const std::map<std::string,variant> &)136  auto ipmiInterface(boost::asio::yield_context /*yield*/, uint8_t netFn,
137                     uint8_t lun, uint8_t cmd, std::vector<uint8_t>& /*data*/,
138                     const std::map<std::string, variant>& /*options*/)
139  {
140      std::vector<uint8_t> reply = {1, 2, 3, 4};
141      uint8_t cc = 0;
142      std::cerr << "ipmiInterface:execute(" << int(netFn) << int(cmd) << ")\n";
143      return std::make_tuple(uint8_t(netFn + 1), lun, cmd, cc, reply);
144  }
145  
do_start_async_to_yield(std::shared_ptr<sdbusplus::asio::connection> conn,boost::asio::yield_context yield)146  void do_start_async_to_yield(std::shared_ptr<sdbusplus::asio::connection> conn,
147                               boost::asio::yield_context yield)
148  {
149      boost::system::error_code ec;
150      int testValue = 0;
151      testValue = conn->yield_method_call<int>(
152          yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
153          "xyz.openbmc_project.test", "TestYieldFunction", int(41));
154  
155      if (!ec && testValue == 42)
156      {
157          std::cout
158              << "yielding call to TestYieldFunction serialized via yield OK!\n";
159      }
160      else
161      {
162          std::cout << "ec = " << ec << ": " << testValue << "\n";
163      }
164  
165      ec.clear();
166      auto badValue = conn->yield_method_call<std::string>(
167          yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
168          "xyz.openbmc_project.test", "TestYieldFunction", int(41));
169  
170      if (!ec)
171      {
172          std::cout
173              << "yielding call to TestYieldFunction returned the wrong type\n";
174      }
175      else
176      {
177          std::cout << "TestYieldFunction expected error: " << ec << "\n";
178      }
179  
180      ec.clear();
181      auto unUsedValue = conn->yield_method_call<std::string>(
182          yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
183          "xyz.openbmc_project.test", "TestYieldFunctionNotExits", int(41));
184  
185      if (!ec)
186      {
187          std::cout << "TestYieldFunctionNotExists returned unexpectedly\n";
188      }
189      else
190      {
191          std::cout << "TestYieldFunctionNotExits expected error: " << ec << "\n";
192      }
193  }
194  
server()195  int server()
196  {
197      // setup connection to dbus
198      boost::asio::io_context io;
199      auto conn = std::make_shared<sdbusplus::asio::connection>(io);
200  
201      // test object server
202      conn->request_name("xyz.openbmc_project.asio-test");
203      auto server = sdbusplus::asio::object_server(conn);
204      std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
205          server.add_interface("/xyz/openbmc_project/test",
206                               "xyz.openbmc_project.test");
207      // test generic properties
208      iface->register_property("int", 33,
209                               sdbusplus::asio::PropertyPermission::readWrite);
210      std::vector<std::string> myStringVec = {"some", "test", "data"};
211      std::vector<std::string> myStringVec2 = {"more", "test", "data"};
212  
213      iface->register_property("myStringVec", myStringVec,
214                               sdbusplus::asio::PropertyPermission::readWrite);
215      iface->register_property("myStringVec2", myStringVec2);
216  
217      // test properties with specialized callbacks
218      iface->register_property("lessThan50", 23,
219                               // custom set
220                               [](const int& req, int& propertyValue) {
221                                   if (req >= 50)
222                                   {
223                                       return false;
224                                   }
225                                   propertyValue = req;
226                                   return true;
227                               });
228      iface->register_property(
229          "TrailTime", std::string("foo"),
230          // custom set
231          [](const std::string& req, std::string& propertyValue) {
232              propertyValue = req;
233              return true;
234          },
235          // custom get
236          [](const std::string& property) {
237              auto now = std::chrono::system_clock::now();
238              auto timePoint = std::chrono::system_clock::to_time_t(now);
239              return property + std::ctime(&timePoint);
240          });
241  
242      // test method creation
243      iface->register_method("TestMethod", [](const int32_t& callCount) {
244          return std::make_tuple(callCount,
245                                 "success: " + std::to_string(callCount));
246      });
247  
248      iface->register_method("TestFunction", foo);
249  
250      // fooYield has boost::asio::yield_context as first argument
251      // so will be executed in coroutine context if called
252      iface->register_method("TestYieldFunction",
253                             [conn](boost::asio::yield_context yield, int val) {
254                                 return fooYield(yield, conn, val);
255                             });
256  
257      iface->register_method("TestMethodWithMessage", methodWithMessage);
258  
259      iface->register_method("VoidFunctionReturnsInt", voidBar);
260  
261      iface->register_method("execute", ipmiInterface);
262  
263      iface->initialize();
264  
265      io.run();
266  
267      return 0;
268  }
269  
client()270  int client()
271  {
272      using GetSubTreeType = std::vector<std::pair<
273          std::string,
274          std::vector<std::pair<std::string, std::vector<std::string>>>>>;
275      using message = sdbusplus::message_t;
276  
277      // setup connection to dbus
278      boost::asio::io_context io;
279      auto conn = std::make_shared<sdbusplus::asio::connection>(io);
280  
281      int ready = 0;
282      while (!ready)
283      {
284          auto readyMsg = conn->new_method_call(
285              "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
286              "xyz.openbmc_project.test", "VoidFunctionReturnsInt");
287          try
288          {
289              message intMsg = conn->call(readyMsg);
290              intMsg.read(ready);
291          }
292          catch (const sdbusplus::exception::exception& e)
293          {
294              ready = 0;
295              // pause to give the server a chance to start up
296              usleep(10000);
297          }
298      }
299  
300      // test async method call and async send
301      auto mesg =
302          conn->new_method_call("xyz.openbmc_project.ObjectMapper",
303                                "/xyz/openbmc_project/object_mapper",
304                                "xyz.openbmc_project.ObjectMapper", "GetSubTree");
305  
306      int32_t depth = 2;
307      constexpr std::array<std::string_view, 1> interfaces{
308          "xyz.openbmc_project.Sensor.Value"};
309      mesg.append("/xyz/openbmc_project/Sensors", depth, interfaces);
310  
311      conn->async_send(mesg, [](boost::system::error_code ec, message& ret) {
312          std::cout << "async_send callback\n";
313          if (ec || ret.is_method_error())
314          {
315              std::cerr << "error with async_send\n";
316              return;
317          }
318          GetSubTreeType data;
319          ret.read(data);
320          for (auto& item : data)
321          {
322              std::cout << item.first << "\n";
323          }
324      });
325  
326      conn->async_method_call(
327          [](boost::system::error_code ec, GetSubTreeType& subtree) {
328              std::cout << "async_method_call callback\n";
329              if (ec)
330              {
331                  std::cerr << "error with async_method_call\n";
332                  return;
333              }
334              for (auto& item : subtree)
335              {
336                  std::cout << item.first << "\n";
337              }
338          },
339          "xyz.openbmc_project.ObjectMapper",
340          "/xyz/openbmc_project/object_mapper",
341          "xyz.openbmc_project.ObjectMapper", "GetSubTree",
342          "/org/openbmc/control", 2, std::vector<std::string>());
343  
344      std::string nonConstCapture = "lalalala";
345      conn->async_method_call(
346          [nonConstCapture = std::move(nonConstCapture)](
347              boost::system::error_code ec,
348              const std::vector<std::string>& /*things*/) mutable {
349              std::cout << "async_method_call callback\n";
350              nonConstCapture += " stuff";
351              if (ec)
352              {
353                  std::cerr << "async_method_call expected failure: " << ec
354                            << "\n";
355              }
356              else
357              {
358                  std::cerr << "async_method_call should have failed!\n";
359              }
360          },
361          "xyz.openbmc_project.ObjectMapper",
362          "/xyz/openbmc_project/object_mapper",
363          "xyz.openbmc_project.ObjectMapper", "GetSubTree",
364          "/xyz/openbmc_project/sensors", depth, interfaces);
365  
366      // sd_events work too using the default event loop
367      sdbusplus::Timer t1([]() { std::cerr << "*** tock ***\n"; });
368      t1.start(std::chrono::microseconds(1000000));
369      sdbusplus::Timer t2([]() { std::cerr << "*** tick ***\n"; });
370      t2.start(std::chrono::microseconds(500000), true);
371      // add the sd_event wrapper to the io object
372      sdbusplus::asio::sd_event_wrapper sdEvents(io);
373  
374      // set up a client to make an async call to the server
375      // using coroutines (userspace cooperative multitasking)
376      (void)boost::asio::spawn(
377          io,
378          [conn](boost::asio::yield_context yield) {
379              do_start_async_method_call_one(conn, yield);
380          },
381          boost::asio::detached);
382      (void)boost::asio::spawn(
383          io,
384          [conn](boost::asio::yield_context yield) {
385              do_start_async_ipmi_call(conn, yield);
386          },
387          boost::asio::detached);
388      (void)boost::asio::spawn(
389          io,
390          [conn](boost::asio::yield_context yield) {
391              do_start_async_to_yield(conn, yield);
392          },
393          boost::asio::detached);
394  
395      conn->async_method_call(
396          [](boost::system::error_code ec, int32_t testValue) {
397              if (ec)
398              {
399                  std::cerr << "TestYieldFunction returned error with "
400                               "async_method_call (ec = "
401                            << ec << ")\n";
402                  return;
403              }
404              std::cout << "TestYieldFunction return " << testValue << "\n";
405          },
406          "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
407          "xyz.openbmc_project.test", "TestYieldFunction", int32_t(41));
408      io.run();
409  
410      return 0;
411  }
412  
main(int argc,const char * argv[])413  int main(int argc, const char* argv[])
414  {
415      if (argc == 1)
416      {
417          int pid = fork();
418          if (pid == 0)
419          {
420              return client();
421          }
422          else if (pid > 0)
423          {
424              return server();
425          }
426          return pid;
427      }
428      if (std::string(argv[1]) == "--server")
429      {
430          return server();
431      }
432      if (std::string(argv[1]) == "--client")
433      {
434          return client();
435      }
436      std::cout << "usage: " << argv[0] << " [--server | --client]\n";
437      return -1;
438  }
439