blob: a48d4994fd7982bf6db79267518f8d8854bfca0d [file] [log] [blame]
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001import http.server
Patrick Williamsc124f4f2015-09-15 14:41:29 -05002import multiprocessing
3import os
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08004import traceback
5import signal
Patrick Williamsc0f7c042017-02-23 20:41:17 -06006from socketserver import ThreadingMixIn
Patrick Williamsc124f4f2015-09-15 14:41:29 -05007
Patrick Williamsc0f7c042017-02-23 20:41:17 -06008class HTTPServer(ThreadingMixIn, http.server.HTTPServer):
Patrick Williamsc124f4f2015-09-15 14:41:29 -05009
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080010 def server_start(self, root_dir, logger):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050011 os.chdir(root_dir)
12 self.serve_forever()
13
Patrick Williamsc0f7c042017-02-23 20:41:17 -060014class HTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050015
16 def log_message(self, format_str, *args):
17 pass
18
19class HTTPService(object):
20
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080021 def __init__(self, root_dir, host='', logger=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050022 self.root_dir = root_dir
23 self.host = host
24 self.port = 0
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080025 self.logger = logger
Patrick Williamsc124f4f2015-09-15 14:41:29 -050026
27 def start(self):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080028 if not os.path.exists(self.root_dir):
29 self.logger.info("Not starting HTTPService for directory %s which doesn't exist" % (self.root_dir))
30 return
31
Patrick Williamsc124f4f2015-09-15 14:41:29 -050032 self.server = HTTPServer((self.host, self.port), HTTPRequestHandler)
33 if self.port == 0:
34 self.port = self.server.server_port
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080035 self.process = multiprocessing.Process(target=self.server.server_start, args=[self.root_dir, self.logger])
36
37 # The signal handler from testimage.bbclass can cause deadlocks here
38 # if the HTTPServer is terminated before it can restore the standard
39 #signal behaviour
40 orig = signal.getsignal(signal.SIGTERM)
41 signal.signal(signal.SIGTERM, signal.SIG_DFL)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050042 self.process.start()
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080043 signal.signal(signal.SIGTERM, orig)
44
45 if self.logger:
46 self.logger.info("Started HTTPService on %s:%s" % (self.host, self.port))
47
Patrick Williamsc124f4f2015-09-15 14:41:29 -050048
49 def stop(self):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080050 if hasattr(self, "server"):
51 self.server.server_close()
52 if hasattr(self, "process"):
53 self.process.terminate()
54 self.process.join()
55 if self.logger:
56 self.logger.info("Stopped HTTPService on %s:%s" % (self.host, self.port))
57