summaryrefslogtreecommitdiff
path: root/mapperx/src/main.cpp
blob: f2434a3fb44e7a3f1ed78c484017fd0cb3309970 (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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
#include <tinyxml2.h>
#include <atomic>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/container/flat_map.hpp>
#include <boost/container/flat_set.hpp>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <sdbusplus/asio/connection.hpp>
#include <sdbusplus/asio/object_server.hpp>

// interface map type is the underlying datastructure the mapper uses.
// The 3 levels of map are
// object paths
//   connection names
//      interface names
using interface_map_type = boost::container::flat_map<
    std::string, boost::container::flat_map<
                     std::string, boost::container::flat_set<std::string>>>;

struct InProgressIntrospect
{
    std::string process_name;
    std::chrono::time_point<std::chrono::steady_clock> process_start_time;
    std::shared_ptr<std::chrono::time_point<std::chrono::steady_clock>>
        global_start_time;
};

struct cmp_str
{
    bool operator()(const char* a, const char* b) const
    {
        return std::strcmp(a, b) < 0;
    }
};

static const boost::container::flat_set<const char*, cmp_str>
    ignored_interfaces{"org.freedesktop.DBus.Introspectable",
                       "org.freedesktop.DBus.Peer",
                       "org.freedesktop.DBus.Properties"};

inline bool should_scan_dbus_interface(const std::string& process_name)
{
    return boost::starts_with(process_name, "xyz.openbmc_project.") ||
           boost::starts_with(process_name, "org.openbmc.") ||
           boost::starts_with(process_name, "com.intel.");
}

void do_introspect(sdbusplus::asio::connection* system_bus,
                   std::shared_ptr<InProgressIntrospect> transaction,
                   interface_map_type& interface_map, std::string path)
{
    system_bus->async_method_call(
        [&, transaction, path, system_bus](const boost::system::error_code ec,
                                           const std::string& introspect_xml) {
            if (ec)
            {
                std::cerr << "Introspect call failed with error: "
                          << ec.message()
                          << " on process: " << transaction->process_name
                          << " path: " << path << "\n";
            }
            else
            {
                tinyxml2::XMLDocument doc;

                doc.Parse(introspect_xml.c_str());
                tinyxml2::XMLNode* pRoot = doc.FirstChildElement("node");
                if (pRoot == nullptr)
                {
                    std::cerr << "XML document did not contain any data\n";
                }
                else
                {
                    tinyxml2::XMLElement* pElement =
                        pRoot->FirstChildElement("node");
                    while (pElement != nullptr)
                    {
                        std::string child_path = pElement->Attribute("name");
                        if (child_path.empty())
                        {
                            continue;
                        }
                        else
                        {
                            std::string parent_path(path);
                            if (parent_path == "/")
                            {
                                parent_path.clear();
                            }
                            do_introspect(system_bus, transaction,
                                          interface_map,
                                          parent_path + "/" + child_path);
                        }
                        pElement = pElement->NextSiblingElement("node");
                    }

                    pElement = pRoot->FirstChildElement("interface");
                    while (pElement != nullptr)
                    {
                        std::string iface_name = pElement->Attribute("name");
                        if (iface_name.empty())
                        {
                            continue;
                        }
                        else
                        {
                            if (ignored_interfaces.find(iface_name.c_str()) ==
                                ignored_interfaces.end())
                            {
                                interface_map[path][transaction->process_name]
                                    .emplace(iface_name);
                            }
                            if (iface_name ==
                                "xyz.openbmc_project.Associations")
                            {
                                // get association
                            }
                        }
                        pElement = pElement->NextSiblingElement("interface");
                    }
                }
            }
            // if we're the last outstanding caller for this process
            if (transaction.use_count() == 1)
            {
                // TODO(ed) This signal doesn't get exposed properly in the
                // introspect right now.  Find out how to register signals in
                // sdbusplus
                sdbusplus::message::message m = system_bus->new_signal(
                    "/xyz/openbmc_project/object_mapper",
                    "xyz.openbmc_project.ObjectMapper.Private",
                    "IntrospectionComplete");
                m.append(transaction->process_name);
                system_bus->call_noreply(m);
                std::chrono::duration<float> diff =
                    std::chrono::steady_clock::now() -
                    *transaction->global_start_time;
                std::cout << std::setw(40) << transaction->process_name
                          << " scan took " << diff.count() << " seconds\n";

                // If we're the last outstanding caller globally, calculate the
                // time it took
                if (transaction->global_start_time.use_count() == 1)
                {
                    diff = std::chrono::steady_clock::now() -
                           *transaction->global_start_time;
                    std::cout << "Total scan took " << diff.count()
                              << " seconds to complete\n";
                }
            }
        },
        transaction->process_name, path, "org.freedesktop.DBus.Introspectable",
        "Introspect");
}

void start_new_introspect(
    sdbusplus::asio::connection* system_bus, interface_map_type& interface_map,
    const std::string& process_name,
    std::shared_ptr<std::chrono::time_point<std::chrono::steady_clock>>
        global_start_time)
{
    auto transaction =
        std::make_shared<InProgressIntrospect>(InProgressIntrospect{
            process_name, std::chrono::steady_clock::now(), global_start_time});
    do_introspect(system_bus, transaction, interface_map, "/");
}

template <class InputIt1, class InputIt2>
bool intersect(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2)
{
    while (first1 != last1 && first2 != last2)
    {
        if (*first1 < *first2)
        {
            ++first1;
            continue;
        }
        if (*first2 < *first1)
        {
            ++first2;
            continue;
        }
        return true;
    }
    return false;
}

int main(int argc, char** argv)
{
    boost::asio::io_service io;
    auto system_bus = std::make_shared<sdbusplus::asio::connection>(io);
    system_bus->request_name("xyz.openbmc_project.ObjectMapperX");

    interface_map_type interface_map;

    std::function<void(sdbusplus::message::message & message)>
        nameChangeHandler = [&](sdbusplus::message::message& message) {
            std::string name;
            std::string old_owner;
            std::string new_owner;

            message.read(name, old_owner, new_owner);

            if (!new_owner.empty())
            {
                auto transaction = std::make_shared<
                    std::chrono::time_point<std::chrono::steady_clock>>(
                    std::chrono::steady_clock::now());
                if (should_scan_dbus_interface(new_owner))
                {
                    // New daemon added
                    start_new_introspect(system_bus.get(), interface_map,
                                         new_owner, transaction);
                }
            }
            if (!old_owner.empty())
            {
                // Connection removed
                interface_map_type::iterator path_it = interface_map.begin();
                while (path_it != interface_map.end())
                {
                    auto connection_it = path_it->second.find(old_owner);
                    if (connection_it != path_it->second.end())
                    {
                        if (connection_it->first == old_owner)
                        {
                            path_it->second.erase(connection_it);
                            break;
                        }
                    }
                    if (path_it->second.empty())
                    {
                        // If the last connection to the object is gone, delete
                        // the top level object
                        path_it = interface_map.erase(path_it);
                        continue;
                    }
                    path_it++;
                }
            }
            else
            {
                std::cerr << "ERROR: both new path and old path are empty";
            }
        };

    sdbusplus::bus::match::match nameOwnerChanged(
        *system_bus, sdbusplus::bus::match::rules::nameOwnerChanged(),
        nameChangeHandler);

    std::function<void(sdbusplus::message::message & message)>
        interfacesAddedHandler = [&](sdbusplus::message::message& message) {
            sdbusplus::message::object_path obj_path;
            std::vector<
                std::pair<std::string,
                          std::vector<std::pair<
                              std::string, sdbusplus::message::variant<bool>>>>>
                interfaces_added;
            message.read(obj_path, interfaces_added);
            const std::string& obj_str =
                static_cast<const std::string&>(obj_path);
            auto iface_list = interface_map[obj_str];
            for (const std::pair<
                     std::string,
                     std::vector<std::pair<std::string,
                                           sdbusplus::message::variant<bool>>>>&
                     interface_pair : interfaces_added)
            {
                iface_list[interface_pair.first].emplace(message.get_sender());
            }
        };

    sdbusplus::bus::match::match interfacesAdded(
        *system_bus, sdbusplus::bus::match::rules::interfacesAdded(),
        interfacesAddedHandler);

    std::function<void(sdbusplus::message::message & message)>
        interfacesRemovedHandler = [&](sdbusplus::message::message& message) {
            sdbusplus::message::object_path obj_path;
            std::vector<std::string> interfaces_removed;
            message.read(obj_path, interfaces_removed);
            const std::string& object_path_str =
                static_cast<const std::string&>(obj_path);
            auto connection_map = interface_map.find(object_path_str);
            if (connection_map == interface_map.end())
            {
                std::cerr << "Unable to find " << object_path_str
                          << " in map\n";
                return;
            }

            const std::string sender = std::string(message.get_sender());

            for (const std::string& interface : interfaces_removed)
            {
                auto interface_set = connection_map->second.find(sender);
                if (interface_set == connection_map->second.end())
                {
                    std::cerr << "Unable to find " << sender << " in map for "
                              << interface << "\n";
                    continue;
                }

                interface_set->second.erase(interface);
                // If this was the last interface on this connection, erase the
                // connection
                if (interface_set->second.empty())
                {
                    connection_map->second.erase(interface_set);
                }
            }
            // If this was the last connection on this object path, erase the
            // object path
            if (connection_map->second.empty())
            {
                interface_map.erase(connection_map);
            }
        };

    sdbusplus::bus::match::match interfacesRemoved(
        *system_bus, sdbusplus::bus::match::rules::interfacesRemoved(),
        interfacesRemovedHandler);

    // Set up the object server, and send some objects
    auto server = sdbusplus::asio::object_server(system_bus);

    std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
        server.add_interface("/xyz/openbmc_project/object_mapper",
                             "xyz.openbmc_project.ObjectMapper");

    iface->register_method(
        "GetAncestors",
        [&](const std::string& req_path, std::vector<std::string>& interfaces) {

            std::sort(interfaces.begin(), interfaces.end());

            std::vector<interface_map_type::value_type> ret;
            for (auto& object_path : interface_map)
            {
                auto& this_path = object_path.first;
                bool add = interfaces.empty();
                if (boost::starts_with(req_path, this_path))
                {
                    for (auto& interface_map : object_path.second)
                    {
                        add = intersect(interfaces.begin(), interfaces.end(),
                                        interface_map.second.begin(),
                                        interface_map.second.end());
                        if (add)
                        {
                            break;
                        }
                    }
                    if (add)
                    {
                        // THis makes a copy.  TODO(ed) make sdbusplus allow
                        // vectors of pointers so that this doesn't need to copy
                        // all strings
                        ret.emplace_back(object_path);
                    }
                }
            }

            return ret;
        });

    iface->register_method(
        "GetObject",
        [&](const std::string& path, std::vector<std::string>& interfaces) {
            std::sort(interfaces.begin(), interfaces.end());
            auto path_ref = interface_map.find(path);
            bool add = false;
            if (path_ref != interface_map.end())
            {
                add = interfaces.empty();
                for (auto& interface_map : path_ref->second)
                {
                    if (intersect(interfaces.begin(), interfaces.end(),
                                  interface_map.second.begin(),
                                  interface_map.second.end()))
                    {
                        add = true;
                        break;
                    }
                }
            }
            if (add)
            {
                return path_ref->second;
            }
            return decltype(path_ref->second){};
        });

    iface->register_method(
        "GetSubTree", [&](const std::string& req_path, int32_t depth,
                          std::vector<std::string>& interfaces) {
            std::sort(interfaces.begin(), interfaces.end());
            std::vector<interface_map_type::value_type> ret;

            for (auto& object_path : interface_map)
            {
                auto& this_path = object_path.first;
                if (boost::starts_with(this_path, req_path))
                {
                    // count the number of slashes past the search term
                    auto this_depth =
                        std::count(this_path.begin() + req_path.size(),
                                   this_path.end(), '/');
                    if (this_depth <= depth)
                    {
                        bool add = interfaces.empty();
                        for (auto& interface_map : object_path.second)
                        {
                            if (intersect(interfaces.begin(), interfaces.end(),
                                          interface_map.second.begin(),
                                          interface_map.second.end()))
                            {
                                add = true;
                                break;
                            }
                        }
                        if (add)
                        {
                            // todo(ed) this is a copy
                            ret.emplace_back(object_path);
                        }
                    }
                }
            }
            return ret;
        });
    iface->register_method(
        "GetSubTreePaths", [&](const std::string& req_path, int32_t depth,
                               const std::vector<std::string>& interfaces) {
            std::vector<std::string> ret;
            for (auto& object_path : interface_map)
            {
                auto& this_path = object_path.first;
                if (boost::starts_with(this_path, req_path))
                {
                    // count the number of slashes past the search term
                    auto this_depth =
                        std::count(this_path.begin() + req_path.size(),
                                   this_path.end(), '/');
                    if (this_depth <= depth)
                    {
                        bool add = interfaces.empty();
                        for (auto& interface_map : object_path.second)
                        {
                            if (intersect(interfaces.begin(), interfaces.end(),
                                          interface_map.second.begin(),
                                          interface_map.second.end()))
                            {
                                add = true;
                                break;
                            }
                        }
                        if (add)
                        {
                            // TODO(ed) this is a copy
                            ret.emplace_back(this_path);
                        }
                    }
                }
            }

            return ret;
        });
    iface->initialize();

    // This needs to be done after our io_service is in run, so that the match
    // creation and name reqest happen before we start introspecting.
    io.post([&]() {
        system_bus->async_method_call(
            [&](const boost::system::error_code ec,
                const std::vector<std::string>& process_names) {
                if (ec)
                {
                    std::cerr << "error getting names: " << ec << "\n";
                }
                else
                {
                    auto global_start_time = std::make_shared<
                        std::chrono::time_point<std::chrono::steady_clock>>(
                        std::chrono::steady_clock::now());

                    for (const std::string& process_name : process_names)
                    {
                        if (should_scan_dbus_interface(process_name))
                        {
                            start_new_introspect(system_bus.get(),
                                                 interface_map, process_name,
                                                 global_start_time);
                        }
                    }
                }
            },
            "org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames");
    });
    io.run();
}