snmpit_arista_switch_daemon.py.in 11 KB
Newer Older
1
2
3
4
5
6
7
8
9
#!/usr/bin/python

#
# EMULAB-LGPL
# Copyright (c) 2012 University of Utah and the Flux Group.
# All rights reserved.
#

#
10
# Daemon server running on Arista switch side for snmpit_arista.
11
#
Weibin Sun's avatar
Weibin Sun committed
12
13
14
15
16
17
# TODO: Wrap XML-RPC method results to be a dict:
#       { 'result' : result_value,
#         'success': int 0 or 1,
#         'error'  : error string on failure, or empty on success
#       }
#
18
19

import PyClient
20
import SimpleXMLRPCServer
21
import sys
22

23
RPC_PORT = @ARISTA_SWITCH_XMLRPCPORT@
24
BIND_ADDR = ""  # This is ANY
25

26
27
28
VLAN_ID_PREFIX = "EV_"
DEFAULT_VLAN_NUM = 1

29
# Global SysDB client and configuration root
30
31
32
sysdbroot = None
sysdbclient = None

33
34
35
36
37
38
debug_level = 1;

def debug(msg, level = 1):
    if level <= debug_level:
        print("[DEBUG %d]: %s"%(level, msg))

39
40
41
42

def initSession():
    pc = PyClient.PyClient("ar", "Sysdb")
    sysdb = pc.agentRoot()
43
    return (pc, sysdb)
44
45
46
47
48

def getBridgingConfig(sysdb):
    return sysdb['bridging']['input']['config']['cli']


49
def vlanExists(sysdb, vlan_num):
50
    bc = getBridgingConfig(sysdb)
Weibin Sun's avatar
Weibin Sun committed
51
    return bc.vlanConfig.has_key(vlan_num)
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
    
def tagPort(sysdb, tags, native_vlan, port):
    bc = getBridgingConfig(sysdb)
    pbc = bc.switchIntfConfig.newMember(port)
    pbc.switchportMode = 'trunk'
    pbc.enabled = True
    pbc.trunkAllowedVlans = tags
    pbc.trunkNativeVlan = int(native_vlan)
   
def initRPCServer(bind_addr, port, funcs):
    s = SimpleXMLRPCServer.SimplerXMLRPCServer((bind_addr, port))
    for f in funcs:
        s.register_function(f[0], f[1])
    return s

#
# XML-RPC method functions
#

71
72
73
74
#
# Return "1" if succeed, error string otherwise
# 
def _createVlan(vlan_id, vlan_num):
Weibin Sun's avatar
Weibin Sun committed
75
    retval = None
76
77
78
79
    try:
        bc = getBridgingConfig(sysdbroot)
        nv = bc.vlanConfig.newMember(int(vlan_num))
        nv.configuredName = VLAN_ID_PREFIX + str(vlan_id)
Weibin Sun's avatar
Weibin Sun committed
80
        retval = 1
81
82
83
84
85
    except:
        print("_createVlan(",
              str(vlan_id), ",",
              str(vlan_num), ") error: ",
              str(sys.exc_info()))
Weibin Sun's avatar
Weibin Sun committed
86
        retval = str(sys.exc_info())
87

Weibin Sun's avatar
Weibin Sun committed
88
    return retval
89

90
91
92
#
# Return 1 on success, error string on failure.
#
93
def _removeVlan(vlan_num):
Weibin Sun's avatar
Weibin Sun committed
94
    retval = None
95
96
97
98
    try:
        bc = getBridgingConfig(sysdbroot)
        if vlanExists(sysdbroot, int(vlan_num)):
            del bc.vlanConfig[int(vlan_num)]
Weibin Sun's avatar
Weibin Sun committed
99
            retval =1
100
        else:
Weibin Sun's avatar
Weibin Sun committed
101
            retval = "VLAN #%d not exists."%(int(vlan_num),)
102
103
104
105
    except:
        print("_removeVlan(",
              str(vlan_num), ") error: ",
              str(sys.exc_info()))
Weibin Sun's avatar
Weibin Sun committed
106
        retval = str(sys.exc_info())
107

Weibin Sun's avatar
Weibin Sun committed
108
    return retval
109

110
111
112
113
114
115
#
# Assign ports to a VLAN, and enable them.
#
# Return #errors.
# 
def _setPortVlan(vlan_num, ports):
Weibin Sun's avatar
Weibin Sun committed
116
    errors = 0
117
118
119
120
121
122
    try:
        bc = getBridgingConfig(sysdbroot)
        
        if not vlanExists(sysdbroot, vlan_num):
            debug("setPortVlan: VLAN #%d not exists."%(int(vlan_num),))
            return 0
123
124
125
126
127
    
        for p in ports:
            try:
                pbc = bc.switchIntfConfig.newMember(p)
            except:
128
129
                debug("setPortVlan: Errors when getting port %s, %s"
                      %(str(p), str(sys.exc_info())))
130
131
                errors += 1
            else:
132
133
134
                pbc.switchportMode = 'access'
                pbc.enabled = True
                pbc.accessVlan = int(vlan_num)
Weibin Sun's avatar
Weibin Sun committed
135

136
137
138
139
140
    except:
        print("_setPortVlan(",
              str(vlan_num), ",",
              str(ports), ") error: ",
              str(sys.exc_info()))
Weibin Sun's avatar
Weibin Sun committed
141
142

    return errors
143

144
145
146
147
148
149

#
# Return #errors.
# If ports is empty, remove all ports from the VLAN.
#
def _removePortsFromVlan(vlan_num, ports):
Weibin Sun's avatar
Weibin Sun committed
150
    errors = 0
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
    try:
        bc = getBridgingConfig(sysdbroot)
        
        if vlanExists(sysdbroot, int(vlan_num)):
            if len(ports) == 0:
                ports = bc.switchIntfConfig.keys()
                
            for p in ports:
                try:
                    pbc = bc.switchIntfConfig.newMember(p)
                except:
                    debug("removePortsFromVlan: Errors when getting port %s, %s"
                          %(str(p), str(sys_exc_info())))
                    errors += 1
                else:
                    if pbc.accessVlan == int(vlan_num):
                        pbc.accessVlan = DEFAULT_VLAN_NUM

    except:
        print("_removePortsFromVlan(",
              str(vlan_num), ",",
              str(ports), ") error: ",
              str(sys.exc_info()))
Weibin Sun's avatar
Weibin Sun committed
174
        errors = 1
175

Weibin Sun's avatar
Weibin Sun committed
176
177
    return errors
    
178
179
180
181
#
# Return 1 if exists, 0 otherwise
#
def _vlanTagExist(tag):
Weibin Sun's avatar
Weibin Sun committed
182
183
184
185
186
187
188
189
    try:
        bc = getBridgingConfig(sysdbroot)
        if bc.vlanConfig.has_key(int(tag)):
            return 1
    except:
        print("_vlanTagExist(", str(tag), ") error: ", str(sys.exc_info()))
    
    return 0
190
191
192
193
194
195
196


#
# Get name -> tag mappings of given VLAN names, if vnames is empty,
# return mappings for all experiment VLANs
#
def _getVlanName2TagMappings(vnames):
197
    mps = dict()
Weibin Sun's avatar
Weibin Sun committed
198
199
200
201
202
203
204
205
206
207
208
    try:
        vc = getBridgingConfig(sysdbroot).vlanConfig
        
        for vlan in vc.keys():
            vid = vc[vlan].configuredName
            if vid.startswith(VLAN_ID_PREFIX):
                if len(vnames) == 0 or vid[len(VLAN_ID_PREFIX):] in vnames:
                    mps[vid[len(VLAN_ID_PREFIX):]] = vc[vlan].vlanId
    except:
        print("_getVlanName2TagMappings(",
              str(vnames), ") error: ", str(sys.exc_info()))        
209
210

    return mps
211

212
213
214
215
#
# Return 1 if has ports, 0 otherwise.
#
def _vlanHasPorts(vlan_num):
Weibin Sun's avatar
Weibin Sun committed
216
217
    try:
        vs = sysdbroot['bridging']['vlan']['status'].vlanStatus
218

Weibin Sun's avatar
Weibin Sun committed
219
220
221
222
223
224
225
226
227
228
        #
        # If there is sub-dir under vlanStatus, then this VLAN has at least on port.
        # Otherwise this VLAN is empty.
        #
        if vs.has_key(int(vlan_num)):
            return 1
    except:
        print("_vlanHasPorts(", str(vlan_num), ") error: ", str(sys.exc_info()))

    return 0
229
230
231
232
233
234
235

#
# List all experiment VLANs.
#
# Return list of list object: [vid, vnum, list of ports].
#
def _listVlans():
236
    vlans = []
Weibin Sun's avatar
Weibin Sun committed
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
    try:
        vs = sysdbroot['bridging']['vlan']['status'].vlanStatus
        vc = getBridgingConfig(sysdbroot).vlanConfig

        vnums = []
        for vnum in vc.keys():
            if vc[vnum].configuredName.startswith(VLAN_ID_PREFIX):
                vnums.append(vnum)
                
                for vn in vnums:
                    ports = []
                    if vs.has_key(vn):
                        ports = vs[vn].vlanPortStatus.keys()
                        
                    vid = vc[vn].configuredName[len(VLAN_ID_PREFIX):]
                    vlans.append([vid, vn, ports])
    except:        
        print("_listVlans() error: ", str(sys.exc_info()))
                        
    return vlans
257

Weibin Sun's avatar
Weibin Sun committed
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#
# Enable port's trunk mode.
#
# Note: First clear all existing allowed VLANs, then
#       set port mode, and set nativeVlan or allowedVlans.
#
# TODO: Is there any other thing as third?
#
def _enablePortTrunking(port, native_vlan_num, tag_native):
    try:
        pc = getBridgingConfig(sysdbroot).switchIntfConfig.newMember(str(port))
        
        pc.switchportMode = 'trunk'
        if int(tag_native) == 1:
            pc.trunkNativeVlan = 0
        else:
            pc.trunkNativeVlan = int(native_vlan_num)
            pc.trunkAllowedVlans = str(native_vlan_num)
        pc.enabled = True
    except:
        print("_enablePortTrunking(", str(port), ",", str(native_vlan_num),
              ",", str(tag_native), ") error: ", str(sys.exc_info()))
        return 0
Weibin Sun's avatar
Weibin Sun committed
281
282

    return 1
283

284
285
286
287

#
# Disable port's trunk mode
#
Weibin Sun's avatar
Weibin Sun committed
288
289
# Return 1 on success, 0 on failure.
#
290
def _disablePortTrunking(port):
Weibin Sun's avatar
Weibin Sun committed
291
    retval = 0
292
    try:
Weibin Sun's avatar
Weibin Sun committed
293
294
295
296
297
298
299
300
301
302
303
304
305
        pc = getBridgingConfig(sysdbroot).switchIntfConfig.newMember(str(port))
        if pc.switchportMode != 'access':
            native_vlan = pc.trunkNativeVlan
            pc.trunkAllowedVlans = ''
            pc.switchportMode = 'access'

            #
            # !!! This is a little bit aggressive.
            #
            if pc.accessVlan == 1 && native_vlan != 0:
                pc.accessVlan = native_vlan
                
            pc.enabled = True
306
    except:
Weibin Sun's avatar
Weibin Sun committed
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
359
360
        print("_disablePortTrunking(", str(port), ") error: ",
              str(sys.exc_info()))
        retval = 0
    
    return retval

#
# Helpers for VLAN ranges parsing and setting
#

# Set bits' value in bitmap according to ranges.
def setBitmapByRanges(bmp, ranges, val = 1):
    for t in ranges:
        l, u = t
        for i in range(l, u+1):
            bmp[i] = val
    return bmp

# Convert a string range to int tuple:
# '200' => (200, 200), '100-200' => (100, 200)
def stringRange2IntTuple(sr):
    bs = sr.split('-')
    return (int(bs[0]), int(bs[-1]))

# Convert a VLAN ranges string to bitmap.
def string2Bitmap(s):
    tks = filter(lambda x: x!="", s.split(","))
    ranges = map(stringRange2IntTuple, tks)
    bmp = [0]*4096
    return setBitmapByRanges(bmp, ranges)

# Convert bitmap to its string ranges representation.
def bitmap2String(bmp):
    s = ''
    l = 0
    u = 0
    in_range = 0
    nbmp = bmp
    nbmp.append(0)
    for i in range(1, len(bmp)):
        if nbmp[i]==1:
            if in_range==0:
                in_range = 1
                l = i
        else:
            if in_range==1:
                in_range = 0
                u = i-1
                sr = str(l)
                if l != u:
                    sr += "-%d"%(u,)
                if s != '':
                    s += ","
                s += sr
361
    
Weibin Sun's avatar
Weibin Sun committed
362
363
    return s

Weibin Sun's avatar
Weibin Sun committed
364
365
366
#
# Set allowed VLANs on trunked port.
#
Weibin Sun's avatar
Weibin Sun committed
367
368
369
370
371
372
# Return 1 on success, 1 on failure.
#
# NOTE: Arista switch CLI supports more sophisticated VLAN range, here
#       we only need deal the range value in existing trunkAllowedVlans.
#       This works because vnums are passed from snmpit, and are all
#       single numbers.
Weibin Sun's avatar
Weibin Sun committed
373
374
#
def _setAllowedVlansOnTrunkedPort(port, allow, vnums):
Weibin Sun's avatar
Weibin Sun committed
375
    retval = 0
Weibin Sun's avatar
Weibin Sun committed
376
377
378
379
380
    try:
        pc = getBridgingConfig(sysdbroot).switchIntfConfig.newMember(str(port))

        if pc.switchportMode == 'access':
            pc.switchportMode = 'trunk'
Weibin Sun's avatar
Weibin Sun committed
381
382
383
384
            pc.trunkAllowedVlans = ''

        bmp = string2Bitmap(pc.trunkAllowedVlans)
        vlan_ranges = map(lambda x: (int(x), int(x)), vnums)
Weibin Sun's avatar
Weibin Sun committed
385
        if int(allow) == 1:
Weibin Sun's avatar
Weibin Sun committed
386
            bmp = setBitmapByRanges(bmp, vlan_ranges)
Weibin Sun's avatar
Weibin Sun committed
387
        else:
Weibin Sun's avatar
Weibin Sun committed
388
389
390
391
392
393
394
395
396
397
            bmp = setBitmapByRanges(bmp, vlan_ranges, 0)
        pc.trunkAllowedVlans = bitmap2String(bmp)
        retval = 1
    except:
        print("_setAllowedVlansOnTrunkedPort(", str(port),
              ",", str(allow), ",", str(vnums), ") error: ",
              str(sys.exc_info()))
        retval = 0
        
    return retval
398

399
400
401
#
# Exported methods list
#
402
403
funcs = [(_createVlan, "createVlan"),
         (_removeVlan, "removeVlan"),
404
         (_setPortVlan, "setPortVlan"),
405
406
         (_removePortsFromVlan, "removePortsFromVlan"),
         (_vlanTagExist, "vlanTagExist"),
407
         (_getVlanName2TagMappings, "getVlanName2TagMappings"),
408
         (_vlanHasPorts, "vlanHasPorts"),
Weibin Sun's avatar
Weibin Sun committed
409
         (_listVlans, "listVlans"),
410
411
412
         (_enablePortTrunking, "enablePortTrunking"),
         (_disablePortTrunking, "disablePortTrunking"),
         (_setAllowedVlansOnTrunkedPort, "setAllowedVlansOnTrunkedPort")
413
414
         ]

415
416
s = initRPCServer(BIND_ADDR, RPC_PORT, funcs)
sysdbclient, sysdbroot = initSession()
417
s.serve_forever()