From 853aad8a365a682a881fdceceb59a2bb1b7abbe1 Mon Sep 17 00:00:00 2001 From: admin Date: Fri, 7 Aug 2026 17:33:58 +0000 Subject: [PATCH] =?UTF-8?q?fix:=20standalone=20tap-proxy.py=20=E2=80=94=20?= =?UTF-8?q?no=20more=20nested=20f-string=20mess?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sources/python/main.py | 52 +++++++------------------------------ sources/python/tap-proxy.py | 51 ++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 42 deletions(-) create mode 100644 sources/python/tap-proxy.py diff --git a/sources/python/main.py b/sources/python/main.py index c480046..722882f 100644 --- a/sources/python/main.py +++ b/sources/python/main.py @@ -398,56 +398,24 @@ def start_debug(): if idx < 0 or idx >= len(s): return n = s[idx] 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 = 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) + tap_script = f"{BASE}/app/tap-proxy.py" # 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) - print(f"Starting tap proxy on port {port}...") - print(f"Log: {BASE}/{n['name']}/tap-*.log") - print("Press Ctrl+C to stop, container will restart automatically.") + print(f"Tap proxy :{port} → {backend}") + print(f"Log: {logdir}/tap-*.log") + print("Press Ctrl+C to stop — container will restart automatically.\n") try: - run(f"python3 {tap}", timeout=300) + run(f"python3 {tap_script} {port} {backend} {logdir}", timeout=300) except: pass 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) if __name__ == "__main__": main() diff --git a/sources/python/tap-proxy.py b/sources/python/tap-proxy.py new file mode 100644 index 0000000..5b36b8d --- /dev/null +++ b/sources/python/tap-proxy.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Tap Proxy — logs HTTP headers. Usage: python3 tap-proxy.py """ +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()