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 * 15),
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):
60 cached_local_state: Optional[BiDict] = None,
61 cached_supplimental_state: Optional[BiDict] = None,
64 if cached_local_state is not None:
65 logger.debug('Loading Arper map from cached local state.')
66 self.state = cached_local_state
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():
77 for mac, ip in self.state.items():
78 logger.debug('%s <-> %s', mac, ip)
80 def update_from_arp_scan(self):
81 network_spec = site_config.get_config().network
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}',
87 except Exception as e:
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':
95 logger.debug('ARPER: %s => %s', mac, ip)
98 def update_from_arp(self):
100 output = exec_utils.cmd('/usr/sbin/arp -a', timeout_seconds=10.0)
101 except Exception as e:
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':
109 logger.debug('ARPER: %s => %s', mac, ip)
112 def get_ip_by_mac(self, mac: str) -> Optional[str]:
114 return self.state.get(mac, None)
116 def get_mac_by_ip(self, ip: str) -> Optional[str]:
117 return self.state.inverse.get(ip, None)
123 freshness_threshold_sec: int,
126 if not file_utils.file_is_readable(cache_file):
127 logger.debug('Can\'t read %s', cache_file)
129 if persistent.was_file_written_within_n_seconds(
131 freshness_threshold_sec,
133 logger.debug('Loading state from %s', cache_file)
135 with open(cache_file, 'r') as rf:
136 contents = rf.readlines()
137 for line in contents:
139 logger.debug('ARPER:%s> %s', cache_file, line)
140 (mac, ip) = line.split(',')
147 logger.debug('%s is too stale.', cache_file)
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.'
160 warnings.warn(msg, stacklevel=2)
162 os.remove(cache_file)
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)
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():
182 print(f'{mac}, {ip}', file=wf)
186 'Only saw %d entries; needed at least %d to bother persisting.',
188 config.config["arper_min_entries_to_be_valid"],