Hook in pylint to the pre-commit hook and start to fix some of its
[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('Also added %d supplimental entries.', len(cached_supplimental_state))
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('%s <-> %s', 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('ARPER: %s => %s', 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('ARPER: %s => %s', 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(
121             cls,
122             cache_file: str,
123             freshness_threshold_sec: int,
124             state: BiDict,
125     ):
126         if not file_utils.file_is_readable(cache_file):
127             logger.debug('Can\'t read %s', cache_file)
128             return
129         if persistent.was_file_written_within_n_seconds(
130             cache_file,
131             freshness_threshold_sec,
132         ):
133             logger.debug('Loading state from %s', cache_file)
134             count = 0
135             with open(cache_file, 'r') as rf:
136                 contents = rf.readlines()
137                 for line in contents:
138                     line = line[:-1]
139                     logger.debug('ARPER:%s> %s', cache_file, line)
140                     (mac, ip) = line.split(',')
141                     mac = mac.strip()
142                     mac = mac.lower()
143                     ip = ip.strip()
144                     state[mac] = ip
145                     count += 1
146         else:
147             logger.debug('%s is too stale.', cache_file)
148
149     @classmethod
150     @overrides
151     def load(cls) -> Any:
152         local_state: BiDict = BiDict()
153         cache_file = config.config['arper_cache_location']
154         max_staleness = config.config['arper_cache_max_staleness'].total_seconds()
155         logger.debug('Trying to load main arper cache from %s...', cache_file)
156         cls.load_state(cache_file, max_staleness, local_state)
157         if len(local_state) <= config.config['arper_min_entries_to_be_valid']:
158             msg = f'{cache_file} is invalid: only {len(local_state)} entries.  Deleting it.'
159             logger.warning(msg)
160             warnings.warn(msg, stacklevel=2)
161             try:
162                 os.remove(cache_file)
163             except Exception:
164                 pass
165
166         supplimental_state: BiDict = BiDict()
167         cache_file = config.config['arper_supplimental_cache_location']
168         max_staleness = config.config['arper_cache_max_staleness'].total_seconds()
169         logger.debug('Trying to suppliment arper state from %s', cache_file)
170         cls.load_state(cache_file, max_staleness, supplimental_state)
171         if len(local_state) > 0:
172             return cls(local_state, supplimental_state)
173         return None
174
175     @overrides
176     def save(self) -> bool:
177         if len(self.state) > config.config['arper_min_entries_to_be_valid']:
178             logger.debug('Persisting state to %s', config.config["arper_cache_location"])
179             with file_utils.FileWriter(config.config['arper_cache_location']) as wf:
180                 for (mac, ip) in self.state.items():
181                     mac = mac.lower()
182                     print(f'{mac}, {ip}', file=wf)
183             return True
184         else:
185             logger.warning(
186                 'Only saw %d entries; needed at least %d to bother persisting.',
187                 len(self.state),
188                 config.config["arper_min_entries_to_be_valid"],
189             )
190             return False