3 """A caching layer around the kernel's network mapping between IPs and MACs"""
8 from typing import Any, Optional
11 from overrides import overrides
14 from collect.bidict import BiDict
22 logger = logging.getLogger(__name__)
24 cfg = config.add_commandline_args(
25 f'MAC <--> IP Address mapping table cache ({__file__})',
26 'Commandline args related to MAC <--> IP Address mapping',
29 '--arper_cache_location',
30 default=f'{os.environ["HOME"]}/cache/.arp_table_cache',
32 help='Where to cache the kernel ARP table',
35 '--arper_cache_max_staleness',
36 type=argparse_utils.valid_duration,
37 default=datetime.timedelta(seconds=60 * 15),
39 help='Max acceptable age of the kernel arp table cache',
42 '--arper_min_entries_to_be_valid',
44 default=site_config.get_config().arper_minimum_device_count,
45 help='Min number of arp entries to bother persisting.',
49 @persistent.persistent_autoloaded_singleton()
50 class Arper(persistent.Persistent):
51 def __init__(self, cached_state: Optional[BiDict] = None) -> None:
53 if cached_state is not None:
54 logger.debug('Loading Arper map from cached state.')
55 self.state = cached_state
57 logger.debug('No usable cached state; calling /usr/sbin/arp')
58 self.update_from_arp_scan()
59 self.update_from_arp()
60 if len(self.state) < config.config['arper_min_entries_to_be_valid']:
62 f'Arper didn\'t find enough entries; only got {len(self.state)}.'
65 def update_from_arp_scan(self):
66 network_spec = site_config.get_config().network
68 output = exec_utils.cmd(
69 f'/usr/local/bin/arp-scan --retry=6 --timeout 350 --backoff=1.4 --random --numeric --plain --ignoredups {network_spec}',
72 except Exception as e:
75 for line in output.split('\n'):
76 ip = string_utils.extract_ip_v4(line)
77 mac = string_utils.extract_mac_address(line)
85 logger.debug(f'ARPER: {mac} => {ip}')
88 def update_from_arp(self):
90 output = exec_utils.cmd('/usr/sbin/arp -a', timeout_seconds=10.0)
91 except Exception as e:
94 for line in output.split('\n'):
95 ip = string_utils.extract_ip_v4(line)
96 mac = string_utils.extract_mac_address(line)
104 logger.debug(f'ARPER: {mac} => {ip}')
107 def get_ip_by_mac(self, mac: str) -> Optional[str]:
109 return self.state.get(mac, None)
111 def get_mac_by_ip(self, ip: str) -> Optional[str]:
112 return self.state.inverse.get(ip, None)
116 def load(cls) -> Any:
117 cache_file = config.config['arper_cache_location']
118 if persistent.was_file_written_within_n_seconds(
120 config.config['arper_cache_max_staleness'].total_seconds(),
122 logger.debug(f'Loading state from {cache_file}')
123 cached_state = BiDict()
124 with open(cache_file, 'r') as rf:
125 contents = rf.readlines()
126 for line in contents:
128 logger.debug(f'ARPER:{cache_file}> {line}')
129 (mac, ip) = line.split(',')
133 cached_state[mac] = ip
136 > config.config['arper_min_entries_to_be_valid']
138 return cls(cached_state)
140 msg = f'{cache_file} is invalid: only {len(cached_state)} entries. Deleting it.'
142 warnings.warn(msg, stacklevel=2)
143 os.remove(cache_file)
144 logger.debug('No usable saved state found')
148 def save(self) -> bool:
149 if len(self.state) > config.config['arper_min_entries_to_be_valid']:
151 f'Persisting state to {config.config["arper_cache_location"]}'
153 with file_utils.FileWriter(
154 config.config['arper_cache_location']
156 for (mac, ip) in self.state.items():
158 print(f'{mac}, {ip}', file=wf)
162 f'Only saw {len(self.state)} entries; needed at least {config.config["arper_min_entries_to_be_valid"]} to bother persisting.'