blob: 4ee1659a82b550637848b18aff1938a0d4b0d51b [file] [log] [blame]
Tomáš Pecka2d578c82021-02-23 19:01:35 +01001/*
2 * Copyright (C) 2021 CESNET, https://photonics.cesnet.cz/
3 *
4 * Written by Tomáš Pecka <tomas.pecka@cesnet.cz>
5 *
6 */
7
8#pragma once
9
10#include <functional>
11#include <mutex>
12#include <netlink/netlink.h>
Tomáš Pecka09729382021-03-08 19:36:50 +010013#include <netlink/route/addr.h>
Tomáš Pecka2d578c82021-02-23 19:01:35 +010014#include <netlink/route/link.h>
Tomáš Peckac017eab2021-03-10 12:26:05 +010015#include <netlink/route/neighbour.h>
Tomáš Pecka2d578c82021-02-23 19:01:35 +010016#include <stdexcept>
17#include <thread>
18#include "utils/log-fwd.h"
19
20namespace velia::system {
21
22namespace impl {
23class nlCacheMngrWatcher;
24}
25
26/** @brief Wrapper for monitoring changes in NETLINK_ROUTE */
27class Rtnetlink {
28public:
29 using nlCacheManager = std::shared_ptr<nl_cache_mngr>;
Tomáš Peckac017eab2021-03-10 12:26:05 +010030 using nlCache = std::unique_ptr<nl_cache, std::function<void(nl_cache*)>>;
31 using nlLink = std::unique_ptr<rtnl_link, std::function<void(rtnl_link*)>>;
32
Tomáš Pecka2d578c82021-02-23 19:01:35 +010033 using LinkCB = std::function<void(rtnl_link* link, int cacheAction)>; /// cacheAction: NL_ACT_*
Tomáš Pecka09729382021-03-08 19:36:50 +010034 using AddrCB = std::function<void(rtnl_addr* addr, int cacheAction)>; /// cacheAction: NL_ACT_*
Tomáš Pecka2d578c82021-02-23 19:01:35 +010035
Tomáš Pecka09729382021-03-08 19:36:50 +010036 Rtnetlink(LinkCB cbLink, AddrCB cbAddr);
Tomáš Pecka2d578c82021-02-23 19:01:35 +010037 ~Rtnetlink();
Tomáš Peckac017eab2021-03-10 12:26:05 +010038 std::vector<nlLink> getLinks();
Tomáš Pecka2d578c82021-02-23 19:01:35 +010039
40private:
Tomáš Peckac017eab2021-03-10 12:26:05 +010041 void resyncCache(const nlCache& cache);
42
Tomáš Pecka2d578c82021-02-23 19:01:35 +010043 velia::Log m_log;
Tomáš Peckac017eab2021-03-10 12:26:05 +010044 std::unique_ptr<nl_sock, std::function<void(nl_sock*)>> m_nlSocket;
45 nlCacheManager m_nlCacheManager; // for updates
46 nlCache m_nlCacheLink; // for getLinks
Tomáš Pecka09729382021-03-08 19:36:50 +010047 LinkCB m_cbLink;
48 AddrCB m_cbAddr;
Tomáš Pecka2d578c82021-02-23 19:01:35 +010049 std::unique_ptr<impl::nlCacheMngrWatcher> m_nlCacheMngrWatcher; // first to destroy, because the thread uses m_nlCacheManager and m_log
50};
51
52class RtnetlinkException : public std::runtime_error {
53public:
54 RtnetlinkException(const std::string& msg);
55 RtnetlinkException(const std::string& funcName, int error);
56};
57
58}