Skip to content

Instantly share code, notes, and snippets.

@rewitt1
Created June 6, 2016 22:43
Show Gist options
  • Save rewitt1/41a2e6e2160e92ab98fbbcd6e06610aa to your computer and use it in GitHub Desktop.
Save rewitt1/41a2e6e2160e92ab98fbbcd6e06610aa to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# webhook.py
#
# Copyright (C) 2016 Intel Corporation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import socket
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
class SocketEnvironmentError(Exception):
pass
# Same as HTTPServer, just requires you to pass in a socket or for it to get
# one from the environment.
class HTTPServerInherit(HTTPServer):
def __init__(self, *args, **kwargs):
newsocket = self._get_socket_from_systemd()
# Since we can't prevent the server from creating a socket, just close
# it and use the new one before activating the server.
super().__init__(*args, bind_and_activate=False, **kwargs)
self.socket.close()
self.socket = newsocket
def _get_socket_from_systemd(self):
if 'LISTEN_PID' in os.environ:
if os.environ['LISTEN_PID'] != str(os.getpid()):
raise SocketEnvironmentError("LISTEN_PID not correct")
else:
raise SocketEnvironmentError("LISTEN_PID not in environment")
# Macro typically specified by systemd code
SD_LISTEN_FDS_START = 3
return socket.socket(fileno=SD_LISTEN_FDS_START)
class PostHandler(BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers.get('Content-Length'))
if not length:
self.send_response(400, 'foo not in headers')
self.end_headers()
else:
print(self.rfile.read(length))
self.send_response(200, 'OK')
self.end_headers()
if __name__ == "__main__":
try:
httpd = HTTPServerInherit(("127.0.0.1", 18000), PostHandler)
httpd.serve_forever()
except SocketEnvironmentError as e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment