Chetan Gaonker | cb122cc | 2016-05-10 10:58:34 -0700 | [diff] [blame^] | 1 | #!/usr/bin/env python |
Chetan Gaonker | cfcce78 | 2016-05-10 10:10:42 -0700 | [diff] [blame] | 2 | # |
| 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 Gaonker | 3533faa | 2016-04-25 17:50:14 -0700 | [diff] [blame] | 17 | import os,time |
| 18 | import io |
| 19 | import json |
| 20 | from pyroute2 import IPRoute |
| 21 | from itertools import chain |
| 22 | from nsenter import Namespace |
| 23 | from docker import Client |
| 24 | from shutil import copy |
| 25 | |
| 26 | class 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 | |
| 46 | flatten = lambda l: chain.from_iterable(l) |
| 47 | |
| 48 | class 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 Gaonker | 8e25e1b | 2016-05-02 13:42:21 -0700 | [diff] [blame] | 57 | self.quagga_config = quagga_config |
Chetan Gaonker | 3533faa | 2016-04-25 17:50:14 -0700 | [diff] [blame] | 58 | |
| 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 Gaonker | 8e25e1b | 2016-05-02 13:42:21 -0700 | [diff] [blame] | 130 | if self.quagga_config: |
Chetan Gaonker | 3533faa | 2016-04-25 17:50:14 -0700 | [diff] [blame] | 131 | self.connect_to_br() |
| 132 | self.id = ctn['Id'] |
| 133 | return ctn |
| 134 | |
| 135 | def connect_to_br(self): |
Chetan Gaonker | 8e25e1b | 2016-05-02 13:42:21 -0700 | [diff] [blame] | 136 | index = 0 |
Chetan Gaonker | 3533faa | 2016-04-25 17:50:14 -0700 | [diff] [blame] | 137 | with docker_netns(self.name) as pid: |
Chetan Gaonker | 8e25e1b | 2016-05-02 13:42:21 -0700 | [diff] [blame] | 138 | for quagga_config in self.quagga_config: |
Chetan Gaonker | 3533faa | 2016-04-25 17:50:14 -0700 | [diff] [blame] | 139 | ip = IPRoute() |
Chetan Gaonker | 8e25e1b | 2016-05-02 13:42:21 -0700 | [diff] [blame] | 140 | 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 Gaonker | 3533faa | 2016-04-25 17:50:14 -0700 | [diff] [blame] | 163 | |
| 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 Gaonker | 462d9fa | 2016-05-03 16:39:10 -0700 | [diff] [blame] | 181 | def 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 Gaonker | c0421e8 | 2016-05-04 17:23:08 -0700 | [diff] [blame] | 189 | mem = max(mem/1024/1024/2, 1) |
Chetan Gaonker | 6d0a7b0 | 2016-05-03 16:57:28 -0700 | [diff] [blame] | 190 | mem = min(mem, 16) |
Chetan Gaonker | 462d9fa | 2016-05-03 16:39:10 -0700 | [diff] [blame] | 191 | return str(mem) + 'G' |
| 192 | |
Chetan Gaonker | 3533faa | 2016-04-25 17:50:14 -0700 | [diff] [blame] | 193 | class Onos(Container): |
| 194 | |
Chetan Gaonker | 8e25e1b | 2016-05-02 13:42:21 -0700 | [diff] [blame] | 195 | quagga_config = ( { 'bridge' : 'quagga-br', 'ip': '10.10.0.4', 'mask' : 16 }, ) |
Chetan Gaonker | 462d9fa | 2016-05-03 16:39:10 -0700 | [diff] [blame] | 196 | SYSTEM_MEMORY = (get_mem(),) * 2 |
| 197 | JAVA_OPTS = '-Xms{} -Xmx{} -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode'.format(*SYSTEM_MEMORY)#-XX:+PrintGCDetails -XX:+PrintGCTimeStamps' |
Chetan Gaonker | 68d9517 | 2016-05-03 11:16:59 -0700 | [diff] [blame] | 198 | env = { 'ONOS_APPS' : 'drivers,openflow,proxyarp,aaa,igmp,vrouter', 'JAVA_OPTS' : JAVA_OPTS } |
Chetan Gaonker | 3533faa | 2016-04-25 17:50:14 -0700 | [diff] [blame] | 199 | 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 | |
| 236 | class 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 Gaonker | 7f4bf74 | 2016-05-04 15:56:08 -0700 | [diff] [blame] | 241 | host_db_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/db') |
Chetan Gaonker | 3533faa | 2016-04-25 17:50:14 -0700 | [diff] [blame] | 242 | guest_db_dir = os.path.join(os.path.sep, 'opt', 'db') |
Chetan Gaonker | 7f4bf74 | 2016-05-04 15:56:08 -0700 | [diff] [blame] | 243 | host_config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/radius-config/freeradius') |
Chetan Gaonker | 3533faa | 2016-04-25 17:50:14 -0700 | [diff] [blame] | 244 | guest_config_dir = os.path.join(os.path.sep, 'etc', 'freeradius') |
Chetan Gaonker | 7f4bf74 | 2016-05-04 15:56:08 -0700 | [diff] [blame] | 245 | start_command = os.path.join(guest_config_dir, 'start-radius.py') |
Chetan Gaonker | 3533faa | 2016-04-25 17:50:14 -0700 | [diff] [blame] | 246 | host_guest_map = ( (host_db_dir, guest_db_dir), |
| 247 | (host_config_dir, guest_config_dir) |
| 248 | ) |
Chetan Gaonker | 7f4bf74 | 2016-05-04 15:56:08 -0700 | [diff] [blame] | 249 | def __init__(self, name = 'cord-radius', image = 'cord-test/radius', tag = 'latest', |
| 250 | boot_delay = 10, restart = False): |
Chetan Gaonker | 3533faa | 2016-04-25 17:50:14 -0700 | [diff] [blame] | 251 | super(Radius, self).__init__(name, image, tag = tag, command = self.start_command) |
Chetan Gaonker | 7f4bf74 | 2016-05-04 15:56:08 -0700 | [diff] [blame] | 252 | if not self.img_exists(): |
| 253 | self.build_image(image) |
| 254 | if restart is True and self.exists(): |
| 255 | self.kill() |
Chetan Gaonker | 3533faa | 2016-04-25 17:50:14 -0700 | [diff] [blame] | 256 | 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 Gaonker | 7f4bf74 | 2016-05-04 15:56:08 -0700 | [diff] [blame] | 266 | time.sleep(boot_delay) |
| 267 | |
| 268 | @classmethod |
| 269 | def build_image(cls, image): |
| 270 | print('Building Radius image %s' %image) |
| 271 | dockerfile = ''' |
| 272 | FROM hbouvier/docker-radius |
| 273 | MAINTAINER chetan@ciena.com |
| 274 | LABEL RUN docker pull hbouvier/docker-radius |
| 275 | LABEL RUN docker run -it --name cord-radius hbouvier/docker-radius |
| 276 | RUN apt-get update |
| 277 | RUN apt-get -y install python python-pexpect strace |
| 278 | WORKDIR /root |
| 279 | CMD ["/etc/freeradius/start-radius.py"] |
| 280 | ''' |
| 281 | super(Radius, cls).build_image(dockerfile, image) |
| 282 | print('Done building image %s' %image) |
Chetan Gaonker | 3533faa | 2016-04-25 17:50:14 -0700 | [diff] [blame] | 283 | |
Chetan Gaonker | 6cf6e47 | 2016-04-26 14:41:51 -0700 | [diff] [blame] | 284 | class Quagga(Container): |
Chetan Gaonker | 8e25e1b | 2016-05-02 13:42:21 -0700 | [diff] [blame] | 285 | 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 Gaonker | 6cf6e47 | 2016-04-26 14:41:51 -0700 | [diff] [blame] | 288 | 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 Gaonker | fd3d650 | 2016-05-03 13:23:07 -0700 | [diff] [blame] | 295 | boot_delay = 15, restart = False, config_file = quagga_config_file): |
Chetan Gaonker | 6cf6e47 | 2016-04-26 14:41:51 -0700 | [diff] [blame] | 296 | 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 Gaonker | 2a6601b | 2016-05-02 17:28:26 -0700 | [diff] [blame] | 318 | onos_quagga_ip = Onos.quagga_config[0]['ip'] |
Chetan Gaonker | 6cf6e47 | 2016-04-26 14:41:51 -0700 | [diff] [blame] | 319 | print('Building Quagga image %s' %image) |
| 320 | dockerfile = ''' |
| 321 | FROM ubuntu:latest |
| 322 | WORKDIR /root |
| 323 | RUN useradd -M quagga |
| 324 | RUN mkdir /var/log/quagga && chown quagga:quagga /var/log/quagga |
| 325 | RUN mkdir /var/run/quagga && chown quagga:quagga /var/run/quagga |
| 326 | RUN apt-get update && apt-get install -qy git autoconf libtool gawk make telnet libreadline6-dev |
| 327 | RUN git clone git://git.sv.gnu.org/quagga.git quagga && \ |
| 328 | (cd quagga && git checkout HEAD && ./bootstrap.sh && \ |
| 329 | sed -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) |
| 331 | RUN ldconfig |
| 332 | '''.format(onos_quagga_ip) |
| 333 | super(Quagga, cls).build_image(dockerfile, image) |
| 334 | print('Done building image %s' %image) |
| 335 | |