Skip to content

Instantly share code, notes, and snippets.

@evilabandon
Forked from feisuzhu/marathon-upstreams
Last active August 29, 2015 14:23
Show Gist options
  • Save evilabandon/b47fcbfdb0aa5b5abde1 to your computer and use it in GitHub Desktop.
Save evilabandon/b47fcbfdb0aa5b5abde1 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# -- stdlib --
import json
import os
import urllib2
# -- third party --
# -- own --
# -- code --
MARATHON = os.environ.get('MARATHON', 'http://mesos1:8080')
nginx_apps = set()
upstream_conf = {}
json_opener = urllib2.build_opener()
json_opener.addheaders = [('Accept', 'application/json')]
conf = json.loads(json_opener.open(MARATHON + '/v2/apps').read())['apps']
'''
{
"labels": {
"nginx-13001": "ip-hash;",
"nginx-13002": "foo; bar; baz;;;",
"nginx-default": "meh; moo; meow"
}
}
'''
for app in conf:
lbls = app['labels']
for k, v in lbls.items():
if not k.startswith('nginx-'):
continue
app_id = app['id'][1:]
k = '%s-%s' % (app_id, k[6:])
options = [i.strip() for i in v.split(';')]
options = [i for i in options if i]
upstream_conf[k] = ''.join([' %s;\n' % i for i in options])
nginx_apps.add(app_id)
def get_conf(app, srv_port):
k = '%s-%s' % (app, srv_port)
if k in upstream_conf:
return upstream_conf[k]
return upstream_conf.get('%s-default' % app, '')
for srv in urllib2.urlopen(MARATHON + '/v2/tasks').readlines():
srv = srv.split('\t')
srv = map(str.strip, srv)
if len(srv) < 2:
continue
if not srv[1]: # srv port
continue
app, port = srv[:2]
if app not in nginx_apps:
continue
print "upstream %s-%s {" % (app, port)
print get_conf(app, port)
for task in srv[2:]:
task = task.strip()
if not task: continue
print " server %s;" % task
print "}\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment