blob: 80d8f7596cae22a59ab110fad787c48cb4b5e0f2 [file] [log] [blame]
A R Karthick41adfce2016-06-10 09:51:25 -07001#
Chetan Gaonkercfcce782016-05-10 10:10:42 -07002# Copyright 2016-present Ciena Corporation
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
A R Karthick41adfce2016-06-10 09:51:25 -07007#
Chetan Gaonkercfcce782016-05-10 10:10:42 -07008# http://www.apache.org/licenses/LICENSE-2.0
A R Karthick41adfce2016-06-10 09:51:25 -07009#
Chetan Gaonkercfcce782016-05-10 10:10:42 -070010# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
Chetan Gaonker3533faa2016-04-25 17:50:14 -070016import os,time
17import io
18import json
A R Karthickd44cea12016-07-20 12:16:41 -070019import yaml
A.R Karthickc4e474d2016-12-12 15:24:57 -080020import errno
A R Karthickaa54a1c2016-12-15 11:42:08 -080021import copy
Chetan Gaonker3533faa2016-04-25 17:50:14 -070022from pyroute2 import IPRoute
A.R Karthickc4e474d2016-12-12 15:24:57 -080023from pyroute2.netlink import NetlinkError
Chetan Gaonker3533faa2016-04-25 17:50:14 -070024from itertools import chain
25from nsenter import Namespace
26from docker import Client
A R Karthickec2db322016-11-17 15:06:01 -080027from shutil import rmtree
A.R Karthick95d044e2016-06-10 18:44:36 -070028from OnosCtrl import OnosCtrl
A R Karthick19aaf5c2016-11-09 17:47:57 -080029from OnosLog import OnosLog
A.R Karthickc4e474d2016-12-12 15:24:57 -080030from threadPool import ThreadPool
A R Karthickaa54a1c2016-12-15 11:42:08 -080031from threading import Lock
Chetan Gaonker3533faa2016-04-25 17:50:14 -070032
33class docker_netns(object):
34
35 dckr = Client()
36 def __init__(self, name):
37 pid = int(self.dckr.inspect_container(name)['State']['Pid'])
38 if pid == 0:
39 raise Exception('no container named {0}'.format(name))
40 self.pid = pid
41
42 def __enter__(self):
43 pid = self.pid
44 if not os.path.exists('/var/run/netns'):
45 os.mkdir('/var/run/netns')
46 os.symlink('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(pid))
47 return str(pid)
48
49 def __exit__(self, type, value, traceback):
50 pid = self.pid
51 os.unlink('/var/run/netns/{0}'.format(pid))
52
53flatten = lambda l: chain.from_iterable(l)
54
55class Container(object):
56 dckr = Client()
A R Karthick07608ef2016-08-23 16:51:19 -070057 IMAGE_PREFIX = '' ##for saving global prefix for all test classes
A R Karthickaa54a1c2016-12-15 11:42:08 -080058 CONFIG_LOCK = Lock()
A R Karthick07608ef2016-08-23 16:51:19 -070059
60 def __init__(self, name, image, prefix='', tag = 'candidate', command = 'bash', quagga_config = None):
Chetan Gaonker3533faa2016-04-25 17:50:14 -070061 self.name = name
A R Karthick07608ef2016-08-23 16:51:19 -070062 self.prefix = prefix
63 if prefix:
64 self.prefix += '/'
65 image = '{}{}'.format(self.prefix, image)
Chetan Gaonker3533faa2016-04-25 17:50:14 -070066 self.image = image
67 self.tag = tag
A R Karthickd44cea12016-07-20 12:16:41 -070068 if tag:
69 self.image_name = image + ':' + tag
70 else:
71 self.image_name = image
Chetan Gaonker3533faa2016-04-25 17:50:14 -070072 self.id = None
73 self.command = command
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -070074 self.quagga_config = quagga_config
Chetan Gaonker3533faa2016-04-25 17:50:14 -070075
76 @classmethod
77 def build_image(cls, dockerfile, tag, force=True, nocache=False):
78 f = io.BytesIO(dockerfile.encode('utf-8'))
79 if force or not cls.image_exists(tag):
80 print('Build {0}...'.format(tag))
81 for line in cls.dckr.build(fileobj=f, rm=True, tag=tag, decode=True, nocache=nocache):
82 if 'stream' in line:
83 print(line['stream'].strip())
84
85 @classmethod
86 def image_exists(cls, name):
87 return name in [ctn['RepoTags'][0] for ctn in cls.dckr.images()]
88
89 @classmethod
90 def create_host_config(cls, port_list = None, host_guest_map = None, privileged = False):
91 port_bindings = None
92 binds = None
93 if port_list:
94 port_bindings = {}
95 for p in port_list:
96 port_bindings[str(p)] = str(p)
97
98 if host_guest_map:
99 binds = []
100 for h, g in host_guest_map:
101 binds.append('{0}:{1}'.format(h, g))
102
103 return cls.dckr.create_host_config(binds = binds, port_bindings = port_bindings, privileged = privileged)
104
105 @classmethod
106 def cleanup(cls, image):
A R Karthick09b1f4e2016-05-12 14:31:50 -0700107 cnt_list = filter(lambda c: c['Image'] == image, cls.dckr.containers(all=True))
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700108 for cnt in cnt_list:
109 print('Cleaning container %s' %cnt['Id'])
A.R Karthick95d044e2016-06-10 18:44:36 -0700110 if cnt.has_key('State') and cnt['State'] == 'running':
A R Karthick09b1f4e2016-05-12 14:31:50 -0700111 cls.dckr.kill(cnt['Id'])
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700112 cls.dckr.remove_container(cnt['Id'], force=True)
113
114 @classmethod
115 def remove_container(cls, name, force=True):
116 try:
117 cls.dckr.remove_container(name, force = force)
118 except: pass
119
120 def exists(self):
121 return '/{0}'.format(self.name) in list(flatten(n['Names'] for n in self.dckr.containers()))
122
123 def img_exists(self):
A R Karthick6d98a592016-08-24 15:16:46 -0700124 return self.image_name in [ctn['RepoTags'][0] if ctn['RepoTags'] else '' for ctn in self.dckr.images()]
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700125
126 def ip(self):
A R Karthick2b93d6a2016-09-06 15:19:09 -0700127 cnt_list = filter(lambda c: c['Names'][0] == '/{}'.format(self.name), self.dckr.containers())
128 #if not cnt_list:
129 # cnt_list = filter(lambda c: c['Image'] == self.image_name, self.dckr.containers())
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700130 cnt_settings = cnt_list.pop()
131 return cnt_settings['NetworkSettings']['Networks']['bridge']['IPAddress']
132
A R Karthick2b93d6a2016-09-06 15:19:09 -0700133 @classmethod
134 def ips(cls, image_name):
135 cnt_list = filter(lambda c: c['Image'] == image_name, cls.dckr.containers())
136 ips = [ cnt['NetworkSettings']['Networks']['bridge']['IPAddress'] for cnt in cnt_list ]
137 return ips
138
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700139 def kill(self, remove = True):
140 self.dckr.kill(self.name)
141 self.dckr.remove_container(self.name, force=True)
142
A R Karthick41adfce2016-06-10 09:51:25 -0700143 def start(self, rm = True, ports = None, volumes = None, host_config = None,
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700144 environment = None, tty = False, stdin_open = True):
145
146 if rm and self.exists():
147 print('Removing container:', self.name)
148 self.dckr.remove_container(self.name, force=True)
149
A R Karthick41adfce2016-06-10 09:51:25 -0700150 ctn = self.dckr.create_container(image=self.image_name, ports = ports, command=self.command,
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700151 detach=True, name=self.name,
A R Karthick41adfce2016-06-10 09:51:25 -0700152 environment = environment,
153 volumes = volumes,
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700154 host_config = host_config, stdin_open=stdin_open, tty = tty)
155 self.dckr.start(container=self.name)
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700156 if self.quagga_config:
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700157 self.connect_to_br()
158 self.id = ctn['Id']
159 return ctn
160
Thangavelu K Sef6f0a52016-12-14 19:57:05 +0000161 @classmethod
162 def pause_container(cls, image, delay):
163 cnt_list = filter(lambda c: c['Image'] == image, cls.dckr.containers(all=True))
164 for cnt in cnt_list:
165 print('Pause the container %s' %cnt['Id'])
166 if cnt.has_key('State') and cnt['State'] == 'running':
167 cls.dckr.pause(cnt['Id'])
168 if delay != 0:
169 time.sleep(delay)
170 for cnt in cnt_list:
171 print('Unpause the container %s' %cnt['Id'])
172 cls.dckr.unpause(cnt['Id'])
173 else:
174 print('Infinity time pause the container %s' %cnt['Id'])
175 return 'success'
176
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700177 def connect_to_br(self):
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700178 index = 0
A R Karthickaa54a1c2016-12-15 11:42:08 -0800179 self.CONFIG_LOCK.acquire()
180 try:
181 with docker_netns(self.name) as pid:
182 for quagga_config in self.quagga_config:
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700183 ip = IPRoute()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800184 br = ip.link_lookup(ifname=quagga_config['bridge'])
185 if len(br) == 0:
186 try:
187 ip.link_create(ifname=quagga_config['bridge'], kind='bridge')
188 except NetlinkError as e:
189 err, _ = e.args
190 if err == errno.EEXIST:
191 pass
192 else:
193 raise NetlinkError(*e.args)
194 br = ip.link_lookup(ifname=quagga_config['bridge'])
195 br = br[0]
196 ip.link('set', index=br, state='up')
197 ifname = '{0}-{1}'.format(self.name, index)
198 ifs = ip.link_lookup(ifname=ifname)
199 if len(ifs) > 0:
200 ip.link_remove(ifs[0])
201 peer_ifname = '{0}-{1}'.format(pid, index)
202 ip.link_create(ifname=ifname, kind='veth', peer=peer_ifname)
203 host = ip.link_lookup(ifname=ifname)[0]
204 ip.link('set', index=host, master=br)
205 ip.link('set', index=host, state='up')
206 guest = ip.link_lookup(ifname=peer_ifname)[0]
207 ip.link('set', index=guest, net_ns_fd=pid)
208 with Namespace(pid, 'net'):
209 ip = IPRoute()
210 ip.link('set', index=guest, ifname='eth{}'.format(index+1))
211 ip.addr('add', index=guest, address=quagga_config['ip'], mask=quagga_config['mask'])
212 ip.link('set', index=guest, state='up')
213 index += 1
214 finally:
215 self.CONFIG_LOCK.release()
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700216
Thangavelu K Sef6f0a52016-12-14 19:57:05 +0000217 def execute(self, cmd, tty = True, stream = False, shell = False, detach = True):
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700218 res = 0
219 if type(cmd) == str:
220 cmds = (cmd,)
221 else:
222 cmds = cmd
223 if shell:
224 for c in cmds:
225 res += os.system('docker exec {0} {1}'.format(self.name, c))
226 return res
227 for c in cmds:
228 i = self.dckr.exec_create(container=self.name, cmd=c, tty = tty, privileged = True)
Thangavelu K Sef6f0a52016-12-14 19:57:05 +0000229 self.dckr.exec_start(i['Id'], stream = stream, detach=detach)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700230 result = self.dckr.exec_inspect(i['Id'])
231 res += 0 if result['ExitCode'] == None else result['ExitCode']
232 return res
233
ChetanGaonker6138fcd2016-08-18 17:56:39 -0700234 def restart(self, timeout =10):
235 return self.dckr.restart(self.name, timeout)
236
A R Karthick1f908202016-11-16 17:32:20 -0800237def get_mem(instances = 1):
238 if instances <= 0:
239 instances = 1
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700240 with open('/proc/meminfo', 'r') as fd:
241 meminfo = fd.readlines()
242 mem = 0
243 for m in meminfo:
244 if m.startswith('MemTotal:') or m.startswith('SwapTotal:'):
245 mem += int(m.split(':')[1].strip().split()[0])
246
A R Karthick1f908202016-11-16 17:32:20 -0800247 mem = max(mem/1024/1024/2/instances, 1)
Chetan Gaonker6d0a7b02016-05-03 16:57:28 -0700248 mem = min(mem, 16)
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700249 return str(mem) + 'G'
250
A R Karthickd44cea12016-07-20 12:16:41 -0700251class OnosCord(Container):
252 """Use this when running the cord tester agent on the onos compute node"""
253 onos_cord_dir = os.path.join(os.getenv('HOME'), 'cord-tester-cord')
254 onos_config_dir_guest = '/root/onos/config'
255 onos_config_dir = os.path.join(onos_cord_dir, 'config')
256 docker_yaml = os.path.join(onos_cord_dir, 'docker-compose.yml')
257
A R Karthickbd9b8a32016-07-21 09:56:45 -0700258 def __init__(self, onos_ip, conf, boot_delay = 60):
259 self.onos_ip = onos_ip
A R Karthickd44cea12016-07-20 12:16:41 -0700260 self.cord_conf_dir = conf
A R Karthickbd9b8a32016-07-21 09:56:45 -0700261 self.boot_delay = boot_delay
A R Karthickd44cea12016-07-20 12:16:41 -0700262 if os.access(self.cord_conf_dir, os.F_OK) and not os.access(self.onos_cord_dir, os.F_OK):
263 os.mkdir(self.onos_cord_dir)
264 os.mkdir(self.onos_config_dir)
265 ##copy the config file from cord-tester-config
266 cmd = 'cp {}/* {}'.format(self.cord_conf_dir, self.onos_cord_dir)
267 os.system(cmd)
268
269 ##update the docker yaml with the config volume
270 with open(self.docker_yaml, 'r') as f:
271 yaml_config = yaml.load(f)
272 image = yaml_config['services'].keys()[0]
273 name = 'cordtestercord_{}_1'.format(image)
274 volumes = yaml_config['services'][image]['volumes']
275 config_volumes = filter(lambda e: e.find(self.onos_config_dir_guest) >= 0, volumes)
276 if not config_volumes:
277 config_volume = '{}:{}'.format(self.onos_config_dir, self.onos_config_dir_guest)
278 volumes.append(config_volume)
279 docker_yaml_changed = '{}-changed'.format(self.docker_yaml)
280 with open(docker_yaml_changed, 'w') as wf:
281 yaml.dump(yaml_config, wf)
282
283 os.rename(docker_yaml_changed, self.docker_yaml)
284 self.volumes = volumes
285
286 super(OnosCord, self).__init__(name, image, tag = '')
287 cord_conf_dir_basename = os.path.basename(self.cord_conf_dir.replace('-', ''))
288 self.xos_onos_name = '{}_{}_1'.format(cord_conf_dir_basename, image)
289 ##Create an container instance of xos onos
290 self.xos_onos = Container(self.xos_onos_name, image, tag = '')
291
292 def start(self, restart = False, network_cfg = None):
293 if restart is True:
294 if self.exists():
295 ##Kill the existing instance
296 print('Killing container %s' %self.name)
297 self.kill()
298 if self.xos_onos.exists():
299 print('Killing container %s' %self.xos_onos.name)
300 self.xos_onos.kill()
301
302 if network_cfg is not None:
303 json_data = json.dumps(network_cfg, indent=4)
304 with open('{}/network-cfg.json'.format(self.onos_config_dir), 'w') as f:
305 f.write(json_data)
306
307 #start the container using docker-compose
308 cmd = 'cd {} && docker-compose up -d'.format(self.onos_cord_dir)
309 os.system(cmd)
A R Karthickbd9b8a32016-07-21 09:56:45 -0700310 #Delay to make sure ONOS fully boots
311 time.sleep(self.boot_delay)
312 Onos.install_cord_apps(onos_ip = self.onos_ip)
A R Karthickd44cea12016-07-20 12:16:41 -0700313
314 def build_image(self):
315 build_cmd = 'cd {} && docker-compose build'.format(self.onos_cord_dir)
316 os.system(build_cmd)
317
A.R Karthick1700e0e2016-10-06 18:16:57 -0700318class OnosCordStopWrapper(Container):
319 onos_cord_dir = os.path.join(os.getenv('HOME'), 'cord-tester-cord')
320 docker_yaml = os.path.join(onos_cord_dir, 'docker-compose.yml')
321
322 def __init__(self):
323 if os.access(self.docker_yaml, os.F_OK):
324 with open(self.docker_yaml, 'r') as f:
325 yaml_config = yaml.load(f)
326 image = yaml_config['services'].keys()[0]
327 name = 'cordtestercord_{}_1'.format(image)
328 super(OnosCordStopWrapper, self).__init__(name, image, tag = '')
329 if self.exists():
330 print('Killing container %s' %self.name)
331 self.kill()
332
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700333class Onos(Container):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800334 QUAGGA_CONFIG = [ { 'bridge' : 'quagga-br', 'ip': '10.10.0.4', 'mask' : 16 }, ]
A R Karthicka2492c12016-12-16 10:31:51 -0800335 MAX_INSTANCES = 3
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700336 SYSTEM_MEMORY = (get_mem(),) * 2
A R Karthicka2492c12016-12-16 10:31:51 -0800337 INSTANCE_MEMORY = (get_mem(instances=MAX_INSTANCES),) * 2
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700338 JAVA_OPTS = '-Xms{} -Xmx{} -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode'.format(*SYSTEM_MEMORY)#-XX:+PrintGCDetails -XX:+PrintGCTimeStamps'
A R Karthick1f908202016-11-16 17:32:20 -0800339 JAVA_OPTS_CLUSTER = '-Xms{} -Xmx{} -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode'.format(*INSTANCE_MEMORY)
A.R Karthick95d044e2016-06-10 18:44:36 -0700340 env = { 'ONOS_APPS' : 'drivers,openflow,proxyarp,vrouter', 'JAVA_OPTS' : JAVA_OPTS }
A.R Karthickdfeadb02016-11-30 17:55:51 -0800341 onos_cord_apps = ( ('cord-config', '1.1-SNAPSHOT'),
342 ('aaa', '1.1-SNAPSHOT'),
343 ('igmp', '1.1-SNAPSHOT'),
344 #('vtn', '1.1-SNAPSHOT'),
A.R Karthick95d044e2016-06-10 18:44:36 -0700345 )
A.R Karthickc4e474d2016-12-12 15:24:57 -0800346 ports = [] #[ 8181, 8101, 9876, 6653, 6633, 2000, 2620 ]
A R Karthickf2f4ca62016-08-17 10:34:08 -0700347 setup_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup')
348 host_config_dir = os.path.join(setup_dir, 'onos-config')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700349 guest_config_dir = '/root/onos/config'
A R Karthickec2db322016-11-17 15:06:01 -0800350 guest_data_dir = '/root/onos/apache-karaf-3.0.5/data'
A R Karthickf2f4ca62016-08-17 10:34:08 -0700351 onos_gen_partitions = os.path.join(setup_dir, 'onos-gen-partitions')
A R Karthick2b93d6a2016-09-06 15:19:09 -0700352 onos_form_cluster = os.path.join(setup_dir, 'onos-form-cluster')
A.R Karthick95d044e2016-06-10 18:44:36 -0700353 cord_apps_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'apps')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700354 host_guest_map = ( (host_config_dir, guest_config_dir), )
A R Karthick2b93d6a2016-09-06 15:19:09 -0700355 cluster_cfg = os.path.join(host_config_dir, 'cluster.json')
356 cluster_mode = False
357 cluster_instances = []
Chetan Gaonker503032a2016-05-12 12:06:29 -0700358 NAME = 'cord-onos'
A R Karthickf2f4ca62016-08-17 10:34:08 -0700359 ##the ip of ONOS in default cluster.json in setup/onos-config
360 CLUSTER_CFG_IP = '172.17.0.2'
A R Karthick07608ef2016-08-23 16:51:19 -0700361 IMAGE = 'onosproject/onos'
362 TAG = 'latest'
363 PREFIX = ''
A R Karthickf2f4ca62016-08-17 10:34:08 -0700364
365 @classmethod
A R Karthick2b93d6a2016-09-06 15:19:09 -0700366 def generate_cluster_cfg(cls, ip):
367 if type(ip) in [ list, tuple ]:
368 ips = ' '.join(ip)
369 else:
370 ips = ip
A R Karthickf2f4ca62016-08-17 10:34:08 -0700371 try:
A R Karthick2b93d6a2016-09-06 15:19:09 -0700372 cmd = '{} {} {}'.format(cls.onos_gen_partitions, cls.cluster_cfg, ips)
373 os.system(cmd)
374 except: pass
375
376 @classmethod
377 def form_cluster(cls, ips):
378 nodes = ' '.join(ips)
379 try:
380 cmd = '{} {}'.format(cls.onos_form_cluster, nodes)
A R Karthickf2f4ca62016-08-17 10:34:08 -0700381 os.system(cmd)
382 except: pass
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700383
A R Karthick9d48c652016-09-15 09:16:36 -0700384 @classmethod
385 def cleanup_runtime(cls):
386 '''Cleanup ONOS runtime generated files'''
387 files = ( Onos.cluster_cfg, os.path.join(Onos.host_config_dir, 'network-cfg.json') )
388 for f in files:
389 if os.access(f, os.F_OK):
390 try:
391 os.unlink(f)
392 except: pass
393
A R Karthickec2db322016-11-17 15:06:01 -0800394 @classmethod
395 def get_data_map(cls, host_volume, guest_volume_dir):
396 host_volume_dir = os.path.join(cls.setup_dir, os.path.basename(host_volume))
397 if not os.path.exists(host_volume_dir):
398 os.mkdir(host_volume_dir)
399 return ( (host_volume_dir, guest_volume_dir), )
400
401 @classmethod
402 def remove_data_map(cls, host_volume, guest_volume_dir):
403 host_volume_dir = os.path.join(cls.setup_dir, os.path.basename(host_volume))
404 if os.path.exists(host_volume_dir):
405 rmtree(host_volume_dir)
406
407 def remove_data_volume(self):
408 if self.data_map is not None:
409 self.remove_data_map(*self.data_map)
410
A.R Karthick1700e0e2016-10-06 18:16:57 -0700411 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX, tag = TAG,
A R Karthickec2db322016-11-17 15:06:01 -0800412 boot_delay = 20, restart = False, network_cfg = None,
A R Karthicka2492c12016-12-16 10:31:51 -0800413 cluster = False, data_volume = None, async = False, quagga_config = None):
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700414 if restart is True:
415 ##Find the right image to restart
416 running_image = filter(lambda c: c['Names'][0] == '/{}'.format(name), self.dckr.containers())
417 if running_image:
418 image_name = running_image[0]['Image']
419 try:
420 image = image_name.split(':')[0]
421 tag = image_name.split(':')[1]
422 except: pass
423
A R Karthickaa54a1c2016-12-15 11:42:08 -0800424 if quagga_config is None:
425 quagga_config = Onos.QUAGGA_CONFIG
426 super(Onos, self).__init__(name, image, prefix = prefix, tag = tag, quagga_config = quagga_config)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700427 self.boot_delay = boot_delay
A R Karthickec2db322016-11-17 15:06:01 -0800428 self.data_map = None
A R Karthick2b93d6a2016-09-06 15:19:09 -0700429 if cluster is True:
430 self.ports = []
A R Karthicka2492c12016-12-16 10:31:51 -0800431 if Onos.MAX_INSTANCES <= 3:
A R Karthick3b811152016-12-15 10:24:24 -0800432 java_opts = self.JAVA_OPTS_CLUSTER
433 else:
A R Karthicka2492c12016-12-16 10:31:51 -0800434 instance_memory = (get_mem(instances=Onos.MAX_INSTANCES),) * 2
A R Karthick3b811152016-12-15 10:24:24 -0800435 java_opts = '-Xms{} -Xmx{} -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode'.format(*instance_memory)
436
437 self.env['JAVA_OPTS'] = java_opts
A R Karthickec2db322016-11-17 15:06:01 -0800438 if data_volume is not None:
439 self.data_map = self.get_data_map(data_volume, self.guest_data_dir)
440 self.host_guest_map = self.host_guest_map + self.data_map
A R Karthick2b93d6a2016-09-06 15:19:09 -0700441 if os.access(self.cluster_cfg, os.F_OK):
442 try:
443 os.unlink(self.cluster_cfg)
444 except: pass
445
446 self.host_config = self.create_host_config(port_list = self.ports,
447 host_guest_map = self.host_guest_map)
448 self.volumes = []
449 for _,g in self.host_guest_map:
450 self.volumes.append(g)
451
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700452 if restart is True and self.exists():
453 self.kill()
A R Karthick2b93d6a2016-09-06 15:19:09 -0700454
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700455 if not self.exists():
456 self.remove_container(name, force=True)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700457 host_config = self.create_host_config(port_list = self.ports,
458 host_guest_map = self.host_guest_map)
459 volumes = []
460 for _,g in self.host_guest_map:
461 volumes.append(g)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700462 if network_cfg is not None:
A R Karthick81acbff2016-06-17 14:45:16 -0700463 json_data = json.dumps(network_cfg, indent=4)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700464 with open('{}/network-cfg.json'.format(self.host_config_dir), 'w') as f:
465 f.write(json_data)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800466 if cluster is False or async is False:
467 print('Starting ONOS container %s' %self.name)
468 self.start(ports = self.ports, environment = self.env,
469 host_config = self.host_config, volumes = self.volumes, tty = True)
470 if not restart:
471 ##wait a bit before fetching IP to regenerate cluster cfg
472 time.sleep(5)
473 ip = self.ip()
474 ##Just a quick hack/check to ensure we don't regenerate in the common case.
475 ##As ONOS is usually the first test container that is started
476 if cluster is False:
477 if ip != self.CLUSTER_CFG_IP or not os.access(self.cluster_cfg, os.F_OK):
478 print('Regenerating ONOS cluster cfg for ip %s' %ip)
479 self.generate_cluster_cfg(ip)
480 self.kill()
481 self.remove_container(self.name, force=True)
482 print('Restarting ONOS container %s' %self.name)
483 self.start(ports = self.ports, environment = self.env,
484 host_config = self.host_config, volumes = self.volumes, tty = True)
485 print('Waiting for ONOS to boot')
486 time.sleep(boot_delay)
487 self.wait_for_onos_start(self.ip())
488 self.running = True
489 else:
490 self.running = False
491 else:
492 self.running = True
493 if self.running:
494 self.ipaddr = self.ip()
495 if cluster is False:
496 self.install_cord_apps(self.ipaddr)
A R Karthick19aaf5c2016-11-09 17:47:57 -0800497
A.R Karthickc4e474d2016-12-12 15:24:57 -0800498 @classmethod
499 def get_quagga_config(cls, instance = 0):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800500 quagga_config = copy.deepcopy(cls.QUAGGA_CONFIG)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800501 if instance == 0:
502 return quagga_config
503 ip = quagga_config[0]['ip']
504 octets = ip.split('.')
A R Karthickaa54a1c2016-12-15 11:42:08 -0800505 octets[3] = str((int(octets[3]) + instance) & 255)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800506 ip = '.'.join(octets)
507 quagga_config[0]['ip'] = ip
508 return quagga_config
509
510 @classmethod
511 def start_cluster_async(cls, onos_instances):
512 instances = filter(lambda o: o.running == False, onos_instances)
513 if not instances:
514 return
515 tpool = ThreadPool(len(instances), queue_size = 1, wait_timeout = 1)
516 for onos in instances:
517 tpool.addTask(onos.start_async)
518 tpool.cleanUpThreads()
519
520 def start_async(self):
521 print('Starting ONOS container %s' %self.name)
522 self.start(ports = self.ports, environment = self.env,
523 host_config = self.host_config, volumes = self.volumes, tty = True)
524 time.sleep(3)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700525 self.ipaddr = self.ip()
A.R Karthickc4e474d2016-12-12 15:24:57 -0800526 print('Waiting for ONOS container %s to start' %self.name)
527 self.wait_for_onos_start(self.ipaddr)
528 self.running = True
529 print('ONOS container %s started' %self.name)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700530
A R Karthick2b93d6a2016-09-06 15:19:09 -0700531 @classmethod
A R Karthick19aaf5c2016-11-09 17:47:57 -0800532 def wait_for_onos_start(cls, ip, tries = 30):
533 onos_log = OnosLog(host = ip)
534 num_tries = 0
535 started = None
536 while not started and num_tries < tries:
537 time.sleep(3)
538 started = onos_log.search_log_pattern('ApplicationManager .* Started')
539 num_tries += 1
540
A R Karthick19aaf5c2016-11-09 17:47:57 -0800541 if not started:
542 print('ONOS did not start')
543 else:
544 print('ONOS started')
545 return started
546
547 @classmethod
A R Karthick2b93d6a2016-09-06 15:19:09 -0700548 def setup_cluster_deprecated(cls, onos_instances, image_name = None):
549 if not onos_instances or len(onos_instances) < 2:
550 return
551 ips = []
552 if image_name is not None:
553 ips = Container.ips(image_name)
554 else:
555 for onos in onos_instances:
556 ips.append(onos.ipaddr)
557 Onos.cluster_instances = onos_instances
558 Onos.cluster_mode = True
559 ##regenerate the cluster json with the 3 instance ips before restarting them back
560 print('Generating cluster cfg for ONOS instances with ips %s' %ips)
561 Onos.generate_cluster_cfg(ips)
562 for onos in onos_instances:
563 onos.kill()
564 onos.remove_container(onos.name, force=True)
565 print('Restarting ONOS container %s for forming cluster' %onos.name)
566 onos.start(ports = onos.ports, environment = onos.env,
567 host_config = onos.host_config, volumes = onos.volumes, tty = True)
568 print('Waiting %d seconds for ONOS %s to boot' %(onos.boot_delay, onos.name))
569 time.sleep(onos.boot_delay)
570 onos.ipaddr = onos.ip()
571 onos.install_cord_apps(onos.ipaddr)
572
573 @classmethod
574 def setup_cluster(cls, onos_instances, image_name = None):
575 if not onos_instances or len(onos_instances) < 2:
576 return
577 ips = []
578 if image_name is not None:
579 ips = Container.ips(image_name)
580 else:
581 for onos in onos_instances:
582 ips.append(onos.ipaddr)
583 Onos.cluster_instances = onos_instances
584 Onos.cluster_mode = True
585 ##regenerate the cluster json with the 3 instance ips before restarting them back
586 print('Forming cluster for ONOS instances with ips %s' %ips)
587 Onos.form_cluster(ips)
588 ##wait for the cluster to be formed
589 print('Waiting for the cluster to be formed')
590 time.sleep(60)
591 for onos in onos_instances:
592 onos.install_cord_apps(onos.ipaddr)
593
594 @classmethod
A R Karthicke2c24bd2016-10-07 14:51:38 -0700595 def add_cluster(cls, count = 1, network_cfg = None):
596 if not cls.cluster_instances or Onos.cluster_mode is False:
597 return
598 for i in range(count):
599 name = '{}-{}'.format(Onos.NAME, len(cls.cluster_instances)+1)
600 onos = cls(name = name, image = Onos.IMAGE, tag = Onos.TAG, prefix = Container.IMAGE_PREFIX,
601 cluster = True, network_cfg = network_cfg)
602 cls.cluster_instances.append(onos)
603
604 cls.setup_cluster(cls.cluster_instances)
605
606 @classmethod
A.R Karthick2560f042016-11-30 14:38:52 -0800607 def restart_cluster(cls, network_cfg = None, timeout = 10, setup = False):
A R Karthick2b93d6a2016-09-06 15:19:09 -0700608 if cls.cluster_mode is False:
609 return
610 if not cls.cluster_instances:
611 return
612
613 if network_cfg is not None:
614 json_data = json.dumps(network_cfg, indent=4)
615 with open('{}/network-cfg.json'.format(cls.host_config_dir), 'w') as f:
616 f.write(json_data)
617
A.R Karthick2560f042016-11-30 14:38:52 -0800618 cls.cleanup_cluster()
619 if timeout > 0:
620 time.sleep(timeout)
621
A R Karthickaa54a1c2016-12-15 11:42:08 -0800622 #start the instances asynchronously
623 cls.start_cluster_async(cls.cluster_instances)
624 time.sleep(5)
A.R Karthick2560f042016-11-30 14:38:52 -0800625 ##form the cluster as appropriate
626 if setup is True:
627 cls.setup_cluster(cls.cluster_instances)
A R Karthickaa54a1c2016-12-15 11:42:08 -0800628 else:
629 for onos in cls.cluster_instances:
630 onos.install_cord_apps(onos.ipaddr)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700631
632 @classmethod
633 def cluster_ips(cls):
634 if cls.cluster_mode is False:
635 return []
636 if not cls.cluster_instances:
637 return []
638 ips = [ onos.ipaddr for onos in cls.cluster_instances ]
639 return ips
640
641 @classmethod
642 def cleanup_cluster(cls):
643 if cls.cluster_mode is False:
644 return
645 if not cls.cluster_instances:
646 return
647 for onos in cls.cluster_instances:
648 if onos.exists():
649 onos.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800650 onos.running = False
A R Karthick2b93d6a2016-09-06 15:19:09 -0700651 onos.remove_container(onos.name, force=True)
A R Karthickd44cea12016-07-20 12:16:41 -0700652
A.R Karthick95d044e2016-06-10 18:44:36 -0700653 @classmethod
A R Karthickde6b9dc2016-11-29 17:46:16 -0800654 def restart_node(cls, node = None, network_cfg = None, timeout = 10):
A R Karthick889d9652016-10-03 14:13:45 -0700655 if node is None:
656 cls(restart = True, network_cfg = network_cfg, image = cls.IMAGE, tag = cls.TAG)
657 else:
658 #Restarts a node in the cluster
659 valid_node = filter(lambda onos: node in [ onos.ipaddr, onos.name ], cls.cluster_instances)
660 if valid_node:
661 onos = valid_node.pop()
662 if onos.exists():
663 onos.kill()
664 onos.remove_container(onos.name, force=True)
A R Karthickde6b9dc2016-11-29 17:46:16 -0800665 if timeout > 0:
666 time.sleep(timeout)
A R Karthick889d9652016-10-03 14:13:45 -0700667 print('Restarting ONOS container %s' %onos.name)
668 onos.start(ports = onos.ports, environment = onos.env,
669 host_config = onos.host_config, volumes = onos.volumes, tty = True)
A R Karthick889d9652016-10-03 14:13:45 -0700670 onos.ipaddr = onos.ip()
A.R Karthick2560f042016-11-30 14:38:52 -0800671 onos.wait_for_onos_start(onos.ipaddr)
672 onos.install_cord_apps(onos.ipaddr)
A R Karthick889d9652016-10-03 14:13:45 -0700673
674 @classmethod
A R Karthickeaf1c4e2016-07-19 12:22:35 -0700675 def install_cord_apps(cls, onos_ip = None):
A.R Karthick95d044e2016-06-10 18:44:36 -0700676 for app, version in cls.onos_cord_apps:
677 app_file = '{}/{}-{}.oar'.format(cls.cord_apps_dir, app, version)
A R Karthickeaf1c4e2016-07-19 12:22:35 -0700678 ok, code = OnosCtrl.install_app(app_file, onos_ip = onos_ip)
A.R Karthick95d044e2016-06-10 18:44:36 -0700679 ##app already installed (conflicts)
680 if code in [ 409 ]:
681 ok = True
682 print('ONOS app %s, version %s %s' %(app, version, 'installed' if ok else 'failed to install'))
683 time.sleep(2)
684
A.R Karthick1700e0e2016-10-06 18:16:57 -0700685class OnosStopWrapper(Container):
686 def __init__(self, name):
687 super(OnosStopWrapper, self).__init__(name, Onos.IMAGE, tag = Onos.TAG, prefix = Container.IMAGE_PREFIX)
688 if self.exists():
689 self.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800690 self.running = False
A.R Karthick1700e0e2016-10-06 18:16:57 -0700691 else:
692 if Onos.cluster_mode is True:
693 valid_node = filter(lambda onos: name in [ onos.ipaddr, onos.name ], Onos.cluster_instances)
694 if valid_node:
695 onos = valid_node.pop()
696 if onos.exists():
697 onos.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800698 onos.running = False
A.R Karthick1700e0e2016-10-06 18:16:57 -0700699
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700700class Radius(Container):
701 ports = [ 1812, 1813 ]
A R Karthick41adfce2016-06-10 09:51:25 -0700702 env = {'TIMEZONE':'America/Los_Angeles',
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700703 'DEBUG': 'true', 'cert_password':'whatever', 'primary_shared_secret':'radius_password'
704 }
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700705 host_db_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/db')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700706 guest_db_dir = os.path.join(os.path.sep, 'opt', 'db')
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700707 host_config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/freeradius')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700708 guest_config_dir = os.path.join(os.path.sep, 'etc', 'freeradius')
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700709 start_command = os.path.join(guest_config_dir, 'start-radius.py')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700710 host_guest_map = ( (host_db_dir, guest_db_dir),
711 (host_config_dir, guest_config_dir)
712 )
Chetan Gaonker503032a2016-05-12 12:06:29 -0700713 IMAGE = 'cord-test/radius'
714 NAME = 'cord-radius'
715
A R Karthick07608ef2016-08-23 16:51:19 -0700716 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = 'candidate',
Chetan Gaonker503032a2016-05-12 12:06:29 -0700717 boot_delay = 10, restart = False, update = False):
A R Karthick07608ef2016-08-23 16:51:19 -0700718 super(Radius, self).__init__(name, image, prefix = prefix, tag = tag, command = self.start_command)
Chetan Gaonker503032a2016-05-12 12:06:29 -0700719 if update is True or not self.img_exists():
A R Karthick07608ef2016-08-23 16:51:19 -0700720 self.build_image(self.image_name)
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700721 if restart is True and self.exists():
722 self.kill()
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700723 if not self.exists():
724 self.remove_container(name, force=True)
725 host_config = self.create_host_config(port_list = self.ports,
726 host_guest_map = self.host_guest_map)
727 volumes = []
728 for _,g in self.host_guest_map:
729 volumes.append(g)
A R Karthick41adfce2016-06-10 09:51:25 -0700730 self.start(ports = self.ports, environment = self.env,
731 volumes = volumes,
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700732 host_config = host_config, tty = True)
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700733 time.sleep(boot_delay)
734
735 @classmethod
736 def build_image(cls, image):
737 print('Building Radius image %s' %image)
738 dockerfile = '''
739FROM hbouvier/docker-radius
740MAINTAINER chetan@ciena.com
741LABEL RUN docker pull hbouvier/docker-radius
742LABEL RUN docker run -it --name cord-radius hbouvier/docker-radius
A R Karthickc762df42016-05-25 10:09:21 -0700743RUN apt-get update && \
744 apt-get -y install python python-pexpect strace
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700745WORKDIR /root
746CMD ["/etc/freeradius/start-radius.py"]
747'''
748 super(Radius, cls).build_image(dockerfile, image)
749 print('Done building image %s' %image)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700750
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700751class Quagga(Container):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800752 QUAGGA_CONFIG = ( { 'bridge' : 'quagga-br', 'ip': '10.10.0.3', 'mask' : 16 },
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700753 { 'bridge' : 'quagga-br', 'ip': '192.168.10.3', 'mask': 16 },
754 )
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700755 ports = [ 179, 2601, 2602, 2603, 2604, 2605, 2606 ]
756 host_quagga_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/quagga-config')
757 guest_quagga_config = '/root/config'
758 quagga_config_file = os.path.join(guest_quagga_config, 'testrib.conf')
759 host_guest_map = ( (host_quagga_config, guest_quagga_config), )
Chetan Gaonker503032a2016-05-12 12:06:29 -0700760 IMAGE = 'cord-test/quagga'
761 NAME = 'cord-quagga'
762
A R Karthick07608ef2016-08-23 16:51:19 -0700763 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = 'candidate',
Chetan Gaonker503032a2016-05-12 12:06:29 -0700764 boot_delay = 15, restart = False, config_file = quagga_config_file, update = False):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800765 super(Quagga, self).__init__(name, image, prefix = prefix, tag = tag, quagga_config = self.QUAGGA_CONFIG)
Chetan Gaonker503032a2016-05-12 12:06:29 -0700766 if update is True or not self.img_exists():
A R Karthick07608ef2016-08-23 16:51:19 -0700767 self.build_image(self.image_name)
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700768 if restart is True and self.exists():
769 self.kill()
770 if not self.exists():
771 self.remove_container(name, force=True)
A R Karthick41adfce2016-06-10 09:51:25 -0700772 host_config = self.create_host_config(port_list = self.ports,
773 host_guest_map = self.host_guest_map,
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700774 privileged = True)
775 volumes = []
776 for _,g in self.host_guest_map:
777 volumes.append(g)
778 self.start(ports = self.ports,
A R Karthick41adfce2016-06-10 09:51:25 -0700779 host_config = host_config,
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700780 volumes = volumes, tty = True)
781 print('Starting Quagga on container %s' %self.name)
782 self.execute('{0}/start.sh {1}'.format(self.guest_quagga_config, config_file))
783 time.sleep(boot_delay)
784
785 @classmethod
786 def build_image(cls, image):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800787 onos_quagga_ip = Onos.QUAGGA_CONFIG[0]['ip']
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700788 print('Building Quagga image %s' %image)
789 dockerfile = '''
A R Karthick41adfce2016-06-10 09:51:25 -0700790FROM ubuntu:14.04
791MAINTAINER chetan@ciena.com
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700792WORKDIR /root
793RUN useradd -M quagga
794RUN mkdir /var/log/quagga && chown quagga:quagga /var/log/quagga
795RUN mkdir /var/run/quagga && chown quagga:quagga /var/run/quagga
A R Karthick973ea692016-10-17 12:23:02 -0700796RUN apt-get update && apt-get install -qy git autoconf libtool gawk make telnet libreadline6-dev pkg-config protobuf-c-compiler
ChetanGaonkerb5b46c62016-08-16 12:02:53 -0700797RUN git clone git://git.savannah.nongnu.org/quagga.git quagga && \
A R Karthick8f69c2c2016-10-21 11:43:26 -0700798(cd quagga && git checkout quagga-1.0.20160315 && ./bootstrap.sh && \
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700799sed -i -r 's,htonl.*?\(INADDR_LOOPBACK\),inet_addr\("{0}"\),g' zebra/zebra_fpm.c && \
800./configure --enable-fpm --disable-doc --localstatedir=/var/run/quagga && make && make install)
801RUN ldconfig
802'''.format(onos_quagga_ip)
803 super(Quagga, cls).build_image(dockerfile, image)
804 print('Done building image %s' %image)
A R Karthick81acbff2016-06-17 14:45:16 -0700805
A.R Karthick1700e0e2016-10-06 18:16:57 -0700806class QuaggaStopWrapper(Container):
807 def __init__(self, name = Quagga.NAME, image = Quagga.IMAGE, tag = 'candidate'):
808 super(QuaggaStopWrapper, self).__init__(name, image, prefix = Container.IMAGE_PREFIX, tag = tag)
809 if self.exists():
810 self.kill()
811
812
A R Karthick81acbff2016-06-17 14:45:16 -0700813def reinitContainerClients():
814 docker_netns.dckr = Client()
815 Container.dckr = Client()
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700816
817class Xos(Container):
818 setup_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup')
819 TAG = 'latest'
820 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -0700821 host_guest_map = None
822 env = None
823 ports = None
824 volumes = None
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700825
A R Karthick6e80afd2016-10-10 16:03:12 -0700826 @classmethod
827 def get_cmd(cls, img_name):
828 cmd = cls.dckr.inspect_image(img_name)['Config']['Cmd']
829 return ' '.join(cmd)
830
A R Karthicke3bde962016-09-27 15:06:35 -0700831 def __init__(self, name, image, prefix = PREFIX, tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -0700832 boot_delay = 20, restart = False, network_cfg = None, update = False):
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700833 if restart is True:
834 ##Find the right image to restart
835 running_image = filter(lambda c: c['Names'][0] == '/{}'.format(name), self.dckr.containers())
836 if running_image:
837 image_name = running_image[0]['Image']
838 try:
839 image = image_name.split(':')[0]
840 tag = image_name.split(':')[1]
841 except: pass
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700842 super(Xos, self).__init__(name, image, prefix = prefix, tag = tag)
843 if update is True or not self.img_exists():
844 self.build_image(self.image_name)
A R Karthick6e80afd2016-10-10 16:03:12 -0700845 self.command = self.get_cmd(self.image_name).strip() or None
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700846 if restart is True and self.exists():
847 self.kill()
848 if not self.exists():
849 self.remove_container(name, force=True)
A R Karthicke3bde962016-09-27 15:06:35 -0700850 host_config = self.create_host_config(port_list = self.ports,
851 host_guest_map = self.host_guest_map,
852 privileged = True)
853 print('Starting XOS container %s' %self.name)
854 self.start(ports = self.ports, environment = self.env, host_config = host_config,
855 volumes = self.volumes, tty = True)
856 print('Waiting %d seconds for XOS Base Container to boot' %(boot_delay))
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700857 time.sleep(boot_delay)
858
859 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -0700860 def build_image(cls, image, dockerfile_path, image_target = 'build'):
861 cmd = 'cd {} && make {}'.format(dockerfile_path, image_target)
862 print('Building XOS %s' %image)
863 res = os.system(cmd)
864 print('Done building image %s. Image build %s' %(image, 'successful' if res == 0 else 'failed'))
865 return res
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700866
A R Karthicke3bde962016-09-27 15:06:35 -0700867class XosServer(Xos):
868 ports = [8000,9998,9999]
869 NAME = 'xos-server'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700870 IMAGE = 'xosproject/xos'
A R Karthicke3bde962016-09-27 15:06:35 -0700871 BASE_IMAGE = 'xosproject/xos-base'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700872 TAG = 'latest'
873 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -0700874 dockerfile_path = os.path.join(Xos.setup_dir, 'xos')
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700875
A R Karthicke3bde962016-09-27 15:06:35 -0700876 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX, tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -0700877 boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -0700878 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700879
880 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -0700881 def build_image(cls, image = IMAGE):
882 ##build the base image and then build the server image
883 Xos.build_image(cls.BASE_IMAGE, cls.dockerfile_path, image_target = 'base')
884 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700885
A R Karthicke3bde962016-09-27 15:06:35 -0700886class XosSynchronizerOpenstack(Xos):
887 ports = [2375,]
888 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer')
889 NAME = 'xos-synchronizer'
890 IMAGE = 'xosproject/xos-synchronizer-openstack'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700891 TAG = 'latest'
892 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -0700893 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700894
A R Karthicke3bde962016-09-27 15:06:35 -0700895 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -0700896 tag = TAG, boot_delay = 20, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -0700897 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700898
899 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -0700900 def build_image(cls, image = IMAGE):
901 XosServer.build_image()
902 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700903
A R Karthicke3bde962016-09-27 15:06:35 -0700904class XosSynchronizerOnboarding(Xos):
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700905 NAME = 'xos-synchronizer-onboarding'
906 IMAGE = 'xosproject/xos-synchronizer-onboarding'
907 TAG = 'latest'
908 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -0700909 dockerfile_path = os.path.join(Xos.setup_dir, 'onboarding_synchronizer')
910 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700911
A R Karthicke3bde962016-09-27 15:06:35 -0700912 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -0700913 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -0700914 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700915
916 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -0700917 def build_image(cls, image = IMAGE):
918 XosSynchronizerOpenstack.build_image()
919 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700920
A R Karthicke3bde962016-09-27 15:06:35 -0700921class XosSynchronizerOpenvpn(Xos):
922 NAME = 'xos-synchronizer-openvpn'
923 IMAGE = 'xosproject/xos-openvpn'
924 TAG = 'latest'
925 PREFIX = ''
926 dockerfile_path = os.path.join(Xos.setup_dir, 'openvpn')
927 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700928
A R Karthicke3bde962016-09-27 15:06:35 -0700929 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -0700930 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -0700931 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
932
933 @classmethod
934 def build_image(cls, image = IMAGE):
935 XosSynchronizerOpenstack.build_image()
936 Xos.build_image(image, cls.dockerfile_path)
937
938class XosPostgresql(Xos):
939 ports = [5432,]
940 NAME = 'xos-db-postgres'
941 IMAGE = 'xosproject/xos-postgres'
942 TAG = 'latest'
943 PREFIX = ''
944 volumes = ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
945 dockerfile_path = os.path.join(Xos.setup_dir, 'postgresql')
946
947 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -0700948 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -0700949 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
950
951 @classmethod
952 def build_image(cls, image = IMAGE):
953 Xos.build_image(image, cls.dockerfile_path)
954
955class XosSyndicateMs(Xos):
956 ports = [8080,]
957 env = None
958 NAME = 'xos-syndicate-ms'
959 IMAGE = 'xosproject/syndicate-ms'
960 TAG = 'latest'
961 PREFIX = ''
962 dockerfile_path = os.path.join(Xos.setup_dir, 'syndicate-ms')
963
964 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -0700965 boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -0700966 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
967
968 @classmethod
969 def build_image(cls, image = IMAGE):
970 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700971
ChetanGaonkerc220e0d2016-10-05 05:06:25 -0700972class XosSyncVtn(Xos):
973 ports = [8080,]
974 env = None
975 NAME = 'xos-synchronizer-vtn'
976 IMAGE = 'xosproject/xos-synchronizer-vtn'
977 TAG = 'latest'
978 PREFIX = ''
979 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vtn')
980
981 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -0700982 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -0700983 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
984
985 @classmethod
986 def build_image(cls, image = IMAGE):
987 Xos.build_image(image, cls.dockerfile_path)
988
989class XosSyncVtr(Xos):
990 ports = [8080,]
991 env = None
992 NAME = 'xos-synchronizer-vtr'
993 IMAGE = 'xosproject/xos-synchronizer-vtr'
994 TAG = 'latest'
995 PREFIX = ''
996 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vtr')
997
998 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -0700999 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001000 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1001
1002 @classmethod
1003 def build_image(cls, image = IMAGE):
1004 Xos.build_image(image, cls.dockerfile_path)
1005
1006class XosSyncVsg(Xos):
1007 ports = [8080,]
1008 env = None
1009 NAME = 'xos-synchronizer-vsg'
1010 IMAGE = 'xosproject/xos-synchronizer-vsg'
1011 TAG = 'latest'
1012 PREFIX = ''
1013 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vsg')
1014
1015 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001016 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001017 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1018
1019 @classmethod
1020 def build_image(cls, image = IMAGE):
1021 Xos.build_image(image, cls.dockerfile_path)
1022
1023
1024class XosSyncOnos(Xos):
1025 ports = [8080,]
1026 env = None
1027 NAME = 'xos-synchronizer-onos'
1028 IMAGE = 'xosproject/xos-synchronizer-onos'
1029 TAG = 'latest'
1030 PREFIX = ''
1031 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-onos')
1032
1033 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001034 boot_delay = 30, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001035 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1036
1037 @classmethod
1038 def build_image(cls, image = IMAGE):
1039 Xos.build_image(image, cls.dockerfile_path)
1040
1041class XosSyncFabric(Xos):
1042 ports = [8080,]
1043 env = None
1044 NAME = 'xos-synchronizer-fabric'
1045 IMAGE = 'xosproject/xos-synchronizer-fabric'
1046 TAG = 'latest'
1047 PREFIX = ''
1048 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-fabric')
1049
1050 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001051 boot_delay = 30, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001052 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1053
1054 @classmethod
1055 def build_image(cls, image = IMAGE):
1056 Xos.build_image(image, cls.dockerfile_path)
A R Karthick19aaf5c2016-11-09 17:47:57 -08001057
1058if __name__ == '__main__':
1059 onos = Onos(boot_delay = 10, restart = True)