blob: a3f23568af774c3533e65ce3c4355cdda5dba6c9 [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):
334
A R Karthickaa54a1c2016-12-15 11:42:08 -0800335 QUAGGA_CONFIG = [ { 'bridge' : 'quagga-br', 'ip': '10.10.0.4', 'mask' : 16 }, ]
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700336 SYSTEM_MEMORY = (get_mem(),) * 2
A R Karthick1f908202016-11-16 17:32:20 -0800337 INSTANCE_MEMORY = (get_mem(instances=3),) * 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 Karthick3b811152016-12-15 10:24:24 -0800413 cluster = False, data_volume = None, async = False, quagga_config = None, max_instances=1):
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 Karthick3b811152016-12-15 10:24:24 -0800427 self.max_instances = max_instances
A R Karthick2b93d6a2016-09-06 15:19:09 -0700428 self.boot_delay = boot_delay
A R Karthickec2db322016-11-17 15:06:01 -0800429 self.data_map = None
A R Karthick2b93d6a2016-09-06 15:19:09 -0700430 if cluster is True:
431 self.ports = []
A R Karthick3b811152016-12-15 10:24:24 -0800432 if self.max_instances <= 3:
433 java_opts = self.JAVA_OPTS_CLUSTER
434 else:
435 instance_memory = (get_mem(instances=self.max_instances),) * 2
436 java_opts = '-Xms{} -Xmx{} -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode'.format(*instance_memory)
437
438 self.env['JAVA_OPTS'] = java_opts
A R Karthickec2db322016-11-17 15:06:01 -0800439 if data_volume is not None:
440 self.data_map = self.get_data_map(data_volume, self.guest_data_dir)
441 self.host_guest_map = self.host_guest_map + self.data_map
A R Karthick2b93d6a2016-09-06 15:19:09 -0700442 if os.access(self.cluster_cfg, os.F_OK):
443 try:
444 os.unlink(self.cluster_cfg)
445 except: pass
446
447 self.host_config = self.create_host_config(port_list = self.ports,
448 host_guest_map = self.host_guest_map)
449 self.volumes = []
450 for _,g in self.host_guest_map:
451 self.volumes.append(g)
452
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700453 if restart is True and self.exists():
454 self.kill()
A R Karthick2b93d6a2016-09-06 15:19:09 -0700455
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700456 if not self.exists():
457 self.remove_container(name, force=True)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700458 host_config = self.create_host_config(port_list = self.ports,
459 host_guest_map = self.host_guest_map)
460 volumes = []
461 for _,g in self.host_guest_map:
462 volumes.append(g)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700463 if network_cfg is not None:
A R Karthick81acbff2016-06-17 14:45:16 -0700464 json_data = json.dumps(network_cfg, indent=4)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700465 with open('{}/network-cfg.json'.format(self.host_config_dir), 'w') as f:
466 f.write(json_data)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800467 if cluster is False or async is False:
468 print('Starting ONOS container %s' %self.name)
469 self.start(ports = self.ports, environment = self.env,
470 host_config = self.host_config, volumes = self.volumes, tty = True)
471 if not restart:
472 ##wait a bit before fetching IP to regenerate cluster cfg
473 time.sleep(5)
474 ip = self.ip()
475 ##Just a quick hack/check to ensure we don't regenerate in the common case.
476 ##As ONOS is usually the first test container that is started
477 if cluster is False:
478 if ip != self.CLUSTER_CFG_IP or not os.access(self.cluster_cfg, os.F_OK):
479 print('Regenerating ONOS cluster cfg for ip %s' %ip)
480 self.generate_cluster_cfg(ip)
481 self.kill()
482 self.remove_container(self.name, force=True)
483 print('Restarting ONOS container %s' %self.name)
484 self.start(ports = self.ports, environment = self.env,
485 host_config = self.host_config, volumes = self.volumes, tty = True)
486 print('Waiting for ONOS to boot')
487 time.sleep(boot_delay)
488 self.wait_for_onos_start(self.ip())
489 self.running = True
490 else:
491 self.running = False
492 else:
493 self.running = True
494 if self.running:
495 self.ipaddr = self.ip()
496 if cluster is False:
497 self.install_cord_apps(self.ipaddr)
A R Karthick19aaf5c2016-11-09 17:47:57 -0800498
A.R Karthickc4e474d2016-12-12 15:24:57 -0800499 @classmethod
500 def get_quagga_config(cls, instance = 0):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800501 quagga_config = copy.deepcopy(cls.QUAGGA_CONFIG)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800502 if instance == 0:
503 return quagga_config
504 ip = quagga_config[0]['ip']
505 octets = ip.split('.')
A R Karthickaa54a1c2016-12-15 11:42:08 -0800506 octets[3] = str((int(octets[3]) + instance) & 255)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800507 ip = '.'.join(octets)
508 quagga_config[0]['ip'] = ip
509 return quagga_config
510
511 @classmethod
512 def start_cluster_async(cls, onos_instances):
513 instances = filter(lambda o: o.running == False, onos_instances)
514 if not instances:
515 return
516 tpool = ThreadPool(len(instances), queue_size = 1, wait_timeout = 1)
517 for onos in instances:
518 tpool.addTask(onos.start_async)
519 tpool.cleanUpThreads()
520
521 def start_async(self):
522 print('Starting ONOS container %s' %self.name)
523 self.start(ports = self.ports, environment = self.env,
524 host_config = self.host_config, volumes = self.volumes, tty = True)
525 time.sleep(3)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700526 self.ipaddr = self.ip()
A.R Karthickc4e474d2016-12-12 15:24:57 -0800527 print('Waiting for ONOS container %s to start' %self.name)
528 self.wait_for_onos_start(self.ipaddr)
529 self.running = True
530 print('ONOS container %s started' %self.name)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700531
A R Karthick2b93d6a2016-09-06 15:19:09 -0700532 @classmethod
A R Karthick19aaf5c2016-11-09 17:47:57 -0800533 def wait_for_onos_start(cls, ip, tries = 30):
534 onos_log = OnosLog(host = ip)
535 num_tries = 0
536 started = None
537 while not started and num_tries < tries:
538 time.sleep(3)
539 started = onos_log.search_log_pattern('ApplicationManager .* Started')
540 num_tries += 1
541
A R Karthick19aaf5c2016-11-09 17:47:57 -0800542 if not started:
543 print('ONOS did not start')
544 else:
545 print('ONOS started')
546 return started
547
548 @classmethod
A R Karthick2b93d6a2016-09-06 15:19:09 -0700549 def setup_cluster_deprecated(cls, onos_instances, image_name = None):
550 if not onos_instances or len(onos_instances) < 2:
551 return
552 ips = []
553 if image_name is not None:
554 ips = Container.ips(image_name)
555 else:
556 for onos in onos_instances:
557 ips.append(onos.ipaddr)
558 Onos.cluster_instances = onos_instances
559 Onos.cluster_mode = True
560 ##regenerate the cluster json with the 3 instance ips before restarting them back
561 print('Generating cluster cfg for ONOS instances with ips %s' %ips)
562 Onos.generate_cluster_cfg(ips)
563 for onos in onos_instances:
564 onos.kill()
565 onos.remove_container(onos.name, force=True)
566 print('Restarting ONOS container %s for forming cluster' %onos.name)
567 onos.start(ports = onos.ports, environment = onos.env,
568 host_config = onos.host_config, volumes = onos.volumes, tty = True)
569 print('Waiting %d seconds for ONOS %s to boot' %(onos.boot_delay, onos.name))
570 time.sleep(onos.boot_delay)
571 onos.ipaddr = onos.ip()
572 onos.install_cord_apps(onos.ipaddr)
573
574 @classmethod
575 def setup_cluster(cls, onos_instances, image_name = None):
576 if not onos_instances or len(onos_instances) < 2:
577 return
578 ips = []
579 if image_name is not None:
580 ips = Container.ips(image_name)
581 else:
582 for onos in onos_instances:
583 ips.append(onos.ipaddr)
584 Onos.cluster_instances = onos_instances
585 Onos.cluster_mode = True
586 ##regenerate the cluster json with the 3 instance ips before restarting them back
587 print('Forming cluster for ONOS instances with ips %s' %ips)
588 Onos.form_cluster(ips)
589 ##wait for the cluster to be formed
590 print('Waiting for the cluster to be formed')
591 time.sleep(60)
592 for onos in onos_instances:
593 onos.install_cord_apps(onos.ipaddr)
594
595 @classmethod
A R Karthicke2c24bd2016-10-07 14:51:38 -0700596 def add_cluster(cls, count = 1, network_cfg = None):
597 if not cls.cluster_instances or Onos.cluster_mode is False:
598 return
599 for i in range(count):
600 name = '{}-{}'.format(Onos.NAME, len(cls.cluster_instances)+1)
601 onos = cls(name = name, image = Onos.IMAGE, tag = Onos.TAG, prefix = Container.IMAGE_PREFIX,
602 cluster = True, network_cfg = network_cfg)
603 cls.cluster_instances.append(onos)
604
605 cls.setup_cluster(cls.cluster_instances)
606
607 @classmethod
A.R Karthick2560f042016-11-30 14:38:52 -0800608 def restart_cluster(cls, network_cfg = None, timeout = 10, setup = False):
A R Karthick2b93d6a2016-09-06 15:19:09 -0700609 if cls.cluster_mode is False:
610 return
611 if not cls.cluster_instances:
612 return
613
614 if network_cfg is not None:
615 json_data = json.dumps(network_cfg, indent=4)
616 with open('{}/network-cfg.json'.format(cls.host_config_dir), 'w') as f:
617 f.write(json_data)
618
A.R Karthick2560f042016-11-30 14:38:52 -0800619 cls.cleanup_cluster()
620 if timeout > 0:
621 time.sleep(timeout)
622
A R Karthickaa54a1c2016-12-15 11:42:08 -0800623 #start the instances asynchronously
624 cls.start_cluster_async(cls.cluster_instances)
625 time.sleep(5)
A.R Karthick2560f042016-11-30 14:38:52 -0800626 ##form the cluster as appropriate
627 if setup is True:
628 cls.setup_cluster(cls.cluster_instances)
A R Karthickaa54a1c2016-12-15 11:42:08 -0800629 else:
630 for onos in cls.cluster_instances:
631 onos.install_cord_apps(onos.ipaddr)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700632
633 @classmethod
634 def cluster_ips(cls):
635 if cls.cluster_mode is False:
636 return []
637 if not cls.cluster_instances:
638 return []
639 ips = [ onos.ipaddr for onos in cls.cluster_instances ]
640 return ips
641
642 @classmethod
643 def cleanup_cluster(cls):
644 if cls.cluster_mode is False:
645 return
646 if not cls.cluster_instances:
647 return
648 for onos in cls.cluster_instances:
649 if onos.exists():
650 onos.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800651 onos.running = False
A R Karthick2b93d6a2016-09-06 15:19:09 -0700652 onos.remove_container(onos.name, force=True)
A R Karthickd44cea12016-07-20 12:16:41 -0700653
A.R Karthick95d044e2016-06-10 18:44:36 -0700654 @classmethod
A R Karthickde6b9dc2016-11-29 17:46:16 -0800655 def restart_node(cls, node = None, network_cfg = None, timeout = 10):
A R Karthick889d9652016-10-03 14:13:45 -0700656 if node is None:
657 cls(restart = True, network_cfg = network_cfg, image = cls.IMAGE, tag = cls.TAG)
658 else:
659 #Restarts a node in the cluster
660 valid_node = filter(lambda onos: node in [ onos.ipaddr, onos.name ], cls.cluster_instances)
661 if valid_node:
662 onos = valid_node.pop()
663 if onos.exists():
664 onos.kill()
665 onos.remove_container(onos.name, force=True)
A R Karthickde6b9dc2016-11-29 17:46:16 -0800666 if timeout > 0:
667 time.sleep(timeout)
A R Karthick889d9652016-10-03 14:13:45 -0700668 print('Restarting ONOS container %s' %onos.name)
669 onos.start(ports = onos.ports, environment = onos.env,
670 host_config = onos.host_config, volumes = onos.volumes, tty = True)
A R Karthick889d9652016-10-03 14:13:45 -0700671 onos.ipaddr = onos.ip()
A.R Karthick2560f042016-11-30 14:38:52 -0800672 onos.wait_for_onos_start(onos.ipaddr)
673 onos.install_cord_apps(onos.ipaddr)
A R Karthick889d9652016-10-03 14:13:45 -0700674
675 @classmethod
A R Karthickeaf1c4e2016-07-19 12:22:35 -0700676 def install_cord_apps(cls, onos_ip = None):
A.R Karthick95d044e2016-06-10 18:44:36 -0700677 for app, version in cls.onos_cord_apps:
678 app_file = '{}/{}-{}.oar'.format(cls.cord_apps_dir, app, version)
A R Karthickeaf1c4e2016-07-19 12:22:35 -0700679 ok, code = OnosCtrl.install_app(app_file, onos_ip = onos_ip)
A.R Karthick95d044e2016-06-10 18:44:36 -0700680 ##app already installed (conflicts)
681 if code in [ 409 ]:
682 ok = True
683 print('ONOS app %s, version %s %s' %(app, version, 'installed' if ok else 'failed to install'))
684 time.sleep(2)
685
A.R Karthick1700e0e2016-10-06 18:16:57 -0700686class OnosStopWrapper(Container):
687 def __init__(self, name):
688 super(OnosStopWrapper, self).__init__(name, Onos.IMAGE, tag = Onos.TAG, prefix = Container.IMAGE_PREFIX)
689 if self.exists():
690 self.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800691 self.running = False
A.R Karthick1700e0e2016-10-06 18:16:57 -0700692 else:
693 if Onos.cluster_mode is True:
694 valid_node = filter(lambda onos: name in [ onos.ipaddr, onos.name ], Onos.cluster_instances)
695 if valid_node:
696 onos = valid_node.pop()
697 if onos.exists():
698 onos.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800699 onos.running = False
A.R Karthick1700e0e2016-10-06 18:16:57 -0700700
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700701class Radius(Container):
702 ports = [ 1812, 1813 ]
A R Karthick41adfce2016-06-10 09:51:25 -0700703 env = {'TIMEZONE':'America/Los_Angeles',
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700704 'DEBUG': 'true', 'cert_password':'whatever', 'primary_shared_secret':'radius_password'
705 }
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700706 host_db_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/db')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700707 guest_db_dir = os.path.join(os.path.sep, 'opt', 'db')
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700708 host_config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/freeradius')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700709 guest_config_dir = os.path.join(os.path.sep, 'etc', 'freeradius')
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700710 start_command = os.path.join(guest_config_dir, 'start-radius.py')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700711 host_guest_map = ( (host_db_dir, guest_db_dir),
712 (host_config_dir, guest_config_dir)
713 )
Chetan Gaonker503032a2016-05-12 12:06:29 -0700714 IMAGE = 'cord-test/radius'
715 NAME = 'cord-radius'
716
A R Karthick07608ef2016-08-23 16:51:19 -0700717 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = 'candidate',
Chetan Gaonker503032a2016-05-12 12:06:29 -0700718 boot_delay = 10, restart = False, update = False):
A R Karthick07608ef2016-08-23 16:51:19 -0700719 super(Radius, self).__init__(name, image, prefix = prefix, tag = tag, command = self.start_command)
Chetan Gaonker503032a2016-05-12 12:06:29 -0700720 if update is True or not self.img_exists():
A R Karthick07608ef2016-08-23 16:51:19 -0700721 self.build_image(self.image_name)
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700722 if restart is True and self.exists():
723 self.kill()
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700724 if not self.exists():
725 self.remove_container(name, force=True)
726 host_config = self.create_host_config(port_list = self.ports,
727 host_guest_map = self.host_guest_map)
728 volumes = []
729 for _,g in self.host_guest_map:
730 volumes.append(g)
A R Karthick41adfce2016-06-10 09:51:25 -0700731 self.start(ports = self.ports, environment = self.env,
732 volumes = volumes,
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700733 host_config = host_config, tty = True)
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700734 time.sleep(boot_delay)
735
736 @classmethod
737 def build_image(cls, image):
738 print('Building Radius image %s' %image)
739 dockerfile = '''
740FROM hbouvier/docker-radius
741MAINTAINER chetan@ciena.com
742LABEL RUN docker pull hbouvier/docker-radius
743LABEL RUN docker run -it --name cord-radius hbouvier/docker-radius
A R Karthickc762df42016-05-25 10:09:21 -0700744RUN apt-get update && \
745 apt-get -y install python python-pexpect strace
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700746WORKDIR /root
747CMD ["/etc/freeradius/start-radius.py"]
748'''
749 super(Radius, cls).build_image(dockerfile, image)
750 print('Done building image %s' %image)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700751
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700752class Quagga(Container):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800753 QUAGGA_CONFIG = ( { 'bridge' : 'quagga-br', 'ip': '10.10.0.3', 'mask' : 16 },
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700754 { 'bridge' : 'quagga-br', 'ip': '192.168.10.3', 'mask': 16 },
755 )
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700756 ports = [ 179, 2601, 2602, 2603, 2604, 2605, 2606 ]
757 host_quagga_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/quagga-config')
758 guest_quagga_config = '/root/config'
759 quagga_config_file = os.path.join(guest_quagga_config, 'testrib.conf')
760 host_guest_map = ( (host_quagga_config, guest_quagga_config), )
Chetan Gaonker503032a2016-05-12 12:06:29 -0700761 IMAGE = 'cord-test/quagga'
762 NAME = 'cord-quagga'
763
A R Karthick07608ef2016-08-23 16:51:19 -0700764 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = 'candidate',
Chetan Gaonker503032a2016-05-12 12:06:29 -0700765 boot_delay = 15, restart = False, config_file = quagga_config_file, update = False):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800766 super(Quagga, self).__init__(name, image, prefix = prefix, tag = tag, quagga_config = self.QUAGGA_CONFIG)
Chetan Gaonker503032a2016-05-12 12:06:29 -0700767 if update is True or not self.img_exists():
A R Karthick07608ef2016-08-23 16:51:19 -0700768 self.build_image(self.image_name)
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700769 if restart is True and self.exists():
770 self.kill()
771 if not self.exists():
772 self.remove_container(name, force=True)
A R Karthick41adfce2016-06-10 09:51:25 -0700773 host_config = self.create_host_config(port_list = self.ports,
774 host_guest_map = self.host_guest_map,
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700775 privileged = True)
776 volumes = []
777 for _,g in self.host_guest_map:
778 volumes.append(g)
779 self.start(ports = self.ports,
A R Karthick41adfce2016-06-10 09:51:25 -0700780 host_config = host_config,
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700781 volumes = volumes, tty = True)
782 print('Starting Quagga on container %s' %self.name)
783 self.execute('{0}/start.sh {1}'.format(self.guest_quagga_config, config_file))
784 time.sleep(boot_delay)
785
786 @classmethod
787 def build_image(cls, image):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800788 onos_quagga_ip = Onos.QUAGGA_CONFIG[0]['ip']
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700789 print('Building Quagga image %s' %image)
790 dockerfile = '''
A R Karthick41adfce2016-06-10 09:51:25 -0700791FROM ubuntu:14.04
792MAINTAINER chetan@ciena.com
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700793WORKDIR /root
794RUN useradd -M quagga
795RUN mkdir /var/log/quagga && chown quagga:quagga /var/log/quagga
796RUN mkdir /var/run/quagga && chown quagga:quagga /var/run/quagga
A R Karthick973ea692016-10-17 12:23:02 -0700797RUN 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 -0700798RUN git clone git://git.savannah.nongnu.org/quagga.git quagga && \
A R Karthick8f69c2c2016-10-21 11:43:26 -0700799(cd quagga && git checkout quagga-1.0.20160315 && ./bootstrap.sh && \
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700800sed -i -r 's,htonl.*?\(INADDR_LOOPBACK\),inet_addr\("{0}"\),g' zebra/zebra_fpm.c && \
801./configure --enable-fpm --disable-doc --localstatedir=/var/run/quagga && make && make install)
802RUN ldconfig
803'''.format(onos_quagga_ip)
804 super(Quagga, cls).build_image(dockerfile, image)
805 print('Done building image %s' %image)
A R Karthick81acbff2016-06-17 14:45:16 -0700806
A.R Karthick1700e0e2016-10-06 18:16:57 -0700807class QuaggaStopWrapper(Container):
808 def __init__(self, name = Quagga.NAME, image = Quagga.IMAGE, tag = 'candidate'):
809 super(QuaggaStopWrapper, self).__init__(name, image, prefix = Container.IMAGE_PREFIX, tag = tag)
810 if self.exists():
811 self.kill()
812
813
A R Karthick81acbff2016-06-17 14:45:16 -0700814def reinitContainerClients():
815 docker_netns.dckr = Client()
816 Container.dckr = Client()
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700817
818class Xos(Container):
819 setup_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup')
820 TAG = 'latest'
821 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -0700822 host_guest_map = None
823 env = None
824 ports = None
825 volumes = None
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700826
A R Karthick6e80afd2016-10-10 16:03:12 -0700827 @classmethod
828 def get_cmd(cls, img_name):
829 cmd = cls.dckr.inspect_image(img_name)['Config']['Cmd']
830 return ' '.join(cmd)
831
A R Karthicke3bde962016-09-27 15:06:35 -0700832 def __init__(self, name, image, prefix = PREFIX, tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -0700833 boot_delay = 20, restart = False, network_cfg = None, update = False):
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700834 if restart is True:
835 ##Find the right image to restart
836 running_image = filter(lambda c: c['Names'][0] == '/{}'.format(name), self.dckr.containers())
837 if running_image:
838 image_name = running_image[0]['Image']
839 try:
840 image = image_name.split(':')[0]
841 tag = image_name.split(':')[1]
842 except: pass
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700843 super(Xos, self).__init__(name, image, prefix = prefix, tag = tag)
844 if update is True or not self.img_exists():
845 self.build_image(self.image_name)
A R Karthick6e80afd2016-10-10 16:03:12 -0700846 self.command = self.get_cmd(self.image_name).strip() or None
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700847 if restart is True and self.exists():
848 self.kill()
849 if not self.exists():
850 self.remove_container(name, force=True)
A R Karthicke3bde962016-09-27 15:06:35 -0700851 host_config = self.create_host_config(port_list = self.ports,
852 host_guest_map = self.host_guest_map,
853 privileged = True)
854 print('Starting XOS container %s' %self.name)
855 self.start(ports = self.ports, environment = self.env, host_config = host_config,
856 volumes = self.volumes, tty = True)
857 print('Waiting %d seconds for XOS Base Container to boot' %(boot_delay))
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700858 time.sleep(boot_delay)
859
860 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -0700861 def build_image(cls, image, dockerfile_path, image_target = 'build'):
862 cmd = 'cd {} && make {}'.format(dockerfile_path, image_target)
863 print('Building XOS %s' %image)
864 res = os.system(cmd)
865 print('Done building image %s. Image build %s' %(image, 'successful' if res == 0 else 'failed'))
866 return res
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700867
A R Karthicke3bde962016-09-27 15:06:35 -0700868class XosServer(Xos):
869 ports = [8000,9998,9999]
870 NAME = 'xos-server'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700871 IMAGE = 'xosproject/xos'
A R Karthicke3bde962016-09-27 15:06:35 -0700872 BASE_IMAGE = 'xosproject/xos-base'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700873 TAG = 'latest'
874 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -0700875 dockerfile_path = os.path.join(Xos.setup_dir, 'xos')
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700876
A R Karthicke3bde962016-09-27 15:06:35 -0700877 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX, tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -0700878 boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -0700879 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700880
881 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -0700882 def build_image(cls, image = IMAGE):
883 ##build the base image and then build the server image
884 Xos.build_image(cls.BASE_IMAGE, cls.dockerfile_path, image_target = 'base')
885 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700886
A R Karthicke3bde962016-09-27 15:06:35 -0700887class XosSynchronizerOpenstack(Xos):
888 ports = [2375,]
889 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer')
890 NAME = 'xos-synchronizer'
891 IMAGE = 'xosproject/xos-synchronizer-openstack'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700892 TAG = 'latest'
893 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -0700894 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700895
A R Karthicke3bde962016-09-27 15:06:35 -0700896 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -0700897 tag = TAG, boot_delay = 20, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -0700898 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700899
900 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -0700901 def build_image(cls, image = IMAGE):
902 XosServer.build_image()
903 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700904
A R Karthicke3bde962016-09-27 15:06:35 -0700905class XosSynchronizerOnboarding(Xos):
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700906 NAME = 'xos-synchronizer-onboarding'
907 IMAGE = 'xosproject/xos-synchronizer-onboarding'
908 TAG = 'latest'
909 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -0700910 dockerfile_path = os.path.join(Xos.setup_dir, 'onboarding_synchronizer')
911 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700912
A R Karthicke3bde962016-09-27 15:06:35 -0700913 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -0700914 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -0700915 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700916
917 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -0700918 def build_image(cls, image = IMAGE):
919 XosSynchronizerOpenstack.build_image()
920 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700921
A R Karthicke3bde962016-09-27 15:06:35 -0700922class XosSynchronizerOpenvpn(Xos):
923 NAME = 'xos-synchronizer-openvpn'
924 IMAGE = 'xosproject/xos-openvpn'
925 TAG = 'latest'
926 PREFIX = ''
927 dockerfile_path = os.path.join(Xos.setup_dir, 'openvpn')
928 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700929
A R Karthicke3bde962016-09-27 15:06:35 -0700930 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -0700931 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -0700932 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
933
934 @classmethod
935 def build_image(cls, image = IMAGE):
936 XosSynchronizerOpenstack.build_image()
937 Xos.build_image(image, cls.dockerfile_path)
938
939class XosPostgresql(Xos):
940 ports = [5432,]
941 NAME = 'xos-db-postgres'
942 IMAGE = 'xosproject/xos-postgres'
943 TAG = 'latest'
944 PREFIX = ''
945 volumes = ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
946 dockerfile_path = os.path.join(Xos.setup_dir, 'postgresql')
947
948 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -0700949 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -0700950 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
951
952 @classmethod
953 def build_image(cls, image = IMAGE):
954 Xos.build_image(image, cls.dockerfile_path)
955
956class XosSyndicateMs(Xos):
957 ports = [8080,]
958 env = None
959 NAME = 'xos-syndicate-ms'
960 IMAGE = 'xosproject/syndicate-ms'
961 TAG = 'latest'
962 PREFIX = ''
963 dockerfile_path = os.path.join(Xos.setup_dir, 'syndicate-ms')
964
965 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -0700966 boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -0700967 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
968
969 @classmethod
970 def build_image(cls, image = IMAGE):
971 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700972
ChetanGaonkerc220e0d2016-10-05 05:06:25 -0700973class XosSyncVtn(Xos):
974 ports = [8080,]
975 env = None
976 NAME = 'xos-synchronizer-vtn'
977 IMAGE = 'xosproject/xos-synchronizer-vtn'
978 TAG = 'latest'
979 PREFIX = ''
980 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vtn')
981
982 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -0700983 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -0700984 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
985
986 @classmethod
987 def build_image(cls, image = IMAGE):
988 Xos.build_image(image, cls.dockerfile_path)
989
990class XosSyncVtr(Xos):
991 ports = [8080,]
992 env = None
993 NAME = 'xos-synchronizer-vtr'
994 IMAGE = 'xosproject/xos-synchronizer-vtr'
995 TAG = 'latest'
996 PREFIX = ''
997 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vtr')
998
999 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001000 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001001 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1002
1003 @classmethod
1004 def build_image(cls, image = IMAGE):
1005 Xos.build_image(image, cls.dockerfile_path)
1006
1007class XosSyncVsg(Xos):
1008 ports = [8080,]
1009 env = None
1010 NAME = 'xos-synchronizer-vsg'
1011 IMAGE = 'xosproject/xos-synchronizer-vsg'
1012 TAG = 'latest'
1013 PREFIX = ''
1014 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vsg')
1015
1016 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001017 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001018 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1019
1020 @classmethod
1021 def build_image(cls, image = IMAGE):
1022 Xos.build_image(image, cls.dockerfile_path)
1023
1024
1025class XosSyncOnos(Xos):
1026 ports = [8080,]
1027 env = None
1028 NAME = 'xos-synchronizer-onos'
1029 IMAGE = 'xosproject/xos-synchronizer-onos'
1030 TAG = 'latest'
1031 PREFIX = ''
1032 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-onos')
1033
1034 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001035 boot_delay = 30, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001036 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1037
1038 @classmethod
1039 def build_image(cls, image = IMAGE):
1040 Xos.build_image(image, cls.dockerfile_path)
1041
1042class XosSyncFabric(Xos):
1043 ports = [8080,]
1044 env = None
1045 NAME = 'xos-synchronizer-fabric'
1046 IMAGE = 'xosproject/xos-synchronizer-fabric'
1047 TAG = 'latest'
1048 PREFIX = ''
1049 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-fabric')
1050
1051 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001052 boot_delay = 30, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001053 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1054
1055 @classmethod
1056 def build_image(cls, image = IMAGE):
1057 Xos.build_image(image, cls.dockerfile_path)
A R Karthick19aaf5c2016-11-09 17:47:57 -08001058
1059if __name__ == '__main__':
1060 onos = Onos(boot_delay = 10, restart = True)