aboutsummaryrefslogtreecommitdiffstats
path: root/examples/einhorn_http.py
blob: 304d01ae169494ec5690fbdd5554dd05547e535d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env python3
"""
This small example program demonstrates one way to integerate with Einhorn using
Python (3).

It serves up the current working directory over HTTP on either the
Einhorn-supplied socket or localhost:8080.
"""

import os
import sys
import socket
import socketserver
import http.server

class EinhornTCPServer(socketserver.TCPServer):

    def __init__(self, server_address, RequestHandlerClass):
        socketserver.BaseServer.__init__(self, server_address, RequestHandlerClass)

        # Try to sniff first socket
        try:
            fd = int(os.environ['EINHORN_FD_0'])
            print("Will try to listen with fd=%d" % fd)
        except KeyError:
            raise EnvironmentError("Couldn't find EINHORN_FD_0 env variable... is this running under einhorn?")

        self.socket = socket.socket(fileno=fd)
        # alternative?
        #self.socket = socket.fromfd(socket.AF_INET, socket.SOCK_STREAM, fd)

        try:
            self.server_activate()
        except:
            self.server_close()
            raise

if __name__ == "__main__":
    Handler = http.server.SimpleHTTPRequestHandler
    try:
        httpd = EinhornTCPServer(None, Handler)
    except EnvironmentError as ee:
        print(ee)
        print("Falling back on vanilla http server on 8080")
        httpd = socketserver.TCPServer(("localhost", 8080), Handler)

    print("Serving!")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("Caught KeyboardInterrupt, shutting down")
        httpd.server_close()