-
Notifications
You must be signed in to change notification settings - Fork 390
/
controller.py
282 lines (262 loc) · 12.9 KB
/
controller.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
#
# Copyright (c) 2015 Juniper Networks, Inc. All rights reserved.
#
from analytic_client import AnalyticApiClient
import time, socket, os
from topology_uve import LinkUve
import gevent
from gevent.coros import Semaphore
from opserver.consistent_schdlr import ConsistentScheduler
import traceback
class PRouter(object):
def __init__(self, name, data):
self.name = name
self.data = data
class Controller(object):
def __init__(self, config):
self._config = config
self._me = socket.gethostname() + ':' + str(os.getpid())
self.analytic_api = AnalyticApiClient(self._config)
self.uve = LinkUve(self._config)
self.sleep_time()
self._keep_running = True
self._vnc = self._config.vnc_api()
def stop(self):
self._keep_running = False
def sleep_time(self, newtime=None):
if newtime:
self._sleep_time = newtime
else:
self._sleep_time = self._config.frequency()
return self._sleep_time
def get_vrouters(self):
self.analytic_api.get_vrouters(True)
self.vrouters = {}
self.vrouter_ips = {}
self.vrouter_macs = {}
for vr in self.analytic_api.list_vrouters():
d = self.analytic_api.get_vrouter(vr, 'VrouterAgent:phy_if')
if 'VrouterAgent' not in d:
d['VrouterAgent'] = {}
_ipl = self.analytic_api.get_vrouter(vr,
'VrouterAgent:self_ip_list')
if 'VrouterAgent' in _ipl:
d['VrouterAgent'].update(_ipl['VrouterAgent'])
if 'VrouterAgent' not in d or\
'self_ip_list' not in d['VrouterAgent'] or\
'phy_if' not in d['VrouterAgent']:
continue
self.vrouters[vr] = {'ips': d['VrouterAgent']['self_ip_list'],
'if': d['VrouterAgent']['phy_if'],
}
for ip in d['VrouterAgent']['self_ip_list']:
self.vrouter_ips[ip] = vr # index
for intf in d['VrouterAgent']['phy_if']:
try:
self.vrouter_macs[intf['mac_address']] = {}
self.vrouter_macs[intf['mac_address']]['vrname'] = vr
self.vrouter_macs[intf['mac_address']]['ifname'] = intf['name']
except:
continue
def get_prouters(self):
self.analytic_api.get_prouters(True)
self.prouters = []
for pr in self.analytic_api.list_prouters():
self.prouters.append(PRouter(pr, self.analytic_api.get_prouter(
pr, 'PRouterEntry')))
def _is_linkup(self, prouter, ifindex):
if 'PRouterEntry' in prouter.data and \
'ifIndexOperStatusTable' in prouter.data['PRouterEntry']:
status = filter(lambda x: x['ifIndex'] == ifindex,
prouter.data['PRouterEntry']['ifIndexOperStatusTable'])
if status and status[0]['ifOperStatus'] == 1:
return True
return False
def _add_link(self, prouter, remote_system_name, local_interface_name,
remote_interface_name, local_interface_index,
remote_interface_index, link_type):
d = dict(remote_system_name=remote_system_name,
local_interface_name=local_interface_name,
remote_interface_name=remote_interface_name,
local_interface_index=local_interface_index,
remote_interface_index=remote_interface_index,
type=link_type)
if self._is_linkup(prouter, local_interface_index):
if prouter.name in self.link:
self.link[prouter.name].append(d)
else:
self.link[prouter.name] = [d]
return True
return False
def _chk_lnk(self, pre, index):
if 'ifIndexOperStatusTable' in pre:
for d in pre['ifIndexOperStatusTable']:
if d['ifIndex'] == index:
return d['ifOperStatus'] == 1
return False
def bms_links(self, prouter, ifm):
if not self._vnc:
self._vnc = self._config.vnc_api()
if self._vnc:
try:
for li in self._vnc.logical_interfaces_list()[
'logical-interfaces']:
if prouter.name in li['fq_name']:
lif = self._vnc.logical_interface_read(id=li['uuid'])
for vmif in lif.get_virtual_machine_interface_refs():
vmi = self._vnc.virtual_machine_interface_read(
id=vmif['uuid'])
for mc in vmi.virtual_machine_interface_mac_addresses.get_mac_address():
ifi = [k for k in ifm if ifm[k] in li[
'fq_name']][0]
rsys = '-'.join(['bms', 'host'] + mc.split(
':'))
if self._add_link(
prouter=prouter,
remote_system_name=rsys,
local_interface_name=li['fq_name'][
-1],
remote_interface_name='em0',#no idea
local_interface_index=ifi,
remote_interface_index=1, #dont know TODO:FIX
link_type=2):
pass
except:
traceback.print_exc()
self._vnc = None # refresh
def compute(self):
self.link = {}
for prouter in self.constnt_schdlr.work_items():
pr, d = prouter.name, prouter.data
if 'PRouterEntry' not in d or 'ifTable' not in d['PRouterEntry']:
continue
self.link[pr] = []
lldp_ints = []
ifm = dict(map(lambda x: (x['ifIndex'], x['ifDescr']),
d['PRouterEntry']['ifTable']))
self.bms_links(prouter, ifm)
for pl in d['PRouterEntry']['lldpTable']['lldpRemoteSystemsData']:
if d['PRouterEntry']['lldpTable']['lldpLocalSystemData'][
'lldpLocSysDesc'].startswith('Cisco'):
loc_pname = [x for x in d['PRouterEntry']['lldpTable'][
'lldpLocalSystemData']['lldpLocPortTable'] if x[
'lldpLocPortNum'] == pl['lldpRemLocalPortNum']][
0]['lldpLocPortDesc']
pl['lldpRemLocalPortNum'] = [k for k in ifm if ifm[
k] == loc_pname][0]
if pl['lldpRemLocalPortNum'] in ifm and self._chk_lnk(
d['PRouterEntry'], pl['lldpRemLocalPortNum']):
if pl['lldpRemPortId'].isdigit():
rii = int(pl['lldpRemPortId'])
else:
try:
rpn = filter(lambda y: y['lldpLocPortId'] == pl[
'lldpRemPortId'], [
x for x in self.prouters if x.name == pl[
'lldpRemSysName']][0].data['PRouterEntry'][
'lldpTable']['lldpLocalSystemData'][
'lldpLocPortTable'])[0]['lldpLocPortDesc']
rii = filter(lambda y: y['ifDescr'] == rpn,
[ x for x in self.prouters \
if x.name == pl['lldpRemSysName']][0].data[
'PRouterEntry']['ifTable'])[0]['ifIndex']
except:
rii = 0
if self._add_link(
prouter=prouter,
remote_system_name=pl['lldpRemSysName'],
local_interface_name=ifm[pl['lldpRemLocalPortNum']],
remote_interface_name=pl['lldpRemPortDesc'],
local_interface_index=pl['lldpRemLocalPortNum'],
remote_interface_index=rii,
link_type=1):
lldp_ints.append(ifm[pl['lldpRemLocalPortNum']])
vrouter_neighbors = []
if 'fdbPortIfIndexTable' in d['PRouterEntry']:
dot1d2snmp = map (lambda x: (
x['dot1dBasePortIfIndex'],
x['snmpIfIndex']),
d['PRouterEntry']['fdbPortIfIndexTable'])
dot1d2snmp_dict = dict(dot1d2snmp)
if 'fdbPortTable' in d['PRouterEntry']:
for mac_entry in d['PRouterEntry']['fdbPortTable']:
if mac_entry['mac'] in self.vrouter_macs:
vrouter_mac_entry = self.vrouter_macs[mac_entry['mac']]
fdbport = mac_entry['dot1dBasePortIfIndex']
try:
snmpport = dot1d2snmp_dict[fdbport]
ifname = ifm[snmpport]
except:
continue
is_lldp_int = any(ifname == lldp_int for lldp_int in lldp_ints)
if is_lldp_int:
continue
if self._add_link(
prouter=prouter,
remote_system_name=vrouter_mac_entry['vrname'],
local_interface_name=ifname,
remote_interface_name=vrouter_mac_entry[
'ifname'],
local_interface_index=snmpport,
remote_interface_index=1, #dont know TODO:FIX
link_type=2):
vrouter_neighbors.append(
vrouter_mac_entry['vrname'])
for arp in d['PRouterEntry']['arpTable']:
if arp['ip'] in self.vrouter_ips:
if arp['mac'] in map(lambda x: x['mac_address'],
self.vrouters[self.vrouter_ips[arp['ip']]]['if']):
vr_name = arp['ip']
vr = self.vrouters[self.vrouter_ips[vr_name]]
if self.vrouter_ips[vr_name] in vrouter_neighbors:
continue
if ifm[arp['localIfIndex']].startswith('vlan'):
continue
if ifm[arp['localIfIndex']].startswith('irb'):
continue
is_lldp_int = any(ifm[arp['localIfIndex']] == lldp_int for lldp_int in lldp_ints)
if is_lldp_int:
continue
if self._add_link(
prouter=prouter,
remote_system_name=self.vrouter_ips[vr_name],
local_interface_name=ifm[arp['localIfIndex']],
remote_interface_name=vr['if'][-1]['name'],#TODO
local_interface_index=arp['localIfIndex'],
remote_interface_index=1, #dont know TODO:FIX
link_type=2):
pass
def send_uve(self):
self.uve.send(self.link)
def switcher(self):
gevent.sleep(0)
def scan_data(self):
t = []
t.append(gevent.spawn(self.get_vrouters))
t.append(gevent.spawn(self.get_prouters))
gevent.joinall(t)
def _del_uves(self, prouters):
with self._sem:
for prouter in prouters:
self.uve.delete(prouter.name)
def run(self):
self._sem = Semaphore()
self.constnt_schdlr = ConsistentScheduler(
self.uve._moduleid,
zookeeper=self._config.zookeeper_server(),
delete_hndlr=self._del_uves,
cluster_id=self._config.cluster_id())
while self._keep_running:
self.scan_data()
if self.constnt_schdlr.schedule(self.prouters):
try:
with self._sem:
self.compute()
self.send_uve()
except Exception as e:
import traceback; traceback.print_exc()
print str(e)
gevent.sleep(self._sleep_time)
else:
gevent.sleep(1)
self.constnt_schdlr.finish()