-
Notifications
You must be signed in to change notification settings - Fork 4
/
httpd-true
executable file
·63 lines (51 loc) · 2 KB
/
httpd-true
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
53
54
55
56
57
58
59
60
61
62
63
#!/bin/env python3
import os
import sys
import time
import socket
import http.server
def get_systemd_socket():
"""Shows how to get the socket"""
SYSTEMD_FIRST_SOCKET_FD = 3
socket_type = http.server.HTTPServer.socket_type
address_family = http.server.HTTPServer.address_family
return socket.fromfd(SYSTEMD_FIRST_SOCKET_FD, address_family, socket_type)
class RequestHandler(http.server.BaseHTTPRequestHandler):
"""Returns the string 'true' to all requests"""
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b"true")
self.wfile.write(b"\n")
return
do_POST = do_GET
class SockInheritHTTPServer(http.server.HTTPServer):
def __init__(self, address_info, handler, bind_and_activate=True):
# Note that we call it with bind_and_activate = False.
http.server.HTTPServer.__init__(self,
address_info,
handler,
bind_and_activate=False)
# The socket from systemd needs to be set AFTER calling the parent's
# class's constructor, otherwise HTTPServer.__init__() will re-set
# self.socket() and the handover won't work.
self.socket = get_systemd_socket()
if bind_and_activate:
self.server_activate()
def wait_loop(delay=60):
# The connection/port/host doesn't really matter as we don't allocate the
# socket ourselves. Pass it in as localhost:80
httpserv = SockInheritHTTPServer(('localhost', 80), RequestHandler)
httpserv.timeout = 1
start = time.monotonic()
end = start + delay
while time.monotonic() < end:
httpserv.handle_request()
httpserv.server_close()
if __name__ == "__main__":
if os.environ.get('LISTEN_PID', None) == str(os.getpid()):
wait_loop()
print("Done serving, shutting down")
sys.exit()
else:
raise SystemExit("This server should only run from systemd")