blob: de4ec2ffc381a0ffe26366cbc22b3c84e34a05fe [file] [log] [blame]
Chetan Gaonkercfcce782016-05-10 10:10:42 -07001#
2# 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
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#
Chetan Gaonker3533faa2016-04-25 17:50:14 -070016import os,time
17import io
18import json
19from pyroute2 import IPRoute
20from itertools import chain
21from nsenter import Namespace
22from docker import Client
23from shutil import copy
24
25class docker_netns(object):
26
27 dckr = Client()
28 def __init__(self, name):
29 pid = int(self.dckr.inspect_container(name)['State']['Pid'])
30 if pid == 0:
31 raise Exception('no container named {0}'.format(name))
32 self.pid = pid
33
34 def __enter__(self):
35 pid = self.pid
36 if not os.path.exists('/var/run/netns'):
37 os.mkdir('/var/run/netns')
38 os.symlink('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(pid))
39 return str(pid)
40
41 def __exit__(self, type, value, traceback):
42 pid = self.pid
43 os.unlink('/var/run/netns/{0}'.format(pid))
44
45flatten = lambda l: chain.from_iterable(l)
46
47class Container(object):
48 dckr = Client()
49 def __init__(self, name, image, tag = 'latest', command = 'bash', quagga_config = None):
50 self.name = name
51 self.image = image
52 self.tag = tag
53 self.image_name = image + ':' + tag
54 self.id = None
55 self.command = command
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -070056 self.quagga_config = quagga_config
Chetan Gaonker3533faa2016-04-25 17:50:14 -070057
58 @classmethod
59 def build_image(cls, dockerfile, tag, force=True, nocache=False):
60 f = io.BytesIO(dockerfile.encode('utf-8'))
61 if force or not cls.image_exists(tag):
62 print('Build {0}...'.format(tag))
63 for line in cls.dckr.build(fileobj=f, rm=True, tag=tag, decode=True, nocache=nocache):
64 if 'stream' in line:
65 print(line['stream'].strip())
66
67 @classmethod
68 def image_exists(cls, name):
69 return name in [ctn['RepoTags'][0] for ctn in cls.dckr.images()]
70
71 @classmethod
72 def create_host_config(cls, port_list = None, host_guest_map = None, privileged = False):
73 port_bindings = None
74 binds = None
75 if port_list:
76 port_bindings = {}
77 for p in port_list:
78 port_bindings[str(p)] = str(p)
79
80 if host_guest_map:
81 binds = []
82 for h, g in host_guest_map:
83 binds.append('{0}:{1}'.format(h, g))
84
85 return cls.dckr.create_host_config(binds = binds, port_bindings = port_bindings, privileged = privileged)
86
87 @classmethod
88 def cleanup(cls, image):
89 cnt_list = filter(lambda c: c['Image'] == image, cls.dckr.containers())
90 for cnt in cnt_list:
91 print('Cleaning container %s' %cnt['Id'])
92 cls.dckr.kill(cnt['Id'])
93 cls.dckr.remove_container(cnt['Id'], force=True)
94
95 @classmethod
96 def remove_container(cls, name, force=True):
97 try:
98 cls.dckr.remove_container(name, force = force)
99 except: pass
100
101 def exists(self):
102 return '/{0}'.format(self.name) in list(flatten(n['Names'] for n in self.dckr.containers()))
103
104 def img_exists(self):
105 return self.image_name in [ctn['RepoTags'][0] for ctn in self.dckr.images()]
106
107 def ip(self):
108 cnt_list = filter(lambda c: c['Image'] == self.image_name, self.dckr.containers())
109 cnt_settings = cnt_list.pop()
110 return cnt_settings['NetworkSettings']['Networks']['bridge']['IPAddress']
111
112 def kill(self, remove = True):
113 self.dckr.kill(self.name)
114 self.dckr.remove_container(self.name, force=True)
115
116 def start(self, rm = True, ports = None, volumes = None, host_config = None,
117 environment = None, tty = False, stdin_open = True):
118
119 if rm and self.exists():
120 print('Removing container:', self.name)
121 self.dckr.remove_container(self.name, force=True)
122
123 ctn = self.dckr.create_container(image=self.image_name, ports = ports, command=self.command,
124 detach=True, name=self.name,
125 environment = environment,
126 volumes = volumes,
127 host_config = host_config, stdin_open=stdin_open, tty = tty)
128 self.dckr.start(container=self.name)
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700129 if self.quagga_config:
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700130 self.connect_to_br()
131 self.id = ctn['Id']
132 return ctn
133
134 def connect_to_br(self):
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700135 index = 0
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700136 with docker_netns(self.name) as pid:
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700137 for quagga_config in self.quagga_config:
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700138 ip = IPRoute()
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700139 br = ip.link_lookup(ifname=quagga_config['bridge'])
140 if len(br) == 0:
Chetan Gaonker5a0fda32016-05-10 14:09:07 -0700141 ip.link_create(ifname=quagga_config['bridge'], kind='bridge')
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700142 br = ip.link_lookup(ifname=quagga_config['bridge'])
143 br = br[0]
144 ip.link('set', index=br, state='up')
145 ifname = '{0}-{1}'.format(self.name, index)
146 ifs = ip.link_lookup(ifname=ifname)
147 if len(ifs) > 0:
148 ip.link_remove(ifs[0])
149 peer_ifname = '{0}-{1}'.format(pid, index)
Chetan Gaonker5a0fda32016-05-10 14:09:07 -0700150 ip.link_create(ifname=ifname, kind='veth', peer=peer_ifname)
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700151 host = ip.link_lookup(ifname=ifname)[0]
152 ip.link('set', index=host, master=br)
153 ip.link('set', index=host, state='up')
154 guest = ip.link_lookup(ifname=peer_ifname)[0]
155 ip.link('set', index=guest, net_ns_fd=pid)
156 with Namespace(pid, 'net'):
157 ip = IPRoute()
158 ip.link('set', index=guest, ifname='eth{}'.format(index+1))
159 ip.addr('add', index=guest, address=quagga_config['ip'], mask=quagga_config['mask'])
160 ip.link('set', index=guest, state='up')
161 index += 1
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700162
163 def execute(self, cmd, tty = True, stream = False, shell = False):
164 res = 0
165 if type(cmd) == str:
166 cmds = (cmd,)
167 else:
168 cmds = cmd
169 if shell:
170 for c in cmds:
171 res += os.system('docker exec {0} {1}'.format(self.name, c))
172 return res
173 for c in cmds:
174 i = self.dckr.exec_create(container=self.name, cmd=c, tty = tty, privileged = True)
175 self.dckr.exec_start(i['Id'], stream = stream, detach=True)
176 result = self.dckr.exec_inspect(i['Id'])
177 res += 0 if result['ExitCode'] == None else result['ExitCode']
178 return res
179
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700180def get_mem():
181 with open('/proc/meminfo', 'r') as fd:
182 meminfo = fd.readlines()
183 mem = 0
184 for m in meminfo:
185 if m.startswith('MemTotal:') or m.startswith('SwapTotal:'):
186 mem += int(m.split(':')[1].strip().split()[0])
187
Chetan Gaonkerc0421e82016-05-04 17:23:08 -0700188 mem = max(mem/1024/1024/2, 1)
Chetan Gaonker6d0a7b02016-05-03 16:57:28 -0700189 mem = min(mem, 16)
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700190 return str(mem) + 'G'
191
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700192class Onos(Container):
193
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700194 quagga_config = ( { 'bridge' : 'quagga-br', 'ip': '10.10.0.4', 'mask' : 16 }, )
Chetan Gaonker462d9fa2016-05-03 16:39:10 -0700195 SYSTEM_MEMORY = (get_mem(),) * 2
196 JAVA_OPTS = '-Xms{} -Xmx{} -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode'.format(*SYSTEM_MEMORY)#-XX:+PrintGCDetails -XX:+PrintGCTimeStamps'
Chetan Gaonker68d95172016-05-03 11:16:59 -0700197 env = { 'ONOS_APPS' : 'drivers,openflow,proxyarp,aaa,igmp,vrouter', 'JAVA_OPTS' : JAVA_OPTS }
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700198 ports = [ 8181, 8101, 9876, 6653, 6633, 2000, 2620 ]
199 host_config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/onos-config')
200 guest_config_dir = '/root/onos/config'
201 host_guest_map = ( (host_config_dir, guest_config_dir), )
Chetan Gaonker503032a2016-05-12 12:06:29 -0700202 NAME = 'cord-onos'
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700203
Chetan Gaonker503032a2016-05-12 12:06:29 -0700204 def __init__(self, name = NAME, image = 'onosproject/onos', tag = 'latest',
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700205 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 Gaonker503032a2016-05-12 12:06:29 -0700249 IMAGE = 'cord-test/radius'
250 NAME = 'cord-radius'
251
252 def __init__(self, name = NAME, image = IMAGE, tag = 'latest',
253 boot_delay = 10, restart = False, update = False):
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700254 super(Radius, self).__init__(name, image, tag = tag, command = self.start_command)
Chetan Gaonker503032a2016-05-12 12:06:29 -0700255 if update is True or not self.img_exists():
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700256 self.build_image(image)
257 if restart is True and self.exists():
258 self.kill()
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700259 if not self.exists():
260 self.remove_container(name, force=True)
261 host_config = self.create_host_config(port_list = self.ports,
262 host_guest_map = self.host_guest_map)
263 volumes = []
264 for _,g in self.host_guest_map:
265 volumes.append(g)
266 self.start(ports = self.ports, environment = self.env,
267 volumes = volumes,
268 host_config = host_config, tty = True)
Chetan Gaonker7f4bf742016-05-04 15:56:08 -0700269 time.sleep(boot_delay)
270
271 @classmethod
272 def build_image(cls, image):
273 print('Building Radius image %s' %image)
274 dockerfile = '''
275FROM hbouvier/docker-radius
276MAINTAINER chetan@ciena.com
277LABEL RUN docker pull hbouvier/docker-radius
278LABEL RUN docker run -it --name cord-radius hbouvier/docker-radius
279RUN apt-get update
280RUN apt-get -y install python python-pexpect strace
281WORKDIR /root
282CMD ["/etc/freeradius/start-radius.py"]
283'''
284 super(Radius, cls).build_image(dockerfile, image)
285 print('Done building image %s' %image)
Chetan Gaonker3533faa2016-04-25 17:50:14 -0700286
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700287class Quagga(Container):
Chetan Gaonker8e25e1b2016-05-02 13:42:21 -0700288 quagga_config = ( { 'bridge' : 'quagga-br', 'ip': '10.10.0.3', 'mask' : 16 },
289 { 'bridge' : 'quagga-br', 'ip': '192.168.10.3', 'mask': 16 },
290 )
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700291 ports = [ 179, 2601, 2602, 2603, 2604, 2605, 2606 ]
292 host_quagga_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/quagga-config')
293 guest_quagga_config = '/root/config'
294 quagga_config_file = os.path.join(guest_quagga_config, 'testrib.conf')
295 host_guest_map = ( (host_quagga_config, guest_quagga_config), )
Chetan Gaonker503032a2016-05-12 12:06:29 -0700296 IMAGE = 'cord-test/quagga'
297 NAME = 'cord-quagga'
298
299 def __init__(self, name = NAME, image = IMAGE, tag = 'latest',
300 boot_delay = 15, restart = False, config_file = quagga_config_file, update = False):
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700301 super(Quagga, self).__init__(name, image, tag = tag, quagga_config = self.quagga_config)
Chetan Gaonker503032a2016-05-12 12:06:29 -0700302 if update is True or not self.img_exists():
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700303 self.build_image(image)
304 if restart is True and self.exists():
305 self.kill()
306 if not self.exists():
307 self.remove_container(name, force=True)
308 host_config = self.create_host_config(port_list = self.ports,
309 host_guest_map = self.host_guest_map,
310 privileged = True)
311 volumes = []
312 for _,g in self.host_guest_map:
313 volumes.append(g)
314 self.start(ports = self.ports,
315 host_config = host_config,
316 volumes = volumes, tty = True)
317 print('Starting Quagga on container %s' %self.name)
318 self.execute('{0}/start.sh {1}'.format(self.guest_quagga_config, config_file))
319 time.sleep(boot_delay)
320
321 @classmethod
322 def build_image(cls, image):
Chetan Gaonker2a6601b2016-05-02 17:28:26 -0700323 onos_quagga_ip = Onos.quagga_config[0]['ip']
Chetan Gaonker6cf6e472016-04-26 14:41:51 -0700324 print('Building Quagga image %s' %image)
325 dockerfile = '''
326FROM ubuntu:latest
327WORKDIR /root
328RUN useradd -M quagga
329RUN mkdir /var/log/quagga && chown quagga:quagga /var/log/quagga
330RUN mkdir /var/run/quagga && chown quagga:quagga /var/run/quagga
331RUN apt-get update && apt-get install -qy git autoconf libtool gawk make telnet libreadline6-dev
332RUN git clone git://git.sv.gnu.org/quagga.git quagga && \
333(cd quagga && git checkout HEAD && ./bootstrap.sh && \
334sed -i -r 's,htonl.*?\(INADDR_LOOPBACK\),inet_addr\("{0}"\),g' zebra/zebra_fpm.c && \
335./configure --enable-fpm --disable-doc --localstatedir=/var/run/quagga && make && make install)
336RUN ldconfig
337'''.format(onos_quagga_ip)
338 super(Quagga, cls).build_image(dockerfile, image)
339 print('Done building image %s' %image)
340