blob: c62ca58b0500d7d2b57bc8000398a327b8c9fef8 [file] [log] [blame]
alshabibc67ee3a2016-10-25 23:24:03 -07001import consul
2from structlog import get_logger
3from twisted.internet import reactor
4from twisted.internet.defer import inlineCallbacks, Deferred, returnValue
5
6from common.utils.dockerhelpers import create_container_network, start_container
7
8containers = {
9 'chameleon' : {
10 'image' : 'opencord/chameleon',
11 'command' : [ "/chameleon/main.py",
12 "-v",
13 "--consul=consul:8500",
14 "--fluentd=fluentd:24224",
15 "--rest-port=8881",
16 "--grpc-endpoint=@voltha-grpc",
17 "--instance-id-is-container-name",
18 "-v"],
19 'ports' : [ 8881 ],
20 'depends_on' : [ "consul", "voltha" ],
21 'links' : [ "consul", "fluentd" ],
22 'environment' : ["SERVICE_8881_NAME=chamleon-rest"],
23 'volumes' : '/var/run/docker.sock:/tmp/docker.sock'
24 }
25}
26
27class ConsulManager(object):
28
29 log = get_logger()
30
31 def __init__(self, arg):
32 self.log.info('Initializing consul manager')
33 self.running = False
34 self.index = 0
35 (host, port) = arg.split(':')
36 self.conn = consul.Consul(host=host, port=port)
37
38 @inlineCallbacks
39 def run(self):
40 if self.running:
41 return
42 self.running = True
43
44 self.log.info('Running consul manager')
45
46 reactor.callLater(0, self.provision_voltha_instances())
47
48 reactor.addSystemEventTrigger('before', 'shutdown', self.shutdown)
49 returnValue(self)
50
51 @inlineCallbacks
52 def shutdown(self):
53 self.log.info('Shutting down consul manager')
54 self.running = False
55
56 @inlineCallbacks
57 def provision_voltha_instances(self):
58 while True:
59 if not self.running:
60 return
61 # maintain index such that callbacks only happen is something has changed
62 # timeout is default to 5m
63 (self.index, data) = self.conn.catalog.service(service='voltha-grpc',
64 index=self.index)
65 self.start_containers(data)
66
67 def start_containers(self, data):
68 for item in data:
69 serviceId = item['ServiceID'].split(':')[1].split('_')[2]
70 serviceTags = item['ServiceTags']
71 self.log.info('voltha instance %s, with tags %s' % (serviceId, serviceTags))
72 for tag in serviceTags:
73 if tag in containers:
74 netcfg = self.create_network(serviceId, tag)
75 self.create_container(serviceId, tag, netcfg)
76
77
78 def create_network(self, id, tag):
79 return create_container_network('podder_%s_%s' % (tag, id),
80 containers[tag]['links'])
81
82 def create_container(self, id, tag, netcfg):
83 args = {}
84 args['image'] = containers['image']
85 args['networking_config'] = netcfg
86 args['command'] = containers['command']
87 args['ports'] = containers['ports']
88 args['environment'] = containers['environment']
89 args['volumes'] = containers['volumes']
90 start_container(args)