Ugh, a bunch of things. @overrides. --lmodule. Chromecasts. etc...
[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 * 60),
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[str, str]] = 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()
60
61     def update(self):
62         output = exec_utils.cmd(
63             '/usr/sbin/arp -a',
64             timeout_seconds=5.0
65         )
66         for line in output.split('\n'):
67             ip = string_utils.extract_ip_v4(line)
68             mac = string_utils.extract_mac_address(line)
69             if ip is not None and mac is not None:
70                 mac = mac.lower()
71                 logger.debug(f'    {mac} => {ip}')
72                 self.state[mac] = ip
73
74     def get_ip_by_mac(self, mac: str) -> Optional[str]:
75         mac = mac.lower()
76         return self.state.get(mac, None)
77
78     def get_mac_by_ip(self, ip: str) -> Optional[str]:
79         return self.state.inverse.get(ip, None)
80
81     @overrides
82     def save(self) -> bool:
83         if len(self.state) > config.config['arper_min_entries_to_be_valid']:
84             logger.debug(
85                 f'Persisting state to {config.config["arper_cache_location"]}'
86             )
87             with file_utils.FileWriter(config.config['arper_cache_location']) as wf:
88                 for (mac, ip) in self.state.items():
89                     mac = mac.lower()
90                     print(f'{mac}, {ip}', file=wf)
91             return True
92         else:
93             logger.warning(
94                 f'Only saw {len(self.state)} entries; needed at least {config.config["arper_min_entries_to_be_valid"]} to bother persisting.'
95             )
96             return False
97
98     @classmethod
99     @overrides
100     def load(cls) -> Any:
101         cache_file = config.config['arper_cache_location']
102         if persistent.was_file_written_within_n_seconds(
103                 cache_file,
104                 config.config['arper_cache_max_staleness'].total_seconds(),
105         ):
106             logger.debug(f'Loading state from {cache_file}')
107             cached_state = BiDict()
108             with open(cache_file, 'r') as rf:
109                 contents = rf.readlines()
110                 for line in contents:
111                     line = line[:-1]
112                     logger.debug(f'ARPER:{cache_file}> {line}')
113                     (mac, ip) = line.split(',')
114                     mac = mac.strip()
115                     mac = mac.lower()
116                     ip = ip.strip()
117                     cached_state[mac] = ip
118             if len(cached_state) > config.config['arper_min_entries_to_be_valid']:
119                 return cls(cached_state)
120             else:
121                 logger.warning(
122                     f'{cache_file} sucks, only {len(cached_state)} entries.  Deleting it.'
123                 )
124                 os.remove(cache_file)
125
126         logger.debug('No usable saved state found')
127         return None