blob: df736802261aaf494bb0fdf4a4e866ab666a4695 [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*)>>;
Tomáš Peckaf9212c42021-03-10 11:45:05 +010032 using nlNeigh = std::unique_ptr<rtnl_neigh, std::function<void(rtnl_neigh*)>>;
Tomáš Peckac017eab2021-03-10 12:26:05 +010033
Tomáš Pecka2d578c82021-02-23 19:01:35 +010034 using LinkCB = std::function<void(rtnl_link* link, int cacheAction)>; /// cacheAction: NL_ACT_*
Tomáš Pecka09729382021-03-08 19:36:50 +010035 using AddrCB = std::function<void(rtnl_addr* addr, int cacheAction)>; /// cacheAction: NL_ACT_*
Tomáš Pecka2d578c82021-02-23 19:01:35 +010036
Tomáš Pecka09729382021-03-08 19:36:50 +010037 Rtnetlink(LinkCB cbLink, AddrCB cbAddr);
Tomáš Pecka2d578c82021-02-23 19:01:35 +010038 ~Rtnetlink();
Tomáš Peckac017eab2021-03-10 12:26:05 +010039 std::vector<nlLink> getLinks();
Tomáš Peckaf9212c42021-03-10 11:45:05 +010040 std::vector<std::pair<nlNeigh, nlLink>> getNeighbours();
Tomáš Pecka2d578c82021-02-23 19:01:35 +010041
42private:
Tomáš Peckac017eab2021-03-10 12:26:05 +010043 void resyncCache(const nlCache& cache);
44
Tomáš Pecka2d578c82021-02-23 19:01:35 +010045 velia::Log m_log;
Tomáš Peckac017eab2021-03-10 12:26:05 +010046 std::unique_ptr<nl_sock, std::function<void(nl_sock*)>> m_nlSocket;
47 nlCacheManager m_nlCacheManager; // for updates
Tomáš Peckaf9212c42021-03-10 11:45:05 +010048 nlCache m_nlCacheLink; // for getLinks, getNeighbours
49 nlCache m_nlCacheNeighbour; // for getNeighbours
Tomáš Pecka09729382021-03-08 19:36:50 +010050 LinkCB m_cbLink;
51 AddrCB m_cbAddr;
Tomáš Pecka2d578c82021-02-23 19:01:35 +010052 std::unique_ptr<impl::nlCacheMngrWatcher> m_nlCacheMngrWatcher; // first to destroy, because the thread uses m_nlCacheManager and m_log
53};
54
55class RtnetlinkException : public std::runtime_error {
56public:
57 RtnetlinkException(const std::string& msg);
58 RtnetlinkException(const std::string& funcName, int error);
59};
60
61}