Path: blob/master/AndroidRunner/StopRunWebserver.py
629 views
from http.server import BaseHTTPRequestHandler, HTTPServer1import threading2import paths3import os.path as op4import datetime5from .util import makedirs6import logging78class StopRunWebserver(BaseHTTPRequestHandler):9DEFAULT_SERVER_PORT = 80001011def do_GET(self): #pragma: no cover12""" Handles incoming HTTP GET requests by:13- Showing a simple webpage telling that the server is running and ready for accepting requests.14"""15self.send_response(200)16self.send_header("Content-type", "text/html")17self.end_headers()18self.wfile.write(bytes("<html><head><title>Android Runner HTTP Server</title></head>", "utf-8"))19self.wfile.write(bytes("<body>", "utf-8"))20self.wfile.write(bytes("<p>The Android Runner web server is running successfully!<br />", "utf-8"))21self.wfile.write(bytes("Send a POST request to this URL to stop the current run. </p>", "utf-8"))22self.wfile.write(bytes("</body></html>", "utf-8"))2324def do_POST(self): #pragma: no cover25""" Handles incoming HTTP POST requests by:261. writing the HTTP POST request payload to a file.272. Stopping the server so the process can write to the queue and the run is stopped.28"""29self.logger = logging.getLogger(self.__class__.__name__)3031if self.headers["Content-Length"] != None and int(self.headers["Content-Length"]) > 0:32content_length = int(self.headers['Content-Length'])33post_data = self.rfile.read(content_length)3435dir_path = op.join(paths.OUTPUT_DIR, "http_post_request_payloads")36makedirs(dir_path)3738file_ = datetime.datetime.now().strftime("%Y_%m_%dT%H_%M_%S_%f")39if self.headers["Content-type"] == "application/json":40filename = op.join(dir_path, f"{file_}.json")41else:42filename = op.join(dir_path, f"{file_}.txt")4344with open(filename, 'w+') as opened_file:45opened_file.write(post_data.decode("utf-8"))46self.logger.info(f"Wrote HTTP POST request payload to {filename}")47else:48self.logger.info("Received HTP POST request did not contain a payload.")4950self.send_response(200)51self.send_header("Access-Control-Allow-Origin", "*")52self.end_headers()5354def kill_server(server):55server.shutdown()5657threading.Thread(target=kill_server, args=(self.server,)).start()5859