a5b1de410f53ae04f917e08c03660b32953e47c1
[python_utils.git] / arper.py
1 #!/usr/bin/env python3
2
3 """A caching layer around the kernel's network mapping between IPs and MACs"""
4
5
6
7
8 import datetime
9 import logging
10 import os
11 from typing import Any, Optional
12 import warnings
13
14 from overrides import overrides
15
16 import argparse_utils
17 from collect.bidict import BiDict
18 import config
19 import exec_utils
20 import file_utils
21 import persistent
22 import string_utils
23 import site_config
24
25 logger = logging.getLogger(__name__)
26
27 cfg = config.add_commandline_args(
28     f'MAC <--> IP Address mapping table cache ({__file__})', 'Commandline args related to MAC <--> IP Address mapping',
29 )
30 cfg.add_argument(
31     '--arper_cache_location',
32     default=f'{os.environ["HOME"]}/cache/.arp_table_cache',
33     metavar='FILENAME',
34     help='Where to cache the kernel ARP table',
35 )
36 cfg.add_argument(
37     '--arper_cache_max_staleness',
38     type=argparse_utils.valid_duration,
39     default=datetime.timedelta(seconds=60 * 15),
40     metavar='DURATION',
41     help='Max acceptable age of the kernel arp table cache',
42 )
43 cfg.add_argument(
44     '--arper_min_entries_to_be_valid',
45     type=int,
46     default=site_config.get_config().arper_minimum_device_count,
47     help='Min number of arp entries to bother persisting.',
48 )
49
50
51 @persistent.persistent_autoloaded_singleton()
52 class Arper(persistent.Persistent):
53     def __init__(self, cached_state: Optional[BiDict] = None) -> None:
54         self.state = BiDict()
55         if cached_state is not None:
56             logger.debug('Loading Arper map from cached state.')
57             self.state = cached_state
58         else:
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(
64                 f'Arper didn\'t find enough entries; only got {len(self.state)}.'
65             )
66
67     def update_from_arp_scan(self):
68         network_spec = site_config.get_config().network
69         try:
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}',
72                 timeout_seconds=10.0,
73             )
74         except Exception as e:
75             logger.exception(e)
76             return
77         for line in output.split('\n'):
78             ip = string_utils.extract_ip_v4(line)
79             mac = string_utils.extract_mac_address(line)
80             if (
81                 ip is not None
82                 and mac is not None
83                 and mac != 'UNKNOWN'
84                 and ip != 'UNKNOWN'
85             ):
86                 mac = mac.lower()
87                 logger.debug(f'ARPER: {mac} => {ip}')
88                 self.state[mac] = ip
89
90     def update_from_arp(self):
91         try:
92             output = exec_utils.cmd('/usr/sbin/arp -a', timeout_seconds=10.0)
93         except Exception as e:
94             logger.exception(e)
95             return
96         for line in output.split('\n'):
97             ip = string_utils.extract_ip_v4(line)
98             mac = string_utils.extract_mac_address(line)
99             if (
100                 ip is not None
101                 and mac is not None
102                 and mac != 'UNKNOWN'
103                 and ip != 'UNKNOWN'
104             ):
105                 mac = mac.lower()
106                 logger.debug(f'ARPER: {mac} => {ip}')
107                 self.state[mac] = ip
108
109     def get_ip_by_mac(self, mac: str) -> Optional[str]:
110         mac = mac.lower()
111         return self.state.get(mac, None)
112
113     def get_mac_by_ip(self, ip: str) -> Optional[str]:
114         return self.state.inverse.get(ip, None)
115
116     @classmethod
117     @overrides
118     def load(cls) -> Any:
119         cache_file = config.config['arper_cache_location']
120         if persistent.was_file_written_within_n_seconds(
121             cache_file,
122             config.config['arper_cache_max_staleness'].total_seconds(),
123         ):
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:
129                     line = line[:-1]
130                     logger.debug(f'ARPER:{cache_file}> {line}')
131                     (mac, ip) = line.split(',')
132                     mac = mac.strip()
133                     mac = mac.lower()
134                     ip = ip.strip()
135                     cached_state[mac] = ip
136             if len(cached_state) > config.config['arper_min_entries_to_be_valid']:
137                 return cls(cached_state)
138             else:
139                 msg = f'{cache_file} is invalid: only {len(cached_state)} entries.  Deleting it.'
140                 logger.warning(msg)
141                 warnings.warn(msg, stacklevel=2)
142                 os.remove(cache_file)
143         logger.debug('No usable saved state found')
144         return None
145
146     @overrides
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():
152                     mac = mac.lower()
153                     print(f'{mac}, {ip}', file=wf)
154             return True
155         else:
156             logger.warning(
157                 f'Only saw {len(self.state)} entries; needed at least {config.config["arper_min_entries_to_be_valid"]} to bother persisting.'
158             )
159             return False