Documentation
[re6stnet.git] / re6st / utils.py
1 import argparse, errno, logging, os, signal, struct, socket, textwrap, time
2 from OpenSSL import crypto
3
4 logging_levels = logging.WARNING, logging.INFO, logging.DEBUG, 5
5
6 class FileHandler(logging.FileHandler):
7
8 _reopen = False
9
10 def release(self):
11 try:
12 if self._reopen:
13 self._reopen = False
14 self.close()
15 self._open()
16 finally:
17 self.lock.release()
18 # In the rare case _reopen is set just before the lock was released
19 if self._reopen and self.lock.acquire(0):
20 self.release()
21
22 def async_reopen(self, *_):
23 self._reopen = True
24 if self.lock.acquire(0):
25 self.release()
26
27 def setupLog(log_level, filename=None, **kw):
28 if log_level and filename:
29 makedirs(os.path.dirname(filename))
30 handler = FileHandler(filename)
31 sig = handler.async_reopen
32 else:
33 handler = logging.StreamHandler()
34 sig = signal.SIG_IGN
35 handler.setFormatter(logging.Formatter(
36 '%(asctime)s %(levelname)-9s %(message)s', '%d-%m-%Y %H:%M:%S'))
37 root = logging.getLogger()
38 root.addHandler(handler)
39 signal.signal(signal.SIGUSR1, sig)
40 if log_level:
41 root.setLevel(logging_levels[log_level-1])
42 else:
43 logging.disable(logging.CRITICAL)
44 logging.addLevelName(5, 'TRACE')
45 logging.trace = lambda *args, **kw: logging.log(5, *args, **kw)
46
47
48 class HelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
49
50 def _get_help_string(self, action):
51 return super(HelpFormatter, self)._get_help_string(action) \
52 if action.default else action.help
53
54 def _split_lines(self, text, width):
55 """Preserves new lines in option descriptions"""
56 lines = []
57 for text in text.splitlines():
58 lines += textwrap.wrap(text, width)
59 return lines
60
61 def _fill_text(self, text, width, indent):
62 """Preserves new lines in other descriptions"""
63 kw = dict(width=width, initial_indent=indent, subsequent_indent=indent)
64 return '\n'.join(textwrap.fill(t, **kw) for t in text.splitlines())
65
66 class ArgParser(argparse.ArgumentParser):
67
68 class _HelpFormatter(HelpFormatter):
69
70 def _format_actions_usage(self, actions, groups):
71 r = HelpFormatter._format_actions_usage(self, actions, groups)
72 if actions and actions[0].option_strings:
73 r = '[@OPTIONS_FILE] ' + r
74 return r
75
76 _ca_help = "Certificate authority (CA) file in .pem format." \
77 " Serial number defines the prefix of the network."
78
79 def convert_arg_line_to_args(self, arg_line):
80 arg_line = arg_line.split('#')[0].rstrip()
81 if arg_line:
82 if arg_line.startswith('@'):
83 yield arg_line
84 return
85 for arg in ('--' + arg_line.lstrip('--')).split():
86 if arg.strip():
87 yield arg
88
89 def __init__(self, **kw):
90 super(ArgParser, self).__init__(formatter_class=self._HelpFormatter,
91 epilog="""Options can be read from a file. For example:
92 $ cat OPTIONS_FILE
93 ca /etc/re6stnet/ca.crt""", **kw)
94
95
96 def makedirs(path):
97 try:
98 os.makedirs(path)
99 except OSError, e:
100 if e.errno != errno.EEXIST:
101 raise
102
103 def binFromIp(ip):
104 ip1, ip2 = struct.unpack('>QQ', socket.inet_pton(socket.AF_INET6, ip))
105 return bin(ip1)[2:].rjust(64, '0') + bin(ip2)[2:].rjust(64, '0')
106
107
108 def ipFromBin(prefix, suffix=''):
109 ip = prefix + suffix.rjust(128 - len(prefix), '0')
110 return socket.inet_ntop(socket.AF_INET6,
111 struct.pack('>QQ', int(ip[:64], 2), int(ip[64:], 2)))
112
113 def networkFromCa(ca_path):
114 # Get network prefix from ca.crt
115 with open(ca_path, 'r') as f:
116 ca = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
117 return bin(ca.get_serial_number())[3:]
118
119 def subnetFromCert(cert_path):
120 # Get ip from cert.crt
121 with open(cert_path, 'r') as f:
122 cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
123 return cert.get_subject().CN
124
125 def address_str(address):
126 return ';'.join(map(','.join, address))
127
128
129 def address_list(address_list):
130 return list(tuple(address.split(','))
131 for address in address_list.split(';'))
132
133
134 def binFromSubnet(subnet):
135 p, l = subnet.split('/')
136 return bin(int(p))[2:].rjust(int(l), '0')