blob: b56b25b9d808bd6a19845f71639bb7eebead4510 [file] [log] [blame]
Chetan Gaonkercb122cc2016-05-10 10:58:34 -07001#!/usr/bin/env python
Chetan Gaonkercfcce782016-05-10 10:10:42 -07002#
3# Copyright 2016-present Ciena Corporation
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
Chetan Gaonker3533faa2016-04-25 17:50:14 -070017import os,time
18import io
19import json
20from pyroute2 import IPRoute
21from itertools import chain
22from nsenter import Namespace
23from docker import Client
24from shutil import copy
25
26class docker_netns(object):
27
28 dckr = Client()
29 def __init__(self, name):
30 pid = int(self.dckr.inspect_container(name)['State']['Pid'])
31 if pid == 0:
32 raise Exception('no container named {0}'.format(name))
33 self.pid = pid
34
35 def __enter__(self):
36 pid = self.pid
37 if not os.path.exists('/var/run/netns'):
38 os.mkdir('/var/run/netns')
39 os.symlink('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(pid))
40 return str(pid)
41
42 def __exit__(self, type, value, traceback):
43 pid = self.pid
44 os.unlink('/var/run/netns/{0}'.format(pid))
45
46flatten = lambda l: chain.from_iterable(l)
47
48class Container(object):
49 dckr = Client()
50 def __init__(self, name, image, tag = 'latest', command = 'bash', quagga_config = None):
51 self.name = name
52 self.image = image
53 self.tag = tag
54 self.image_name = image + ':' + tag
55 self.id = None
56 self.command = command
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -070057 self.quagga_config = quagga_config
Chetan Gaonker3533faa2016-04-25 17:50:14 -070058
59 @classmethod
60 def build_image(cls, dockerfile, tag, force=True, nocache=False):
61 f = io.BytesIO(dockerfile.encode('utf-8'))
62 if force or not cls.image_exists(tag):
63 print('Build {0}...'.format(tag))
64 for line in cls.dckr.build(fileobj=f, rm=True, tag=tag, decode=True, nocache=nocache):
65 if 'stream' in line:
66 print(line['stream'].strip())
67
68 @classmethod
69 def image_exists(cls, name):
70 return name in [ctn['RepoTags'][0] for ctn in cls.dckr.images()]
71
72 @classmethod
73 def create_host_config(cls, port_list = None, host_guest_map = None, privileged = False):
74 port_bindings = None
75 binds = None
76 if port_list:
77 port_bindings = {}
78 for p in port_list:
79 port_bindings[str(p)] = str(p)
80
81 if host_guest_map:
82 binds = []
83 for h, g in host_guest_map:
84 binds.append('{0}:{1}'.format(h, g))
85
86 return cls.dckr.create_host_config(binds = binds, port_bindings = port_bindings, privileged = privileged)
87
88 @classmethod
89 def cleanup(cls, image):
90 cnt_list = filter(lambda c: c['Image'] == image, cls.dckr.containers())
91 for cnt in cnt_list:
92 print('Cleaning container %s' %cnt['Id'])
93 cls.dckr.kill(cnt['Id'])
94 cls.dckr.remove_container(cnt['Id'], force=True)
95
96 @classmethod
97 def remove_container(cls, name, force=True):
98 try:
99 cls.dckr.remove_container(name, force = force)
100 except: pass
101
102 def exists(self):
103 return '/{0}'.format(self.name) in list(flatten(n['Names'] for n in self.dckr.containers()))
104
105 def img_exists(self):
106 return self.image_name in [ctn['RepoTags'][0] for ctn in self.dckr.images()]
107
108 def ip(self):
109 cnt_list = filter(lambda c: c['Image'] == self.image_name, self.dckr.containers())
110 cnt_settings = cnt_list.pop()
111 return cnt_settings['NetworkSettings']['Networks']['bridge']['IPAddress']
112
113 def kill(self, remove = True):
114 self.dckr.kill(self.name)
115 self.dckr.remove_container(self.name, force=True)
116
117 def start(self, rm = True, ports = None, volumes = None, host_config = None,
118 environment = None, tty = False, stdin_open = True):
119
120 if rm and self.exists():
121 print('Removing container:', self.name)
122 self.dckr.remove_container(self.name, force=True)
123
124 ctn = self.dckr.create_container(image=self.image_name, ports = ports, command=self.command,
125 detach=True, name=self.name,
126 environment = environment,
127 volumes = volumes,
128 host_config = host_config, stdin_open=stdin_open, tty = tty)
129 self.dckr.start(container=self.name)
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700130 if self.quagga_config:
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700131 self.connect_to_br()
132 self.id = ctn['Id']
133 return ctn
134
135 def connect_to_br(self):
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700136 index = 0
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700137 with docker_netns(self.name) as pid:
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700138 for quagga_config in self.quagga_config:
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700139 ip = IPRoute()
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700140 br = ip.link_lookup(ifname=quagga_config['bridge'])
141 if len(br) == 0:
142 ip.link_create(ifname=quagga_config['bridge'], kind='bridge')
143 br = ip.link_lookup(ifname=quagga_config['bridge'])
144 br = br[0]
145 ip.link('set', index=br, state='up')
146 ifname = '{0}-{1}'.format(self.name, index)
147 ifs = ip.link_lookup(ifname=ifname)
148 if len(ifs) > 0:
149 ip.link_remove(ifs[0])
150 peer_ifname = '{0}-{1}'.format(pid, index)
151 ip.link_create(ifname=ifname, kind='veth', peer=peer_ifname)
152 host = ip.link_lookup(ifname=ifname)[0]
153 ip.link('set', index=host, master=br)
154 ip.link('set', index=host, state='up')
155 guest = ip.link_lookup(ifname=peer_ifname)[0]
156 ip.link('set', index=guest, net_ns_fd=pid)
157 with Namespace(pid, 'net'):
158 ip = IPRoute()
159 ip.link('set', index=guest, ifname='eth{}'.format(index+1))
160 ip.addr('add', index=guest, address=quagga_config['ip'], mask=quagga_config['mask'])
161 ip.link('set', index=guest, state='up')
162 index += 1
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700163
164 def execute(self, cmd, tty = True, stream = False, shell = False):
165 res = 0
166 if type(cmd) == str:
167 cmds = (cmd,)
168 else:
169 cmds = cmd
170 if shell:
171 for c in cmds:
172 res += os.system('docker exec {0} {1}'.format(self.name, c))
173 return res
174 for c in cmds:
175 i = self.dckr.exec_create(container=self.name, cmd=c, tty = tty, privileged = True)
176 self.dckr.exec_start(i['Id'], stream = stream, detach=True)
177 result = self.dckr.exec_inspect(i['Id'])
178 res += 0 if result['ExitCode'] == None else result['ExitCode']
179 return res
180
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700181def get_mem():
182 with open('/proc/meminfo', 'r') as fd:
183 meminfo = fd.readlines()
184 mem = 0
185 for m in meminfo:
186 if m.startswith('MemTotal:') or m.startswith('SwapTotal:'):
187 mem += int(m.split(':')[1].strip().split()[0])
188
Chetan Gaonkerc0421e82016-05-04 17:23:08 -0700189 mem = max(mem/1024/1024/2, 1)
Chetan Gaonker6d0a7b02016-05-03 16:57:28 -0700190 mem = min(mem, 16)
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700191 return str(mem) + 'G'
192
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700193class Onos(Container):
194
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700195 quagga_config = ( { 'bridge' : 'quagga-br', 'ip': '10.10.0.4', 'mask' : 16 }, )
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700196 SYSTEM_MEMORY = (get_mem(),) * 2
197 JAVA_OPTS = '-Xms{} -Xmx{} -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode'.format(*SYSTEM_MEMORY)#-XX:+PrintGCDetails -XX:+PrintGCTimeStamps'
Chetan Gaonker68d95172016-05-03 11:16:59 -0700198 env = { 'ONOS_APPS' : 'drivers,openflow,proxyarp,aaa,igmp,vrouter', 'JAVA_OPTS' : JAVA_OPTS }
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700199 ports = [ 8181, 8101, 9876, 6653, 6633, 2000, 2620 ]
200 host_config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/onos-config')
201 guest_config_dir = '/root/onos/config'
202 host_guest_map = ( (host_config_dir, guest_config_dir), )
203
204 def __init__(self, name = 'cord-onos', image = 'onosproject/onos', tag = 'latest',
205 boot_delay = 60, restart = False, network_cfg = None):
206 if restart is True:
207 ##Find the right image to restart
208 running_image = filter(lambda c: c['Names'][0] == '/{}'.format(name), self.dckr.containers())
209 if running_image:
210 image_name = running_image[0]['Image']
211 try:
212 image = image_name.split(':')[0]
213 tag = image_name.split(':')[1]
214 except: pass
215
216 super(Onos, self).__init__(name, image, tag = tag, quagga_config = self.quagga_config)
217 if restart is True and self.exists():
218 self.kill()
219 if not self.exists():
220 self.remove_container(name, force=True)
221 host_config = self.create_host_config(port_list = self.ports,
222 host_guest_map = self.host_guest_map)
223 volumes = []
224 for _,g in self.host_guest_map:
225 volumes.append(g)
226 if network_cfg is not None:
227 json_data = json.dumps(network_cfg)
228 with open('{}/network-cfg.json'.format(self.host_config_dir), 'w') as f:
229 f.write(json_data)
230 print('Starting ONOS container %s' %self.name)
231 self.start(ports = self.ports, environment = self.env,
232 host_config = host_config, volumes = volumes, tty = True)
233 print('Waiting %d seconds for ONOS to boot' %(boot_delay))
234 time.sleep(boot_delay)
235
236class Radius(Container):
237 ports = [ 1812, 1813 ]
238 env = {'TIMEZONE':'America/Los_Angeles',
239 'DEBUG': 'true', 'cert_password':'whatever', 'primary_shared_secret':'radius_password'
240 }
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700241 host_db_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/db')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700242 guest_db_dir = os.path.join(os.path.sep, 'opt', 'db')
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700243 host_config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/freeradius')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700244 guest_config_dir = os.path.join(os.path.sep, 'etc', 'freeradius')
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700245 start_command = os.path.join(guest_config_dir, 'start-radius.py')
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700246 host_guest_map = ( (host_db_dir, guest_db_dir),
247 (host_config_dir, guest_config_dir)
248 )
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700249 def __init__(self, name = 'cord-radius', image = 'cord-test/radius', tag = 'latest',
250 boot_delay = 10, restart = False):
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700251 super(Radius, self).__init__(name, image, tag = tag, command = self.start_command)
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700252 if not self.img_exists():
253 self.build_image(image)
254 if restart is True and self.exists():
255 self.kill()
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700256 if not self.exists():
257 self.remove_container(name, force=True)
258 host_config = self.create_host_config(port_list = self.ports,
259 host_guest_map = self.host_guest_map)
260 volumes = []
261 for _,g in self.host_guest_map:
262 volumes.append(g)
263 self.start(ports = self.ports, environment = self.env,
264 volumes = volumes,
265 host_config = host_config, tty = True)
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700266 time.sleep(boot_delay)
267
268 @classmethod
269 def build_image(cls, image):
270 print('Building Radius image %s' %image)
271 dockerfile = '''
272FROM hbouvier/docker-radius
273MAINTAINER chetan@ciena.com
274LABEL RUN docker pull hbouvier/docker-radius
275LABEL RUN docker run -it --name cord-radius hbouvier/docker-radius
276RUN apt-get update
277RUN apt-get -y install python python-pexpect strace
278WORKDIR /root
279CMD ["/etc/freeradius/start-radius.py"]
280'''
281 super(Radius, cls).build_image(dockerfile, image)
282 print('Done building image %s' %image)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700283
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700284class Quagga(Container):
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700285 quagga_config = ( { 'bridge' : 'quagga-br', 'ip': '10.10.0.3', 'mask' : 16 },
286 { 'bridge' : 'quagga-br', 'ip': '192.168.10.3', 'mask': 16 },
287 )
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700288 ports = [ 179, 2601, 2602, 2603, 2604, 2605, 2606 ]
289 host_quagga_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/quagga-config')
290 guest_quagga_config = '/root/config'
291 quagga_config_file = os.path.join(guest_quagga_config, 'testrib.conf')
292 host_guest_map = ( (host_quagga_config, guest_quagga_config), )
293
294 def __init__(self, name = 'cord-quagga', image = 'cord-test/quagga', tag = 'latest',
Chetan Gaonkerfd3d6502016-05-03 13:23:07 -0700295 boot_delay = 15, restart = False, config_file = quagga_config_file):
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700296 super(Quagga, self).__init__(name, image, tag = tag, quagga_config = self.quagga_config)
297 if not self.img_exists():
298 self.build_image(image)
299 if restart is True and self.exists():
300 self.kill()
301 if not self.exists():
302 self.remove_container(name, force=True)
303 host_config = self.create_host_config(port_list = self.ports,
304 host_guest_map = self.host_guest_map,
305 privileged = True)
306 volumes = []
307 for _,g in self.host_guest_map:
308 volumes.append(g)
309 self.start(ports = self.ports,
310 host_config = host_config,
311 volumes = volumes, tty = True)
312 print('Starting Quagga on container %s' %self.name)
313 self.execute('{0}/start.sh {1}'.format(self.guest_quagga_config, config_file))
314 time.sleep(boot_delay)
315
316 @classmethod
317 def build_image(cls, image):
Chetan Gaonker2a6601b2016-05-02 17:28:26 -0700318 onos_quagga_ip = Onos.quagga_config[0]['ip']
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700319 print('Building Quagga image %s' %image)
320 dockerfile = '''
321FROM ubuntu:latest
322WORKDIR /root
323RUN useradd -M quagga
324RUN mkdir /var/log/quagga && chown quagga:quagga /var/log/quagga
325RUN mkdir /var/run/quagga && chown quagga:quagga /var/run/quagga
326RUN apt-get update && apt-get install -qy git autoconf libtool gawk make telnet libreadline6-dev
327RUN git clone git://git.sv.gnu.org/quagga.git quagga && \
328(cd quagga && git checkout HEAD && ./bootstrap.sh && \
329sed -i -r 's,htonl.*?\(INADDR_LOOPBACK\),inet_addr\("{0}"\),g' zebra/zebra_fpm.c && \
330./configure --enable-fpm --disable-doc --localstatedir=/var/run/quagga && make && make install)
331RUN ldconfig
332'''.format(onos_quagga_ip)
333 super(Quagga, cls).build_image(dockerfile, image)
334 print('Done building image %s' %image)
335