Left: | ||
Right: |
LEFT | RIGHT |
---|---|
1 #!/usr/bin/env python3 | 1 #!/usr/bin/env python3 |
2 | 2 |
3 import argparse | 3 import argparse |
4 import re | 4 import re |
5 import sys | 5 import sys |
6 import threading | 6 import threading |
7 import traceback | |
7 | 8 |
8 from http.server import BaseHTTPRequestHandler, HTTPServer | 9 from http.server import BaseHTTPRequestHandler, HTTPServer |
9 from string import Template | 10 from string import Template |
10 | 11 |
11 PROXY_TOKEN = 'http_' | 12 # The token used for the headers passed by nginx is: http_ |
12 REGEX = '\\$' + PROXY_TOKEN + '[a-z_0-9]+\\b' | 13 REGEX = r'\$http_\w+\b' |
13 DEFAULT_LOG = '$remote_addr - - [$time_local] "$request" $status $bytes_sent' | 14 DEFAULT_LOG = '$remote_addr - - [$time_local] "$request" $status $bytes_sent' |
14 _lock = threading.Lock() | 15 _lock = threading.Lock() |
15 | 16 |
16 | 17 |
17 class Handler(BaseHTTPRequestHandler): | 18 class Handler(BaseHTTPRequestHandler): |
18 def get_header_values(self): | 19 def get_header_values(self): |
19 values = {} | 20 values = {} |
20 headers = re.findall(REGEX, self.format) | 21 headers = re.findall(REGEX, self.format) |
21 for name in headers: | 22 for name in headers: |
22 new_var = name[len(PROXY_TOKEN)+1:] | 23 new_var = name[6:].replace('_', '-') |
23 values[name[1:]] = self.headers.get(new_var, '-') | 24 values[name[1:]] = self.headers.get(new_var, '-') |
24 return values | 25 return values |
25 | 26 |
27 def send_simple_response(self, status, response=None): | |
28 self.send_response(status) | |
29 self.end_headers() | |
30 if response is None: | |
31 response = bytes(self.responses[status][0], 'UTF-8') | |
32 self.wfile.write(response) | |
33 | |
26 def write_info(self, args): | 34 def write_info(self, args): |
27 _lock.acquire() | 35 message = Template(self.format).safe_substitute(args) + '\n' |
28 message = Template(self.format) | 36 with _lock: |
Vasily Kuznetsov
2017/08/11 17:31:47
You should probably use try/finally here with the
| |
29 self.info_file.write(message.safe_substitute(args)) | 37 self.output.write(message) |
30 if self.info_file is sys.stdout: | 38 self.output.flush() |
31 self.info_file.flush() | |
32 _lock.release() | |
33 | 39 |
34 def do_POST(self): | 40 def do_POST(self): |
35 status = 200 | 41 status = 200 |
36 content = bytes(self.response, 'UTF-8') | 42 content = bytes(self.response, 'UTF-8') |
37 values = { | 43 values = { |
38 'remote_addr': self.address_string(), | 44 'remote_addr': self.address_string(), |
39 'time_local': self.log_date_time_string(), | 45 'time_local': self.log_date_time_string(), |
40 'request': self.requestline, | 46 'request': self.requestline, |
41 'status': status, | 47 'status': status, |
42 'bytes_sent': len(content), | 48 'bytes_sent': len(content), |
43 } | 49 } |
44 values.update(self.get_header_values()) | 50 values.update(self.get_header_values()) |
45 self.write_info(values) | 51 try: |
46 self.send_response(status) | 52 self.write_info(values) |
47 self.send_header('Content-Type', values['content_type']) | 53 self.send_simple_response(status, content) |
48 self.send_header('Content-Length', values['content_length']) | 54 except: |
49 self.end_headers() | 55 traceback.print_exc(file=sys.stderr) |
50 self.wfile.write(content) | 56 self.send_simple_response(500) |
51 | 57 |
52 | 58 |
53 if __name__ == '__main__': | 59 if __name__ == '__main__': |
54 parser = argparse.ArgumentParser() | 60 parser = argparse.ArgumentParser() |
55 parser.add_argument('--port', action='store', | 61 parser.add_argument('--port', action='store', |
56 default=8000, type=int, | 62 default=8000, type=int, |
57 nargs='?', | 63 nargs='?', |
58 help='Port to use [default: 8000]') | 64 help='Port to use [default: 8000]') |
59 parser.add_argument('--response', action='store', | 65 parser.add_argument('--response', action='store', |
60 type=str, nargs='?', default='OK', | 66 type=str, nargs='?', default='OK', |
61 help='The response send to the client') | 67 help='The response send to the client') |
62 parser.add_argument('--format', action='store', | 68 parser.add_argument('--format', action='store', |
63 type=str, nargs='?', | 69 type=str, nargs='?', |
64 default=DEFAULT_LOG, | 70 default=DEFAULT_LOG, |
65 help='Format of the log ouput') | 71 help='Format of the log ouput') |
66 parser.add_argument('info_file', action='store', | 72 parser.add_argument('output', action='store', |
Vasily Kuznetsov
2017/08/11 17:31:47
I'm not sure if "info_file" is the best name, it s
| |
67 type=str, nargs='?', default='-', | 73 type=str, nargs='?', default='-', |
68 help='The file where the logs will be written') | 74 help='The file where the logs will be written') |
69 args = parser.parse_args() | 75 args = parser.parse_args() |
70 setattr(Handler, 'format', args.format) | 76 if args.output and args.output != '-': |
71 setattr(Handler, 'response', args.response) | 77 fh = open(args.output, 'a') |
72 server_address = ('', args.port) | |
73 httpd = HTTPServer(server_address, Handler) | |
74 if args.info_file and args.info_file != '-': | |
75 fh = open(args.info_file, 'a') | |
76 else: | 78 else: |
77 fh = sys.stdout | 79 fh = open(sys.stdout.fileno(), 'w', closefd=False) |
78 setattr(Handler, 'info_file', fh) | |
Vasily Kuznetsov
2017/08/11 17:31:47
I think it would be more clear to order the steps
| |
79 try: | 80 try: |
81 Handler.output = fh | |
82 Handler.format = args.format | |
83 Handler.response = args.response | |
84 server_address = ('', args.port) | |
85 httpd = HTTPServer(server_address, Handler) | |
80 httpd.serve_forever() | 86 httpd.serve_forever() |
81 except: | 87 finally: |
82 if args.info_file != '-': | 88 fh.close() |
83 fh.close() | |
LEFT | RIGHT |