summaryrefslogtreecommitdiffhomepage
path: root/test/lib/yabgp_helper.py
blob: e13a312f60ae89b0493a6ccc1733ceef1a288587 (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
#!/usr/bin/env python3


import json
import logging
import sys

from flask import Blueprint
import flask

from yabgp.agent import prepare_service
from yabgp.common import constants
from yabgp.handler import BaseHandler
from yabgp.api import app
from yabgp.api import utils as api_utils
from yabgp.api.v1 import auth

LOG = logging.getLogger(__name__)
blueprint = Blueprint('v1-ext', __name__)
_send_update = api_utils.send_update


def _extract_afi_safi(attr):
    # MP_REACH_NLRI(14) or MP_UNREACH_NLRI(15)
    nlri = attr.get(14, None) or attr.get(15, None)
    if nlri and 'afi_safi' in nlri:
        afi_safi = nlri.get('afi_safi', None)
        return constants.AFI_SAFI_DICT.get(tuple(afi_safi), None)
    return 'ipv4'


def _construct_msg(attr, nlri, withdraw):
    return {
        'afi_safi': _extract_afi_safi(attr),
        'attr': attr,
        'nlir': nlri or [],
        'withdraw': withdraw or [],
    }


def _extract_nlri_list(msg):
    try:
        if msg['afi_safi'] == 'ipv4':
            return msg['nlri']
        return msg['attr'][14]['nlri']  # MP_REACH_NLRI(14)
    except KeyError:
        # Ignore case when no nlri
        pass
    return []


def _extract_withdraw_list(msg):
    try:
        if msg['afi_safi'] == 'ipv4':
            return msg['withdraw']
        return msg['attr'][15]['withdraw']  # MP_UNREACH_NLRI(15)
    except KeyError:
        # Ignore case when no withdraw
        pass
    return []


def _nlri_key(nlri):
    if isinstance(nlri, (dict, list)):
        return json.dumps(nlri)
    return str(nlri)


# ADJ_RIB_IN = {
#     <peer.factory.peer_addr>: {
#         <afi_safi>: {
#             <nlri>: <msg>,
#             ...
#         },
#         ...
#     },
#     ...
# }
ADJ_RIB_IN = {}


@blueprint.route('/peer/<peer_ip>/adj-rib-in')
@auth.login_required
@api_utils.log_request
def peer_adj_rib_in(peer_ip):
    """
    Dumps one peer's adj-RIB-in.
    """
    return flask.jsonify(ADJ_RIB_IN.get(peer_ip, {}))


# ADJ_RIB_OUT = {
#     <peer_ip>: {
#         <afi_safi>: {
#             <nlri>: <msg>,
#             ...
#         },
#         ...
#     },
#     ...
# }
ADJ_RIB_OUT = {}


@blueprint.route('/peer/<peer_ip>/adj-rib-out')
@auth.login_required
@api_utils.log_request
def peer_adj_rib_out(peer_ip):
    """
    Dumps one peer's adj-RIB-out.
    """
    return flask.jsonify(ADJ_RIB_OUT.get(peer_ip, {}))


app.app.register_blueprint(blueprint, url_prefix='/v1-ext')


def send_update(peer_ip, attr, nlri, withdraw):
    """
    Wrapper of "yabgp.api.send_update" in order to hook sending UPDATE
    messages via REST API.
    """
    msg = _construct_msg(attr, nlri, withdraw)
    afi_safi = msg['afi_safi']
    ADJ_RIB_OUT.setdefault(peer_ip, {})
    ADJ_RIB_OUT[peer_ip].setdefault(afi_safi, {})
    rib = ADJ_RIB_OUT[peer_ip][afi_safi]
    for _nlri in _extract_nlri_list(msg):
        rib[_nlri_key(_nlri)] = msg
    for _withdraw in _extract_withdraw_list(msg):
        rib.pop(_nlri_key(_withdraw), None)
    return _send_update(peer_ip, attr, nlri, withdraw)


setattr(api_utils, 'send_update', send_update)


class CliHandler(BaseHandler):

    def __init__(self):
        super(CliHandler, self).__init__()

    def init(self):
        pass

    def on_update_error(self, peer, timestamp, msg):
        LOG.info('[-] UPDATE ERROR: %s', msg)

    def route_refresh_received(self, peer, msg, msg_type):
        LOG.info('[+] ROUTE_REFRESH received: %s', msg)

    def keepalive_received(self, peer, timestamp):
        LOG.debug('[+] KEEPALIVE received: %s', peer.factory.peer_addr)

    def open_received(self, peer, timestamp, result):
        LOG.info('[+] OPEN received: %s', result)

    def update_received(self, peer, timestamp, msg):
        LOG.info('[+] UPDATE received: %s', msg)
        peer_addr = peer.factory.peer_addr
        afi_safi = msg['afi_safi']
        ADJ_RIB_IN.setdefault(peer.factory.peer_addr, {})
        ADJ_RIB_IN[peer_addr].setdefault(afi_safi, {})
        rib = ADJ_RIB_IN[peer_addr][afi_safi]
        for nlri in _extract_nlri_list(msg):
            rib[_nlri_key(nlri)] = msg
        for withdraw in _extract_withdraw_list(msg):
            rib.pop(_nlri_key(withdraw), None)

    def notification_received(self, peer, msg):
        LOG.info('[-] NOTIFICATION received: %s', msg)

    def on_connection_lost(self, peer):
        LOG.info('[-] CONNECTION lost: %s', peer.factory.peer_addr)

    def on_connection_failed(self, peer, msg):
        LOG.info('[-] CONNECTION failed: %s', msg)


def main():
    try:
        cli_handler = CliHandler()
        prepare_service(handler=cli_handler)
    except Exception as e:
        print(e)


if __name__ == '__main__':
    sys.exit(main())