3 """A caching layer around the kernel's network mapping between IPs and MACs"""
10 from typing import Any, Optional
12 from overrides import overrides
21 from collect.bidict import BiDict
23 logger = logging.getLogger(__name__)
25 cfg = config.add_commandline_args(
26 f'MAC <--> IP Address mapping table cache ({__file__})',
27 'Commandline args related to MAC <--> IP Address mapping',
30 '--arper_cache_location',
31 default=site_config.get_config().arper_cache_file,
33 help='Where to cache the kernel ARP table',
36 '--arper_supplimental_cache_location',
37 default=site_config.get_config(site_config.other_location()).arper_cache_file,
39 help='Where someone else is caching the kernel ARP table',
42 '--arper_cache_max_staleness',
43 type=argparse_utils.valid_duration,
44 default=datetime.timedelta(seconds=60 * 30),
46 help='Max acceptable age of the kernel arp table cache',
49 '--arper_min_entries_to_be_valid',
51 default=site_config.get_config().arper_minimum_device_count,
52 help='Min number of arp entries to bother persisting.',
56 @persistent.persistent_autoloaded_singleton() # type: ignore
57 class Arper(persistent.Persistent):
58 """A caching layer around the kernel's network mapping between IPs and
59 MACs. This class restores persisted state that expires
60 periodically (see --arper_cache_max_staleness) at program startup
61 time. If it's unable to use the file's contents, it queries the
62 kernel (via arp) and uses an auxillary utility called arp-scan to
63 query the network. If it has to do this there's a latency hit but
64 it persists the collected data in the cache file. Either way, the
65 class behaves as a global singleton hosting this data thereafter.
71 cached_local_state: Optional[BiDict] = None,
72 cached_supplimental_state: Optional[BiDict] = None,
75 if cached_local_state is not None:
76 logger.debug('Loading Arper map from cached local state.')
77 self.state = cached_local_state
79 logger.debug('No usable cached state; calling /usr/sbin/arp')
80 self.update_from_arp_scan()
81 self.update_from_arp()
82 if len(self.state) < config.config['arper_min_entries_to_be_valid']:
83 raise Exception(f'Arper didn\'t find enough entries; only got {len(self.state)}.')
84 if cached_supplimental_state is not None:
85 logger.debug('Also added %d supplimental entries.', len(cached_supplimental_state))
86 for mac, ip in cached_supplimental_state.items():
88 for mac, ip in self.state.items():
89 logger.debug('%s <-> %s', mac, ip)
91 def update_from_arp_scan(self):
92 network_spec = site_config.get_config().network
94 output = exec_utils.cmd(
95 f'/usr/local/bin/arp-scan --retry=6 --timeout 350 --backoff=1.4 --random --numeric --plain --ignoredups {network_spec}',
98 except Exception as e:
101 for line in output.split('\n'):
102 ip = string_utils.extract_ip_v4(line)
103 mac = string_utils.extract_mac_address(line)
104 if ip is not None and mac is not None and mac != 'UNKNOWN' and ip != 'UNKNOWN':
106 logger.debug('ARPER: %s => %s', mac, ip)
109 def update_from_arp(self):
111 output = exec_utils.cmd('/usr/sbin/arp -a', timeout_seconds=10.0)
112 except Exception as e:
115 for line in output.split('\n'):
116 ip = string_utils.extract_ip_v4(line)
117 mac = string_utils.extract_mac_address(line)
118 if ip is not None and mac is not None and mac != 'UNKNOWN' and ip != 'UNKNOWN':
120 logger.debug('ARPER: %s => %s', mac, ip)
123 def get_ip_by_mac(self, mac: str) -> Optional[str]:
125 return self.state.get(mac, None)
127 def get_mac_by_ip(self, ip: str) -> Optional[str]:
128 return self.state.inverse.get(ip, None)
134 freshness_threshold_sec: int,
137 if not file_utils.file_is_readable(cache_file):
138 logger.debug('Can\'t read %s', cache_file)
140 if persistent.was_file_written_within_n_seconds(
142 freshness_threshold_sec,
144 logger.debug('Loading state from %s', cache_file)
146 with open(cache_file, 'r') as rf:
147 contents = rf.readlines()
148 for line in contents:
150 logger.debug('ARPER:%s> %s', cache_file, line)
151 (mac, ip) = line.split(',')
158 logger.debug('%s is too stale.', cache_file)
162 def load(cls) -> Any:
163 local_state: BiDict = BiDict()
164 cache_file = config.config['arper_cache_location']
165 max_staleness = config.config['arper_cache_max_staleness'].total_seconds()
166 logger.debug('Trying to load main arper cache from %s...', cache_file)
167 cls.load_state(cache_file, max_staleness, local_state)
168 if len(local_state) <= config.config['arper_min_entries_to_be_valid']:
169 msg = f'{cache_file} is invalid: only {len(local_state)} entries. Deleting it.'
171 warnings.warn(msg, stacklevel=2)
173 os.remove(cache_file)
177 supplimental_state: BiDict = BiDict()
178 cache_file = config.config['arper_supplimental_cache_location']
179 max_staleness = config.config['arper_cache_max_staleness'].total_seconds()
180 logger.debug('Trying to suppliment arper state from %s', cache_file)
181 cls.load_state(cache_file, max_staleness, supplimental_state)
182 if len(local_state) > 0:
183 return cls(local_state, supplimental_state)
187 def save(self) -> bool:
188 if len(self.state) > config.config['arper_min_entries_to_be_valid']:
189 logger.debug('Persisting state to %s', config.config["arper_cache_location"])
190 with file_utils.FileWriter(config.config['arper_cache_location']) as wf:
191 for (mac, ip) in self.state.items():
193 print(f'{mac}, {ip}', file=wf)
197 'Only saw %d entries; needed at least %d to bother persisting.',
199 config.config["arper_min_entries_to_be_valid"],