ulgcisco.py 30.8 KB
Newer Older
1 2 3
#!/usr/bin/env python
#
# ULG - Universal Looking Glass
4
# (C) 2012 CZ.NIC, z.s.p.o.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


# Imports
import os
import pexpect
import re
24 25
import sys
import string
26 27 28 29

import defaults

import ulgmodel
30
import ulggraph
31

32
# module globals
33 34
STRING_EXPECT_SSH_NEWKEY='Are you sure you want to continue connecting'
STRING_EXPECT_PASSWORD='(P|p)assword:'
35
STRING_EXPECT_SHELL_PROMPT_REGEXP = '\n[a-zA-Z0-9\._-]+>'
36
BGP_IPV6_SUM_TABLE_SPLITLINE_REGEXP='^\s*[0-9a-fA-F:]+\s*$'
37 38

BGP_IPV6_TABLE_HEADER_REGEXP='^\s*(Neighbor)\s+(V)\s+(AS)\s+(MsgRcvd)\s+(MsgSent)\s+(TblVer)\s+(InQ)\s+(OutQ)\s+(Up/Down)\s+(State/PfxRcd)\s*$'
39
BGP_IPV6_TABLE_LINE_REGEXP='^\s*([0-9a-fA-F:]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([a-zA-Z0-9:]+)\s+([a-zA-Z0-9\(\)]+|[a-zA-Z0-9]+\s\(Admin\))\s*$'
40
BGP_IPV4_TABLE_HEADER_REGEXP='^\s*(Neighbor)\s+(V)\s+(AS)\s+(MsgRcvd)\s+(MsgSent)\s+(TblVer)\s+(InQ)\s+(OutQ)\s+(Up/Down)\s+(State/PfxRcd)\s*$'
41 42 43
BGP_IPV4_TABLE_LINE_REGEXP='^\s*([0-9\.]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([a-zA-Z0-9:]+)\s+([a-zA-Z0-9\(\)]+|[a-zA-Z0-9]+\s\(Admin\))\s*$'

BGP_PREFIX_TABLE_HEADER='^(\s)\s+(Network)\s+(Next Hop)\s+(Metric)\s+(LocPrf)\s+(Weight)\s+(Path)\s*$'
44 45 46 47 48 49

RESCAN_BGP_IPv4_COMMAND='show bgp ipv4 unicast summary'
RESCAN_BGP_IPv6_COMMAND='show bgp ipv6 unicast summary'

MAC_ADDRESS_REGEXP = '^[0-9a-fA-F]{4}\.[0-9a-fA-F]{4}\.[0-9a-fA-F]{4}$'

50 51 52
BGP_RED_STATES = ['Idle', 'Active', '(NoNeg)']
BGP_YELLOW_STATES = ['Idle (Admin)',]

53
REGEX_SH_BGP_UNI_ASLINE = '^(\s*)([0-9\s]+)(|,.*)\s*$'
54 55 56 57 58 59 60 61 62 63 64
regex_sh_bgp_uni_asline = re.compile(REGEX_SH_BGP_UNI_ASLINE)

REGEX_SH_BGP_UNI_AGGR = '\s*\(aggregated by ([0-9]+) [0-9a-fA-F:\.]+\).*'
regex_sh_bgp_uni_aggr = re.compile(REGEX_SH_BGP_UNI_AGGR)

REGEX_SH_BGP_UNI_RECUSE = '\s*\(received & used\).*'
regex_sh_bgp_uni_recuse = re.compile(REGEX_SH_BGP_UNI_RECUSE)

REGEX_SH_BGP_UNI_RECONLY = '\s*\(received-only\).*'
regex_sh_bgp_uni_reconly = re.compile(REGEX_SH_BGP_UNI_RECONLY)

65
REGEX_SH_BGP_UNI_TABLE_START = '\s*Advertised\s+to\s+update-groups.*'
66 67 68 69 70 71 72 73
regex_sh_bgp_uni_table_start = re.compile(REGEX_SH_BGP_UNI_TABLE_START)

REGEX_SH_BGP_UNI_PEERLINE = '\s*([0-9a-fA-F:\.]+)\s.*from\s.*'
regex_sh_bgp_uni_peerline = re.compile(REGEX_SH_BGP_UNI_PEERLINE)

REGEX_SH_BGP_UNI_ORIGLINE_BEST = '\s*Origin\s.*\sbest.*'
regex_sh_bgp_uni_origline_best = re.compile(REGEX_SH_BGP_UNI_ORIGLINE_BEST)

74 75
COMMAND_NAME_GRAPH4 = 'Graph - show bgp ipv4 unicast <IP subnet>'
COMMAND_NAME_GRAPH6 = 'Graph - show bgp ipv6 unicast <IP subnet>'
76

77 78
STRING_COMMAND_LOGOUT = 'logout'

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
def cisco_parse_sh_bgp_uni(lines,prependas):
	def split_ases(ases):
		return str.split(ases)

	def get_info(info):
		res = {'recuse':False, 'reconly':False, 'aggr':None}

		for g in info.split(','):
			if(regex_sh_bgp_uni_recuse.match(g)):
				res['recuse'] = True
			if(regex_sh_bgp_uni_reconly.match(g)):
				res['reconly'] = True

			m = regex_sh_bgp_uni_aggr.match(g)
			if(m):
				res['aggr'] = m.group(1)

		return res

	paths = []
99
	table_prestarted = False
100 101 102 103 104
	table_started = False
	for l in str.splitlines(lines):
		if(table_started):
			m = regex_sh_bgp_uni_asline.match(l)
			if(m):
105
				ases = [ulgmodel.annotateAS("AS"+str(asn)) for asn in [prependas] + split_ases(m.group(2))]
106
				infotext = m.group(3)
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
				if(infotext):
					paths.append((ases,get_info(infotext)))
				else:
					paths.append((ases,{'recuse':False, 'reconly':False, 'aggr':None}))
				continue

			m = regex_sh_bgp_uni_peerline.match(l)
			if(m):
				paths[-1][1]['peer'] = m.group(1)
				continue

			m = regex_sh_bgp_uni_origline_best.match(l)
			if(m):
				paths[-1][1]['recuse'] = True
		else:
122
			if(table_prestarted):
123
				table_started = True
124 125
			if(regex_sh_bgp_uni_table_start.match(l)):
				table_prestarted = True
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

	return paths


def reduce_bgp_paths(paths):
	def has_valid(paths,onepath):
		for p in paths:
			if((onepath[0] == p[0]) and (not p[1]['reconly'])):
				return True
		return False

	def has_used(paths,onepath):
		for p in paths:
			if((onepath[0] == p[0]) and (p[1]['recuse'])):
				return True
		return False

	def assign_value(path):
		if(path[1]['recuse']):
			return 1
		elif(path[1]['reconly']):
			return 100
		else:
			return 10

	newpaths = []
	for p in paths:
		if((p[1]['reconly']) and has_valid(paths,p)):
			pass
		elif(not (p[1]['recuse']) and has_used(paths,p)):
			pass
		else:
			newpaths.append(p)
	return sorted(newpaths,key=assign_value)
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

def matchCiscoBGPLines(header,lines):
    # Match cisco lines formatted to be aligned to columns. Like:
    #    Network          Next Hop            Metric LocPrf Weight Path
    # *  79.170.248.0/21  91.210.16.6            300             0 20723 i
    # *>i91.199.207.0/24  217.31.48.123            0   1024      0 44672 i
    # 0  1                2                   3      4      5      6
    #
    #    Network          Next Hop            Metric LocPrf Weight Path
    # *>i2001:67C:278::/48
    #                     2001:1AB0:B0F4:FFFF::2
    #                                         0        1024      0 51278 i
    # *> 2001:1AB0::/32   ::                  0              32768 i
    # 0  1                2                   3      4      5      6
    #
    # First find boundaries, second section text (if it overflow next boundary
    # line wrap is expected) and then remove white spaces and return sections.
    #
    # ?1 hat happens when last element is line-wrapped? It looks like it does
    # not happen in my settings.

    def divideGroups(line,max_index_start=sys.maxint,table_line=False):
        # divide groups starting before max_index_start
        result = []

        # when parsing table_line (not the header and not the continuation line)
186
        # cut off first four charactes and use them as a group
187
        if(table_line and
188 189 190
           (not re.match('^\s*$',line[0:4]))):
            result.append([0,4])
            line = '    '+line[4:]
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

        last_group = False
        for r in re.compile('[^\s]+').finditer(line):
            if(not last_group):
                result.append([r.start(),r.end()])

            if(r.start() >= max_index_start):
                last_group = True

        # shortcut for empty lines / no results
        if(len(result)==0):
            return None

        # add tail to last groups
        result[-1][1] = len(line)
        return result


    def matchGroup(header_groups_indexes,line_group_indexes,last_element):
        if(len(header_groups_indexes) == 1):
            return 0

        # beginning of the second group is right of the beginning of the tested
        if((len(header_groups_indexes) > 1) and
           (header_groups_indexes[1][0] > line_group_indexes[0])):
            return 0

        # beginning of the last (and the only possible) group is left
        # the beginning of the tested
        if(header_groups_indexes[-1][0] <= line_group_indexes[0]):
            return (len(header_groups_indexes)-1)

        # linear algorithm !!!
        # rewrite to tree(?)
        for hgipos,hgi in enumerate(header_groups_indexes):

            if((hgipos >= 1) and
               (hgipos < (len(header_groups_indexes)-1)) and
               (header_groups_indexes[hgipos-1][1] <= line_group_indexes[0]) and
               (header_groups_indexes[hgipos+1][0] >= line_group_indexes[1])):
                return hgipos

            if((last_element) and
               (hgipos >= 1) and
               (hgi[0] <= line_group_indexes[0]) and
               (len(header_groups_indexes)-1 > hgipos) and
               (header_groups_indexes[hgipos+1][0] > line_group_indexes[0])):
                return hgipos

        return None


    def normalize(instr):
        return instr.strip()


    hgidxs = divideGroups(header)
    result = [[]]

    for l in lines:
        # divide groups (leave the last group in one part)
        lgps = divideGroups(l,hgidxs[-1][0],True)
        if(lgps==None):
            continue

        for lgpidx,lgp in enumerate(lgps):
            gidx = matchGroup(hgidxs,lgp,(lgpidx == (len(lgps)-1)))
            if(gidx == None):
                raise Exception("No group matched for line indexes. line="+l+" header_group_indexes="+
                                str(hgidxs)+" line_group_index="+str(lgp))

262

263 264 265 266 267 268 269 270 271
            if(gidx < len(result[-1])):
                result.append([])

            while(gidx > len(result[-1])):
                result[-1].append('')


            result[-1].append(normalize(l[lgp[0]:lgp[1]]))

272
    ulgmodel.debug("DEBUG bgpmatchlines:"+str(result))
273

274 275 276
    return result

def normalizeBGPIPv6SumSplitLines(lines):
277
    """This function concatenates lines with longer IPv6 addresses that
278
router splits on the header boundary."""
279
    result = []
280
    slr = re.compile(BGP_IPV6_SUM_TABLE_SPLITLINE_REGEXP)
281 282 283 284 285 286 287 288 289 290 291 292
    b = None
    
    for l in lines:
        if(b):
            result.append(b + l)
            b = None
        elif(slr.match(l)):
            b = l
        else:
            result.append(l)
            
    return result
293

294
# classes
295

296 297
class CiscoCommandBgpIPv46Sum(ulgmodel.TextCommand):
    """ Abstract class, baseline for IPv4 and IPv6 versions. """
298

299 300 301
    RED_STATES = BGP_RED_STATES
    YELLOW_STATES = BGP_YELLOW_STATES

302 303
    def __init__(self,name=None,peer_address_command=None,peer_received_command=None):
        self.command=self.COMMAND_TEXT
304
        self.param_specs=[]
305
        self.peer_address_command = peer_address_command
306
        self.peer_received_command = peer_received_command
307 308 309 310 311 312 313 314 315

        if(name==None):
            if(self.param_specs):
                self.name=self.command % tuple([('<'+str(c.getName())+'>') for c in self.param_specs])
            else:
                self.name=self.command
        else:
            self.name = name

316

317
    def _getPeerURL(self,decorator_helper,router,peer_address):
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
        if decorator_helper and self.peer_address_command:
            return decorator_helper.getRuncommandURL({'routerid':str(decorator_helper.getRouterID(router)),
                                                      'commandid':str(decorator_helper.getCommandID(router,self.peer_address_command)),
                                                      'param0':peer_address})
        else:
            return None


    def _getPeerReceivedURL(self,decorator_helper,router,peer_address):
        if decorator_helper and self.peer_received_command:
            return decorator_helper.getRuncommandURL({'routerid':str(decorator_helper.getRouterID(router)),
                                                      'commandid':str(decorator_helper.getCommandID(router,self.peer_received_command)),
                                                      'param0':peer_address})
        else:
            return None


    def _getPeerTableCell(self,decorator_helper,router,peer):
        url = self._getPeerURL(decorator_helper,router,peer)
        if url:
            return decorator_helper.ahref(url,peer)
        else:
            return peer


    def _getReceivedTableCell(self,decorator_helper,router,peer,received):
        if re.compile('[0-9]+').match(received):
            url = self._getPeerReceivedURL(decorator_helper,router,peer)
            if url:
                return decorator_helper.ahref(url,received)
            else:
                return received
        else:
            return received

353
    def _decorateTableLine(self,line,decorator_helper,router):
354
        lrm = re.compile(self.TABLE_LINE_REGEXP).match(line)
355 356
        if(lrm):
            # color selection
357
            if(lrm.group(10) in self.YELLOW_STATES):
358
                color = ulgmodel.TableDecorator.YELLOW
359
            elif(lrm.group(10) in self.RED_STATES):
360 361 362 363
                color = ulgmodel.TableDecorator.RED
            else:
                color = ulgmodel.TableDecorator.GREEN

364
            # generate table content
365
            return [
366
                (self._getPeerTableCell(decorator_helper,router,lrm.group(1)),color),
367
                (lrm.group(2),color),
368
                (decorator_helper.decorateASN(lrm.group(3),prefix=''),color),
369 370 371 372 373 374
                (lrm.group(4),color),
                (lrm.group(5),color),
                (lrm.group(6),color),
                (lrm.group(7),color),
                (lrm.group(8),color),
                (lrm.group(9),color),
375
                (self._getReceivedTableCell(decorator_helper,router,lrm.group(1),lrm.group(10)),color),
376
                ]
377
        else:
378
            raise Exception("Can not parse line: "+line)
379

380 381 382 383 384 385
    def decorateResult(self,session,decorator_helper=None):
        if(not session):
            raise Exception('Can not decorate result without valid session.')
        
        if((not session.getRouter()) or (not decorator_helper)):
            return "<pre>\n%s\n</pre>" % session.getResult()
386

387
        lines = str.splitlines(session.getResult())
388 389 390 391 392 393 394

        before=''
        after=''
        table=[]
        table_header=[]

        tb = False
395 396
        header_regexp = re.compile(self.TABLE_HEADER_REGEXP)
        line_regexp = re.compile(self.TABLE_LINE_REGEXP)
397 398 399
        for l in lines:
            if(tb):
                # inside table body
400
                table.append(self._decorateTableLine(l,decorator_helper,session.getRouter()))
401 402 403 404 405 406 407

            else:
                # should we switch to table body?
                thrm = header_regexp.match(l)
                if(thrm):
                    tb = True
                    table_header = [g for g in thrm.groups()]
408 409 410
                else:
                    # not yet in the table body, append before-table section
                    before = before + l + '\n'
411

412
        result_len = len(table)
413
        table = table[session.getRange():session.getRange()+defaults.range_step]
414 415

        return (ulgmodel.TableDecorator(table,table_header,before=decorator_helper.pre(before)).decorate(),result_len)
416 417


418 419
class CiscoCommandBgpIPv4Sum(CiscoCommandBgpIPv46Sum):
    COMMAND_TEXT='show bgp ipv4 unicast summary'
420 421
    TABLE_LINE_REGEXP=BGP_IPV4_TABLE_LINE_REGEXP
    TABLE_HEADER_REGEXP=BGP_IPV4_TABLE_HEADER_REGEXP
422 423 424 425 426 427 428

    def __init__(self,name=None,peer_address_command=None,peer_received_command=None):
        return CiscoCommandBgpIPv46Sum.__init__(self,name,peer_address_command,peer_received_command)


class CiscoCommandBgpIPv6Sum(CiscoCommandBgpIPv46Sum):
    COMMAND_TEXT='show bgp ipv6 unicast summary'
429 430
    TABLE_LINE_REGEXP=BGP_IPV6_TABLE_LINE_REGEXP
    TABLE_HEADER_REGEXP=BGP_IPV6_TABLE_HEADER_REGEXP
431 432 433 434

    def __init__(self,name=None,peer_address_command=None,peer_received_command=None):
        return CiscoCommandBgpIPv46Sum.__init__(self,name,peer_address_command,peer_received_command)

435
    def decorateResult(self,session,decorator_helper=None):
436
        res=''
437
        for l in normalizeBGPIPv6SumSplitLines(str.splitlines(session.getResult())):
438 439
            res = res + "\n" + l

440 441 442
        s = decorator_helper.copy_session(session)
        s.setResult(res)
        return super(CiscoCommandBgpIPv6Sum,self).decorateResult(s,decorator_helper)
443 444


445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
class CiscoCommandShowBgpIPv4Neigh(ulgmodel.TextCommand):
    COMMAND_TEXT='show bgp ipv4 unicast neighbor %s'

    def __init__(self,peers,name=None):
        peer_param = ulgmodel.SelectionParameter([tuple((p,p,)) for p in peers],
                                                 name=defaults.STRING_IPADDRESS)
        ulgmodel.TextCommand.__init__(self,self.COMMAND_TEXT,param_specs=[peer_param],name=name)

class CiscoCommandShowBgpIPv6Neigh(ulgmodel.TextCommand):
    COMMAND_TEXT='show bgp ipv6 unicast neighbor %s'

    def __init__(self,peers,name=None):
        peer_param = ulgmodel.SelectionParameter([tuple((p,p,)) for p in peers],
                                                 name=defaults.STRING_IPADDRESS)
        ulgmodel.TextCommand.__init__(self,self.COMMAND_TEXT,param_specs=[peer_param],name=name)

461
class CiscoCommandShowBgpIPv46Select(ulgmodel.TextCommand):
462 463 464
    TABLE_HEADER_REGEXP=BGP_PREFIX_TABLE_HEADER
    LASTLINE_REGEXP='^\s*Total number of prefixes [0-9]+\s*$'

465 466 467 468 469
    def __init__(self,peers,name=None):
        peer_param = ulgmodel.SelectionParameter([tuple((p,p,)) for p in peers],
                                                      name=defaults.STRING_IPADDRESS)
        ulgmodel.TextCommand.__init__(self,self.COMMAND_TEXT,param_specs=[peer_param],name=name)

470 471 472 473 474
    def _decorateASPath(self,path,decorator_helper):
        result = ''
        for asnm in re.compile('[^\s]+').finditer(path):
            asn = asnm.group(0)
            if(asn.isdigit()):
475
                result = result + ' ' + decorator_helper.decorateASN(asn,prefix='')
476
            else:
477
                if(re.match('^\s*\{[0-9,]+\}\s*', asn)):
478 479
                    result = result + '{'
                    isnext = False
480
                    for sasnm in re.compile('([0-9]+)(,|\})').finditer(asn):
481 482 483
                        sasn = sasnm.group(0)
                        if(sasn.isdigit()):
                            if(isnext):
484
                                result = result + ',' + decorator_helper.decorateASN(sasn,prefix='')
485 486
                            else:
                                isnext = True
487
                                result = result + decorator_helper.decorateASN(sasn,prefix='')
488 489 490 491 492 493
                    result = result + '}'
                else:
                    result = result + ' ' +asn

        return result

494 495
    def _genTable(self,table_lines,decorator_helper,router):
        mls = matchCiscoBGPLines(self.table_header,table_lines)
496

497 498
        result = []
        for ml in mls:
499 500 501
		# generate table content
		result.append([
				(ml[0],),
502
				(decorator_helper.decoratePrefix(ml[1]),),
503 504 505 506 507 508 509
				(ml[2],),
				(ml[3],),
				(ml[4],),
				(ml[5],),
				(self._decorateASPath(ml[6],decorator_helper),),
				])
	return result
510

511
    def decorateResult(self,session,decorator_helper=None):
512 513 514 515 516 517 518 519 520
	def restrict(lines,start,count):
            res=[]
            s=start
	    r = re.compile("^\s{6,}.*")
	    
            while(r.match(lines[s]) and s > 0):
                s=s-1

	    e=s+count
521 522
	    if(e >= len(lines)):
		    e=len(lines)-1
523 524 525 526 527
	    while(r.match(lines[e]) and e < (len(lines)-1)):
                e=e+1

	    return lines[s:e]

528 529 530 531 532
        if(not session):
            raise Exception("Can not decorate result without valid session passed.")

        if((not session.getRouter()) or (not decorator_helper)):
            return "<pre>\n%s\n</pre>" % session.getResult()
533

534
        lines = str.splitlines(session.getResult())
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565

        before=''
        after=None
        table=[]
        table_header_descr=[]

        tb = False
        header_regexp = re.compile(self.TABLE_HEADER_REGEXP)
        lastline_regexp = re.compile(self.LASTLINE_REGEXP)
        table_lines = []
        for l in lines:
            if(tb):
                # inside table body
                if(lastline_regexp.match(l)):
                    after = l
                else:
                    table_lines.append(l)

            else:
                # should we switch to table body?
                thrm = header_regexp.match(l)
                if(thrm):
                    # set header accoring to the local router alignment
                    # include (unnamed) states (=S)
                    self.table_header = 'S'+(l[1:].replace('Next Hop','Next_Hop',1))
                    tb = True
                    table_header_descr = [g for g in thrm.groups()]
                else:
                    # not yet in the table body, append before-table section
                    before = before + l + '\n'

566
        result_len = len(table_lines)
567
        if(table_lines):
568
            table = self._genTable(restrict(table_lines,session.getRange(),defaults.range_step),
569
                                   decorator_helper,session.getRouter())
570 571 572 573

        if(after):
            after=decorator_helper.pre(after)

574
        return (ulgmodel.TableDecorator(table,table_header_descr,before=decorator_helper.pre(before),
575
                                       after=after).decorate(),result_len)
576

577
        
578 579 580 581 582 583 584 585 586 587 588 589
class CiscoCommandShowBgpIPv4NeighAdv(CiscoCommandShowBgpIPv46Select):
    COMMAND_TEXT='show bgp ipv4 unicast neighbor %s advertised'

class CiscoCommandShowBgpIPv6NeighAdv(CiscoCommandShowBgpIPv46Select):
    COMMAND_TEXT='show bgp ipv6 unicast neighbor %s advertised'

class CiscoCommandShowBgpIPv4NeighRecv(CiscoCommandShowBgpIPv46Select):
    COMMAND_TEXT='show bgp ipv4 unicast neighbor %s received-routes'

class CiscoCommandShowBgpIPv6NeighRecv(CiscoCommandShowBgpIPv46Select):
    COMMAND_TEXT='show bgp ipv6 unicast neighbor %s received-routes'

590 591 592
class CiscoCommandGraphShowBgpIPv46Uni(ulgmodel.TextCommand):
    TABLE_HEADER_REGEXP=BGP_PREFIX_TABLE_HEADER

593 594 595 596
    def __init__(self,peers,name=None,param=None):
        ulgmodel.TextCommand.__init__(self,self.COMMAND_TEXT,
				      param_specs=[param],
				      name=name)
597 598

    def decorateResult(self,session,decorator_helper=None):
599
        ulgmodel.debug("IN BGP GRAPH decorateResult")
600
        if(session.isFinished()):
601
		ulgmodel.debug("IN BGP GRAPH decorateResult -> session.isFinished=TRUE")
602
		if(session.getData() != None) and (session.getData() != []):
603 604
			ulgmodel.debug("IN BGP GRAPH decorateResult -> session.getData checked OK")
			return (decorator_helper.img(decorator_helper.getSpecialContentURL(session.getSessionId()),defaults.STRING_BGP_GRAPH),1)
605
		else:
606 607
			ulgmodel.debug("IN BGP GRAPH decorateResult -> session.getData checked failed, producing error")
			return (decorator_helper.pre(defaults.STRING_BGP_GRAPH_ERROR), 1)
608
	else:
609
		ulgmodel.debug("IN BGP GRAPH decorateResult -> session.isFinished=FALSE")
610 611 612 613
		return ('',0)

    def finishHook(self,session):
	    session.setData(cisco_parse_sh_bgp_uni(session.getResult(),str(session.getRouter().getASN())))
614 615

    def getSpecialContent(self,session,**params):
616
        paths = session.getData()
617 618 619 620 621 622 623
        print "Content-type: image/png\n"
        ulggraph.bgp_graph_gen(reduce_bgp_paths(paths),start=session.getRouter().getName(),
			       end=session.getParameters()[0])

    def showRange(self):
        return False

624 625 626

class CiscoCommandGraphShowBgpIPv4Uni(CiscoCommandGraphShowBgpIPv46Uni):
    COMMAND_TEXT='show bgp ipv4 unicast %s'
627 628 629 630 631

    def __init__(self,peers,name=None):
        CiscoCommandGraphShowBgpIPv46Uni.__init__(self,peers,name,
						  param=ulgmodel.IPv4SubnetParameter())

632 633 634

class CiscoCommandGraphShowBgpIPv6Uni(CiscoCommandGraphShowBgpIPv46Uni):
    COMMAND_TEXT='show bgp ipv6 unicast %s'
635 636 637 638 639 640

    def __init__(self,peers,name=None):
        CiscoCommandGraphShowBgpIPv46Uni.__init__(self,peers,name,
						  param=ulgmodel.IPv6SubnetParameter())


641

642
class CiscoShowBgpIPv46Uni(ulgmodel.TextCommand):
643 644
	def __init__(self,param):
		ulgmodel.TextCommand.__init__(self,self.COMMAND_TEXT,[param]),
645

646 647 648 649 650 651 652
	def decorateResult(self,session,decorator_helper=None):
		def decorateLine(l):			
			m = regex_sh_bgp_uni_asline.match(l)
			if(m):
				r = m.group(1)
				ases = str.split(m.group(2))
				for asn in ases:
653
					r = r + ' ' + decorator_helper.decorateASN(asn,prefix='')
654
				r = r + m.group(3)
655
				return decorator_helper.annotateIPs(r)
656
			else:
657
				return decorator_helper.annotateIPs(l)
658 659 660 661 662 663 664 665 666 667 668


		s = str.splitlines(session.getResult())
		lbeg = 0
		lend = len(s)
		if(session.getRange() != None and self.showRange()):
			lbeg = session.getRange()
			lend = session.getRange()+defaults.range_step+1

		r=''
		table_started=False
669
		table_prestarted = False
670 671 672 673 674
		for sl in s[lbeg:lend]:
			if(table_started):
				r += decorateLine(sl) + "\n"
			else:
				r += sl + "\n"
675
				if(table_prestarted):
676
					table_started = True
677 678
				if(regex_sh_bgp_uni_table_start.match(sl)):
					table_prestarted = True
679 680 681

		return ("<pre>\n%s\n</pre>" % r, len(s))

682 683 684

class CiscoShowBgpIPv4Uni(CiscoShowBgpIPv46Uni):
	COMMAND_TEXT = 'show bgp ipv4 unicast %s'
685 686 687 688

	def __init__(self,name=None):
		CiscoShowBgpIPv46Uni.__init__(self,param=ulgmodel.IPv4SubnetParameter())

689 690 691

class CiscoShowBgpIPv6Uni(CiscoShowBgpIPv46Uni):
	COMMAND_TEXT = 'show bgp ipv6 unicast %s'
692 693 694 695

	def __init__(self,name=None):
		CiscoShowBgpIPv46Uni.__init__(self,param=ulgmodel.IPv6SubnetParameter())

696

697
class CiscoRouter(ulgmodel.RemoteRouter):
698 699 700 701 702 703 704 705 706 707
    PS_KEY_BGPV4 = '-bgpipv4'
    PS_KEY_BGPV6 = '-bgpipv6'

    def _getDefaultCommands(self):
        _show_bgp_ipv4_uni_neigh = CiscoCommandShowBgpIPv4Neigh(self.getBGPIPv4Peers())
        _show_bgp_ipv4_uni_neigh_advertised = CiscoCommandShowBgpIPv4NeighAdv(self.getBGPIPv4Peers())
        _show_bgp_ipv4_uni_neigh_received_routes = CiscoCommandShowBgpIPv4NeighRecv(self.getBGPIPv4Peers())
        _show_bgp_ipv6_uni_neigh = CiscoCommandShowBgpIPv6Neigh(self.getBGPIPv6Peers())
        _show_bgp_ipv6_uni_neigh_advertised = CiscoCommandShowBgpIPv6NeighAdv(self.getBGPIPv6Peers())
        _show_bgp_ipv6_uni_neigh_received_routes = CiscoCommandShowBgpIPv6NeighRecv(self.getBGPIPv6Peers())
708
        _graph_show_bgp_ipv4_uni = CiscoCommandGraphShowBgpIPv4Uni(self.getBGPIPv4Peers(),COMMAND_NAME_GRAPH4)
709
	_graph_show_bgp_ipv6_uni = CiscoCommandGraphShowBgpIPv6Uni(self.getBGPIPv6Peers(),COMMAND_NAME_GRAPH6)
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724

        return [ulgmodel.TextCommand('show version'),
                ulgmodel.TextCommand('show interfaces status'),
                CiscoCommandBgpIPv4Sum('show bgp ipv4 unicast summary',
                                        peer_address_command=_show_bgp_ipv4_uni_neigh,
                                       peer_received_command=_show_bgp_ipv4_uni_neigh_received_routes),
                CiscoCommandBgpIPv6Sum('show bgp ipv6 unicast summary',
                                       peer_address_command=_show_bgp_ipv6_uni_neigh,
                                       peer_received_command=_show_bgp_ipv6_uni_neigh_received_routes),
                _show_bgp_ipv4_uni_neigh,
                _show_bgp_ipv6_uni_neigh,
                _show_bgp_ipv4_uni_neigh_received_routes,
                _show_bgp_ipv6_uni_neigh_received_routes,
                _show_bgp_ipv4_uni_neigh_advertised,
                _show_bgp_ipv6_uni_neigh_advertised,
725 726
                CiscoShowBgpIPv4Uni(),
		CiscoShowBgpIPv6Uni(),
727 728
                ulgmodel.TextCommand('show ip route %s',[ulgmodel.IPv4AddressParameter()]),
                ulgmodel.TextCommand('show ipv6 unicast route %s',[ulgmodel.IPv6AddressParameter()]),
729 730 731 732
                ulgmodel.TextCommand('show ip arp %s',[ulgmodel.TextParameter('.*',name=defaults.STRING_NONEORINTORIPADDRESS)]),
                ulgmodel.TextCommand('show ipv6 neighbors %s',[ulgmodel.TextParameter('.*',name=defaults.STRING_NONEORINTORIPADDRESS)]),
                ulgmodel.TextCommand('show mac-address-table address %s',[ulgmodel.TextParameter(MAC_ADDRESS_REGEXP,name=defaults.STRING_MACADDRESS)]),
                ulgmodel.TextCommand('show mac-address-table interface %s',[ulgmodel.TextParameter('.*',name=defaults.STRING_INTERFACE)]),
733
                _graph_show_bgp_ipv4_uni,
734
		_graph_show_bgp_ipv6_uni,
735 736
                ]

737
    def __init__(self, host, user, password, port=22, commands=None, enable_bgp=True, asn='My ASN'):
738 739 740 741
        self.setHost(host)
        self.setPort(port)
        self.setUser(user)
        self.setPassword(password)
742 743 744
        self.bgp_ipv4_peers = []
        self.bgp_ipv6_peers = []
        self.setName(host)
745
	self.setASN(asn)
746 747 748 749 750 751 752

        if enable_bgp:
            if(defaults.rescan_on_display):
                self.rescanHook()
            else:
                self.loadBGPPeers()

753 754 755
        if(commands):
            self.setCommands(commands)
        else:
756 757
            self.setCommands(self._getDefaultCommands())

758 759 760 761

    def getForkNeeded(self):
        return True

762
    def rescanBGPPeers(self,command,regexp,ipv6=True):
763
        table = self.runRawSyncCommand(command)
764 765 766 767

        peers = []
        rlr = re.compile(regexp)
        if ipv6:
768
            lines = normalizeBGPIPv6SumSplitLines(str.splitlines(table))
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
        else:
            lines = str.splitlines(table)
        for tl in lines:
            rlrm = rlr.match(tl)
            if(rlrm):
                peers.append(rlrm.group(1))

        return peers

    def rescanBGPIPv4Peers(self):
        self.bgp_ipv4_peers = self.rescanBGPPeers(RESCAN_BGP_IPv4_COMMAND,BGP_IPV4_TABLE_LINE_REGEXP,False)

    def rescanBGPIPv6Peers(self):
        self.bgp_ipv6_peers = self.rescanBGPPeers(RESCAN_BGP_IPv6_COMMAND,BGP_IPV6_TABLE_LINE_REGEXP,True)
        
    def rescanHook(self):
        self.rescanBGPIPv4Peers()
        self.rescanBGPIPv6Peers()
        self.saveBGPPeers()

    def getBGPIPv4Peers(self):
        return self.bgp_ipv4_peers

    def getBGPIPv6Peers(self):
        return self.bgp_ipv6_peers

    def saveBGPPeers(self):
        key4 = self.getHost() + self.PS_KEY_BGPV4
        key6 = self.getHost() + self.PS_KEY_BGPV6

        ps = ulgmodel.PersistentStorage.load()
        ps.set(key4,self.getBGPIPv4Peers())
        ps.set(key6,self.getBGPIPv6Peers())
        ps.save()

    def loadBGPPeers(self):
        key4 = self.getHost() + self.PS_KEY_BGPV4
        key6 = self.getHost() + self.PS_KEY_BGPV6

        ps = ulgmodel.PersistentStorage.load()
        self.bgp_ipv4_peers = ps.get(key4)
        self.bgp_ipv6_peers = ps.get(key6)

        if(not self.getBGPIPv4Peers()) or (not self.getBGPIPv6Peers()):
            self.rescanHook()

815
    def runRawCommand(self,command,outfile):
816 817 818
        skiplines=1

	# connect
819
        c=defaults.bin_ssh+' -p'+str(self.getPort())+' '+str(self.getUser())+'@'+self.getHost()
820 821
        s=pexpect.spawn(c,timeout=defaults.timeout)
	s.logfile = open('/tmp/ulgcisco.log', 'w')
822

823 824
	y=0
	p=0
825
        # handle ssh
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
	while True:
		i=s.expect([STRING_EXPECT_SSH_NEWKEY,STRING_EXPECT_PASSWORD,
			    STRING_EXPECT_SHELL_PROMPT_REGEXP,pexpect.EOF,pexpect.TIMEOUT])
		if(i==0):
			if(y>1):
				raise Exception("pexpect session failed: Can not save SSH key.")

			s.sendline('yes')
			y+=1

		elif(i==1):
			if(p>1):
				raise Exception("pexpect session failed: Password not accepted.")

			s.sendline(self.password)
			p+=1
		elif(i==2): # prompt
			break
		elif(i==3):
			raise Exception("pexpect session failed: Remote server disconnected.")
		elif(i==4):
			raise Exception("pexpect session failed: Connection timeout.")
		else:
			raise Exception("pexpect session failed: Unknown error. last output: "+s.before)

	s.sendline('terminal length 0')
	s.expect(['\n',pexpect.EOF,pexpect.TIMEOUT])

	s.sendline('terminal width 0')
	s.expect(['\n',pexpect.EOF,pexpect.TIMEOUT])

	l=0
	s.sendline(command)
	while True:
		i=s.expect([STRING_EXPECT_SHELL_PROMPT_REGEXP,'\n',pexpect.EOF,pexpect.TIMEOUT])
		if(i==0): # prompt
			s.sendline(STRING_COMMAND_LOGOUT)
			s.expect(['\n',pexpect.EOF,pexpect.TIMEOUT])
			break
		elif(i==1): # anything to capture
			if(l>=skiplines):
				outfile.write(s.before + "\n")
			l+=1
		elif(i==2):
			raise Exception("pexpect session failed: Remote server disconnected.")
		elif(i==3):
			raise Exception("pexpect session failed: Connection timeout.")
		else:
			raise Exception("pexpect session failed: Unknown error. last output: "+s.before)