3 """A caching layer around the kernel's network mapping between IPs and MACs"""
11 from typing import Any, Optional
14 from overrides import overrides
17 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__})', 'Commandline args related to MAC <--> IP Address mapping',
31 '--arper_cache_location',
32 default=f'{os.environ["HOME"]}/cache/.arp_table_cache',
34 help='Where to cache the kernel ARP table',
37 '--arper_cache_max_staleness',
38 type=argparse_utils.valid_duration,
39 default=datetime.timedelta(seconds=60 * 15),
41 help='Max acceptable age of the kernel arp table cache',
44 '--arper_min_entries_to_be_valid',
46 default=site_config.get_config().arper_minimum_device_count,
47 help='Min number of arp entries to bother persisting.',
51 @persistent.persistent_autoloaded_singleton()
52 class Arper(persistent.Persistent):
53 def __init__(self, cached_state: Optional[BiDict] = None) -> None:
55 if cached_state is not None:
56 logger.debug('Loading Arper map from cached state.')
57 self.state = cached_state
59 logger.debug('No usable cached state; calling /usr/sbin/arp')
60 self.update_from_arp_scan()
61 self.update_from_arp()
62 if len(self.state) < config.config['arper_min_entries_to_be_valid']:
64 f'Arper didn\'t find enough entries; only got {len(self.state)}.'
67 def update_from_arp_scan(self):
68 network_spec = site_config.get_config().network
70 output = exec_utils.cmd(
71 f'/usr/local/bin/arp-scan --retry=6 --timeout 350 --backoff=1.4 --random --numeric --plain --ignoredups {network_spec}',
74 except Exception as e:
77 for line in output.split('\n'):
78 ip = string_utils.extract_ip_v4(line)
79 mac = string_utils.extract_mac_address(line)
87 logger.debug(f'ARPER: {mac} => {ip}')
90 def update_from_arp(self):
92 output = exec_utils.cmd('/usr/sbin/arp -a', timeout_seconds=10.0)
93 except Exception as e:
96 for line in output.split('\n'):
97 ip = string_utils.extract_ip_v4(line)
98 mac = string_utils.extract_mac_address(line)
106 logger.debug(f'ARPER: {mac} => {ip}')
109 def get_ip_by_mac(self, mac: str) -> Optional[str]:
111 return self.state.get(mac, None)
113 def get_mac_by_ip(self, ip: str) -> Optional[str]:
114 return self.state.inverse.get(ip, None)
118 def load(cls) -> Any:
119 cache_file = config.config['arper_cache_location']
120 if persistent.was_file_written_within_n_seconds(
122 config.config['arper_cache_max_staleness'].total_seconds(),
124 logger.debug(f'Loading state from {cache_file}')
125 cached_state = BiDict()
126 with open(cache_file, 'r') as rf:
127 contents = rf.readlines()
128 for line in contents:
130 logger.debug(f'ARPER:{cache_file}> {line}')
131 (mac, ip) = line.split(',')
135 cached_state[mac] = ip
136 if len(cached_state) > config.config['arper_min_entries_to_be_valid']:
137 return cls(cached_state)
139 msg = f'{cache_file} is invalid: only {len(cached_state)} entries. Deleting it.'
141 warnings.warn(msg, stacklevel=2)
142 os.remove(cache_file)
143 logger.debug('No usable saved state found')
147 def save(self) -> bool:
148 if len(self.state) > config.config['arper_min_entries_to_be_valid']:
149 logger.debug(f'Persisting state to {config.config["arper_cache_location"]}')
150 with file_utils.FileWriter(config.config['arper_cache_location']) as wf:
151 for (mac, ip) in self.state.items():
153 print(f'{mac}, {ip}', file=wf)
157 f'Only saw {len(self.state)} entries; needed at least {config.config["arper_min_entries_to_be_valid"]} to bother persisting.'