Stop trying to cache mac addresses from house and cabin in the same
[python_utils.git] / arper.py
1 #!/usr/bin/env python3
2
3 """A caching layer around the kernel's network mapping between IPs and MACs"""
4
5
6 import datetime
7 import logging
8 import os
9 import warnings
10 from typing import Any, Optional
11
12 from overrides import overrides
13
14 import argparse_utils
15 import config
16 import exec_utils
17 import file_utils
18 import persistent
19 import site_config
20 import string_utils
21 from collect.bidict import BiDict
22
23 logger = logging.getLogger(__name__)
24
25 cfg = config.add_commandline_args(
26     f'MAC <--> IP Address mapping table cache ({__file__})',
27     'Commandline args related to MAC <--> IP Address mapping',
28 )
29 cfg.add_argument(
30     '--arper_cache_location',
31     default=site_config.get_config().arper_cache_file,
32     metavar='FILENAME',
33     help='Where to cache the kernel ARP table',
34 )
35 cfg.add_argument(
36     '--arper_supplimental_cache_location',
37     default=site_config.get_config(site_config.other_location()).arper_cache_file,
38     metavar='FILENAME',
39     help='Where someone else is caching the kernel ARP table',
40 )
41 cfg.add_argument(
42     '--arper_cache_max_staleness',
43     type=argparse_utils.valid_duration,
44     default=datetime.timedelta(seconds=60 * 15),
45     metavar='DURATION',
46     help='Max acceptable age of the kernel arp table cache',
47 )
48 cfg.add_argument(
49     '--arper_min_entries_to_be_valid',
50     type=int,
51     default=site_config.get_config().arper_minimum_device_count,
52     help='Min number of arp entries to bother persisting.',
53 )
54
55
56 @persistent.persistent_autoloaded_singleton()  # type: ignore
57 class Arper(persistent.Persistent):
58     def __init__(
59         self,
60         cached_local_state: Optional[BiDict] = None,
61         cached_supplimental_state: Optional[BiDict] = None,
62     ) -> None:
63         self.state = BiDict()
64         if cached_local_state is not None:
65             logger.debug('Loading Arper map from cached local state.')
66             self.state = cached_local_state
67         else:
68             logger.debug('No usable cached state; calling /usr/sbin/arp')
69             self.update_from_arp_scan()
70             self.update_from_arp()
71         if len(self.state) < config.config['arper_min_entries_to_be_valid']:
72             raise Exception(f'Arper didn\'t find enough entries; only got {len(self.state)}.')
73         if cached_supplimental_state is not None:
74             logger.debug(f'Also added {len(cached_supplimental_state)} supplimental entries.')
75             for mac, ip in cached_supplimental_state.items():
76                 self.state[mac] = ip
77         for mac, ip in self.state.items():
78             logger.debug(f'{mac} <-> {ip}')
79
80     def update_from_arp_scan(self):
81         network_spec = site_config.get_config().network
82         try:
83             output = exec_utils.cmd(
84                 f'/usr/local/bin/arp-scan --retry=6 --timeout 350 --backoff=1.4 --random --numeric --plain --ignoredups {network_spec}',
85                 timeout_seconds=10.0,
86             )
87         except Exception as e:
88             logger.exception(e)
89             return
90         for line in output.split('\n'):
91             ip = string_utils.extract_ip_v4(line)
92             mac = string_utils.extract_mac_address(line)
93             if ip is not None and mac is not None and mac != 'UNKNOWN' and ip != 'UNKNOWN':
94                 mac = mac.lower()
95                 logger.debug(f'ARPER: {mac} => {ip}')
96                 self.state[mac] = ip
97
98     def update_from_arp(self):
99         try:
100             output = exec_utils.cmd('/usr/sbin/arp -a', timeout_seconds=10.0)
101         except Exception as e:
102             logger.exception(e)
103             return
104         for line in output.split('\n'):
105             ip = string_utils.extract_ip_v4(line)
106             mac = string_utils.extract_mac_address(line)
107             if ip is not None and mac is not None and mac != 'UNKNOWN' and ip != 'UNKNOWN':
108                 mac = mac.lower()
109                 logger.debug(f'ARPER: {mac} => {ip}')
110                 self.state[mac] = ip
111
112     def get_ip_by_mac(self, mac: str) -> Optional[str]:
113         mac = mac.lower()
114         return self.state.get(mac, None)
115
116     def get_mac_by_ip(self, ip: str) -> Optional[str]:
117         return self.state.inverse.get(ip, None)
118
119     @classmethod
120     def load_state(cls, cache_file: str, freshness_threshold_sec: int, state: BiDict):
121         if not file_utils.file_is_readable(cache_file):
122             logger.debug(f'Can\'t read {cache_file}')
123             return None
124         if persistent.was_file_written_within_n_seconds(
125             cache_file,
126             freshness_threshold_sec,
127         ):
128             logger.debug(f'Loading state from {cache_file}')
129             count = 0
130             with open(cache_file, 'r') as rf:
131                 contents = rf.readlines()
132                 for line in contents:
133                     line = line[:-1]
134                     logger.debug(f'ARPER:{cache_file}> {line}')
135                     (mac, ip) = line.split(',')
136                     mac = mac.strip()
137                     mac = mac.lower()
138                     ip = ip.strip()
139                     state[mac] = ip
140                     count += 1
141         else:
142             logger.debug(f'{cache_file} is too stale.')
143
144     @classmethod
145     @overrides
146     def load(cls) -> Any:
147         local_state = BiDict()
148         cache_file = config.config['arper_cache_location']
149         max_staleness = config.config['arper_cache_max_staleness'].total_seconds()
150         logger.debug(f'Trying to load main arper cache from {cache_file}...')
151         cls.load_state(cache_file, max_staleness, local_state)
152         if len(local_state) <= config.config['arper_min_entries_to_be_valid']:
153             msg = f'{cache_file} is invalid: only {len(local_state)} entries.  Deleting it.'
154             logger.warning(msg)
155             warnings.warn(msg, stacklevel=2)
156             try:
157                 os.remove(cache_file)
158             except Exception:
159                 pass
160
161         supplimental_state = BiDict()
162         cache_file = config.config['arper_supplimental_cache_location']
163         max_staleness = config.config['arper_cache_max_staleness'].total_seconds()
164         logger.debug(f'Trying to suppliment arper state from {cache_file}...')
165         cls.load_state(cache_file, max_staleness, supplimental_state)
166         if len(supplimental_state) == 0:
167             supplimental_state = None
168
169         if len(local_state) > 0:
170             return cls(local_state, supplimental_state)
171         return None
172
173     @overrides
174     def save(self) -> bool:
175         if len(self.state) > config.config['arper_min_entries_to_be_valid']:
176             logger.debug(f'Persisting state to {config.config["arper_cache_location"]}')
177             with file_utils.FileWriter(config.config['arper_cache_location']) as wf:
178                 for (mac, ip) in self.state.items():
179                     mac = mac.lower()
180                     print(f'{mac}, {ip}', file=wf)
181             return True
182         else:
183             logger.warning(
184                 f'Only saw {len(self.state)} entries; needed at least {config.config["arper_min_entries_to_be_valid"]} to bother persisting.'
185             )
186             return False