blob: eb202942707b901fafbb89306485262179f6c41d [file] [log] [blame]
Matteo Scandolo48d3d2d2017-08-08 13:05:27 -07001
2# Copyright 2017-present Open Networking Foundation
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
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# 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
16
A R Karthick41adfce2016-06-10 09:51:25 -070017#
Chetan Gaonkercfcce782016-05-10 10:10:42 -070018# Copyright 2016-present Ciena Corporation
19#
20# Licensed under the Apache License, Version 2.0 (the "License");
21# you may not use this file except in compliance with the License.
22# You may obtain a copy of the License at
A R Karthick41adfce2016-06-10 09:51:25 -070023#
Chetan Gaonkercfcce782016-05-10 10:10:42 -070024# http://www.apache.org/licenses/LICENSE-2.0
A R Karthick41adfce2016-06-10 09:51:25 -070025#
Chetan Gaonkercfcce782016-05-10 10:10:42 -070026# Unless required by applicable law or agreed to in writing, software
27# distributed under the License is distributed on an "AS IS" BASIS,
28# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29# See the License for the specific language governing permissions and
30# limitations under the License.
31#
Chetan Gaonker3533faa2016-04-25 17:50:14 -070032import os,time
33import io
34import json
A R Karthickd44cea12016-07-20 12:16:41 -070035import yaml
A.R Karthickc4e474d2016-12-12 15:24:57 -080036import errno
A R Karthickaa54a1c2016-12-15 11:42:08 -080037import copy
Chetan Gaonker3533faa2016-04-25 17:50:14 -070038from pyroute2 import IPRoute
A.R Karthickc4e474d2016-12-12 15:24:57 -080039from pyroute2.netlink import NetlinkError
Chetan Gaonker3533faa2016-04-25 17:50:14 -070040from itertools import chain
41from nsenter import Namespace
A R Karthick6f2ac6f2017-07-26 12:55:24 -070042try:
43 from docker import APIClient as Client
44except:
45 from docker import Client
A R Karthick85eb1862017-01-23 16:10:57 -080046from docker import utils as dockerutils
A.R Karthickf184b342017-01-27 19:30:50 -080047import shutil
A.R Karthick95d044e2016-06-10 18:44:36 -070048from OnosCtrl import OnosCtrl
A R Karthick19aaf5c2016-11-09 17:47:57 -080049from OnosLog import OnosLog
A R Karthick03bd2812017-03-03 17:49:17 -080050from onosclidriver import OnosCliDriver
A.R Karthickc4e474d2016-12-12 15:24:57 -080051from threadPool import ThreadPool
A R Karthickaa54a1c2016-12-15 11:42:08 -080052from threading import Lock
Chetan Gaonker3533faa2016-04-25 17:50:14 -070053
54class docker_netns(object):
55
56 dckr = Client()
57 def __init__(self, name):
58 pid = int(self.dckr.inspect_container(name)['State']['Pid'])
59 if pid == 0:
60 raise Exception('no container named {0}'.format(name))
61 self.pid = pid
62
63 def __enter__(self):
64 pid = self.pid
65 if not os.path.exists('/var/run/netns'):
66 os.mkdir('/var/run/netns')
67 os.symlink('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(pid))
68 return str(pid)
69
70 def __exit__(self, type, value, traceback):
71 pid = self.pid
72 os.unlink('/var/run/netns/{0}'.format(pid))
73
74flatten = lambda l: chain.from_iterable(l)
75
76class Container(object):
77 dckr = Client()
A R Karthick07608ef2016-08-23 16:51:19 -070078 IMAGE_PREFIX = '' ##for saving global prefix for all test classes
A R Karthickaa54a1c2016-12-15 11:42:08 -080079 CONFIG_LOCK = Lock()
A R Karthick07608ef2016-08-23 16:51:19 -070080
81 def __init__(self, name, image, prefix='', tag = 'candidate', command = 'bash', quagga_config = None):
Chetan Gaonker3533faa2016-04-25 17:50:14 -070082 self.name = name
A R Karthick07608ef2016-08-23 16:51:19 -070083 self.prefix = prefix
84 if prefix:
85 self.prefix += '/'
86 image = '{}{}'.format(self.prefix, image)
Chetan Gaonker3533faa2016-04-25 17:50:14 -070087 self.image = image
88 self.tag = tag
A R Karthickd44cea12016-07-20 12:16:41 -070089 if tag:
90 self.image_name = image + ':' + tag
91 else:
92 self.image_name = image
Chetan Gaonker3533faa2016-04-25 17:50:14 -070093 self.id = None
94 self.command = command
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -070095 self.quagga_config = quagga_config
Chetan Gaonker3533faa2016-04-25 17:50:14 -070096
97 @classmethod
98 def build_image(cls, dockerfile, tag, force=True, nocache=False):
99 f = io.BytesIO(dockerfile.encode('utf-8'))
100 if force or not cls.image_exists(tag):
101 print('Build {0}...'.format(tag))
102 for line in cls.dckr.build(fileobj=f, rm=True, tag=tag, decode=True, nocache=nocache):
103 if 'stream' in line:
104 print(line['stream'].strip())
105
106 @classmethod
107 def image_exists(cls, name):
A R Karthicke07fc3a2017-02-27 10:49:29 -0800108 #return name in [ctn['RepoTags'][0] for ctn in cls.dckr.images()]
109 return name in list( flatten(ctn['RepoTags'] if ctn['RepoTags'] else '' for ctn in cls.dckr.images()) )
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700110
111 @classmethod
112 def create_host_config(cls, port_list = None, host_guest_map = None, privileged = False):
113 port_bindings = None
114 binds = None
115 if port_list:
116 port_bindings = {}
117 for p in port_list:
A R Karthick184945a2017-07-25 17:23:57 -0700118 if type(p) is tuple:
119 port_bindings[str(p[0])] = str(p[1])
120 else:
121 port_bindings[str(p)] = str(p)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700122
123 if host_guest_map:
124 binds = []
125 for h, g in host_guest_map:
126 binds.append('{0}:{1}'.format(h, g))
127
128 return cls.dckr.create_host_config(binds = binds, port_bindings = port_bindings, privileged = privileged)
129
130 @classmethod
A R Karthick85eb1862017-01-23 16:10:57 -0800131 def connect_to_network(cls, name, network):
132 try:
133 cls.dckr.connect_container_to_network(name, network)
A R Karthick85eb1862017-01-23 16:10:57 -0800134 except:
A R Karthick1555c7c2017-09-07 14:59:41 -0700135 connect_cmd = 'docker network connect %s %s' %(network, name)
136 os.system(connect_cmd)
137 return True
A R Karthick85eb1862017-01-23 16:10:57 -0800138
139 @classmethod
140 def create_network(cls, network, subnet = None, gateway = None):
141 ipam_config = None
142 if subnet is not None and gateway is not None:
A R Karthick1555c7c2017-09-07 14:59:41 -0700143 try:
144 ipam_pool = dockerutils.create_ipam_pool(subnet = subnet, gateway = gateway)
145 ipam_config = dockerutils.create_ipam_config(pool_configs = [ipam_pool])
146 cls.dckr.create_network(network, driver='bridge', ipam = ipam_config)
147 except:
148 create_cmd = 'docker network create %s --subnet %s --gateway %s >/dev/null 2>&1' %(network, subnet, gateway)
149 os.system(create_cmd)
A R Karthick85eb1862017-01-23 16:10:57 -0800150
151 @classmethod
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700152 def cleanup(cls, image):
A R Karthick09b1f4e2016-05-12 14:31:50 -0700153 cnt_list = filter(lambda c: c['Image'] == image, cls.dckr.containers(all=True))
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700154 for cnt in cnt_list:
155 print('Cleaning container %s' %cnt['Id'])
A.R Karthick95d044e2016-06-10 18:44:36 -0700156 if cnt.has_key('State') and cnt['State'] == 'running':
A R Karthick09b1f4e2016-05-12 14:31:50 -0700157 cls.dckr.kill(cnt['Id'])
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700158 cls.dckr.remove_container(cnt['Id'], force=True)
159
160 @classmethod
161 def remove_container(cls, name, force=True):
162 try:
163 cls.dckr.remove_container(name, force = force)
164 except: pass
165
166 def exists(self):
167 return '/{0}'.format(self.name) in list(flatten(n['Names'] for n in self.dckr.containers()))
168
169 def img_exists(self):
A R Karthicke07fc3a2017-02-27 10:49:29 -0800170 #return self.image_name in [ctn['RepoTags'][0] if ctn['RepoTags'] else '' for ctn in self.dckr.images()]
171 return self.image_name in list( flatten(ctn['RepoTags'] if ctn['RepoTags'] else '' for ctn in self.dckr.images()) )
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700172
A R Karthick75844572017-01-23 16:57:44 -0800173 def ip(self, network = None):
A R Karthick2b93d6a2016-09-06 15:19:09 -0700174 cnt_list = filter(lambda c: c['Names'][0] == '/{}'.format(self.name), self.dckr.containers())
175 #if not cnt_list:
176 # cnt_list = filter(lambda c: c['Image'] == self.image_name, self.dckr.containers())
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700177 cnt_settings = cnt_list.pop()
A R Karthick75844572017-01-23 16:57:44 -0800178 if network is not None and cnt_settings['NetworkSettings']['Networks'].has_key(network):
179 return cnt_settings['NetworkSettings']['Networks'][network]['IPAddress']
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700180 return cnt_settings['NetworkSettings']['Networks']['bridge']['IPAddress']
181
A R Karthick2b93d6a2016-09-06 15:19:09 -0700182 @classmethod
183 def ips(cls, image_name):
184 cnt_list = filter(lambda c: c['Image'] == image_name, cls.dckr.containers())
185 ips = [ cnt['NetworkSettings']['Networks']['bridge']['IPAddress'] for cnt in cnt_list ]
186 return ips
187
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700188 def kill(self, remove = True):
189 self.dckr.kill(self.name)
190 self.dckr.remove_container(self.name, force=True)
191
A R Karthick41adfce2016-06-10 09:51:25 -0700192 def start(self, rm = True, ports = None, volumes = None, host_config = None,
A R Karthick1555c7c2017-09-07 14:59:41 -0700193 environment = None, tty = False, stdin_open = True,
194 network_disabled = False, network = None):
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700195
196 if rm and self.exists():
197 print('Removing container:', self.name)
198 self.dckr.remove_container(self.name, force=True)
199
A R Karthick41adfce2016-06-10 09:51:25 -0700200 ctn = self.dckr.create_container(image=self.image_name, ports = ports, command=self.command,
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700201 detach=True, name=self.name,
A R Karthick41adfce2016-06-10 09:51:25 -0700202 environment = environment,
203 volumes = volumes,
A R Karthick1555c7c2017-09-07 14:59:41 -0700204 host_config = host_config, stdin_open=stdin_open, tty = tty,
205 network_disabled = network_disabled)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700206 self.dckr.start(container=self.name)
A R Karthick1555c7c2017-09-07 14:59:41 -0700207 if network_disabled is False:
208 if network is not None:
209 self.connect_to_network(self.name, network)
210 if self.quagga_config:
211 self.connect_to_br(index = 1)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700212 self.id = ctn['Id']
213 return ctn
214
Thangavelu K Sef6f0a52016-12-14 19:57:05 +0000215 @classmethod
216 def pause_container(cls, image, delay):
217 cnt_list = filter(lambda c: c['Image'] == image, cls.dckr.containers(all=True))
218 for cnt in cnt_list:
219 print('Pause the container %s' %cnt['Id'])
220 if cnt.has_key('State') and cnt['State'] == 'running':
221 cls.dckr.pause(cnt['Id'])
222 if delay != 0:
223 time.sleep(delay)
224 for cnt in cnt_list:
225 print('Unpause the container %s' %cnt['Id'])
226 cls.dckr.unpause(cnt['Id'])
227 else:
228 print('Infinity time pause the container %s' %cnt['Id'])
229 return 'success'
230
A R Karthick52414732017-01-31 09:59:47 -0800231 def connect_to_br(self, index = 0):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800232 self.CONFIG_LOCK.acquire()
233 try:
234 with docker_netns(self.name) as pid:
235 for quagga_config in self.quagga_config:
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700236 ip = IPRoute()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800237 br = ip.link_lookup(ifname=quagga_config['bridge'])
238 if len(br) == 0:
239 try:
240 ip.link_create(ifname=quagga_config['bridge'], kind='bridge')
241 except NetlinkError as e:
242 err, _ = e.args
243 if err == errno.EEXIST:
244 pass
245 else:
246 raise NetlinkError(*e.args)
247 br = ip.link_lookup(ifname=quagga_config['bridge'])
248 br = br[0]
249 ip.link('set', index=br, state='up')
A R Karthick52414732017-01-31 09:59:47 -0800250 ifname = '{0}-{1}'.format(self.name[:12], index)
A R Karthickaa54a1c2016-12-15 11:42:08 -0800251 ifs = ip.link_lookup(ifname=ifname)
252 if len(ifs) > 0:
253 ip.link_remove(ifs[0])
254 peer_ifname = '{0}-{1}'.format(pid, index)
255 ip.link_create(ifname=ifname, kind='veth', peer=peer_ifname)
256 host = ip.link_lookup(ifname=ifname)[0]
257 ip.link('set', index=host, master=br)
258 ip.link('set', index=host, state='up')
259 guest = ip.link_lookup(ifname=peer_ifname)[0]
260 ip.link('set', index=guest, net_ns_fd=pid)
261 with Namespace(pid, 'net'):
262 ip = IPRoute()
263 ip.link('set', index=guest, ifname='eth{}'.format(index+1))
264 ip.addr('add', index=guest, address=quagga_config['ip'], mask=quagga_config['mask'])
265 ip.link('set', index=guest, state='up')
266 index += 1
267 finally:
268 self.CONFIG_LOCK.release()
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700269
Thangavelu K Sef6f0a52016-12-14 19:57:05 +0000270 def execute(self, cmd, tty = True, stream = False, shell = False, detach = True):
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700271 res = 0
272 if type(cmd) == str:
273 cmds = (cmd,)
274 else:
275 cmds = cmd
276 if shell:
277 for c in cmds:
278 res += os.system('docker exec {0} {1}'.format(self.name, c))
279 return res
280 for c in cmds:
281 i = self.dckr.exec_create(container=self.name, cmd=c, tty = tty, privileged = True)
A R Karthickd6dd9b22017-02-24 15:17:22 -0800282 s = self.dckr.exec_start(i['Id'], stream = stream, detach=detach, socket=True)
283 try:
284 s.close()
285 except: pass
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700286 result = self.dckr.exec_inspect(i['Id'])
287 res += 0 if result['ExitCode'] == None else result['ExitCode']
288 return res
289
ChetanGaonker6138fcd2016-08-18 17:56:39 -0700290 def restart(self, timeout =10):
291 return self.dckr.restart(self.name, timeout)
292
A R Karthickc69d73e2017-01-20 11:44:34 -0800293def get_mem(jvm_heap_size = None, instances = 1):
A R Karthick1f908202016-11-16 17:32:20 -0800294 if instances <= 0:
295 instances = 1
A R Karthickc69d73e2017-01-20 11:44:34 -0800296 heap_size = jvm_heap_size
297 heap_size_i = 0
298 #sanitize the heap size config
299 if heap_size is not None:
300 if not heap_size.isdigit():
301 try:
302 heap_size_i = int(heap_size[:-1])
303 suffix = heap_size[-1]
304 if suffix == 'M':
305 heap_size_i /= 1024 #convert to gigs
A.R Karthick99044822017-02-09 14:04:20 -0800306 #allow to specific minimum heap size
307 if heap_size_i == 0:
308 return heap_size
A R Karthickc69d73e2017-01-20 11:44:34 -0800309 except:
310 ##invalid suffix length probably. Fall back to default
311 heap_size = None
312 else:
313 heap_size_i = int(heap_size)
314
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700315 with open('/proc/meminfo', 'r') as fd:
316 meminfo = fd.readlines()
317 mem = 0
318 for m in meminfo:
319 if m.startswith('MemTotal:') or m.startswith('SwapTotal:'):
320 mem += int(m.split(':')[1].strip().split()[0])
321
A R Karthick1f908202016-11-16 17:32:20 -0800322 mem = max(mem/1024/1024/2/instances, 1)
Chetan Gaonker6d0a7b02016-05-03 16:57:28 -0700323 mem = min(mem, 16)
A R Karthickc69d73e2017-01-20 11:44:34 -0800324
325 if heap_size_i:
326 #we take the minimum of the provided heap size and max allowed heap size
327 heap_size_i = min(heap_size_i, mem)
328 else:
329 heap_size_i = mem
330
331 return '{}G'.format(heap_size_i)
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700332
A R Karthickd44cea12016-07-20 12:16:41 -0700333class OnosCord(Container):
334 """Use this when running the cord tester agent on the onos compute node"""
A R Karthickd44cea12016-07-20 12:16:41 -0700335 onos_config_dir_guest = '/root/onos/config'
A R Karthick03bd2812017-03-03 17:49:17 -0800336 synchronizer_map = { 'vtn' : { 'install':
337 ('http://mavenrepo:8080/repository/org/opencord/cord-config/1.2-SNAPSHOT/cord-config-1.2-SNAPSHOT.oar',
338 'http://mavenrepo:8080/repository/org/opencord/vtn/1.2-SNAPSHOT/vtn-1.2-SNAPSHOT.oar',),
339 'activate':
340 ('org.onosproject.ovsdb-base', 'org.onosproject.drivers.ovsdb',
341 'org.onosproject.dhcp', 'org.onosproject.optical-model',
342 'org.onosproject.openflow-base', 'org.onosproject.proxyarp',
343 'org.onosproject.hostprovider'),
344 },
345 'fabric' : { 'activate':
346 ('org.onosproject.hostprovider', 'org.onosproject.optical-model',
347 'org.onosproject.openflow-base', 'org.onosproject.vrouter',
348 'org.onosproject.netcfghostprovider', 'org.onosproject.netcfglinksprovider',
349 'org.onosproject.segmentrouting', 'org.onosproject.proxyarp'),
350 }
351 }
352 tester_apps = ('http://mavenrepo:8080/repository/org/opencord/aaa/1.2-SNAPSHOT/aaa-1.2-SNAPSHOT.oar',
353 'http://mavenrepo:8080/repository/org/opencord/igmp/1.2-SNAPSHOT/igmp-1.2-SNAPSHOT.oar',)
A R Karthickd44cea12016-07-20 12:16:41 -0700354
A.R Karthickddf12772017-05-17 13:49:47 -0700355 old_service_profile = '/opt/cord/orchestration/service-profile/cord-pod'
A R Karthick49529c52017-05-19 09:43:01 -0700356 cord_profile = '/opt/cord_profile'
A.R Karthickddf12772017-05-17 13:49:47 -0700357
A R Karthick03bd2812017-03-03 17:49:17 -0800358 def __init__(self, onos_ip, conf, service_profile, synchronizer, start = True, boot_delay = 5):
A.R Karthickf184b342017-01-27 19:30:50 -0800359 if not os.access(conf, os.F_OK):
360 raise Exception('ONOS cord configuration location %s is invalid' %conf)
A.R Karthickddf12772017-05-17 13:49:47 -0700361 self.old_cord = False
362 if os.access(self.old_service_profile, os.F_OK):
363 self.old_cord = True
A R Karthickbd9b8a32016-07-21 09:56:45 -0700364 self.onos_ip = onos_ip
A.R Karthickf184b342017-01-27 19:30:50 -0800365 self.onos_cord_dir = conf
A R Karthickbd9b8a32016-07-21 09:56:45 -0700366 self.boot_delay = boot_delay
A.R Karthickf184b342017-01-27 19:30:50 -0800367 self.synchronizer = synchronizer
368 self.service_profile = service_profile
369 self.docker_yaml = os.path.join(conf, 'docker-compose.yml')
370 self.docker_yaml_saved = os.path.join(conf, 'docker-compose.yml.saved')
371 self.onos_config_dir = os.path.join(conf, 'config')
372 self.onos_cfg_save_loc = os.path.join(conf, 'network-cfg.json.saved')
373 instance_active = False
374 #if we have a wrapper onos instance already active, back out
375 if os.access(self.onos_config_dir, os.F_OK) or os.access(self.docker_yaml_saved, os.F_OK):
376 instance_active = True
377 else:
378 if start is True:
379 os.mkdir(self.onos_config_dir)
380 shutil.copy(self.docker_yaml, self.docker_yaml_saved)
A R Karthickd44cea12016-07-20 12:16:41 -0700381
A.R Karthickf184b342017-01-27 19:30:50 -0800382 self.start_wrapper = instance_active is False and start is True
A R Karthickd44cea12016-07-20 12:16:41 -0700383 ##update the docker yaml with the config volume
384 with open(self.docker_yaml, 'r') as f:
385 yaml_config = yaml.load(f)
386 image = yaml_config['services'].keys()[0]
A R Karthick8983cb02017-06-09 11:32:53 -0700387 cord_conf_dir_basename = os.path.basename(self.onos_cord_dir.replace('-', '').replace('_', ''))
A.R Karthickf184b342017-01-27 19:30:50 -0800388 xos_onos_name = '{}_{}_1'.format(cord_conf_dir_basename, image)
A R Karthick5778a792017-01-31 13:47:16 -0800389 if not yaml_config['services'][image].has_key('volumes'):
390 yaml_config['services'][image]['volumes'] = []
A R Karthickd44cea12016-07-20 12:16:41 -0700391 volumes = yaml_config['services'][image]['volumes']
392 config_volumes = filter(lambda e: e.find(self.onos_config_dir_guest) >= 0, volumes)
393 if not config_volumes:
394 config_volume = '{}:{}'.format(self.onos_config_dir, self.onos_config_dir_guest)
395 volumes.append(config_volume)
A.R Karthickf184b342017-01-27 19:30:50 -0800396 if self.start_wrapper:
397 docker_yaml_changed = '{}-changed'.format(self.docker_yaml)
398 with open(docker_yaml_changed, 'w') as wf:
399 yaml.dump(yaml_config, wf)
400 os.rename(docker_yaml_changed, self.docker_yaml)
A R Karthickd44cea12016-07-20 12:16:41 -0700401 self.volumes = volumes
402
A R Karthickd44cea12016-07-20 12:16:41 -0700403 ##Create an container instance of xos onos
A R Karthick52414732017-01-31 09:59:47 -0800404 super(OnosCord, self).__init__(xos_onos_name, image, tag = '', quagga_config = Onos.QUAGGA_CONFIG)
A.R Karthickf184b342017-01-27 19:30:50 -0800405 self.last_cfg = None
406 if self.start_wrapper:
407 #fetch the current config of onos cord instance and save it
408 try:
409 self.last_cfg = OnosCtrl.get_config(controller = onos_ip)
410 json_data = json.dumps(self.last_cfg, indent=4)
411 with open(self.onos_cfg_save_loc, 'w') as f:
412 f.write(json_data)
413 except:
414 pass
415 #start the container back with the shared onos config volume
416 self.start()
A R Karthickd44cea12016-07-20 12:16:41 -0700417
A R Karthick03bd2812017-03-03 17:49:17 -0800418 def cliEnter(self):
419 retries = 0
420 while retries < 30:
421 cli = OnosCliDriver(controller = self.onos_ip, connect = True)
422 if cli.handle:
423 return cli
424 else:
425 retries += 1
A R Karthick72fcbc52017-03-06 12:35:17 -0800426 time.sleep(3)
A R Karthick03bd2812017-03-03 17:49:17 -0800427
428 return None
429
430 def cliExit(self, cli):
431 if cli:
432 cli.disconnect()
433
A.R Karthickddf12772017-05-17 13:49:47 -0700434 def synchronize_fabric(self, cfg = None):
435 if self.old_cord is True:
436 cmds = [ 'cd {} && make {}'.format(self.old_service_profile, self.synchronizer),
437 'sleep 30'
438 ]
439 for cmd in cmds:
440 try:
441 os.system(cmd)
442 except:
443 pass
444
A R Karthick03bd2812017-03-03 17:49:17 -0800445 def synchronize_vtn(self, cfg = None):
A.R Karthickddf12772017-05-17 13:49:47 -0700446 if self.old_cord is True:
447 cmds = [ 'cd {} && make {}'.format(self.old_service_profile, self.synchronizer),
448 'sleep 30'
449 ]
450 for cmd in cmds:
451 try:
452 os.system(cmd)
453 except:
454 pass
455 return
A R Karthick03bd2812017-03-03 17:49:17 -0800456 if cfg is None:
457 return
458 if not cfg.has_key('apps'):
459 return
460 if not cfg['apps'].has_key('org.opencord.vtn'):
461 return
462 vtn_neutron_cfg = cfg['apps']['org.opencord.vtn']['cordvtn']['openstack']
463 password = vtn_neutron_cfg['password']
464 endpoint = vtn_neutron_cfg['endpoint']
465 user = vtn_neutron_cfg['user']
466 tenant = vtn_neutron_cfg['tenant']
467 vtn_host = cfg['apps']['org.opencord.vtn']['cordvtn']['nodes'][0]['hostname']
468 cli = self.cliEnter()
469 if cli is None:
470 return
471 cli.cordVtnSyncNeutronStates(endpoint, password, tenant = tenant, user = user)
472 time.sleep(2)
473 cli.cordVtnNodeInit(vtn_host)
474 self.cliExit(cli)
475
476 def synchronize(self, cfg_unlink = False):
A R Karthick03bd2812017-03-03 17:49:17 -0800477
478 if not self.synchronizer_map.has_key(self.synchronizer):
479 return
480
481 install_list = ()
482 if self.synchronizer_map[self.synchronizer].has_key('install'):
483 install_list = self.synchronizer_map[self.synchronizer]['install']
484
485 activate_list = ()
486 if self.synchronizer_map[self.synchronizer].has_key('activate'):
487 activate_list = self.synchronizer_map[self.synchronizer]['activate']
488
489 for app_url in install_list:
490 print('Installing app from url: %s' %app_url)
491 OnosCtrl.install_app_from_url(None, None, app_url = app_url, onos_ip = self.onos_ip)
492
493 for app in activate_list:
494 print('Activating app %s' %app)
495 OnosCtrl(app, controller = self.onos_ip).activate()
496 time.sleep(2)
497
498 for app_url in self.tester_apps:
499 print('Installing tester app from url: %s' %app_url)
500 OnosCtrl.install_app_from_url(None, None, app_url = app_url, onos_ip = self.onos_ip)
501
A R Karthick72fcbc52017-03-06 12:35:17 -0800502 cfg = None
503 #restore the saved config after applications are activated
504 if os.access(self.onos_cfg_save_loc, os.F_OK):
505 with open(self.onos_cfg_save_loc, 'r') as f:
506 cfg = json.load(f)
507 try:
508 OnosCtrl.config(cfg, controller = self.onos_ip)
509 if cfg_unlink is True:
510 os.unlink(self.onos_cfg_save_loc)
511 except:
512 pass
513
514 if hasattr(self, 'synchronize_{}'.format(self.synchronizer)):
515 getattr(self, 'synchronize_{}'.format(self.synchronizer))(cfg = cfg)
516
517 #now restart the xos synchronizer container
A R Karthick49529c52017-05-19 09:43:01 -0700518 cmd = None
519 if os.access('{}/onboarding-docker-compose/docker-compose.yml'.format(self.cord_profile), os.F_OK):
520 cmd = 'cd {}/onboarding-docker-compose && \
521 docker-compose -p {} restart xos_synchronizer_{}'.format(self.cord_profile,
522 self.service_profile,
523 self.synchronizer)
524 else:
525 if os.access('{}/docker-compose.yml'.format(self.cord_profile), os.F_OK):
526 cmd = 'cd {} && \
527 docker-compose -p {} restart {}-synchronizer'.format(self.cord_profile,
528 self.service_profile,
529 self.synchronizer)
530 if cmd is not None:
531 try:
532 print(cmd)
533 os.system(cmd)
534 except:
535 pass
A R Karthick03bd2812017-03-03 17:49:17 -0800536
A R Karthickd44cea12016-07-20 12:16:41 -0700537 def start(self, restart = False, network_cfg = None):
A R Karthick928ad622017-01-30 12:18:32 -0800538 if network_cfg is not None:
A R Karthickd44cea12016-07-20 12:16:41 -0700539 json_data = json.dumps(network_cfg, indent=4)
540 with open('{}/network-cfg.json'.format(self.onos_config_dir), 'w') as f:
541 f.write(json_data)
A R Karthick52414732017-01-31 09:59:47 -0800542
543 #we avoid using docker-compose restart for now.
544 #since we don't want to retain the metadata across restarts
A R Karthick03bd2812017-03-03 17:49:17 -0800545 #stop and start and synchronize the services before installing tester cord apps
546 cmds = [ 'cd {} && docker-compose down'.format(self.onos_cord_dir),
547 'cd {} && docker-compose up -d'.format(self.onos_cord_dir),
A R Karthickbc894372017-05-12 16:34:08 -0700548 'sleep 150',
A R Karthick03bd2812017-03-03 17:49:17 -0800549 ]
550 for cmd in cmds:
A.R Karthickf184b342017-01-27 19:30:50 -0800551 try:
A R Karthick03bd2812017-03-03 17:49:17 -0800552 print(cmd)
A.R Karthickf184b342017-01-27 19:30:50 -0800553 os.system(cmd)
A R Karthick03bd2812017-03-03 17:49:17 -0800554 except:pass
A R Karthick52414732017-01-31 09:59:47 -0800555
A R Karthick03bd2812017-03-03 17:49:17 -0800556 self.synchronize()
A R Karthick52414732017-01-31 09:59:47 -0800557 ##we could also connect container to default docker network but disabled for now
558 #Container.connect_to_network(self.name, 'bridge')
A R Karthick52414732017-01-31 09:59:47 -0800559 #connect container to the quagga bridge
560 self.connect_to_br(index = 0)
A.R Karthickf184b342017-01-27 19:30:50 -0800561 print('Waiting %d seconds for ONOS instance to start' %self.boot_delay)
A R Karthickbd9b8a32016-07-21 09:56:45 -0700562 time.sleep(self.boot_delay)
A R Karthickd44cea12016-07-20 12:16:41 -0700563
564 def build_image(self):
565 build_cmd = 'cd {} && docker-compose build'.format(self.onos_cord_dir)
566 os.system(build_cmd)
567
A.R Karthickf184b342017-01-27 19:30:50 -0800568 def restore(self, force = False):
569 restore = self.start_wrapper is True or force is True
570 if not restore:
A.R Karthick263d3fc2017-01-27 12:52:53 -0800571 return
A R Karthick394976f2017-01-31 14:25:16 -0800572 #nothing to restore
573 if not os.access(self.docker_yaml_saved, os.F_OK):
574 return
A R Karthick03bd2812017-03-03 17:49:17 -0800575
A.R Karthickf184b342017-01-27 19:30:50 -0800576 #restore the config files back. The synchronizer restore should bring the last config back
577 cmds = ['cd {} && docker-compose down'.format(self.onos_cord_dir),
578 'rm -rf {}'.format(self.onos_config_dir),
579 'mv {} {}'.format(self.docker_yaml_saved, self.docker_yaml),
580 'cd {} && docker-compose up -d'.format(self.onos_cord_dir),
A R Karthickbc894372017-05-12 16:34:08 -0700581 'sleep 150',
A.R Karthickf184b342017-01-27 19:30:50 -0800582 ]
583 for cmd in cmds:
A.R Karthickb17e2022017-01-27 11:29:26 -0800584 try:
A.R Karthickf184b342017-01-27 19:30:50 -0800585 print(cmd)
586 os.system(cmd)
A.R Karthickb17e2022017-01-27 11:29:26 -0800587 except: pass
588
A R Karthick03bd2812017-03-03 17:49:17 -0800589 self.synchronize(cfg_unlink = True)
A.R Karthickb17e2022017-01-27 11:29:26 -0800590
A.R Karthick1700e0e2016-10-06 18:16:57 -0700591class OnosCordStopWrapper(Container):
592 onos_cord_dir = os.path.join(os.getenv('HOME'), 'cord-tester-cord')
593 docker_yaml = os.path.join(onos_cord_dir, 'docker-compose.yml')
594
595 def __init__(self):
596 if os.access(self.docker_yaml, os.F_OK):
597 with open(self.docker_yaml, 'r') as f:
598 yaml_config = yaml.load(f)
599 image = yaml_config['services'].keys()[0]
600 name = 'cordtestercord_{}_1'.format(image)
601 super(OnosCordStopWrapper, self).__init__(name, image, tag = '')
602 if self.exists():
603 print('Killing container %s' %self.name)
604 self.kill()
605
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700606class Onos(Container):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800607 QUAGGA_CONFIG = [ { 'bridge' : 'quagga-br', 'ip': '10.10.0.4', 'mask' : 16 }, ]
A R Karthicka2492c12016-12-16 10:31:51 -0800608 MAX_INSTANCES = 3
A R Karthickc69d73e2017-01-20 11:44:34 -0800609 JVM_HEAP_SIZE = None
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700610 SYSTEM_MEMORY = (get_mem(),) * 2
A R Karthicka2492c12016-12-16 10:31:51 -0800611 INSTANCE_MEMORY = (get_mem(instances=MAX_INSTANCES),) * 2
A R Karthickc69d73e2017-01-20 11:44:34 -0800612 JAVA_OPTS_FORMAT = '-Xms{} -Xmx{} -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode'
613 JAVA_OPTS_DEFAULT = JAVA_OPTS_FORMAT.format(*SYSTEM_MEMORY) #-XX:+PrintGCDetails -XX:+PrintGCTimeStamps'
614 JAVA_OPTS_CLUSTER_DEFAULT = JAVA_OPTS_FORMAT.format(*INSTANCE_MEMORY)
615 env = { 'ONOS_APPS' : 'drivers,openflow,proxyarp,vrouter', 'JAVA_OPTS' : JAVA_OPTS_DEFAULT }
A R Karthick6e70e142017-07-28 15:25:38 -0700616 onos_cord_apps = ( ['cord-config', '1.2-SNAPSHOT', 'org.opencord.config'],
A R Karthick1555c7c2017-09-07 14:59:41 -0700617 ['sadis-app', '3.0-SNAPSHOT', 'org.opencord.sadis'],
618 ['olt-app', '1.2-SNAPSHOT', 'org.onosproject.olt'],
A R Karthick6e70e142017-07-28 15:25:38 -0700619 ['aaa', '1.2-SNAPSHOT', 'org.opencord.aaa'],
620 ['igmp', '1.2-SNAPSHOT', 'org.opencord.igmp'],
A.R Karthick95d044e2016-06-10 18:44:36 -0700621 )
A R Karthickb608d402017-06-02 11:48:41 -0700622 cord_apps_version_updated = False
A R Karthick184945a2017-07-25 17:23:57 -0700623 expose_port = False
624 expose_ports = [ 8181, 8101, 9876, 6653, 6633, 2000, 2620, 5005 ]
625 ports = []
A R Karthickf2f4ca62016-08-17 10:34:08 -0700626 setup_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup')
627 host_config_dir = os.path.join(setup_dir, 'onos-config')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700628 guest_config_dir = '/root/onos/config'
A.R Karthickdda22062017-02-09 14:39:20 -0800629 guest_data_dir = '/root/onos/apache-karaf-3.0.8/data'
630 guest_log_file = '/root/onos/apache-karaf-3.0.8/data/log/karaf.log'
A R Karthickf2f4ca62016-08-17 10:34:08 -0700631 onos_gen_partitions = os.path.join(setup_dir, 'onos-gen-partitions')
A R Karthick2b93d6a2016-09-06 15:19:09 -0700632 onos_form_cluster = os.path.join(setup_dir, 'onos-form-cluster')
A.R Karthick95d044e2016-06-10 18:44:36 -0700633 cord_apps_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'apps')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700634 host_guest_map = ( (host_config_dir, guest_config_dir), )
A R Karthickd52ca8a2017-07-24 17:38:55 -0700635 ssl_key = None
A R Karthick2b93d6a2016-09-06 15:19:09 -0700636 cluster_cfg = os.path.join(host_config_dir, 'cluster.json')
637 cluster_mode = False
638 cluster_instances = []
Chetan Gaonker503032a2016-05-12 12:06:29 -0700639 NAME = 'cord-onos'
A R Karthickf2f4ca62016-08-17 10:34:08 -0700640 ##the ip of ONOS in default cluster.json in setup/onos-config
641 CLUSTER_CFG_IP = '172.17.0.2'
A R Karthick07608ef2016-08-23 16:51:19 -0700642 IMAGE = 'onosproject/onos'
643 TAG = 'latest'
644 PREFIX = ''
A R Karthickf2f4ca62016-08-17 10:34:08 -0700645
646 @classmethod
A R Karthick2b93d6a2016-09-06 15:19:09 -0700647 def generate_cluster_cfg(cls, ip):
648 if type(ip) in [ list, tuple ]:
649 ips = ' '.join(ip)
650 else:
651 ips = ip
A R Karthickf2f4ca62016-08-17 10:34:08 -0700652 try:
A R Karthick2b93d6a2016-09-06 15:19:09 -0700653 cmd = '{} {} {}'.format(cls.onos_gen_partitions, cls.cluster_cfg, ips)
654 os.system(cmd)
655 except: pass
656
657 @classmethod
658 def form_cluster(cls, ips):
659 nodes = ' '.join(ips)
660 try:
661 cmd = '{} {}'.format(cls.onos_form_cluster, nodes)
A R Karthickf2f4ca62016-08-17 10:34:08 -0700662 os.system(cmd)
663 except: pass
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700664
A R Karthick9d48c652016-09-15 09:16:36 -0700665 @classmethod
666 def cleanup_runtime(cls):
667 '''Cleanup ONOS runtime generated files'''
668 files = ( Onos.cluster_cfg, os.path.join(Onos.host_config_dir, 'network-cfg.json') )
669 for f in files:
670 if os.access(f, os.F_OK):
671 try:
672 os.unlink(f)
673 except: pass
674
A R Karthickec2db322016-11-17 15:06:01 -0800675 @classmethod
676 def get_data_map(cls, host_volume, guest_volume_dir):
677 host_volume_dir = os.path.join(cls.setup_dir, os.path.basename(host_volume))
678 if not os.path.exists(host_volume_dir):
679 os.mkdir(host_volume_dir)
680 return ( (host_volume_dir, guest_volume_dir), )
681
682 @classmethod
683 def remove_data_map(cls, host_volume, guest_volume_dir):
684 host_volume_dir = os.path.join(cls.setup_dir, os.path.basename(host_volume))
685 if os.path.exists(host_volume_dir):
A.R Karthickf184b342017-01-27 19:30:50 -0800686 shutil.rmtree(host_volume_dir)
A R Karthickec2db322016-11-17 15:06:01 -0800687
A R Karthick973010f2017-02-06 16:41:51 -0800688 @classmethod
689 def update_data_dir(cls, karaf):
690 Onos.guest_data_dir = '/root/onos/apache-karaf-{}/data'.format(karaf)
691 Onos.guest_log_file = '/root/onos/apache-karaf-{}/data/log/karaf.log'.format(karaf)
692
A R Karthickd52ca8a2017-07-24 17:38:55 -0700693 @classmethod
694 def update_ssl_key(cls, key):
695 if os.access(key, os.F_OK):
696 try:
697 shutil.copy(key, cls.host_config_dir)
698 cls.ssl_key = os.path.join(cls.host_config_dir, os.path.basename(key))
699 except:pass
700
A R Karthick184945a2017-07-25 17:23:57 -0700701 @classmethod
702 def set_expose_port(cls, flag):
703 cls.expose_port = flag
704
705 def get_port_map(self, instance=0):
706 if self.expose_port is False:
707 return self.ports
708 return map(lambda p: (p, p + instance), self.expose_ports)
709
A R Karthickec2db322016-11-17 15:06:01 -0800710 def remove_data_volume(self):
711 if self.data_map is not None:
712 self.remove_data_map(*self.data_map)
713
A.R Karthick1700e0e2016-10-06 18:16:57 -0700714 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX, tag = TAG,
A R Karthickec2db322016-11-17 15:06:01 -0800715 boot_delay = 20, restart = False, network_cfg = None,
A R Karthick85eb1862017-01-23 16:10:57 -0800716 cluster = False, data_volume = None, async = False, quagga_config = None,
A R Karthick184945a2017-07-25 17:23:57 -0700717 network = None, instance = 0):
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700718 if restart is True:
719 ##Find the right image to restart
720 running_image = filter(lambda c: c['Names'][0] == '/{}'.format(name), self.dckr.containers())
721 if running_image:
722 image_name = running_image[0]['Image']
723 try:
724 image = image_name.split(':')[0]
725 tag = image_name.split(':')[1]
726 except: pass
727
A R Karthickaa54a1c2016-12-15 11:42:08 -0800728 if quagga_config is None:
729 quagga_config = Onos.QUAGGA_CONFIG
730 super(Onos, self).__init__(name, image, prefix = prefix, tag = tag, quagga_config = quagga_config)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700731 self.boot_delay = boot_delay
A R Karthickec2db322016-11-17 15:06:01 -0800732 self.data_map = None
A R Karthickc69d73e2017-01-20 11:44:34 -0800733 instance_memory = (get_mem(jvm_heap_size = Onos.JVM_HEAP_SIZE, instances = Onos.MAX_INSTANCES),) * 2
734 self.env['JAVA_OPTS'] = self.JAVA_OPTS_FORMAT.format(*instance_memory)
A R Karthick184945a2017-07-25 17:23:57 -0700735 self.ports = self.get_port_map(instance = instance)
A R Karthickd52ca8a2017-07-24 17:38:55 -0700736 if self.ssl_key:
737 key_files = ( os.path.join(self.guest_config_dir, os.path.basename(self.ssl_key)), ) * 2
738 self.env['JAVA_OPTS'] += ' -DenableOFTLS=true -Djavax.net.ssl.keyStore={} -Djavax.net.ssl.keyStorePassword=222222 -Djavax.net.ssl.trustStore={} -Djavax.net.ssl.trustStorePassword=222222'.format(*key_files)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700739 if cluster is True:
A R Karthickec2db322016-11-17 15:06:01 -0800740 if data_volume is not None:
741 self.data_map = self.get_data_map(data_volume, self.guest_data_dir)
742 self.host_guest_map = self.host_guest_map + self.data_map
A R Karthick2b93d6a2016-09-06 15:19:09 -0700743 if os.access(self.cluster_cfg, os.F_OK):
744 try:
745 os.unlink(self.cluster_cfg)
746 except: pass
747
748 self.host_config = self.create_host_config(port_list = self.ports,
749 host_guest_map = self.host_guest_map)
750 self.volumes = []
751 for _,g in self.host_guest_map:
752 self.volumes.append(g)
753
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700754 if restart is True and self.exists():
755 self.kill()
A R Karthick2b93d6a2016-09-06 15:19:09 -0700756
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700757 if not self.exists():
758 self.remove_container(name, force=True)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -0700759 host_config = self.create_host_config(port_list = self.ports,
760 host_guest_map = self.host_guest_map)
761 volumes = []
762 for _,g in self.host_guest_map:
763 volumes.append(g)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700764 if network_cfg is not None:
A R Karthick81acbff2016-06-17 14:45:16 -0700765 json_data = json.dumps(network_cfg, indent=4)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700766 with open('{}/network-cfg.json'.format(self.host_config_dir), 'w') as f:
767 f.write(json_data)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800768 if cluster is False or async is False:
769 print('Starting ONOS container %s' %self.name)
770 self.start(ports = self.ports, environment = self.env,
A R Karthick1555c7c2017-09-07 14:59:41 -0700771 host_config = self.host_config, volumes = self.volumes, tty = True,
772 network = Radius.NETWORK)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800773 if not restart:
774 ##wait a bit before fetching IP to regenerate cluster cfg
775 time.sleep(5)
776 ip = self.ip()
777 ##Just a quick hack/check to ensure we don't regenerate in the common case.
778 ##As ONOS is usually the first test container that is started
779 if cluster is False:
780 if ip != self.CLUSTER_CFG_IP or not os.access(self.cluster_cfg, os.F_OK):
781 print('Regenerating ONOS cluster cfg for ip %s' %ip)
782 self.generate_cluster_cfg(ip)
783 self.kill()
784 self.remove_container(self.name, force=True)
785 print('Restarting ONOS container %s' %self.name)
786 self.start(ports = self.ports, environment = self.env,
A R Karthick1555c7c2017-09-07 14:59:41 -0700787 host_config = self.host_config, volumes = self.volumes, tty = True,
788 network = Radius.NETWORK)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800789 print('Waiting for ONOS to boot')
790 time.sleep(boot_delay)
791 self.wait_for_onos_start(self.ip())
792 self.running = True
793 else:
794 self.running = False
795 else:
796 self.running = True
797 if self.running:
798 self.ipaddr = self.ip()
799 if cluster is False:
800 self.install_cord_apps(self.ipaddr)
A R Karthick19aaf5c2016-11-09 17:47:57 -0800801
A.R Karthickc4e474d2016-12-12 15:24:57 -0800802 @classmethod
803 def get_quagga_config(cls, instance = 0):
A R Karthickaa54a1c2016-12-15 11:42:08 -0800804 quagga_config = copy.deepcopy(cls.QUAGGA_CONFIG)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800805 if instance == 0:
806 return quagga_config
807 ip = quagga_config[0]['ip']
808 octets = ip.split('.')
A R Karthickaa54a1c2016-12-15 11:42:08 -0800809 octets[3] = str((int(octets[3]) + instance) & 255)
A.R Karthickc4e474d2016-12-12 15:24:57 -0800810 ip = '.'.join(octets)
811 quagga_config[0]['ip'] = ip
812 return quagga_config
813
814 @classmethod
815 def start_cluster_async(cls, onos_instances):
816 instances = filter(lambda o: o.running == False, onos_instances)
817 if not instances:
818 return
819 tpool = ThreadPool(len(instances), queue_size = 1, wait_timeout = 1)
820 for onos in instances:
821 tpool.addTask(onos.start_async)
822 tpool.cleanUpThreads()
823
824 def start_async(self):
825 print('Starting ONOS container %s' %self.name)
826 self.start(ports = self.ports, environment = self.env,
827 host_config = self.host_config, volumes = self.volumes, tty = True)
828 time.sleep(3)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700829 self.ipaddr = self.ip()
A.R Karthickc4e474d2016-12-12 15:24:57 -0800830 print('Waiting for ONOS container %s to start' %self.name)
831 self.wait_for_onos_start(self.ipaddr)
832 self.running = True
833 print('ONOS container %s started' %self.name)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700834
A R Karthick2b93d6a2016-09-06 15:19:09 -0700835 @classmethod
A R Karthick19aaf5c2016-11-09 17:47:57 -0800836 def wait_for_onos_start(cls, ip, tries = 30):
A R Karthick973010f2017-02-06 16:41:51 -0800837 onos_log = OnosLog(host = ip, log_file = Onos.guest_log_file)
A R Karthick19aaf5c2016-11-09 17:47:57 -0800838 num_tries = 0
839 started = None
840 while not started and num_tries < tries:
841 time.sleep(3)
842 started = onos_log.search_log_pattern('ApplicationManager .* Started')
843 num_tries += 1
844
A R Karthick19aaf5c2016-11-09 17:47:57 -0800845 if not started:
846 print('ONOS did not start')
847 else:
848 print('ONOS started')
849 return started
850
851 @classmethod
A R Karthick2b93d6a2016-09-06 15:19:09 -0700852 def setup_cluster_deprecated(cls, onos_instances, image_name = None):
853 if not onos_instances or len(onos_instances) < 2:
854 return
855 ips = []
856 if image_name is not None:
857 ips = Container.ips(image_name)
858 else:
859 for onos in onos_instances:
860 ips.append(onos.ipaddr)
861 Onos.cluster_instances = onos_instances
862 Onos.cluster_mode = True
863 ##regenerate the cluster json with the 3 instance ips before restarting them back
864 print('Generating cluster cfg for ONOS instances with ips %s' %ips)
865 Onos.generate_cluster_cfg(ips)
866 for onos in onos_instances:
867 onos.kill()
868 onos.remove_container(onos.name, force=True)
869 print('Restarting ONOS container %s for forming cluster' %onos.name)
870 onos.start(ports = onos.ports, environment = onos.env,
871 host_config = onos.host_config, volumes = onos.volumes, tty = True)
872 print('Waiting %d seconds for ONOS %s to boot' %(onos.boot_delay, onos.name))
873 time.sleep(onos.boot_delay)
874 onos.ipaddr = onos.ip()
875 onos.install_cord_apps(onos.ipaddr)
876
877 @classmethod
878 def setup_cluster(cls, onos_instances, image_name = None):
879 if not onos_instances or len(onos_instances) < 2:
880 return
881 ips = []
882 if image_name is not None:
883 ips = Container.ips(image_name)
884 else:
885 for onos in onos_instances:
886 ips.append(onos.ipaddr)
887 Onos.cluster_instances = onos_instances
888 Onos.cluster_mode = True
889 ##regenerate the cluster json with the 3 instance ips before restarting them back
890 print('Forming cluster for ONOS instances with ips %s' %ips)
891 Onos.form_cluster(ips)
892 ##wait for the cluster to be formed
893 print('Waiting for the cluster to be formed')
894 time.sleep(60)
895 for onos in onos_instances:
896 onos.install_cord_apps(onos.ipaddr)
897
898 @classmethod
A R Karthicke2c24bd2016-10-07 14:51:38 -0700899 def add_cluster(cls, count = 1, network_cfg = None):
900 if not cls.cluster_instances or Onos.cluster_mode is False:
901 return
902 for i in range(count):
A R Karthick184945a2017-07-25 17:23:57 -0700903 instance = len(cls.cluster_instances)
904 name = '{}-{}'.format(Onos.NAME, instance+1)
A R Karthicke2c24bd2016-10-07 14:51:38 -0700905 onos = cls(name = name, image = Onos.IMAGE, tag = Onos.TAG, prefix = Container.IMAGE_PREFIX,
A R Karthick184945a2017-07-25 17:23:57 -0700906 cluster = True, network_cfg = network_cfg, instance = instance)
A R Karthicke2c24bd2016-10-07 14:51:38 -0700907 cls.cluster_instances.append(onos)
908
909 cls.setup_cluster(cls.cluster_instances)
910
911 @classmethod
A.R Karthick2560f042016-11-30 14:38:52 -0800912 def restart_cluster(cls, network_cfg = None, timeout = 10, setup = False):
A R Karthick2b93d6a2016-09-06 15:19:09 -0700913 if cls.cluster_mode is False:
914 return
915 if not cls.cluster_instances:
916 return
917
918 if network_cfg is not None:
919 json_data = json.dumps(network_cfg, indent=4)
920 with open('{}/network-cfg.json'.format(cls.host_config_dir), 'w') as f:
921 f.write(json_data)
922
A.R Karthick2560f042016-11-30 14:38:52 -0800923 cls.cleanup_cluster()
924 if timeout > 0:
925 time.sleep(timeout)
926
A R Karthickaa54a1c2016-12-15 11:42:08 -0800927 #start the instances asynchronously
928 cls.start_cluster_async(cls.cluster_instances)
929 time.sleep(5)
A.R Karthick2560f042016-11-30 14:38:52 -0800930 ##form the cluster as appropriate
931 if setup is True:
932 cls.setup_cluster(cls.cluster_instances)
A R Karthickaa54a1c2016-12-15 11:42:08 -0800933 else:
934 for onos in cls.cluster_instances:
935 onos.install_cord_apps(onos.ipaddr)
A R Karthick2b93d6a2016-09-06 15:19:09 -0700936
937 @classmethod
938 def cluster_ips(cls):
939 if cls.cluster_mode is False:
940 return []
941 if not cls.cluster_instances:
942 return []
943 ips = [ onos.ipaddr for onos in cls.cluster_instances ]
944 return ips
945
946 @classmethod
947 def cleanup_cluster(cls):
948 if cls.cluster_mode is False:
949 return
950 if not cls.cluster_instances:
951 return
952 for onos in cls.cluster_instances:
953 if onos.exists():
954 onos.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -0800955 onos.running = False
A R Karthick2b93d6a2016-09-06 15:19:09 -0700956 onos.remove_container(onos.name, force=True)
A R Karthickd44cea12016-07-20 12:16:41 -0700957
A.R Karthick95d044e2016-06-10 18:44:36 -0700958 @classmethod
A R Karthickde6b9dc2016-11-29 17:46:16 -0800959 def restart_node(cls, node = None, network_cfg = None, timeout = 10):
A R Karthick889d9652016-10-03 14:13:45 -0700960 if node is None:
961 cls(restart = True, network_cfg = network_cfg, image = cls.IMAGE, tag = cls.TAG)
962 else:
963 #Restarts a node in the cluster
964 valid_node = filter(lambda onos: node in [ onos.ipaddr, onos.name ], cls.cluster_instances)
965 if valid_node:
966 onos = valid_node.pop()
967 if onos.exists():
968 onos.kill()
969 onos.remove_container(onos.name, force=True)
A R Karthickde6b9dc2016-11-29 17:46:16 -0800970 if timeout > 0:
971 time.sleep(timeout)
A R Karthick889d9652016-10-03 14:13:45 -0700972 print('Restarting ONOS container %s' %onos.name)
973 onos.start(ports = onos.ports, environment = onos.env,
A R Karthick1555c7c2017-09-07 14:59:41 -0700974 host_config = onos.host_config, volumes = onos.volumes, tty = True,
975 network = Radius.NETWORK)
A R Karthick889d9652016-10-03 14:13:45 -0700976 onos.ipaddr = onos.ip()
A.R Karthick2560f042016-11-30 14:38:52 -0800977 onos.wait_for_onos_start(onos.ipaddr)
978 onos.install_cord_apps(onos.ipaddr)
A R Karthick889d9652016-10-03 14:13:45 -0700979
980 @classmethod
A R Karthickb608d402017-06-02 11:48:41 -0700981 def cliEnter(cls, onos_ip = None):
982 retries = 0
983 while retries < 10:
984 cli = OnosCliDriver(controller = onos_ip, connect = True)
985 if cli.handle:
986 return cli
987 else:
988 retries += 1
989 time.sleep(3)
990
991 return None
992
993 @classmethod
994 def cliExit(cls, cli):
995 if cli:
996 cli.disconnect()
997
998 @classmethod
999 def getVersion(cls, onos_ip = None):
1000 cli = cls.cliEnter(onos_ip = onos_ip)
1001 try:
1002 summary = json.loads(cli.summary(jsonFormat = True))
1003 except:
1004 cls.cliExit(cli)
1005 return '1.8.0'
1006 cls.cliExit(cli)
1007 return summary['version']
1008
1009 @classmethod
1010 def update_cord_apps_version(cls, onos_ip = None):
1011 if cls.cord_apps_version_updated == True:
1012 return
1013 version = cls.getVersion(onos_ip = onos_ip)
1014 major = int(version.split('.')[0])
1015 minor = int(version.split('.')[1])
A R Karthick5b8310e2017-09-01 13:55:15 -07001016 try:
1017 patch = int(version.split('.')[2])
1018 except:
1019 patch = 0
A R Karthickb608d402017-06-02 11:48:41 -07001020 app_version = '1.2-SNAPSHOT'
1021 if major > 1:
A R Karthick1555c7c2017-09-07 14:59:41 -07001022 app_version = '3.0-SNAPSHOT'
A R Karthick5b8310e2017-09-01 13:55:15 -07001023 elif major == 1 and minor >= 10:
A R Karthick1555c7c2017-09-07 14:59:41 -07001024 app_version = '3.0-SNAPSHOT'
A R Karthick5b8310e2017-09-01 13:55:15 -07001025 if patch < 3:
1026 app_version = '1.2-SNAPSHOT'
A R Karthickb608d402017-06-02 11:48:41 -07001027 for apps in cls.onos_cord_apps:
1028 apps[1] = app_version
1029 cls.cord_apps_version_updated = True
1030
1031 @classmethod
A R Karthickeaf1c4e2016-07-19 12:22:35 -07001032 def install_cord_apps(cls, onos_ip = None):
A R Karthickb608d402017-06-02 11:48:41 -07001033 cls.update_cord_apps_version(onos_ip = onos_ip)
A R Karthick6e70e142017-07-28 15:25:38 -07001034 for app, version,_ in cls.onos_cord_apps:
A.R Karthick95d044e2016-06-10 18:44:36 -07001035 app_file = '{}/{}-{}.oar'.format(cls.cord_apps_dir, app, version)
A R Karthickeaf1c4e2016-07-19 12:22:35 -07001036 ok, code = OnosCtrl.install_app(app_file, onos_ip = onos_ip)
A.R Karthick95d044e2016-06-10 18:44:36 -07001037 ##app already installed (conflicts)
1038 if code in [ 409 ]:
1039 ok = True
1040 print('ONOS app %s, version %s %s' %(app, version, 'installed' if ok else 'failed to install'))
1041 time.sleep(2)
1042
A R Karthick6e70e142017-07-28 15:25:38 -07001043 @classmethod
1044 def activate_apps(cls, apps, onos_ip = None, deactivate = False):
1045 for app in apps:
1046 if deactivate is True:
1047 OnosCtrl(app, controller = onos_ip).deactivate()
1048 time.sleep(2)
1049 OnosCtrl(app, controller = onos_ip).activate()
1050
1051 time.sleep(5)
1052
1053 @classmethod
1054 def activate_cord_apps(cls, onos_ip = None, deactivate = True):
1055 cord_apps = map(lambda a: a[2], cls.onos_cord_apps)
1056 cls.activate_apps(cord_apps, onos_ip = onos_ip, deactivate = deactivate)
1057
A.R Karthick1700e0e2016-10-06 18:16:57 -07001058class OnosStopWrapper(Container):
1059 def __init__(self, name):
1060 super(OnosStopWrapper, self).__init__(name, Onos.IMAGE, tag = Onos.TAG, prefix = Container.IMAGE_PREFIX)
1061 if self.exists():
1062 self.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -08001063 self.running = False
A.R Karthick1700e0e2016-10-06 18:16:57 -07001064 else:
1065 if Onos.cluster_mode is True:
1066 valid_node = filter(lambda onos: name in [ onos.ipaddr, onos.name ], Onos.cluster_instances)
1067 if valid_node:
1068 onos = valid_node.pop()
1069 if onos.exists():
1070 onos.kill()
A R Karthickaa54a1c2016-12-15 11:42:08 -08001071 onos.running = False
A.R Karthick1700e0e2016-10-06 18:16:57 -07001072
Chetan Gaonker3533faa2016-04-25 17:50:14 -07001073class Radius(Container):
1074 ports = [ 1812, 1813 ]
A R Karthick41adfce2016-06-10 09:51:25 -07001075 env = {'TIMEZONE':'America/Los_Angeles',
Chetan Gaonker3533faa2016-04-25 17:50:14 -07001076 'DEBUG': 'true', 'cert_password':'whatever', 'primary_shared_secret':'radius_password'
1077 }
Chetan Gaonker7f4bf742016-05-04 15:56:08 -07001078 host_db_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/db')
Chetan Gaonker3533faa2016-04-25 17:50:14 -07001079 guest_db_dir = os.path.join(os.path.sep, 'opt', 'db')
Chetan Gaonker7f4bf742016-05-04 15:56:08 -07001080 host_config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/freeradius')
Chetan Gaonker3533faa2016-04-25 17:50:14 -07001081 guest_config_dir = os.path.join(os.path.sep, 'etc', 'freeradius')
Chetan Gaonker7f4bf742016-05-04 15:56:08 -07001082 start_command = os.path.join(guest_config_dir, 'start-radius.py')
Chetan Gaonker3533faa2016-04-25 17:50:14 -07001083 host_guest_map = ( (host_db_dir, guest_db_dir),
1084 (host_config_dir, guest_config_dir)
1085 )
A R Karthickf7a613b2017-02-24 09:36:44 -08001086 IMAGE = 'cordtest/radius'
Chetan Gaonker503032a2016-05-12 12:06:29 -07001087 NAME = 'cord-radius'
A R Karthick1555c7c2017-09-07 14:59:41 -07001088 NETWORK = 'cord-radius-test'
1089 SUBNET = '11.0.0.0/24'
1090 SUBNET_PREFIX = '11.0.0'
1091 GATEWAY = '11.0.0.1'
1092
1093 @classmethod
1094 def create_network(cls, name = NETWORK):
1095 try:
1096 Container.create_network(name, subnet = cls.SUBNET, gateway = cls.GATEWAY)
1097 except:
1098 pass
Chetan Gaonker503032a2016-05-12 12:06:29 -07001099
A R Karthick07608ef2016-08-23 16:51:19 -07001100 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = 'candidate',
A R Karthick1555c7c2017-09-07 14:59:41 -07001101 boot_delay = 10, restart = False, update = False, network = None, network_disabled = False):
A R Karthick07608ef2016-08-23 16:51:19 -07001102 super(Radius, self).__init__(name, image, prefix = prefix, tag = tag, command = self.start_command)
Chetan Gaonker503032a2016-05-12 12:06:29 -07001103 if update is True or not self.img_exists():
A R Karthick07608ef2016-08-23 16:51:19 -07001104 self.build_image(self.image_name)
Chetan Gaonker7f4bf742016-05-04 15:56:08 -07001105 if restart is True and self.exists():
1106 self.kill()
Chetan Gaonker3533faa2016-04-25 17:50:14 -07001107 if not self.exists():
1108 self.remove_container(name, force=True)
1109 host_config = self.create_host_config(port_list = self.ports,
1110 host_guest_map = self.host_guest_map)
1111 volumes = []
1112 for _,g in self.host_guest_map:
1113 volumes.append(g)
A R Karthick41adfce2016-06-10 09:51:25 -07001114 self.start(ports = self.ports, environment = self.env,
1115 volumes = volumes,
A R Karthick1555c7c2017-09-07 14:59:41 -07001116 host_config = host_config, tty = True, network_disabled = network_disabled)
1117 if network_disabled is False:
1118 Container.connect_to_network(self.name, self.NETWORK)
Chetan Gaonker7f4bf742016-05-04 15:56:08 -07001119 time.sleep(boot_delay)
1120
1121 @classmethod
1122 def build_image(cls, image):
1123 print('Building Radius image %s' %image)
1124 dockerfile = '''
1125FROM hbouvier/docker-radius
1126MAINTAINER chetan@ciena.com
1127LABEL RUN docker pull hbouvier/docker-radius
1128LABEL RUN docker run -it --name cord-radius hbouvier/docker-radius
A R Karthickc762df42016-05-25 10:09:21 -07001129RUN apt-get update && \
1130 apt-get -y install python python-pexpect strace
Chetan Gaonker7f4bf742016-05-04 15:56:08 -07001131WORKDIR /root
1132CMD ["/etc/freeradius/start-radius.py"]
1133'''
1134 super(Radius, cls).build_image(dockerfile, image)
1135 print('Done building image %s' %image)
Chetan Gaonker3533faa2016-04-25 17:50:14 -07001136
Chetan Gaonker6cf6e472016-04-26 14:41:51 -07001137class Quagga(Container):
A R Karthickaa54a1c2016-12-15 11:42:08 -08001138 QUAGGA_CONFIG = ( { 'bridge' : 'quagga-br', 'ip': '10.10.0.3', 'mask' : 16 },
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -07001139 { 'bridge' : 'quagga-br', 'ip': '192.168.10.3', 'mask': 16 },
1140 )
Chetan Gaonker6cf6e472016-04-26 14:41:51 -07001141 ports = [ 179, 2601, 2602, 2603, 2604, 2605, 2606 ]
1142 host_quagga_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/quagga-config')
1143 guest_quagga_config = '/root/config'
1144 quagga_config_file = os.path.join(guest_quagga_config, 'testrib.conf')
1145 host_guest_map = ( (host_quagga_config, guest_quagga_config), )
A R Karthickf7a613b2017-02-24 09:36:44 -08001146 IMAGE = 'cordtest/quagga'
Chetan Gaonker503032a2016-05-12 12:06:29 -07001147 NAME = 'cord-quagga'
1148
A R Karthick07608ef2016-08-23 16:51:19 -07001149 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = 'candidate',
A R Karthick85eb1862017-01-23 16:10:57 -08001150 boot_delay = 15, restart = False, config_file = quagga_config_file, update = False,
1151 network = None):
A R Karthickaa54a1c2016-12-15 11:42:08 -08001152 super(Quagga, self).__init__(name, image, prefix = prefix, tag = tag, quagga_config = self.QUAGGA_CONFIG)
Chetan Gaonker503032a2016-05-12 12:06:29 -07001153 if update is True or not self.img_exists():
A R Karthick07608ef2016-08-23 16:51:19 -07001154 self.build_image(self.image_name)
Chetan Gaonker6cf6e472016-04-26 14:41:51 -07001155 if restart is True and self.exists():
1156 self.kill()
1157 if not self.exists():
1158 self.remove_container(name, force=True)
A R Karthick41adfce2016-06-10 09:51:25 -07001159 host_config = self.create_host_config(port_list = self.ports,
1160 host_guest_map = self.host_guest_map,
Chetan Gaonker6cf6e472016-04-26 14:41:51 -07001161 privileged = True)
1162 volumes = []
1163 for _,g in self.host_guest_map:
1164 volumes.append(g)
1165 self.start(ports = self.ports,
A R Karthick41adfce2016-06-10 09:51:25 -07001166 host_config = host_config,
Chetan Gaonker6cf6e472016-04-26 14:41:51 -07001167 volumes = volumes, tty = True)
A R Karthick85eb1862017-01-23 16:10:57 -08001168 if network is not None:
1169 Container.connect_to_network(self.name, network)
Chetan Gaonker6cf6e472016-04-26 14:41:51 -07001170 print('Starting Quagga on container %s' %self.name)
1171 self.execute('{0}/start.sh {1}'.format(self.guest_quagga_config, config_file))
1172 time.sleep(boot_delay)
1173
1174 @classmethod
1175 def build_image(cls, image):
A R Karthickaa54a1c2016-12-15 11:42:08 -08001176 onos_quagga_ip = Onos.QUAGGA_CONFIG[0]['ip']
Chetan Gaonker6cf6e472016-04-26 14:41:51 -07001177 print('Building Quagga image %s' %image)
1178 dockerfile = '''
A R Karthick41adfce2016-06-10 09:51:25 -07001179FROM ubuntu:14.04
1180MAINTAINER chetan@ciena.com
Chetan Gaonker6cf6e472016-04-26 14:41:51 -07001181WORKDIR /root
1182RUN useradd -M quagga
1183RUN mkdir /var/log/quagga && chown quagga:quagga /var/log/quagga
1184RUN mkdir /var/run/quagga && chown quagga:quagga /var/run/quagga
A R Karthick973ea692016-10-17 12:23:02 -07001185RUN 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 -07001186RUN git clone git://git.savannah.nongnu.org/quagga.git quagga && \
A R Karthick8f69c2c2016-10-21 11:43:26 -07001187(cd quagga && git checkout quagga-1.0.20160315 && ./bootstrap.sh && \
Chetan Gaonker6cf6e472016-04-26 14:41:51 -07001188sed -i -r 's,htonl.*?\(INADDR_LOOPBACK\),inet_addr\("{0}"\),g' zebra/zebra_fpm.c && \
1189./configure --enable-fpm --disable-doc --localstatedir=/var/run/quagga && make && make install)
1190RUN ldconfig
1191'''.format(onos_quagga_ip)
1192 super(Quagga, cls).build_image(dockerfile, image)
1193 print('Done building image %s' %image)
A R Karthick81acbff2016-06-17 14:45:16 -07001194
A.R Karthick1700e0e2016-10-06 18:16:57 -07001195class QuaggaStopWrapper(Container):
1196 def __init__(self, name = Quagga.NAME, image = Quagga.IMAGE, tag = 'candidate'):
1197 super(QuaggaStopWrapper, self).__init__(name, image, prefix = Container.IMAGE_PREFIX, tag = tag)
1198 if self.exists():
1199 self.kill()
1200
1201
A R Karthick81acbff2016-06-17 14:45:16 -07001202def reinitContainerClients():
1203 docker_netns.dckr = Client()
1204 Container.dckr = Client()
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001205
1206class Xos(Container):
1207 setup_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup')
1208 TAG = 'latest'
1209 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -07001210 host_guest_map = None
1211 env = None
1212 ports = None
1213 volumes = None
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001214
A R Karthick6e80afd2016-10-10 16:03:12 -07001215 @classmethod
1216 def get_cmd(cls, img_name):
1217 cmd = cls.dckr.inspect_image(img_name)['Config']['Cmd']
1218 return ' '.join(cmd)
1219
A R Karthicke3bde962016-09-27 15:06:35 -07001220 def __init__(self, name, image, prefix = PREFIX, tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001221 boot_delay = 20, restart = False, network_cfg = None, update = False):
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001222 if restart is True:
1223 ##Find the right image to restart
1224 running_image = filter(lambda c: c['Names'][0] == '/{}'.format(name), self.dckr.containers())
1225 if running_image:
1226 image_name = running_image[0]['Image']
1227 try:
1228 image = image_name.split(':')[0]
1229 tag = image_name.split(':')[1]
1230 except: pass
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001231 super(Xos, self).__init__(name, image, prefix = prefix, tag = tag)
1232 if update is True or not self.img_exists():
1233 self.build_image(self.image_name)
A R Karthick6e80afd2016-10-10 16:03:12 -07001234 self.command = self.get_cmd(self.image_name).strip() or None
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001235 if restart is True and self.exists():
1236 self.kill()
1237 if not self.exists():
1238 self.remove_container(name, force=True)
A R Karthicke3bde962016-09-27 15:06:35 -07001239 host_config = self.create_host_config(port_list = self.ports,
1240 host_guest_map = self.host_guest_map,
1241 privileged = True)
1242 print('Starting XOS container %s' %self.name)
1243 self.start(ports = self.ports, environment = self.env, host_config = host_config,
1244 volumes = self.volumes, tty = True)
1245 print('Waiting %d seconds for XOS Base Container to boot' %(boot_delay))
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001246 time.sleep(boot_delay)
1247
1248 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -07001249 def build_image(cls, image, dockerfile_path, image_target = 'build'):
1250 cmd = 'cd {} && make {}'.format(dockerfile_path, image_target)
1251 print('Building XOS %s' %image)
1252 res = os.system(cmd)
1253 print('Done building image %s. Image build %s' %(image, 'successful' if res == 0 else 'failed'))
1254 return res
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001255
A R Karthicke3bde962016-09-27 15:06:35 -07001256class XosServer(Xos):
1257 ports = [8000,9998,9999]
1258 NAME = 'xos-server'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001259 IMAGE = 'xosproject/xos'
A R Karthicke3bde962016-09-27 15:06:35 -07001260 BASE_IMAGE = 'xosproject/xos-base'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001261 TAG = 'latest'
1262 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -07001263 dockerfile_path = os.path.join(Xos.setup_dir, 'xos')
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001264
A R Karthicke3bde962016-09-27 15:06:35 -07001265 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX, tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001266 boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001267 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001268
1269 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -07001270 def build_image(cls, image = IMAGE):
1271 ##build the base image and then build the server image
1272 Xos.build_image(cls.BASE_IMAGE, cls.dockerfile_path, image_target = 'base')
1273 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001274
A R Karthicke3bde962016-09-27 15:06:35 -07001275class XosSynchronizerOpenstack(Xos):
1276 ports = [2375,]
1277 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer')
1278 NAME = 'xos-synchronizer'
1279 IMAGE = 'xosproject/xos-synchronizer-openstack'
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001280 TAG = 'latest'
1281 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -07001282 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001283
A R Karthicke3bde962016-09-27 15:06:35 -07001284 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -07001285 tag = TAG, boot_delay = 20, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001286 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001287
1288 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -07001289 def build_image(cls, image = IMAGE):
1290 XosServer.build_image()
1291 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001292
A R Karthicke3bde962016-09-27 15:06:35 -07001293class XosSynchronizerOnboarding(Xos):
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001294 NAME = 'xos-synchronizer-onboarding'
1295 IMAGE = 'xosproject/xos-synchronizer-onboarding'
1296 TAG = 'latest'
1297 PREFIX = ''
A R Karthicke3bde962016-09-27 15:06:35 -07001298 dockerfile_path = os.path.join(Xos.setup_dir, 'onboarding_synchronizer')
1299 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001300
A R Karthicke3bde962016-09-27 15:06:35 -07001301 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -07001302 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001303 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001304
1305 @classmethod
A R Karthicke3bde962016-09-27 15:06:35 -07001306 def build_image(cls, image = IMAGE):
1307 XosSynchronizerOpenstack.build_image()
1308 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001309
A R Karthicke3bde962016-09-27 15:06:35 -07001310class XosSynchronizerOpenvpn(Xos):
1311 NAME = 'xos-synchronizer-openvpn'
1312 IMAGE = 'xosproject/xos-openvpn'
1313 TAG = 'latest'
1314 PREFIX = ''
1315 dockerfile_path = os.path.join(Xos.setup_dir, 'openvpn')
1316 host_guest_map = ( ('/usr/local/share/ca-certificates', '/usr/local/share/ca-certificates'),)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001317
A R Karthicke3bde962016-09-27 15:06:35 -07001318 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -07001319 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001320 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1321
1322 @classmethod
1323 def build_image(cls, image = IMAGE):
1324 XosSynchronizerOpenstack.build_image()
1325 Xos.build_image(image, cls.dockerfile_path)
1326
1327class XosPostgresql(Xos):
1328 ports = [5432,]
1329 NAME = 'xos-db-postgres'
1330 IMAGE = 'xosproject/xos-postgres'
1331 TAG = 'latest'
1332 PREFIX = ''
1333 volumes = ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
1334 dockerfile_path = os.path.join(Xos.setup_dir, 'postgresql')
1335
1336 def __init__(self, name = NAME, image = IMAGE, prefix = PREFIX,
A R Karthick6e80afd2016-10-10 16:03:12 -07001337 tag = TAG, boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001338 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1339
1340 @classmethod
1341 def build_image(cls, image = IMAGE):
1342 Xos.build_image(image, cls.dockerfile_path)
1343
1344class XosSyndicateMs(Xos):
1345 ports = [8080,]
1346 env = None
1347 NAME = 'xos-syndicate-ms'
1348 IMAGE = 'xosproject/syndicate-ms'
1349 TAG = 'latest'
1350 PREFIX = ''
1351 dockerfile_path = os.path.join(Xos.setup_dir, 'syndicate-ms')
1352
1353 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001354 boot_delay = 10, restart = False, network_cfg = None, update = False):
A R Karthicke3bde962016-09-27 15:06:35 -07001355 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1356
1357 @classmethod
1358 def build_image(cls, image = IMAGE):
1359 Xos.build_image(image, cls.dockerfile_path)
ChetanGaonker2c0e9bb2016-09-21 13:38:37 -07001360
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001361class XosSyncVtn(Xos):
1362 ports = [8080,]
1363 env = None
1364 NAME = 'xos-synchronizer-vtn'
1365 IMAGE = 'xosproject/xos-synchronizer-vtn'
1366 TAG = 'latest'
1367 PREFIX = ''
1368 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vtn')
1369
1370 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001371 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001372 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1373
1374 @classmethod
1375 def build_image(cls, image = IMAGE):
1376 Xos.build_image(image, cls.dockerfile_path)
1377
1378class XosSyncVtr(Xos):
1379 ports = [8080,]
1380 env = None
1381 NAME = 'xos-synchronizer-vtr'
1382 IMAGE = 'xosproject/xos-synchronizer-vtr'
1383 TAG = 'latest'
1384 PREFIX = ''
1385 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vtr')
1386
1387 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001388 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001389 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1390
1391 @classmethod
1392 def build_image(cls, image = IMAGE):
1393 Xos.build_image(image, cls.dockerfile_path)
1394
1395class XosSyncVsg(Xos):
1396 ports = [8080,]
1397 env = None
1398 NAME = 'xos-synchronizer-vsg'
1399 IMAGE = 'xosproject/xos-synchronizer-vsg'
1400 TAG = 'latest'
1401 PREFIX = ''
1402 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-vsg')
1403
1404 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001405 boot_delay = 10, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001406 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1407
1408 @classmethod
1409 def build_image(cls, image = IMAGE):
1410 Xos.build_image(image, cls.dockerfile_path)
1411
1412
1413class XosSyncOnos(Xos):
1414 ports = [8080,]
1415 env = None
1416 NAME = 'xos-synchronizer-onos'
1417 IMAGE = 'xosproject/xos-synchronizer-onos'
1418 TAG = 'latest'
1419 PREFIX = ''
1420 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-onos')
1421
1422 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001423 boot_delay = 30, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001424 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1425
1426 @classmethod
1427 def build_image(cls, image = IMAGE):
1428 Xos.build_image(image, cls.dockerfile_path)
1429
1430class XosSyncFabric(Xos):
1431 ports = [8080,]
1432 env = None
1433 NAME = 'xos-synchronizer-fabric'
1434 IMAGE = 'xosproject/xos-synchronizer-fabric'
1435 TAG = 'latest'
1436 PREFIX = ''
1437 dockerfile_path = os.path.join(Xos.setup_dir, 'synchronizer-fabric')
1438
1439 def __init__(self, name = NAME, image = IMAGE, prefix = '', tag = TAG,
A R Karthick6e80afd2016-10-10 16:03:12 -07001440 boot_delay = 30, restart = False, network_cfg = None, update = False):
ChetanGaonkerc220e0d2016-10-05 05:06:25 -07001441 Xos.__init__(self, name, image, prefix, tag, boot_delay, restart, network_cfg, update)
1442
1443 @classmethod
1444 def build_image(cls, image = IMAGE):
1445 Xos.build_image(image, cls.dockerfile_path)
A R Karthick19aaf5c2016-11-09 17:47:57 -08001446
1447if __name__ == '__main__':
1448 onos = Onos(boot_delay = 10, restart = True)