blob: 2f346754d1c3e6e5a71560bcd9933851248ba15a [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 Karthick85eb1862017-01-23 16:10:57 -080027from docker import utils as dockerutils
A.R Karthickf184b342017-01-27 19:30:50 -080028import shutil
A.R Karthick95d044e2016-06-10 18:44:36 -070029from OnosCtrl import OnosCtrl
A R Karthick19aaf5c2016-11-09 17:47:57 -080030from OnosLog import OnosLog
A.R Karthickc4e474d2016-12-12 15:24:57 -080031from threadPool import ThreadPool
A R Karthickaa54a1c2016-12-15 11:42:08 -080032from threading import Lock
Chetan Gaonker3533faa2016-04-25 17:50:14 -070033
34class docker_netns(object):
35
36 dckr = Client()
37 def __init__(self, name):
38 pid = int(self.dckr.inspect_container(name)['State']['Pid'])
39 if pid == 0:
40 raise Exception('no container named {0}'.format(name))
41 self.pid = pid
42
43 def __enter__(self):
44 pid = self.pid
45 if not os.path.exists('/var/run/netns'):
46 os.mkdir('/var/run/netns')
47 os.symlink('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(pid))
48 return str(pid)
49
50 def __exit__(self, type, value, traceback):
51 pid = self.pid
52 os.unlink('/var/run/netns/{0}'.format(pid))
53
54flatten = lambda l: chain.from_iterable(l)
55
56class Container(object):
57 dckr = Client()
A R Karthick07608ef2016-08-23 16:51:19 -070058 IMAGE_PREFIX = '' ##for saving global prefix for all test classes
A R Karthickaa54a1c2016-12-15 11:42:08 -080059 CONFIG_LOCK = Lock()
A R Karthick07608ef2016-08-23 16:51:19 -070060
61 def __init__(self, name, image, prefix='', tag = 'candidate', command = 'bash', quagga_config = None):
Chetan Gaonker3533faa2016-04-25 17:50:14 -070062 self.name = name
A R Karthick07608ef2016-08-23 16:51:19 -070063 self.prefix = prefix
64 if prefix:
65 self.prefix += '/'
66 image = '{}{}'.format(self.prefix, image)
Chetan Gaonker3533faa2016-04-25 17:50:14 -070067 self.image = image
68 self.tag = tag
A R Karthickd44cea12016-07-20 12:16:41 -070069 if tag:
70 self.image_name = image + ':' + tag
71 else:
72 self.image_name = image
Chetan Gaonker3533faa2016-04-25 17:50:14 -070073 self.id = None
74 self.command = command
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -070075 self.quagga_config = quagga_config
Chetan Gaonker3533faa2016-04-25 17:50:14 -070076
77 @classmethod
78 def build_image(cls, dockerfile, tag, force=True, nocache=False):
79 f = io.BytesIO(dockerfile.encode('utf-8'))
80 if force or not cls.image_exists(tag):
81 print('Build {0}...'.format(tag))
82 for line in cls.dckr.build(fileobj=f, rm=True, tag=tag, decode=True, nocache=nocache):
83 if 'stream' in line:
84 print(line['stream'].strip())
85
86 @classmethod
87 def image_exists(cls, name):
88 return name in [ctn['RepoTags'][0] for ctn in cls.dckr.images()]
89
90 @classmethod
91 def create_host_config(cls, port_list = None, host_guest_map = None, privileged = False):
92 port_bindings = None
93 binds = None
94 if port_list:
95 port_bindings = {}
96 for p in port_list:
97 port_bindings[str(p)] = str(p)
98
99 if host_guest_map:
100 binds = []
101 for h, g in host_guest_map:
102 binds.append('{0}:{1}'.format(h, g))
103
104 return cls.dckr.create_host_config(binds = binds, port_bindings = port_bindings, privileged = privileged)
105
106 @classmethod
A R Karthick85eb1862017-01-23 16:10:57 -0800107 def connect_to_network(cls, name, network):
108 try:
109 cls.dckr.connect_container_to_network(name, network)
110 return True
111 except:
112 return False
113
114 @classmethod
115 def create_network(cls, network, subnet = None, gateway = None):
116 ipam_config = None
117 if subnet is not None and gateway is not None:
118 ipam_pool = dockerutils.create_ipam_pool(subnet = subnet, gateway = gateway)
119 ipam_config = dockerutils.create_ipam_config(pool_configs = [ipam_pool])
120 cls.dckr.create_network(network, driver='bridge', ipam = ipam_config)
121
122 @classmethod
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700123 def cleanup(cls, image):
A R Karthick09b1f4e2016-05-12 14:31:50 -0700124 cnt_list = filter(lambda c: c['Image'] == image, cls.dckr.containers(all=True))
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700125 for cnt in cnt_list:
126 print('Cleaning container %s' %cnt['Id'])
A.R Karthick95d044e2016-06-10 18:44:36 -0700127 if cnt.has_key('State') and cnt['State'] == 'running':
A R Karthick09b1f4e2016-05-12 14:31:50 -0700128 cls.dckr.kill(cnt['Id'])
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700129 cls.dckr.remove_container(cnt['Id'], force=True)
130
131 @classmethod
132 def remove_container(cls, name, force=True):
133 try:
134 cls.dckr.remove_container(name, force = force)
135 except: pass
136
137 def exists(self):
138 return '/{0}'.format(self.name) in list(flatten(n['Names'] for n in self.dckr.containers()))
139
140 def img_exists(self):
A R Karthick6d98a592016-08-24 15:16:46 -0700141 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 -0700142
A R Karthick75844572017-01-23 16:57:44 -0800143 def ip(self, network = None):
A R Karthick2b93d6a2016-09-06 15:19:09 -0700144 cnt_list = filter(lambda c: c['Names'][0] == '/{}'.format(self.name), self.dckr.containers())
145 #if not cnt_list:
146 # cnt_list = filter(lambda c: c['Image'] == self.image_name, self.dckr.containers())
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700147 cnt_settings = cnt_list.pop()
A R Karthick75844572017-01-23 16:57:44 -0800148 if network is not None and cnt_settings['NetworkSettings']['Networks'].has_key(network):
149 return cnt_settings['NetworkSettings']['Networks'][network]['IPAddress']
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700150 return cnt_settings['NetworkSettings']['Networks']['bridge']['IPAddress']
151
A R Karthick2b93d6a2016-09-06 15:19:09 -0700152 @classmethod
153 def ips(cls, image_name):
154 cnt_list = filter(lambda c: c['Image'] == image_name, cls.dckr.containers())
155 ips = [ cnt['NetworkSettings']['Networks']['bridge']['IPAddress'] for cnt in cnt_list ]
156 return ips
157
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700158 def kill(self, remove = True):
159 self.dckr.kill(self.name)
160 self.dckr.remove_container(self.name, force=True)
161
A R Karthick41adfce2016-06-10 09:51:25 -0700162 def start(self, rm = True, ports = None, volumes = None, host_config = None,
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700163 environment = None, tty = False, stdin_open = True):
164
165 if rm and self.exists():
166 print('Removing container:', self.name)
167 self.dckr.remove_container(self.name, force=True)
168
A R Karthick41adfce2016-06-10 09:51:25 -0700169 ctn = self.dckr.create_container(image=self.image_name, ports = ports, command=self.command,
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700170 detach=True, name=self.name,
A R Karthick41adfce2016-06-10 09:51:25 -0700171 environment = environment,
172 volumes = volumes,
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700173 host_config = host_config, stdin_open=stdin_open, tty = tty)
174 self.dckr.start(container=self.name)
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700175 if self.quagga_config:
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700176 self.connect_to_br()
177 self.id = ctn['Id']
178 return ctn
179
Thangavelu K Sef6f0a52016-12-14 19:57:05 +0000180 @classmethod
181 def pause_container(cls, image, delay):
182 cnt_list = filter(lambda c: c['Image'] == image, cls.dckr.containers(all=True))
183 for cnt in cnt_list:
184 print('Pause the container %s' %cnt['Id'])
185 if cnt.has_key('State') and cnt['State'] == 'running':
186 cls.dckr.pause(cnt['Id'])
187 if delay != 0:
188 time.sleep(delay)
189 for cnt in cnt_list:
190 print('Unpause the container %s' %cnt['Id'])
191 cls.dckr.unpause(cnt['Id'])
192 else:
193 print('Infinity time pause the container %s' %cnt['Id'])
194 return 'success'
195
A R Karthick52414732017-01-31 09:59:47 -0800196 def connect_to_br(self, index = 0):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800197 self.CONFIG_LOCK.acquire()
198 try:
199 with docker_netns(self.name) as pid:
200 for quagga_config in self.quagga_config:
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700201 ip = IPRoute()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800202 br = ip.link_lookup(ifname=quagga_config['bridge'])
203 if len(br) == 0:
204 try:
205 ip.link_create(ifname=quagga_config['bridge'], kind='bridge')
206 except NetlinkError as e:
207 err, _ = e.args
208 if err == errno.EEXIST:
209 pass
210 else:
211 raise NetlinkError(*e.args)
212 br = ip.link_lookup(ifname=quagga_config['bridge'])
213 br = br[0]
214 ip.link('set', index=br, state='up')
A R Karthick52414732017-01-31 09:59:47 -0800215 ifname = '{0}-{1}'.format(self.name[:12], index)
A R Karthickaa54a1c2016-12-15 11:42:08 -0800216 ifs = ip.link_lookup(ifname=ifname)
217 if len(ifs) > 0:
218 ip.link_remove(ifs[0])
219 peer_ifname = '{0}-{1}'.format(pid, index)
220 ip.link_create(ifname=ifname, kind='veth', peer=peer_ifname)
221 host = ip.link_lookup(ifname=ifname)[0]
222 ip.link('set', index=host, master=br)
223 ip.link('set', index=host, state='up')
224 guest = ip.link_lookup(ifname=peer_ifname)[0]
225 ip.link('set', index=guest, net_ns_fd=pid)
226 with Namespace(pid, 'net'):
227 ip = IPRoute()
228 ip.link('set', index=guest, ifname='eth{}'.format(index+1))
229 ip.addr('add', index=guest, address=quagga_config['ip'], mask=quagga_config['mask'])
230 ip.link('set', index=guest, state='up')
231 index += 1
232 finally:
233 self.CONFIG_LOCK.release()
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700234
Thangavelu K Sef6f0a52016-12-14 19:57:05 +0000235 def execute(self, cmd, tty = True, stream = False, shell = False, detach = True):
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700236 res = 0
237 if type(cmd) == str:
238 cmds = (cmd,)
239 else:
240 cmds = cmd
241 if shell:
242 for c in cmds:
243 res += os.system('docker exec {0} {1}'.format(self.name, c))
244 return res
245 for c in cmds:
246 i = self.dckr.exec_create(container=self.name, cmd=c, tty = tty, privileged = True)
Thangavelu K Sef6f0a52016-12-14 19:57:05 +0000247 self.dckr.exec_start(i['Id'], stream = stream, detach=detach)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700248 result = self.dckr.exec_inspect(i['Id'])
249 res += 0 if result['ExitCode'] == None else result['ExitCode']
250 return res
251
ChetanGaonker6138fcd2016-08-18 17:56:39 -0700252 def restart(self, timeout =10):
253 return self.dckr.restart(self.name, timeout)
254
A R Karthickc69d73e2017-01-20 11:44:34 -0800255def get_mem(jvm_heap_size = None, instances = 1):
A R Karthick1f908202016-11-16 17:32:20 -0800256 if instances <= 0:
257 instances = 1
A R Karthickc69d73e2017-01-20 11:44:34 -0800258 heap_size = jvm_heap_size
259 heap_size_i = 0
260 #sanitize the heap size config
261 if heap_size is not None:
262 if not heap_size.isdigit():
263 try:
264 heap_size_i = int(heap_size[:-1])
265 suffix = heap_size[-1]
266 if suffix == 'M':
267 heap_size_i /= 1024 #convert to gigs
268 except:
269 ##invalid suffix length probably. Fall back to default
270 heap_size = None
271 else:
272 heap_size_i = int(heap_size)
273
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700274 with open('/proc/meminfo', 'r') as fd:
275 meminfo = fd.readlines()
276 mem = 0
277 for m in meminfo:
278 if m.startswith('MemTotal:') or m.startswith('SwapTotal:'):
279 mem += int(m.split(':')[1].strip().split()[0])
280
A R Karthick1f908202016-11-16 17:32:20 -0800281 mem = max(mem/1024/1024/2/instances, 1)
Chetan Gaonker6d0a7b02016-05-03 16:57:28 -0700282 mem = min(mem, 16)
A R Karthickc69d73e2017-01-20 11:44:34 -0800283
284 if heap_size_i:
285 #we take the minimum of the provided heap size and max allowed heap size
286 heap_size_i = min(heap_size_i, mem)
287 else:
288 heap_size_i = mem
289
290 return '{}G'.format(heap_size_i)
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700291
A R Karthickd44cea12016-07-20 12:16:41 -0700292class OnosCord(Container):
293 """Use this when running the cord tester agent on the onos compute node"""
A R Karthickd44cea12016-07-20 12:16:41 -0700294 onos_config_dir_guest = '/root/onos/config'
A R Karthickd44cea12016-07-20 12:16:41 -0700295
A R Karthick52414732017-01-31 09:59:47 -0800296 def __init__(self, onos_ip, conf, service_profile, synchronizer, start = True, boot_delay = 25):
A.R Karthickf184b342017-01-27 19:30:50 -0800297 if not os.access(conf, os.F_OK):
298 raise Exception('ONOS cord configuration location %s is invalid' %conf)
299 if not os.access(service_profile, os.F_OK):
300 raise Exception('ONOS cord service profile location is not accessible' %service_profile)
A R Karthickbd9b8a32016-07-21 09:56:45 -0700301 self.onos_ip = onos_ip
A.R Karthickf184b342017-01-27 19:30:50 -0800302 self.onos_cord_dir = conf
A R Karthickbd9b8a32016-07-21 09:56:45 -0700303 self.boot_delay = boot_delay
A.R Karthickf184b342017-01-27 19:30:50 -0800304 self.synchronizer = synchronizer
305 self.service_profile = service_profile
306 self.docker_yaml = os.path.join(conf, 'docker-compose.yml')
307 self.docker_yaml_saved = os.path.join(conf, 'docker-compose.yml.saved')
308 self.onos_config_dir = os.path.join(conf, 'config')
309 self.onos_cfg_save_loc = os.path.join(conf, 'network-cfg.json.saved')
310 instance_active = False
311 #if we have a wrapper onos instance already active, back out
312 if os.access(self.onos_config_dir, os.F_OK) or os.access(self.docker_yaml_saved, os.F_OK):
313 instance_active = True
314 else:
315 if start is True:
316 os.mkdir(self.onos_config_dir)
317 shutil.copy(self.docker_yaml, self.docker_yaml_saved)
A R Karthickd44cea12016-07-20 12:16:41 -0700318
A.R Karthickf184b342017-01-27 19:30:50 -0800319 self.start_wrapper = instance_active is False and start is True
A R Karthickd44cea12016-07-20 12:16:41 -0700320 ##update the docker yaml with the config volume
321 with open(self.docker_yaml, 'r') as f:
322 yaml_config = yaml.load(f)
323 image = yaml_config['services'].keys()[0]
A.R Karthickf184b342017-01-27 19:30:50 -0800324 cord_conf_dir_basename = os.path.basename(self.onos_cord_dir.replace('-', ''))
325 xos_onos_name = '{}_{}_1'.format(cord_conf_dir_basename, image)
A R Karthickd44cea12016-07-20 12:16:41 -0700326 volumes = yaml_config['services'][image]['volumes']
327 config_volumes = filter(lambda e: e.find(self.onos_config_dir_guest) >= 0, volumes)
328 if not config_volumes:
329 config_volume = '{}:{}'.format(self.onos_config_dir, self.onos_config_dir_guest)
330 volumes.append(config_volume)
A.R Karthickf184b342017-01-27 19:30:50 -0800331 if self.start_wrapper:
332 docker_yaml_changed = '{}-changed'.format(self.docker_yaml)
333 with open(docker_yaml_changed, 'w') as wf:
334 yaml.dump(yaml_config, wf)
335 os.rename(docker_yaml_changed, self.docker_yaml)
A R Karthickd44cea12016-07-20 12:16:41 -0700336 self.volumes = volumes
337
A R Karthickd44cea12016-07-20 12:16:41 -0700338 ##Create an container instance of xos onos
A R Karthick52414732017-01-31 09:59:47 -0800339 super(OnosCord, self).__init__(xos_onos_name, image, tag = '', quagga_config = Onos.QUAGGA_CONFIG)
A.R Karthickf184b342017-01-27 19:30:50 -0800340 self.last_cfg = None
341 if self.start_wrapper:
342 #fetch the current config of onos cord instance and save it
343 try:
344 self.last_cfg = OnosCtrl.get_config(controller = onos_ip)
345 json_data = json.dumps(self.last_cfg, indent=4)
346 with open(self.onos_cfg_save_loc, 'w') as f:
347 f.write(json_data)
348 except:
349 pass
350 #start the container back with the shared onos config volume
351 self.start()
A R Karthickd44cea12016-07-20 12:16:41 -0700352
353 def start(self, restart = False, network_cfg = None):
A R Karthick928ad622017-01-30 12:18:32 -0800354 if network_cfg is not None:
A R Karthickd44cea12016-07-20 12:16:41 -0700355 json_data = json.dumps(network_cfg, indent=4)
356 with open('{}/network-cfg.json'.format(self.onos_config_dir), 'w') as f:
357 f.write(json_data)
A R Karthick52414732017-01-31 09:59:47 -0800358
359 #we avoid using docker-compose restart for now.
360 #since we don't want to retain the metadata across restarts
361 if True:
A.R Karthickf184b342017-01-27 19:30:50 -0800362 #stop and start and synchronize the services before installing tester cord apps
363 cmds = [ 'cd {} && docker-compose down'.format(self.onos_cord_dir),
364 'cd {} && docker-compose up -d'.format(self.onos_cord_dir),
365 'sleep 45',
366 'cd {} && make {}'.format(self.service_profile, self.synchronizer)
367 ]
368 for cmd in cmds:
369 try:
370 print(cmd)
371 os.system(cmd)
372 except:pass
373 Onos.install_cord_apps(onos_ip = self.onos_ip)
374 else:
375 cmd = 'cd {} && docker-compose restart'.format(self.onos_cord_dir)
376 try:
377 os.system(cmd)
378 except: pass
A R Karthick52414732017-01-31 09:59:47 -0800379
380 ##we could also connect container to default docker network but disabled for now
381 #Container.connect_to_network(self.name, 'bridge')
382
383 #connect container to the quagga bridge
384 self.connect_to_br(index = 0)
A.R Karthickf184b342017-01-27 19:30:50 -0800385 print('Waiting %d seconds for ONOS instance to start' %self.boot_delay)
A R Karthickbd9b8a32016-07-21 09:56:45 -0700386 time.sleep(self.boot_delay)
A R Karthickd44cea12016-07-20 12:16:41 -0700387
388 def build_image(self):
389 build_cmd = 'cd {} && docker-compose build'.format(self.onos_cord_dir)
390 os.system(build_cmd)
391
A.R Karthickf184b342017-01-27 19:30:50 -0800392 def restore(self, force = False):
393 restore = self.start_wrapper is True or force is True
394 if not restore:
A.R Karthick263d3fc2017-01-27 12:52:53 -0800395 return
A.R Karthickf184b342017-01-27 19:30:50 -0800396 #restore the config files back. The synchronizer restore should bring the last config back
397 cmds = ['cd {} && docker-compose down'.format(self.onos_cord_dir),
398 'rm -rf {}'.format(self.onos_config_dir),
399 'mv {} {}'.format(self.docker_yaml_saved, self.docker_yaml),
400 'cd {} && docker-compose up -d'.format(self.onos_cord_dir),
401 'sleep 45',
402 'cd {} && make {}'.format(self.service_profile, self.synchronizer)
403 ]
404 for cmd in cmds:
A.R Karthickb17e2022017-01-27 11:29:26 -0800405 try:
A.R Karthickf184b342017-01-27 19:30:50 -0800406 print(cmd)
407 os.system(cmd)
A.R Karthickb17e2022017-01-27 11:29:26 -0800408 except: pass
409
A.R Karthickf184b342017-01-27 19:30:50 -0800410 #We may not have to restore the config but still it should match synchronizer last config
411 if os.access(self.onos_cfg_save_loc, os.F_OK):
412 with open(self.onos_cfg_save_loc, 'r') as f:
413 cfg = json.load(f)
414 try:
415 OnosCtrl.config(cfg, controller = self.onos_ip)
416 os.unlink(self.onos_cfg_save_loc)
417 except:
418 pass
A.R Karthickb17e2022017-01-27 11:29:26 -0800419
A.R Karthick1700e0e2016-10-06 18:16:57 -0700420class OnosCordStopWrapper(Container):
421 onos_cord_dir = os.path.join(os.getenv('HOME'), 'cord-tester-cord')
422 docker_yaml = os.path.join(onos_cord_dir, 'docker-compose.yml')
423
424 def __init__(self):
425 if os.access(self.docker_yaml, os.F_OK):
426 with open(self.docker_yaml, 'r') as f:
427 yaml_config = yaml.load(f)
428 image = yaml_config['services'].keys()[0]
429 name = 'cordtestercord_{}_1'.format(image)
430 super(OnosCordStopWrapper, self).__init__(name, image, tag = '')
431 if self.exists():
432 print('Killing container %s' %self.name)
433 self.kill()
434
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700435class Onos(Container):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800436 QUAGGA_CONFIG = [ { 'bridge' : 'quagga-br', 'ip': '10.10.0.4', 'mask' : 16 }, ]
A R Karthicka2492c12016-12-16 10:31:51 -0800437 MAX_INSTANCES = 3
A R Karthickc69d73e2017-01-20 11:44:34 -0800438 JVM_HEAP_SIZE = None
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700439 SYSTEM_MEMORY = (get_mem(),) * 2
A R Karthicka2492c12016-12-16 10:31:51 -0800440 INSTANCE_MEMORY = (get_mem(instances=MAX_INSTANCES),) * 2
A R Karthickc69d73e2017-01-20 11:44:34 -0800441 JAVA_OPTS_FORMAT = '-Xms{} -Xmx{} -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode'
442 JAVA_OPTS_DEFAULT = JAVA_OPTS_FORMAT.format(*SYSTEM_MEMORY) #-XX:+PrintGCDetails -XX:+PrintGCTimeStamps'
443 JAVA_OPTS_CLUSTER_DEFAULT = JAVA_OPTS_FORMAT.format(*INSTANCE_MEMORY)
444 env = { 'ONOS_APPS' : 'drivers,openflow,proxyarp,vrouter', 'JAVA_OPTS' : JAVA_OPTS_DEFAULT }
A.R Karthickdfeadb02016-11-30 17:55:51 -0800445 onos_cord_apps = ( ('cord-config', '1.1-SNAPSHOT'),
446 ('aaa', '1.1-SNAPSHOT'),
447 ('igmp', '1.1-SNAPSHOT'),
448 #('vtn', '1.1-SNAPSHOT'),
A.R Karthick95d044e2016-06-10 18:44:36 -0700449 )
A.R Karthickc4e474d2016-12-12 15:24:57 -0800450 ports = [] #[ 8181, 8101, 9876, 6653, 6633, 2000, 2620 ]
A R Karthickf2f4ca62016-08-17 10:34:08 -0700451 setup_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup')
452 host_config_dir = os.path.join(setup_dir, 'onos-config')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700453 guest_config_dir = '/root/onos/config'
A R Karthickec2db322016-11-17 15:06:01 -0800454 guest_data_dir = '/root/onos/apache-karaf-3.0.5/data'
A R Karthickf2f4ca62016-08-17 10:34:08 -0700455 onos_gen_partitions = os.path.join(setup_dir, 'onos-gen-partitions')
A R Karthick2b93d6a2016-09-06 15:19:09 -0700456 onos_form_cluster = os.path.join(setup_dir, 'onos-form-cluster')
A.R Karthick95d044e2016-06-10 18:44:36 -0700457 cord_apps_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'apps')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700458 host_guest_map = ( (host_config_dir, guest_config_dir), )
A R Karthick2b93d6a2016-09-06 15:19:09 -0700459 cluster_cfg = os.path.join(host_config_dir, 'cluster.json')
460 cluster_mode = False
461 cluster_instances = []
Chetan Gaonker503032a2016-05-12 12:06:29 -0700462 NAME = 'cord-onos'
A R Karthickf2f4ca62016-08-17 10:34:08 -0700463 ##the ip of ONOS in default cluster.json in setup/onos-config
464 CLUSTER_CFG_IP = '172.17.0.2'
A R Karthick07608ef2016-08-23 16:51:19 -0700465 IMAGE = 'onosproject/onos'
466 TAG = 'latest'
467 PREFIX = ''
A R Karthickf2f4ca62016-08-17 10:34:08 -0700468
469 @classmethod
A R Karthick2b93d6a2016-09-06 15:19:09 -0700470 def generate_cluster_cfg(cls, ip):
471 if type(ip) in [ list, tuple ]:
472 ips = ' '.join(ip)
473 else:
474 ips = ip
A R Karthickf2f4ca62016-08-17 10:34:08 -0700475 try:
A R Karthick2b93d6a2016-09-06 15:19:09 -0700476 cmd = '{} {} {}'.format(cls.onos_gen_partitions, cls.cluster_cfg, ips)
477 os.system(cmd)
478 except: pass
479
480 @classmethod
481 def form_cluster(cls, ips):
482 nodes = ' '.join(ips)
483 try:
484 cmd = '{} {}'.format(cls.onos_form_cluster, nodes)
A R Karthickf2f4ca62016-08-17 10:34:08 -0700485 os.system(cmd)
486 except: pass
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700487
A R Karthick9d48c652016-09-15 09:16:36 -0700488 @classmethod
489 def cleanup_runtime(cls):
490 '''Cleanup ONOS runtime generated files'''
491 files = ( Onos.cluster_cfg, os.path.join(Onos.host_config_dir, 'network-cfg.json') )
492 for f in files:
493 if os.access(f, os.F_OK):
494 try:
495 os.unlink(f)
496 except: pass
497
A R Karthickec2db322016-11-17 15:06:01 -0800498 @classmethod
499 def get_data_map(cls, host_volume, guest_volume_dir):
500 host_volume_dir = os.path.join(cls.setup_dir, os.path.basename(host_volume))
501 if not os.path.exists(host_volume_dir):
502 os.mkdir(host_volume_dir)
503 return ( (host_volume_dir, guest_volume_dir), )
504
505 @classmethod
506 def remove_data_map(cls, host_volume, guest_volume_dir):
507 host_volume_dir = os.path.join(cls.setup_dir, os.path.basename(host_volume))
508 if os.path.exists(host_volume_dir):
A.R Karthickf184b342017-01-27 19:30:50 -0800509 shutil.rmtree(host_volume_dir)
A R Karthickec2db322016-11-17 15:06:01 -0800510
511 def remove_data_volume(self):
512 if self.data_map is not None:
513 self.remove_data_map(*self.data_map)
514
A.R Karthick1700e0e2016-10-06 18:16:57 -0700515 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX, tag = TAG,
A R Karthickec2db322016-11-17 15:06:01 -0800516 boot_delay = 20, restart = False, network_cfg = None,
A R Karthick85eb1862017-01-23 16:10:57 -0800517 cluster = False, data_volume = None, async = False, quagga_config = None,
518 network = None):
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700519 if restart is True:
520 ##Find the right image to restart
521 running_image = filter(lambda c: c['Names'][0] == '/{}'.format(name), self.dckr.containers())
522 if running_image:
523 image_name = running_image[0]['Image']
524 try:
525 image = image_name.split(':')[0]
526 tag = image_name.split(':')[1]
527 except: pass
528
A R Karthickaa54a1c2016-12-15 11:42:08 -0800529 if quagga_config is None:
530 quagga_config = Onos.QUAGGA_CONFIG
531 super(Onos, self).__init__(name, image, prefix = prefix, tag = tag, quagga_config = quagga_config)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700532 self.boot_delay = boot_delay
A R Karthickec2db322016-11-17 15:06:01 -0800533 self.data_map = None
A R Karthickc69d73e2017-01-20 11:44:34 -0800534 instance_memory = (get_mem(jvm_heap_size = Onos.JVM_HEAP_SIZE, instances = Onos.MAX_INSTANCES),) * 2
535 self.env['JAVA_OPTS'] = self.JAVA_OPTS_FORMAT.format(*instance_memory)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700536 if cluster is True:
537 self.ports = []
A R Karthickec2db322016-11-17 15:06:01 -0800538 if data_volume is not None:
539 self.data_map = self.get_data_map(data_volume, self.guest_data_dir)
540 self.host_guest_map = self.host_guest_map + self.data_map
A R Karthick2b93d6a2016-09-06 15:19:09 -0700541 if os.access(self.cluster_cfg, os.F_OK):
542 try:
543 os.unlink(self.cluster_cfg)
544 except: pass
545
546 self.host_config = self.create_host_config(port_list = self.ports,
547 host_guest_map = self.host_guest_map)
548 self.volumes = []
549 for _,g in self.host_guest_map:
550 self.volumes.append(g)
551
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700552 if restart is True and self.exists():
553 self.kill()
A R Karthick2b93d6a2016-09-06 15:19:09 -0700554
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700555 if not self.exists():
556 self.remove_container(name, force=True)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700557 host_config = self.create_host_config(port_list = self.ports,
558 host_guest_map = self.host_guest_map)
559 volumes = []
560 for _,g in self.host_guest_map:
561 volumes.append(g)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700562 if network_cfg is not None:
A R Karthick81acbff2016-06-17 14:45:16 -0700563 json_data = json.dumps(network_cfg, indent=4)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700564 with open('{}/network-cfg.json'.format(self.host_config_dir), 'w') as f:
565 f.write(json_data)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800566 if cluster is False or async is False:
567 print('Starting ONOS container %s' %self.name)
568 self.start(ports = self.ports, environment = self.env,
569 host_config = self.host_config, volumes = self.volumes, tty = True)
570 if not restart:
571 ##wait a bit before fetching IP to regenerate cluster cfg
572 time.sleep(5)
573 ip = self.ip()
574 ##Just a quick hack/check to ensure we don't regenerate in the common case.
575 ##As ONOS is usually the first test container that is started
576 if cluster is False:
577 if ip != self.CLUSTER_CFG_IP or not os.access(self.cluster_cfg, os.F_OK):
578 print('Regenerating ONOS cluster cfg for ip %s' %ip)
579 self.generate_cluster_cfg(ip)
580 self.kill()
581 self.remove_container(self.name, force=True)
582 print('Restarting ONOS container %s' %self.name)
583 self.start(ports = self.ports, environment = self.env,
584 host_config = self.host_config, volumes = self.volumes, tty = True)
585 print('Waiting for ONOS to boot')
586 time.sleep(boot_delay)
587 self.wait_for_onos_start(self.ip())
588 self.running = True
589 else:
590 self.running = False
591 else:
592 self.running = True
593 if self.running:
594 self.ipaddr = self.ip()
595 if cluster is False:
596 self.install_cord_apps(self.ipaddr)
A R Karthick19aaf5c2016-11-09 17:47:57 -0800597
A.R Karthickc4e474d2016-12-12 15:24:57 -0800598 @classmethod
599 def get_quagga_config(cls, instance = 0):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800600 quagga_config = copy.deepcopy(cls.QUAGGA_CONFIG)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800601 if instance == 0:
602 return quagga_config
603 ip = quagga_config[0]['ip']
604 octets = ip.split('.')
A R Karthickaa54a1c2016-12-15 11:42:08 -0800605 octets[3] = str((int(octets[3]) + instance) & 255)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800606 ip = '.'.join(octets)
607 quagga_config[0]['ip'] = ip
608 return quagga_config
609
610 @classmethod
611 def start_cluster_async(cls, onos_instances):
612 instances = filter(lambda o: o.running == False, onos_instances)
613 if not instances:
614 return
615 tpool = ThreadPool(len(instances), queue_size = 1, wait_timeout = 1)
616 for onos in instances:
617 tpool.addTask(onos.start_async)
618 tpool.cleanUpThreads()
619
620 def start_async(self):
621 print('Starting ONOS container %s' %self.name)
622 self.start(ports = self.ports, environment = self.env,
623 host_config = self.host_config, volumes = self.volumes, tty = True)
624 time.sleep(3)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700625 self.ipaddr = self.ip()
A.R Karthickc4e474d2016-12-12 15:24:57 -0800626 print('Waiting for ONOS container %s to start' %self.name)
627 self.wait_for_onos_start(self.ipaddr)
628 self.running = True
629 print('ONOS container %s started' %self.name)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700630
A R Karthick2b93d6a2016-09-06 15:19:09 -0700631 @classmethod
A R Karthick19aaf5c2016-11-09 17:47:57 -0800632 def wait_for_onos_start(cls, ip, tries = 30):
633 onos_log = OnosLog(host = ip)
634 num_tries = 0
635 started = None
636 while not started and num_tries < tries:
637 time.sleep(3)
638 started = onos_log.search_log_pattern('ApplicationManager .* Started')
639 num_tries += 1
640
A R Karthick19aaf5c2016-11-09 17:47:57 -0800641 if not started:
642 print('ONOS did not start')
643 else:
644 print('ONOS started')
645 return started
646
647 @classmethod
A R Karthick2b93d6a2016-09-06 15:19:09 -0700648 def setup_cluster_deprecated(cls, onos_instances, image_name = None):
649 if not onos_instances or len(onos_instances) < 2:
650 return
651 ips = []
652 if image_name is not None:
653 ips = Container.ips(image_name)
654 else:
655 for onos in onos_instances:
656 ips.append(onos.ipaddr)
657 Onos.cluster_instances = onos_instances
658 Onos.cluster_mode = True
659 ##regenerate the cluster json with the 3 instance ips before restarting them back
660 print('Generating cluster cfg for ONOS instances with ips %s' %ips)
661 Onos.generate_cluster_cfg(ips)
662 for onos in onos_instances:
663 onos.kill()
664 onos.remove_container(onos.name, force=True)
665 print('Restarting ONOS container %s for forming cluster' %onos.name)
666 onos.start(ports = onos.ports, environment = onos.env,
667 host_config = onos.host_config, volumes = onos.volumes, tty = True)
668 print('Waiting %d seconds for ONOS %s to boot' %(onos.boot_delay, onos.name))
669 time.sleep(onos.boot_delay)
670 onos.ipaddr = onos.ip()
671 onos.install_cord_apps(onos.ipaddr)
672
673 @classmethod
674 def setup_cluster(cls, onos_instances, image_name = None):
675 if not onos_instances or len(onos_instances) < 2:
676 return
677 ips = []
678 if image_name is not None:
679 ips = Container.ips(image_name)
680 else:
681 for onos in onos_instances:
682 ips.append(onos.ipaddr)
683 Onos.cluster_instances = onos_instances
684 Onos.cluster_mode = True
685 ##regenerate the cluster json with the 3 instance ips before restarting them back
686 print('Forming cluster for ONOS instances with ips %s' %ips)
687 Onos.form_cluster(ips)
688 ##wait for the cluster to be formed
689 print('Waiting for the cluster to be formed')
690 time.sleep(60)
691 for onos in onos_instances:
692 onos.install_cord_apps(onos.ipaddr)
693
694 @classmethod
A R Karthicke2c24bd2016-10-07 14:51:38 -0700695 def add_cluster(cls, count = 1, network_cfg = None):
696 if not cls.cluster_instances or Onos.cluster_mode is False:
697 return
698 for i in range(count):
699 name = '{}-{}'.format(Onos.NAME, len(cls.cluster_instances)+1)
700 onos = cls(name = name, image = Onos.IMAGE, tag = Onos.TAG, prefix = Container.IMAGE_PREFIX,
701 cluster = True, network_cfg = network_cfg)
702 cls.cluster_instances.append(onos)
703
704 cls.setup_cluster(cls.cluster_instances)
705
706 @classmethod
A.R Karthick2560f042016-11-30 14:38:52 -0800707 def restart_cluster(cls, network_cfg = None, timeout = 10, setup = False):
A R Karthick2b93d6a2016-09-06 15:19:09 -0700708 if cls.cluster_mode is False:
709 return
710 if not cls.cluster_instances:
711 return
712
713 if network_cfg is not None:
714 json_data = json.dumps(network_cfg, indent=4)
715 with open('{}/network-cfg.json'.format(cls.host_config_dir), 'w') as f:
716 f.write(json_data)
717
A.R Karthick2560f042016-11-30 14:38:52 -0800718 cls.cleanup_cluster()
719 if timeout > 0:
720 time.sleep(timeout)
721
A R Karthickaa54a1c2016-12-15 11:42:08 -0800722 #start the instances asynchronously
723 cls.start_cluster_async(cls.cluster_instances)
724 time.sleep(5)
A.R Karthick2560f042016-11-30 14:38:52 -0800725 ##form the cluster as appropriate
726 if setup is True:
727 cls.setup_cluster(cls.cluster_instances)
A R Karthickaa54a1c2016-12-15 11:42:08 -0800728 else:
729 for onos in cls.cluster_instances:
730 onos.install_cord_apps(onos.ipaddr)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700731
732 @classmethod
733 def cluster_ips(cls):
734 if cls.cluster_mode is False:
735 return []
736 if not cls.cluster_instances:
737 return []
738 ips = [ onos.ipaddr for onos in cls.cluster_instances ]
739 return ips
740
741 @classmethod
742 def cleanup_cluster(cls):
743 if cls.cluster_mode is False:
744 return
745 if not cls.cluster_instances:
746 return
747 for onos in cls.cluster_instances:
748 if onos.exists():
749 onos.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800750 onos.running = False
A R Karthick2b93d6a2016-09-06 15:19:09 -0700751 onos.remove_container(onos.name, force=True)
A R Karthickd44cea12016-07-20 12:16:41 -0700752
A.R Karthick95d044e2016-06-10 18:44:36 -0700753 @classmethod
A R Karthickde6b9dc2016-11-29 17:46:16 -0800754 def restart_node(cls, node = None, network_cfg = None, timeout = 10):
A R Karthick889d9652016-10-03 14:13:45 -0700755 if node is None:
756 cls(restart = True, network_cfg = network_cfg, image = cls.IMAGE, tag = cls.TAG)
757 else:
758 #Restarts a node in the cluster
759 valid_node = filter(lambda onos: node in [ onos.ipaddr, onos.name ], cls.cluster_instances)
760 if valid_node:
761 onos = valid_node.pop()
762 if onos.exists():
763 onos.kill()
764 onos.remove_container(onos.name, force=True)
A R Karthickde6b9dc2016-11-29 17:46:16 -0800765 if timeout > 0:
766 time.sleep(timeout)
A R Karthick889d9652016-10-03 14:13:45 -0700767 print('Restarting ONOS container %s' %onos.name)
768 onos.start(ports = onos.ports, environment = onos.env,
769 host_config = onos.host_config, volumes = onos.volumes, tty = True)
A R Karthick889d9652016-10-03 14:13:45 -0700770 onos.ipaddr = onos.ip()
A.R Karthick2560f042016-11-30 14:38:52 -0800771 onos.wait_for_onos_start(onos.ipaddr)
772 onos.install_cord_apps(onos.ipaddr)
A R Karthick889d9652016-10-03 14:13:45 -0700773
774 @classmethod
A R Karthickeaf1c4e2016-07-19 12:22:35 -0700775 def install_cord_apps(cls, onos_ip = None):
A.R Karthick95d044e2016-06-10 18:44:36 -0700776 for app, version in cls.onos_cord_apps:
777 app_file = '{}/{}-{}.oar'.format(cls.cord_apps_dir, app, version)
A R Karthickeaf1c4e2016-07-19 12:22:35 -0700778 ok, code = OnosCtrl.install_app(app_file, onos_ip = onos_ip)
A.R Karthick95d044e2016-06-10 18:44:36 -0700779 ##app already installed (conflicts)
780 if code in [ 409 ]:
781 ok = True
782 print('ONOS app %s, version %s %s' %(app, version, 'installed' if ok else 'failed to install'))
783 time.sleep(2)
784
A.R Karthick1700e0e2016-10-06 18:16:57 -0700785class OnosStopWrapper(Container):
786 def __init__(self, name):
787 super(OnosStopWrapper, self).__init__(name, Onos.IMAGE, tag = Onos.TAG, prefix = Container.IMAGE_PREFIX)
788 if self.exists():
789 self.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800790 self.running = False
A.R Karthick1700e0e2016-10-06 18:16:57 -0700791 else:
792 if Onos.cluster_mode is True:
793 valid_node = filter(lambda onos: name in [ onos.ipaddr, onos.name ], Onos.cluster_instances)
794 if valid_node:
795 onos = valid_node.pop()
796 if onos.exists():
797 onos.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800798 onos.running = False
A.R Karthick1700e0e2016-10-06 18:16:57 -0700799
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700800class Radius(Container):
801 ports = [ 1812, 1813 ]
A R Karthick41adfce2016-06-10 09:51:25 -0700802 env = {'TIMEZONE':'America/Los_Angeles',
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700803 'DEBUG': 'true', 'cert_password':'whatever', 'primary_shared_secret':'radius_password'
804 }
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700805 host_db_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/db')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700806 guest_db_dir = os.path.join(os.path.sep, 'opt', 'db')
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700807 host_config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/freeradius')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700808 guest_config_dir = os.path.join(os.path.sep, 'etc', 'freeradius')
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700809 start_command = os.path.join(guest_config_dir, 'start-radius.py')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700810 host_guest_map = ( (host_db_dir, guest_db_dir),
811 (host_config_dir, guest_config_dir)
812 )
Chetan Gaonker503032a2016-05-12 12:06:29 -0700813 IMAGE = 'cord-test/radius'
814 NAME = 'cord-radius'
815
A R Karthick07608ef2016-08-23 16:51:19 -0700816 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = 'candidate',
A R Karthick85eb1862017-01-23 16:10:57 -0800817 boot_delay = 10, restart = False, update = False, network = None):
A R Karthick07608ef2016-08-23 16:51:19 -0700818 super(Radius, self).__init__(name, image, prefix = prefix, tag = tag, command = self.start_command)
Chetan Gaonker503032a2016-05-12 12:06:29 -0700819 if update is True or not self.img_exists():
A R Karthick07608ef2016-08-23 16:51:19 -0700820 self.build_image(self.image_name)
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700821 if restart is True and self.exists():
822 self.kill()
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700823 if not self.exists():
824 self.remove_container(name, force=True)
825 host_config = self.create_host_config(port_list = self.ports,
826 host_guest_map = self.host_guest_map)
827 volumes = []
828 for _,g in self.host_guest_map:
829 volumes.append(g)
A R Karthick41adfce2016-06-10 09:51:25 -0700830 self.start(ports = self.ports, environment = self.env,
831 volumes = volumes,
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700832 host_config = host_config, tty = True)
A R Karthick85eb1862017-01-23 16:10:57 -0800833 if network is not None:
834 Container.connect_to_network(self.name, network)
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700835 time.sleep(boot_delay)
836
837 @classmethod
838 def build_image(cls, image):
839 print('Building Radius image %s' %image)
840 dockerfile = '''
841FROM hbouvier/docker-radius
842MAINTAINER chetan@ciena.com
843LABEL RUN docker pull hbouvier/docker-radius
844LABEL RUN docker run -it --name cord-radius hbouvier/docker-radius
A R Karthickc762df42016-05-25 10:09:21 -0700845RUN apt-get update && \
846 apt-get -y install python python-pexpect strace
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700847WORKDIR /root
848CMD ["/etc/freeradius/start-radius.py"]
849'''
850 super(Radius, cls).build_image(dockerfile, image)
851 print('Done building image %s' %image)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700852
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700853class Quagga(Container):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800854 QUAGGA_CONFIG = ( { 'bridge' : 'quagga-br', 'ip': '10.10.0.3', 'mask' : 16 },
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700855 { 'bridge' : 'quagga-br', 'ip': '192.168.10.3', 'mask': 16 },
856 )
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700857 ports = [ 179, 2601, 2602, 2603, 2604, 2605, 2606 ]
858 host_quagga_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/quagga-config')
859 guest_quagga_config = '/root/config'
860 quagga_config_file = os.path.join(guest_quagga_config, 'testrib.conf')
861 host_guest_map = ( (host_quagga_config, guest_quagga_config), )
Chetan Gaonker503032a2016-05-12 12:06:29 -0700862 IMAGE = 'cord-test/quagga'
863 NAME = 'cord-quagga'
864
A R Karthick07608ef2016-08-23 16:51:19 -0700865 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = 'candidate',
A R Karthick85eb1862017-01-23 16:10:57 -0800866 boot_delay = 15, restart = False, config_file = quagga_config_file, update = False,
867 network = None):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800868 super(Quagga, self).__init__(name, image, prefix = prefix, tag = tag, quagga_config = self.QUAGGA_CONFIG)
Chetan Gaonker503032a2016-05-12 12:06:29 -0700869 if update is True or not self.img_exists():
A R Karthick07608ef2016-08-23 16:51:19 -0700870 self.build_image(self.image_name)
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700871 if restart is True and self.exists():
872 self.kill()
873 if not self.exists():
874 self.remove_container(name, force=True)
A R Karthick41adfce2016-06-10 09:51:25 -0700875 host_config = self.create_host_config(port_list = self.ports,
876 host_guest_map = self.host_guest_map,
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700877 privileged = True)
878 volumes = []
879 for _,g in self.host_guest_map:
880 volumes.append(g)
881 self.start(ports = self.ports,
A R Karthick41adfce2016-06-10 09:51:25 -0700882 host_config = host_config,
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700883 volumes = volumes, tty = True)
A R Karthick85eb1862017-01-23 16:10:57 -0800884 if network is not None:
885 Container.connect_to_network(self.name, network)
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700886 print('Starting Quagga on container %s' %self.name)
887 self.execute('{0}/start.sh {1}'.format(self.guest_quagga_config, config_file))
888 time.sleep(boot_delay)
889
890 @classmethod
891 def build_image(cls, image):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800892 onos_quagga_ip = Onos.QUAGGA_CONFIG[0]['ip']
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700893 print('Building Quagga image %s' %image)
894 dockerfile = '''
A R Karthick41adfce2016-06-10 09:51:25 -0700895FROM ubuntu:14.04
896MAINTAINER chetan@ciena.com
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700897WORKDIR /root
898RUN useradd -M quagga
899RUN mkdir /var/log/quagga && chown quagga:quagga /var/log/quagga
900RUN mkdir /var/run/quagga && chown quagga:quagga /var/run/quagga
A R Karthick973ea692016-10-17 12:23:02 -0700901RUN 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 -0700902RUN git clone git://git.savannah.nongnu.org/quagga.git quagga && \
A R Karthick8f69c2c2016-10-21 11:43:26 -0700903(cd quagga && git checkout quagga-1.0.20160315 && ./bootstrap.sh && \
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700904sed -i -r 's,htonl.*?\(INADDR_LOOPBACK\),inet_addr\("{0}"\),g' zebra/zebra_fpm.c && \
905./configure --enable-fpm --disable-doc --localstatedir=/var/run/quagga && make && make install)
906RUN ldconfig
907'''.format(onos_quagga_ip)
908 super(Quagga, cls).build_image(dockerfile, image)
909 print('Done building image %s' %image)
A R Karthick81acbff2016-06-17 14:45:16 -0700910
A.R Karthick1700e0e2016-10-06 18:16:57 -0700911class QuaggaStopWrapper(Container):
912 def __init__(self, name = Quagga.NAME, image = Quagga.IMAGE, tag = 'candidate'):
913 super(QuaggaStopWrapper, self).__init__(name, image, prefix = Container.IMAGE_PREFIX, tag = tag)
914 if self.exists():
915 self.kill()
916
917
A R Karthick81acbff2016-06-17 14:45:16 -0700918def reinitContainerClients():
919 docker_netns.dckr = Client()
920 Container.dckr = Client()
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700921
922class Xos(Container):
923 setup_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup')
924 TAG = 'latest'
925 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -0700926 host_guest_map = None
927 env = None
928 ports = None
929 volumes = None
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700930
A R Karthick6e80afd2016-10-10 16:03:12 -0700931 @classmethod
932 def get_cmd(cls, img_name):
933 cmd = cls.dckr.inspect_image(img_name)['Config']['Cmd']
934 return ' '.join(cmd)
935
A R Karthicke3bde962016-09-27 15:06:35 -0700936 def __init__(self, name, image, prefix = PREFIX, tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -0700937 boot_delay = 20, restart = False, network_cfg = None, update = False):
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700938 if restart is True:
939 ##Find the right image to restart
940 running_image = filter(lambda c: c['Names'][0] == '/{}'.format(name), self.dckr.containers())
941 if running_image:
942 image_name = running_image[0]['Image']
943 try:
944 image = image_name.split(':')[0]
945 tag = image_name.split(':')[1]
946 except: pass
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700947 super(Xos, self).__init__(name, image, prefix = prefix, tag = tag)
948 if update is True or not self.img_exists():
949 self.build_image(self.image_name)
A R Karthick6e80afd2016-10-10 16:03:12 -0700950 self.command = self.get_cmd(self.image_name).strip() or None
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700951 if restart is True and self.exists():
952 self.kill()
953 if not self.exists():
954 self.remove_container(name, force=True)
A R Karthicke3bde962016-09-27 15:06:35 -0700955 host_config = self.create_host_config(port_list = self.ports,
956 host_guest_map = self.host_guest_map,
957 privileged = True)
958 print('Starting XOS container %s' %self.name)
959 self.start(ports = self.ports, environment = self.env, host_config = host_config,
960 volumes = self.volumes, tty = True)
961 print('Waiting %d seconds for XOS Base Container to boot' %(boot_delay))
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700962 time.sleep(boot_delay)
963
964 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -0700965 def build_image(cls, image, dockerfile_path, image_target = 'build'):
966 cmd = 'cd {} && make {}'.format(dockerfile_path, image_target)
967 print('Building XOS %s' %image)
968 res = os.system(cmd)
969 print('Done building image %s. Image build %s' %(image, 'successful' if res == 0 else 'failed'))
970 return res
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700971
A R Karthicke3bde962016-09-27 15:06:35 -0700972class XosServer(Xos):
973 ports = [8000,9998,9999]
974 NAME = 'xos-server'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700975 IMAGE = 'xosproject/xos'
A R Karthicke3bde962016-09-27 15:06:35 -0700976 BASE_IMAGE = 'xosproject/xos-base'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700977 TAG = 'latest'
978 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -0700979 dockerfile_path = os.path.join(Xos.setup_dir, 'xos')
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700980
A R Karthicke3bde962016-09-27 15:06:35 -0700981 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX, tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -0700982 boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -0700983 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700984
985 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -0700986 def build_image(cls, image = IMAGE):
987 ##build the base image and then build the server image
988 Xos.build_image(cls.BASE_IMAGE, cls.dockerfile_path, image_target = 'base')
989 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700990
A R Karthicke3bde962016-09-27 15:06:35 -0700991class XosSynchronizerOpenstack(Xos):
992 ports = [2375,]
993 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer')
994 NAME = 'xos-synchronizer'
995 IMAGE = 'xosproject/xos-synchronizer-openstack'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700996 TAG = 'latest'
997 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -0700998 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700999
A R Karthicke3bde962016-09-27 15:06:35 -07001000 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -07001001 tag = TAG, boot_delay = 20, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001002 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001003
1004 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -07001005 def build_image(cls, image = IMAGE):
1006 XosServer.build_image()
1007 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001008
A R Karthicke3bde962016-09-27 15:06:35 -07001009class XosSynchronizerOnboarding(Xos):
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001010 NAME = 'xos-synchronizer-onboarding'
1011 IMAGE = 'xosproject/xos-synchronizer-onboarding'
1012 TAG = 'latest'
1013 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -07001014 dockerfile_path = os.path.join(Xos.setup_dir, 'onboarding_synchronizer')
1015 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001016
A R Karthicke3bde962016-09-27 15:06:35 -07001017 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -07001018 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001019 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001020
1021 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -07001022 def build_image(cls, image = IMAGE):
1023 XosSynchronizerOpenstack.build_image()
1024 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001025
A R Karthicke3bde962016-09-27 15:06:35 -07001026class XosSynchronizerOpenvpn(Xos):
1027 NAME = 'xos-synchronizer-openvpn'
1028 IMAGE = 'xosproject/xos-openvpn'
1029 TAG = 'latest'
1030 PREFIX = ''
1031 dockerfile_path = os.path.join(Xos.setup_dir, 'openvpn')
1032 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001033
A R Karthicke3bde962016-09-27 15:06:35 -07001034 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -07001035 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -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 XosSynchronizerOpenstack.build_image()
1041 Xos.build_image(image, cls.dockerfile_path)
1042
1043class XosPostgresql(Xos):
1044 ports = [5432,]
1045 NAME = 'xos-db-postgres'
1046 IMAGE = 'xosproject/xos-postgres'
1047 TAG = 'latest'
1048 PREFIX = ''
1049 volumes = ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
1050 dockerfile_path = os.path.join(Xos.setup_dir, 'postgresql')
1051
1052 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -07001053 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001054 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1055
1056 @classmethod
1057 def build_image(cls, image = IMAGE):
1058 Xos.build_image(image, cls.dockerfile_path)
1059
1060class XosSyndicateMs(Xos):
1061 ports = [8080,]
1062 env = None
1063 NAME = 'xos-syndicate-ms'
1064 IMAGE = 'xosproject/syndicate-ms'
1065 TAG = 'latest'
1066 PREFIX = ''
1067 dockerfile_path = os.path.join(Xos.setup_dir, 'syndicate-ms')
1068
1069 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001070 boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001071 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1072
1073 @classmethod
1074 def build_image(cls, image = IMAGE):
1075 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001076
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001077class XosSyncVtn(Xos):
1078 ports = [8080,]
1079 env = None
1080 NAME = 'xos-synchronizer-vtn'
1081 IMAGE = 'xosproject/xos-synchronizer-vtn'
1082 TAG = 'latest'
1083 PREFIX = ''
1084 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vtn')
1085
1086 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001087 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001088 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1089
1090 @classmethod
1091 def build_image(cls, image = IMAGE):
1092 Xos.build_image(image, cls.dockerfile_path)
1093
1094class XosSyncVtr(Xos):
1095 ports = [8080,]
1096 env = None
1097 NAME = 'xos-synchronizer-vtr'
1098 IMAGE = 'xosproject/xos-synchronizer-vtr'
1099 TAG = 'latest'
1100 PREFIX = ''
1101 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vtr')
1102
1103 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001104 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001105 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1106
1107 @classmethod
1108 def build_image(cls, image = IMAGE):
1109 Xos.build_image(image, cls.dockerfile_path)
1110
1111class XosSyncVsg(Xos):
1112 ports = [8080,]
1113 env = None
1114 NAME = 'xos-synchronizer-vsg'
1115 IMAGE = 'xosproject/xos-synchronizer-vsg'
1116 TAG = 'latest'
1117 PREFIX = ''
1118 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vsg')
1119
1120 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001121 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001122 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1123
1124 @classmethod
1125 def build_image(cls, image = IMAGE):
1126 Xos.build_image(image, cls.dockerfile_path)
1127
1128
1129class XosSyncOnos(Xos):
1130 ports = [8080,]
1131 env = None
1132 NAME = 'xos-synchronizer-onos'
1133 IMAGE = 'xosproject/xos-synchronizer-onos'
1134 TAG = 'latest'
1135 PREFIX = ''
1136 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-onos')
1137
1138 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001139 boot_delay = 30, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001140 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1141
1142 @classmethod
1143 def build_image(cls, image = IMAGE):
1144 Xos.build_image(image, cls.dockerfile_path)
1145
1146class XosSyncFabric(Xos):
1147 ports = [8080,]
1148 env = None
1149 NAME = 'xos-synchronizer-fabric'
1150 IMAGE = 'xosproject/xos-synchronizer-fabric'
1151 TAG = 'latest'
1152 PREFIX = ''
1153 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-fabric')
1154
1155 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001156 boot_delay = 30, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001157 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1158
1159 @classmethod
1160 def build_image(cls, image = IMAGE):
1161 Xos.build_image(image, cls.dockerfile_path)
A R Karthick19aaf5c2016-11-09 17:47:57 -08001162
1163if __name__ == '__main__':
1164 onos = Onos(boot_delay = 10, restart = True)