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):
52 self, cached_state: Optional[BiDict] = 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']:
63 raise Exception('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)
78 if ip is not None and mac is not None and mac != 'UNKNOWN' and ip != 'UNKNOWN':
80 logger.debug(f'ARPER: {mac} => {ip}')
83 def update_from_arp(self):
85 output = exec_utils.cmd(
89 except Exception as e:
92 for line in output.split('\n'):
93 ip = string_utils.extract_ip_v4(line)
94 mac = string_utils.extract_mac_address(line)
95 if ip is not None and mac is not None and mac != 'UNKNOWN' and ip != 'UNKNOWN':
97 logger.debug(f'ARPER: {mac} => {ip}')
100 def get_ip_by_mac(self, mac: str) -> Optional[str]:
102 return self.state.get(mac, None)
104 def get_mac_by_ip(self, ip: str) -> Optional[str]:
105 return self.state.inverse.get(ip, None)
109 def load(cls) -> Any:
110 cache_file = config.config['arper_cache_location']
111 if persistent.was_file_written_within_n_seconds(
113 config.config['arper_cache_max_staleness'].total_seconds(),
115 logger.debug(f'Loading state from {cache_file}')
116 cached_state = BiDict()
117 with open(cache_file, 'r') as rf:
118 contents = rf.readlines()
119 for line in contents:
121 logger.debug(f'ARPER:{cache_file}> {line}')
122 (mac, ip) = line.split(',')
126 cached_state[mac] = ip
127 if len(cached_state) > config.config['arper_min_entries_to_be_valid']:
128 return cls(cached_state)
130 msg = f'{cache_file} is invalid: only {len(cached_state)} entries. Deleting it.'
133 os.remove(cache_file)
134 logger.debug('No usable saved state found')
138 def save(self) -> bool:
139 if len(self.state) > config.config['arper_min_entries_to_be_valid']:
141 f'Persisting state to {config.config["arper_cache_location"]}'
143 with file_utils.FileWriter(config.config['arper_cache_location']) as wf:
144 for (mac, ip) in self.state.items():
146 print(f'{mac}, {ip}', file=wf)
150 f'Only saw {len(self.state)} entries; needed at least {config.config["arper_min_entries_to_be_valid"]} to bother persisting.'