summaryrefslogtreecommitdiffhomepage
path: root/test/lib/exabgp.py
blob: 10406b6bb8854c56d467a35754c767a2e28354cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import

from fabric import colors

from lib.base import (
    BGPContainer,
    CmdBuffer,
    try_several_times,
    wait_for_completion,
)


class ExaBGPContainer(BGPContainer):

    SHARED_VOLUME = '/shared_volume'
    PID_FILE = '/var/run/exabgp.pid'

    def __init__(self, name, asn, router_id, ctn_image_name='osrg/exabgp:4.0.5'):
        super(ExaBGPContainer, self).__init__(name, asn, router_id, ctn_image_name)
        self.shared_volumes.append((self.config_dir, self.SHARED_VOLUME))

    def _pre_start_exabgp(self):
        # Create named pipes for "exabgpcli"
        named_pipes = '/run/exabgp.in /run/exabgp.out'
        self.local('mkfifo {0}'.format(named_pipes), capture=True)
        self.local('chmod 777 {0}'.format(named_pipes), capture=True)

    def _start_exabgp(self):
        cmd = CmdBuffer(' ')
        cmd << 'env exabgp.log.destination={0}/exabgpd.log'.format(self.SHARED_VOLUME)
        cmd << 'exabgp.daemon.user=root'
        cmd << 'exabgp.daemon.pid={0}'.format(self.PID_FILE)
        cmd << 'exabgp.tcp.bind="0.0.0.0" exabgp.tcp.port=179'
        cmd << 'exabgp {0}/exabgpd.conf'.format(self.SHARED_VOLUME)
        self.local(str(cmd), detach=True)

    def _wait_for_boot(self):
        def _f():
            ret = self.local('exabgpcli version > /dev/null 2>&1; echo $?', capture=True)
            return ret == '0'

        return wait_for_completion(_f)

    def run(self):
        super(ExaBGPContainer, self).run()
        self._pre_start_exabgp()
        # To start ExaBGP, it is required to configure neighbor settings, so
        # here does not start ExaBGP yet.
        # self._start_exabgp()
        return self.WAIT_FOR_BOOT

    def create_config(self):
        # Manpage of exabgp.conf(5):
        # https://github.com/Exa-Networks/exabgp/blob/master/doc/man/exabgp.conf.5
        cmd = CmdBuffer('\n')
        for peer, info in self.peers.iteritems():
            cmd << 'neighbor {0} {{'.format(info['neigh_addr'].split('/')[0])
            cmd << '    router-id {0};'.format(self.router_id)
            cmd << '    local-address {0};'.format(info['local_addr'].split('/')[0])
            cmd << '    local-as {0};'.format(self.asn)
            cmd << '    peer-as {0};'.format(peer.asn)

            caps = []
            if info['as2']:
                caps.append('        asn4 disable;')
            if info['addpath']:
                caps.append('        add-path send/receive;')
            if caps:
                cmd << '    capability {'
                for cap in caps:
                    cmd << cap
                cmd << '    }'

            if info['passwd']:
                cmd << '    md5-password "{0}";'.format(info['passwd'])

            if info['passive']:
                cmd << '    passive;'
            cmd << '}'

        with open('{0}/exabgpd.conf'.format(self.config_dir), 'w') as f:
            print colors.yellow('[{0}\'s new exabgpd.conf]'.format(self.name))
            print colors.yellow(str(cmd))
            f.write(str(cmd))

    def _is_running(self):
        ret = self.local("test -f {0}; echo $?".format(self.PID_FILE), capture=True)
        return ret == '0'

    def reload_config(self):
        if not self.peers:
            return

        def _reload():
            if self._is_running():
                self.local('/usr/bin/pkill --pidfile {0} && rm -f {0}'.format(self.PID_FILE), capture=True)
            else:
                self._start_exabgp()
                self._wait_for_boot()

            if not self._is_running():
                raise RuntimeError('Could not start ExaBGP')

        try_several_times(_reload)

    def _construct_ip_unicast(self, path):
        cmd = CmdBuffer(' ')
        cmd << str(path['prefix'])
        if path['next-hop']:
            cmd << 'next-hop {0}'.format(path['next-hop'])
        else:
            cmd << 'next-hop self'
        return str(cmd)

    def _construct_flowspec(self, path):
        cmd = CmdBuffer(' ')
        cmd << '{ match {'
        for match in path['matchs']:
            cmd << '{0};'.format(match)
        cmd << '} then {'
        for then in path['thens']:
            cmd << '{0};'.format(then)
        cmd << '} }'
        return str(cmd)

    def _construct_path_attributes(self, path):
        cmd = CmdBuffer(' ')
        if path['as-path']:
            cmd << 'as-path [{0}]'.format(' '.join(str(i) for i in path['as-path']))
        if path['med']:
            cmd << 'med {0}'.format(path['med'])
        if path['local-pref']:
            cmd << 'local-preference {0}'.format(path['local-pref'])
        if path['community']:
            cmd << 'community [{0}]'.format(' '.join(c for c in path['community']))
        if path['extended-community']:
            cmd << 'extended-community [{0}]'.format(path['extended-community'])
        if path['attr']:
            cmd << 'attribute [ {0} ]'.format(path['attr'])
        return str(cmd)

    def _construct_path(self, path, rf='ipv4', is_withdraw=False):
        cmd = CmdBuffer(' ')

        if rf in ['ipv4', 'ipv6']:
            cmd << 'route'
            cmd << self._construct_ip_unicast(path)
        elif rf in ['ipv4-flowspec', 'ipv6-flowspec']:
            cmd << 'flow route'
            cmd << self._construct_flowspec(path)
        else:
            raise ValueError('unsupported address family: %s' % rf)

        if path['identifier']:
            cmd << 'path-information {0}'.format(path['identifier'])

        if not is_withdraw:
            # Withdrawal should not require path attributes
            cmd << self._construct_path_attributes(path)

        return str(cmd)

    def add_route(self, route, rf='ipv4', attribute=None, aspath=None,
                  community=None, med=None, extendedcommunity=None,
                  nexthop=None, matchs=None, thens=None,
                  local_pref=None, identifier=None, reload_config=False):
        if not self._is_running():
            raise RuntimeError('ExaBGP is not yet running')

        self.routes.setdefault(route, [])
        path = {
            'prefix': route,
            'rf': rf,
            'attr': attribute,
            'next-hop': nexthop,
            'as-path': aspath,
            'community': community,
            'med': med,
            'local-pref': local_pref,
            'extended-community': extendedcommunity,
            'identifier': identifier,
            'matchs': matchs,
            'thens': thens,
        }

        cmd = CmdBuffer(' ')
        cmd << "exabgpcli 'announce"
        cmd << self._construct_path(path, rf=rf)
        cmd << "'"
        self.local(str(cmd), capture=True)

        self.routes[route].append(path)

    def del_route(self, route, identifier=None, reload_config=False):
        if not self._is_running():
            raise RuntimeError('ExaBGP is not yet running')

        path = None
        new_paths = []
        for p in self.routes.get(route, []):
            if p['identifier'] != identifier:
                new_paths.append(p)
            else:
                path = p
        if not path:
            return

        rf = path['rf']
        cmd = CmdBuffer(' ')
        cmd << "exabgpcli 'withdraw"
        cmd << self._construct_path(path, rf=rf, is_withdraw=True)
        cmd << "'"
        self.local(str(cmd), capture=True)

        self.routes[route] = new_paths


class RawExaBGPContainer(ExaBGPContainer):
    def __init__(self, name, config, ctn_image_name='osrg/exabgp',
                 exabgp_path=''):
        asn = None
        router_id = None
        for line in config.split('\n'):
            line = line.strip()
            if line.startswith('local-as'):
                asn = int(line[len('local-as'):].strip('; '))
            if line.startswith('router-id'):
                router_id = line[len('router-id'):].strip('; ')
        if not asn:
            raise Exception('asn not in exabgp config')
        if not router_id:
            raise Exception('router-id not in exabgp config')
        self.config = config

        super(RawExaBGPContainer, self).__init__(name, asn, router_id,
                                                 ctn_image_name, exabgp_path)

    def create_config(self):
        with open('{0}/exabgpd.conf'.format(self.config_dir), 'w') as f:
            print colors.yellow('[{0}\'s new exabgpd.conf]'.format(self.name))
            print colors.yellow(self.config)
            f.write(self.config)