blob: df9a196874a816f7ff45745993216cf8e1741a01 [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 Karthickec2db322016-11-17 15:06:01 -080028from shutil import rmtree
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
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700196 def connect_to_br(self):
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700197 index = 0
A R Karthickaa54a1c2016-12-15 11:42:08 -0800198 self.CONFIG_LOCK.acquire()
199 try:
200 with docker_netns(self.name) as pid:
201 for quagga_config in self.quagga_config:
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700202 ip = IPRoute()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800203 br = ip.link_lookup(ifname=quagga_config['bridge'])
204 if len(br) == 0:
205 try:
206 ip.link_create(ifname=quagga_config['bridge'], kind='bridge')
207 except NetlinkError as e:
208 err, _ = e.args
209 if err == errno.EEXIST:
210 pass
211 else:
212 raise NetlinkError(*e.args)
213 br = ip.link_lookup(ifname=quagga_config['bridge'])
214 br = br[0]
215 ip.link('set', index=br, state='up')
216 ifname = '{0}-{1}'.format(self.name, index)
217 ifs = ip.link_lookup(ifname=ifname)
218 if len(ifs) > 0:
219 ip.link_remove(ifs[0])
220 peer_ifname = '{0}-{1}'.format(pid, index)
221 ip.link_create(ifname=ifname, kind='veth', peer=peer_ifname)
222 host = ip.link_lookup(ifname=ifname)[0]
223 ip.link('set', index=host, master=br)
224 ip.link('set', index=host, state='up')
225 guest = ip.link_lookup(ifname=peer_ifname)[0]
226 ip.link('set', index=guest, net_ns_fd=pid)
227 with Namespace(pid, 'net'):
228 ip = IPRoute()
229 ip.link('set', index=guest, ifname='eth{}'.format(index+1))
230 ip.addr('add', index=guest, address=quagga_config['ip'], mask=quagga_config['mask'])
231 ip.link('set', index=guest, state='up')
232 index += 1
233 finally:
234 self.CONFIG_LOCK.release()
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700235
Thangavelu K Sef6f0a52016-12-14 19:57:05 +0000236 def execute(self, cmd, tty = True, stream = False, shell = False, detach = True):
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700237 res = 0
238 if type(cmd) == str:
239 cmds = (cmd,)
240 else:
241 cmds = cmd
242 if shell:
243 for c in cmds:
244 res += os.system('docker exec {0} {1}'.format(self.name, c))
245 return res
246 for c in cmds:
247 i = self.dckr.exec_create(container=self.name, cmd=c, tty = tty, privileged = True)
Thangavelu K Sef6f0a52016-12-14 19:57:05 +0000248 self.dckr.exec_start(i['Id'], stream = stream, detach=detach)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700249 result = self.dckr.exec_inspect(i['Id'])
250 res += 0 if result['ExitCode'] == None else result['ExitCode']
251 return res
252
ChetanGaonker6138fcd2016-08-18 17:56:39 -0700253 def restart(self, timeout =10):
254 return self.dckr.restart(self.name, timeout)
255
A R Karthickc69d73e2017-01-20 11:44:34 -0800256def get_mem(jvm_heap_size = None, instances = 1):
A R Karthick1f908202016-11-16 17:32:20 -0800257 if instances <= 0:
258 instances = 1
A R Karthickc69d73e2017-01-20 11:44:34 -0800259 heap_size = jvm_heap_size
260 heap_size_i = 0
261 #sanitize the heap size config
262 if heap_size is not None:
263 if not heap_size.isdigit():
264 try:
265 heap_size_i = int(heap_size[:-1])
266 suffix = heap_size[-1]
267 if suffix == 'M':
268 heap_size_i /= 1024 #convert to gigs
269 except:
270 ##invalid suffix length probably. Fall back to default
271 heap_size = None
272 else:
273 heap_size_i = int(heap_size)
274
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700275 with open('/proc/meminfo', 'r') as fd:
276 meminfo = fd.readlines()
277 mem = 0
278 for m in meminfo:
279 if m.startswith('MemTotal:') or m.startswith('SwapTotal:'):
280 mem += int(m.split(':')[1].strip().split()[0])
281
A R Karthick1f908202016-11-16 17:32:20 -0800282 mem = max(mem/1024/1024/2/instances, 1)
Chetan Gaonker6d0a7b02016-05-03 16:57:28 -0700283 mem = min(mem, 16)
A R Karthickc69d73e2017-01-20 11:44:34 -0800284
285 if heap_size_i:
286 #we take the minimum of the provided heap size and max allowed heap size
287 heap_size_i = min(heap_size_i, mem)
288 else:
289 heap_size_i = mem
290
291 return '{}G'.format(heap_size_i)
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700292
A R Karthickd44cea12016-07-20 12:16:41 -0700293class OnosCord(Container):
294 """Use this when running the cord tester agent on the onos compute node"""
295 onos_cord_dir = os.path.join(os.getenv('HOME'), 'cord-tester-cord')
296 onos_config_dir_guest = '/root/onos/config'
297 onos_config_dir = os.path.join(onos_cord_dir, 'config')
298 docker_yaml = os.path.join(onos_cord_dir, 'docker-compose.yml')
A.R Karthickb17e2022017-01-27 11:29:26 -0800299 onos_cfg_save_loc = os.path.join(onos_cord_dir, 'network-cfg.json.saved')
A R Karthickd44cea12016-07-20 12:16:41 -0700300
A R Karthickbd9b8a32016-07-21 09:56:45 -0700301 def __init__(self, onos_ip, conf, boot_delay = 60):
302 self.onos_ip = onos_ip
A R Karthickd44cea12016-07-20 12:16:41 -0700303 self.cord_conf_dir = conf
A R Karthickbd9b8a32016-07-21 09:56:45 -0700304 self.boot_delay = boot_delay
A R Karthickd44cea12016-07-20 12:16:41 -0700305 if os.access(self.cord_conf_dir, os.F_OK) and not os.access(self.onos_cord_dir, os.F_OK):
306 os.mkdir(self.onos_cord_dir)
307 os.mkdir(self.onos_config_dir)
308 ##copy the config file from cord-tester-config
309 cmd = 'cp {}/* {}'.format(self.cord_conf_dir, self.onos_cord_dir)
310 os.system(cmd)
311
312 ##update the docker yaml with the config volume
313 with open(self.docker_yaml, 'r') as f:
314 yaml_config = yaml.load(f)
315 image = yaml_config['services'].keys()[0]
316 name = 'cordtestercord_{}_1'.format(image)
317 volumes = yaml_config['services'][image]['volumes']
318 config_volumes = filter(lambda e: e.find(self.onos_config_dir_guest) >= 0, volumes)
319 if not config_volumes:
320 config_volume = '{}:{}'.format(self.onos_config_dir, self.onos_config_dir_guest)
321 volumes.append(config_volume)
322 docker_yaml_changed = '{}-changed'.format(self.docker_yaml)
323 with open(docker_yaml_changed, 'w') as wf:
324 yaml.dump(yaml_config, wf)
325
326 os.rename(docker_yaml_changed, self.docker_yaml)
327 self.volumes = volumes
328
329 super(OnosCord, self).__init__(name, image, tag = '')
330 cord_conf_dir_basename = os.path.basename(self.cord_conf_dir.replace('-', ''))
331 self.xos_onos_name = '{}_{}_1'.format(cord_conf_dir_basename, image)
332 ##Create an container instance of xos onos
333 self.xos_onos = Container(self.xos_onos_name, image, tag = '')
A.R Karthickb17e2022017-01-27 11:29:26 -0800334 #fetch the current config of onos cord instance
335 try:
336 self.last_cfg = OnosCtrl.get_config(controller = onos_ip)
337 except:
338 self.last_cfg = None
A R Karthickd44cea12016-07-20 12:16:41 -0700339
340 def start(self, restart = False, network_cfg = None):
341 if restart is True:
342 if self.exists():
343 ##Kill the existing instance
344 print('Killing container %s' %self.name)
345 self.kill()
346 if self.xos_onos.exists():
A.R Karthickb17e2022017-01-27 11:29:26 -0800347 if self.last_cfg is not None:
348 #save the current network config of onos cord instance
349 json_data = json.dumps(self.last_cfg, indent=4)
350 with open(self.onos_cfg_save_loc, 'w') as f:
351 f.write(json_data)
A R Karthickd44cea12016-07-20 12:16:41 -0700352 print('Killing container %s' %self.xos_onos.name)
353 self.xos_onos.kill()
354
355 if network_cfg is not None:
356 json_data = json.dumps(network_cfg, indent=4)
357 with open('{}/network-cfg.json'.format(self.onos_config_dir), 'w') as f:
358 f.write(json_data)
359
360 #start the container using docker-compose
361 cmd = 'cd {} && docker-compose up -d'.format(self.onos_cord_dir)
362 os.system(cmd)
A R Karthickbd9b8a32016-07-21 09:56:45 -0700363 #Delay to make sure ONOS fully boots
364 time.sleep(self.boot_delay)
365 Onos.install_cord_apps(onos_ip = self.onos_ip)
A R Karthickd44cea12016-07-20 12:16:41 -0700366
367 def build_image(self):
368 build_cmd = 'cd {} && docker-compose build'.format(self.onos_cord_dir)
369 os.system(build_cmd)
370
A.R Karthickb17e2022017-01-27 11:29:26 -0800371 @classmethod
372 def restore_onos_cord(cls, onos_cord, onos_ip):
373 #bring down the onos cord wrapper container
374 #if there is no saved config, there is nothing to restore as it was never restarted
375 if not os.access(cls.onos_cfg_save_loc, os.F_OK):
376 return
377 if not onos_cord or not os.access(onos_cord, os.F_OK):
378 return
379
380 print('Stopping the existing ONOS cord wrapper instance at %s' %(cls.onos_cord_dir))
381 cmd = 'cd {} && docker-compose down'.format(cls.onos_cord_dir)
382 try:
383 os.system(cmd)
384 except:pass
385
386 print('Starting the ONOS cord instance at %s' %(onos_cord))
387 #bring back up the onos cord container
388 cmd = 'cd {} && docker-compose up -d'.format(onos_cord)
389 try:
390 os.system(cmd)
391 time.sleep(30)
392 except:
393 pass
394
395 #now restore back the old config
396 print('Restoring back the saved ONOS cord config at %s for ONOS cord instance' %(cls.onos_cfg_save_loc))
397 with open(cls.onos_cfg_save_loc, 'r') as f:
398 config = json.load(f)
399 try:
400 OnosCtrl.config(config, controller = onos_ip)
401 os.unlink(cls.onos_cfg_save_loc)
402 except: pass
403
404 print('Cleaning up the ONOS cord wrapper directory at %s' %(cls.onos_cord_dir))
405 try:
406 os.system('rm -rf {}'.format(cls.onos_cord_dir))
407 except:
408 pass
409
A.R Karthick1700e0e2016-10-06 18:16:57 -0700410class OnosCordStopWrapper(Container):
411 onos_cord_dir = os.path.join(os.getenv('HOME'), 'cord-tester-cord')
412 docker_yaml = os.path.join(onos_cord_dir, 'docker-compose.yml')
413
414 def __init__(self):
415 if os.access(self.docker_yaml, os.F_OK):
416 with open(self.docker_yaml, 'r') as f:
417 yaml_config = yaml.load(f)
418 image = yaml_config['services'].keys()[0]
419 name = 'cordtestercord_{}_1'.format(image)
420 super(OnosCordStopWrapper, self).__init__(name, image, tag = '')
421 if self.exists():
422 print('Killing container %s' %self.name)
423 self.kill()
424
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700425class Onos(Container):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800426 QUAGGA_CONFIG = [ { 'bridge' : 'quagga-br', 'ip': '10.10.0.4', 'mask' : 16 }, ]
A R Karthicka2492c12016-12-16 10:31:51 -0800427 MAX_INSTANCES = 3
A R Karthickc69d73e2017-01-20 11:44:34 -0800428 JVM_HEAP_SIZE = None
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700429 SYSTEM_MEMORY = (get_mem(),) * 2
A R Karthicka2492c12016-12-16 10:31:51 -0800430 INSTANCE_MEMORY = (get_mem(instances=MAX_INSTANCES),) * 2
A R Karthickc69d73e2017-01-20 11:44:34 -0800431 JAVA_OPTS_FORMAT = '-Xms{} -Xmx{} -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode'
432 JAVA_OPTS_DEFAULT = JAVA_OPTS_FORMAT.format(*SYSTEM_MEMORY) #-XX:+PrintGCDetails -XX:+PrintGCTimeStamps'
433 JAVA_OPTS_CLUSTER_DEFAULT = JAVA_OPTS_FORMAT.format(*INSTANCE_MEMORY)
434 env = { 'ONOS_APPS' : 'drivers,openflow,proxyarp,vrouter', 'JAVA_OPTS' : JAVA_OPTS_DEFAULT }
A.R Karthickdfeadb02016-11-30 17:55:51 -0800435 onos_cord_apps = ( ('cord-config', '1.1-SNAPSHOT'),
436 ('aaa', '1.1-SNAPSHOT'),
437 ('igmp', '1.1-SNAPSHOT'),
438 #('vtn', '1.1-SNAPSHOT'),
A.R Karthick95d044e2016-06-10 18:44:36 -0700439 )
A.R Karthickc4e474d2016-12-12 15:24:57 -0800440 ports = [] #[ 8181, 8101, 9876, 6653, 6633, 2000, 2620 ]
A R Karthickf2f4ca62016-08-17 10:34:08 -0700441 setup_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup')
442 host_config_dir = os.path.join(setup_dir, 'onos-config')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700443 guest_config_dir = '/root/onos/config'
A R Karthickec2db322016-11-17 15:06:01 -0800444 guest_data_dir = '/root/onos/apache-karaf-3.0.5/data'
A R Karthickf2f4ca62016-08-17 10:34:08 -0700445 onos_gen_partitions = os.path.join(setup_dir, 'onos-gen-partitions')
A R Karthick2b93d6a2016-09-06 15:19:09 -0700446 onos_form_cluster = os.path.join(setup_dir, 'onos-form-cluster')
A.R Karthick95d044e2016-06-10 18:44:36 -0700447 cord_apps_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'apps')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700448 host_guest_map = ( (host_config_dir, guest_config_dir), )
A R Karthick2b93d6a2016-09-06 15:19:09 -0700449 cluster_cfg = os.path.join(host_config_dir, 'cluster.json')
450 cluster_mode = False
451 cluster_instances = []
Chetan Gaonker503032a2016-05-12 12:06:29 -0700452 NAME = 'cord-onos'
A R Karthickf2f4ca62016-08-17 10:34:08 -0700453 ##the ip of ONOS in default cluster.json in setup/onos-config
454 CLUSTER_CFG_IP = '172.17.0.2'
A R Karthick07608ef2016-08-23 16:51:19 -0700455 IMAGE = 'onosproject/onos'
456 TAG = 'latest'
457 PREFIX = ''
A R Karthickf2f4ca62016-08-17 10:34:08 -0700458
459 @classmethod
A R Karthick2b93d6a2016-09-06 15:19:09 -0700460 def generate_cluster_cfg(cls, ip):
461 if type(ip) in [ list, tuple ]:
462 ips = ' '.join(ip)
463 else:
464 ips = ip
A R Karthickf2f4ca62016-08-17 10:34:08 -0700465 try:
A R Karthick2b93d6a2016-09-06 15:19:09 -0700466 cmd = '{} {} {}'.format(cls.onos_gen_partitions, cls.cluster_cfg, ips)
467 os.system(cmd)
468 except: pass
469
470 @classmethod
471 def form_cluster(cls, ips):
472 nodes = ' '.join(ips)
473 try:
474 cmd = '{} {}'.format(cls.onos_form_cluster, nodes)
A R Karthickf2f4ca62016-08-17 10:34:08 -0700475 os.system(cmd)
476 except: pass
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700477
A R Karthick9d48c652016-09-15 09:16:36 -0700478 @classmethod
479 def cleanup_runtime(cls):
480 '''Cleanup ONOS runtime generated files'''
481 files = ( Onos.cluster_cfg, os.path.join(Onos.host_config_dir, 'network-cfg.json') )
482 for f in files:
483 if os.access(f, os.F_OK):
484 try:
485 os.unlink(f)
486 except: pass
487
A R Karthickec2db322016-11-17 15:06:01 -0800488 @classmethod
489 def get_data_map(cls, host_volume, guest_volume_dir):
490 host_volume_dir = os.path.join(cls.setup_dir, os.path.basename(host_volume))
491 if not os.path.exists(host_volume_dir):
492 os.mkdir(host_volume_dir)
493 return ( (host_volume_dir, guest_volume_dir), )
494
495 @classmethod
496 def remove_data_map(cls, host_volume, guest_volume_dir):
497 host_volume_dir = os.path.join(cls.setup_dir, os.path.basename(host_volume))
498 if os.path.exists(host_volume_dir):
499 rmtree(host_volume_dir)
500
501 def remove_data_volume(self):
502 if self.data_map is not None:
503 self.remove_data_map(*self.data_map)
504
A.R Karthick1700e0e2016-10-06 18:16:57 -0700505 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX, tag = TAG,
A R Karthickec2db322016-11-17 15:06:01 -0800506 boot_delay = 20, restart = False, network_cfg = None,
A R Karthick85eb1862017-01-23 16:10:57 -0800507 cluster = False, data_volume = None, async = False, quagga_config = None,
508 network = None):
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700509 if restart is True:
510 ##Find the right image to restart
511 running_image = filter(lambda c: c['Names'][0] == '/{}'.format(name), self.dckr.containers())
512 if running_image:
513 image_name = running_image[0]['Image']
514 try:
515 image = image_name.split(':')[0]
516 tag = image_name.split(':')[1]
517 except: pass
518
A R Karthickaa54a1c2016-12-15 11:42:08 -0800519 if quagga_config is None:
520 quagga_config = Onos.QUAGGA_CONFIG
521 super(Onos, self).__init__(name, image, prefix = prefix, tag = tag, quagga_config = quagga_config)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700522 self.boot_delay = boot_delay
A R Karthickec2db322016-11-17 15:06:01 -0800523 self.data_map = None
A R Karthickc69d73e2017-01-20 11:44:34 -0800524 instance_memory = (get_mem(jvm_heap_size = Onos.JVM_HEAP_SIZE, instances = Onos.MAX_INSTANCES),) * 2
525 self.env['JAVA_OPTS'] = self.JAVA_OPTS_FORMAT.format(*instance_memory)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700526 if cluster is True:
527 self.ports = []
A R Karthickec2db322016-11-17 15:06:01 -0800528 if data_volume is not None:
529 self.data_map = self.get_data_map(data_volume, self.guest_data_dir)
530 self.host_guest_map = self.host_guest_map + self.data_map
A R Karthick2b93d6a2016-09-06 15:19:09 -0700531 if os.access(self.cluster_cfg, os.F_OK):
532 try:
533 os.unlink(self.cluster_cfg)
534 except: pass
535
536 self.host_config = self.create_host_config(port_list = self.ports,
537 host_guest_map = self.host_guest_map)
538 self.volumes = []
539 for _,g in self.host_guest_map:
540 self.volumes.append(g)
541
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700542 if restart is True and self.exists():
543 self.kill()
A R Karthick2b93d6a2016-09-06 15:19:09 -0700544
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700545 if not self.exists():
546 self.remove_container(name, force=True)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700547 host_config = self.create_host_config(port_list = self.ports,
548 host_guest_map = self.host_guest_map)
549 volumes = []
550 for _,g in self.host_guest_map:
551 volumes.append(g)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700552 if network_cfg is not None:
A R Karthick81acbff2016-06-17 14:45:16 -0700553 json_data = json.dumps(network_cfg, indent=4)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700554 with open('{}/network-cfg.json'.format(self.host_config_dir), 'w') as f:
555 f.write(json_data)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800556 if cluster is False or async is False:
557 print('Starting ONOS container %s' %self.name)
558 self.start(ports = self.ports, environment = self.env,
559 host_config = self.host_config, volumes = self.volumes, tty = True)
560 if not restart:
561 ##wait a bit before fetching IP to regenerate cluster cfg
562 time.sleep(5)
563 ip = self.ip()
564 ##Just a quick hack/check to ensure we don't regenerate in the common case.
565 ##As ONOS is usually the first test container that is started
566 if cluster is False:
567 if ip != self.CLUSTER_CFG_IP or not os.access(self.cluster_cfg, os.F_OK):
568 print('Regenerating ONOS cluster cfg for ip %s' %ip)
569 self.generate_cluster_cfg(ip)
570 self.kill()
571 self.remove_container(self.name, force=True)
572 print('Restarting ONOS container %s' %self.name)
573 self.start(ports = self.ports, environment = self.env,
574 host_config = self.host_config, volumes = self.volumes, tty = True)
575 print('Waiting for ONOS to boot')
576 time.sleep(boot_delay)
577 self.wait_for_onos_start(self.ip())
578 self.running = True
579 else:
580 self.running = False
581 else:
582 self.running = True
583 if self.running:
584 self.ipaddr = self.ip()
585 if cluster is False:
586 self.install_cord_apps(self.ipaddr)
A R Karthick19aaf5c2016-11-09 17:47:57 -0800587
A.R Karthickc4e474d2016-12-12 15:24:57 -0800588 @classmethod
589 def get_quagga_config(cls, instance = 0):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800590 quagga_config = copy.deepcopy(cls.QUAGGA_CONFIG)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800591 if instance == 0:
592 return quagga_config
593 ip = quagga_config[0]['ip']
594 octets = ip.split('.')
A R Karthickaa54a1c2016-12-15 11:42:08 -0800595 octets[3] = str((int(octets[3]) + instance) & 255)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800596 ip = '.'.join(octets)
597 quagga_config[0]['ip'] = ip
598 return quagga_config
599
600 @classmethod
601 def start_cluster_async(cls, onos_instances):
602 instances = filter(lambda o: o.running == False, onos_instances)
603 if not instances:
604 return
605 tpool = ThreadPool(len(instances), queue_size = 1, wait_timeout = 1)
606 for onos in instances:
607 tpool.addTask(onos.start_async)
608 tpool.cleanUpThreads()
609
610 def start_async(self):
611 print('Starting ONOS container %s' %self.name)
612 self.start(ports = self.ports, environment = self.env,
613 host_config = self.host_config, volumes = self.volumes, tty = True)
614 time.sleep(3)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700615 self.ipaddr = self.ip()
A.R Karthickc4e474d2016-12-12 15:24:57 -0800616 print('Waiting for ONOS container %s to start' %self.name)
617 self.wait_for_onos_start(self.ipaddr)
618 self.running = True
619 print('ONOS container %s started' %self.name)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700620
A R Karthick2b93d6a2016-09-06 15:19:09 -0700621 @classmethod
A R Karthick19aaf5c2016-11-09 17:47:57 -0800622 def wait_for_onos_start(cls, ip, tries = 30):
623 onos_log = OnosLog(host = ip)
624 num_tries = 0
625 started = None
626 while not started and num_tries < tries:
627 time.sleep(3)
628 started = onos_log.search_log_pattern('ApplicationManager .* Started')
629 num_tries += 1
630
A R Karthick19aaf5c2016-11-09 17:47:57 -0800631 if not started:
632 print('ONOS did not start')
633 else:
634 print('ONOS started')
635 return started
636
637 @classmethod
A R Karthick2b93d6a2016-09-06 15:19:09 -0700638 def setup_cluster_deprecated(cls, onos_instances, image_name = None):
639 if not onos_instances or len(onos_instances) < 2:
640 return
641 ips = []
642 if image_name is not None:
643 ips = Container.ips(image_name)
644 else:
645 for onos in onos_instances:
646 ips.append(onos.ipaddr)
647 Onos.cluster_instances = onos_instances
648 Onos.cluster_mode = True
649 ##regenerate the cluster json with the 3 instance ips before restarting them back
650 print('Generating cluster cfg for ONOS instances with ips %s' %ips)
651 Onos.generate_cluster_cfg(ips)
652 for onos in onos_instances:
653 onos.kill()
654 onos.remove_container(onos.name, force=True)
655 print('Restarting ONOS container %s for forming cluster' %onos.name)
656 onos.start(ports = onos.ports, environment = onos.env,
657 host_config = onos.host_config, volumes = onos.volumes, tty = True)
658 print('Waiting %d seconds for ONOS %s to boot' %(onos.boot_delay, onos.name))
659 time.sleep(onos.boot_delay)
660 onos.ipaddr = onos.ip()
661 onos.install_cord_apps(onos.ipaddr)
662
663 @classmethod
664 def setup_cluster(cls, onos_instances, image_name = None):
665 if not onos_instances or len(onos_instances) < 2:
666 return
667 ips = []
668 if image_name is not None:
669 ips = Container.ips(image_name)
670 else:
671 for onos in onos_instances:
672 ips.append(onos.ipaddr)
673 Onos.cluster_instances = onos_instances
674 Onos.cluster_mode = True
675 ##regenerate the cluster json with the 3 instance ips before restarting them back
676 print('Forming cluster for ONOS instances with ips %s' %ips)
677 Onos.form_cluster(ips)
678 ##wait for the cluster to be formed
679 print('Waiting for the cluster to be formed')
680 time.sleep(60)
681 for onos in onos_instances:
682 onos.install_cord_apps(onos.ipaddr)
683
684 @classmethod
A R Karthicke2c24bd2016-10-07 14:51:38 -0700685 def add_cluster(cls, count = 1, network_cfg = None):
686 if not cls.cluster_instances or Onos.cluster_mode is False:
687 return
688 for i in range(count):
689 name = '{}-{}'.format(Onos.NAME, len(cls.cluster_instances)+1)
690 onos = cls(name = name, image = Onos.IMAGE, tag = Onos.TAG, prefix = Container.IMAGE_PREFIX,
691 cluster = True, network_cfg = network_cfg)
692 cls.cluster_instances.append(onos)
693
694 cls.setup_cluster(cls.cluster_instances)
695
696 @classmethod
A.R Karthick2560f042016-11-30 14:38:52 -0800697 def restart_cluster(cls, network_cfg = None, timeout = 10, setup = False):
A R Karthick2b93d6a2016-09-06 15:19:09 -0700698 if cls.cluster_mode is False:
699 return
700 if not cls.cluster_instances:
701 return
702
703 if network_cfg is not None:
704 json_data = json.dumps(network_cfg, indent=4)
705 with open('{}/network-cfg.json'.format(cls.host_config_dir), 'w') as f:
706 f.write(json_data)
707
A.R Karthick2560f042016-11-30 14:38:52 -0800708 cls.cleanup_cluster()
709 if timeout > 0:
710 time.sleep(timeout)
711
A R Karthickaa54a1c2016-12-15 11:42:08 -0800712 #start the instances asynchronously
713 cls.start_cluster_async(cls.cluster_instances)
714 time.sleep(5)
A.R Karthick2560f042016-11-30 14:38:52 -0800715 ##form the cluster as appropriate
716 if setup is True:
717 cls.setup_cluster(cls.cluster_instances)
A R Karthickaa54a1c2016-12-15 11:42:08 -0800718 else:
719 for onos in cls.cluster_instances:
720 onos.install_cord_apps(onos.ipaddr)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700721
722 @classmethod
723 def cluster_ips(cls):
724 if cls.cluster_mode is False:
725 return []
726 if not cls.cluster_instances:
727 return []
728 ips = [ onos.ipaddr for onos in cls.cluster_instances ]
729 return ips
730
731 @classmethod
732 def cleanup_cluster(cls):
733 if cls.cluster_mode is False:
734 return
735 if not cls.cluster_instances:
736 return
737 for onos in cls.cluster_instances:
738 if onos.exists():
739 onos.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800740 onos.running = False
A R Karthick2b93d6a2016-09-06 15:19:09 -0700741 onos.remove_container(onos.name, force=True)
A R Karthickd44cea12016-07-20 12:16:41 -0700742
A.R Karthick95d044e2016-06-10 18:44:36 -0700743 @classmethod
A R Karthickde6b9dc2016-11-29 17:46:16 -0800744 def restart_node(cls, node = None, network_cfg = None, timeout = 10):
A R Karthick889d9652016-10-03 14:13:45 -0700745 if node is None:
746 cls(restart = True, network_cfg = network_cfg, image = cls.IMAGE, tag = cls.TAG)
747 else:
748 #Restarts a node in the cluster
749 valid_node = filter(lambda onos: node in [ onos.ipaddr, onos.name ], cls.cluster_instances)
750 if valid_node:
751 onos = valid_node.pop()
752 if onos.exists():
753 onos.kill()
754 onos.remove_container(onos.name, force=True)
A R Karthickde6b9dc2016-11-29 17:46:16 -0800755 if timeout > 0:
756 time.sleep(timeout)
A R Karthick889d9652016-10-03 14:13:45 -0700757 print('Restarting ONOS container %s' %onos.name)
758 onos.start(ports = onos.ports, environment = onos.env,
759 host_config = onos.host_config, volumes = onos.volumes, tty = True)
A R Karthick889d9652016-10-03 14:13:45 -0700760 onos.ipaddr = onos.ip()
A.R Karthick2560f042016-11-30 14:38:52 -0800761 onos.wait_for_onos_start(onos.ipaddr)
762 onos.install_cord_apps(onos.ipaddr)
A R Karthick889d9652016-10-03 14:13:45 -0700763
764 @classmethod
A R Karthickeaf1c4e2016-07-19 12:22:35 -0700765 def install_cord_apps(cls, onos_ip = None):
A.R Karthick95d044e2016-06-10 18:44:36 -0700766 for app, version in cls.onos_cord_apps:
767 app_file = '{}/{}-{}.oar'.format(cls.cord_apps_dir, app, version)
A R Karthickeaf1c4e2016-07-19 12:22:35 -0700768 ok, code = OnosCtrl.install_app(app_file, onos_ip = onos_ip)
A.R Karthick95d044e2016-06-10 18:44:36 -0700769 ##app already installed (conflicts)
770 if code in [ 409 ]:
771 ok = True
772 print('ONOS app %s, version %s %s' %(app, version, 'installed' if ok else 'failed to install'))
773 time.sleep(2)
774
A.R Karthick1700e0e2016-10-06 18:16:57 -0700775class OnosStopWrapper(Container):
776 def __init__(self, name):
777 super(OnosStopWrapper, self).__init__(name, Onos.IMAGE, tag = Onos.TAG, prefix = Container.IMAGE_PREFIX)
778 if self.exists():
779 self.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800780 self.running = False
A.R Karthick1700e0e2016-10-06 18:16:57 -0700781 else:
782 if Onos.cluster_mode is True:
783 valid_node = filter(lambda onos: name in [ onos.ipaddr, onos.name ], Onos.cluster_instances)
784 if valid_node:
785 onos = valid_node.pop()
786 if onos.exists():
787 onos.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800788 onos.running = False
A.R Karthick1700e0e2016-10-06 18:16:57 -0700789
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700790class Radius(Container):
791 ports = [ 1812, 1813 ]
A R Karthick41adfce2016-06-10 09:51:25 -0700792 env = {'TIMEZONE':'America/Los_Angeles',
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700793 'DEBUG': 'true', 'cert_password':'whatever', 'primary_shared_secret':'radius_password'
794 }
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700795 host_db_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/db')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700796 guest_db_dir = os.path.join(os.path.sep, 'opt', 'db')
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700797 host_config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/freeradius')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700798 guest_config_dir = os.path.join(os.path.sep, 'etc', 'freeradius')
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700799 start_command = os.path.join(guest_config_dir, 'start-radius.py')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700800 host_guest_map = ( (host_db_dir, guest_db_dir),
801 (host_config_dir, guest_config_dir)
802 )
Chetan Gaonker503032a2016-05-12 12:06:29 -0700803 IMAGE = 'cord-test/radius'
804 NAME = 'cord-radius'
805
A R Karthick07608ef2016-08-23 16:51:19 -0700806 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = 'candidate',
A R Karthick85eb1862017-01-23 16:10:57 -0800807 boot_delay = 10, restart = False, update = False, network = None):
A R Karthick07608ef2016-08-23 16:51:19 -0700808 super(Radius, self).__init__(name, image, prefix = prefix, tag = tag, command = self.start_command)
Chetan Gaonker503032a2016-05-12 12:06:29 -0700809 if update is True or not self.img_exists():
A R Karthick07608ef2016-08-23 16:51:19 -0700810 self.build_image(self.image_name)
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700811 if restart is True and self.exists():
812 self.kill()
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700813 if not self.exists():
814 self.remove_container(name, force=True)
815 host_config = self.create_host_config(port_list = self.ports,
816 host_guest_map = self.host_guest_map)
817 volumes = []
818 for _,g in self.host_guest_map:
819 volumes.append(g)
A R Karthick41adfce2016-06-10 09:51:25 -0700820 self.start(ports = self.ports, environment = self.env,
821 volumes = volumes,
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700822 host_config = host_config, tty = True)
A R Karthick85eb1862017-01-23 16:10:57 -0800823 if network is not None:
824 Container.connect_to_network(self.name, network)
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700825 time.sleep(boot_delay)
826
827 @classmethod
828 def build_image(cls, image):
829 print('Building Radius image %s' %image)
830 dockerfile = '''
831FROM hbouvier/docker-radius
832MAINTAINER chetan@ciena.com
833LABEL RUN docker pull hbouvier/docker-radius
834LABEL RUN docker run -it --name cord-radius hbouvier/docker-radius
A R Karthickc762df42016-05-25 10:09:21 -0700835RUN apt-get update && \
836 apt-get -y install python python-pexpect strace
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700837WORKDIR /root
838CMD ["/etc/freeradius/start-radius.py"]
839'''
840 super(Radius, cls).build_image(dockerfile, image)
841 print('Done building image %s' %image)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700842
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700843class Quagga(Container):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800844 QUAGGA_CONFIG = ( { 'bridge' : 'quagga-br', 'ip': '10.10.0.3', 'mask' : 16 },
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700845 { 'bridge' : 'quagga-br', 'ip': '192.168.10.3', 'mask': 16 },
846 )
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700847 ports = [ 179, 2601, 2602, 2603, 2604, 2605, 2606 ]
848 host_quagga_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/quagga-config')
849 guest_quagga_config = '/root/config'
850 quagga_config_file = os.path.join(guest_quagga_config, 'testrib.conf')
851 host_guest_map = ( (host_quagga_config, guest_quagga_config), )
Chetan Gaonker503032a2016-05-12 12:06:29 -0700852 IMAGE = 'cord-test/quagga'
853 NAME = 'cord-quagga'
854
A R Karthick07608ef2016-08-23 16:51:19 -0700855 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = 'candidate',
A R Karthick85eb1862017-01-23 16:10:57 -0800856 boot_delay = 15, restart = False, config_file = quagga_config_file, update = False,
857 network = None):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800858 super(Quagga, self).__init__(name, image, prefix = prefix, tag = tag, quagga_config = self.QUAGGA_CONFIG)
Chetan Gaonker503032a2016-05-12 12:06:29 -0700859 if update is True or not self.img_exists():
A R Karthick07608ef2016-08-23 16:51:19 -0700860 self.build_image(self.image_name)
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700861 if restart is True and self.exists():
862 self.kill()
863 if not self.exists():
864 self.remove_container(name, force=True)
A R Karthick41adfce2016-06-10 09:51:25 -0700865 host_config = self.create_host_config(port_list = self.ports,
866 host_guest_map = self.host_guest_map,
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700867 privileged = True)
868 volumes = []
869 for _,g in self.host_guest_map:
870 volumes.append(g)
871 self.start(ports = self.ports,
A R Karthick41adfce2016-06-10 09:51:25 -0700872 host_config = host_config,
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700873 volumes = volumes, tty = True)
A R Karthick85eb1862017-01-23 16:10:57 -0800874 if network is not None:
875 Container.connect_to_network(self.name, network)
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700876 print('Starting Quagga on container %s' %self.name)
877 self.execute('{0}/start.sh {1}'.format(self.guest_quagga_config, config_file))
878 time.sleep(boot_delay)
879
880 @classmethod
881 def build_image(cls, image):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800882 onos_quagga_ip = Onos.QUAGGA_CONFIG[0]['ip']
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700883 print('Building Quagga image %s' %image)
884 dockerfile = '''
A R Karthick41adfce2016-06-10 09:51:25 -0700885FROM ubuntu:14.04
886MAINTAINER chetan@ciena.com
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700887WORKDIR /root
888RUN useradd -M quagga
889RUN mkdir /var/log/quagga && chown quagga:quagga /var/log/quagga
890RUN mkdir /var/run/quagga && chown quagga:quagga /var/run/quagga
A R Karthick973ea692016-10-17 12:23:02 -0700891RUN 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 -0700892RUN git clone git://git.savannah.nongnu.org/quagga.git quagga && \
A R Karthick8f69c2c2016-10-21 11:43:26 -0700893(cd quagga && git checkout quagga-1.0.20160315 && ./bootstrap.sh && \
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700894sed -i -r 's,htonl.*?\(INADDR_LOOPBACK\),inet_addr\("{0}"\),g' zebra/zebra_fpm.c && \
895./configure --enable-fpm --disable-doc --localstatedir=/var/run/quagga && make && make install)
896RUN ldconfig
897'''.format(onos_quagga_ip)
898 super(Quagga, cls).build_image(dockerfile, image)
899 print('Done building image %s' %image)
A R Karthick81acbff2016-06-17 14:45:16 -0700900
A.R Karthick1700e0e2016-10-06 18:16:57 -0700901class QuaggaStopWrapper(Container):
902 def __init__(self, name = Quagga.NAME, image = Quagga.IMAGE, tag = 'candidate'):
903 super(QuaggaStopWrapper, self).__init__(name, image, prefix = Container.IMAGE_PREFIX, tag = tag)
904 if self.exists():
905 self.kill()
906
907
A R Karthick81acbff2016-06-17 14:45:16 -0700908def reinitContainerClients():
909 docker_netns.dckr = Client()
910 Container.dckr = Client()
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700911
912class Xos(Container):
913 setup_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup')
914 TAG = 'latest'
915 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -0700916 host_guest_map = None
917 env = None
918 ports = None
919 volumes = None
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700920
A R Karthick6e80afd2016-10-10 16:03:12 -0700921 @classmethod
922 def get_cmd(cls, img_name):
923 cmd = cls.dckr.inspect_image(img_name)['Config']['Cmd']
924 return ' '.join(cmd)
925
A R Karthicke3bde962016-09-27 15:06:35 -0700926 def __init__(self, name, image, prefix = PREFIX, tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -0700927 boot_delay = 20, restart = False, network_cfg = None, update = False):
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700928 if restart is True:
929 ##Find the right image to restart
930 running_image = filter(lambda c: c['Names'][0] == '/{}'.format(name), self.dckr.containers())
931 if running_image:
932 image_name = running_image[0]['Image']
933 try:
934 image = image_name.split(':')[0]
935 tag = image_name.split(':')[1]
936 except: pass
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700937 super(Xos, self).__init__(name, image, prefix = prefix, tag = tag)
938 if update is True or not self.img_exists():
939 self.build_image(self.image_name)
A R Karthick6e80afd2016-10-10 16:03:12 -0700940 self.command = self.get_cmd(self.image_name).strip() or None
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700941 if restart is True and self.exists():
942 self.kill()
943 if not self.exists():
944 self.remove_container(name, force=True)
A R Karthicke3bde962016-09-27 15:06:35 -0700945 host_config = self.create_host_config(port_list = self.ports,
946 host_guest_map = self.host_guest_map,
947 privileged = True)
948 print('Starting XOS container %s' %self.name)
949 self.start(ports = self.ports, environment = self.env, host_config = host_config,
950 volumes = self.volumes, tty = True)
951 print('Waiting %d seconds for XOS Base Container to boot' %(boot_delay))
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700952 time.sleep(boot_delay)
953
954 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -0700955 def build_image(cls, image, dockerfile_path, image_target = 'build'):
956 cmd = 'cd {} && make {}'.format(dockerfile_path, image_target)
957 print('Building XOS %s' %image)
958 res = os.system(cmd)
959 print('Done building image %s. Image build %s' %(image, 'successful' if res == 0 else 'failed'))
960 return res
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700961
A R Karthicke3bde962016-09-27 15:06:35 -0700962class XosServer(Xos):
963 ports = [8000,9998,9999]
964 NAME = 'xos-server'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700965 IMAGE = 'xosproject/xos'
A R Karthicke3bde962016-09-27 15:06:35 -0700966 BASE_IMAGE = 'xosproject/xos-base'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700967 TAG = 'latest'
968 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -0700969 dockerfile_path = os.path.join(Xos.setup_dir, 'xos')
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700970
A R Karthicke3bde962016-09-27 15:06:35 -0700971 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX, tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -0700972 boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -0700973 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700974
975 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -0700976 def build_image(cls, image = IMAGE):
977 ##build the base image and then build the server image
978 Xos.build_image(cls.BASE_IMAGE, cls.dockerfile_path, image_target = 'base')
979 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700980
A R Karthicke3bde962016-09-27 15:06:35 -0700981class XosSynchronizerOpenstack(Xos):
982 ports = [2375,]
983 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer')
984 NAME = 'xos-synchronizer'
985 IMAGE = 'xosproject/xos-synchronizer-openstack'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700986 TAG = 'latest'
987 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -0700988 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700989
A R Karthicke3bde962016-09-27 15:06:35 -0700990 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -0700991 tag = TAG, boot_delay = 20, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -0700992 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700993
994 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -0700995 def build_image(cls, image = IMAGE):
996 XosServer.build_image()
997 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700998
A R Karthicke3bde962016-09-27 15:06:35 -0700999class XosSynchronizerOnboarding(Xos):
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001000 NAME = 'xos-synchronizer-onboarding'
1001 IMAGE = 'xosproject/xos-synchronizer-onboarding'
1002 TAG = 'latest'
1003 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -07001004 dockerfile_path = os.path.join(Xos.setup_dir, 'onboarding_synchronizer')
1005 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001006
A R Karthicke3bde962016-09-27 15:06:35 -07001007 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -07001008 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001009 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001010
1011 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -07001012 def build_image(cls, image = IMAGE):
1013 XosSynchronizerOpenstack.build_image()
1014 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001015
A R Karthicke3bde962016-09-27 15:06:35 -07001016class XosSynchronizerOpenvpn(Xos):
1017 NAME = 'xos-synchronizer-openvpn'
1018 IMAGE = 'xosproject/xos-openvpn'
1019 TAG = 'latest'
1020 PREFIX = ''
1021 dockerfile_path = os.path.join(Xos.setup_dir, 'openvpn')
1022 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001023
A R Karthicke3bde962016-09-27 15:06:35 -07001024 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -07001025 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001026 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1027
1028 @classmethod
1029 def build_image(cls, image = IMAGE):
1030 XosSynchronizerOpenstack.build_image()
1031 Xos.build_image(image, cls.dockerfile_path)
1032
1033class XosPostgresql(Xos):
1034 ports = [5432,]
1035 NAME = 'xos-db-postgres'
1036 IMAGE = 'xosproject/xos-postgres'
1037 TAG = 'latest'
1038 PREFIX = ''
1039 volumes = ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
1040 dockerfile_path = os.path.join(Xos.setup_dir, 'postgresql')
1041
1042 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)
1045
1046 @classmethod
1047 def build_image(cls, image = IMAGE):
1048 Xos.build_image(image, cls.dockerfile_path)
1049
1050class XosSyndicateMs(Xos):
1051 ports = [8080,]
1052 env = None
1053 NAME = 'xos-syndicate-ms'
1054 IMAGE = 'xosproject/syndicate-ms'
1055 TAG = 'latest'
1056 PREFIX = ''
1057 dockerfile_path = os.path.join(Xos.setup_dir, 'syndicate-ms')
1058
1059 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001060 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 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001066
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001067class XosSyncVtn(Xos):
1068 ports = [8080,]
1069 env = None
1070 NAME = 'xos-synchronizer-vtn'
1071 IMAGE = 'xosproject/xos-synchronizer-vtn'
1072 TAG = 'latest'
1073 PREFIX = ''
1074 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vtn')
1075
1076 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001077 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001078 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1079
1080 @classmethod
1081 def build_image(cls, image = IMAGE):
1082 Xos.build_image(image, cls.dockerfile_path)
1083
1084class XosSyncVtr(Xos):
1085 ports = [8080,]
1086 env = None
1087 NAME = 'xos-synchronizer-vtr'
1088 IMAGE = 'xosproject/xos-synchronizer-vtr'
1089 TAG = 'latest'
1090 PREFIX = ''
1091 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vtr')
1092
1093 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001094 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001095 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1096
1097 @classmethod
1098 def build_image(cls, image = IMAGE):
1099 Xos.build_image(image, cls.dockerfile_path)
1100
1101class XosSyncVsg(Xos):
1102 ports = [8080,]
1103 env = None
1104 NAME = 'xos-synchronizer-vsg'
1105 IMAGE = 'xosproject/xos-synchronizer-vsg'
1106 TAG = 'latest'
1107 PREFIX = ''
1108 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vsg')
1109
1110 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001111 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001112 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1113
1114 @classmethod
1115 def build_image(cls, image = IMAGE):
1116 Xos.build_image(image, cls.dockerfile_path)
1117
1118
1119class XosSyncOnos(Xos):
1120 ports = [8080,]
1121 env = None
1122 NAME = 'xos-synchronizer-onos'
1123 IMAGE = 'xosproject/xos-synchronizer-onos'
1124 TAG = 'latest'
1125 PREFIX = ''
1126 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-onos')
1127
1128 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001129 boot_delay = 30, 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 XosSyncFabric(Xos):
1137 ports = [8080,]
1138 env = None
1139 NAME = 'xos-synchronizer-fabric'
1140 IMAGE = 'xosproject/xos-synchronizer-fabric'
1141 TAG = 'latest'
1142 PREFIX = ''
1143 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-fabric')
1144
1145 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001146 boot_delay = 30, 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)
A R Karthick19aaf5c2016-11-09 17:47:57 -08001152
1153if __name__ == '__main__':
1154 onos = Onos(boot_delay = 10, restart = True)