BaseHTTPRequestHandler - handling temporary loss of served directory

12/16/2019

My http server serves files from directory. Everything works fine, unless served files got updated (git) - temporarily the folder is unacessible for a moment. it is being mounted from separate git sync container and it creates a softlink

filesystem:
lrwxrwxrwx    1 65533    nogroup         44 Dec 16 15:48 directory -> rev-05d85b09143cf7205e00ce1c50afaa18a26b6e61

code:

def main():    
    os.chdir(root)    
    server = HTTPServer(('0.0.0.0', 80), MyHandler)
    server.serve_forever()

After such event the server is not serving files anymore. My guess is I should use try-except, some sleep and restart. Is it the best way of doing so?

I tried:

def main():
    while True:
        try:
            os.chdir(root)
            server = HTTPServer(('0.0.0.0', 80), MyHandler)
            server.serve_forever()
        except Exception as e:
            logger.warning("Cannot access root dir, possibly new git commit")
            time.sleep(5)
        continue

but no luck... it stops serving after dir being unaccessible Whats more, exception is being thrown, but the except clause is never executed. its just happy to print to console

Exception happened during processing of request from ('10.0.8.214', 58676)
Traceback (most recent call last):
  File "/usr/lib/python3.7/socketserver.py", line 316, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python3.7/socketserver.py", line 347, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python3.7/socketserver.py", line 360, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python3.7/http/server.py", line 644, in __init__
    directory = os.getcwd()
FileNotFoundError: [Errno 2] No such file or directory
-- Wojtas.Zet
docker
httpserver
kubernetes
python-3.x

0 Answers