blob: b8a4ec06f7a5884c529476a6f75d90c6d92985c2 [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)
A R Karthickd6dd9b22017-02-24 15:17:22 -0800247 s = self.dckr.exec_start(i['Id'], stream = stream, detach=detach, socket=True)
248 try:
249 s.close()
250 except: pass
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700251 result = self.dckr.exec_inspect(i['Id'])
252 res += 0 if result['ExitCode'] == None else result['ExitCode']
253 return res
254
ChetanGaonker6138fcd2016-08-18 17:56:39 -0700255 def restart(self, timeout =10):
256 return self.dckr.restart(self.name, timeout)
257
A R Karthickc69d73e2017-01-20 11:44:34 -0800258def get_mem(jvm_heap_size = None, instances = 1):
A R Karthick1f908202016-11-16 17:32:20 -0800259 if instances <= 0:
260 instances = 1
A R Karthickc69d73e2017-01-20 11:44:34 -0800261 heap_size = jvm_heap_size
262 heap_size_i = 0
263 #sanitize the heap size config
264 if heap_size is not None:
265 if not heap_size.isdigit():
266 try:
267 heap_size_i = int(heap_size[:-1])
268 suffix = heap_size[-1]
269 if suffix == 'M':
270 heap_size_i /= 1024 #convert to gigs
A.R Karthick99044822017-02-09 14:04:20 -0800271 #allow to specific minimum heap size
272 if heap_size_i == 0:
273 return heap_size
A R Karthickc69d73e2017-01-20 11:44:34 -0800274 except:
275 ##invalid suffix length probably. Fall back to default
276 heap_size = None
277 else:
278 heap_size_i = int(heap_size)
279
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700280 with open('/proc/meminfo', 'r') as fd:
281 meminfo = fd.readlines()
282 mem = 0
283 for m in meminfo:
284 if m.startswith('MemTotal:') or m.startswith('SwapTotal:'):
285 mem += int(m.split(':')[1].strip().split()[0])
286
A R Karthick1f908202016-11-16 17:32:20 -0800287 mem = max(mem/1024/1024/2/instances, 1)
Chetan Gaonker6d0a7b02016-05-03 16:57:28 -0700288 mem = min(mem, 16)
A R Karthickc69d73e2017-01-20 11:44:34 -0800289
290 if heap_size_i:
291 #we take the minimum of the provided heap size and max allowed heap size
292 heap_size_i = min(heap_size_i, mem)
293 else:
294 heap_size_i = mem
295
296 return '{}G'.format(heap_size_i)
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700297
A R Karthickd44cea12016-07-20 12:16:41 -0700298class OnosCord(Container):
299 """Use this when running the cord tester agent on the onos compute node"""
A R Karthickd44cea12016-07-20 12:16:41 -0700300 onos_config_dir_guest = '/root/onos/config'
A R Karthickf6ef89b2017-02-01 11:32:19 -0800301 tester_apps = ( 'org.onosproject.proxyarp', 'org.onosproject.hostprovider' )
A R Karthickd44cea12016-07-20 12:16:41 -0700302
A R Karthick52414732017-01-31 09:59:47 -0800303 def __init__(self, onos_ip, conf, service_profile, synchronizer, start = True, boot_delay = 25):
A.R Karthickf184b342017-01-27 19:30:50 -0800304 if not os.access(conf, os.F_OK):
305 raise Exception('ONOS cord configuration location %s is invalid' %conf)
306 if not os.access(service_profile, os.F_OK):
307 raise Exception('ONOS cord service profile location is not accessible' %service_profile)
A R Karthickbd9b8a32016-07-21 09:56:45 -0700308 self.onos_ip = onos_ip
A.R Karthickf184b342017-01-27 19:30:50 -0800309 self.onos_cord_dir = conf
A R Karthickbd9b8a32016-07-21 09:56:45 -0700310 self.boot_delay = boot_delay
A.R Karthickf184b342017-01-27 19:30:50 -0800311 self.synchronizer = synchronizer
312 self.service_profile = service_profile
313 self.docker_yaml = os.path.join(conf, 'docker-compose.yml')
314 self.docker_yaml_saved = os.path.join(conf, 'docker-compose.yml.saved')
315 self.onos_config_dir = os.path.join(conf, 'config')
316 self.onos_cfg_save_loc = os.path.join(conf, 'network-cfg.json.saved')
317 instance_active = False
318 #if we have a wrapper onos instance already active, back out
319 if os.access(self.onos_config_dir, os.F_OK) or os.access(self.docker_yaml_saved, os.F_OK):
320 instance_active = True
321 else:
322 if start is True:
323 os.mkdir(self.onos_config_dir)
324 shutil.copy(self.docker_yaml, self.docker_yaml_saved)
A R Karthickd44cea12016-07-20 12:16:41 -0700325
A.R Karthickf184b342017-01-27 19:30:50 -0800326 self.start_wrapper = instance_active is False and start is True
A R Karthickd44cea12016-07-20 12:16:41 -0700327 ##update the docker yaml with the config volume
328 with open(self.docker_yaml, 'r') as f:
329 yaml_config = yaml.load(f)
330 image = yaml_config['services'].keys()[0]
A.R Karthickf184b342017-01-27 19:30:50 -0800331 cord_conf_dir_basename = os.path.basename(self.onos_cord_dir.replace('-', ''))
332 xos_onos_name = '{}_{}_1'.format(cord_conf_dir_basename, image)
A R Karthick5778a792017-01-31 13:47:16 -0800333 if not yaml_config['services'][image].has_key('volumes'):
334 yaml_config['services'][image]['volumes'] = []
A R Karthickd44cea12016-07-20 12:16:41 -0700335 volumes = yaml_config['services'][image]['volumes']
336 config_volumes = filter(lambda e: e.find(self.onos_config_dir_guest) >= 0, volumes)
337 if not config_volumes:
338 config_volume = '{}:{}'.format(self.onos_config_dir, self.onos_config_dir_guest)
339 volumes.append(config_volume)
A.R Karthickf184b342017-01-27 19:30:50 -0800340 if self.start_wrapper:
341 docker_yaml_changed = '{}-changed'.format(self.docker_yaml)
342 with open(docker_yaml_changed, 'w') as wf:
343 yaml.dump(yaml_config, wf)
344 os.rename(docker_yaml_changed, self.docker_yaml)
A R Karthickd44cea12016-07-20 12:16:41 -0700345 self.volumes = volumes
346
A R Karthickd44cea12016-07-20 12:16:41 -0700347 ##Create an container instance of xos onos
A R Karthick52414732017-01-31 09:59:47 -0800348 super(OnosCord, self).__init__(xos_onos_name, image, tag = '', quagga_config = Onos.QUAGGA_CONFIG)
A.R Karthickf184b342017-01-27 19:30:50 -0800349 self.last_cfg = None
350 if self.start_wrapper:
351 #fetch the current config of onos cord instance and save it
352 try:
353 self.last_cfg = OnosCtrl.get_config(controller = onos_ip)
354 json_data = json.dumps(self.last_cfg, indent=4)
355 with open(self.onos_cfg_save_loc, 'w') as f:
356 f.write(json_data)
357 except:
358 pass
359 #start the container back with the shared onos config volume
360 self.start()
A R Karthickd44cea12016-07-20 12:16:41 -0700361
362 def start(self, restart = False, network_cfg = None):
A R Karthick928ad622017-01-30 12:18:32 -0800363 if network_cfg is not None:
A R Karthickd44cea12016-07-20 12:16:41 -0700364 json_data = json.dumps(network_cfg, indent=4)
365 with open('{}/network-cfg.json'.format(self.onos_config_dir), 'w') as f:
366 f.write(json_data)
A R Karthick52414732017-01-31 09:59:47 -0800367
368 #we avoid using docker-compose restart for now.
369 #since we don't want to retain the metadata across restarts
370 if True:
A.R Karthickf184b342017-01-27 19:30:50 -0800371 #stop and start and synchronize the services before installing tester cord apps
372 cmds = [ 'cd {} && docker-compose down'.format(self.onos_cord_dir),
373 'cd {} && docker-compose up -d'.format(self.onos_cord_dir),
374 'sleep 45',
375 'cd {} && make {}'.format(self.service_profile, self.synchronizer)
376 ]
377 for cmd in cmds:
378 try:
379 print(cmd)
380 os.system(cmd)
381 except:pass
382 Onos.install_cord_apps(onos_ip = self.onos_ip)
A R Karthickf6ef89b2017-02-01 11:32:19 -0800383 self.activate_apps()
A.R Karthickf184b342017-01-27 19:30:50 -0800384 else:
385 cmd = 'cd {} && docker-compose restart'.format(self.onos_cord_dir)
386 try:
387 os.system(cmd)
388 except: pass
A R Karthick52414732017-01-31 09:59:47 -0800389
390 ##we could also connect container to default docker network but disabled for now
391 #Container.connect_to_network(self.name, 'bridge')
392
393 #connect container to the quagga bridge
394 self.connect_to_br(index = 0)
A.R Karthickf184b342017-01-27 19:30:50 -0800395 print('Waiting %d seconds for ONOS instance to start' %self.boot_delay)
A R Karthickbd9b8a32016-07-21 09:56:45 -0700396 time.sleep(self.boot_delay)
A R Karthickd44cea12016-07-20 12:16:41 -0700397
A R Karthickdb5a5fc2017-02-01 16:40:43 -0800398 def activate_apps(self):
399 for app in self.tester_apps:
A R Karthickf6ef89b2017-02-01 11:32:19 -0800400 print('Activating ONOS app %s' %(app))
A R Karthickdb5a5fc2017-02-01 16:40:43 -0800401 OnosCtrl(app, controller = self.onos_ip).activate()
A R Karthickf6ef89b2017-02-01 11:32:19 -0800402 time.sleep(2)
403
A R Karthickd44cea12016-07-20 12:16:41 -0700404 def build_image(self):
405 build_cmd = 'cd {} && docker-compose build'.format(self.onos_cord_dir)
406 os.system(build_cmd)
407
A.R Karthickf184b342017-01-27 19:30:50 -0800408 def restore(self, force = False):
409 restore = self.start_wrapper is True or force is True
410 if not restore:
A.R Karthick263d3fc2017-01-27 12:52:53 -0800411 return
A R Karthick394976f2017-01-31 14:25:16 -0800412 #nothing to restore
413 if not os.access(self.docker_yaml_saved, os.F_OK):
414 return
A.R Karthickf184b342017-01-27 19:30:50 -0800415 #restore the config files back. The synchronizer restore should bring the last config back
416 cmds = ['cd {} && docker-compose down'.format(self.onos_cord_dir),
417 'rm -rf {}'.format(self.onos_config_dir),
418 'mv {} {}'.format(self.docker_yaml_saved, self.docker_yaml),
419 'cd {} && docker-compose up -d'.format(self.onos_cord_dir),
420 'sleep 45',
421 'cd {} && make {}'.format(self.service_profile, self.synchronizer)
422 ]
423 for cmd in cmds:
A.R Karthickb17e2022017-01-27 11:29:26 -0800424 try:
A.R Karthickf184b342017-01-27 19:30:50 -0800425 print(cmd)
426 os.system(cmd)
A.R Karthickb17e2022017-01-27 11:29:26 -0800427 except: pass
428
A.R Karthickf184b342017-01-27 19:30:50 -0800429 #We may not have to restore the config but still it should match synchronizer last config
430 if os.access(self.onos_cfg_save_loc, os.F_OK):
431 with open(self.onos_cfg_save_loc, 'r') as f:
432 cfg = json.load(f)
433 try:
434 OnosCtrl.config(cfg, controller = self.onos_ip)
435 os.unlink(self.onos_cfg_save_loc)
436 except:
437 pass
A.R Karthickb17e2022017-01-27 11:29:26 -0800438
A.R Karthick1700e0e2016-10-06 18:16:57 -0700439class OnosCordStopWrapper(Container):
440 onos_cord_dir = os.path.join(os.getenv('HOME'), 'cord-tester-cord')
441 docker_yaml = os.path.join(onos_cord_dir, 'docker-compose.yml')
442
443 def __init__(self):
444 if os.access(self.docker_yaml, os.F_OK):
445 with open(self.docker_yaml, 'r') as f:
446 yaml_config = yaml.load(f)
447 image = yaml_config['services'].keys()[0]
448 name = 'cordtestercord_{}_1'.format(image)
449 super(OnosCordStopWrapper, self).__init__(name, image, tag = '')
450 if self.exists():
451 print('Killing container %s' %self.name)
452 self.kill()
453
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700454class Onos(Container):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800455 QUAGGA_CONFIG = [ { 'bridge' : 'quagga-br', 'ip': '10.10.0.4', 'mask' : 16 }, ]
A R Karthicka2492c12016-12-16 10:31:51 -0800456 MAX_INSTANCES = 3
A R Karthickc69d73e2017-01-20 11:44:34 -0800457 JVM_HEAP_SIZE = None
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700458 SYSTEM_MEMORY = (get_mem(),) * 2
A R Karthicka2492c12016-12-16 10:31:51 -0800459 INSTANCE_MEMORY = (get_mem(instances=MAX_INSTANCES),) * 2
A R Karthickc69d73e2017-01-20 11:44:34 -0800460 JAVA_OPTS_FORMAT = '-Xms{} -Xmx{} -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode'
461 JAVA_OPTS_DEFAULT = JAVA_OPTS_FORMAT.format(*SYSTEM_MEMORY) #-XX:+PrintGCDetails -XX:+PrintGCTimeStamps'
462 JAVA_OPTS_CLUSTER_DEFAULT = JAVA_OPTS_FORMAT.format(*INSTANCE_MEMORY)
463 env = { 'ONOS_APPS' : 'drivers,openflow,proxyarp,vrouter', 'JAVA_OPTS' : JAVA_OPTS_DEFAULT }
A.R Karthickdfeadb02016-11-30 17:55:51 -0800464 onos_cord_apps = ( ('cord-config', '1.1-SNAPSHOT'),
465 ('aaa', '1.1-SNAPSHOT'),
466 ('igmp', '1.1-SNAPSHOT'),
467 #('vtn', '1.1-SNAPSHOT'),
A.R Karthick95d044e2016-06-10 18:44:36 -0700468 )
A.R Karthickdda22062017-02-09 14:39:20 -0800469 ports = [] #[ 8181, 8101, 9876, 6653, 6633, 2000, 2620, 5005 ]
A R Karthickf2f4ca62016-08-17 10:34:08 -0700470 setup_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup')
471 host_config_dir = os.path.join(setup_dir, 'onos-config')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700472 guest_config_dir = '/root/onos/config'
A.R Karthickdda22062017-02-09 14:39:20 -0800473 guest_data_dir = '/root/onos/apache-karaf-3.0.8/data'
474 guest_log_file = '/root/onos/apache-karaf-3.0.8/data/log/karaf.log'
A R Karthickf2f4ca62016-08-17 10:34:08 -0700475 onos_gen_partitions = os.path.join(setup_dir, 'onos-gen-partitions')
A R Karthick2b93d6a2016-09-06 15:19:09 -0700476 onos_form_cluster = os.path.join(setup_dir, 'onos-form-cluster')
A.R Karthick95d044e2016-06-10 18:44:36 -0700477 cord_apps_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'apps')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700478 host_guest_map = ( (host_config_dir, guest_config_dir), )
A R Karthick2b93d6a2016-09-06 15:19:09 -0700479 cluster_cfg = os.path.join(host_config_dir, 'cluster.json')
480 cluster_mode = False
481 cluster_instances = []
Chetan Gaonker503032a2016-05-12 12:06:29 -0700482 NAME = 'cord-onos'
A R Karthickf2f4ca62016-08-17 10:34:08 -0700483 ##the ip of ONOS in default cluster.json in setup/onos-config
484 CLUSTER_CFG_IP = '172.17.0.2'
A R Karthick07608ef2016-08-23 16:51:19 -0700485 IMAGE = 'onosproject/onos'
486 TAG = 'latest'
487 PREFIX = ''
A R Karthickf2f4ca62016-08-17 10:34:08 -0700488
489 @classmethod
A R Karthick2b93d6a2016-09-06 15:19:09 -0700490 def generate_cluster_cfg(cls, ip):
491 if type(ip) in [ list, tuple ]:
492 ips = ' '.join(ip)
493 else:
494 ips = ip
A R Karthickf2f4ca62016-08-17 10:34:08 -0700495 try:
A R Karthick2b93d6a2016-09-06 15:19:09 -0700496 cmd = '{} {} {}'.format(cls.onos_gen_partitions, cls.cluster_cfg, ips)
497 os.system(cmd)
498 except: pass
499
500 @classmethod
501 def form_cluster(cls, ips):
502 nodes = ' '.join(ips)
503 try:
504 cmd = '{} {}'.format(cls.onos_form_cluster, nodes)
A R Karthickf2f4ca62016-08-17 10:34:08 -0700505 os.system(cmd)
506 except: pass
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700507
A R Karthick9d48c652016-09-15 09:16:36 -0700508 @classmethod
509 def cleanup_runtime(cls):
510 '''Cleanup ONOS runtime generated files'''
511 files = ( Onos.cluster_cfg, os.path.join(Onos.host_config_dir, 'network-cfg.json') )
512 for f in files:
513 if os.access(f, os.F_OK):
514 try:
515 os.unlink(f)
516 except: pass
517
A R Karthickec2db322016-11-17 15:06:01 -0800518 @classmethod
519 def get_data_map(cls, host_volume, guest_volume_dir):
520 host_volume_dir = os.path.join(cls.setup_dir, os.path.basename(host_volume))
521 if not os.path.exists(host_volume_dir):
522 os.mkdir(host_volume_dir)
523 return ( (host_volume_dir, guest_volume_dir), )
524
525 @classmethod
526 def remove_data_map(cls, host_volume, guest_volume_dir):
527 host_volume_dir = os.path.join(cls.setup_dir, os.path.basename(host_volume))
528 if os.path.exists(host_volume_dir):
A.R Karthickf184b342017-01-27 19:30:50 -0800529 shutil.rmtree(host_volume_dir)
A R Karthickec2db322016-11-17 15:06:01 -0800530
A R Karthick973010f2017-02-06 16:41:51 -0800531 @classmethod
532 def update_data_dir(cls, karaf):
533 Onos.guest_data_dir = '/root/onos/apache-karaf-{}/data'.format(karaf)
534 Onos.guest_log_file = '/root/onos/apache-karaf-{}/data/log/karaf.log'.format(karaf)
535
A R Karthickec2db322016-11-17 15:06:01 -0800536 def remove_data_volume(self):
537 if self.data_map is not None:
538 self.remove_data_map(*self.data_map)
539
A.R Karthick1700e0e2016-10-06 18:16:57 -0700540 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX, tag = TAG,
A R Karthickec2db322016-11-17 15:06:01 -0800541 boot_delay = 20, restart = False, network_cfg = None,
A R Karthick85eb1862017-01-23 16:10:57 -0800542 cluster = False, data_volume = None, async = False, quagga_config = None,
543 network = None):
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700544 if restart is True:
545 ##Find the right image to restart
546 running_image = filter(lambda c: c['Names'][0] == '/{}'.format(name), self.dckr.containers())
547 if running_image:
548 image_name = running_image[0]['Image']
549 try:
550 image = image_name.split(':')[0]
551 tag = image_name.split(':')[1]
552 except: pass
553
A R Karthickaa54a1c2016-12-15 11:42:08 -0800554 if quagga_config is None:
555 quagga_config = Onos.QUAGGA_CONFIG
556 super(Onos, self).__init__(name, image, prefix = prefix, tag = tag, quagga_config = quagga_config)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700557 self.boot_delay = boot_delay
A R Karthickec2db322016-11-17 15:06:01 -0800558 self.data_map = None
A R Karthickc69d73e2017-01-20 11:44:34 -0800559 instance_memory = (get_mem(jvm_heap_size = Onos.JVM_HEAP_SIZE, instances = Onos.MAX_INSTANCES),) * 2
560 self.env['JAVA_OPTS'] = self.JAVA_OPTS_FORMAT.format(*instance_memory)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700561 if cluster is True:
562 self.ports = []
A R Karthickec2db322016-11-17 15:06:01 -0800563 if data_volume is not None:
564 self.data_map = self.get_data_map(data_volume, self.guest_data_dir)
565 self.host_guest_map = self.host_guest_map + self.data_map
A R Karthick2b93d6a2016-09-06 15:19:09 -0700566 if os.access(self.cluster_cfg, os.F_OK):
567 try:
568 os.unlink(self.cluster_cfg)
569 except: pass
570
571 self.host_config = self.create_host_config(port_list = self.ports,
572 host_guest_map = self.host_guest_map)
573 self.volumes = []
574 for _,g in self.host_guest_map:
575 self.volumes.append(g)
576
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700577 if restart is True and self.exists():
578 self.kill()
A R Karthick2b93d6a2016-09-06 15:19:09 -0700579
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700580 if not self.exists():
581 self.remove_container(name, force=True)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700582 host_config = self.create_host_config(port_list = self.ports,
583 host_guest_map = self.host_guest_map)
584 volumes = []
585 for _,g in self.host_guest_map:
586 volumes.append(g)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700587 if network_cfg is not None:
A R Karthick81acbff2016-06-17 14:45:16 -0700588 json_data = json.dumps(network_cfg, indent=4)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700589 with open('{}/network-cfg.json'.format(self.host_config_dir), 'w') as f:
590 f.write(json_data)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800591 if cluster is False or async is False:
592 print('Starting ONOS container %s' %self.name)
593 self.start(ports = self.ports, environment = self.env,
594 host_config = self.host_config, volumes = self.volumes, tty = True)
595 if not restart:
596 ##wait a bit before fetching IP to regenerate cluster cfg
597 time.sleep(5)
598 ip = self.ip()
599 ##Just a quick hack/check to ensure we don't regenerate in the common case.
600 ##As ONOS is usually the first test container that is started
601 if cluster is False:
602 if ip != self.CLUSTER_CFG_IP or not os.access(self.cluster_cfg, os.F_OK):
603 print('Regenerating ONOS cluster cfg for ip %s' %ip)
604 self.generate_cluster_cfg(ip)
605 self.kill()
606 self.remove_container(self.name, force=True)
607 print('Restarting ONOS container %s' %self.name)
608 self.start(ports = self.ports, environment = self.env,
609 host_config = self.host_config, volumes = self.volumes, tty = True)
610 print('Waiting for ONOS to boot')
611 time.sleep(boot_delay)
612 self.wait_for_onos_start(self.ip())
613 self.running = True
614 else:
615 self.running = False
616 else:
617 self.running = True
618 if self.running:
619 self.ipaddr = self.ip()
620 if cluster is False:
621 self.install_cord_apps(self.ipaddr)
A R Karthick19aaf5c2016-11-09 17:47:57 -0800622
A.R Karthickc4e474d2016-12-12 15:24:57 -0800623 @classmethod
624 def get_quagga_config(cls, instance = 0):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800625 quagga_config = copy.deepcopy(cls.QUAGGA_CONFIG)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800626 if instance == 0:
627 return quagga_config
628 ip = quagga_config[0]['ip']
629 octets = ip.split('.')
A R Karthickaa54a1c2016-12-15 11:42:08 -0800630 octets[3] = str((int(octets[3]) + instance) & 255)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800631 ip = '.'.join(octets)
632 quagga_config[0]['ip'] = ip
633 return quagga_config
634
635 @classmethod
636 def start_cluster_async(cls, onos_instances):
637 instances = filter(lambda o: o.running == False, onos_instances)
638 if not instances:
639 return
640 tpool = ThreadPool(len(instances), queue_size = 1, wait_timeout = 1)
641 for onos in instances:
642 tpool.addTask(onos.start_async)
643 tpool.cleanUpThreads()
644
645 def start_async(self):
646 print('Starting ONOS container %s' %self.name)
647 self.start(ports = self.ports, environment = self.env,
648 host_config = self.host_config, volumes = self.volumes, tty = True)
649 time.sleep(3)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700650 self.ipaddr = self.ip()
A.R Karthickc4e474d2016-12-12 15:24:57 -0800651 print('Waiting for ONOS container %s to start' %self.name)
652 self.wait_for_onos_start(self.ipaddr)
653 self.running = True
654 print('ONOS container %s started' %self.name)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700655
A R Karthick2b93d6a2016-09-06 15:19:09 -0700656 @classmethod
A R Karthick19aaf5c2016-11-09 17:47:57 -0800657 def wait_for_onos_start(cls, ip, tries = 30):
A R Karthick973010f2017-02-06 16:41:51 -0800658 onos_log = OnosLog(host = ip, log_file = Onos.guest_log_file)
A R Karthick19aaf5c2016-11-09 17:47:57 -0800659 num_tries = 0
660 started = None
661 while not started and num_tries < tries:
662 time.sleep(3)
663 started = onos_log.search_log_pattern('ApplicationManager .* Started')
664 num_tries += 1
665
A R Karthick19aaf5c2016-11-09 17:47:57 -0800666 if not started:
667 print('ONOS did not start')
668 else:
669 print('ONOS started')
670 return started
671
672 @classmethod
A R Karthick2b93d6a2016-09-06 15:19:09 -0700673 def setup_cluster_deprecated(cls, onos_instances, image_name = None):
674 if not onos_instances or len(onos_instances) < 2:
675 return
676 ips = []
677 if image_name is not None:
678 ips = Container.ips(image_name)
679 else:
680 for onos in onos_instances:
681 ips.append(onos.ipaddr)
682 Onos.cluster_instances = onos_instances
683 Onos.cluster_mode = True
684 ##regenerate the cluster json with the 3 instance ips before restarting them back
685 print('Generating cluster cfg for ONOS instances with ips %s' %ips)
686 Onos.generate_cluster_cfg(ips)
687 for onos in onos_instances:
688 onos.kill()
689 onos.remove_container(onos.name, force=True)
690 print('Restarting ONOS container %s for forming cluster' %onos.name)
691 onos.start(ports = onos.ports, environment = onos.env,
692 host_config = onos.host_config, volumes = onos.volumes, tty = True)
693 print('Waiting %d seconds for ONOS %s to boot' %(onos.boot_delay, onos.name))
694 time.sleep(onos.boot_delay)
695 onos.ipaddr = onos.ip()
696 onos.install_cord_apps(onos.ipaddr)
697
698 @classmethod
699 def setup_cluster(cls, onos_instances, image_name = None):
700 if not onos_instances or len(onos_instances) < 2:
701 return
702 ips = []
703 if image_name is not None:
704 ips = Container.ips(image_name)
705 else:
706 for onos in onos_instances:
707 ips.append(onos.ipaddr)
708 Onos.cluster_instances = onos_instances
709 Onos.cluster_mode = True
710 ##regenerate the cluster json with the 3 instance ips before restarting them back
711 print('Forming cluster for ONOS instances with ips %s' %ips)
712 Onos.form_cluster(ips)
713 ##wait for the cluster to be formed
714 print('Waiting for the cluster to be formed')
715 time.sleep(60)
716 for onos in onos_instances:
717 onos.install_cord_apps(onos.ipaddr)
718
719 @classmethod
A R Karthicke2c24bd2016-10-07 14:51:38 -0700720 def add_cluster(cls, count = 1, network_cfg = None):
721 if not cls.cluster_instances or Onos.cluster_mode is False:
722 return
723 for i in range(count):
724 name = '{}-{}'.format(Onos.NAME, len(cls.cluster_instances)+1)
725 onos = cls(name = name, image = Onos.IMAGE, tag = Onos.TAG, prefix = Container.IMAGE_PREFIX,
726 cluster = True, network_cfg = network_cfg)
727 cls.cluster_instances.append(onos)
728
729 cls.setup_cluster(cls.cluster_instances)
730
731 @classmethod
A.R Karthick2560f042016-11-30 14:38:52 -0800732 def restart_cluster(cls, network_cfg = None, timeout = 10, setup = False):
A R Karthick2b93d6a2016-09-06 15:19:09 -0700733 if cls.cluster_mode is False:
734 return
735 if not cls.cluster_instances:
736 return
737
738 if network_cfg is not None:
739 json_data = json.dumps(network_cfg, indent=4)
740 with open('{}/network-cfg.json'.format(cls.host_config_dir), 'w') as f:
741 f.write(json_data)
742
A.R Karthick2560f042016-11-30 14:38:52 -0800743 cls.cleanup_cluster()
744 if timeout > 0:
745 time.sleep(timeout)
746
A R Karthickaa54a1c2016-12-15 11:42:08 -0800747 #start the instances asynchronously
748 cls.start_cluster_async(cls.cluster_instances)
749 time.sleep(5)
A.R Karthick2560f042016-11-30 14:38:52 -0800750 ##form the cluster as appropriate
751 if setup is True:
752 cls.setup_cluster(cls.cluster_instances)
A R Karthickaa54a1c2016-12-15 11:42:08 -0800753 else:
754 for onos in cls.cluster_instances:
755 onos.install_cord_apps(onos.ipaddr)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700756
757 @classmethod
758 def cluster_ips(cls):
759 if cls.cluster_mode is False:
760 return []
761 if not cls.cluster_instances:
762 return []
763 ips = [ onos.ipaddr for onos in cls.cluster_instances ]
764 return ips
765
766 @classmethod
767 def cleanup_cluster(cls):
768 if cls.cluster_mode is False:
769 return
770 if not cls.cluster_instances:
771 return
772 for onos in cls.cluster_instances:
773 if onos.exists():
774 onos.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800775 onos.running = False
A R Karthick2b93d6a2016-09-06 15:19:09 -0700776 onos.remove_container(onos.name, force=True)
A R Karthickd44cea12016-07-20 12:16:41 -0700777
A.R Karthick95d044e2016-06-10 18:44:36 -0700778 @classmethod
A R Karthickde6b9dc2016-11-29 17:46:16 -0800779 def restart_node(cls, node = None, network_cfg = None, timeout = 10):
A R Karthick889d9652016-10-03 14:13:45 -0700780 if node is None:
781 cls(restart = True, network_cfg = network_cfg, image = cls.IMAGE, tag = cls.TAG)
782 else:
783 #Restarts a node in the cluster
784 valid_node = filter(lambda onos: node in [ onos.ipaddr, onos.name ], cls.cluster_instances)
785 if valid_node:
786 onos = valid_node.pop()
787 if onos.exists():
788 onos.kill()
789 onos.remove_container(onos.name, force=True)
A R Karthickde6b9dc2016-11-29 17:46:16 -0800790 if timeout > 0:
791 time.sleep(timeout)
A R Karthick889d9652016-10-03 14:13:45 -0700792 print('Restarting ONOS container %s' %onos.name)
793 onos.start(ports = onos.ports, environment = onos.env,
794 host_config = onos.host_config, volumes = onos.volumes, tty = True)
A R Karthick889d9652016-10-03 14:13:45 -0700795 onos.ipaddr = onos.ip()
A.R Karthick2560f042016-11-30 14:38:52 -0800796 onos.wait_for_onos_start(onos.ipaddr)
797 onos.install_cord_apps(onos.ipaddr)
A R Karthick889d9652016-10-03 14:13:45 -0700798
799 @classmethod
A R Karthickeaf1c4e2016-07-19 12:22:35 -0700800 def install_cord_apps(cls, onos_ip = None):
A.R Karthick95d044e2016-06-10 18:44:36 -0700801 for app, version in cls.onos_cord_apps:
802 app_file = '{}/{}-{}.oar'.format(cls.cord_apps_dir, app, version)
A R Karthickeaf1c4e2016-07-19 12:22:35 -0700803 ok, code = OnosCtrl.install_app(app_file, onos_ip = onos_ip)
A.R Karthick95d044e2016-06-10 18:44:36 -0700804 ##app already installed (conflicts)
805 if code in [ 409 ]:
806 ok = True
807 print('ONOS app %s, version %s %s' %(app, version, 'installed' if ok else 'failed to install'))
808 time.sleep(2)
809
A.R Karthick1700e0e2016-10-06 18:16:57 -0700810class OnosStopWrapper(Container):
811 def __init__(self, name):
812 super(OnosStopWrapper, self).__init__(name, Onos.IMAGE, tag = Onos.TAG, prefix = Container.IMAGE_PREFIX)
813 if self.exists():
814 self.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800815 self.running = False
A.R Karthick1700e0e2016-10-06 18:16:57 -0700816 else:
817 if Onos.cluster_mode is True:
818 valid_node = filter(lambda onos: name in [ onos.ipaddr, onos.name ], Onos.cluster_instances)
819 if valid_node:
820 onos = valid_node.pop()
821 if onos.exists():
822 onos.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800823 onos.running = False
A.R Karthick1700e0e2016-10-06 18:16:57 -0700824
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700825class Radius(Container):
826 ports = [ 1812, 1813 ]
A R Karthick41adfce2016-06-10 09:51:25 -0700827 env = {'TIMEZONE':'America/Los_Angeles',
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700828 'DEBUG': 'true', 'cert_password':'whatever', 'primary_shared_secret':'radius_password'
829 }
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700830 host_db_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/db')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700831 guest_db_dir = os.path.join(os.path.sep, 'opt', 'db')
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700832 host_config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/freeradius')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700833 guest_config_dir = os.path.join(os.path.sep, 'etc', 'freeradius')
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700834 start_command = os.path.join(guest_config_dir, 'start-radius.py')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700835 host_guest_map = ( (host_db_dir, guest_db_dir),
836 (host_config_dir, guest_config_dir)
837 )
A R Karthickf7a613b2017-02-24 09:36:44 -0800838 IMAGE = 'cordtest/radius'
Chetan Gaonker503032a2016-05-12 12:06:29 -0700839 NAME = 'cord-radius'
840
A R Karthick07608ef2016-08-23 16:51:19 -0700841 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = 'candidate',
A R Karthick85eb1862017-01-23 16:10:57 -0800842 boot_delay = 10, restart = False, update = False, network = None):
A R Karthick07608ef2016-08-23 16:51:19 -0700843 super(Radius, self).__init__(name, image, prefix = prefix, tag = tag, command = self.start_command)
Chetan Gaonker503032a2016-05-12 12:06:29 -0700844 if update is True or not self.img_exists():
A R Karthick07608ef2016-08-23 16:51:19 -0700845 self.build_image(self.image_name)
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700846 if restart is True and self.exists():
847 self.kill()
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700848 if not self.exists():
849 self.remove_container(name, force=True)
850 host_config = self.create_host_config(port_list = self.ports,
851 host_guest_map = self.host_guest_map)
852 volumes = []
853 for _,g in self.host_guest_map:
854 volumes.append(g)
A R Karthick41adfce2016-06-10 09:51:25 -0700855 self.start(ports = self.ports, environment = self.env,
856 volumes = volumes,
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700857 host_config = host_config, tty = True)
A R Karthick85eb1862017-01-23 16:10:57 -0800858 if network is not None:
859 Container.connect_to_network(self.name, network)
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700860 time.sleep(boot_delay)
861
862 @classmethod
863 def build_image(cls, image):
864 print('Building Radius image %s' %image)
865 dockerfile = '''
866FROM hbouvier/docker-radius
867MAINTAINER chetan@ciena.com
868LABEL RUN docker pull hbouvier/docker-radius
869LABEL RUN docker run -it --name cord-radius hbouvier/docker-radius
A R Karthickc762df42016-05-25 10:09:21 -0700870RUN apt-get update && \
871 apt-get -y install python python-pexpect strace
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700872WORKDIR /root
873CMD ["/etc/freeradius/start-radius.py"]
874'''
875 super(Radius, cls).build_image(dockerfile, image)
876 print('Done building image %s' %image)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700877
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700878class Quagga(Container):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800879 QUAGGA_CONFIG = ( { 'bridge' : 'quagga-br', 'ip': '10.10.0.3', 'mask' : 16 },
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700880 { 'bridge' : 'quagga-br', 'ip': '192.168.10.3', 'mask': 16 },
881 )
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700882 ports = [ 179, 2601, 2602, 2603, 2604, 2605, 2606 ]
883 host_quagga_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/quagga-config')
884 guest_quagga_config = '/root/config'
885 quagga_config_file = os.path.join(guest_quagga_config, 'testrib.conf')
886 host_guest_map = ( (host_quagga_config, guest_quagga_config), )
A R Karthickf7a613b2017-02-24 09:36:44 -0800887 IMAGE = 'cordtest/quagga'
Chetan Gaonker503032a2016-05-12 12:06:29 -0700888 NAME = 'cord-quagga'
889
A R Karthick07608ef2016-08-23 16:51:19 -0700890 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = 'candidate',
A R Karthick85eb1862017-01-23 16:10:57 -0800891 boot_delay = 15, restart = False, config_file = quagga_config_file, update = False,
892 network = None):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800893 super(Quagga, self).__init__(name, image, prefix = prefix, tag = tag, quagga_config = self.QUAGGA_CONFIG)
Chetan Gaonker503032a2016-05-12 12:06:29 -0700894 if update is True or not self.img_exists():
A R Karthick07608ef2016-08-23 16:51:19 -0700895 self.build_image(self.image_name)
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700896 if restart is True and self.exists():
897 self.kill()
898 if not self.exists():
899 self.remove_container(name, force=True)
A R Karthick41adfce2016-06-10 09:51:25 -0700900 host_config = self.create_host_config(port_list = self.ports,
901 host_guest_map = self.host_guest_map,
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700902 privileged = True)
903 volumes = []
904 for _,g in self.host_guest_map:
905 volumes.append(g)
906 self.start(ports = self.ports,
A R Karthick41adfce2016-06-10 09:51:25 -0700907 host_config = host_config,
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700908 volumes = volumes, tty = True)
A R Karthick85eb1862017-01-23 16:10:57 -0800909 if network is not None:
910 Container.connect_to_network(self.name, network)
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700911 print('Starting Quagga on container %s' %self.name)
912 self.execute('{0}/start.sh {1}'.format(self.guest_quagga_config, config_file))
913 time.sleep(boot_delay)
914
915 @classmethod
916 def build_image(cls, image):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800917 onos_quagga_ip = Onos.QUAGGA_CONFIG[0]['ip']
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700918 print('Building Quagga image %s' %image)
919 dockerfile = '''
A R Karthick41adfce2016-06-10 09:51:25 -0700920FROM ubuntu:14.04
921MAINTAINER chetan@ciena.com
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700922WORKDIR /root
923RUN useradd -M quagga
924RUN mkdir /var/log/quagga && chown quagga:quagga /var/log/quagga
925RUN mkdir /var/run/quagga && chown quagga:quagga /var/run/quagga
A R Karthick973ea692016-10-17 12:23:02 -0700926RUN 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 -0700927RUN git clone git://git.savannah.nongnu.org/quagga.git quagga && \
A R Karthick8f69c2c2016-10-21 11:43:26 -0700928(cd quagga && git checkout quagga-1.0.20160315 && ./bootstrap.sh && \
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700929sed -i -r 's,htonl.*?\(INADDR_LOOPBACK\),inet_addr\("{0}"\),g' zebra/zebra_fpm.c && \
930./configure --enable-fpm --disable-doc --localstatedir=/var/run/quagga && make && make install)
931RUN ldconfig
932'''.format(onos_quagga_ip)
933 super(Quagga, cls).build_image(dockerfile, image)
934 print('Done building image %s' %image)
A R Karthick81acbff2016-06-17 14:45:16 -0700935
A.R Karthick1700e0e2016-10-06 18:16:57 -0700936class QuaggaStopWrapper(Container):
937 def __init__(self, name = Quagga.NAME, image = Quagga.IMAGE, tag = 'candidate'):
938 super(QuaggaStopWrapper, self).__init__(name, image, prefix = Container.IMAGE_PREFIX, tag = tag)
939 if self.exists():
940 self.kill()
941
942
A R Karthick81acbff2016-06-17 14:45:16 -0700943def reinitContainerClients():
944 docker_netns.dckr = Client()
945 Container.dckr = Client()
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700946
947class Xos(Container):
948 setup_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup')
949 TAG = 'latest'
950 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -0700951 host_guest_map = None
952 env = None
953 ports = None
954 volumes = None
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700955
A R Karthick6e80afd2016-10-10 16:03:12 -0700956 @classmethod
957 def get_cmd(cls, img_name):
958 cmd = cls.dckr.inspect_image(img_name)['Config']['Cmd']
959 return ' '.join(cmd)
960
A R Karthicke3bde962016-09-27 15:06:35 -0700961 def __init__(self, name, image, prefix = PREFIX, tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -0700962 boot_delay = 20, restart = False, network_cfg = None, update = False):
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700963 if restart is True:
964 ##Find the right image to restart
965 running_image = filter(lambda c: c['Names'][0] == '/{}'.format(name), self.dckr.containers())
966 if running_image:
967 image_name = running_image[0]['Image']
968 try:
969 image = image_name.split(':')[0]
970 tag = image_name.split(':')[1]
971 except: pass
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700972 super(Xos, self).__init__(name, image, prefix = prefix, tag = tag)
973 if update is True or not self.img_exists():
974 self.build_image(self.image_name)
A R Karthick6e80afd2016-10-10 16:03:12 -0700975 self.command = self.get_cmd(self.image_name).strip() or None
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700976 if restart is True and self.exists():
977 self.kill()
978 if not self.exists():
979 self.remove_container(name, force=True)
A R Karthicke3bde962016-09-27 15:06:35 -0700980 host_config = self.create_host_config(port_list = self.ports,
981 host_guest_map = self.host_guest_map,
982 privileged = True)
983 print('Starting XOS container %s' %self.name)
984 self.start(ports = self.ports, environment = self.env, host_config = host_config,
985 volumes = self.volumes, tty = True)
986 print('Waiting %d seconds for XOS Base Container to boot' %(boot_delay))
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700987 time.sleep(boot_delay)
988
989 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -0700990 def build_image(cls, image, dockerfile_path, image_target = 'build'):
991 cmd = 'cd {} && make {}'.format(dockerfile_path, image_target)
992 print('Building XOS %s' %image)
993 res = os.system(cmd)
994 print('Done building image %s. Image build %s' %(image, 'successful' if res == 0 else 'failed'))
995 return res
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700996
A R Karthicke3bde962016-09-27 15:06:35 -0700997class XosServer(Xos):
998 ports = [8000,9998,9999]
999 NAME = 'xos-server'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001000 IMAGE = 'xosproject/xos'
A R Karthicke3bde962016-09-27 15:06:35 -07001001 BASE_IMAGE = 'xosproject/xos-base'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001002 TAG = 'latest'
1003 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -07001004 dockerfile_path = os.path.join(Xos.setup_dir, 'xos')
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001005
A R Karthicke3bde962016-09-27 15:06:35 -07001006 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX, tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001007 boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001008 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001009
1010 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -07001011 def build_image(cls, image = IMAGE):
1012 ##build the base image and then build the server image
1013 Xos.build_image(cls.BASE_IMAGE, cls.dockerfile_path, image_target = 'base')
1014 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001015
A R Karthicke3bde962016-09-27 15:06:35 -07001016class XosSynchronizerOpenstack(Xos):
1017 ports = [2375,]
1018 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer')
1019 NAME = 'xos-synchronizer'
1020 IMAGE = 'xosproject/xos-synchronizer-openstack'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001021 TAG = 'latest'
1022 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -07001023 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001024
A R Karthicke3bde962016-09-27 15:06:35 -07001025 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -07001026 tag = TAG, boot_delay = 20, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001027 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001028
1029 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -07001030 def build_image(cls, image = IMAGE):
1031 XosServer.build_image()
1032 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001033
A R Karthicke3bde962016-09-27 15:06:35 -07001034class XosSynchronizerOnboarding(Xos):
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001035 NAME = 'xos-synchronizer-onboarding'
1036 IMAGE = 'xosproject/xos-synchronizer-onboarding'
1037 TAG = 'latest'
1038 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -07001039 dockerfile_path = os.path.join(Xos.setup_dir, 'onboarding_synchronizer')
1040 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001041
A R Karthicke3bde962016-09-27 15:06:35 -07001042 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -07001043 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001044 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001045
1046 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -07001047 def build_image(cls, image = IMAGE):
1048 XosSynchronizerOpenstack.build_image()
1049 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001050
A R Karthicke3bde962016-09-27 15:06:35 -07001051class XosSynchronizerOpenvpn(Xos):
1052 NAME = 'xos-synchronizer-openvpn'
1053 IMAGE = 'xosproject/xos-openvpn'
1054 TAG = 'latest'
1055 PREFIX = ''
1056 dockerfile_path = os.path.join(Xos.setup_dir, 'openvpn')
1057 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001058
A R Karthicke3bde962016-09-27 15:06:35 -07001059 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -07001060 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001061 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1062
1063 @classmethod
1064 def build_image(cls, image = IMAGE):
1065 XosSynchronizerOpenstack.build_image()
1066 Xos.build_image(image, cls.dockerfile_path)
1067
1068class XosPostgresql(Xos):
1069 ports = [5432,]
1070 NAME = 'xos-db-postgres'
1071 IMAGE = 'xosproject/xos-postgres'
1072 TAG = 'latest'
1073 PREFIX = ''
1074 volumes = ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
1075 dockerfile_path = os.path.join(Xos.setup_dir, 'postgresql')
1076
1077 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -07001078 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001079 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1080
1081 @classmethod
1082 def build_image(cls, image = IMAGE):
1083 Xos.build_image(image, cls.dockerfile_path)
1084
1085class XosSyndicateMs(Xos):
1086 ports = [8080,]
1087 env = None
1088 NAME = 'xos-syndicate-ms'
1089 IMAGE = 'xosproject/syndicate-ms'
1090 TAG = 'latest'
1091 PREFIX = ''
1092 dockerfile_path = os.path.join(Xos.setup_dir, 'syndicate-ms')
1093
1094 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001095 boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001096 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1097
1098 @classmethod
1099 def build_image(cls, image = IMAGE):
1100 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001101
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001102class XosSyncVtn(Xos):
1103 ports = [8080,]
1104 env = None
1105 NAME = 'xos-synchronizer-vtn'
1106 IMAGE = 'xosproject/xos-synchronizer-vtn'
1107 TAG = 'latest'
1108 PREFIX = ''
1109 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vtn')
1110
1111 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001112 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001113 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1114
1115 @classmethod
1116 def build_image(cls, image = IMAGE):
1117 Xos.build_image(image, cls.dockerfile_path)
1118
1119class XosSyncVtr(Xos):
1120 ports = [8080,]
1121 env = None
1122 NAME = 'xos-synchronizer-vtr'
1123 IMAGE = 'xosproject/xos-synchronizer-vtr'
1124 TAG = 'latest'
1125 PREFIX = ''
1126 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vtr')
1127
1128 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001129 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001130 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1131
1132 @classmethod
1133 def build_image(cls, image = IMAGE):
1134 Xos.build_image(image, cls.dockerfile_path)
1135
1136class XosSyncVsg(Xos):
1137 ports = [8080,]
1138 env = None
1139 NAME = 'xos-synchronizer-vsg'
1140 IMAGE = 'xosproject/xos-synchronizer-vsg'
1141 TAG = 'latest'
1142 PREFIX = ''
1143 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vsg')
1144
1145 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001146 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001147 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1148
1149 @classmethod
1150 def build_image(cls, image = IMAGE):
1151 Xos.build_image(image, cls.dockerfile_path)
1152
1153
1154class XosSyncOnos(Xos):
1155 ports = [8080,]
1156 env = None
1157 NAME = 'xos-synchronizer-onos'
1158 IMAGE = 'xosproject/xos-synchronizer-onos'
1159 TAG = 'latest'
1160 PREFIX = ''
1161 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-onos')
1162
1163 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001164 boot_delay = 30, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001165 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1166
1167 @classmethod
1168 def build_image(cls, image = IMAGE):
1169 Xos.build_image(image, cls.dockerfile_path)
1170
1171class XosSyncFabric(Xos):
1172 ports = [8080,]
1173 env = None
1174 NAME = 'xos-synchronizer-fabric'
1175 IMAGE = 'xosproject/xos-synchronizer-fabric'
1176 TAG = 'latest'
1177 PREFIX = ''
1178 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-fabric')
1179
1180 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001181 boot_delay = 30, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001182 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1183
1184 @classmethod
1185 def build_image(cls, image = IMAGE):
1186 Xos.build_image(image, cls.dockerfile_path)
A R Karthick19aaf5c2016-11-09 17:47:57 -08001187
1188if __name__ == '__main__':
1189 onos = Onos(boot_delay = 10, restart = True)