forked from carosio/bird-snmp-agent
-
Notifications
You must be signed in to change notification settings - Fork 8
/
birdagent.py
358 lines (323 loc) · 15 KB
/
birdagent.py
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
#
# Copyright (c) 2016 Travelping GmbH <[email protected]>
# by Tobias Hintze <[email protected]>
#
# This code is inspired and partially copied from
# https://r3blog.nl/index.php/archives/2011/02/24/bgp4-mib-support-for-bird/
# That original code does not clearly declare any license.
#
# This code also uses python-agentx library licensed under GPLv3
# (see agentx.py for details)
#
# So this code is licensed under the GPLv3 (see COPYING.GPLv3).
#
"""
birdagent - agentx code for the bird routing daemon
used by bird_bgp - for the bgp4-mib
"""
from __future__ import print_function
from past.builtins import cmp
from builtins import object
from adv_agentx import AgentX
from adv_agentx import SnmpGauge32, SnmpCounter32, SnmpIpAddress
import sys
import re
import subprocess
import glob
import dateutil.parser
from datetime import datetime
import pytz
from tzlocal import get_localzone
class BirdAgent(object):
def __init__(self, cfgfile, birdcli, sscmd):
self.cfgfile = cfgfile
self.birdcli = birdcli
self.sscmd = sscmd
bgp_states = {
"idle": 1,
"connect": 2,
"active": 3,
"opensent": 4,
"openconfirm": 5,
"established": 6,
}
_re_config_include = re.compile("^include\s*\"(/[^\"]*)\".*$")
_re_config_bgp_proto_begin = re.compile(
"^protocol bgp ([a-zA-Z0-9_]+).*\{$")
_re_config_local_as = re.compile(
"local ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+) as ([0-9]+);")
_re_config_bgp_holdtime = re.compile("hold time ([0-9]+);")
_re_config_bgp_keepalive = re.compile("keepalive time ([0-9]+);")
_re_config_remote_peer = re.compile(
"neighbor ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+) as ([0-9]+);")
_re_config_timeformat = re.compile(
"\s*timeformat\s+protocol\s+iso\s+long\s+;")
_re_config_proto_end = re.compile("^\}$")
_re_birdcli_bgp_begin = re.compile(
"^([a-zA-Z0-9_]+)\s+BGP\s+[a-zA-Z0-9-_]+\s+[a-zA-Z0-9]+\s+(\d\d\d\d-\d\d-\d\d\s\d\d:\d\d:\d\d).*$")
_re_birdcli_bgp_peer = {
"bgpPeerIdentifier": re.compile("^\s+Neighbor ID:\s+([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$"),
"bgpPeerState": re.compile("^\s+BGP state:\s+([a-zA-Z]+)$"),
"bgpPeerLocalAddr": re.compile("^\s+Source address:\s+([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$"),
"bgpPeerRemoteAddr": re.compile("^\s+Neighbor address:\s+([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$"),
"bgpPeerRemoteAs": re.compile("^\s+Neighbor AS:\s+([0-9]+)$"),
"bgpPeerInUpdates": re.compile("^\s+Import updates:\s+([0-9]+)\s+[0-9\-]+\s+[0-9\-]+\s+[0-9\-]+\s+[0-9\-]+$"),
"bgpPeerOutUpdates": re.compile("^\s+Export updates:\s+([0-9]+)\s+[0-9\-]+\s+[0-9\-]+\s+[0-9\-]+\s+[0-9\-]+$"),
"bgpPeerHoldTime": re.compile("^\s+Hold timer:\s+([0-9]+)\/[0-9]+$"),
"bgpPeerHoldTimeConfigured": re.compile("^\s+Hold timer:\s+[0-9]+\/([0-9]+)$"),
"bgpPeerKeepAlive": re.compile("^\s+Keepalive timer:\s+([0-9]+)\/[0-9]+$"),
"bgpPeerKeepAliveConfigured": re.compile("^\s+Keepalive timer:\s+[0-9]+\/([0-9]+)$"),
"bgpPeerLastError": re.compile("^\s+Last error:\s+([a-zA-Z0-9-_\ ]+)$")}
_re_birdcli_bgp_end = re.compile("^$")
_re_ss = re.compile(
"^[0-9]+\s+[0-9]+\s+([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(?:%[a-z0-9-\.]+)?:([0-9]+)\s+([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(?:%[a-z0-9-\.]+?)?:([0-9]+)")
bgp_keys = [
'bgpPeerIdentifier',
'bgpPeerState',
'bgpPeerAdminStatus',
'bgpPeerNegotiatedVersion',
'bgpPeerLocalAddr',
'bgpPeerLocalPort',
'bgpPeerRemoteAddr',
'bgpPeerRemotePort',
'bgpPeerRemoteAs',
'bgpPeerInUpdates',
'bgpPeerOutUpdates',
'bgpPeerInTotalMessages',
'bgpPeerOutTotalMessages',
'bgpPeerLastError',
'bgpPeerFsmEstablishedTransitions',
'bgpPeerFsmEstablishedTime',
'bgpPeerConnectRetryInterval',
'bgpPeerHoldTime',
'bgpPeerKeepAlive',
'bgpPeerHoldTimeConfigured',
'bgpPeerKeepAliveConfigured',
'bgpPeerMinASOriginationInterval',
'bgpPeerMinRouteAdvertisementInterval',
'bgpPeerInUpdateElapsedTime',
]
bgp_defaults = {
'bgpPeerIdentifier': SnmpIpAddress("0.0.0.0"),
'bgpPeerLocalAddr': SnmpIpAddress("0.0.0.0"),
'bgpPeerLocalPort': 0,
'bgpPeerRemoteAs': 0,
'bgpPeerRemotePort': 0,
'bgpPeerHoldTime': 0,
'bgpPeerHoldTimeConfigured': 0,
'bgpPeerKeepAlive': 0,
'bgpPeerKeepAliveConfigured': 0,
'bgpPeerState': 1,
'bgpPeerInUpdates': SnmpCounter32(0),
'bgpPeerOutUpdates': SnmpCounter32(0),
'bgpPeerAdminStatus': 2,
'bgpPeerConnectRetryInterval': 0,
'bgpPeerFsmEstablishedTime': SnmpGauge32(0),
'bgpPeerFsmEstablishedTransitions': SnmpCounter32(0),
'bgpPeerInTotalMessages': SnmpCounter32(0),
'bgpPeerInUpdateElapsedTime': SnmpGauge32(0),
'bgpPeerLastError': '0',
'bgpPeerMinASOriginationInterval': 15,
'bgpPeerMinRouteAdvertisementInterval': 30,
'bgpPeerNegotiatedVersion': 0,
'bgpPeerOutTotalMessages': SnmpCounter32(0),
}
@staticmethod
def ipCompare(ip1, ip2):
lst1 = "%3s.%3s.%3s.%3s" % tuple(ip1.split("."))
lst2 = "%3s.%3s.%3s.%3s" % tuple(ip2.split("."))
return cmp(lst1, lst2)
@staticmethod
def combinedConfigLines(filename):
"""
yield the whole bird configuration file line by line;
all include-statements are resolved/unrolled
"""
try:
with open(filename, "r") as bird_conf:
for line in bird_conf:
line = line.strip()
match = BirdAgent._re_config_include.search(line)
if not match:
yield line
else:
for subconf in glob.glob(match.group(1)):
yield "# subconf: %s (from %s)" % (subconf, line)
for subline in BirdAgent.combinedConfigLines(subconf):
yield subline
except IOError:
print("ERROR: Unable to open %s, terminating..." % filename)
sys.exit(1)
except Exception as e:
print(
"ERROR: Unexpected error in combinedConfigLines(): [%s], terminating" % e)
sys.exit(1)
@staticmethod
def bgpKeys():
return BirdAgent.bgp_keys
def getBGPState(self):
"""
fetch BGP-related state from:
* parsing configuration file
* parsing `birdc show protocols all` output
* parsing `ss` output
"""
timezone = get_localzone()
current_time = datetime.now(pytz.utc)
# fetch some data from the configuration:
cfg = {}
cfg["bgp-peers"] = {}
proto = None
for line in BirdAgent.combinedConfigLines(self.cfgfile):
if self._re_config_timeformat:
cfg["timeformat"] = True
match = self._re_config_bgp_proto_begin.search(line)
if match:
proto = match.group(1)
cfg["bgp-peers"][proto] = {}
if proto:
match = self._re_config_local_as.search(line)
if match:
cfg["bgp-peers"][proto]["bgpPeerLocalAddr"] = SnmpIpAddress(
match.group(1))
cfg["bgp-peers"][proto]["bgpPeerLocalAs"] = int(
match.group(2))
if "bgpLocalAs" not in cfg:
cfg["bgpLocalAs"] = int(match.group(2))
elif cfg["bgpLocalAs"] != int(match.group(2)):
print("WARNING: multiple local AS: %i/%i" %
(cfg["bgpLocalAs"], int(match.group(2))))
match = self._re_config_remote_peer.search(line)
if match:
cfg["bgp-peers"][proto]["bgpPeerRemoteAddr"] = SnmpIpAddress(
match.group(1))
cfg["bgp-peers"][proto]["bgpPeerRemoteAs"] = int(
match.group(2))
match = self._re_config_bgp_holdtime.search(line)
if match:
cfg["bgp-peers"][proto]["bgpPeerHoldTimeConfigured"] = int(
match.group(1))
match = self._re_config_bgp_keepalive.search(line)
if match:
cfg["bgp-peers"][proto]["bgpPeerKeepAliveConfigured"] = int(
match.group(1))
if self._re_config_proto_end.search(line):
proto = None
if "timeformat" not in cfg:
print("ERROR: timeformat not configured for this agent's use, terminating...")
sys.exit(1)
# Validate protocol's config
for proto in cfg["bgp-peers"]:
if not cfg["bgp-peers"][proto]: continue
if "bgpPeerLocalAddr" not in cfg["bgp-peers"][proto] and \
"bgpPeerLocalAs" not in cfg["bgp-peers"][proto]:
print(
"WARNING: Protocol \"%s\" does not have a properly formated 'local <ip> as <asn>;' line in the config" % proto)
if "bgpPeerRemoteAddr" not in cfg["bgp-peers"][proto] and \
"bgpPeerRemoteAs" not in cfg["bgp-peers"][proto]:
print(
"WARNING: Protocol \"%s\" does not have a properly formated 'neighbor <ip> as <asn>;' line in the config" % proto)
state = cfg.copy()
bgp_proto = None
# "with"-context-manager for Popen not available in python < 3.2
birdc = subprocess.Popen([self.birdcli, "show", "protocols", "all"],
stdout=subprocess.PIPE)
output = birdc.communicate()[0].decode('utf-8', 'ignore')
if birdc.returncode != 0:
print(
"ERROR: bird-CLI %s failed: %i" %
(self.birdcli, birdc.returncode))
for line in output.split("\n"):
match = self._re_birdcli_bgp_begin.search(line)
if match:
bgp_proto = match.group(1)
timestamp = dateutil.parser.parse(match.group(2))
if not timestamp.tzinfo:
timestamp = timezone.localize(timestamp)
if bgp_proto not in state["bgp-peers"]:
print(
"WARNING: proto \"%s\" not in config, skipping" %
bgp_proto)
continue
state["bgp-peers"][bgp_proto]["bgpPeerFsmEstablishedTime"] = SnmpGauge32(
abs(current_time - timestamp).total_seconds())
if bgp_proto:
try:
for peerprop_name, peerprop_re in list(
self._re_birdcli_bgp_peer.items()):
match = peerprop_re.search(line)
if match:
if peerprop_name == 'bgpPeerState':
if not match.group(1).lower() == 'down':
state["bgp-peers"][bgp_proto][peerprop_name] = \
self.bgp_states[match.group(1).lower()]
else:
# handle disabled (down) protocols
state["bgp-peers"][bgp_proto][peerprop_name] = int(
1)
state["bgp-peers"][bgp_proto]["bgpPeerAdminStatus"] = int(
1)
state["bgp-peers"][bgp_proto]["bgpPeerFsmEstablishedTime"] = int(
0)
elif peerprop_name in [
'bgpPeerIdentifier',
'bgpPeerLocalAddr',
'bgpPeerRemoteAddr']:
state["bgp-peers"][bgp_proto][peerprop_name] = SnmpIpAddress(
match.group(1))
elif peerprop_name in [
'bgpPeerInUpdates',
'bgpPeerOutUpdates']:
state["bgp-peers"][bgp_proto][peerprop_name] = SnmpCounter32(
match.group(1))
else:
state["bgp-peers"][bgp_proto][peerprop_name] = int(
match.group(1))
except:
print("WARNING: Unable to process \"%s\" as \"%s\" for protocol \"%s\"" %
(match.group(1), peerprop_name, bgp_proto))
if self._re_birdcli_bgp_end.search(line):
bgp_proto = None
# use ss to query for source and destination ports of the bgp protocols
bgp_sessions = {}
try:
ss = subprocess.Popen(self.sscmd, shell=True,
stdout=subprocess.PIPE)
for line in ss.communicate()[0].decode('utf-8', 'ignore').split("\n"):
match = self._re_ss.search(line)
if not match:
continue
# key 4-tuples by remote ip: src-addr, src-port, dst-addr, dst-port
bgp_sessions[match.group(3)] = match.groups()
except subprocess.CalledProcessError as e:
print(
"ERROR: Error executing \"ss\" command [%s], terminating..." % e)
sys.exit(1)
# match the connection 4-tuples with bgp-state
for proto in list(state["bgp-peers"].keys()):
if not state["bgp-peers"][proto]: continue
# enrich the state by local+remote ports
try:
srcip, srcport, dstip, dstport = bgp_sessions[state["bgp-peers"][
proto]["bgpPeerRemoteAddr"]]
except:
print("INFO: Protocol \"%s\" has no active BGP session." % proto)
try:
state["bgp-peers"][proto]["bgpPeerRemoteAddr"] = \
cfg["bgp-peers"][proto]["bgpPeerRemoteAddr"]
continue
except:
state["bgp-peers"][proto]["bgpPeerRemoteAddr"] = SnmpIpAddress(
"0.0.0.0")
continue
# Check for mismatch between config and ss output
if srcip != state["bgp-peers"][proto]["bgpPeerLocalAddr"] or \
dstip != state["bgp-peers"][proto]["bgpPeerRemoteAddr"]:
print(
"WARNING: Protocol \"%s\" has mismatch between the configuration file (local: %s, neighbor %s) and the active BGP session (local: %s, neighbor: %s)" %
(proto, state["bgp-peers"][proto]["bgpPeerLocalAddr"], state["bgp-peers"][proto]["bgpPeerRemoteAddr"], srcip, dstip))
continue
# populate the ports
state["bgp-peers"][proto]["bgpPeerLocalPort"] = int(srcport)
state["bgp-peers"][proto]["bgpPeerRemotePort"] = int(dstport)
return state