Satish K
Committed by Gerrit Code Review

[Emu][ONOS-2593, ONOS-2594] BGP SBI controller and session handler

Change-Id: Ia95717ff173b2e3e1198bdd0fafef7cb0aa8f734
Showing 20 changed files with 1526 additions and 96 deletions
......@@ -47,288 +47,251 @@ public interface BGPCfg {
/**
* Returns the status of the configuration based on this state certain operations like connection is handled.
*
* @return
* State of the configuration
* @return State of the configuration
*/
State getState();
/**
* To set the current state of the configuration.
*
* @param state
* Configuration State enum
* @param state Configuration State enum
*/
void setState(State state);
/**
* Get the status of the link state support for this BGP speaker.
*
* @return
* true if the link state is supported else false
* @return true if the link state is supported else false
*/
boolean getLsCapability();
/**
* Set the link state support to this BGP speaker.
*
* @param lscapability
* true value if link state is supported else false
* @param lscapability true value if link state is supported else false
*/
void setLsCapability(boolean lscapability);
/**
* Get the status of the 32 bit AS support for this BGP speaker.
*
* @return
* true if the 32 bit AS number is supported else false
* @return true if the 32 bit AS number is supported else false
*/
boolean getLargeASCapability();
/**
* Set the 32 bit AS support capability to this BGP speaker.
*
* @param largeAs
* true value if the 32 bit AS is supported else false
* @param largeAs true value if the 32 bit AS is supported else false
*/
void setLargeASCapability(boolean largeAs);
/**
* Set the AS number to which this BGP speaker belongs.
*
* @param localAs
* 16 or 32 bit AS number, length is dependent on the capability
* @param localAs 16 or 32 bit AS number, length is dependent on the capability
*/
void setAsNumber(int localAs);
/**
* Get the AS number to which this BGP speaker belongs.
*
* @return
* 16 or 32 bit AS number, length is dependent on the capability
* @return 16 or 32 bit AS number, length is dependent on the capability
*/
int getAsNumber();
/**
* Get the connection retry count number.
*
* @return
* connection retry count if there is a connection error
* @return connection retry count if there is a connection error
*/
int getMaxConnRetryCount();
/**
* Set the connection retry count.
*
* @param retryCount
* number of times to try to connect if there is any error
* @param retryCount number of times to try to connect if there is any error
*/
void setMaxConnRetryCout(int retryCount);
/**
* Get the connection retry time in seconds.
*
* @return
* connection retry time in seconds
* @return connection retry time in seconds
*/
int getMaxConnRetryTime();
/**
* Set the connection retry time in seconds.
*
* @param retryTime
* connection retry times in seconds
* @param retryTime connection retry times in seconds
*/
void setMaxConnRetryTime(int retryTime);
/**
* Set the keep alive timer for the connection.
*
* @param holdTime
* connection hold timer in seconds
* @param holdTime connection hold timer in seconds
*/
void setHoldTime(short holdTime);
/**
* Returns the connection hold timer in seconds.
*
* @return
* connection hold timer in seconds
* @return connection hold timer in seconds
*/
short getHoldTime();
/**
* Returns the maximum number of session supported.
*
* @return
* maximum number of session supported
* @return maximum number of session supported
*/
int getMaxSession();
/**
* Set the maximum number of sessions to support.
*
* @param maxsession
* maximum number of session
* @param maxsession maximum number of session
*/
void setMaxSession(int maxsession);
/**
* Returns the Router ID of this BGP speaker.
*
* @return
* IP address in string format
* @return IP address in string format
*/
String getRouterId();
/**
* Set the Router ID of this BGP speaker.
*
* @param routerid
* IP address in string format
* @param routerid IP address in string format
*/
void setRouterId(String routerid);
/**
* Add the BGP peer IP address and the AS number to which it belongs.
*
* @param routerid
* IP address in string format
* @param remoteAs
* AS number to which it belongs
* @return
* true if added successfully else false
* @param routerid IP address in string format
* @param remoteAs AS number to which it belongs
*
* @return true if added successfully else false
*/
boolean addPeer(String routerid, int remoteAs);
/**
* Add the BGP peer IP address and the keep alive time.
*
* @param routerid
* IP address in string format
* @param holdTime
* keep alive time for the connection
* @return
* true if added successfully else false
* @param routerid IP address in string format
* @param holdTime keep alive time for the connection
*
* @return true if added successfully else false
*/
boolean addPeer(String routerid, short holdTime);
/**
* Add the BGP peer IP address, the AS number to which it belongs and keep alive time.
*
* @param routerid
* IP address in string format
* @param remoteAs
* AS number to which it belongs
* @param holdTime
* keep alive time for the connection
* @return
* true if added successfully else false
* @param routerid IP address in string format
* @param remoteAs AS number to which it belongs
* @param holdTime keep alive time for the connection
*
* @return true if added successfully else false
*/
boolean addPeer(String routerid, int remoteAs, short holdTime);
/**
* Remove the BGP peer with this IP address.
*
* @param routerid
* router IP address
* @return
* true if removed successfully else false
* @param routerid router IP address
*
* @return true if removed successfully else false
*/
boolean removePeer(String routerid);
/**
* Connect to BGP peer with this IP address.
*
* @param routerid
* router IP address
* @return
* true of the configuration is found and able to connect else false
* @param routerid router IP address
*
* @return true of the configuration is found and able to connect else false
*/
boolean connectPeer(String routerid);
/**
* Disconnect this BGP peer with this IP address.
*
* @param routerid
* router IP address in string format
* @return
* true if the configuration is found and able to disconnect else false
* @param routerid router IP address in string format
*
* @return true if the configuration is found and able to disconnect else false
*/
boolean disconnectPeer(String routerid);
/**
* Returns the peer tree information.
*
* @return
* return the tree map with IP as key and BGPPeerCfg as object
* @return return the tree map with IP as key and BGPPeerCfg as object
*/
TreeMap<String, BGPPeerCfg> displayPeers();
/**
* Return the BGP Peer information with this matching IP.
*
* @param routerid
* router IP address in string format
* @return
* BGPPeerCfg object
* @param routerid router IP address in string format
*
* @return BGPPeerCfg object
*/
BGPPeerCfg displayPeers(String routerid);
/**
* Check if this BGP peer is configured.
*
* @param routerid
* router IP address in string format
* @return
* true if configured exists else false
* @param routerid router IP address in string format
*
* @return true if configured exists else false
*/
boolean isPeerConfigured(String routerid);
/**
* Check if this BGP speaker is having connection with the peer.
*
* @param routerid
* router IP address in string format
* @return
* true if the connection exists else false
* @param routerid router IP address in string format
*
* @return true if the connection exists else false
*/
boolean isPeerConnected(String routerid);
/**
* Return the peer tree map.
*
* @return
* return the tree map with IP as key and BGPPeerCfg as object
* @return return the tree map with IP as key and BGPPeerCfg as object
*/
TreeMap<String, BGPPeerCfg> getPeerTree();
/**
* Set the current connection state information.
*
* @param routerid
* router IP address in string format
* @param state
* state information
* @param routerid router IP address in string format
* @param state state information
*/
void setPeerConnState(String routerid, BGPPeerCfg.State state);
/**
* Check if the peer can be connected or not.
*
* @param routerid
* router IP address in string format
* @return
* true if the peer can be connected else false
* @param routerid router IP address in string format
*
* @return true if the peer can be connected else false
*/
boolean isPeerConnectable(String routerid);
/**
* Get the current peer connection state information.
*
* @param routerid
* router IP address in string format
* @return
* state information
* @param routerid router IP address in string format
*
* @return state information
*/
BGPPeerCfg.State getPeerConnState(String routerid);
}
......
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgp.controller;
import org.onosproject.bgpio.protocol.BGPMessage;
/**
* Abstraction of an BGP controller. Serves as a one stop shop for obtaining BGP devices and (un)register listeners
* on bgp events
*/
public interface BGPController {
/**
* Send a message to a particular bgp peer.
*
* @param bgpId the id of the peer to send message.
* @param msg the message to send
*/
void writeMsg(BGPId bgpId, BGPMessage msg);
/**
* Process a message and notify the appropriate listeners.
*
* @param bgpId id of the peer the message arrived on
* @param msg the message to process.
*/
void processBGPPacket(BGPId bgpId, BGPMessage msg);
/**
* Get the BGPConfig class to the caller.
*
* @return configuration object
*/
BGPCfg getConfig();
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgp.controller;
import org.onlab.packet.IpAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkArgument;
/**
* The class representing a network peer bgp ip.
* This class is immutable.
*/
public final class BGPId {
private static final String SCHEME = "bgp";
private static final long UNKNOWN = 0;
private final IpAddress ipAddress;
/**
* Private constructor.
*/
private BGPId(IpAddress ipAddress) {
this.ipAddress = ipAddress;
}
/**
* Create a BGPId from ip address.
*
* @param ipAddress IP address
* @return object of BGPId
*/
public static BGPId bgpId(IpAddress ipAddress) {
return new BGPId(ipAddress);
}
/**
* Returns the ip address.
*
* @return ipAddress
*/
public IpAddress ipAddress() {
return ipAddress;
}
/**
* Convert the BGPId value to a ':' separated hexadecimal string.
*
* @return the BGPId value as a ':' separated hexadecimal string.
*/
@Override
public String toString() {
return ipAddress.toString();
}
@Override
public boolean equals(Object other) {
if (!(other instanceof BGPId)) {
return false;
}
BGPId otherBGPid = (BGPId) other;
return Objects.equals(ipAddress, otherBGPid.ipAddress);
}
@Override
public int hashCode() {
return Objects.hash(ipAddress);
}
/**
* Returns BGPId created from the given device URI.
*
* @param uri device URI
* @return object of BGPId
*/
public static BGPId bgpId(URI uri) {
checkArgument(uri.getScheme().equals(SCHEME), "Unsupported URI scheme");
return new BGPId(IpAddress.valueOf(uri.getSchemeSpecificPart()));
}
/**
* Produces device URI from the given DPID.
*
* @param bgpId device bgpId
* @return device URI
*/
public static URI uri(BGPId bgpId) {
return uri(bgpId.ipAddress());
}
/**
* Produces device URI from the given DPID long.
*
* @param ipAddress device ip address
* @return device URI
*/
public static URI uri(IpAddress ipAddress) {
try {
return new URI(SCHEME, ipAddress.toString(), null);
} catch (URISyntaxException e) {
return null;
}
}
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgp.controller;
/**
* A representation of a packet context which allows any provider to view a packet in event, but may block the response
* to the event if blocked has been called. This packet context can be used to react to the packet in event with a
* packet out.
*/
public interface BGPPacketStats {
/**
* Returns the count for no of packets sent out.
*
* @return int value of no of packets sent
*/
int outPacketCount();
/**
* Returns the count for no of packets received.
*
* @return int value of no of packets sent
*/
int inPacketCount();
/**
* Returns the count for no of wrong packets received.
*
* @return int value of no of wrong packets received
*/
int wrongPacketCount();
/**
* Returns the time.
*
* @return the time
*/
long getTime();
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgpio.exceptions;
import org.jboss.netty.buffer.ChannelBuffer;
/**
* Custom Exception for BGP IO.
*/
public class BGPParseException extends Exception {
private static final long serialVersionUID = 1L;
private byte errorCode;
private byte errorSubCode;
private ChannelBuffer data;
/**
* Default constructor to create a new exception.
*/
public BGPParseException() {
super();
}
/**
* Constructor to create exception from message and cause.
*
* @param message the detail of exception in string
* @param cause underlying cause of the error
*/
public BGPParseException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* Constructor to create exception from message.
*
* @param message the detail of exception in string
*/
public BGPParseException(final String message) {
super(message);
}
/**
* Constructor to create exception from cause.
*
* @param cause underlying cause of the error
*/
public BGPParseException(final Throwable cause) {
super(cause);
}
/**
* Constructor to create exception from error code and error subcode.
*
* @param errorCode error code of BGP message
* @param errorSubCode error subcode of BGP message
* @param data error data of BGP message
*/
public BGPParseException(final byte errorCode, final byte errorSubCode, final ChannelBuffer data) {
super();
this.errorCode = errorCode;
this.errorSubCode = errorSubCode;
this.data = data;
}
/**
* Returns errorcode for this exception.
*
* @return errorcode for this exception
*/
public byte getErrorCode() {
return this.errorCode;
}
/**
* Returns error Subcode for this exception.
*
* @return error Subcode for this exception
*/
public byte getErrorSubCode() {
return this.errorSubCode;
}
/**
* Returns error data for this exception.
*
* @return error data for this exception
*/
public ChannelBuffer getData() {
return this.data;
}
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgpio.protocol;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onosproject.bgpio.exceptions.BGPParseException;
import org.onosproject.bgpio.types.BGPHeader;
/**
* Abstraction of an entity providing BGP Messages.
*/
public interface BGPMessage extends Writeable {
/**
* Returns BGP Header of BGP Message.
*
* @return BGP Header of BGP Message
*/
BGPHeader getHeader();
/**
* Returns version of BGP Message.
*
* @return version of BGP Message
*/
BGPVersion getVersion();
/**
* Returns BGP Type of BGP Message.
*
* @return BGP Type of BGP Message
*/
BGPType getType();
@Override
void writeTo(ChannelBuffer cb) throws BGPParseException;
/**
* Builder interface with get and set functions to build BGP Message.
*/
interface Builder {
/**
* Builds BGP Message.
*
* @return BGP Message
* @throws BGPParseException while building bgp message
*/
BGPMessage build() throws BGPParseException;
/**
* Returns BGP Version of BGP Message.
*
* @return BGP Version of BGP Message
*/
BGPVersion getVersion();
/**
* Returns BGP Type of BGP Message.
*
* @return BGP Type of BGP Message
*/
BGPType getType();
/**
* Returns BGP Header of BGP Message.
*
* @return BGP Header of BGP Message
*/
BGPHeader getHeader();
/**
* Sets BgpHeader and return its builder.
*
* @param bgpMsgHeader BGP Message Header
* @return builder by setting BGP message header
*/
Builder setHeader(BGPHeader bgpMsgHeader);
}
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgpio.protocol;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onosproject.bgpio.exceptions.BGPParseException;
import org.onosproject.bgpio.types.BGPHeader;
/**
* Abstraction of an entity providing BGP Message Reader.
*/
public interface BGPMessageReader<T> {
/**
* Reads the Objects in the BGP Message and Returns BGP Message.
*
* @param cb Channel Buffer
* @param bgpHeader BGP message header
* @return BGP Message
* @throws BGPParseException while parsing BGP message.
*/
T readFrom(ChannelBuffer cb, BGPHeader bgpHeader) throws BGPParseException;
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgpio.protocol;
/**
* Enum to Provide the Different types of BGP messages.
*/
public enum BGPType {
NONE(0), OPEN(1), UPDATE(2), NOTIFICATION(3), KEEP_ALIVE(4);
int value;
/**
* Assign value with the value val as the types of BGP message.
*
* @param val type of BGP message
*/
BGPType(int val) {
value = val;
}
/**
* Returns value as type of BGP message.
*
* @return value type of BGP message
*/
public byte getType() {
return (byte) value;
}
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgpio.protocol;
/**
* Enum to provide BGP Message Version.
*/
public enum BGPVersion {
BGP_4(4);
public final int packetVersion;
/**
* Assign BGP PacketVersion with specified packetVersion.
*
* @param packetVersion version of BGP
*/
BGPVersion(final int packetVersion) {
this.packetVersion = packetVersion;
}
/**
* Returns Packet version of BGP Message.
*
* @return packetVersion
*/
public int getPacketVersion() {
return packetVersion;
}
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgpio.protocol;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onosproject.bgpio.exceptions.BGPParseException;
/**
* Abstraction of an entity providing functionality to write byte streams of
* Messages to channel buffer.
*/
public interface Writeable {
/**
* Writes byte streams of messages to channel buffer.
*
* @param cb channelBuffer
* @throws BGPParseException when error occurs while writing BGP message to channel buffer
*/
void writeTo(ChannelBuffer cb) throws BGPParseException;
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgpio.types;
import org.jboss.netty.buffer.ChannelBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides BGP Message Header which is common for all the Messages.
*/
public class BGPHeader {
/* 0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ +
| Marker |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Length | Type |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
protected static final Logger log = LoggerFactory.getLogger(BGPHeader.class);
public static final int MARKER_LENGTH = 16;
public static final short DEFAULT_HEADER_LENGTH = 19;
private byte[] marker;
private byte type;
private short length;
/**
* Reset fields.
*/
public BGPHeader() {
this.marker = null;
this.length = 0;
this.type = 0;
}
/**
* Constructors to initialize parameters.
*
* @param marker field in BGP header
* @param length message length
* @param type message type
*/
public BGPHeader(byte[] marker, short length, byte type) {
this.marker = marker;
this.length = length;
this.type = type;
}
/**
* Sets marker field.
*
* @param value marker field
*/
public void setMarker(byte[] value) {
this.marker = value;
}
/**
* Sets message type.
*
* @param value message type
*/
public void setType(byte value) {
this.type = value;
}
/**
* Sets message length.
*
* @param value message length
*/
public void setLength(short value) {
this.length = value;
}
/**
* Returns message length.
*
* @return message length
*/
public short getLength() {
return this.length;
}
/**
* Returns message marker.
*
* @return message marker
*/
public byte[] getMarker() {
return this.marker;
}
/**
* Returns message type.
*
* @return message type
*/
public byte getType() {
return this.type;
}
/**
* Writes Byte stream of BGP header to channel buffer.
*
* @param cb ChannelBuffer
* @return length index of message header
*/
public int write(ChannelBuffer cb) {
cb.writeBytes(getMarker(), 0, MARKER_LENGTH);
int headerLenIndex = cb.writerIndex();
cb.writeShort((short) 0);
cb.writeByte(type);
return headerLenIndex;
}
/**
* Read from channel buffer and Returns BGP header.
*
* @param cb ChannelBuffer
* @return object of BGPHeader
*/
public static BGPHeader read(ChannelBuffer cb) {
byte[] marker = new byte[MARKER_LENGTH];
byte type;
short length;
cb.readBytes(marker, 0, MARKER_LENGTH);
length = cb.readShort();
type = cb.readByte();
return new BGPHeader(marker, length, type);
}
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgpio.types;
import org.jboss.netty.buffer.ChannelBuffer;
/**
* Abstraction which Provides the BGP of TLV format.
*/
public interface BGPValueType {
/**
* Returns the Type of BGP Message.
*
* @return short value of type
*/
short getType();
/**
* Writes the byte Stream of BGP Message to channel buffer.
*
* @param cb channel buffer
* @return length written to channel buffer
*/
int write(ChannelBuffer cb);
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgp.controller.impl;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
/**
* Channel handler deals with the bgp peer connection and dispatches messages from peer to the appropriate locations.
*/
class BGPChannelHandler extends IdleStateAwareChannelHandler {
// TODO: implement FSM and session handling mechanism
/**
* Create a new unconnected BGPChannelHandler.
*
* @param bgpCtrlImpl bgp controller implementation object
*/
BGPChannelHandler(BGPControllerImpl bgpCtrlImpl) {
}
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgp.controller.impl;
import static org.onlab.util.Tools.groupedThreads;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Service;
import org.onosproject.bgp.controller.BGPCfg;
import org.onosproject.bgp.controller.BGPController;
import org.onosproject.bgp.controller.BGPId;
import org.onosproject.bgpio.protocol.BGPMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(immediate = true)
@Service
public class BGPControllerImpl implements BGPController {
private static final Logger log = LoggerFactory.getLogger(BGPControllerImpl.class);
private final ExecutorService executorMsgs = Executors.newFixedThreadPool(32,
groupedThreads("onos/bgp",
"event-stats-%d"));
private final ExecutorService executorBarrier = Executors.newFixedThreadPool(4,
groupedThreads("onos/bgp",
"event-barrier-%d"));
final Controller ctrl = new Controller(this);
private BGPConfig bgpconfig = new BGPConfig();
@Activate
public void activate() {
this.ctrl.start();
log.info("Started");
}
@Deactivate
public void deactivate() {
// Close all connected peers
this.ctrl.stop();
log.info("Stopped");
}
@Override
public void writeMsg(BGPId bgpId, BGPMessage msg) {
// TODO: Send message
}
@Override
public void processBGPPacket(BGPId bgpId, BGPMessage msg) {
switch (msg.getType()) {
case OPEN:
// TODO: Process Open message
break;
case KEEP_ALIVE:
// TODO: Process keepalive message
break;
case NOTIFICATION:
// TODO: Process notificatoin message
break;
case UPDATE:
// TODO: Process update message
break;
default:
// TODO: Process other message
break;
}
}
/**
* Get controller instance.
*
* @return ctrl the controller.
*/
public Controller getController() {
return ctrl;
}
@Override
public BGPCfg getConfig() {
return this.bgpconfig;
}
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgp.controller.impl;
import java.util.LinkedList;
import java.util.List;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.onosproject.bgpio.protocol.BGPMessage;
import org.onlab.util.HexDump;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Decode an bgp message from a Channel, for use in a netty pipeline.
*/
public class BGPMessageDecoder extends FrameDecoder {
protected static final Logger log = LoggerFactory.getLogger(BGPMessageDecoder.class);
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
List<BGPMessage> msgList = new LinkedList<BGPMessage>();
log.debug("MESSAGE IS RECEIVED.");
if (!channel.isConnected()) {
log.info("Channel is not connected.");
return null;
}
HexDump.dump(buffer);
// TODO: decode bgp messages
return msgList;
}
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgp.controller.impl;
import java.util.List;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
import org.onosproject.bgpio.protocol.BGPMessage;
import org.onlab.util.HexDump;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Encode an bgp message for output into a ChannelBuffer, for use in a
* netty pipeline.
*/
public class BGPMessageEncoder extends OneToOneEncoder {
protected static final Logger log = LoggerFactory.getLogger(BGPMessageEncoder.class);
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
log.debug("BGPMessageEncoder::encode");
if (!(msg instanceof List)) {
log.debug("Invalid msg.");
return msg;
}
@SuppressWarnings("unchecked")
List<BGPMessage> msglist = (List<BGPMessage>) msg;
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
log.debug("SENDING MESSAGE");
for (BGPMessage pm : msglist) {
pm.writeTo(buf);
}
HexDump.dump(buf);
return buf;
}
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgp.controller.impl;
import org.onosproject.bgp.controller.BGPPacketStats;
/**
* A representation of a packet context which allows any provider
* to view a packet in event, but may block the response to the
* event if blocked has been called. This packet context can be used
* to react to the packet in event with a packet out.
*/
public class BGPPacketStatsImpl implements BGPPacketStats {
private int inPacketCount;
private int outPacketCount;
private int wrongPacketCount;
private long time;
/**
* Resets parameter.
*/
public BGPPacketStatsImpl() {
this.inPacketCount = 0;
this.outPacketCount = 0;
this.wrongPacketCount = 0;
this.time = 0;
}
/**
* Get the outgoing packet count number.
*
* @return
* packet count
*/
public int outPacketCount() {
return outPacketCount;
}
/**
* Get the incoming packet count number.
*
* @return
* packet count
*/
public int inPacketCount() {
return inPacketCount;
}
/**
* Get the wrong packet count number.
*
* @return
* packet count
*/
public int wrongPacketCount() {
return wrongPacketCount;
}
/**
* Increments the received packet counter.
*/
public void addInPacket() {
this.inPacketCount++;
}
/**
* Increments the sent packet counter.
*/
public void addOutPacket() {
this.outPacketCount++;
}
/**
* Increments the sent packet counter by specified value.
*
* @param value of no of packets sent
*/
public void addOutPacket(int value) {
this.outPacketCount = this.outPacketCount + value;
}
/**
* Increments the wrong packet counter.
*/
public void addWrongPacket() {
this.wrongPacketCount++;
}
/**
* Resets wrong packet count.
*/
public void resetWrongPacket() {
this.wrongPacketCount = 0;
}
/**
* Get the time.
*
* @return
* time
*/
public long getTime() {
return this.time;
}
/**
* Sets the time.
*
* @param time value to set
*/
public void setTime(long time) {
this.time = time;
}
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgp.controller.impl;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.timeout.ReadTimeoutHandler;
import org.jboss.netty.util.ExternalResourceReleasable;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timer;
/**
* Creates a ChannelPipeline for a server-side bgp channel.
*/
public class BGPPipelineFactory
implements ChannelPipelineFactory, ExternalResourceReleasable {
static final Timer TIMER = new HashedWheelTimer();
protected ReadTimeoutHandler readTimeoutHandler;
BGPControllerImpl bgpCtrlImpl;
/**
* Constructor to initialize the values.
*
* @param ctrlImpl parent ctrlImpl
* @param isServBgp if it is a server or not
*/
public BGPPipelineFactory(BGPControllerImpl ctrlImpl, boolean isServBgp) {
super();
bgpCtrlImpl = ctrlImpl;
/* hold time*/
readTimeoutHandler = new ReadTimeoutHandler(TIMER, bgpCtrlImpl.getConfig().getHoldTime());
}
@Override
public ChannelPipeline getPipeline() throws Exception {
BGPChannelHandler handler = new BGPChannelHandler(bgpCtrlImpl);
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("bgpmessagedecoder", new BGPMessageDecoder());
pipeline.addLast("bgpmessageencoder", new BGPMessageEncoder());
pipeline.addLast("holdTime", readTimeoutHandler);
pipeline.addLast("PassiveHandler", handler);
return pipeline;
}
@Override
public void releaseExternalResources() {
TIMER.stop();
}
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgp.controller.impl;
import static org.onlab.util.Tools.groupedThreads;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The main controller class. Handles all setup and network listeners - Distributed ownership control of bgp peer
* through IControllerRegistryService
*/
public class Controller {
protected static final Logger log = LoggerFactory.getLogger(Controller.class);
private ChannelGroup cg;
// Configuration options
private static final short BGP_PORT_NUM = 179;
private int workerThreads = 16;
// Start time of the controller
protected long systemStartTime;
private NioServerSocketChannelFactory serverExecFactory;
// Perf. related configuration
protected static final int SEND_BUFFER_SIZE = 4 * 1024 * 1024;
BGPControllerImpl bgpCtrlImpl;
/**
* Constructor to initialize parameter.
*
* @param bgpCtrlImpl BGP controller Impl instance
*/
public Controller(BGPControllerImpl bgpCtrlImpl) {
this.bgpCtrlImpl = bgpCtrlImpl;
}
// ***************
// Getters/Setters
// ***************
/**
* To get system start time.
*
* @return system start time in milliseconds
*/
public long getSystemStartTime() {
return (this.systemStartTime);
}
// **************
// Initialization
// **************
/**
* Tell controller that we're ready to accept bgp peer connections.
*/
public void run() {
try {
final ServerBootstrap bootstrap = createServerBootStrap();
bootstrap.setOption("reuseAddr", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.sendBufferSize", Controller.SEND_BUFFER_SIZE);
ChannelPipelineFactory pfact = new BGPPipelineFactory(bgpCtrlImpl, true);
bootstrap.setPipelineFactory(pfact);
InetSocketAddress sa = new InetSocketAddress(getBgpPortNum());
cg = new DefaultChannelGroup();
cg.add(bootstrap.bind(sa));
log.info("Listening for Peer connection on {}", sa);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Creates server boot strap.
*
* @return ServerBootStrap
*/
private ServerBootstrap createServerBootStrap() {
if (workerThreads == 0) {
serverExecFactory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(groupedThreads("onos/bgp", "boss-%d")),
Executors.newCachedThreadPool(groupedThreads("onos/bgp", "worker-%d")));
return new ServerBootstrap(serverExecFactory);
} else {
serverExecFactory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(groupedThreads("onos/bgp", "boss-%d")),
Executors.newCachedThreadPool(groupedThreads("onos/bgp", "worker-%d")),
workerThreads);
return new ServerBootstrap(serverExecFactory);
}
}
/**
* Initialize internal data structures.
*/
public void init() {
// These data structures are initialized here because other
// module's startUp() might be called before ours
this.systemStartTime = System.currentTimeMillis();
}
// **************
// Utility methods
// **************
public Map<String, Long> getMemory() {
Map<String, Long> m = new HashMap<>();
Runtime runtime = Runtime.getRuntime();
m.put("total", runtime.totalMemory());
m.put("free", runtime.freeMemory());
return m;
}
public Long getUptime() {
RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
return rb.getUptime();
}
/**
* Starts the BGP controller.
*/
public void start() {
log.info("Started");
this.init();
this.run();
}
/**
* Stops the BGP controller.
*/
public void stop() {
log.info("Stopped");
serverExecFactory.shutdown();
cg.close();
}
/**
* Returns port number.
*
* @return port number
*/
public static short getBgpPortNum() {
return BGP_PORT_NUM;
}
}
\ No newline at end of file
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onlab.util;
import org.jboss.netty.buffer.ChannelBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* HexDump class an utility to dump buffer in hex format.
*/
public final class HexDump {
protected static final Logger log = LoggerFactory.getLogger(HexDump.class);
private HexDump() {
}
/**
* Dump the buffer content in hex format.
*
* @param buff buffer content to dump in hex format
*/
public static void dump(ChannelBuffer buff) {
try {
byte[] yTemp;
yTemp = buff.array();
int iStartIndex = buff.readerIndex();
int iEndIndex = buff.writerIndex();
do {
StringBuilder sb = new StringBuilder();
for (int k = 0; (k < 16) && (iStartIndex < iEndIndex); ++k) {
if (0 == k % 4) {
sb.append(String.format(" ")); // blank after 4 bytes
}
sb.append(String.format("%02X ", yTemp[iStartIndex++]));
}
log.debug(sb.toString());
} while (iStartIndex < iEndIndex);
} catch (Exception e) {
log.error("[HexDump] Invalid buffer: " + e.toString());
}
}
}