3 # © Copyright 2021-2022, Scott Gasch
5 """A caching layer around the kernel's network mapping between IPs and MACs"""
12 from typing import Any, Optional
14 from overrides import overrides
23 from collect.bidict import BiDict
25 logger = logging.getLogger(__name__)
27 cfg = config.add_commandline_args(
28 f'MAC <--> IP Address mapping table cache ({__file__})',
29 'Commandline args related to MAC <--> IP Address mapping',
32 '--arper_cache_location',
33 default=site_config.get_config().arper_cache_file,
35 help='Where to cache the kernel ARP table',
38 '--arper_supplimental_cache_location',
39 default=site_config.get_config(site_config.other_location()).arper_cache_file,
41 help='Where someone else is caching the kernel ARP table',
44 '--arper_cache_max_staleness',
45 type=argparse_utils.valid_duration,
46 default=datetime.timedelta(seconds=60 * 30),
48 help='Max acceptable age of the kernel arp table cache',
51 '--arper_min_entries_to_be_valid',
53 default=site_config.get_config().arper_minimum_device_count,
54 help='Min number of arp entries to bother persisting.',
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.
73 cached_local_state: Optional[BiDict] = None,
74 cached_supplimental_state: Optional[BiDict] = None,
76 """For most purposes, ignore the arguments. Because this is a
77 Persistent subclass the decorator will handle invoking our load
78 and save methods to read/write persistent state transparently.
81 cached_local_state: local state to initialize mapping
82 cached_supplimental_state: remote state to initialize mapping
86 if cached_local_state is not None:
87 logger.debug('Loading Arper map from cached local state.')
88 self.state = cached_local_state
90 logger.debug('No usable cached state; calling /usr/sbin/arp')
91 self._update_from_arp_scan()
92 self._update_from_arp()
93 if len(self.state) < config.config['arper_min_entries_to_be_valid']:
94 raise Exception(f'Arper didn\'t find enough entries; only got {len(self.state)}.')
95 if cached_supplimental_state is not None:
96 logger.debug('Also added %d supplimental entries.', len(cached_supplimental_state))
97 for mac, ip in cached_supplimental_state.items():
99 for mac, ip in self.state.items():
100 logger.debug('%s <-> %s', mac, ip)
102 def _update_from_arp_scan(self):
103 """Internal method to initialize our state via a call to arp-scan."""
105 network_spec = site_config.get_config().network
107 output = exec_utils.cmd(
108 f'/usr/local/bin/arp-scan --retry=6 --timeout 350 --backoff=1.4 --random --numeric --plain --ignoredups {network_spec}',
109 timeout_seconds=10.0,
111 except Exception as e:
114 for line in output.split('\n'):
115 ip = string_utils.extract_ip_v4(line)
116 mac = string_utils.extract_mac_address(line)
117 if ip is not None and mac is not None and mac != 'UNKNOWN' and ip != 'UNKNOWN':
119 logger.debug('ARPER: %s => %s', mac, ip)
122 def _update_from_arp(self):
123 """Internal method to initialize our state via a call to arp."""
126 output = exec_utils.cmd('/usr/sbin/arp -a', timeout_seconds=10.0)
127 except Exception as e:
130 for line in output.split('\n'):
131 ip = string_utils.extract_ip_v4(line)
132 mac = string_utils.extract_mac_address(line)
133 if ip is not None and mac is not None and mac != 'UNKNOWN' and ip != 'UNKNOWN':
135 logger.debug('ARPER: %s => %s', mac, ip)
138 def get_ip_by_mac(self, mac: str) -> Optional[str]:
139 """Given a MAC address, see if we know it's IP address and, if so,
140 return it. If not, return None.
143 mac: the MAC address to lookup. Should be formatted like
147 The IPv4 address associated with that MAC address (as a string)
148 or None if it's not known.
150 m = string_utils.extract_mac_address(mac)
154 if not string_utils.is_mac_address(m):
156 return self.state.get(m, None)
158 def get_mac_by_ip(self, ip: str) -> Optional[str]:
159 """Given an IPv4 address (as a string), check to see if we know what
160 MAC address is associated with it and, if so, return it. If not,
164 ip: the IPv4 address to look up.
167 The associated MAC address, if known. Or None if not.
169 return self.state.inverse.get(ip, None)
175 freshness_threshold_sec: int,
178 """Internal helper method behind load."""
180 if not file_utils.file_is_readable(cache_file):
181 logger.debug('Can\'t read %s', cache_file)
183 if persistent.was_file_written_within_n_seconds(
185 freshness_threshold_sec,
187 logger.debug('Loading state from %s', cache_file)
189 with open(cache_file, 'r') as rf:
190 contents = rf.readlines()
191 for line in contents:
193 logger.debug('ARPER:%s> %s', cache_file, line)
194 (mac, ip) = line.split(',')
201 logger.debug('%s is too stale.', cache_file)
205 def load(cls) -> Any:
206 """Internal helper method to fulfull Persistent requirements."""
208 local_state: BiDict = BiDict()
209 cache_file = config.config['arper_cache_location']
210 max_staleness = config.config['arper_cache_max_staleness'].total_seconds()
211 logger.debug('Trying to load main arper cache from %s...', cache_file)
212 cls._load_state(cache_file, max_staleness, local_state)
213 if len(local_state) <= config.config['arper_min_entries_to_be_valid']:
214 msg = f'{cache_file} is invalid: only {len(local_state)} entries. Deleting it.'
216 warnings.warn(msg, stacklevel=2)
218 os.remove(cache_file)
222 supplimental_state: BiDict = BiDict()
223 cache_file = config.config['arper_supplimental_cache_location']
224 max_staleness = config.config['arper_cache_max_staleness'].total_seconds()
225 logger.debug('Trying to suppliment arper state from %s', cache_file)
226 cls._load_state(cache_file, max_staleness, supplimental_state)
227 if len(local_state) > 0:
228 return cls(local_state, supplimental_state)
232 def save(self) -> bool:
233 """Internal helper method to fulfull Persistent requirements."""
235 if len(self.state) > config.config['arper_min_entries_to_be_valid']:
236 logger.debug('Persisting state to %s', config.config["arper_cache_location"])
237 with file_utils.FileWriter(config.config['arper_cache_location']) as wf:
238 for (mac, ip) in self.state.items():
240 print(f'{mac}, {ip}', file=wf)
244 'Only saw %d entries; needed at least %d to bother persisting.',
246 config.config["arper_min_entries_to_be_valid"],