summaryrefslogtreecommitdiff
path: root/src/CommonAPI/DBus/DBusServiceRegistry.h
blob: 09f020afed1f9c36a1861602ff00bb65db6a9915 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/* Copyright (C) 2013 BMW Group
 * Author: Manfred Bathelt (manfred.bathelt@bmw.de)
 * Author: Juergen Gehring (juergen.gehring@bmw.de)
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#if !defined (COMMONAPI_INTERNAL_COMPILATION)
#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents."
#endif

#ifndef COMMONAPI_DBUS_DBUS_SERVICE_REGISTRY_H_
#define COMMONAPI_DBUS_DBUS_SERVICE_REGISTRY_H_

#include <CommonAPI/types.h>
#include <CommonAPI/Attribute.h>
#include <CommonAPI/Proxy.h>
#include <CommonAPI/Factory.h>

#include "DBusProxyConnection.h"
#include "DBusAddressTranslator.h"
#include "DBusDaemonProxy.h"

#include "pugixml/pugixml.hpp"

#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <map>
#include <unordered_set>
#include <string>
#include <vector>
#include <memory>
#include <list>
#include <algorithm>
#include <set>

#include <condition_variable>
#include <mutex>
#include <future>

namespace CommonAPI {
namespace DBus {

typedef Event<std::string, std::string, std::string> NameOwnerChangedEvent;
typedef Event<std::string, std::string, std::string>::Subscription NameOwnerChangedEventSubscription;

//connectionName, objectPath
typedef std::pair<std::string, std::string> DBusInstanceId;

class DBusProxyConnection;
class DBusDaemonProxy;

class DBusServiceRegistry: public std::enable_shared_from_this<DBusServiceRegistry>,
                           public DBusProxyConnection::DBusSignalHandler {
 public:
    enum class DBusRecordState {
        UNKNOWN,
        AVAILABLE,
        RESOLVING,
        RESOLVED,
        NOT_AVAILABLE
    };

    // template class DBusServiceListener<> { typedef functor; typedef list; typedef subscription }
    typedef std::function<SubscriptionStatus(const AvailabilityStatus& availabilityStatus)> DBusServiceListener;
    typedef std::list<DBusServiceListener> DBusServiceListenerList;
    typedef DBusServiceListenerList::iterator DBusServiceSubscription;


    typedef std::function<SubscriptionStatus(const std::vector<std::string>& interfaces,
                                             const AvailabilityStatus& availabilityStatus)> DBusManagedInterfaceListener;
    typedef std::list<DBusManagedInterfaceListener> DBusManagedInterfaceListenerList;
    typedef DBusManagedInterfaceListenerList::iterator DBusManagedInterfaceSubscription;


    DBusServiceRegistry(std::shared_ptr<DBusProxyConnection> dbusProxyConnection);

    DBusServiceRegistry(const DBusServiceRegistry&) = delete;
    DBusServiceRegistry& operator=(const DBusServiceRegistry&) = delete;

    virtual ~DBusServiceRegistry();

    void init();


    DBusServiceSubscription subscribeAvailabilityListener(const std::string& commonApiAddress,
                                                          DBusServiceListener serviceListener);

    void unsubscribeAvailabilityListener(const std::string& commonApiAddress,
                                         DBusServiceSubscription& listenerSubscription);


    bool isServiceInstanceAlive(const std::string& dbusInterfaceName,
                                const std::string& dbusConnectionName,
                                const std::string& dbusObjectPath);


    virtual std::vector<std::string> getAvailableServiceInstances(const std::string& interfaceName,
                                                                  const std::string& domainName = "local");

    virtual void getAvailableServiceInstancesAsync(Factory::GetAvailableServiceInstancesCallback callback,
                                                   const std::string& interfaceName,
                                                   const std::string& domainName = "local");


    virtual SubscriptionStatus onSignalDBusMessage(const DBusMessage&);

//    std::vector<std::string> getManagedObjects(const std::string& connectionName, const std::string& objectpath);

 private:
    struct DBusInterfaceNameListenersRecord {
        DBusInterfaceNameListenersRecord(): state(DBusRecordState::UNKNOWN) {
        }

        DBusInterfaceNameListenersRecord(DBusInterfaceNameListenersRecord&& other):
            state(other.state),
            listenerList(std::move(other.listenerList))
        {
        }

        DBusRecordState state;
        DBusServiceListenerList listenerList;
    };

    typedef std::unordered_map<std::string, DBusInterfaceNameListenersRecord> DBusInterfaceNameListenersMap;

    struct DBusServiceListenersRecord {
        DBusServiceListenersRecord(): uniqueBusNameState(DBusRecordState::UNKNOWN),
                        //futureOnResolve(),
                        mutexOnResolve() {
        }

        DBusServiceListenersRecord(DBusServiceListenersRecord&& other):
            uniqueBusNameState(other.uniqueBusNameState),
            uniqueBusName(std::move(other.uniqueBusName)),
            promiseOnResolve(std::move(other.promiseOnResolve)),
            futureOnResolve(std::move(other.futureOnResolve)),
            mutexOnResolve(std::move(other.mutexOnResolve)),
            dbusObjectPathListenersMap(std::move(other.dbusObjectPathListenersMap))
        {
            /*other.uniqueBusName = NULL;
            other.promiseOnResolve = NULL;
            other.futureOnResolve = NULL;
            other.mutexOnResolve = NULL;
            other.dbusObjectPathListenersMap = NULL;
            other.dbusServiceListenersMap = NULL;*/
        }

        ~DBusServiceListenersRecord() {};

        DBusRecordState uniqueBusNameState;
        std::string uniqueBusName;

        std::promise<DBusRecordState> promiseOnResolve;
        std::shared_future<DBusRecordState> futureOnResolve;
        std::unique_lock<std::mutex>* mutexOnResolve;

        std::unordered_map<std::string, DBusInterfaceNameListenersMap> dbusObjectPathListenersMap;

        /* per manager records: anser commonapi queries and update after dbus GetManagedObjects */
//        typedef std::unordered_set<std::string> DBusObjectPathsSet;
//        typedef std::pair<DBusObjectPathsSet, DBusManagedInterfaceListenerList> DBusManagedInterfaceRecord;
//        typedef std::unordered_map<std::string, DBusManagedInterfaceRecord> DBusManagedInterfacesMap;
//        typedef std::pair<DBusRecordState, DBusManagedInterfacesMap> DBusObjectManagerRecord;
//        std::unordered_map<std::string, DBusObjectManagerRecord> dbusObjectManagersMap;
    };

    std::unordered_map<std::string, DBusServiceListenersRecord> dbusServiceListenersMap;


    struct DBusObjectPathCache {
        DBusObjectPathCache(): referenceCount(0), state(DBusRecordState::UNKNOWN) {
        }

        DBusObjectPathCache(DBusObjectPathCache&& other):
            referenceCount(other.referenceCount),
            state(other.state),
            promiseOnResolve(std::move(other.promiseOnResolve)),
            dbusInterfaceNamesCache(std::move(other.dbusInterfaceNamesCache))
        {
            /*other.promiseOnResolve = NULL;
            other.dbusInterfaceNamesCache = NULL;*/
        }

        ~DBusObjectPathCache() {}

        size_t referenceCount;
        DBusRecordState state;
        std::promise<DBusRecordState> promiseOnResolve;

        std::unordered_set<std::string> dbusInterfaceNamesCache;
    };

    struct DBusUniqueNameRecord {
        DBusUniqueNameRecord(): objectPathsState(DBusRecordState::UNKNOWN) {
        }

        DBusUniqueNameRecord(DBusUniqueNameRecord&& other) :
            uniqueName(std::move(other.uniqueName)),
            objectPathsState(other.objectPathsState),
            ownedBusNames(std::move(other.ownedBusNames)),
            dbusObjectPathsCache(std::move(other.dbusObjectPathsCache))
        {
            /*other.uniqueName = NULL;
            other.ownedBusNames = NULL;
            other.dbusObjectPathsCache = NULL;*/
        }
        std::string uniqueName;
        DBusRecordState objectPathsState;
        std::unordered_set<std::string> ownedBusNames;
        std::unordered_map<std::string, DBusObjectPathCache> dbusObjectPathsCache;

        // TODO managed objects
    };

    std::unordered_map<std::string, DBusUniqueNameRecord> dbusUniqueNamesMap_;
    typedef std::unordered_map<std::string, DBusUniqueNameRecord>::iterator DBusUniqueNamesMapIterator;

    // mapping service names (well-known names) to service instances
    std::unordered_map<std::string, DBusUniqueNameRecord*> dbusServiceNameMap_;


    // protects the dbus service maps
    std::mutex dbusServicesMutex_;


    void resolveDBusServiceName(const std::string& dbusServiceName,
                                DBusServiceListenersRecord& dbusServiceListenersRecord);

    void onGetNameOwnerCallback(const CallStatus& status, std::string dbusServiceUniqueName, const std::string& dbusServiceName);


    DBusRecordState resolveDBusInterfaceNameState(const std::string& dbusInterfaceName,
                                                  const std::string& dbusObjectPath,
                                                  const std::string& dbusServiceName,
                                                  DBusServiceListenersRecord& dbusServiceListenersRecord);


    DBusObjectPathCache& getDBusObjectPathCacheReference(const std::string& dbusObjectPath,
                                                         const std::string& dbusServiceUniqueName,
                                                         DBusUniqueNameRecord& dbusUniqueNameRecord);

    void releaseDBusObjectPathCacheReference(const std::string& dbusObjectPath,
                                             const DBusServiceListenersRecord& dbusServiceListenersRecord);


    bool introspectDBusObjectPath(const std::string& dbusServiceUniqueName, const std::string& dbusObjectPath);

    void onIntrospectCallback(const CallStatus& status,
                              std::string xmlData,
                              const std::string& dbusServiceName,
                              const std::string& dbusObjectPath);

    void parseIntrospectionData(const std::string& xmlData,
                                const std::string& rootObjectPath,
                                const std::string& dbusServiceUniqueName);

    void parseIntrospectionNode(const pugi::xml_node& node,
                                const std::string& rootObjectPath,
                                const std::string& fullObjectPath,
                                const std::string& dbusServiceUniqueName);

    void processIntrospectionObjectPath(const pugi::xml_node& node,
                                        const std::string& rootObjectPath,
                                        const std::string& dbusServiceUniqueName);

    void processIntrospectionInterface(const pugi::xml_node& node,
                                       const std::string& rootObjectPath,
                                       const std::string& fullObjectPath,
                                       const std::string& dbusServiceUniqueName);

    SubscriptionStatus onDBusDaemonProxyStatusEvent(const AvailabilityStatus& availabilityStatus);

    SubscriptionStatus onDBusDaemonProxyNameOwnerChangedEvent(const std::string& name,
                                                              const std::string& oldOwner,
                                                              const std::string& newOwner);

    std::shared_ptr<DBusDaemonProxy> dbusDaemonProxy_;
    bool initialized_;

    ProxyStatusEvent::Subscription dbusDaemonProxyStatusEventSubscription_;
    NameOwnerChangedEvent::Subscription dbusDaemonProxyNameOwnerChangedEventSubscription_;


    void checkDBusServiceWasAvailable(const std::string& dbusServiceName, const std::string& dbusServiceUniqueName);

    void onDBusServiceAvailable(const std::string& dbusServiceName, const std::string& dbusServiceUniqueName);

    void onDBusServiceNotAvailable(DBusServiceListenersRecord& dbusServiceListenersRecord);


    void notifyDBusServiceListeners(const DBusUniqueNameRecord& dbusUniqueNameRecord,
                                    const std::string& dbusObjectPath,
                                    const std::unordered_set<std::string>& dbusInterfaceNames,
                                    const DBusRecordState& dbusInterfaceNamesState);

    void notifyDBusObjectPathResolved(DBusInterfaceNameListenersMap& dbusInterfaceNameListenersMap,
                                      const std::unordered_set<std::string>& dbusInterfaceNames);

    void notifyDBusObjectPathChanged(DBusInterfaceNameListenersMap& dbusInterfaceNameListenersMap,
                                     const std::unordered_set<std::string>& dbusInterfaceNames,
                                     const DBusRecordState& dbusInterfaceNamesState);

    void notifyDBusInterfaceNameListeners(DBusInterfaceNameListenersRecord& dbusInterfaceNameListenersRecord,
                                          const bool& isDBusInterfaceNameAvailable);


    void removeUniqueName(const DBusUniqueNamesMapIterator& dbusUniqueName);
    DBusUniqueNameRecord* insertServiceNameMapping(const std::string& dbusUniqueName, const std::string& dbusServiceName);
    bool findCachedDbusService(const std::string& dbusServiceName, DBusUniqueNameRecord** uniqueNameRecord);
    bool findCachedObjectPath(const std::string& dbusObjectPathName, const DBusUniqueNameRecord* uniqueNameRecord, DBusObjectPathCache* objectPathCache);

    std::condition_variable monitorResolveAllServices_;
    std::mutex mutexServiceResolveCount;
    int servicesToResolve;

    std::condition_variable monitorResolveAllObjectPaths_;
    std::mutex mutexObjectPathsResolveCount;
    int objectPathsToResolve;


    void fetchAllServiceNames();

    inline const bool isDBusServiceName(const std::string& serviceName) {
        return (serviceName.length() > 0 && serviceName[0] != ':');
    };


    inline const bool isOrgFreedesktopDBusInterface(const std::string& dbusInterfaceName) {
        return dbusInterfaceName.find("org.freedesktop.") == 0;
    }

    std::thread::id notificationThread_;
};


} // namespace DBus
} // namespace CommonAPI

#endif // COMMONAPI_DBUS_DBUS_SERVICE_REGISTRY_H_