Add requirements.txt
[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 import datetime
6 import logging
7 import os
8 from typing import Any, Optional
9
10 from overrides import overrides
11
12 import argparse_utils
13 from collect.bidict import BiDict
14 import config
15 import exec_utils
16 import file_utils
17 import persistent
18 import string_utils
19 import site_config
20
21 logger = logging.getLogger(__name__)
22
23 cfg = config.add_commandline_args(
24     f'MAC <--> IP Address mapping table cache ({__file__})',
25     'Commandline args related to MAC <--> IP Address mapping',
26 )
27 cfg.add_argument(
28     '--arper_cache_location',
29     default=f'{os.environ["HOME"]}/cache/.arp_table_cache',
30     metavar='FILENAME',
31     help='Where to cache the kernel ARP table',
32 )
33 cfg.add_argument(
34     '--arper_cache_max_staleness',
35     type=argparse_utils.valid_duration,
36     default=datetime.timedelta(seconds=60 * 15),
37     metavar='DURATION',
38     help='Max acceptable age of the kernel arp table cache'
39 )
40 cfg.add_argument(
41     '--arper_min_entries_to_be_valid',
42     type=int,
43     default=site_config.get_config().arper_minimum_device_count,
44     help='Min number of arp entries to bother persisting.'
45 )
46
47
48 @persistent.persistent_autoloaded_singleton()
49 class Arper(persistent.Persistent):
50     def __init__(
51             self, cached_state: Optional[BiDict] = None
52     ) -> 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('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(
85                 '/usr/sbin/arp -a',
86                 timeout_seconds=10.0
87             )
88         except Exception as e:
89             logger.exception(e)
90             return
91         for line in output.split('\n'):
92             ip = string_utils.extract_ip_v4(line)
93             mac = string_utils.extract_mac_address(line)
94             if ip is not None and mac is not None and mac != 'UNKNOWN' and ip != 'UNKNOWN':
95                 mac = mac.lower()
96                 logger.debug(f'ARPER: {mac} => {ip}')
97                 self.state[mac] = ip
98
99     def get_ip_by_mac(self, mac: str) -> Optional[str]:
100         mac = mac.lower()
101         return self.state.get(mac, None)
102
103     def get_mac_by_ip(self, ip: str) -> Optional[str]:
104         return self.state.inverse.get(ip, None)
105
106     @classmethod
107     @overrides
108     def load(cls) -> Any:
109         cache_file = config.config['arper_cache_location']
110         if persistent.was_file_written_within_n_seconds(
111                 cache_file,
112                 config.config['arper_cache_max_staleness'].total_seconds(),
113         ):
114             logger.debug(f'Loading state from {cache_file}')
115             cached_state = BiDict()
116             with open(cache_file, 'r') as rf:
117                 contents = rf.readlines()
118                 for line in contents:
119                     line = line[:-1]
120                     logger.debug(f'ARPER:{cache_file}> {line}')
121                     (mac, ip) = line.split(',')
122                     mac = mac.strip()
123                     mac = mac.lower()
124                     ip = ip.strip()
125                     cached_state[mac] = ip
126             if len(cached_state) > config.config['arper_min_entries_to_be_valid']:
127                 return cls(cached_state)
128             else:
129                 logger.warning(
130                     f'{cache_file} sucks, only {len(cached_state)} entries.  Deleting it.'
131                 )
132                 os.remove(cache_file)
133         logger.debug('No usable saved state found')
134         return None
135
136     @overrides
137     def save(self) -> bool:
138         if len(self.state) > config.config['arper_min_entries_to_be_valid']:
139             logger.debug(
140                 f'Persisting state to {config.config["arper_cache_location"]}'
141             )
142             with file_utils.FileWriter(config.config['arper_cache_location']) as wf:
143                 for (mac, ip) in self.state.items():
144                     mac = mac.lower()
145                     print(f'{mac}, {ip}', file=wf)
146             return True
147         else:
148             logger.warning(
149                 f'Only saw {len(self.state)} entries; needed at least {config.config["arper_min_entries_to_be_valid"]} to bother persisting.'
150             )
151             return False