3 """A caching layer around the kernel's network mapping between IPs and MACs"""
9 from typing import Any, Optional
12 from overrides import overrides
15 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=f'{os.environ["HOME"]}/cache/.arp_table_cache',
33 help='Where to cache the kernel ARP table',
36 '--arper_cache_max_staleness',
37 type=argparse_utils.valid_duration,
38 default=datetime.timedelta(seconds=60 * 15),
40 help='Max acceptable age of the kernel arp table cache',
43 '--arper_min_entries_to_be_valid',
45 default=site_config.get_config().arper_minimum_device_count,
46 help='Min number of arp entries to bother persisting.',
50 @persistent.persistent_autoloaded_singleton()
51 class Arper(persistent.Persistent):
52 def __init__(self, cached_state: Optional[BiDict] = None) -> None:
54 if cached_state is not None:
55 logger.debug('Loading Arper map from cached state.')
56 self.state = cached_state
58 logger.debug('No usable cached state; calling /usr/sbin/arp')
59 self.update_from_arp_scan()
60 self.update_from_arp()
61 if len(self.state) < config.config['arper_min_entries_to_be_valid']:
63 f'Arper didn\'t find enough entries; only got {len(self.state)}.'
66 def update_from_arp_scan(self):
67 network_spec = site_config.get_config().network
69 output = exec_utils.cmd(
70 f'/usr/local/bin/arp-scan --retry=6 --timeout 350 --backoff=1.4 --random --numeric --plain --ignoredups {network_spec}',
73 except Exception as e:
76 for line in output.split('\n'):
77 ip = string_utils.extract_ip_v4(line)
78 mac = string_utils.extract_mac_address(line)
86 logger.debug(f'ARPER: {mac} => {ip}')
89 def update_from_arp(self):
91 output = exec_utils.cmd('/usr/sbin/arp -a', timeout_seconds=10.0)
92 except Exception as e:
95 for line in output.split('\n'):
96 ip = string_utils.extract_ip_v4(line)
97 mac = string_utils.extract_mac_address(line)
105 logger.debug(f'ARPER: {mac} => {ip}')
108 def get_ip_by_mac(self, mac: str) -> Optional[str]:
110 return self.state.get(mac, None)
112 def get_mac_by_ip(self, ip: str) -> Optional[str]:
113 return self.state.inverse.get(ip, None)
117 def load(cls) -> Any:
118 cache_file = config.config['arper_cache_location']
119 if persistent.was_file_written_within_n_seconds(
121 config.config['arper_cache_max_staleness'].total_seconds(),
123 logger.debug(f'Loading state from {cache_file}')
124 cached_state = BiDict()
125 with open(cache_file, 'r') as rf:
126 contents = rf.readlines()
127 for line in contents:
129 logger.debug(f'ARPER:{cache_file}> {line}')
130 (mac, ip) = line.split(',')
134 cached_state[mac] = ip
135 if len(cached_state) > config.config['arper_min_entries_to_be_valid']:
136 return cls(cached_state)
138 msg = f'{cache_file} is invalid: only {len(cached_state)} entries. Deleting it.'
140 warnings.warn(msg, stacklevel=2)
141 os.remove(cache_file)
142 logger.debug('No usable saved state found')
146 def save(self) -> bool:
147 if len(self.state) > config.config['arper_min_entries_to_be_valid']:
148 logger.debug(f'Persisting state to {config.config["arper_cache_location"]}')
149 with file_utils.FileWriter(config.config['arper_cache_location']) as wf:
150 for (mac, ip) in self.state.items():
152 print(f'{mac}, {ip}', file=wf)
156 f'Only saw {len(self.state)} entries; needed at least {config.config["arper_min_entries_to_be_valid"]} to bother persisting.'