...
1#!/usr/bin/env python3
2
3# Copyright 2019 Datawire. All rights reserved.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License
16
17import sys
18
19import logging
20import select
21import socket
22
23__version__ = '0.1.0'
24
25logging.basicConfig(
26 level=logging.DEBUG,
27 format="%%(asctime)s stats-web %s %%(levelname)s: %%(message)s" % __version__,
28 datefmt="%Y-%m-%d %H:%M:%S"
29)
30
31from flask import Flask, Response, jsonify, request
32
33__version__ = "?.?.?"
34
35app = Flask(__name__)
36
37@app.before_request
38def before():
39 logging.debug("=>> %s" % request)
40
41 for header in sorted(request.headers.keys()):
42 logging.debug("=>> %s: %s" % (header, request.headers[header]))
43
44@app.route('/', defaults={'cmd': ''})
45@app.route('/<path:cmd>')
46def hrm(cmd):
47 while cmd.startswith('/'):
48 cmd = cmd[1:]
49
50 while cmd.endswith('/'):
51 cmd = cmd[:-1]
52
53 logging.debug(f"forwarding command {cmd}")
54
55 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
56 sock.setblocking(0)
57
58 sock.sendto(bytes(cmd, "utf-8"), ('127.0.0.1', 8125))
59
60 status = 500
61 text = f'{cmd} timed out'
62
63 ready = select.select([ sock ], [], [], 2)
64
65 if ready[0]:
66 text, server_address = sock.recvfrom(8192)
67 status = 200
68
69 resp = Response(text, status=status)
70 resp.headers['X-StatsWeb-Version'] = __version__
71
72 return resp
73
74if __name__ == "__main__":
75 logging.info("initializing")
76 app.run(host='0.0.0.0', port=3000, debug=True)
View as plain text