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