blob: 58d3c3b3f87ccb8243a451382f043ee3e8176efb [file] [log] [blame]
Brad Bishopc342db32019-05-15 21:57:59 -04001#
2# SPDX-License-Identifier: MIT
3#
4
Patrick Williamsc0f7c042017-02-23 20:41:17 -06005import http.server
Patrick Williamsc124f4f2015-09-15 14:41:29 -05006import multiprocessing
7import os
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08008import traceback
9import signal
Patrick Williamsc0f7c042017-02-23 20:41:17 -060010from socketserver import ThreadingMixIn
Patrick Williamsc124f4f2015-09-15 14:41:29 -050011
Patrick Williamsc0f7c042017-02-23 20:41:17 -060012class HTTPServer(ThreadingMixIn, http.server.HTTPServer):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050013
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080014 def server_start(self, root_dir, logger):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050015 os.chdir(root_dir)
16 self.serve_forever()
17
Patrick Williamsc0f7c042017-02-23 20:41:17 -060018class HTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050019
20 def log_message(self, format_str, *args):
21 pass
22
23class HTTPService(object):
24
Andrew Geissler82c905d2020-04-13 13:39:40 -050025 def __init__(self, root_dir, host='', port=0, logger=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050026 self.root_dir = root_dir
27 self.host = host
Andrew Geissler82c905d2020-04-13 13:39:40 -050028 self.port = port
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080029 self.logger = logger
Patrick Williamsc124f4f2015-09-15 14:41:29 -050030
31 def start(self):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080032 if not os.path.exists(self.root_dir):
33 self.logger.info("Not starting HTTPService for directory %s which doesn't exist" % (self.root_dir))
34 return
35
Patrick Williamsc124f4f2015-09-15 14:41:29 -050036 self.server = HTTPServer((self.host, self.port), HTTPRequestHandler)
37 if self.port == 0:
38 self.port = self.server.server_port
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080039 self.process = multiprocessing.Process(target=self.server.server_start, args=[self.root_dir, self.logger])
40
41 # The signal handler from testimage.bbclass can cause deadlocks here
42 # if the HTTPServer is terminated before it can restore the standard
43 #signal behaviour
44 orig = signal.getsignal(signal.SIGTERM)
45 signal.signal(signal.SIGTERM, signal.SIG_DFL)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050046 self.process.start()
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080047 signal.signal(signal.SIGTERM, orig)
48
49 if self.logger:
50 self.logger.info("Started HTTPService on %s:%s" % (self.host, self.port))
51
Patrick Williamsc124f4f2015-09-15 14:41:29 -050052
53 def stop(self):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080054 if hasattr(self, "server"):
55 self.server.server_close()
56 if hasattr(self, "process"):
57 self.process.terminate()
58 self.process.join()
59 if self.logger:
60 self.logger.info("Stopped HTTPService on %s:%s" % (self.host, self.port))
61