snmpit_apcon.pm 34.7 KB
Newer Older
1 2 3 4
#!/usr/bin/perl -W

#
# EMULAB-LGPL
5
# Copyright (c) 2010 University of Utah and the Flux Group.
6 7 8 9 10 11 12 13 14 15 16 17 18
# All rights reserved.
#

#
# snmpit module for Apcon 2000 series layer 1 switch
#

package snmpit_apcon;
use strict;

$| = 1; # Turn off line buffering on output

use English;
19
use SNMP; 
20
use snmpit_lib;
21
use libdb;
22 23

use libtestbed;
24 25 26 27 28 29 30 31 32 33 34 35
use Expect;


# CLI constants
my $CLI_UNNAMED_PATTERN = "[Uu]nnamed";
my $CLI_UNNAMED_NAME = "unnamed";
my $CLI_NOCONNECTION = "A00";
my $CLI_TIMEOUT = 10000;

# commands to show something
my $CLI_SHOW_CONNECTIONS = "show connections raw\r";
my $CLI_SHOW_PORT_NAMES  = "show port names *\r";
36
my $CLI_SHOW_PORT_RATES  = "show port rate raw *\r";
37 38 39 40 41 42

# mappings from port control command to CLI command
my %portCMDs =
(
    "enable" => "00",
    "disable"=> "00",
43 44
    "1000mbit"=> "9F",
    "100mbit"=> "9B",
45 46 47
    "10mbit" => "99",
    "auto"   => "00",
    "full"   => "94",
48 49
    "half"   => "8C",
    "auto1000mbit" => "9C",
50
    "full1000mbit" => "94",
51 52
    "half1000mbit" => "8C",
    "auto100mbit"  => "9A",
53
    "full100mbit"  => "92",
54
    "half100mbit"  => "8A",
55 56 57 58 59
    "auto10mbit"   => "99",
    "full10mbit"   => "91",
    "half10mbit"   => "89",
);

60 61 62 63 64 65
#
# port rate values on Apcon, for raw port info translation 
#
my %portRates =
(
    "00" => ["Auto Negotiate", "auto", "auto"],
66
    "9F" => ["10/100/1000 Mbps Full/Half Duplex", "auto", "auto"],
67 68 69 70 71 72 73 74 75 76
    "9C" => ["1000 Mbps Full/Half Duplex", "auto", "1000Mb"],
    "94" => ["1000 Mbps Full Duplex", "full", "1000Mb"],
    "8C" => ["1000 Mbps Half Duplex", "half", "1000Mb"],
    "9B" => ["10/100 Mbps Full/Half Duplex", "auto", "100Mb"],
    "9A" => ["100 Mbps Full/Half Duplex", "auto", "100Mb"],
    "92" => ["100 Mbps Full Duplex", "full", "100Mb"],
    "8A" => ["100 Mbps Half Duplex", "half", "100Mb"],
    "99" => ["10 Mbps Full/Half Duplex", "auto", "10Mb"],
    "91" => ["10 Mbps Full Duplex", "full", "10Mb"],
    "89" => ["10 Mbps Half Duplex", "half", "10Mb"],
77
    "FF" => ["Analyzer Tap Auto", "auto", "auto"],
78 79 80 81 82 83 84 85 86 87
    "FC" => ["Analyzer Tap 1000 Mbps Full/Half Duplex", "auto", "1000Mb"],
    "F4" => ["Analyzer Tap 1000 Mbps Full Duplex", "full", "1000Mb"],
    "EC" => ["Analyzer Tap 1000 Mbps Half Duplex", "half", "1000Mb"],
    "FB" => ["Analyzer Tap 10/100 Mbps Full/Half Duplex", "auto", "100Mb"],
    "FA" => ["Analyzer Tap 100 Mbps Full/Half Duplex", "auto", "100Mb"],
    "F2" => ["Analyzer Tap 100 Mbps Full Duplex", "full", "100Mb"],
    "EA" => ["Analyzer Tap 100 Mbps Half Duplex", "half", "100Mb"],
    "F9" => ["Analyzer Tap 10 Mbps Full/Half Duplex", "auto", "10Mb"],
    "F1" => ["Analyzer Tap 10 Mbps Full Duplex", "full", "10Mb"],
    "E9" => ["Analyzer Tap 10 Mbps Half Duplex", "half", "10Mb"],
88 89
);

90
my %emptyVlans = ();
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
#
# All functions are based on snmpit_hp class.
#
# NOTES: This device is a layer 1 switch that has no idea
# about VLAN. We use the port name on switch as VLAN name here. 
# So in this module, vlan_id and vlan_number are the same 
# thing. vlan_id acts as the port name.
#
# Another fact: the port name can't exist without naming
# a port. So we can't find a VLAN if no ports are in it.
#

#
# Creates a new object.
#
# usage: new($classname,$devicename,$debuglevel,$community)
#        returns a new object.
#
# We actually donot use SNMP, the SNMP values here, like
# community, are just for compatibility.
#
sub new($$$;$) {

    # The next two lines are some voodoo taken from perltoot(1)
    my $proto = shift;
    my $class = ref($proto) || $proto;

    my $name = shift;
    my $debugLevel = shift;
121
    my $community = shift;  # actually the password for ssh
122 123 124 125 126 127 128 129 130 131

    #
    # Create the actual object
    #
    my $self = {};

    #
    # Set the defaults for this object
    # 
    if (defined($debugLevel)) {
132
        $self->{DEBUG} = $debugLevel;
133
    } else {
134
        $self->{DEBUG} = 0;
135 136 137 138 139 140 141 142 143 144
    }
    $self->{BLOCK} = 1;
    $self->{CONFIRM} = 1;
    $self->{NAME} = $name;

    #
    # Get config options from the database
    #
    my $options = getDeviceOptions($self->{NAME});
    if (!$options) {
145 146
        warn "ERROR: Getting switch options for $self->{NAME}\n";
        return undef;
147 148 149 150 151
    }

    $self->{MIN_VLAN}         = $options->{'min_vlan'};
    $self->{MAX_VLAN}         = $options->{'max_vlan'};

152 153 154 155
    #
    # A simple trick here: we store the ssh password in the 
    # 'snmp_community' column.
    #
156
    if ($community) { # Allow this to over-ride the default
157
        $self->{COMMUNITY}    = $community;
158
    } else {
159
        $self->{COMMUNITY}    = $options->{'snmp_community'};
160
    }
161
    $self->{PASSWORD} = $self->{COMMUNITY};
162 163 164 165 166 167 168

    # other global variables
    $self->{DOALLPORTS} = 0;
    $self->{DOALLPORTS} = 1;
    $self->{SKIPIGMP} = 1;

    if ($self->{DEBUG}) {
169 170
        print "snmpit_apcon initializing $self->{NAME}, " .
            "debug level $self->{DEBUG}\n" ;   
171 172
    }

173 174 175 176 177 178
    $self->{SESS} = undef;
    $self->{CLI_PROMPT} = "$self->{NAME}>> ";

    # Make it a class object
    bless($self, $class);

179 180 181 182 183
    #
    # Create the Expect object
    #
    # We'd better set a long timeout on Apcon switch
    # to keep the connection alive.
184
    $self->{SESS} = $self->createExpectObject();
185
    if (!$self->{SESS}) {
186 187
        warn "WARNNING: Unable to connect via SSH to $self->{NAME}\n";
        return undef;
188 189 190 191
    }

    # TODO: may need this:
    #$self->readifIndex();
192
    $self->readTranslationTable();
193 194 195 196 197

    return $self;
}


198 199 200 201 202 203 204 205 206 207 208 209
#
# Create an Expect object that spawns the ssh process 
# to switch.
#
sub createExpectObject($)
{
    my $self = shift;
    
    my $spawn_cmd = "ssh -l admin $self->{NAME}";
    # Create Expect object and initialize it:
    my $exp = new Expect();
    if (!$exp) {
210 211
        # upper layer will check this
        return undef;
212 213 214 215
    }
    $exp->raw_pty(0);
    $exp->log_stdout(0);
    $exp->spawn($spawn_cmd)
216
    or die "Cannot spawn $spawn_cmd: $!\n";
217
    $exp->expect($CLI_TIMEOUT,
218 219 220
         ["admin\@$self->{NAME}'s password:" => sub { my $e = shift;
                               $e->send($self->{PASSWORD}."\n");
                               exp_continue;}],
221 222 223
         ["Are you sure you want to continue connecting (yes/no)?" => sub { 
                               # Only occurs for the first time connection...
                               my $e = shift;
224
                               $e->send("yes\n");
225
                               exp_continue;}],
226 227 228 229
         ["Permission denied (password)." => sub { 
                               die "Password incorrect!\n";} ],
         [ timeout => sub { die "Timeout when connect to switch!\n";} ],
         $self->{CLI_PROMPT} );
230 231 232
    return $exp;
}

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
#
# Convert port format between switch format and db format
# the original format is auto-detected.
# simply, a switch port starts with A-Z, or A-I on Apcon 2000 series
# while a db port is totally number: card.port.
#
sub convertPortFormat($$)
{
    my ($self, $srcport) = @_;
    my $card = "";
    my $port = "";
    
    if ($srcport =~ /([A-Z])([0-9]{2})/) {
        # froms switch to db
        $card = ord($1) - ord('A') + 1;
        $port = int($2);
        
        return "$card.$port";
    } elsif ($srcport =~ /(\d+)\.(\d+)/) {
        # from db to switch
        $card = chr(ord('A') + $1 - 1);
        $port = sprintf("%02d", $2);
        
        return "$card"."$port";
    } else {
        # unknown format, return itself
        return $srcport;
    }
}


##############################################################################

my %Interfaces=();
# Interfaces maps pcX:Y<==>MAC

my %PortIface=();
# Maps pcX:Y<==>pcX:iface

my %Ports=();
# Ports maps pcX:Y<==>switch:port

#
# This function fills in %Interfaces and %Ports
# They hold pcX:Y<==>MAC and pcX:Y<==>switch:port respectively
#
# XXX: Temp workround for portnum
#
sub readTranslationTable($) {
    my $self = shift;
    my $name="";
    my $mac="";
    my $iface="";
    my $switchport="";

    print "FILLING %Interfaces\n" if $self->{DEBUG};
    my $result =
	DBQueryFatal("select node_id,card,port,mac,iface from interfaces");
    while ( @_ = $result->fetchrow_array()) {
292 293 294 295 296 297 298 299 300
        $name = "$_[0]:$_[1]";
        $iface = "$_[0]:$_[4]";
        if ($_[2] != 1) {$name .=$_[2]; }
        $mac = "$_[3]";
        $Interfaces{$name} = $mac;
        $Interfaces{$mac} = $name;
        $PortIface{$name} = $iface;
        $PortIface{$iface} = $name;
        print "Interfaces: $mac <==> $name\n" if $self->{DEBUG} > 1;
301 302 303 304 305 306 307
    }

    print "FILLING %Ports\n" if $self->{DEBUG};
    $result = DBQueryFatal("select node_id1,card1,port1,node_id2,card2,port2 ".
	    "from wires;");
    while ( my @row = $result->fetchrow_array()) {
        my ($node_id1, $card1, $port1, $node_id2, $card2, $port2) = @row;
308
        $name = "$node_id1:$card1.$port1";
309 310 311 312 313 314 315
        print "Name='$name'\t" if $self->{DEBUG} > 2;
        print "Dev='$node_id2'\t" if $self->{DEBUG} > 2;
        $switchport = "$node_id2:$card2.$port2";
        print "switchport='$switchport'\n" if $self->{DEBUG} > 2;
        $Ports{$name} = $switchport;
        $Ports{$switchport} = $name;
        print "Ports: '$name' <==> '$switchport'\n" if $self->{DEBUG} > 1;
316 317 318 319 320 321
    }

}

##############################################################################

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336

#
# parse the connection output
# return two hashes for query from either direction
#
sub parseConnections($$) 
{
    my $self = shift;
    my $raw = shift;

    my @lines = split( /\n/, $raw );
    my %dst = ();
    my %src = ();

    foreach my $line ( @lines ) {
337 338 339 340 341 342 343 344 345 346
        if ( $line =~ /^([A-I][0-9]{2}):\s+([A-I][0-9]{2})\W*$/ ) {
            if ( $2 ne $CLI_NOCONNECTION ) {
                $src{$1} = $2;
                if ( ! (exists $dst{$2}) ) {
                    $dst{$2} = {};
                }

                $dst{$2}{$1} = 1;
            }
        }
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
    }

    return (\%src, \%dst);
}


#
# parse the port names output
# return the port => name hashtable
#
sub parseNames($$)
{
    my $self = shift;
    my $raw = shift;

    my %names = ();

    foreach ( split ( /\n/, $raw ) ) {
365 366 367 368 369
        if ( /^([A-I][0-9]{2}):\s+(\w+)\W*/ ) {
            if ( $2 !~ /$CLI_UNNAMED_PATTERN/ ) {
            $names{$1} = $2;
            }
        }
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    }

    return \%names;
}


#
# parse the show classes output
# return the classname => 1 hashtable, not a list.
#
sub parseClasses($$)
{
    my $self = shift;
    my $raw = shift;
    
    my %clses = ();

    foreach ( split ( /\n/, $raw ) ) {
388 389 390
        if ( /^Class\s\d{1,2}:\s+(\w+)\s+(\w+)\W*$/ ) {
            $clses{$2} = 1;
        }
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    }

    return \%clses;
}

#
# parse the show zones output
# return the zonename => 1 hashtable, not a list
#
sub parseZones($$)
{
    my $self = shift;
    my $raw = shift;

    my %zones = ();

    foreach ( split ( /\n/, $raw) ) {
408 409 410
        if ( /^\d{1,2}:\s+(\w+)\W*$/ ) {
            $zones{$1} = 1;
        }
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    }

    return \%zones;
}


#
# parse the show class ports output
# return the ports list
#
sub parseClassPorts($$)
{
    my $self = shift;
    my $raw = shift;
    my @ports = ();

    foreach ( split ( /\n/, $raw) ) {
428 429 430
        if ( /^Port\s+\d+:\s+([A-I][0-9]{2})\W*$/ ) {
            push @ports, $1;
        }
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
    }

    return \@ports;
}


#
# parse the show zone ports output
# same to parse_class_ports
#
sub parseZonePorts($$)
{
    my ($self, $raw) = @_;
    return $self->parseClassPorts($raw);
}


#
# helper to do CLI command and check the error msg
#
sub doCLICmd($$)
{
    my ($self, $cmd) = @_;
    my $output = "";
    my $exp = $self->{SESS};

    $exp->clear_accum(); # Clean the accumulated output, as a rule.
    $exp->send($cmd);
    $exp->expect($CLI_TIMEOUT,
460 461 462 463
         [$self->{CLI_PROMPT} => sub {
             my $e = shift;
             $output = $e->before();
          }]);
464 465 466

    $cmd = quotemeta($cmd);
    if ( $output =~ /^($cmd)\n(ERROR:.+)\r\n[.\n]*$/ ) {
467
        return (1, $2);
468
    } else {
469
        return (0, $output);
470 471 472 473 474 475 476 477 478 479 480
    }
}


#
# get the raw CLI output of a command
#
sub getRawOutput($$)
{
    my ($self, $cmd) = @_;
    my ($rt, $output) = $self->doCLICmd($cmd);
481 482 483 484 485
    if ( !$rt ) {        
        my $qcmd = quotemeta($cmd);
        if ( $output =~ /^($qcmd)/ ) {
            return substr($output, length($cmd)+1);
        }        
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    }

    return undef;
}


#
# get all name => prorts hash
# return the name => port list hashtable
#
sub getAllNamedPorts($)
{
    my $self = shift;

    my $raw = $self->getRawOutput($CLI_SHOW_PORT_NAMES);
    my $names = $self->parseNames($raw); 

    my %nps = ();
    foreach my $k (keys %{$names}) {
505 506 507
        if ( !(exists $nps{$names->{$k}}) ) {
            $nps{$names->{$k}} = ();
        }
508

509
        push @{$nps{$names->{$k}}}, $k;
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
    }

    return \%nps;
}


#
# get the name of a port
#
sub getPortName($$)
{
    my ($self, $port) = @_;

    my $raw = $self->getRawOutput("show port info $port\r");
    if ( $raw =~ /$port Name:\s+(\w+)\W*\n/ ) {
525 526 527
        if (  $1 !~ /$CLI_UNNAMED_PATTERN/ ) {
            return $1;
        }
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
    }

    return undef;
}

#
# get the ports list by their name.
#
sub getNamedPorts($$)
{
    my ($self, $pname) = @_;
    my @ports = ();

    my $raw = $self->getRawOutput($CLI_SHOW_PORT_NAMES);
    foreach ( split /\n/, $raw ) {
543 544 545
        if ( /^([A-I][0-9]{2}):\s+($pname)\W*/ ) {
            push @ports, $1;
        }
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
    }

    return \@ports;
}

#
# get connections of ports with the given name
# return two hashtabls whose format is same to parseConnections
#
sub getNamedConnections($$)
{
    my ($self, $name) = @_;

    my $raw_conns = $self->getRawOutput($CLI_SHOW_CONNECTIONS);
    my ($allsrc, $alldst) = $self->parseConnections($raw_conns);
    my $ports = $self->getNamedPorts($name);

    my %src = ();
    my %dst = ();

    #
    # There may be something special: a named port may connect to
    # a port whose name is not the same. Then this connection
    # should not belong to the 'vlan'. Till now the following codes
    # have not dealt with it yet.
    #
572
    # MAYBE-TODO: remove those connections containning ports don't belong
573 574 575
    #       to the 'vlan'.
    #
    foreach my $p (@$ports) {
576 577 578
        if ( exists($allsrc->{$p}) ) {
            $src{$p} = $allsrc->{$p};
        } 
579

580 581 582
        if ( exists($alldst->{$p}) ) {
            $dst{$p} = $alldst->{$p};
        }
583 584 585 586 587
    }

    return (\%src, \%dst);
}

588 589 590 591 592 593 594 595 596 597 598 599 600
#
# parse the show port rate raw * output
# return the hashtable ref: port name => [desired rate, actual rate]
#
sub parsePortRates($$)
{
    my $self = shift;
    my $raw = shift;
    
    my %rates = ();
    my @lines = split( /\n/, $raw );
 
    foreach my $line ( @lines ) {
601 602
        if ( $line =~ 
	    /^([A-I][0-9]{2})\s+Desired Rate:\s+0x([A-F0-9]{2})\s+/ ) {
603
            @{$rates{$1}} = ($2,[]);            
604
        } else {
605 606 607
            if ( $line =~ 
		/^([A-I][0-9]{2})\s+Actual Link:\s+0x([A-F0-9]{2})\s+(.+)\r$/
	       ) {
608 609 610 611 612 613
                my ($port, $arate, $desc) = ($1, $2, $3);
                if ($desc =~ /^(10{1,3}Mb)\s+(\w+)\s*/) {
                        @{$rates{$port}[1]} = ($arate, $desc, $2,$1);
                } else {
                        @{$rates{$port}[1]} = ("00",);
                }                                
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
            }
        }
    }

    return \%rates;
}

#
# Get a single port rate
#   return undef on any errors
#   return the array ref: [desired rate, actual rate]
#
sub getPortRate($$)
{
    my ($self, $port) = @_;
    my $cmd = "show port rate raw $port\r";

    my $raw = $self->getRawOutput($cmd);
    if ( defined($raw) ) {
        my $rate = $self->parsePortRates($raw);
        if ( exists($rate->{$port}) ) {
            return \@{$rate->{$port}};
        }   
    }    
    
    return undef;
}

#
# Get all ports rates
#   return undef on any errors
#   return the hashtable ref: portnumber => [desired rate, actual rate]
#
sub getAllPortsRates($)
{
    my $self = shift;
    
    my $raw = $self->getRawOutput($CLI_SHOW_PORT_RATES);
    if ( defined($raw) ) {
        my $rates = $self->parsePortRates($raw);
654
        return \%$rates; 
655 656 657 658 659
    }    
    
    return undef;
}

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
#
# Add a new class
#
sub addCls($$)
{
    my ($self, $clsname) = @_;
    my $cmd = "add class I $clsname\r";

    return $self->doCLICmd($cmd);
}

#
# Add a new zone
#
sub addZone($$)
{
    my ($self, $zonename) = @_;
    my $cmd = "add zone $zonename\r";

    return $self->doCLICmd($cmd);
}

#
# Add some ports to a class
#
sub addClassPorts($$@)
{
    my ($self, $clsname, @ports) = @_;
    my $cmd = "add class ports $clsname ".join("", @ports)."\r";

    return $self->doCLICmd($cmd);
}

# 
# Connect ports functions:
#

#
# Make a multicast connection $src --> @dsts
#
sub connectMulticast($$@)
{
    my ($self, $src, @dsts) = @_;
    my $cmd = "connect multicast $src".join("", @dsts)."\r";

    return $self->doCLICmd($cmd);
}

#
# Make a duplex connection $src <> $dst
#
sub connectDuplex($$$)
{
    my ($self, $src, $dst) = @_;
    my $cmd = "connect duplex $src"."$dst"."\r";

    return $self->doCLICmd($cmd);
}

#
# Make a simplex connection $src -> $dst
#
sub connectSimplex($$$)
{
    my ($self, $src, $dst) = @_;
    my $cmd = "connect simplex $src"."$dst"."\r";

    return $self->doCLICmd($cmd);
}


#
# Add some ports to a vlan, 
# it actually names those ports to the vlanname. 
#
sub namePorts($$@)
{
    my ($self, $name, @ports) = @_;

739 740 741 742 743 744 745 746 747 748 749 750
    for( my $i = 0; $i < @ports; $i++ ) {        
        my ($rt, $msg) = $self->doCLICmd(
                     "configure port name $ports[$i] $name\r");

        # undo set name
        if ( $rt ) {
            for ($i--; $i >= 0; $i-- ) {            
                $self->doCLICmd(
                    "configure port name $ports[$i] $CLI_UNNAMED_NAME\r");
            }
            return $msg;
        }
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
    }

    return 0;
}


#
# Unname ports, the name of those ports will be $CLI_UNNAMED_NAME
#
sub unnamePorts($@)
{
    my ($self, @ports) = @_;

    my $emsg = "";
    foreach my $p (@ports) {
766 767 768 769 770
        my ($rt, $msg) = $self->doCLICmd(
                     "configure port name $p $CLI_UNNAMED_NAME\r");
        if ( $rt ) {
            $emsg = $emsg.$msg."\n";
        }
771 772 773
    }

    if ( $emsg eq "" ) {
774
        return 0;
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
    }

    return $emsg;
}


#
# Disconnect ports
# $sconns: the dst => src hashtable.
#
sub disconnectPorts($$) 
{
    my ($self, $sconns) = @_;

    my $emsg = "";
    foreach my $dst (keys %$sconns) {
791 792 793 794 795
        my ($rt, $msg) = $self->doCLICmd(
                     "disconnect $dst".$sconns->{$dst}."\r");
        if ( $rt ) {
            $emsg = $emsg.$msg."\n";
        }
796 797 798
    }

    if ( $emsg eq "" ) {
799
        return 0;
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
    }

    return $emsg;
}


#
# Remove a 'vlan', unname the ports and disconnect them
#
sub removePortName($$)
{
    my ($self, $name) =  @_;

    # Disconnect ports:
    my ($src, $dst) = $self->getNamedConnections($name);
    my $disrt = $self->disconnectPorts($src);

    # Unname ports:
    my $ports = $self->getNamedPorts($name);
    my $unrt = $self->unnamePorts(@$ports);
    if ( $unrt || $disrt) {
821
        return $disrt.$unrt;
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
    }

    return 0;
}


#
# Set port rate, for port control.
# Rates are defined in %portCMDs.
#
sub setPortRate($$$)
{
    my ($self, $port, $rate) = @_;

    if ( !exists($portCMDs{$rate}) ) {
837
        return "ERROR: port rate unsupported!\n";
838 839 840 841 842
    }

    my $cmd = "configure rate $port $portCMDs{$rate}\r";
    my ($rt, $msg) = $self->doCLICmd($cmd);
    if ( $rt ) {
843
        return $msg;
844 845 846 847 848
    }

    return 0;
}

849 850 851 852 853 854 855 856
#
# Internal
# convert port format from pcxx:card to [A-I][0-9]{2}
#
sub convertPortFromNode2Dev($$) {
    my $self = shift;
    my $pcport = shift;
    
857
    my $modport = $Ports{"$pcport.1"};
858 859 860 861 862 863
    if (defined($modport)) {
        return $self->convertPortFormat($modport);
    }
    
    return $pcport;
}
864

865 866 867 868 869
#
# Set a variable associated with a port. The commands to execute are given
# in the apcon_clilib::portCMDs hash
#
# usage: portControl($self, $command, @ports)
870 871 872
#     returns 0 on success.
#     returns number of failed ports on failure.
#     returns -1 if the operation is unsupported
873 874 875 876 877 878 879 880 881 882 883
#
sub portControl ($$@) {
    my $self = shift;

    my $cmd = shift;
    my @ports = @_;

    $self->debug("portControl: $cmd -> (@ports)\n");

    my $errors = 0;
    foreach my $port (@ports) { 
884
        $port = $self->convertPortFromNode2Dev($port);
885 886 887 888
        my $rt = $self->setPortRate($port, $cmd);
        if ($rt) {
            if ($rt =~ /^ERROR: port rate unsupported/) {
                #
889
                # Command not supported
890
                #
891
                $self->debug("Unsupported port command '$cmd' ignored.\n");
892 893
                return 0;
            }
894

895 896
            $errors++;
        }
897 898 899 900 901
    }

    return $errors;
}

902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
# 
# Check to see if the given 802.1Q VLAN tag exists on the switch
#
# usage: vlanNumberExists($self, $vlan_number)
#        returns 1 if the VLAN exists, 0 otherwise
#
sub vlanNumberExists($$) {
    my ($self, $vlan_number) = @_;

    if ($self->findVlan($vlan_number)) {
        return 1;
    } else {
        return 0;
    }
}
917 918

#
919 920
# Original purpose: 
# Given VLAN indentifiers from the database, finds the 802.1Q VLAN
921 922 923 924
# number for them. If not VLAN id is given, returns mappings for the entire
# switch.
#
# On Apcon switch, no VLAN exists. So we use port name as VLAN name. This 
925
# funtion actually either list all VLAN names or do the existance checking,
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
# which will set the mapping value to undef for nonexisted VLANs. 
# 
# usage: findVlans($self, @vlan_ids)
#        returns a hash mapping VLAN ids to ... VLAN ids.
#        any VLANs not found have NULL VLAN numbers
#
sub findVlans($@) { 
    my $self = shift;
    my @vlan_ids = @_;
    my %mapping = ();
    my $id = $self->{NAME} . "::findVlans";
    my ($count, $name, $vlan_number, $vlan_name) = (scalar(@vlan_ids));
    $self->debug("$id\n");

    if ($count > 0) { @mapping{@vlan_ids} = undef; }

    # 
    # Get all port names, which are considered to be VLAN names.
    #
945
    my $vlans = $self->getAllNamedPorts();
946
    foreach $vlan_name (keys %{$vlans}) {
947 948 949
        if (!@vlan_ids || exists $mapping{$vlan_name}) {
            $mapping{$vlan_name} = $vlan_name;
        }
950 951
    }

952 953 954 955 956 957
    foreach $vlan_name (keys %emptyVlans) {
        if ( exists $mapping{$vlan_name} ) {
            $mapping{$vlan_name} = $vlan_name;
        }
    }
    
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
    return %mapping;
}


#
# See the comments of findVlans above for explanation.
#
# usage: findVlan($self, $vlan_id,$no_retry)
#        returns the VLAN number for the given vlan_id if it exists
#        returns undef if the VLAN id is not found
#
sub findVlan($$;$) { 
    my $self = shift;
    my $vlan_id = shift;

    #
    # Just for compatibility, we don't use retry for CLI.
    #
    my $no_retry = shift;
    my $id = $self->{NAME} . ":findVlan";

    $self->debug("$id ( $vlan_id )\n",2);
    
981
    my $ports = $self->getNamedPorts($vlan_id);
982
    if (@$ports) {
983
        return $vlan_id;
984 985
    } elsif (exists($emptyVlans{$vlan_id})) {
        return $vlan_id; #return $emptyVlans{$vlan_id};
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    }

    return undef;
}

#   
# Create a VLAN on this switch, with the given identifier (which comes from
# the database) and given 802.1Q tag number, which is ignored.
#
# usage: createVlan($self, $vlan_id, $vlan_number)
#        returns the new VLAN number on success
#        returns 0 on failure
#
sub createVlan($$$) {
    my $self = shift;
    my $vlan_id = shift;
    my $vlan_number = shift; # we ignore this on Apcon switch
    my $id = $self->{NAME} . ":createVlan";

    #
    # To acts similar to other device modules
    #
    if (!defined($vlan_number)) {
1009 1010
        warn "$id called without supplying vlan_number";
        return 0;
1011 1012 1013
    }
    my $check_number = $self->findVlan($vlan_id,1);
    if (defined($check_number)) {
1014 1015
        warn "$id: recreating vlan id $vlan_id \n";
        return 0;
1016 1017
    }
    
1018
    print "  Creating VLAN $vlan_id as VLAN #$vlan_id on " .
1019
        "$self->{NAME} ...\n";
1020

1021 1022 1023 1024
    #
    # We record this vlan because it is still empty.
    # Apcon switch doesn't support empty VLAN.
    #
1025
    $emptyVlans{$vlan_id} = $vlan_number;
1026

1027
    return $vlan_id;
1028 1029 1030 1031 1032 1033 1034
}

#
# Put the given ports in the given VLAN. The VLAN is given as an 802.1Q 
# tag number.
#
# usage: setPortVlan($self, $vlan_number, @ports)
1035 1036
#     returns 0 on sucess.
#     returns the number of failed ports on failure.
1037 1038 1039
#
sub setPortVlan($$@) {
    my $self = shift;
1040 1041
    my $vlan_id = shift;
    my @pcports = @_;
1042 1043

    my $id = $self->{NAME} . "::setPortVlan";
1044 1045
    $self->debug("$id: $vlan_id ");
    $self->debug("ports: " . join(",",@pcports) . "\n");
1046 1047

    if (@pcports != 2) {
1048 1049
        warn "$id: supports only two ports in one VLAN.\n";
        return 1;
1050 1051
    }

1052
    my @ports = map {$self->convertPortFromNode2Dev($_)} @pcports;
1053 1054 1055 1056
    
    $self->lock();

    # Check if ports are free
1057
    foreach my $port (@ports) {        
1058 1059 1060 1061 1062
        if ($self->getPortName($port)) {
            warn "ERROR: Port $port already in use.\n";
            $self->unlock();
            return 1;
        }
1063 1064
    }
    
1065
    my $errmsg = $self->namePorts($vlan_id, @ports);
1066
    if ($errmsg) {
1067 1068 1069
        warn "$errmsg";
        $self->unlock();
        return 1;
1070 1071
    }

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
    my ($rt, $msg) = $self->connectDuplex($ports[0], $ports[1]);
    if ($rt) {
	$self->unnamePorts(@ports);
	warn "$id: ports connection failed. $msg\n";

	# We unnamed the ports so vlan doesn't exist now.
	if (exists($emptyVlans{$vlan_id})) {
	    delete $emptyVlans{$vlan_id};
	}

	$self->unlock();
	return 1;
    }

1086 1087
    $self->unlock();

1088 1089 1090 1091
    #
    # Check if this vlan was empty before and delete
    # it from the empty vlan records if YES.
    #
1092 1093
    if (exists($emptyVlans{$vlan_id})) {
        delete $emptyVlans{$vlan_id};
1094 1095
    }

1096 1097 1098 1099 1100 1101 1102 1103 1104
    return 0;
}


#
# Remove the given ports from the given VLAN. The VLAN is given as an 802.1Q 
# tag number.
#
# usage: delPortVlan($self, $vlan_number, @ports)
1105 1106
#     returns 0 on sucess.
#     returns the number of failed ports on failure.
1107 1108 1109
#
sub delPortVlan($$@) {
    my $self = shift;
1110 1111
    my $vlan_id = shift;
    my @pcports = @_;
1112

1113 1114 1115
    $self->debug($self->{NAME} . "::delPortVlan $vlan_id ");
    $self->debug("ports: " . join(",",@pcports) . "\n");
    my @ports = map {$self->convertPortFromNode2Dev($_)} @pcports;
1116 1117 1118
    
    $self->lock();

1119
    # Remember all ports for empty check after remove
1120
    my $allports = $self->getNamedPorts($vlan_id);
1121

1122
    #
1123
    # Find connections of @ports
1124
    #
1125
    my ($src, $dst) = $self->getNamedConnections($vlan_id);
1126 1127 1128
    my %sconns = ();
    foreach my $p (@ports) {

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
        if (exists($src->{$p})) {
        
            # As destination:
            $sconns{$p} = $src->{$p};
        } else {
            if (exists($dst->{$p})) {
        
                # As source:
                foreach my $pdst (keys %{$dst->{$p}}) {
                    $sconns{$pdst} = $p;
                }
            }    
        }
1142 1143
    }
    
1144
    # Disconnect conections of @ports
1145
    my $errmsg = $self->disconnectPorts(\%sconns);
1146
    if ($errmsg) {
1147 1148 1149
        warn "$errmsg";
        $self->unlock();
        return 1;
1150 1151
    }
    
1152
    # Unname the ports, looks like 'remove'
1153
    $errmsg = $self->unnamePorts(@ports);
1154
    if ($errmsg) {
1155 1156 1157
        warn "$errmsg";
        $self->unlock();
        return 1;
1158 1159
    }    

1160 1161 1162 1163
    #
    # Remember the empty VLAN for warning msg when unloading module
    #
    if (scalar (@ports) == scalar (@$allports)) {
1164
        $emptyVlans{$vlan_id} = 1;
1165 1166
    }

1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    $self->unlock();

    return 0;
}

#
# Disables all ports in the given VLANS. Each VLAN is given as a VLAN
# 802.1Q tag value.
#
# This version will also 'delete' the VLAN because no ports use
# the vlan name any more. Same to removeVlan().
#
# usage: removePortsFromVlan(self,@vlan)
1180 1181
#     returns 0 on sucess.
#     returns the number of failed ports on failure.
1182 1183 1184 1185 1186 1187 1188 1189
#
sub removePortsFromVlan($@) {
    my $self = shift;
    my @vlan_numbers = @_;
    my $errors = 0;
    my $id = $self->{NAME} . "::removePortsFromVlan";

    foreach my $vlan_number (@vlan_numbers) {
1190 1191 1192
        if ($self->removePortName($vlan_number)) {
            $errors++;
        } else {
1193
            $emptyVlans{$vlan_number} = 1;
1194
        }
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    }
    return $errors;
}

#
# Removes and disables some ports in a given VLAN.
# The VLAN is given as a VLAN 802.1Q tag value.
#
# This function is the same to delPortVlan because
# disconnect a connection will disable its two endports
# at the same time.
#
# usage: removeSomePortsFromVlan(self,vlan,@ports)
1208 1209
#     returns 0 on sucess.
#     returns the number of failed ports on failure.
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
#
sub removeSomePortsFromVlan($$@) {
    my ($self, $vlan_number, @ports) = @_;
    return $self->delPortVlan($vlan_number, @ports);
}

#
# Remove the given VLANs from this switch. Removes all ports from the VLAN,
# The VLAN is given as a VLAN identifier from the database.
#
# usage: removeVlan(self,int vlan)
1221 1222
#     returns 1 on success
#     returns 0 on failure
1223 1224 1225 1226 1227 1228 1229 1230
#
#
sub removeVlan($@) {
    my $self = shift;
    my @vlan_numbers = @_;
    my $errors = 0;

    foreach my $vlan_number (@vlan_numbers) {
1231 1232 1233 1234 1235 1236 1237 1238 1239
        if ($self->removePortName($vlan_number)) {
            $errors++;
        } else {
        
            #
            # Check if this vlan was empty before and delete
            # it from the empty vlan records if YES.
            #
            if (exists($emptyVlans{$vlan_number})) {
1240
                delete $emptyVlans{$vlan_number};
1241 1242
            }

1243
            print "Removed VLAN $vlan_number on switch $self->{NAME}.\n";    
1244
        }    
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
    }

    return ($errors == 0) ? 1:0;
}



#
# Determine if a VLAN has any members 
# (Used by stack->switchesWithPortsInVlan())
#
sub vlanHasPorts($$) {
    my ($self, $vlan_number) = @_;

1259
    my $portset = $self->getNamedPorts($vlan_number);
1260
    if (@$portset) {
1261
        return 1;
1262
    }
1263 1264

    if (!exists($emptyVlans{$vlan_number})) {
1265
        $emptyVlans{$vlan_number} = -1;
1266 1267
    }

1268 1269 1270
    return 0;
}

1271 1272 1273 1274 1275 1276 1277 1278

#
# Internal
# Convert from switch device port to pc node port
#
sub convertPortFromDev2Node($$) {
    my ($self, $devport) = @_;
    
1279
    my $pnum = $self->{NAME}.":".$self->convertPortFormat($devport);
1280 1281 1282 1283 1284 1285 1286 1287
    if (!exists $Ports{$pnum}) {
        return undef;
    }
    
    return $Ports{$pnum};
}


1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
#
# List all VLANs on the device
#
# usage: listVlans($self)
# see snmpit_cisco_stack.pm for a description of return value format
#
sub listVlans($) {
    my $self = shift;

    my @list = ();
1298
    my $vlans = $self->getAllNamedPorts();
1299
    foreach my $vlan_id (keys %$vlans) {
1300
        my @swports = @{$vlans->{$vlan_id}};
1301 1302 1303 1304 1305 1306 1307 1308 1309
        my @pcports = ();

        foreach my $p (@swports) {
            my $pcp = $self->convertPortFromDev2Node($p);
            if ($pcp) {
                push @pcports, $pcp;
            } else {
                push @pcports, $p;
            }
1310
        }
1311

1312
        push @list, [$vlan_id, $vlan_id, \@pcports];
1313
    }
1314
    
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
    return @list;
}

#
# List all ports on the device
#
# usage: listPorts($self)
# see snmpit_cisco_stack.pm for a description of return value format
#
sub listPorts($) {
    my $self = shift;
    my @ports = ();

1328 1329
    my $rates = $self->getAllPortsRates();
    foreach my $port (keys %$rates) {
1330 1331 1332 1333
        my ($drate, $arateref) = @{$rates->{$port}};
        my @arate = @$arateref;         
        my @strdrate = @{$portRates{$drate}};        

1334 1335 1336 1337 1338 1339 1340 1341
        my $pnum = $self->{NAME}.":".$self->convertPortFormat($port);
        
        if (!exists $Ports{$pnum}) {
            next;
        }
        
        my $finalport = $Ports{$pnum};      

1342 1343 1344
        #
        # if port is actived, use actual rate, otherwise use desired rate
        #
1345
        if ( $arate[0] eq "00" ) {        
1346
            push @ports, [$finalport, "no", "down", $strdrate[2], $strdrate[1]];
1347 1348 1349 1350
        } else {
            #
            # Not sure if it is OK to just ignore the desired rate
            #
1351
            push @ports, [$finalport, "yes", "up", $arate[3], $arate[2]];
1352 1353 1354
        }
    }
    
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
    return @ports;
}

# 
# Get statistics for ports on the switch
#
# Unsupported operation on Apcon 2000-series switch via CLI.
#
# usage: getStats($self)
# see snmpit_cisco_stack.pm for a description of return value format
#
#
sub getStats() {
    my $self = shift;

    warn "Port statistics are unavaialble on our Apcon 2000 switch.";
    return undef;
}


#
# Get the ifindex for an EtherChannel (trunk given as a list of ports)
#
# usage: getChannelIfIndex(self, ports)
#        Returns: undef if more than one port is given, and no channel is found
#           an ifindex if a channel is found and/or only one port is given
#
sub getChannelIfIndex($@) {
    warn "ERROR: Apcon switch doesn't support trunking";
    return undef;
}


#
# Enable, or disable,  port on a trunk
#
# usage: setVlansOnTrunk(self, modport, value, vlan_numbers)
#        modport: module.port of the trunk to operate on
#        value: 0 to disallow the VLAN on the trunk, 1 to allow it
1394
#     vlan_numbers: An array of 802.1Q VLAN numbers to operate on
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
#        Returns 1 on success, 0 otherwise
#
sub setVlansOnTrunk($$$$) {
    warn "ERROR: Apcon switch doesn't support trunking";
    return 0;
}

#
# Enable trunking on a port
#
# usage: enablePortTrunking2(self, modport, nativevlan, equaltrunking)
#        modport: module.port of the trunk to operate on
#        nativevlan: VLAN number of the native VLAN for this trunk
1408
#     equaltrunk: don't do dual mode; tag PVID also.
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
#        Returns 1 on success, 0 otherwise
#
sub enablePortTrunking2($$$$) {
    warn "ERROR: Apcon switch doesn't support trunking";
    return 0;
}

#
# Disable trunking on a port
#
# usage: disablePortTrunking(self, modport)
#        modport: module.port of the trunk to operate on
#        Returns 1 on success, 0 otherwise
#
sub disablePortTrunking($$;$) {
    warn "ERROR: Apcon switch doesn't support trunking";
    return 0;
}


#
# Prints out a debugging message, but only if debugging is on. If a level is
# given, the debuglevel must be >= that level for the message to print. If
# the level is omitted, 1 is assumed
#
# Usage: debug($self, $message, $level)
#
sub debug($$;$) {
    my $self = shift;
    my $string = shift;
    my $debuglevel = shift;
    if (!(defined $debuglevel)) {
1441
        $debuglevel = 1;
1442 1443
    }
    if ($self->{DEBUG} >= $debuglevel) {
1444
        print STDERR $string;
1445 1446 1447 1448 1449 1450 1451 1452 1453
    }
}

my $lock_held = 0;

sub lock($) {
    my $self = shift;
    my $token = "snmpit_" . $self->{NAME};
    if ($lock_held == 0) {
1454 1455 1456
        my $old_umask = umask(0);
        die if (TBScriptLock($token,0,1800) != TBSCRIPTLOCK_OKAY());
        umask($old_umask);
1457 1458 1459 1460 1461
    }
    $lock_held = 1;
}

sub unlock($) {
1462 1463
    if ($lock_held == 1) { TBScriptUnlock();}
    $lock_held = 0;
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
}


#
# Enable Openflow
#
sub enableOpenflow($$) {
    warn "ERROR: Apcon switch doesn't support Openflow now";
    return 0;
}

#
# Disable Openflow
#
sub disableOpenflow($$) {
    warn "ERROR: Apcon switch doesn't support Openflow now";
    return 0;
}

#
# Set controller
#
sub setOpenflowController($$$) {
    warn "ERROR: Apcon switch doesn't support Openflow now";
    return 0;
}

#
# Set listener
#
sub setOpenflowListener($$$) {
    warn "ERROR: Apcon switch doesn't support Openflow now";
    return 0;
}

#
# Get used listener ports
#
sub getUsedOpenflowListenerPorts($) {
    my %ports = ();

    warn "ERROR: Apcon switch doesn't support Openflow now";
    return %ports;
}


#
# Check if Openflow is supported on this switch
#
sub isOpenflowSupported($) {
    return 0;
}

1517 1518 1519 1520 1521 1522 1523 1524

#
# Print warning messages for empty VLANs that will be deleted 
# after unloading the package.
#
END 
{

1525 1526
    foreach my $vlanid (keys %emptyVlans) {        
        warn "WARNING: the unsupported empty VLAN $vlanid is deleted.\n";
1527 1528 1529 1530
    }

}

1531 1532
# End with true
1;