|
| 1 | +#!/usr/bin/python3 |
| 2 | + |
| 3 | +import sys |
| 4 | +import os |
| 5 | +import signal |
| 6 | +import time |
| 7 | +import http.server |
| 8 | +import socketserver |
| 9 | +import daemon |
| 10 | + |
| 11 | + |
| 12 | +PID_FILE = "webserver.pid" |
| 13 | +LOG_FILE = "webserver.log" |
| 14 | +HTTP_PORT = 8000 |
| 15 | + |
| 16 | + |
| 17 | +def kill_instance(pid): |
| 18 | + while True: |
| 19 | + try: |
| 20 | + os.kill(pid, 0) |
| 21 | + except OSError: |
| 22 | + try: |
| 23 | + os.remove(PID_FILE) |
| 24 | + except FileNotFoundError: |
| 25 | + pass |
| 26 | + return |
| 27 | + print(f"Killing previous webserver instance with pid {pid}") |
| 28 | + try: |
| 29 | + os.kill(pid, signal.SIGTERM) |
| 30 | + except OSError: |
| 31 | + pass |
| 32 | + time.sleep(.1) |
| 33 | + |
| 34 | +class SafeHTTPRequestHandler(http.server.SimpleHTTPRequestHandler): |
| 35 | + def send_head(self): |
| 36 | + path = self.translate_path(self.path) |
| 37 | + if os.path.isdir(path): |
| 38 | + for index in ("index.html", "index.htm"): |
| 39 | + index = os.path.join(path, index) |
| 40 | + if os.path.exists(index): |
| 41 | + path = index |
| 42 | + break |
| 43 | + else: |
| 44 | + return self.list_directory(path) |
| 45 | + if not os.path.exists(path): |
| 46 | + self.send_error(404, f"File not found: {self.path}") |
| 47 | + return None |
| 48 | + return http.server.SimpleHTTPRequestHandler.send_head(self) |
| 49 | + |
| 50 | +class ReusableTCPServer(socketserver.TCPServer): |
| 51 | + allow_reuse_address = True |
| 52 | + |
| 53 | +def run_server(port): |
| 54 | + with open(PID_FILE, "w") as f: |
| 55 | + f.write(str(os.getpid())) |
| 56 | + with ReusableTCPServer(("", port), SafeHTTPRequestHandler) as httpd: |
| 57 | + print(f"Serving HTTP on port {port}") |
| 58 | + httpd.serve_forever() |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | +def main(): |
| 63 | + if len(sys.argv) > 1: |
| 64 | + port = sys.argv[1] |
| 65 | + try: |
| 66 | + port = int(port) |
| 67 | + except ValueError: |
| 68 | + raise RuntimeError(f"Bad port value: {port}") |
| 69 | + else: |
| 70 | + port = 8000 |
| 71 | + os.chdir(os.path.dirname(sys.argv[0])) |
| 72 | + os.chdir("bin") |
| 73 | + try: |
| 74 | + with open(PID_FILE) as pid: |
| 75 | + pid = int(pid.read()) |
| 76 | + except FileNotFoundError: |
| 77 | + pid = None |
| 78 | + if pid: |
| 79 | + kill_instance(pid) |
| 80 | + # MAIN |
| 81 | + log_file = open(LOG_FILE, "a+") |
| 82 | + with daemon.DaemonContext( |
| 83 | + stderr = log_file, |
| 84 | + stdout = log_file, |
| 85 | + working_directory = os.getcwd() |
| 86 | + ): |
| 87 | + try: |
| 88 | + run_server(port) |
| 89 | + except Exception as e: |
| 90 | + try: |
| 91 | + print(f"Removing pid file {PID_FILE}") |
| 92 | + os.remove(PID_FILE) |
| 93 | + except: |
| 94 | + pass |
| 95 | + raise e |
| 96 | + |
| 97 | +if __name__ == "__main__": |
| 98 | + main() |
| 99 | + |
0 commit comments