github.com/osrg/gobgp/v3@v3.30.0/test/lib/exabgp.py (about) 1 # Copyright (C) 2015 Nippon Telegraph and Telephone Corporation. 2 # 3 # Licensed under the Apache License, Version 2.0 (the "License"); 4 # you may not use this file except in compliance with the License. 5 # You may obtain a copy of the License at 6 # 7 # http://www.apache.org/licenses/LICENSE-2.0 8 # 9 # Unless required by applicable law or agreed to in writing, software 10 # distributed under the License is distributed on an "AS IS" BASIS, 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 12 # implied. 13 # See the License for the specific language governing permissions and 14 # limitations under the License. 15 16 17 from lib.base import ( 18 BGPContainer, 19 CmdBuffer, 20 try_several_times, 21 wait_for_completion, 22 yellow, 23 ) 24 25 26 class ExaBGPContainer(BGPContainer): 27 28 SHARED_VOLUME = '/shared_volume' 29 PID_FILE = '/var/run/exabgp.pid' 30 31 def __init__(self, name, asn, router_id, ctn_image_name='osrg/exabgp:4.0.5'): 32 super(ExaBGPContainer, self).__init__(name, asn, router_id, ctn_image_name) 33 self.shared_volumes.append((self.config_dir, self.SHARED_VOLUME)) 34 35 def _pre_start_exabgp(self): 36 # Create named pipes for "exabgpcli" 37 named_pipes = '/run/exabgp.in /run/exabgp.out' 38 self.local('mkfifo {0}'.format(named_pipes), capture=True) 39 self.local('chmod 777 {0}'.format(named_pipes), capture=True) 40 41 def _start_exabgp(self): 42 cmd = CmdBuffer(' ') 43 cmd << 'env exabgp.log.destination={0}/exabgpd.log'.format(self.SHARED_VOLUME) 44 cmd << 'exabgp.daemon.user=root' 45 cmd << 'exabgp.daemon.pid={0}'.format(self.PID_FILE) 46 cmd << 'exabgp.tcp.bind="0.0.0.0" exabgp.tcp.port=179' 47 cmd << 'exabgp {0}/exabgpd.conf'.format(self.SHARED_VOLUME) 48 self.local(str(cmd), detach=True) 49 50 def _wait_for_boot(self): 51 def _f(): 52 ret = self.local('exabgpcli version > /dev/null 2>&1; echo $?', capture=True) 53 return ret == '0' 54 55 return wait_for_completion(_f) 56 57 def run(self): 58 super(ExaBGPContainer, self).run() 59 self._pre_start_exabgp() 60 # To start ExaBGP, it is required to configure neighbor settings, so 61 # here does not start ExaBGP yet. 62 # self._start_exabgp() 63 return self.WAIT_FOR_BOOT 64 65 def create_config(self): 66 # Manpage of exabgp.conf(5): 67 # https://github.com/Exa-Networks/exabgp/blob/master/doc/man/exabgp.conf.5 68 cmd = CmdBuffer('\n') 69 for peer, info in self.peers.items(): 70 cmd << 'neighbor {0} {{'.format(info['neigh_addr'].split('/')[0]) 71 cmd << ' router-id {0};'.format(self.router_id) 72 cmd << ' local-address {0};'.format(info['local_addr'].split('/')[0]) 73 cmd << ' local-as {0};'.format(self.asn) 74 cmd << ' peer-as {0};'.format(peer.asn) 75 76 caps = [] 77 if info['as2']: 78 caps.append(' asn4 disable;') 79 if info["addpath"] > 0: 80 caps.append(' add-path send/receive;') 81 if caps: 82 cmd << ' capability {' 83 for cap in caps: 84 cmd << cap 85 cmd << ' }' 86 87 if info['passwd']: 88 cmd << ' md5-password "{0}";'.format(info['passwd']) 89 90 if info['passive']: 91 cmd << ' passive;' 92 cmd << '}' 93 94 with open('{0}/exabgpd.conf'.format(self.config_dir), 'w') as f: 95 print(yellow('[{0}\'s new exabgpd.conf]'.format(self.name))) 96 print(yellow(str(cmd))) 97 f.write(str(cmd)) 98 99 def _is_running(self): 100 ret = self.local("test -f {0}; echo $?".format(self.PID_FILE), capture=True) 101 return ret == '0' 102 103 def reload_config(self): 104 if not self.peers: 105 return 106 107 def _reload(): 108 if self._is_running(): 109 self.local('/usr/bin/pkill --pidfile {0} && rm -f {0}'.format(self.PID_FILE), capture=True) 110 else: 111 self._start_exabgp() 112 self._wait_for_boot() 113 114 if not self._is_running(): 115 raise RuntimeError('Could not start ExaBGP') 116 117 try_several_times(_reload) 118 119 def _construct_ip_unicast(self, path): 120 cmd = CmdBuffer(' ') 121 cmd << str(path['prefix']) 122 if path['next-hop']: 123 cmd << 'next-hop {0}'.format(path['next-hop']) 124 else: 125 cmd << 'next-hop self' 126 return str(cmd) 127 128 def _construct_flowspec(self, path): 129 cmd = CmdBuffer(' ') 130 cmd << '{ match {' 131 for match in path['matchs']: 132 cmd << '{0};'.format(match) 133 cmd << '} then {' 134 for then in path['thens']: 135 cmd << '{0};'.format(then) 136 cmd << '} }' 137 return str(cmd) 138 139 def _construct_path_attributes(self, path): 140 cmd = CmdBuffer(' ') 141 if path['as-path']: 142 cmd << 'as-path [{0}]'.format(' '.join(str(i) for i in path['as-path'])) 143 if path['med']: 144 cmd << 'med {0}'.format(path['med']) 145 if path['local-pref']: 146 cmd << 'local-preference {0}'.format(path['local-pref']) 147 if path['community']: 148 cmd << 'community [{0}]'.format(' '.join(c for c in path['community'])) 149 if path['extended-community']: 150 cmd << 'extended-community [{0}]'.format(path['extended-community']) 151 if path['attr']: 152 cmd << 'attribute [ {0} ]'.format(path['attr']) 153 return str(cmd) 154 155 def _construct_path(self, path, rf='ipv4', is_withdraw=False): 156 cmd = CmdBuffer(' ') 157 158 if rf in ['ipv4', 'ipv6']: 159 cmd << 'route' 160 cmd << self._construct_ip_unicast(path) 161 elif rf in ['ipv4-flowspec', 'ipv6-flowspec']: 162 cmd << 'flow route' 163 cmd << self._construct_flowspec(path) 164 else: 165 raise ValueError('unsupported address family: %s' % rf) 166 167 if path['identifier']: 168 cmd << 'path-information {0}'.format(path['identifier']) 169 170 if not is_withdraw: 171 # Withdrawal should not require path attributes 172 cmd << self._construct_path_attributes(path) 173 174 return str(cmd) 175 176 def add_route(self, route, rf='ipv4', attribute=None, aspath=None, 177 community=None, med=None, extendedcommunity=None, 178 nexthop=None, matchs=None, thens=None, 179 local_pref=None, identifier=None, reload_config=False): 180 if not self._is_running(): 181 raise RuntimeError('ExaBGP is not yet running') 182 183 self.routes.setdefault(route, []) 184 path = { 185 'prefix': route, 186 'rf': rf, 187 'attr': attribute, 188 'next-hop': nexthop, 189 'as-path': aspath, 190 'community': community, 191 'med': med, 192 'local-pref': local_pref, 193 'extended-community': extendedcommunity, 194 'identifier': identifier, 195 'matchs': matchs, 196 'thens': thens, 197 } 198 199 cmd = CmdBuffer(' ') 200 cmd << "exabgpcli 'announce" 201 cmd << self._construct_path(path, rf=rf) 202 cmd << "'" 203 self.local(str(cmd), capture=True) 204 205 self.routes[route].append(path) 206 207 def del_route(self, route, identifier=None, reload_config=False): 208 if not self._is_running(): 209 raise RuntimeError('ExaBGP is not yet running') 210 211 path = None 212 new_paths = [] 213 for p in self.routes.get(route, []): 214 if p['identifier'] != identifier: 215 new_paths.append(p) 216 else: 217 path = p 218 if not path: 219 return 220 221 rf = path['rf'] 222 cmd = CmdBuffer(' ') 223 cmd << "exabgpcli 'withdraw" 224 cmd << self._construct_path(path, rf=rf, is_withdraw=True) 225 cmd << "'" 226 self.local(str(cmd), capture=True) 227 228 self.routes[route] = new_paths 229 230 def _get_adj_rib(self, peer, rf, in_out='in'): 231 # IPv4 Unicast: 232 # neighbor 172.17.0.2 ipv4 unicast 192.168.100.0/24 path-information 0.0.0.20 next-hop self 233 # IPv6 FlowSpec: 234 # neighbor 172.17.0.2 ipv6 flow flow destination-ipv6 2002:1::/64/0 source-ipv6 2002:2::/64/0 next-header =udp flow-label >100 235 rf_map = { 236 'ipv4': ['ipv4', 'unicast'], 237 'ipv6': ['ipv6', 'unicast'], 238 'ipv4-flowspec': ['ipv4', 'flow'], 239 'ipv6-flowspec': ['ipv6', 'flow'], 240 } 241 assert rf in rf_map 242 assert in_out in ('in', 'out') 243 peer_addr = self.peer_name(peer) 244 lines = self.local('exabgpcli show adj-rib {0}'.format(in_out), capture=True).split('\n') 245 # rib = { 246 # <nlri>: [ 247 # { 248 # 'nlri': <nlri>, 249 # 'next-hop': <next-hop>, 250 # ... 251 # }, 252 # ... 253 # ], 254 # } 255 rib = {} 256 for line in lines: 257 if not line: 258 continue 259 values = line.split() 260 if peer_addr != values[1]: 261 continue 262 elif rf is not None and rf_map[rf] != values[2:4]: 263 continue 264 if rf in ('ipv4', 'ipv6'): 265 nlri = values[4] 266 rib.setdefault(nlri, []) 267 path = {k: v for k, v in zip(*[iter(values[5:])] * 2)} 268 path['nlri'] = nlri 269 rib[nlri].append(path) 270 elif rf in ('ipv4-flowspec', 'ipv6-flowspec'): 271 # XXX: Missing path attributes? 272 nlri = ' '.join(values[5:]) 273 rib.setdefault(nlri, []) 274 path = {'nlri': nlri} 275 rib[nlri].append(path) 276 return rib 277 278 def get_adj_rib_in(self, peer, rf='ipv4'): 279 return self._get_adj_rib(peer, rf, 'in') 280 281 def get_adj_rib_out(self, peer, rf='ipv4'): 282 return self._get_adj_rib(peer, rf, 'out') 283 284 285 class RawExaBGPContainer(ExaBGPContainer): 286 def __init__(self, name, config, ctn_image_name='osrg/exabgp', 287 exabgp_path=''): 288 asn = None 289 router_id = None 290 for line in config.split('\n'): 291 line = line.strip() 292 if line.startswith('local-as'): 293 asn = int(line[len('local-as'):].strip('; ')) 294 if line.startswith('router-id'): 295 router_id = line[len('router-id'):].strip('; ') 296 if not asn: 297 raise Exception('asn not in exabgp config') 298 if not router_id: 299 raise Exception('router-id not in exabgp config') 300 self.config = config 301 302 super(RawExaBGPContainer, self).__init__(name, asn, router_id, 303 ctn_image_name, exabgp_path) 304 305 def create_config(self): 306 with open('{0}/exabgpd.conf'.format(self.config_dir), 'w') as f: 307 print(yellow('[{0}\'s new exabgpd.conf]'.format(self.name))) 308 print(yellow(self.config)) 309 f.write(self.config)