Created
November 10, 2016 15:32
-
-
Save evandhoffman/5048374cfbd3bf2d11a6d60f9ce20ea6 to your computer and use it in GitHub Desktop.
Echoservice - service that registers itself with consul and starts a webserver. Useful for playing with Traefik.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SimpleHTTPServer | |
import SocketServer | |
import requests | |
import json | |
import getopt, sys | |
CONSUL_URL = 'http://localhost:8500' | |
# https://www.consul.io/docs/agent/http/agent.html#agent_service_register | |
def register_service(name, address, port): | |
request = { 'Name': name, | |
'Tags': [ 'echo', name ], | |
'Address': address, | |
'Port': port, | |
'Check': { | |
'DeregisterCriticalServiceAfter': '1m', | |
'HTTP': "http://%s:%d/" % ( address, port), | |
'Interval': "10s" | |
} | |
} | |
payload = json.dumps(request) | |
r = requests.post("%s/v1/agent/service/register" % CONSUL_URL, data=payload) | |
print "Made request: %s" % payload | |
print "full response: %s" % r | |
def start_server(port): | |
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler | |
httpd = SocketServer.TCPServer(("", port), Handler) | |
httpd.serve_forever() | |
def main(argv): | |
try: | |
opts, args = getopt.getopt(argv,"a:p:n:") | |
except getopt.GetoptError: | |
sys.exit(2) | |
for opt, arg in opts: | |
if opt == '-p': | |
svc_port = int(arg) | |
elif opt == '-n': | |
svc_name = arg | |
elif opt == '-a': | |
svc_addr = arg | |
else: | |
print "invalid option: %s" % opt | |
sys.exit(2) | |
print "Registering service" | |
register_service(svc_name, svc_addr, svc_port) | |
print "serving at port", svc_port | |
start_server(svc_port) | |
if __name__ == "__main__": | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment