fix: standalone tap-proxy.py — no more nested f-string mess
This commit is contained in:
parent
c17a44f077
commit
853aad8a36
2 changed files with 61 additions and 42 deletions
|
|
@ -398,56 +398,24 @@ def start_debug():
|
||||||
if idx < 0 or idx >= len(s): return
|
if idx < 0 or idx >= len(s): return
|
||||||
n = s[idx]
|
n = s[idx]
|
||||||
port = str(n.get('port', '8081'))
|
port = str(n.get('port', '8081'))
|
||||||
|
backend = f"{n.get('upstream_ip','127.0.0.1')}:{n.get('upstream_port','80')}"
|
||||||
|
logdir = f"{BASE}/{n['name']}"
|
||||||
|
os.makedirs(logdir, exist_ok=True)
|
||||||
|
|
||||||
# Write tap proxy script
|
tap_script = f"{BASE}/app/tap-proxy.py"
|
||||||
tap = f"""{BASE}/app/tap-proxy.py"""
|
|
||||||
with open(tap, "w") as f:
|
|
||||||
f.write(f'''#!/usr/bin/env python3
|
|
||||||
import http.server, urllib.request, os
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
BACKEND = "http://{n.get('upstream_ip','127.0.0.1')}:{n.get('upstream_port','80')}"
|
|
||||||
LOG = "{BASE}/{n['name']}/tap-{{}}.log".format(datetime.now().strftime("%Y%m%d-%H%M%S"))
|
|
||||||
|
|
||||||
class Tap(http.server.BaseHTTPRequestHandler):
|
|
||||||
def do_GET(self): self._tap('GET')
|
|
||||||
def do_POST(self): self._tap('POST')
|
|
||||||
def do_PUT(self): self._tap('PUT')
|
|
||||||
def _tap(self, method):
|
|
||||||
now = datetime.now().strftime('%H:%M:%S')
|
|
||||||
msg = f"\\n{'='*60}\\n[{{now}}] {method} {self.path}\\nClient: {self.client_address[0]}\\n"
|
|
||||||
for k,v in sorted(self.headers.items()): msg += f" {k}: {v}\\n"
|
|
||||||
body = self.rfile.read(int(self.headers.get('Content-Length',0))) if 'Content-Length' in self.headers else None
|
|
||||||
req = urllib.request.Request(f"{{BACKEND}}{{self.path}}", data=body, method=method)
|
|
||||||
for k,v in self.headers.items():
|
|
||||||
if k.lower() not in ('host','connection'): req.add_header(k,v)
|
|
||||||
resp = urllib.request.urlopen(req, timeout=30)
|
|
||||||
msg += f"\\nRESPONSE: {resp.status}\\n"
|
|
||||||
for k,v in resp.getheaders(): msg += f" {k}: {v}\\n"
|
|
||||||
self.send_response(resp.status)
|
|
||||||
for k,v in resp.getheaders():
|
|
||||||
if k.lower() not in ('transfer-encoding','connection'): self.send_header(k,v)
|
|
||||||
self.end_headers(); self.wfile.write(resp.read())
|
|
||||||
with open(LOG, "a") as l: l.write(msg)
|
|
||||||
def log_message(self,*a): pass
|
|
||||||
|
|
||||||
print(f"Tap proxy :{port} → {{BACKEND}}\\nLog: {{LOG}}\\nCtrl+C to stop")
|
|
||||||
http.server.HTTPServer(('0.0.0.0',{port}), Tap).serve_forever()
|
|
||||||
''')
|
|
||||||
os.chmod(tap, 0o755)
|
|
||||||
|
|
||||||
# Stop container, start tap
|
# Stop container, start tap
|
||||||
print(f"\\nStopping wallarm-{n['name']}...")
|
print(f"\nStopping wallarm-{n['name']}...")
|
||||||
run(f"docker stop wallarm-{n['name']} 2>/dev/null", timeout=10)
|
run(f"docker stop wallarm-{n['name']} 2>/dev/null", timeout=10)
|
||||||
print(f"Starting tap proxy on port {port}...")
|
print(f"Tap proxy :{port} → {backend}")
|
||||||
print(f"Log: {BASE}/{n['name']}/tap-*.log")
|
print(f"Log: {logdir}/tap-*.log")
|
||||||
print("Press Ctrl+C to stop, container will restart automatically.")
|
print("Press Ctrl+C to stop — container will restart automatically.\n")
|
||||||
try:
|
try:
|
||||||
run(f"python3 {tap}", timeout=300)
|
run(f"python3 {tap_script} {port} {backend} {logdir}", timeout=300)
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
finally:
|
finally:
|
||||||
print(f"\\nRestarting wallarm-{n['name']}...")
|
print(f"\nRestarting wallarm-{n['name']}...")
|
||||||
run(f"docker start wallarm-{n['name']} 2>/dev/null || bash {BASE}/{n['name']}/start.sh", timeout=30)
|
run(f"docker start wallarm-{n['name']} 2>/dev/null || bash {BASE}/{n['name']}/start.sh", timeout=30)
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
|
|
||||||
51
sources/python/tap-proxy.py
Normal file
51
sources/python/tap-proxy.py
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Tap Proxy — logs HTTP headers. Usage: python3 tap-proxy.py <port> <backend_host:port> <log_dir>"""
|
||||||
|
import http.server, urllib.request, sys
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8081
|
||||||
|
BACKEND = sys.argv[2] if len(sys.argv) > 2 else "127.0.0.1:80"
|
||||||
|
LOG = (sys.argv[3] if len(sys.argv) > 3 else "/tmp") + "/tap-" + datetime.now().strftime("%Y%m%d-%H%M%S") + ".log"
|
||||||
|
BACKEND_URL = "http://" + BACKEND
|
||||||
|
|
||||||
|
class Tap(http.server.BaseHTTPRequestHandler):
|
||||||
|
def do_GET(self): self._tap('GET')
|
||||||
|
def do_POST(self): self._tap('POST')
|
||||||
|
def do_PUT(self): self._tap('PUT')
|
||||||
|
def do_DELETE(self): self._tap('DELETE')
|
||||||
|
|
||||||
|
def _tap(self, method):
|
||||||
|
now = datetime.now().strftime('%H:%M:%S')
|
||||||
|
msg = "\n" + "="*60 + "\n[" + now + "] " + method + " " + self.path
|
||||||
|
msg += "\nClient: " + self.client_address[0] + "\n" + "-"*60 + "\n"
|
||||||
|
for k, v in sorted(self.headers.items()):
|
||||||
|
msg += " " + k + ": " + v + "\n"
|
||||||
|
|
||||||
|
body = self.rfile.read(int(self.headers.get('Content-Length', 0))) if 'Content-Length' in self.headers else None
|
||||||
|
req = urllib.request.Request(BACKEND_URL + self.path, data=body, method=method)
|
||||||
|
for k, v in self.headers.items():
|
||||||
|
if k.lower() not in ('host', 'connection'):
|
||||||
|
req.add_header(k, v)
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = urllib.request.urlopen(req, timeout=30)
|
||||||
|
msg += "\nRESPONSE: " + str(resp.status) + "\n"
|
||||||
|
for k, v in resp.getheaders():
|
||||||
|
msg += " " + k + ": " + v + "\n"
|
||||||
|
self.send_response(resp.status)
|
||||||
|
for k, v in resp.getheaders():
|
||||||
|
if k.lower() not in ('transfer-encoding', 'connection'):
|
||||||
|
self.send_header(k, v)
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(resp.read())
|
||||||
|
except Exception as e:
|
||||||
|
msg += "\nERROR: " + str(e) + "\n"
|
||||||
|
self.send_error(502)
|
||||||
|
|
||||||
|
with open(LOG, "a") as f:
|
||||||
|
f.write(msg)
|
||||||
|
|
||||||
|
def log_message(self, *args): pass
|
||||||
|
|
||||||
|
print("Tap proxy :{0} -> {1}\nLog: {2}\nCtrl+C to stop".format(PORT, BACKEND_URL, LOG))
|
||||||
|
http.server.HTTPServer(('0.0.0.0', PORT), Tap).serve_forever()
|
||||||
Loading…
Reference in a new issue