Provide access to D-Bus message in high-level API

This commit is contained in:
Stanislav Angelovic
2021-06-02 15:17:20 +00:00
committed by Urs Ritzmann
parent 75ea127374
commit e16ffb1288
14 changed files with 205 additions and 28 deletions

View File

@ -437,7 +437,7 @@ Thus, in the end of the day, the code written using the convenience API is:
- significantly shorter,
- almost as fast as one written using the basic API layer.
The code written using this layer expresses in a declarative way *what* it does, rather then *how*. Let's look at code samples.
The code written using this layer expresses in a declarative way *what* it does, rather than *how*. Let's look at code samples.
### Server side
@ -446,30 +446,6 @@ The code written using this layer expresses in a declarative way *what* it does,
#include <vector>
#include <string>
// Yeah, global variable is ugly, but this is just an example and we want to access
// the concatenator instance from within the concatenate method handler to be able
// to emit signals.
sdbus::IObject* g_concatenator{};
std::string concatenate(const std::vector<int> numbers, const std::string& separator)
{
// Return error if there are no numbers in the collection
if (numbers.empty())
throw sdbus::Error("org.sdbuscpp.Concatenator.Error", "No numbers provided");
std::string result;
for (auto number : numbers)
{
result += (result.empty() ? std::string() : separator) + std::to_string(number);
}
// Emit 'concatenated' signal
const char* interfaceName = "org.sdbuscpp.Concatenator";
g_concatenator->emitSignal("concatenated").onInterface(interfaceName).withArguments(result);
return result;
}
int main(int argc, char *argv[])
{
// Create D-Bus connection to the system bus and requests name on it.
@ -479,12 +455,29 @@ int main(int argc, char *argv[])
// Create concatenator D-Bus object.
const char* objectPath = "/org/sdbuscpp/concatenator";
auto concatenator = sdbus::createObject(*connection, objectPath);
auto concatenate = [&concatenator](const std::vector<int> numbers, const std::string& separator)
{
// Return error if there are no numbers in the collection
if (numbers.empty())
throw sdbus::Error("org.sdbuscpp.Concatenator.Error", "No numbers provided");
g_concatenator = concatenator.get();
std::string result;
for (auto number : numbers)
{
result += (result.empty() ? std::string() : separator) + std::to_string(number);
}
// Emit 'concatenated' signal
const char* interfaceName = "org.sdbuscpp.Concatenator";
concatenator->emitSignal("concatenated").onInterface(interfaceName).withArguments(result);
return result;
};
// Register D-Bus methods and signals on the concatenator object, and exports the object.
const char* interfaceName = "org.sdbuscpp.Concatenator";
concatenator->registerMethod("concatenate").onInterface(interfaceName).implementedAs(&concatenate);
concatenator->registerMethod("concatenate").onInterface(interfaceName).implementedAs(std::move(concatenate));
concatenator->registerSignal("concatenated").onInterface(interfaceName).withParameters<std::string>();
concatenator->finishRegistration();
@ -560,6 +553,30 @@ Tip: When registering a D-Bus object, we can additionally provide names of input
concatenator->registerSignal("concatenated").onInterface(interfaceName).withParameters<std::string>("concatenatedString");
```
### Accessing a corresponding D-Bus message
The convenience API hides away the level of D-Bus messages. But the messages carry with them additional information that may need in some implementations. For example, a name of a method call sender; or info on credentials. Is there a way to access a corresponding D-Bus message in a high-level callback handler?
Yes, there is -- we can access the corresponding D-Bus message in:
* method implementation callback handlers (server side),
* property set implementation callback handlers (server side),
* signal callback handlers (client side).
Both `IObject` and `IProxy` provide the `getCurrentlyProcessedMessage()` method. This method is meant to be called from within a callback handler. It returns a pointer to the corresponding D-Bus message that caused invocation of the handler. The pointer is only valid (dereferencable) as long as the flow of execution does not leave the callback handler. When called from other contexts/threads, the pointer may be both zero or non-zero, and its dereferencing is undefined behavior.
An excerpt of the above example of concatenator modified to print out a name of the sender of method call:
```c++
auto concatenate = [&concatenator](const std::vector<int> numbers, const std::string& separator)
{
const auto* methodCallMsg = concatenator->getCurrentlyProcessedMessage();
std::cout << "Sender of this method call: " << methodCallMsg.getSender() << std::endl;
/*...*/
};
```
Implementing the Concatenator example using sdbus-c++-generated stubs
---------------------------------------------------------------------
@ -755,6 +772,8 @@ protected:
};
```
Tip: By inheriting from `sdbus::AdaptorInterfaces`, we get access to the protected `getObject()` method. We can call this method inside our adaptor implementation class to access the underlying `IObject` object.
That's it. We now have an implementation of a D-Bus object implementing `org.sdbuscpp.Concatenator` interface. Let's now create a service publishing the object.
```cpp
@ -817,6 +836,8 @@ protected:
};
```
Tip: By inheriting from `sdbus::ProxyInterfaces`, we get access to the protected `getProxy()` method. We can call this method inside our proxy implementation class to access the underlying `IProxy` object.
In the above example, a proxy is created that creates and maintains its own system bus connection. However, there are `ProxyInterfaces` class template constructor overloads that also take the connection from the user as the first parameter, and pass that connection over to the underlying proxy. The connection instance is used by all interfaces listed in the `ProxyInterfaces` template parameter list.
Note however that there are multiple `ProxyInterfaces` constructor overloads, and they differ in how the proxy behaves towards the D-Bus connection. These overloads precisely map the `sdbus::createProxy` overloads, as they are actually implemented on top of them. See [Proxy and D-Bus connection](#Proxy-and-D-Bus-connection) for more info. We can even create a `IProxy` instance on our own, and inject it into our proxy class -- there is a constructor overload for it in `ProxyInterfaces`. This can help if we need to provide mocked implementations in our unit tests.
@ -859,6 +880,27 @@ int main(int argc, char *argv[])
}
```
### Accessing a corresponding D-Bus message
Simply combine `getObject()`/`getProxy()` and `getCurrentlyProcessedMessage()` methods. Both were already discussed above. An example:
```c++
class Concatenator : public sdbus::AdaptorInterfaces</*...*/>
{
public:
/*...*/
protected:
std::string concatenate(const std::vector<int32_t>& numbers, const std::string& separator) override
{
const auto* methodCallMsg = getObject().getCurrentlyProcessedMessage();
std::cout << "Sender of this method call: " << methodCallMsg.getSender() << std::endl;
/*...*/
}
};
```
Asynchronous server-side methods
--------------------------------

View File

@ -440,6 +440,22 @@ namespace sdbus {
* @brief Returns object path of the underlying DBus object
*/
virtual const std::string& getObjectPath() const = 0;
/*!
* @brief Provides currently processed D-Bus message
*
* This method provides immutable access to the currently processed incoming D-Bus message.
* "Currently processed" means that the registered callback handler(s) for that message
* are being invoked. This method is meant to be called from within a callback handler
* (e.g. D-Bus method implementation handler). In such a case it is guaranteed to return
* a valid pointer to the D-Bus message for which the handler is called. If called from other
* contexts/threads, it may return a nonzero pointer or a nullptr, depending on whether a message
* was processed at the time of call or not, but the value is nondereferencable, since the pointed-to
* message may have gone in the meantime.
*
* @return A pointer to the currently processed D-Bus message
*/
virtual const Message* getCurrentlyProcessedMessage() const = 0;
};
// Out-of-line member definitions

View File

@ -278,6 +278,22 @@ namespace sdbus {
* @brief Returns object path of the underlying DBus object
*/
virtual const std::string& getObjectPath() const = 0;
/*!
* @brief Provides currently processed D-Bus message
*
* This method provides immutable access to the currently processed incoming D-Bus message.
* "Currently processed" means that the registered callback handler(s) for that message
* are being invoked. This method is meant to be called from within a callback handler
* (e.g. from a D-Bus signal handler, or async method reply handler, etc.). In such a case it is
* guaranteed to return a valid pointer to the D-Bus message for which the handler is called.
* If called from other contexts/threads, it may return a nonzero pointer or a nullptr, depending
* on whether a message was processed at the time of call or not, but the value is nondereferencable,
* since the pointed-to message may have gone in the meantime.
*
* @return A pointer to the currently processed D-Bus message
*/
virtual const Message* getCurrentlyProcessedMessage() const = 0;
};
/********************************************//**

View File

@ -31,6 +31,7 @@
#include <sdbus-c++/Error.h>
#include <sdbus-c++/MethodResult.h>
#include <sdbus-c++/Flags.h>
#include "ScopeGuard.h"
#include "IConnection.h"
#include "VTableUtils.h"
#include <systemd/sd-bus.h>
@ -230,6 +231,11 @@ const std::string& Object::getObjectPath() const
return objectPath_;
}
const Message* Object::getCurrentlyProcessedMessage() const
{
return m_CurrentlyProcessedMessage.load(std::memory_order_relaxed);
}
const std::vector<sd_bus_vtable>& Object::createInterfaceVTable(InterfaceData& interfaceData)
{
auto& vtable = interfaceData.vtable;
@ -317,13 +323,19 @@ int Object::sdbus_method_callback(sd_bus_message *sdbusMessage, void *userData,
auto message = Message::Factory::create<MethodCall>(sdbusMessage, &object->connection_.getSdBusInterface());
object->m_CurrentlyProcessedMessage.store(&message, std::memory_order_relaxed);
SCOPE_EXIT
{
object->m_CurrentlyProcessedMessage.store(nullptr, std::memory_order_relaxed);
};
// Note: The lookup can be optimized by using sorted vectors instead of associative containers
auto& callback = object->interfaces_[message.getInterfaceName()].methods[message.getMemberName()].callback;
assert(callback);
try
{
callback(std::move(message));
callback(message);
}
catch (const sdbus::Error& e)
{
@ -384,6 +396,12 @@ int Object::sdbus_property_set_callback( sd_bus */*bus*/
auto value = Message::Factory::create<PropertySetCall>(sdbusValue, &object->connection_.getSdBusInterface());
object->m_CurrentlyProcessedMessage.store(&value, std::memory_order_relaxed);
SCOPE_EXIT
{
object->m_CurrentlyProcessedMessage.store(nullptr, std::memory_order_relaxed);
};
try
{
callback(value);

View File

@ -35,6 +35,7 @@
#include <vector>
#include <functional>
#include <memory>
#include <atomic>
#include <cassert>
namespace sdbus::internal {
@ -102,6 +103,7 @@ namespace sdbus::internal {
sdbus::IConnection& getConnection() const override;
const std::string& getObjectPath() const override;
const Message* getCurrentlyProcessedMessage() const override;
private:
using InterfaceName = std::string;
@ -170,6 +172,7 @@ namespace sdbus::internal {
std::string objectPath_;
std::map<InterfaceName, InterfaceData> interfaces_;
SlotPtr objectManagerSlot_;
std::atomic<const Message*> m_CurrentlyProcessedMessage{nullptr};
};
}

View File

@ -209,6 +209,11 @@ const std::string& Proxy::getObjectPath() const
return objectPath_;
}
const Message* Proxy::getCurrentlyProcessedMessage() const
{
return m_CurrentlyProcessedMessage.load(std::memory_order_relaxed);
}
int Proxy::sdbus_async_reply_handler(sd_bus_message *sdbusMessage, void *userData, sd_bus_error */*retError*/)
{
auto* asyncCallData = static_cast<AsyncCalls::CallData*>(userData);
@ -229,6 +234,12 @@ int Proxy::sdbus_async_reply_handler(sd_bus_message *sdbusMessage, void *userDat
auto message = Message::Factory::create<MethodReply>(sdbusMessage, &proxy.connection_->getSdBusInterface());
proxy.m_CurrentlyProcessedMessage.store(&message, std::memory_order_relaxed);
SCOPE_EXIT
{
proxy.m_CurrentlyProcessedMessage.store(nullptr, std::memory_order_relaxed);
};
const auto* error = sd_bus_message_get_error(sdbusMessage);
if (error == nullptr)
{
@ -250,6 +261,13 @@ int Proxy::sdbus_signal_handler(sd_bus_message *sdbusMessage, void *userData, sd
assert(signalData->callback);
auto message = Message::Factory::create<Signal>(sdbusMessage, &signalData->proxy.connection_->getSdBusInterface());
signalData->proxy.m_CurrentlyProcessedMessage.store(&message, std::memory_order_relaxed);
SCOPE_EXIT
{
signalData->proxy.m_CurrentlyProcessedMessage.store(nullptr, std::memory_order_relaxed);
};
signalData->callback(message);
return 0;
}

View File

@ -35,6 +35,7 @@
#include <map>
#include <unordered_map>
#include <mutex>
#include <atomic>
#include <condition_variable>
namespace sdbus::internal {
@ -62,6 +63,7 @@ namespace sdbus::internal {
sdbus::IConnection& getConnection() const override;
const std::string& getObjectPath() const override;
const Message* getCurrentlyProcessedMessage() const override;
private:
class SyncCallReplyData
@ -173,6 +175,8 @@ namespace sdbus::internal {
std::mutex mutex_;
std::unordered_map<void*, std::shared_ptr<CallData>> calls_;
} pendingAsyncCalls_;
std::atomic<const Message*> m_CurrentlyProcessedMessage{nullptr};
};
}

View File

@ -45,6 +45,7 @@ using ::testing::Gt;
using ::testing::AnyOf;
using ::testing::ElementsAre;
using ::testing::SizeIs;
using ::testing::NotNull;
using namespace std::chrono_literals;
using namespace sdbus::test;
@ -238,6 +239,22 @@ TEST_F(SdbusTestObject, CanReceiveSignalWhileMakingMethodCall)
ASSERT_TRUE(waitUntil(m_proxy->m_gotSignalWithMap));
}
TEST_F(SdbusTestObject, CanAccessAssociatedMethodCallMessageInMethodCallHandler)
{
m_proxy->doOperation(10); // This will save pointer to method call message on server side
ASSERT_THAT(m_adaptor->m_methodCallMsg, NotNull());
ASSERT_THAT(m_adaptor->m_methodCallMemberName, Eq("doOperation"));
}
TEST_F(SdbusTestObject, CanAccessAssociatedMethodCallMessageInAsyncMethodCallHandler)
{
m_proxy->doOperationAsync(10); // This will save pointer to method call message on server side
ASSERT_THAT(m_adaptor->m_methodCallMsg, NotNull());
ASSERT_THAT(m_adaptor->m_methodCallMemberName, Eq("doOperationAsync"));
}
#if LIBSYSTEMD_VERSION>=240
TEST_F(SdbusTestObject, CanSetGeneralMethodTimeoutWithLibsystemdVersionGreaterThan239)
{

View File

@ -45,6 +45,9 @@ using ::testing::Gt;
using ::testing::AnyOf;
using ::testing::ElementsAre;
using ::testing::SizeIs;
using ::testing::NotNull;
using ::testing::Not;
using ::testing::IsEmpty;
using namespace std::chrono_literals;
using namespace sdbus::test;
@ -72,3 +75,11 @@ TEST_F(SdbusTestObject, WritesAndReadsReadWritePropertySuccesfully)
ASSERT_THAT(m_proxy->action(), Eq(newActionValue));
}
TEST_F(SdbusTestObject, CanAccessAssociatedPropertySetMessageInPropertySetHandler)
{
m_proxy->blocking(true); // This will save pointer to property get message on server side
ASSERT_THAT(m_adaptor->m_propertySetMsg, NotNull());
ASSERT_THAT(m_adaptor->m_propertySetSender, Not(IsEmpty()));
}

View File

@ -39,6 +39,7 @@ using ::testing::Gt;
using ::testing::AnyOf;
using ::testing::ElementsAre;
using ::testing::SizeIs;
using ::testing::NotNull;
using namespace std::chrono_literals;
using namespace sdbus::test;
@ -103,3 +104,13 @@ TEST_F(SdbusTestObject, EmitsSignalWithoutRegistrationSuccesfully)
ASSERT_TRUE(waitUntil(m_proxy->m_gotSignalWithSignature));
ASSERT_THAT(m_proxy->m_signatureFromSignal["platform"], Eq("av"));
}
TEST_F(SdbusTestObject, CanAccessAssociatedSignalMessageInSignalHandler)
{
m_adaptor->emitSimpleSignal();
waitUntil(m_proxy->m_gotSimpleSignal);
ASSERT_THAT(m_proxy->m_signalMsg, NotNull());
ASSERT_THAT(m_proxy->m_signalMemberName, Eq("simpleSignal"));
}

View File

@ -121,11 +121,18 @@ uint32_t TestAdaptor::sumVectorItems(const std::vector<uint16_t>& a, const std::
uint32_t TestAdaptor::doOperation(const uint32_t& param)
{
std::this_thread::sleep_for(std::chrono::milliseconds(param));
m_methodCallMsg = getObject().getCurrentlyProcessedMessage();
m_methodCallMemberName = m_methodCallMsg->getMemberName();
return param;
}
void TestAdaptor::doOperationAsync(sdbus::Result<uint32_t>&& result, uint32_t param)
{
m_methodCallMsg = getObject().getCurrentlyProcessedMessage();
m_methodCallMemberName = m_methodCallMsg->getMemberName();
if (param == 0)
{
// Don't sleep and return the result from this thread
@ -227,6 +234,9 @@ bool TestAdaptor::blocking()
void TestAdaptor::blocking(const bool& value)
{
m_propertySetMsg = getObject().getCurrentlyProcessedMessage();
m_propertySetSender = m_propertySetMsg->getSender();
m_blocking = value;
}

View File

@ -86,6 +86,11 @@ public: // for tests
mutable std::atomic<bool> m_wasMultiplyCalled{false};
mutable double m_multiplyResult{};
mutable std::atomic<bool> m_wasThrowErrorCalled{false};
const Message* m_methodCallMsg{};
std::string m_methodCallMemberName;
const Message* m_propertySetMsg{};
std::string m_propertySetSender;
};
}}

View File

@ -54,6 +54,9 @@ TestProxy::~TestProxy()
void TestProxy::onSimpleSignal()
{
m_signalMsg = getProxy().getCurrentlyProcessedMessage();
m_signalMemberName = m_signalMsg->getMemberName();
m_gotSimpleSignal = true;
}

View File

@ -87,6 +87,9 @@ public: // for tests
std::function<void(const std::string&, const std::map<std::string, sdbus::Variant>&, const std::vector<std::string>&)> m_onPropertiesChangedHandler;
std::function<void(const sdbus::ObjectPath&, const std::map<std::string, std::map<std::string, sdbus::Variant>>&)> m_onInterfacesAddedHandler;
std::function<void(const sdbus::ObjectPath&, const std::vector<std::string>&)> m_onInterfacesRemovedHandler;
const Message* m_signalMsg{};
std::string m_signalMemberName;
};
}}