new_snmpit_apcon.pm 33 KB
Newer Older
Weibin Sun's avatar
Weibin Sun committed
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/perl -W

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

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

13
package new_snmpit_apcon;
Weibin Sun's avatar
Weibin Sun committed
14
15
16
17
18
19
use strict;

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

use English;
use SNMP; 
20
use new_snmpit_lib;
Weibin Sun's avatar
Weibin Sun committed
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
use libdb;

use libtestbed;
use Expect;
use Lan;
use Port;


# 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";
my $CLI_SHOW_PORT_RATES  = "show port rate raw *\r";

# mappings from port control command to CLI command
my %portCMDs =
(
    "enable" => "00",
    "disable"=> "00",
    "1000mbit"=> "9F",
    "100mbit"=> "9B",
    "10mbit" => "99",
    "auto"   => "00",
    "full"   => "94",
    "half"   => "8C",
    "auto1000mbit" => "9C",
    "full1000mbit" => "94",
    "half1000mbit" => "8C",
    "auto100mbit"  => "9A",
    "full100mbit"  => "92",
    "half100mbit"  => "8A",
    "auto10mbit"   => "99",
    "full10mbit"   => "91",
    "half10mbit"   => "89",
);

#
# port rate values on Apcon, for raw port info translation 
#
my %portRates =
(
    "00" => ["Auto Negotiate", "auto", "auto"],
    "9F" => ["10/100/1000 Mbps Full/Half Duplex", "auto", "auto"],
    "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"],
    "FF" => ["Analyzer Tap Auto", "auto", "auto"],
    "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"],
);

my %emptyVlans = ();

#
# 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;
    my $community = shift;  # actually the password for ssh

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

    #
    # Set the defaults for this object
    # 
    if (defined($debugLevel)) {
        $self->{DEBUG} = $debugLevel;
    } else {
        $self->{DEBUG} = 0;
    }
    $self->{BLOCK} = 1;
    $self->{CONFIRM} = 1;
    $self->{NAME} = $name;

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

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

    #
    # A simple trick here: we store the ssh password in the 
    # 'snmp_community' column.
    #
    if ($community) { # Allow this to over-ride the default
        $self->{COMMUNITY}    = $community;
    } else {
        $self->{COMMUNITY}    = $options->{'snmp_community'};
    }
    $self->{PASSWORD} = $self->{COMMUNITY};

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

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

    $self->{SESS} = undef;
    $self->{CLI_PROMPT} = "$self->{NAME}>> ";

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

    #
    # Lazy initialization of the Expect object is adopted, so
    # we set the session object to be undef.
    #
    $self->{SESS} = undef;

    #$self->readTranslationTable();

    return $self;
}

#
# 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) {
        # upper layer will check this
        return undef;
    }
    $exp->raw_pty(0);
    $exp->log_stdout(0);
    $exp->spawn($spawn_cmd)
    or die "Cannot spawn $spawn_cmd: $!\n";
    $exp->expect($CLI_TIMEOUT,
         ["admin\@$self->{NAME}'s password:" => sub { my $e = shift;
                               $e->send($self->{PASSWORD}."\n");
                               exp_continue;}],
         ["Are you sure you want to continue connecting (yes/no)?" => sub { 
                               # Only occurs for the first time connection...
                               my $e = shift;
                               $e->send("yes\n");
                               exp_continue;}],
         ["Permission denied (password)." => sub { 
                               die "Password incorrect!\n";} ],
         [ timeout => sub { die "Timeout when connect to switch!\n";} ],
         $self->{CLI_PROMPT} );
    return $exp;
}


sub toApconPort($$)
{
        my ($self, $p) = @_;
        
232
233
234
        my $apcport = $p->getEndByNode($self->{NAME});
        if (!defined($apcport)) {
        	return $p;
Weibin Sun's avatar
Weibin Sun committed
235
236
        }
        
237
238
        my $card = chr(ord('A')+int($apcport->card()) - 1);
        my $port = sprintf("%02d", int($apcport->port()));
Weibin Sun's avatar
Weibin Sun committed
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
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
654
655
656
657
658
659
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
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
815
816
817
818
819
820
821
        
        return "$card"."$port";
}

sub fromApconPort($$)
{
	my ($self, $ap) = @_;
	
	if ($ap =~ /([A-Z])([0-9]{2})/) {
                # froms switch to db
                my $card = ord($1) - ord('A') + 1;
                my $port = int($2);
        
                return Port->LookupByTriple($self->{NAME}, $card, $port);
        }
        
        return $ap;
}


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


#
# 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 ) {
        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;
            }
        }
    }

    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 ) ) {
        if ( /^([A-I][0-9]{2}):\s+(\w+)\W*/ ) {
            if ( $2 !~ /$CLI_UNNAMED_PATTERN/ ) {
		$names{$1} = $2;
            }
        }
    }

    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 ) ) {
        if ( /^Class\s\d{1,2}:\s+(\w+)\s+(\w+)\W*$/ ) {
            $clses{$2} = 1;
        }
    }

    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) ) {
        if ( /^\d{1,2}:\s+(\w+)\W*$/ ) {
            $zones{$1} = 1;
        }
    }

    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) ) {
        if ( /^Port\s+\d+:\s+([A-I][0-9]{2})\W*$/ ) {
            push @ports, $1;
        }
    }

    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};

    if (!$exp) {
	#
	# Create the Expect object, lazy initialization.
	#
	# We'd better set a long timeout on Apcon switch
	# to keep the connection alive.
	$self->{SESS} = $self->createExpectObject();
	if (!$self->{SESS}) {
	    warn "WARNNING: Unable to connect to $self->{NAME}\n";
	    return (1, "Unable to connect to switch $self->{NAME}.");
	}
	$exp = $self->{SESS};
    }

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

    $cmd = quotemeta($cmd);
    if ( $output =~ /^($cmd)\n(ERROR:.+)\r\n[.\n]*$/ ) {
	$self->debug("snmpit_apcon: Error in doCLICmd: $2\n");
        return (1, $2);
    } else {
        return (0, $output);
    }
}


#
# get the raw CLI output of a command
#
sub getRawOutput($$)
{
    my ($self, $cmd) = @_;
    my ($rt, $output) = $self->doCLICmd($cmd);
    if ( !$rt ) {        
        my $qcmd = quotemeta($cmd);
        if ( $output =~ /^($qcmd)/ ) {
            return substr($output, length($cmd)+1);
        }        
    }

    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}) {
        if ( !(exists $nps{$names->{$k}}) ) {
            $nps{$names->{$k}} = ();
        }

        push @{$nps{$names->{$k}}}, $k;
    }

    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/ ) {
        if (  $1 !~ /$CLI_UNNAMED_PATTERN/ ) {
	    $self->debug("snmpit_apcon: getPortName: $port as $1\n");
            return $1;
        }
    }

    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 ) {
        if ( /^([A-I][0-9]{2}):\s+($pname)\W*/ ) {
            push @ports, $1;
        }
    }

    $self->debug("snmpit_apcon: getNamedPorts: ".join(", ", @ports)."\n");

    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.
    #
    # MAYBE-TODO: remove those connections containning ports don't belong
    #       to the 'vlan'.
    #
    foreach my $p (@$ports) {
        if ( exists($allsrc->{$p}) ) {
            $src{$p} = $allsrc->{$p};
        } 

        if ( exists($alldst->{$p}) ) {
            $dst{$p} = $alldst->{$p};
        }
    }

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

#
# 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 ) {
        if ( $line =~ 
	    /^([A-I][0-9]{2})\s+Desired Rate:\s+0x([A-F0-9]{2})\s+/ ) {
            @{$rates{$1}} = ($2,[]);            
        } else {
            if ( $line =~ 
		/^([A-I][0-9]{2})\s+Actual Link:\s+0x([A-F0-9]{2})\s+(.+)\r$/
	       ) {
                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",);
                }                                
            }
        }
    }

    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);
        return \%$rates; 
    }    
    
    return undef;
}

#
# 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";

    $self->debug("snmpit_apcon: connectMulticast: $cmd\n");

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

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

    $self->debug("snmpit_apcon: connectDuplex: $cmd\n");

    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) = @_;

    for( my $i = 0; $i < @ports; $i++ ) {        
        my ($rt, $msg) = $self->doCLICmd(
                     "configure port name $ports[$i] $name\r");

        # undo set name
        if ( $rt ) {

	    $self->debug("snmpit_apcon: namePorts failed: ".join(", ", @ports)."\n");

            for ($i--; $i >= 0; $i-- ) {            
                $self->doCLICmd(
                    "configure port name $ports[$i] $CLI_UNNAMED_NAME\r");
            }
            return $msg;
        }
    }

    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) {
        my ($rt, $msg) = $self->doCLICmd(
                     "configure port name $p $CLI_UNNAMED_NAME\r");
        if ( $rt ) {
            $emsg = $emsg.$msg."\n";
        }
    }

    if ( $emsg eq "" ) {
        return 0;
    }

    return $emsg;
}


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

    my $emsg = "";
    foreach my $dst (keys %$sconns) {
        my ($rt, $msg) = $self->doCLICmd(
                     "disconnect $dst".$sconns->{$dst}."\r");
        if ( $rt ) {
            $emsg = $emsg.$msg."\n";
        }
    }

    if ( $emsg eq "" ) {
        return 0;
    }

    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) {
        return $disrt.$unrt;
    }

    return 0;
}


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

    if ( !exists($portCMDs{$rate}) ) {
        return "ERROR: port rate unsupported!\n";
    }

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

    return 0;
}

#
# Set a variable associated with a port. The commands to execute are given
# in the apcon_clilib::portCMDs hash
#
# usage: portControl($self, $command, @ports)
#     returns 0 on success.
#     returns number of failed ports on failure.
#     returns -1 if the operation is unsupported
#
822
sub portControl ($$@) {
Weibin Sun's avatar
Weibin Sun committed
823
824
825
826
827
828
829
    my $self = shift;

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

    my $errors = 0;
    foreach my $port (@pcports) { 	
Weibin Sun's avatar
Weibin Sun committed
830
	if (isSwitchPort($port) || ref($self->toApconPort($port->getSwitchPort()))) {
Weibin Sun's avatar
Weibin Sun committed
831
832
833
                next;
        }

Weibin Sun's avatar
Weibin Sun committed
834
        my $rt = $self->setPortRate($self->toApconPort($port->getSwitchPort()), $cmd);
Weibin Sun's avatar
Weibin Sun committed
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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
        if ($rt) {
            if ($rt =~ /^ERROR: port rate unsupported/) {
                #
                # Command not supported
                #
                $self->debug("Unsupported port command '$cmd' ignored.\n");
                return 0;
            }

            $errors++;
        }
    }

    return $errors;
}

# 
# 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;
    }
}

#
# Original purpose: 
# Given VLAN indentifiers from the database, finds the 802.1Q VLAN
# 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 
# funtion actually either list all VLAN names or do the existance checking,
# 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.
    #
    my $vlans = $self->getAllNamedPorts();
    foreach $vlan_name (keys %{$vlans}) {
        if (!@vlan_ids || exists $mapping{$vlan_name}) {
            $mapping{$vlan_name} = $vlan_name;
        }
    }

    foreach $vlan_name (keys %emptyVlans) {
        if ( exists $mapping{$vlan_name} ) {
            $mapping{$vlan_name} = $vlan_name;
        }
    }
    
    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);
    
    my $ports = $self->getNamedPorts($vlan_id);
    if (@$ports) {
        return $vlan_id;
    } elsif (exists($emptyVlans{$vlan_id})) {
        return $vlan_id;
    }

    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)) {
        warn "$id called without supplying vlan_number";
        return 0;
    }
    my $check_number = $self->findVlan($vlan_id,1);
    if (defined($check_number)) {
        warn "$id: recreating vlan id $vlan_id \n";
        return 0;
    }
    
    print "  Creating VLAN $vlan_id as VLAN #$vlan_id on " .
        "$self->{NAME} ...\n";

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

    return $vlan_id;
}

#
# Put the given ports in the given VLAN. The VLAN is given as an 802.1Q 
# tag number.
#
# usage: setPortVlan($self, $vlan_number, @ports)
#     returns 0 on sucess.
#     returns the number of failed ports on failure.
#
987
sub setPortVlan($$@) {
Weibin Sun's avatar
Weibin Sun committed
988
989
990
991
992
993
    my $self = shift;
    my $vlan_id = shift;
    my @pcports = @_;

    my $id = $self->{NAME} . "::setPortVlan";
    $self->debug("$id: $vlan_id ");
Weibin Sun's avatar
Weibin Sun committed
994
    $self->debug("ports: " . Port->toStrings(@pcports). "\n");
Weibin Sun's avatar
Weibin Sun committed
995
996
997
998
999
1000

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

Weibin Sun's avatar
Weibin Sun committed
1001
    my @ports = grep(!ref($_), map( $self->toApconPort($_->getSwitchPort()), @pcports));
Weibin Sun's avatar
Weibin Sun committed
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
    $self->lock();

    # Check if ports are free
    foreach my $port (@ports) {        
        if ($self->getPortName($port)) {
            warn "ERROR: Port $port already in use.\n";
            $self->unlock();
	    $self->debug("Port $port already in use in $_.\n");
            return 1;
        }
    }

    $self->debug("$id: ports is free\n");
    
    my $errmsg = $self->namePorts($vlan_id, @ports);
    if ($errmsg) {
        warn "$errmsg";
        $self->unlock();
	$self->debug("$errmsg");
        return 1;
    }

    my ($rt, $msg) = $self->connectDuplex($ports[0], $ports[1]);
    if ($rt) {
	$self->unnamePorts(@ports);
	warn "$id: ports connection failed. $msg\n";
	$self->debug("$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;
    }

    $self->unlock();

    #
    # Check if this vlan was empty before and delete
    # it from the empty vlan records if YES.
    #
    if (exists($emptyVlans{$vlan_id})) {
        delete $emptyVlans{$vlan_id};
    }

    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)
#     returns 0 on sucess.
#     returns the number of failed ports on failure.
#
1061
sub delPortVlan($$@) {
Weibin Sun's avatar
Weibin Sun committed
1062
1063
1064
1065
1066
    my $self = shift;
    my $vlan_id = shift;
    my @pcports = @_;

    $self->debug($self->{NAME} . "::delPortVlan $vlan_id ");
Weibin Sun's avatar
Weibin Sun committed
1067
    $self->debug("ports: " . Port->toStrings(@pcports) . "\n");
Weibin Sun's avatar
Weibin Sun committed
1068

Weibin Sun's avatar
Weibin Sun committed
1069
    my @ports = grep(!ref($_), map($self->toApconPort($_->getSwitchPort()), @pcports));
Weibin Sun's avatar
Weibin Sun committed
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231

    $self->lock();

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

    #
    # Find connections of @ports
    #
    my ($src, $dst) = $self->getNamedConnections($vlan_id);
    my %sconns = ();
    foreach my $p (@ports) {

        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;
                }
            }    
        }
    }
    
    # Disconnect conections of @ports
    my $errmsg = $self->disconnectPorts(\%sconns);
    if ($errmsg) {
        warn "$errmsg";
        $self->unlock();
        return 1;
    }
    
    # Unname the ports, looks like 'remove'
    $errmsg = $self->unnamePorts(@ports);
    if ($errmsg) {
        warn "$errmsg";
        $self->unlock();
        return 1;
    }    

    #
    # Remember the empty VLAN for warning msg when unloading module
    #
    if (scalar (@ports) == scalar (@$allports)) {
        $emptyVlans{$vlan_id} = 1;
    }

    $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)
#     returns 0 on sucess.
#     returns the number of failed ports on failure.
#
sub removePortsFromVlan($@) {
    my $self = shift;
    my @vlan_numbers = @_;
    my $errors = 0;
    my $id = $self->{NAME} . "::removePortsFromVlan";

    foreach my $vlan_number (@vlan_numbers) {
        if ($self->removePortName($vlan_number)) {
            $errors++;
        } else {
            $emptyVlans{$vlan_number} = 1;
        }
    }
    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)
#     returns 0 on sucess.
#     returns the number of failed ports on failure.
#
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)
#     returns 1 on success
#     returns 0 on failure
#
#
sub removeVlan($@) {
    my $self = shift;
    my @vlan_numbers = @_;
    my $errors = 0;

    foreach my $vlan_number (@vlan_numbers) {
        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})) {
                delete $emptyVlans{$vlan_number};
            }

            print "Removed VLAN $vlan_number on switch $self->{NAME}.\n";    
        }    
    }

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



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

    my $portset = $self->getNamedPorts($vlan_number);
    if (@$portset) {
        return 1;
    }

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

    return 0;
}


#
# List all VLANs on the device
#
# usage: listVlans($self)
# see snmpit_cisco_stack.pm for a description of return value format
#
1232
sub listVlans($) {
Weibin Sun's avatar
Weibin Sun committed
1233
1234
1235
1236
1237
1238
    my $self = shift;

    my @list = ();
    my $vlans = $self->getAllNamedPorts();
    foreach my $vlan_id (keys %$vlans) {
        my @swports = @{$vlans->{$vlan_id}};
Weibin Sun's avatar
Weibin Sun committed
1239
1240
1241
        my @pcports = map($_->getPCPort(), 
                        grep(ref($_), 
                        map($self->fromApconPort($_), @swports)));
Weibin Sun's avatar
Weibin Sun committed
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
        
        push @list, [$vlan_id, $vlan_id, \@pcports];
    }
    
    return @list;
}

#
# List all ports on the device
#
# usage: listPorts($self)
# see snmpit_cisco_stack.pm for a description of return value format
#
1255
sub listPorts($) {
Weibin Sun's avatar
Weibin Sun committed
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
    my $self = shift;
    my @ports = ();

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

        my $finalport = $self->fromApconPort($port);
Weibin Sun's avatar
Weibin Sun committed
1266
        if (!ref($finalport)) {
Weibin Sun's avatar
Weibin Sun committed
1267
		next;
Weibin Sun's avatar
Weibin Sun committed
1268
        }          
Weibin Sun's avatar
Weibin Sun committed
1269
1270
1271
1272
1273

        #
        # if port is actived, use actual rate, otherwise use desired rate
        #
        if ( $arate[0] eq "00" ) {        
Weibin Sun's avatar
Weibin Sun committed
1274
            push @ports, [$finalport->getPCPort(), "no", "down", $strdrate[2], $strdrate[1]];
Weibin Sun's avatar
Weibin Sun committed
1275
1276
1277
1278
        } else {
            #
            # Not sure if it is OK to just ignore the desired rate
            #
Weibin Sun's avatar
Weibin Sun committed
1279
            push @ports, [$finalport->getPCPort(), "yes", "up", $arate[3], $arate[2]];
Weibin Sun's avatar
Weibin Sun committed
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
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
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
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
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
        }
    }
    
    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
#     vlan_numbers: An array of 802.1Q VLAN numbers to operate on
#        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
#     equaltrunk: don't do dual mode; tag PVID also.
#        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)) {
        $debuglevel = 1;
    }
    if ($self->{DEBUG} >= $debuglevel) {
        print STDERR $string;
    }
}

my $lock_held = 0;

sub lock($) {
    my $self = shift;
    my $token = "snmpit_" . $self->{NAME};
    if ($lock_held == 0) {
        my $old_umask = umask(0);
        die if (TBScriptLock($token,0,1800) != TBSCRIPTLOCK_OKAY());
        umask($old_umask);
    }
    $lock_held = 1;
}

sub unlock($) {
    if ($lock_held == 1) { TBScriptUnlock();}
    $lock_held = 0;
}


#
# 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;
}


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

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

}

# End with true
1;