70 lines
2.1 KiB
Python
70 lines
2.1 KiB
Python
from http.server import HTTPServer, BaseHTTPRequestHandler
|
|
import json
|
|
import os
|
|
import threading
|
|
import logging
|
|
|
|
from wsgiref.simple_server import make_server
|
|
from pyramid.config import Configurator
|
|
|
|
|
|
def service_discovery(request):
|
|
discovery_data = request.json_body
|
|
|
|
outdir = request.registry.settings['outdir']
|
|
service = request.matchdict['service']
|
|
key = request.matchdict['key']
|
|
filename = os.path.join(outdir, f'{service}-{key}.json')
|
|
|
|
try:
|
|
with open(filename, 'w') as outfile:
|
|
logging.info('Writting new configuration at %s', filename)
|
|
json.dump(discovery_data, outfile, indent=4, sort_keys=True)
|
|
except Exception as e:
|
|
logging.exception('Error writing discovery file')
|
|
request.response.status = 500
|
|
return {"status": "Error"}
|
|
|
|
request.response.status = 204
|
|
return {"status": "Created"}
|
|
|
|
|
|
def status(request):
|
|
return {'status': 'ok'}
|
|
|
|
|
|
class ServerController(threading.Thread):
|
|
def __init__(self, ip, port, outdir):
|
|
super().__init__()
|
|
self.server_addr = (ip, port)
|
|
with Configurator(settings={'outdir': outdir}) as config:
|
|
config.add_route('service_discovery', '/{service}/{key}')
|
|
config.add_route('status', '/status')
|
|
config.add_view(
|
|
service_discovery,
|
|
route_name='service_discovery',
|
|
request_method='POST',
|
|
renderer='json')
|
|
config.add_view(
|
|
status,
|
|
route_name='status',
|
|
request_method='GET',
|
|
renderer='json')
|
|
app = config.make_wsgi_app()
|
|
|
|
self.httpd = make_server(ip, port, app)
|
|
self.http_thread = threading.Thread(target=self.httpd.serve_forever)
|
|
|
|
def run(self):
|
|
logging.info('Starting server, listening on %s:%d', *self.server_addr)
|
|
self.http_thread.start()
|
|
|
|
def stop(self):
|
|
logging.info('Stoping server')
|
|
self.httpd.shutdown()
|
|
|
|
|
|
def start_server(ip, port, outdir):
|
|
server = ServerController(ip, port, outdir)
|
|
return server
|