Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
S2-group
GitHub Repository: S2-group/android-runner
Path: blob/master/AndroidRunner/StopRunWebserver.py
629 views
1
from http.server import BaseHTTPRequestHandler, HTTPServer
2
import threading
3
import paths
4
import os.path as op
5
import datetime
6
from .util import makedirs
7
import logging
8
9
class StopRunWebserver(BaseHTTPRequestHandler):
10
DEFAULT_SERVER_PORT = 8000
11
12
def do_GET(self): #pragma: no cover
13
""" Handles incoming HTTP GET requests by:
14
- Showing a simple webpage telling that the server is running and ready for accepting requests.
15
"""
16
self.send_response(200)
17
self.send_header("Content-type", "text/html")
18
self.end_headers()
19
self.wfile.write(bytes("<html><head><title>Android Runner HTTP Server</title></head>", "utf-8"))
20
self.wfile.write(bytes("<body>", "utf-8"))
21
self.wfile.write(bytes("<p>The Android Runner web server is running successfully!<br />", "utf-8"))
22
self.wfile.write(bytes("Send a POST request to this URL to stop the current run. </p>", "utf-8"))
23
self.wfile.write(bytes("</body></html>", "utf-8"))
24
25
def do_POST(self): #pragma: no cover
26
""" Handles incoming HTTP POST requests by:
27
1. writing the HTTP POST request payload to a file.
28
2. Stopping the server so the process can write to the queue and the run is stopped.
29
"""
30
self.logger = logging.getLogger(self.__class__.__name__)
31
32
if self.headers["Content-Length"] != None and int(self.headers["Content-Length"]) > 0:
33
content_length = int(self.headers['Content-Length'])
34
post_data = self.rfile.read(content_length)
35
36
dir_path = op.join(paths.OUTPUT_DIR, "http_post_request_payloads")
37
makedirs(dir_path)
38
39
file_ = datetime.datetime.now().strftime("%Y_%m_%dT%H_%M_%S_%f")
40
if self.headers["Content-type"] == "application/json":
41
filename = op.join(dir_path, f"{file_}.json")
42
else:
43
filename = op.join(dir_path, f"{file_}.txt")
44
45
with open(filename, 'w+') as opened_file:
46
opened_file.write(post_data.decode("utf-8"))
47
self.logger.info(f"Wrote HTTP POST request payload to {filename}")
48
else:
49
self.logger.info("Received HTP POST request did not contain a payload.")
50
51
self.send_response(200)
52
self.send_header("Access-Control-Allow-Origin", "*")
53
self.end_headers()
54
55
def kill_server(server):
56
server.shutdown()
57
58
threading.Thread(target=kill_server, args=(self.server,)).start()
59