-
-
Save Morabaraba/e93a9f3e18e0d8916051ef119e48a00e to your computer and use it in GitHub Desktop.
Register mqtt/ssl Consul Services using the rabbitmq service health check and amqp Service.Tags
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
#!/usr/libexec/platform-python | |
import urllib.request | |
import json | |
import sys | |
SERVER = 'http://127.0.0.1:8500' | |
HEALTH_CHECK_RABBITMQ_AMQP = '/v1/health/service/rabbitmq?filter=%22amqp%22%20in%20Service.Tags' | |
HEALTH_CHECK_RABBITMQ_MQTT = '/v1/health/service/rabbitmq?filter=%22mqtt_ssl%22%20in%20Service.Tags' | |
SERVICE_REGISTER = '/v1/agent/service/register' | |
SERVICE_DEREGISTER = '/v1/agent/service/deregister/' | |
SERVICE_TEMPLATE = { | |
"Name": "rabbitmq", | |
"Tags": ["mqtt_ssl"], | |
"Port": 8883 | |
} | |
def get_url(url): | |
response = urllib.request.urlopen(url) | |
data = response.read() # a `bytes` object | |
text = data.decode('utf-8') # a `str`; this step can't be used if data is binary | |
return text | |
def put_url(url, data): | |
print(url) | |
req = urllib.request.Request(url=url, data=data, method='PUT') | |
return urllib.request.urlopen(req) | |
def clone(obj): | |
return json.loads(json.dumps(obj)) | |
def register(): | |
health_json = json.loads(get_url(SERVER + HEALTH_CHECK_RABBITMQ_AMQP)) | |
for instance in health_json: | |
mqtt_service = clone(SERVICE_TEMPLATE) | |
mqtt_service['ID'] = instance['Service']['ID'] + '-mqtt' | |
mqtt_service['Address'] = instance['Service']['Address'] | |
data = bytes(json.dumps(mqtt_service), encoding='utf8') | |
print(data) | |
with put_url(SERVER + SERVICE_REGISTER, data) as f: | |
print(f.status) | |
print(f.reason) | |
def deregister(): | |
health_json = json.loads(get_url(SERVER + HEALTH_CHECK_RABBITMQ_MQTT)) | |
for instance in health_json: | |
put_url(SERVER + SERVICE_DEREGISTER + instance['Service']['ID'], b'') | |
if len(sys.argv) < 2: | |
print('argument 1 must be either "register" or "deregister"') | |
exit(1) | |
if sys.argv[1] == 'register': | |
register() | |
elif sys.argv[1] == 'deregister': | |
deregister() | |
else: | |
print('argument 1 must be either "register" or "deregister"') | |
exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment