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