Change settings in flake8 and black.
[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 import warnings
10 from typing import Any, Optional
11
12 from overrides import overrides
13
14 import argparse_utils
15 import config
16 import exec_utils
17 import file_utils
18 import persistent
19 import site_config
20 import string_utils
21 from collect.bidict import BiDict
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()  # type: ignore
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(f'Arper didn\'t find enough entries; only got {len(self.state)}.')
63
64     def update_from_arp_scan(self):
65         network_spec = site_config.get_config().network
66         try:
67             output = exec_utils.cmd(
68                 f'/usr/local/bin/arp-scan --retry=6 --timeout 350 --backoff=1.4 --random --numeric --plain --ignoredups {network_spec}',
69                 timeout_seconds=10.0,
70             )
71         except Exception as e:
72             logger.exception(e)
73             return
74         for line in output.split('\n'):
75             ip = string_utils.extract_ip_v4(line)
76             mac = string_utils.extract_mac_address(line)
77             if ip is not None and mac is not None and mac != 'UNKNOWN' and ip != 'UNKNOWN':
78                 mac = mac.lower()
79                 logger.debug(f'ARPER: {mac} => {ip}')
80                 self.state[mac] = ip
81
82     def update_from_arp(self):
83         try:
84             output = exec_utils.cmd('/usr/sbin/arp -a', timeout_seconds=10.0)
85         except Exception as e:
86             logger.exception(e)
87             return
88         for line in output.split('\n'):
89             ip = string_utils.extract_ip_v4(line)
90             mac = string_utils.extract_mac_address(line)
91             if ip is not None and mac is not None and mac != 'UNKNOWN' and ip != 'UNKNOWN':
92                 mac = mac.lower()
93                 logger.debug(f'ARPER: {mac} => {ip}')
94                 self.state[mac] = ip
95
96     def get_ip_by_mac(self, mac: str) -> Optional[str]:
97         mac = mac.lower()
98         return self.state.get(mac, None)
99
100     def get_mac_by_ip(self, ip: str) -> Optional[str]:
101         return self.state.inverse.get(ip, None)
102
103     @classmethod
104     @overrides
105     def load(cls) -> Any:
106         cache_file = config.config['arper_cache_location']
107         if persistent.was_file_written_within_n_seconds(
108             cache_file,
109             config.config['arper_cache_max_staleness'].total_seconds(),
110         ):
111             logger.debug(f'Loading state from {cache_file}')
112             cached_state = BiDict()
113             with open(cache_file, 'r') as rf:
114                 contents = rf.readlines()
115                 for line in contents:
116                     line = line[:-1]
117                     logger.debug(f'ARPER:{cache_file}> {line}')
118                     (mac, ip) = line.split(',')
119                     mac = mac.strip()
120                     mac = mac.lower()
121                     ip = ip.strip()
122                     cached_state[mac] = ip
123             if len(cached_state) > config.config['arper_min_entries_to_be_valid']:
124                 return cls(cached_state)
125             else:
126                 msg = f'{cache_file} is invalid: only {len(cached_state)} entries.  Deleting it.'
127                 logger.warning(msg)
128                 warnings.warn(msg, stacklevel=2)
129                 os.remove(cache_file)
130         logger.debug('No usable saved state found')
131         return None
132
133     @overrides
134     def save(self) -> bool:
135         if len(self.state) > config.config['arper_min_entries_to_be_valid']:
136             logger.debug(f'Persisting state to {config.config["arper_cache_location"]}')
137             with file_utils.FileWriter(config.config['arper_cache_location']) as wf:
138                 for (mac, ip) in self.state.items():
139                     mac = mac.lower()
140                     print(f'{mac}, {ip}', file=wf)
141             return True
142         else:
143             logger.warning(
144                 f'Only saw {len(self.state)} entries; needed at least {config.config["arper_min_entries_to_be_valid"]} to bother persisting.'
145             )
146             return False