Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • tfs/controller
1 result
Show changes
Showing
with 3648 additions and 0 deletions
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.bgp4session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* BGP4 DeadTimer management Thread
*
*/
public class DeadTimerThread extends Thread {
private BGP4Session bgp4Session = null;
private int deadTimer = 0;
private Logger log;
private boolean running;
public DeadTimerThread(BGP4Session p, int d) {
this.deadTimer = d;
this.bgp4Session = p;
log=LoggerFactory.getLogger("BGP4Server");
}
public void run() {
running=true;
while (running) {
try {
sleep(deadTimer * 1000);
/*
* Time's over, close PCEP Session
*/
log.warn("DeadTimer OVER");
this.bgp4Session.close(/*ObjectParameters.REASON_DEADTIMER*/);
return;
} catch (InterruptedException e) {
//return;
if (running==false){
log.debug("Ending DeadTimerThread");
return;
}
else {
log.debug("Reseting Dead Timer");
}
} catch (Exception e) {
//FIXME: Ver que hacer aqui, por ahora, solo saco un log
log.warn("Unhandled exception: " + e.getMessage());
}
}
}
public void stopRunning(){
running=false;
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.bgp4session;
import es.tid.bgp.bgp4.messages.BGP4Keepalive;
import es.tid.bgp.bgp4.messages.BGP4Message;
import es.tid.bgp.bgp4.messages.BGP4MessageTypes;
import es.tid.bgp.bgp4.messages.BGP4Open;
import es.tid.bgp.bgp4.open.BGP4CapabilitiesOptionalParameter;
import es.tid.bgp.bgp4.open.BGP4OctetsASByteCapabilityAdvertisement;
import es.tid.bgp.bgp4.open.MultiprotocolExtensionCapabilityAdvertisement;
import es.tid.bgp.bgp4.update.fields.pathAttributes.AFICodes;
import es.tid.bgp.bgp4.update.fields.pathAttributes.SAFICodes;
import eu.teraflow.tid.bgp4Peer.peer.BGP4Exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.Socket;
import java.util.Timer;
/**
* Generic BGP4 Session.
* Implements the basics of a BGP4 Session
* Any particular session must inherit this one
*
* @author ogondio
*
*/
public abstract class GenericBGP4Session extends Thread implements BGP4Session {
/**
* PCEP Session Manager
*/
protected BGP4SessionsInformation BGP4SessionsInformation;
/**
* Thread to send periodic Keepalives
*/
protected KeepAliveThread keepAliveT = null;
/**
* Value of the Keepalive timer set by the Local PCE. Used to send keepalives
*/
protected int keepAliveLocal;
/**
* Value of the Keepalive timer of the peer PCC. It is not used in the server!!!
*/
protected int keepAlivePeer;
/**
* Thread to check if the connection is still alive.
* If in this time the PCE has not received anything, it closes the session
* It is set by the PCC (in this case, the remote peer)
*/
protected DeadTimerThread deadTimerT = null;
/**
* Value of the deadtimer that the PCC sends. It is used in the PCC in the thread
*/
protected int deadTimerPeer;
/**
* Socket of the communication between BGP peers
*/
protected Socket socket = null;
/**
* Remote Peer IP Address
* Obtained from the socket for convenience
*/
protected Inet4Address remotePeerIP=null;
/**
* DataOutputStream to send messages to the peer
*/
protected DataOutputStream out=null;
/**
* DataInputStream to receive messages from PCC
*/
protected DataInputStream in=null;//
/**
* Queue to send the Computing Path Requests
*/
//protected RequestQueueSend req;
/**
* Logger to write the Parent PCE server log
*/
protected Logger log;
/**
* Timer to schedule KeepWait and OpenWait Timers
*/
protected Timer timer;
/**
* Finite State Machine of the PCEP protocol
*/
protected int FSMstate;
/**
* Remote Domain ID
* null if not sent
*/
protected Inet4Address remoteDomainId=null;
/**
* Remote List of OF Codes
* If sent by the peer PCE
*/
//private LinkedList<Integer> remoteOfCodes;//FIME: What do we do with them?
/**
* RemoteOK: a boolean that is set to 1 if the system has received an
acceptable Open message.
*/
private boolean remoteOK=false;
/**
*
*/
private boolean localOK=false;
/**
*
*/
private int openRetry=0;
/**
* Byte array to store the last PCEP message read.
*/
protected byte[] msg = null;
/**
* Initial number of the session ID (internal use only)
*/
public static long sessionIdCounter=0;
/**
*
*/
protected Boolean updateFrom;
protected boolean sendTo;
/**
* Session ID (internal use only)
*/
private long sessionId;
/**************** PARAMETROS DE LA SESION ********************/
private int ConnectRetryCounter=0;
private ConnectRetryTimer connectRetryTimer = null;
private int connectRetryTime; //FIXME: esto aun no se que es.
/**************PARAMETROS OPEN MESSAGE************************/
protected int holdTime;
/**
* Time between sending keepalives
*/
protected int keepAliveTimer;
/**
* IP address that is assigned to that BGP speaker
*/
protected Inet4Address BGPIdentifier;
/**
* Autonomous System number of the sender
*/
protected int myAutonomousSystem;
/**
* version indicates the protocol version number of the message
* it must be 4
*/
protected int version;
public GenericBGP4Session(BGP4SessionsInformation bgp4SessionsInformation,int holdTime,Inet4Address BGPIdentifier,int version,int myAutonomousSystem,int mykeepAliveTimer) {
log=LoggerFactory.getLogger("BGP4Parser");
this.BGP4SessionsInformation=bgp4SessionsInformation;
this.holdTime=holdTime;
this.BGPIdentifier=BGPIdentifier;
this.version = version;
this.myAutonomousSystem=myAutonomousSystem;
this.keepAliveTimer = mykeepAliveTimer;
this.newSessionId();
}
/**
* Read PCE message from TCP stream
* @param in InputStream
* @return byte array with a BGP4 Message
* @throws IOException Execption thrown trying to read message
*/
protected byte[] readBGP4Msg(DataInputStream in) throws IOException{
byte[] ret = null;
byte[] hdr = new byte[BGP4Message.getBGPHeaderLength()];
byte[] temp = null;
boolean endHdr = false;
int r = 0;
int length = 0;
boolean endMsg = false;
int offset = 0;
while (!endMsg) {
try {
if (endHdr) {
r = in.read(temp, offset, 1);
}
else {
r = in.read(hdr, offset, 1);
}
} catch (IOException e){
log.warn("Error reading data: "+ e.getMessage());
throw e;
}catch (Exception e) {
log.warn("readMsg Oops: " + e.getMessage());
throw new IOException();
}
if (r > 0) {
if (offset == BGP4Message.getBGPMarkerLength()) {
length = ((int)hdr[offset]&0xFF) << 8;
}
if (offset == BGP4Message.getBGPMarkerLength() + 1) {
length = length | (((int)hdr[offset]&0xFF));
temp = new byte[length];
endHdr = true;
System.arraycopy(hdr, 0, temp, 0, BGP4Message.getBGPHeaderLength());
}
if ((length > 0) && (offset == length - 1)) {
endMsg = true;
}
offset++;
}
else if (r==-1){
log.debug("End of stream has been reached");
throw new IOException();
}
}
if (length > 0) {
ret = new byte[length];
System.arraycopy(temp, 0, ret, 0, length);
}
return ret;
}
/**
* Read PCE message from TCP stream
* @param in InputStream
* @return byte array with a BGP4 Message
* @throws IOException Execption thrown trying to read message
*/
protected byte[] readMsgOptimized(DataInputStream in) throws IOException{
byte[] ret = null;
byte[] hdr = new byte[4];
byte[] temp = null;
boolean endHdr = false;
int r = 0;
int length = 0;
boolean endMsg = false;
int offset = 0;
while (!endMsg) {
try {
if (endHdr) {
//log.info("Vamos a leer datos ");
r = in.read(temp, offset, length-offset);
if (r>0){
if ((offset+r)>=length){
//log.info("Bien ");
endMsg=true;
}else {
offset=offset+r;
}
}
else if (r<0){
log.error("End of stream has been reached reading data");
throw new IOException();
}
}
else {
//log.info("Vamos a leer la cabecera ");
r = in.read(hdr, offset, 4-offset);
if (r < 0) {
log.error("End of stream has been reached reading header");
throw new IOException();
}else if (r >0){
if ((offset+r)>=4){
length = ( (hdr[offset+2]&0xFF) << 8) | ((hdr[offset+3]&0xFF));
offset=4;
temp = new byte[length];
endHdr = true;
System.arraycopy(hdr, 0, temp, 0, 4);
if (length==4){
endMsg=true;
}
}else {
offset=offset+r;
}
}
}
} catch (IOException e){
log.error("Error reading data: "+ e.getMessage());
throw e;
}catch (Exception e) {
log.error("readMsg Oops: " + e.getMessage());
log.error("Failure reason : "+e.getStackTrace());
throw new IOException();
}
}
if (length > 0) {
ret = new byte[length];
System.arraycopy(temp, 0, ret, 0, length);
}
return ret;
}
// /**
// * <p>Close the PCE session</p>
// * <p>List of reasons (RFC 5440):</p>
// * Value Meaning
// 1 No explanation provided
// 2 DeadTimer expired
// 3 Reception of a malformed PCEP message
// 4 Reception of an unacceptable number of unknown
// requests/replies
// 5 Reception of an unacceptable number of unrecognized
// PCEP messages
// * @param reason Reason for closing the PCEP Session
// * @return PCEP Session closed OK
// */
// public void close(int reason){
// log.info("Closing PCEP Session");
// BGP4Close p_close=new BGP4Close();
// p_close.setReason(reason);
// sendPCEPMessage(p_close);
// killSession();
// }
public DataOutputStream getOut() {
return out;
}
public void setOut(DataOutputStream out) {
this.out = out;
}
/**
* Starts the deadTimerThread
*/
protected void startDeadTimer() {
this.deadTimerT.start();
}
/**
* Resets the DeadTimerThread
* To be called every time a message in the session is received
*/
protected void resetDeadTimer() {
if (this.deadTimerT != null) {
this.deadTimerT.interrupt();
}
}
public Socket getSocket() {
return socket;
}
/**
* Ends the DeadTimer Thread
*/
protected void cancelDeadTimer() {
log.debug("Cancelling DeadTimer");
if (this.deadTimerT != null) {
this.deadTimerT.stopRunning();
this.deadTimerT.interrupt();
this.deadTimerT=null;
}
}
/**
* Starts the Keep Alive Thread
*/
public void startKeepAlive() {
this.keepAliveT.start();
}
/**
* Ends the KeepAlive Thread
*/
public void cancelKeepAlive() {
log.debug("Cancelling KeepAliveTimer");
if (this.keepAliveT != null) {
this.keepAliveT.stopRunning();
this.keepAliveT.interrupt();
this.keepAliveT=null;
}
}
/**
* Ends current connections
*/
protected void endConnections(){
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (this.socket != null) {
log.warn("Closing socket");
this.socket.close();
}
} catch (Exception e) {
log.warn("Error closing connections: " + e.getMessage());
}
}
public int getFSMstate() {
return FSMstate;
}
protected void setFSMstate(int fSMstate) {
FSMstate = fSMstate;
}
public void killSession(){
log.warn("Killing Session");
timer.cancel();
this.endConnections();
this.cancelDeadTimer();
this.cancelKeepAlive();
this.endSession();
this.BGP4SessionsInformation.deleteSession(this.sessionId);
log.warn("Interrupting thread!!!!");
this.interrupt();
}
/**
* DO HERE ANYTHING NEEDED AT CLOSING??
* STATISTICS, ETC
*/
protected abstract void endSession();
protected void initializeBGP4Session() throws BGP4Exception {
this.BGP4SessionsInformation.addSession(this.getSessionId(), this);
/**
* Byte array to store the last PCEP message read.
*/
byte[] msg = null;
//First get the input and output stream
try {
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
} catch (IOException e) {
log.warn("Problem in the sockets, ending BGP4Session");
killSession();
return;
}
//- Starts the ConnectRetryTimer with initial value
int initialValue=1000;//FIXME: no tengo ni idea de este parametro aun
connectRetryTimer= new ConnectRetryTimer(initialValue) ;
//STARTING PCEP SESSION ESTABLISHMENT PHASE
//It begins in Open Wait State
this.setFSMstate(BGP4StateSession.BGP4_STATE_OPEN_WAIT);
log.debug("Entering BGP4_STATE_OPEN_WAIT, Scheduling Open Wait Timer");
//Create the 60 seconds Open Wait Timer to wait for an OPEN message
OpenWaitTimerTask owtt= new OpenWaitTimerTask(this);
this.timer.schedule(owtt, 60000);
//Define (Not use yet), the keepwait timer
KeepWaitTimerTask kwtt=new KeepWaitTimerTask(this);
BGP4Open open_msg=new BGP4Open();
//Rellenar:
// - My autonomous system
// - holdTime
// - BGPIdentifier
open_msg.setMyAutonomousSystem(myAutonomousSystem);
open_msg.setBGPIdentifier(BGPIdentifier);
open_msg.setHoldTime(holdTime);
//Chek optional parameters
BGP4CapabilitiesOptionalParameter cop = new BGP4CapabilitiesOptionalParameter();
open_msg.getParametersList().add(cop);
MultiprotocolExtensionCapabilityAdvertisement multProtExtCapAdv = new MultiprotocolExtensionCapabilityAdvertisement();
multProtExtCapAdv.setAFI(AFICodes.AFI_BGP_LS);
multProtExtCapAdv.setSAFI(SAFICodes.SAFI_BGP_LS);
cop.getCapabilityList().add(multProtExtCapAdv);
BGP4OctetsASByteCapabilityAdvertisement fouroctects = new BGP4OctetsASByteCapabilityAdvertisement();
fouroctects.setAS(myAutonomousSystem);
cop.getCapabilityList().add(fouroctects);
//Send the OPEN message
this.sendBGP4Message(open_msg);
//Now, read messages until we are in SESSION UP
while (this.FSMstate!=BGP4StateSession.BGP4_STATE_SESSION_UP){
//log.info("State session "+this.FSMstate);
try {
//Read a new message
msg = readBGP4Msg(in);
}catch (IOException e){
log.warn("Error reading message, ending session"+e.getMessage());
killSession();
return;
}
if (msg != null) {//If null, it is not a valid PCEP message
//log.info("Read a message");
switch(BGP4Message.getMessageType(msg)) {
case BGP4MessageTypes.MESSAGE_OPEN:
//log.info("OPEN Message Received");
if (this.FSMstate==BGP4StateSession.BGP4_STATE_OPEN_WAIT){
log.debug("FSMstate = BGP4_STATE_OPEN_WAIT");
BGP4Open open_received;
// try {
open_received=new BGP4Open(msg);
log.debug("**** Open received ****\n"+ open_received.toString());//FIXME!!! Cambiar a finest
owtt.cancel();
//Check parameters
if (openRetry==1){
boolean checkOK=true;
this.version = open_received.getVersion();
if (this.version != 4){
checkOK=false;
}
// this.deadTimerPeer=open_received.getDeadTimer();
// this.keepAlivePeer=open_received.getKeepalive();
//
// if (this.deadTimerPeer>maxDeadTimerAccepted){
// checkOK=false;
// }
// if (this.deadTimerPeer==0){
// if(zeroDeadTimerAccepted==false){
// checkOK=false;
// }
// }
// if (this.keepAlivePeer<minimumKeepAliveTimerAccepted){
// checkOK=false;
// }
if (checkOK==false){
log.debug("Dont accept");
// PCEPError perror=new PCEPError();
// PCEPErrorObject perrorObject=new PCEPErrorObject();
// perrorObject.setErrorType(ObjectParameters.ERROR_ESTABLISHMENT);
// perrorObject.setErrorValue(ObjectParameters.ERROR_ESTABLISHMENT_SECOND_OPEN_MESSAGE_UNACCEPTABLE_SESSION_CHARACTERISTICS);
// ErrorConstruct error_c=new ErrorConstruct();
// error_c.getErrorObjList().add(perrorObject);
// perror.setError(error_c);
// log.info("Sending Error and ending PCEPSession");
// sendPCEPMessage(perror);
}
else {
/**
* If no errors are detected, and the session characteristics are
* acceptable to the local system, the system:
o Sends a Keepalive message to the PCEP peer,
o Starts the Keepalive timer,
o Sets the RemoteOK variable to 1.
If LocalOK=1, the system clears the OpenWait timer and moves to the
UP state.
If LocalOK=0, the system clears the OpenWait timer, starts the
KeepWait timer, and moves to the KeepWait state.
*/
this.BGPIdentifier=open_received.getBGPIdentifier();
this.myAutonomousSystem=open_received.getMyAutonomousSystem();
this.holdTime=open_received.getHoldTime();
// if (open_received.getOptionalParameterLength() != 0){
// log.info("Tiene parametros opcionales");
// }
log.debug("OPEN Accepted");
log.debug("Sending KA to confirm");
BGP4Keepalive ka_snd= new BGP4Keepalive();
log.debug("Sending Keepalive message");
sendBGP4Message(ka_snd); //Creates the Keep Wait Timer to wait for a KA to acknowledge the OPEN sent
//FIXME: START KA TIMER!
this.remoteOK=true;
if(this.localOK==true){
log.debug("Entering STATE_SESSION_UP");
this.setFSMstate(BGP4StateSession.BGP4_STATE_SESSION_UP);
}
else {
log.debug("Entering STATE_KEEP_WAIT");
log.debug("Scheduling KeepwaitTimer");
timer.schedule(kwtt, 60000);
this.setFSMstate(BGP4StateSession.BGP4_STATE_KEEP_WAIT);
}
}
}
else {//Open retry is 0
log.debug("Open retry is equal to 0");
boolean dtOK=true;
// boolean kaOK=true;
this.version=open_received.getVersion();
if (this.version != 4){
dtOK=false;
}
if (dtOK==false){
///Parameters are unacceptable but negotiable
log.debug("PEER Open parameters are unaccpetable, but negotiable");
// PCEPError perror=new PCEPError();
// PCEPErrorObject perrorObject=new PCEPErrorObject();
// perrorObject.setErrorType(ObjectParameters.ERROR_ESTABLISHMENT);
// perrorObject.setErrorValue(ObjectParameters.ERROR_ESTABLISHMENT_UNACCEPTABLE_NEGOTIABLE_SESSION_CHARACTERISTICS);
// if (dtOK==false){
// open_received.setDeadTimer(this.deadTimerLocal);
// }
// if (kaOK==false) {
// open_received.setKeepalive(this.keepAliveLocal);
// }
// LinkedList<PCEPErrorObject> perrobjlist=new LinkedList<PCEPErrorObject>();
// perrobjlist.add(perrorObject);
// perror.setErrorObjList(perrobjlist);
// perror.setOpen(open_received.getOpen());
// log.info("Sending Error with new proposal");
// this.sendPCEPMessage(perror);
// this.openRetry=this.openRetry+1;
/**
* o If LocalOK=1, the system restarts the OpenWait timer and stays in
the OpenWait state.
o If LocalOK=0, the system clears the OpenWait timer, starts the
KeepWait timer, and moves to the KeepWait state.
*/
if (localOK==true){
//log.info("Local ok esta a true, vamos a open wait");
owtt.cancel();
owtt= new OpenWaitTimerTask(this);
this.timer.schedule(owtt, 60000);
this.setFSMstate(BGP4StateSession.BGP4_STATE_OPEN_WAIT);
}
else {
//log.info("Local ok esta a false, vamos a keep wait");
owtt.cancel();
this.setFSMstate(BGP4StateSession.BGP4_STATE_KEEP_WAIT);
this.timer.schedule(kwtt, 60000);
}
}
else {
/*
* If no errors are detected, and the session characteristics are
acceptable to the local system, the system:
o Sends a Keepalive message to the PCEP peer,
o Starts the Keepalive timer,
o Sets the RemoteOK variable to 1.
If LocalOK=1, the system clears the OpenWait timer and moves to the
UP state.
If LocalOK=0, the system clears the OpenWait timer, starts the
KeepWait timer, and moves to the KeepWait state.
*/
this.BGPIdentifier=open_received.getBGPIdentifier();
this.myAutonomousSystem=open_received.getMyAutonomousSystem();
this.holdTime=open_received.getHoldTime();
// if (open_received.getOptionalParameterLength() != 0){
// log.info("Tiene parametros opcionales");
// }
//this.BGP4SessionsInformation.addSession(this.getSessionId(), this);
BGP4Keepalive p_ka= new BGP4Keepalive();
//log.info("Sending Keepalive message");
sendBGP4Message(p_ka); //Creates the Keep Wait Timer to wait for a KA to acknowledge the OPEN sent
//FIXME: START KA TIMER!
this.remoteOK=true;
if(this.localOK==true){
//log.info("Entering STATE_SESSION_UP");
//He conseguido establecer sesion. Hay que matar el otro hilo
this.setFSMstate(BGP4StateSession.BGP4_STATE_SESSION_UP);
//La sesion se ha establecido
}
else {
//log.info("Entering STATE_KEEP_WAIT");
//log.fine("Scheduling KeepwaitTimer");
timer.schedule(kwtt, 60000);
this.setFSMstate(BGP4StateSession.BGP4_STATE_KEEP_WAIT);
}
}
}
}
else{
log.debug("Ignore OPEN message, already one received!!");
}
break;
case BGP4MessageTypes.MESSAGE_KEEPALIVE:
//log.info("KeepAlive Message Received");
this.localOK=true;
if(this.FSMstate==BGP4StateSession.BGP4_STATE_KEEP_WAIT){
// If RemoteOK=1, the system clears the KeepWait timer and moves to
// the UP state.
// If RemoteOK=0, the system clears the KeepWait timer, starts the
// OpenWait timer, and moves to the OpenWait State.
if (remoteOK==true){
kwtt.cancel();
//log.info("Entering STATE_SESSION_UP");
this.setFSMstate(BGP4StateSession.BGP4_STATE_SESSION_UP);
}
else{
kwtt.cancel();
//log.info("Entering OPEN WAIT STATE");
owtt=new OpenWaitTimerTask(this);
this.timer.schedule(owtt, 60000);
this.setFSMstate(BGP4StateSession.BGP4_STATE_OPEN_WAIT);
}
}
//If not... seguimos igual que estabamos
//Mas KA no hacen mal...
break;
default:
log.error("UNEXPECTED Message Received");
if (this.FSMstate!=BGP4StateSession.BGP4_STATE_OPEN_WAIT){
log.debug("Ignore OPEN message, already one received!!");
}
else {
log.error("Unexpected message RECEIVED, closing");
}
break;
}
}
else {
if (this.FSMstate!=BGP4StateSession.BGP4_STATE_OPEN_WAIT){
log.info("Ignore message, already one received!!");
}
else {
log.error("Unexpected message RECEIVED, closing");
}
}//Fin del else
}//Fin del WHILE
}
@Override
public void sendBGP4Message(BGP4Message message) {
message.encode();
try {
out.write(message.getBytes());
out.flush();
} catch (Exception e) {
log.error("Problem writing message, finishing session "+e.getMessage());
killSession();
}
}
public Inet4Address getRemotePeerIP() {
return remotePeerIP;
}
public Inet4Address getBGPIdentifier() {
return BGPIdentifier;
}
public void setBGPIdentifier(Inet4Address bGPIdentifier) {
BGPIdentifier = bGPIdentifier;
}
public Boolean getUpdateFrom() {
return updateFrom;
}
public void setUpdateFrom(Boolean updateFrom) {
this.updateFrom = updateFrom;
}
public Boolean getSendTo(){
return sendTo;
}
public void setSendTo(boolean sendTo) {
this.sendTo = sendTo;
}
public int getMyAutonomousSystem() {
return myAutonomousSystem;
}
public void setMyAutonomousSystem(int myAutonomousSystem) {
this.myAutonomousSystem = myAutonomousSystem;
}
public String shortInfo(){
StringBuffer sb=new StringBuffer(1000);
if (this.socket!=null){
sb.append("remAddr: ");
sb.append(this.socket.getRemoteSocketAddress());
sb.append(" state: ");
if (this.FSMstate==BGP4StateSession.BGP4_STATE_OPEN_WAIT){
sb.append("OPEN_WAIT");
}else if (this.FSMstate==BGP4StateSession.BGP4_STATE_IDLE){
sb.append("IDLE");
}else if (this.FSMstate==BGP4StateSession.BGP4_STATE_KEEP_WAIT){
sb.append("KEEP_WAIT");
}else if (this.FSMstate==BGP4StateSession.BGP4_STATE_SESSION_UP){
sb.append("SESSION_UP");
}else if (this.FSMstate==BGP4StateSession.BGP4_STATE_SESSION_UP){
sb.append("TCP_PENDING");
}else {
sb.append("UNKNOWN");
}
}
return sb.toString();
}
public String toString(){
StringBuffer sb=new StringBuffer(1000);
sb.append("\t> Session ID: "+this.sessionId+"\n");
sb.append("\t> BGP Remote Peer: "+this.remotePeerIP+"\n");
sb.append("\t> BGPIdentifier: "+this.BGPIdentifier+"\n");
if (this.socket!=null){
sb.append("\t> remAddr: ");
sb.append(this.socket.getRemoteSocketAddress()+"\n");
sb.append("\t> state: ");
if (this.FSMstate==BGP4StateSession.BGP4_STATE_OPEN_WAIT){
sb.append("OPEN_WAIT\n");
}else if (this.FSMstate==BGP4StateSession.BGP4_STATE_IDLE){
sb.append("IDLE\n");
}else if (this.FSMstate==BGP4StateSession.BGP4_STATE_KEEP_WAIT){
sb.append("KEEP_WAIT\n");
}else if (this.FSMstate==BGP4StateSession.BGP4_STATE_SESSION_UP){
sb.append("SESSION_UP\n");
}else if (this.FSMstate==BGP4StateSession.BGP4_STATE_SESSION_UP){
sb.append("TCP_PENDING\n");
}else {
sb.append("UNKNOWN");
}
}
return sb.toString();
}
public synchronized void newSessionId(){
this.sessionId=GenericBGP4Session.sessionIdCounter+1;
sessionIdCounter=sessionIdCounter+1;
}
public long getSessionId() {
return sessionId;
}
@Override
public void close() {
// TODO Auto-generated method stub
}
@Override
public boolean equals(Object obj) {
if (remotePeerIP != null){
if (this.remotePeerIP.equals(((GenericBGP4Session)obj).getBGPIdentifier())){
return true;
}
}
else {
log.info("TODO NUL!! en el equals!");
}
return false;
}
public Inet4Address getPeerIP(){
return (Inet4Address)this.socket.getInetAddress();
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.bgp4session;
import es.tid.bgp.bgp4.messages.BGP4Keepalive;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.DataOutputStream;
import java.io.IOException;
public class KeepAliveThread extends Thread {
private int keepAlive = 0;
private boolean running;
private Logger log;
private DataOutputStream out=null; //Use this to send messages to peer
/*
* @param p
* @param k
*/
public KeepAliveThread(DataOutputStream out, int k) {
this.keepAlive = k;
this.out = out;
log=LoggerFactory.getLogger("BGP4Server");
}
/**
* Starts the Keepalive process
*/
public void run() {
running=true;
while (running) {
try {
if (keepAlive > 0) {
sleep(keepAlive * 1000);
sendKeepAlive();
}
else {
log.debug("Ending KEEPALIVE mechanism");
return;
}
} catch (InterruptedException e) {
if (running==false){
log.debug("Ending KeepAliveThread");
return;
}
else {
//Keepalive Timer is reseted
log.debug("Reseting Keepalive timer");
}
}
}
}
/**
* Sets the running variable to false. After this, an interrupt will cause
* the KeepaliveThread to end.
*/
public void stopRunning(){
running=false;
}
/**
* Sends KeepAlive Message. It does not wait for any response.
*/
private void sendKeepAlive() {
BGP4Keepalive p_ka= new BGP4Keepalive();
//try {
p_ka.encode();
// } catch (PCEPProtocolViolationException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
try {
log.debug("Sending Keepalive message");
out.write(p_ka.getBytes());
out.flush();
} catch (IOException e) {
log.warn("Error sending KEEPALIVE: " + e.getMessage());
}
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.bgp4session;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* If no Open message is received before the expiration of the OpenWait
timer, the PCEP peer sends a PCErr message with Error-Type=1 and
Error-value=2, the system releases the PCEP resources for the PCEP
peer, closes the TCP connection, and moves to the Idle state.
* @author Oscar Gonzalez de Dios
*
*/
public class KeepWaitTimerTask extends TimerTask {
// private DataOutputStream out=null; //Use this to send messages to peer
private BGP4Session bgp4Session;
private Logger log;
public KeepWaitTimerTask(BGP4Session bgp4Session){
this.bgp4Session=bgp4Session;
log=LoggerFactory.getLogger("PCEServer");
}
public void run() {
log.warn("KEEP WAIT Timer OVER");
// PCEPError perror=new PCEPError();
// PCEPErrorObject perrorObject=new PCEPErrorObject();
// perrorObject.setErrorType(ObjectParameters.ERROR_ESTABLISHMENT);
// perrorObject.setErrorValue(ObjectParameters.ERROR_ESTABLISHMENT_NO_KA_OR_ERROR_KEEPWAIT_TIMER);
// ErrorConstruct error_c=new ErrorConstruct();
// error_c.getErrorObjList().add(perrorObject);
// perror.setError(error_c);
// bgp4Session.sendBGP4Message(perror);
this.bgp4Session.killSession();
return;
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.bgp4session;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* If no Open message is received before the expiration of the OpenWait
timer, the PCEP peer sends a PCErr message with Error-Type=1 and
Error-value=2, the system releases the PCEP resources for the PCEP
peer, closes the TCP connection, and moves to the Idle state.
* @author Oscar Gonzalez de Dios
*
*/
public class OpenWaitTimerTask extends TimerTask {
// private DataOutputStream out=null; //Use this to send messages to peer
private BGP4Session bgp4Session;
private Logger log;
public OpenWaitTimerTask(BGP4Session bgp4Session){
this.bgp4Session=bgp4Session;
log=LoggerFactory.getLogger("PCEServer");
}
public void run() {
log.warn("OPEN WAIT Timer OVER");
// PCEPError perror=new PCEPError();
// PCEPErrorObject perrorObject=new PCEPErrorObject();
// perrorObject.setErrorType(ObjectParameters.ERROR_ESTABLISHMENT);
// perrorObject.setErrorValue(ObjectParameters.ERROR_ESTABLISHMENT_NO_OPEN_MESSAGE);
// ErrorConstruct error_c=new ErrorConstruct();
// error_c.getErrorObjList().add(perrorObject);
// perror.setError(error_c);
// log.info("Sending Error");
// bgp4Session.sendPCEPMessage(perror);
this.bgp4Session.killSession();
return;
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.grpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;
public class grpcApp {
public static void main( String[] args ) throws Exception
{
// Create a new server to listen on port 8080
Server server = ServerBuilder.forPort(2021)
.addService(new updateServiceImpl())
.build();
// Start the server
server.start();
// Server threads are running in the background.
System.out.println("Server started");
// Don't exit the main thread. Wait until server is terminated.
server.awaitTermination();
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.grpc;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.google.common.net.InetAddresses;
import eu.teraflow.tid.bgp4Peer.models.LinkNLRIMsg;
import eu.teraflow.tid.bgp4Peer.models.NodeNLRIMsg;
import eu.teraflow.tid.bgp4Peer.models.UpdateMsg;
import eu.teraflow.tid.bgp4Peer.models.UpdateMsgList;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;
import jdk.javadoc.internal.doclets.toolkit.util.links.LinkInfo;
import src.main.proto.GrpcService.linkInfo;
import src.main.proto.GrpcService.nodeInfo;
import src.main.proto.GrpcService.NodeDescriptors;
import src.main.proto.GrpcService.updateRequest;
import src.main.proto.GrpcService.updateResponse;
import src.main.proto.updateServiceGrpc;
import src.main.proto.updateServiceGrpc.updateServiceBlockingStub;
import src.main.proto.updateServiceGrpc.updateServiceStub;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
public class grpcClient {
private static final Logger logger = Logger.getLogger(grpcClient.class.getName());
public static void sendGrpcUpdateMsg(UpdateMsg update) throws Exception{
updateRequest request=null;
nodeInfo n=null;
linkInfo unic=null;
List <linkInfo> l = new ArrayList<>();
List <nodeInfo> nodes = new ArrayList<>();
if(update.nodeCheck()==false && update.linkCheck()==false){
return;
}
// Build node for grpc message
if(update.nodeCheck()!=false) {
for(NodeNLRIMsg node : update.getNodeList()){
n = nodeInfo.newBuilder().setNodeName(node.getNodeName()).
setIgpID(node.getRouterID()).
setBgplsID(node.getLocalBgplsID()).
setAsID(InetAddresses.coerceToInteger(node.getAs_number())).
setLearntFrom(node.getLearntFrom()).
buildPartial();
nodes.add(n);
}
}
for(LinkNLRIMsg link : update.getLinkList()) {
// String strIPlocal;
// String strIPremote;
String strIgpR;
String strIgpL;
// LinkNLRIMsg link=update.getLink();
// if(link.getiPv4RouterIDLocalNodeLATLV()==null)
// strIPlocal="-";
// else {
// strIPlocal=link.getiPv4RouterIDLocalNodeLATLV();
// }
// if(link.getiPv4RouterIDNeighborNodeLATLV()==null)
// strIPremote="-";
// else {
// strIPremote=link.getiPv4RouterIDNeighborNodeLATLV();
// }
if(link.getRemoteNodeIGPId()==null)
strIgpR="-";
else {
strIgpR=link.getRemoteNodeIGPId().toString();
}
if(link.getLocalNodeIGPId()==null)
strIgpL="-";
else {
strIgpL=link.getLocalNodeIGPId().toString();
}
String ipv4R;
if(link.getiPv4RouterIDLocalNodeLATLV()==null)
ipv4R="-";
else {
ipv4R=link.getiPv4RouterIDLocalNodeLATLV();
}
String ipv4L;
if(link.getiPv4RouterIDNeighborNodeLATLV()==null)
ipv4L="-";
else {
ipv4L=link.getiPv4RouterIDNeighborNodeLATLV();
}
// Build link for grpc message. need non null values in some cases
unic = linkInfo.newBuilder().setLocalID(strIgpR).
setLocalIPv4ID(ipv4L).
setRemoteID(strIgpL).
setRemoteIPv4ID(ipv4R).
setLocal(NodeDescriptors.newBuilder().
setAsNumber(link.getLocalDomainID().toString()).
setBgplsID(link.getLocalBgplsID())).
setRemote(NodeDescriptors.newBuilder().
setAsNumber(link.getRemoteDomainID().toString()).
setBgplsID(link.getRemoteBgplsID())).
setAvailableBw(link.getAvailableBw()).
setResidualBw(link.getResidualBw()).setUtilized(link.getUtilizedBw()).
setMinLinkDelay(link.getMinDelay()).setMaxLinkDelay(link.getMaxDelay()).
setDelayVariation(link.getLinkDelayVar()).setDelay(link.getLinkDelay()).
setTEDefaultMetric(1).setAdjacencySid("0").setLearntFrom(link.getLearntFrom()).buildPartial();
l.add(unic);
}
if(nodes.size()==0 && l.size()>0) {
request=updateRequest.newBuilder().
setNextHop(update.getNextHop().toString()).
setAddressFamilyID(Integer.toString(update.getAFI())).
setAsPathSegment(Integer.toString(update.getAsPathSegment())).
addAllLink(l).build();
}else if(nodes.size()>0&& l.size()==0) {
// logger.debug("ADDING NODE");
request=updateRequest.newBuilder().
setNextHop(update.getNextHop().toString()).
setAddressFamilyID(Integer.toString(update.getAFI())).
setAsPathSegment(Integer.toString(update.getAsPathSegment())).
addAllNode(nodes).build();
}else {
//Error if node name is null
// TODO: handle seng grpc error?
// logger.debug("ADDING NODE AND LINK");
request=updateRequest.newBuilder().
setNextHop("-"+update.getNextHop().toString()).
setAddressFamilyID(Integer.toString(update.getAFI())).
setAsPathSegment(Integer.toString(update.getAsPathSegment())).
addAllNode(nodes).addAllLink(l).build();
}
final ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost",2021).usePlaintext().build();
updateServiceBlockingStub stub = updateServiceGrpc.newBlockingStub(channel);
//TODO: this to a function
System.out.println("grpcClient request: "+request.toString());
// channel.awaitTermination(20, TimeUnit.SECONDS);
// updateResponse response = stub.update(request);
// Espera hasta que el canal esté inactivo
updateResponse response = stub.update(request);
System.out.println("\nRESPUESTA RECIBIDA");
System.out.println(response);
}
// private void shutdownManagedChannel(ManagedChannel managedChannel) {
// managedChannel.shutdown();
// try {
// managedChannel.awaitTermination(mChannelShutdownTimeoutMs, TimeUnit.MILLISECONDS);
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// // Allow thread to exit.
// } finally {
// managedChannel.shutdownNow();
// }
// Verify.verify(managedChannel.isShutdown());
// }
// stub.update(request, new StreamObserver <updateResponse>() {
// public void onNext(updateResponse response) {
// System.out.println("respuesta del server: "+response);
// }
// public void onError(Throwable t) {
// System.out.println("error: "+t.getMessage());
// latch.countDown();
// }
// public void onCompleted() {
// // Typically you'll shutdown the channel somewhere else.
// // But for the purpose of the lab, we are only making a single
// // request. We'll shutdown as soon as this request is done.
// latch.countDown();
// logger.info("gRPC call completed");
// System.out.println("OnCompleted");
// // channel.shutdownNow();
// // try{
// // channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
// // }catch (InterruptedException e){
// // System.out.println("channel error"+e.toString());
// // }
// }
// });
// latch.await(5, TimeUnit.SECONDS);
// channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
public static void sendGrpc(UpdateMsgList update) {
//construir mensaje
//update get node,lin,path
//getname,ids,as
final ManagedChannel channel = ManagedChannelBuilder.forTarget("localhost:2021").usePlaintext().build();
updateServiceStub stub = updateServiceGrpc.newStub(channel);
if(update.getNodeList().isEmpty()&&update.getLinkList().isEmpty()) {
return;
}
updateRequest request=null;
nodeInfo n=null;
linkInfo l=null;
if(!update.getNodeList().isEmpty()) {
for(NodeNLRIMsg node: update.getNodeList()) {
n = nodeInfo.newBuilder().setNodeName(node.getNodeName()).setIgpID(node.getLocalBgplsID()).
setBgplsID(node.getBgplsID().toString()).setAsID(InetAddresses.coerceToInteger(node.getAs_number())).
buildPartial();
}
}
if(!update.getLinkList().isEmpty()) {
String strIPlocal;
String strIPremote;
String strIgpR;
String strIgpL;
for(LinkNLRIMsg link: update.getLinkList()) {
if(link.getiPv4RouterIDLocalNodeLATLV()==null)
strIPlocal="-";
else {
strIPlocal=link.getiPv4RouterIDLocalNodeLATLV();
}
if(link.getiPv4RouterIDNeighborNodeLATLV()==null)
strIPremote="-";
else {
strIPremote=link.getiPv4RouterIDNeighborNodeLATLV();
}
if(link.getRemoteNodeIGPId()==null)
strIgpR="-";
else {
strIgpR=link.getRemoteNodeIGPId().toString();
}
if(link.getLocalNodeIGPId()==null)
strIgpL="-";
else {
strIgpL=link.getLocalNodeIGPId().toString();
}
String ipv4R;
if(link.getiPv4RouterIDNeighborNodeLATLV()==null)
ipv4R="-";
else {
ipv4R=link.getiPv4RouterIDNeighborNodeLATLV();
}
String ipv4L;
if(link.getiPv4RouterIDLocalNodeLATLV()==null)
ipv4L="-";
else {
ipv4L=link.getiPv4RouterIDLocalNodeLATLV();
}
// NodeDescriptors local= NodeDescriptors.newBuilder().
// setAsNumber(link.getLocalDomainID().toString()).
// setBgplsID(link.getLocalBgplsID()).buildPartial();
l = linkInfo.newBuilder().setLocalID(strIgpR).
setLocalIPv4ID(ipv4L).
setRemoteID(strIgpL).
setRemoteIPv4ID(ipv4R).
setLocal(NodeDescriptors.newBuilder().
setAsNumber(link.getLocalDomainID().toString()).
setBgplsID(link.getLocalBgplsID())).
setRemote(NodeDescriptors.newBuilder().
setAsNumber(link.getRemoteDomainID().toString()).
setBgplsID(link.getRemoteBgplsID())).
setAvailableBw(link.getAvailableBw()).
setResidualBw(link.getResidualBw()).setUtilized(link.getUtilizedBw()).
setMinLinkDelay(link.getMinDelay()).setMaxLinkDelay(link.getMaxDelay()).
setDelayVariation(link.getLinkDelayVar()).setDelay(link.getLinkDelay()).
setTEDefaultMetric(1).setAdjacencySid("0").buildPartial();
}
}
if(n==null) {
request = updateRequest.newBuilder().addLink(l).build();
}else if(l==null) {
request = updateRequest.newBuilder().addNode(n).build();
}else {
request = updateRequest.newBuilder().addNode(n).addLink(l).build();
}
stub.update(request, new StreamObserver <updateResponse>() {
public void onNext(updateResponse response) {
System.out.println("respuesta del server: "+response);
}
public void onError(Throwable t) {
System.out.println("error: "+t.getMessage());
}
public void onCompleted() {
// Typically you'll shutdown the channel somewhere else.
// But for the purpose of the lab, we are only making a single
// request. We'll shutdown as soon as this request is done.
System.out.println("channel shutdown");
channel.shutdownNow();
}
});
}
public static void main( String[] args ) throws Exception
{
final ManagedChannel channel = ManagedChannelBuilder.forTarget("localhost:2021").usePlaintext().build();
// Replace the previous synchronous code with asynchronous code.
// This time use an async stub:
updateServiceStub stub = updateServiceGrpc.newStub(channel);
// Construct a request
int a = 123;
nodeInfo n = nodeInfo.newBuilder().setNodeName("router 3").setIgpID("1341234").buildPartial();
updateRequest request =
updateRequest.newBuilder().addNode(n).build();
// Make an Asynchronous call. Listen to responses w/ StreamObserver
stub.update(request, new StreamObserver <updateResponse>() {
public void onNext(updateResponse response) {
System.out.println("respuesta del server: "+response);
}
public void onError(Throwable t) {
System.out.println("error: "+t.getMessage());
}
public void onCompleted() {
// Typically you'll shutdown the channel somewhere else.
// But for the purpose of the lab, we are only making a single
// request. We'll shutdown as soon as this request is done.
System.out.println("channel shutdown");
channel.shutdownNow();
}
});
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.grpc;
import io.grpc.stub.StreamObserver;
import src.main.proto.GrpcService.updateRequest;
import src.main.proto.GrpcService.updateResponse;
import src.main.proto.updateServiceGrpc.updateServiceImplBase;
public class updateServiceImpl extends updateServiceImplBase{
public void update(updateRequest request, StreamObserver<updateResponse> responseObserver) {
System.out.println(request);
updateResponse response = updateResponse.newBuilder()
.setAck("Update procesado, " + request )
.build();
// Use responseObserver to send a single response back
responseObserver.onNext(response);
// When you are done, you must call onCompleted.
responseObserver.onCompleted();
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.json;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import eu.teraflow.tid.bgp4Peer.models.LinkNLRIMsg;
import eu.teraflow.tid.bgp4Peer.models.NodeNLRIMsg;
import eu.teraflow.tid.bgp4Peer.models.PathAttributeMsg;
import eu.teraflow.tid.bgp4Peer.models.UpdateMsg;
import eu.teraflow.tid.bgp4Peer.models.UpdateMsgList;
public class bgpMarshal {
ObjectMapper mapper = new ObjectMapper();
JsonGenerator g;
FileWriter fWriter;
public void bgpMarshaller() throws IOException{
mapper.setSerializationInclusion(Inclusion.NON_NULL);
mapper.setSerializationInclusion(Inclusion.NON_EMPTY);
// String jsonStr = mapper.writeValueAsString(node);
// mapper.writeValue(new File("target/node.json"), nodeList);
// System.out.println(jsonStr);
}
public void writeFile(UpdateMsgList update) throws JsonGenerationException, JsonMappingException, IOException {
g = mapper.getJsonFactory().createJsonGenerator(new File("node.json"), JsonEncoding.UTF8);
// update=update.id2Name();
mapper.writeValue(g, update);
String temp = mapper.writeValueAsString(update)+"\n";
// FileOutputStream fos = new FileOutputStream("target/update.json", true);
// fos.write(temp.getBytes());
// fos.close();
fWriter = new FileWriter("updateWriter.json");
// if(temp.length()>2)
fWriter.write(temp);
}
public void closeFile() throws IOException {
g.close();
fWriter.close();
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.management;
import eu.teraflow.tid.bgp4Peer.bgp4session.BGP4SessionsInformation;
import eu.teraflow.tid.bgp4Peer.peer.SendTopology;
import eu.teraflow.tid.tedb.MultiDomainTEDB;
import eu.teraflow.tid.tedb.TEDB;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.ServerSocket;
import java.util.Hashtable;
/**
* To manage the server
*
* @author mcs
*
*/
public class BGP4ManagementServer extends Thread {
private Logger log;
private int BGP4ManagementPort = 8888;
private BGP4SessionsInformation bgp4SessionsInformation;
/**
* Topology database for interDomain Links.
*/
private MultiDomainTEDB multiTEDB;
/**
* Topology database for intradomain Links. It owns several domains.
*/
private Hashtable<String,TEDB> intraTEDBs;
/**
* Class to send the topology. It is needes to set the parameters sendTopology to true or false.
*/
private SendTopology sendTopology;
public BGP4ManagementServer(int BGP4ManagementPort, MultiDomainTEDB multiTEDB, Hashtable<String,TEDB> intraTEDBs, BGP4SessionsInformation bgp4SessionsInformation, SendTopology sendTopology){
log =LoggerFactory.getLogger("BGP4Server");
this.BGP4ManagementPort = BGP4ManagementPort;
this.multiTEDB=multiTEDB;
this.intraTEDBs=intraTEDBs;
this.bgp4SessionsInformation =bgp4SessionsInformation;
this.sendTopology=sendTopology;
}
/**
* RUN
*/
public void run(){
ServerSocket serverSocket = null;
boolean listening=true;
try {
log.debug("Listening management on port "+BGP4ManagementPort);
serverSocket = new ServerSocket(BGP4ManagementPort);
}
catch (Exception e){
log.error("Could not listen management on port "+BGP4ManagementPort);
e.printStackTrace();
return;
}
try {
while (listening) {
new BGP4ManagementSession(serverSocket.accept(),multiTEDB,intraTEDBs,bgp4SessionsInformation, sendTopology).start();
}
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.management;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Inet4Address;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Hashtable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.teraflow.tid.bgp4Peer.bgp4session.BGP4SessionsInformation;
import eu.teraflow.tid.bgp4Peer.peer.SendTopology;
import eu.teraflow.tid.bgp4Peer.tedb.IntraTEDBS;
import eu.teraflow.tid.tedb.DomainTEDB;
import eu.teraflow.tid.tedb.MultiDomainTEDB;
import eu.teraflow.tid.tedb.SimpleTEDB;
import eu.teraflow.tid.tedb.TEDB;
/**
*
* @author mcs
*
*/
public class BGP4ManagementSession extends Thread {
/**
* The socket of the management session
*/
private Socket socket;
/**
* Logger
*/
private Logger log;
/**
* Output Stream of the managament session, to write the answers.
*/
private PrintStream out;
/**
* Topology database for interDomain Links.
*/
private MultiDomainTEDB multiTEDB;
/**
* Topology database for intradomain Links. It owns several domains.
*/
private Hashtable<String,TEDB> intraTEDBs;
/**
* The infomation of all the active sessions
*/
private BGP4SessionsInformation bgp4SessionsInformation;
/**
* Class to send the topology. It is needes to set the parameters sendTopology to true or false.
*/
private SendTopology sendTopology;
public BGP4ManagementSession(Socket s,MultiDomainTEDB multiTEDB, Hashtable<String,TEDB> intraTEDBs,BGP4SessionsInformation bgp4SessionsInformation, SendTopology sendTopology){
this.socket=s;
log=LoggerFactory.getLogger("BGP4Server");
this.multiTEDB=multiTEDB;
this.intraTEDBs=intraTEDBs;
this.bgp4SessionsInformation= bgp4SessionsInformation;
this.sendTopology=sendTopology;
}
public void run(){
log.info("Starting Management session");
boolean running=true;
try {
out=new PrintStream(socket.getOutputStream());
} catch (IOException e) {
log.warn("Management session cancelled: "+e.getMessage());
return;
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (running) {
//out.print("BGP4:>");
out.print("Available commands:\r\n");
out.print(" > show topology\r\n");
out.print(" > show sessions\r\n");
out.print(" > set traces on\r\n");
out.print(" > set traces off\r\n");
out.print(" > send topology on\r\n");
out.print(" > send topology off\r\n");
out.print(" > quit\r\n");
String command = null;
try {
command = br.readLine();
} catch (IOException ioe) {
log.warn("IO error trying to read your command");
return;
}
if (command.equals("quit")) {
log.info("Ending Management Session");
out.println("bye!");
try {
out.close();
} catch (Exception e){
e.printStackTrace();
}
try {
br.close();
} catch (Exception e){
e.printStackTrace();
}
return;
}
// else if (command.equals("help")){
// out.print("Available commands:\r\n");
// out.print(" > show topology\r\n");
// out.print(" > show sessions\r\n");
// out.print(" > set traces on\r\n");
// out.print(" > set traces off\r\n");
// out.print(" > send topology on\r\n");
// out.print(" > send topology off\r\n");
// out.print(" > quit\r\n");
//
// }
else if (command.equals("show sessions")){
//Print intradomain and interDomain links
out.print(bgp4SessionsInformation.toString());
}
else if (command.equals("show topology")){
//Print intradomain and interDomain links
if (multiTEDB != null)
out.println(multiTEDB.printTopology());
Enumeration<String> domainTedbs=intraTEDBs.keys();
while (domainTedbs.hasMoreElements()){
String domainID=domainTedbs.nextElement();
TEDB ted=intraTEDBs.get(domainID);
if (ted instanceof DomainTEDB) {
out.println("Intradomain TEDB with ID "+domainID);
out.println(ted.printTopology());
}
}
}
else if (command.equals("set traces on")) {
//log.setLevel(Level.ALL);
Logger log2=LoggerFactory.getLogger("BGP4Parser");
//log2.setLevel(Level.ALL);
Logger log3=LoggerFactory.getLogger("BGP4Client");
//log3.setLevel(Level.ALL);
out.print("traces on!\r\n");
}
else if (command.equals("set traces off")) {
//log.setLevel(Level.SEVERE);
Logger log2=LoggerFactory.getLogger("BGP4Parser");
//log2.setLevel(Level.SEVERE);
Logger log3=LoggerFactory.getLogger("BGP4Client");
//log3.setLevel(Level.SEVERE);
out.print("traces off!\r\n");
}
else if (command.equals("send topology on")) {
sendTopology.setSendTopology(true);
}
else if (command.equals("send topology off")) {
sendTopology.setSendTopology(false);
}
else{
out.print("invalid command\n");
out.print("\n");
}
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.models;
import java.net.Inet4Address;
import java.util.ArrayList;
import org.slf4j.Logger;
import es.tid.bgp.bgp4.update.fields.LinkNLRI;
import es.tid.bgp.bgp4.update.tlv.node_link_prefix_descriptor_subTLVs.NodeDescriptorsSubTLV;
public class LinkNLRIMsg {
private ArrayList<NodeDescriptorsSubTLV> nodeDescriptorsSubTLV;
// Dominios
private Inet4Address localDomainID;
private Inet4Address remoteDomainID;
private Inet4Address areaID;
private Inet4Address bgplsID;
private Inet4Address LocalNodeIGPId;
private Inet4Address RemoteNodeIGPId;
private int linkDelay;
private int linkDelayVar;
private int minDelay;
private int maxDelay;
private int linkLoss;
private int residualBw;
private int availableBw;
private int utilizedBw;
private Inet4Address iPv4RouterIDLocalNodeLATLV;
private Inet4Address iPv4RouterIDNeighborNodeLATLV;
private int IGP_type;
private String localIGPID = null;
private String remoteIGPID = null;
private String localBgplsID;
private String remoteBgplsID;
private Logger log;
private String learntFrom;
public LinkNLRIMsg(LinkNLRI linkNLRI, String learntFrom) {
// LinkState vs Link??
this.learntFrom = learntFrom;
if (linkNLRI.getLocalNodeDescriptors().getAutonomousSystemSubTLV() != null) {
localDomainID = linkNLRI.getLocalNodeDescriptors().getAutonomousSystemSubTLV().getAS_ID();
}
if (linkNLRI.getLocalNodeDescriptors().getAreaID() != null) {
areaID = linkNLRI.getLocalNodeDescriptors().getAreaID().getAREA_ID();
}
if (linkNLRI.getLocalNodeDescriptors().getBGPLSIDSubTLV() != null) {
bgplsID = linkNLRI.getLocalNodeDescriptors().getBGPLSIDSubTLV().getBGPLS_ID();
}
if (linkNLRI.getLocalNodeDescriptors().getIGPRouterID() != null) {
LocalNodeIGPId = linkNLRI.getLocalNodeDescriptors().getIGPRouterID().getIpv4AddressOSPF();
}
if (linkNLRI.getRemoteNodeDescriptorsTLV().getAutonomousSystemSubTLV() != null) {
remoteDomainID = linkNLRI.getRemoteNodeDescriptorsTLV().getAutonomousSystemSubTLV().getAS_ID();
}
if (linkNLRI.getRemoteNodeDescriptorsTLV().getAreaID() != null) {
areaID = linkNLRI.getRemoteNodeDescriptorsTLV().getAreaID().getAREA_ID();
}
if (linkNLRI.getRemoteNodeDescriptorsTLV().getBGPLSIDSubTLV() != null) {
bgplsID = linkNLRI.getRemoteNodeDescriptorsTLV().getBGPLSIDSubTLV().getBGPLS_ID();
}
if (linkNLRI.getRemoteNodeDescriptorsTLV().getIGPRouterID() != null) {
RemoteNodeIGPId = linkNLRI.getRemoteNodeDescriptorsTLV().getIGPRouterID().getIpv4AddressOSPF();
}
if (linkNLRI.getUndirectionalLinkDelayTLV() != null) {
linkDelay = linkNLRI.getUndirectionalLinkDelayTLV().getDelay();
}
if (linkNLRI.getUndirectionalDelayVariationTLV() != null) {
linkDelayVar = linkNLRI.getUndirectionalDelayVariationTLV().getDelayVar();
}
if (linkNLRI.getMinMaxUndirectionalLinkDelayTLV() != null) {
maxDelay = linkNLRI.getMinMaxUndirectionalLinkDelayTLV().getHighDelay();
minDelay = linkNLRI.getMinMaxUndirectionalLinkDelayTLV().getLowDelay();
}
if (linkNLRI.getUndirectionalLinkLossTLV() != null) {
linkLoss = linkNLRI.getUndirectionalLinkLossTLV().getLinkLoss();
}
if (linkNLRI.getUndirectionalResidualBwTLV() != null) {
residualBw = linkNLRI.getUndirectionalResidualBwTLV().getResidualBw();
}
if (linkNLRI.getUndirectionalAvailableBwTLV() != null) {
availableBw = linkNLRI.getUndirectionalAvailableBwTLV().getAvailableBw();
}
if (linkNLRI.getUndirectionalUtilizedBwTLV() != null) {
utilizedBw = linkNLRI.getUndirectionalUtilizedBwTLV().getUtilizedBw();
}
if (linkNLRI.getIpv4InterfaceAddressTLV() != null) {
iPv4RouterIDLocalNodeLATLV = linkNLRI.getIpv4InterfaceAddressTLV().getIpv4Address();
}
if (linkNLRI.getIpv4NeighborAddressTLV() != null) {
iPv4RouterIDNeighborNodeLATLV = linkNLRI.getIpv4NeighborAddressTLV().getIpv4Address();
}
if (linkNLRI.getLocalNodeDescriptors().getBGPLSIDSubTLV().getBGPLS_ID() != null) {// alguna condicion?
localBgplsID = linkNLRI.getLocalNodeDescriptors().getBGPLSIDSubTLV().getBGPLS_ID().toString();
}
if (linkNLRI.getRemoteNodeDescriptorsTLV().getBGPLSIDSubTLV().getBGPLS_ID() != null) {// alguna condicion?
remoteBgplsID = linkNLRI.getRemoteNodeDescriptorsTLV().getBGPLSIDSubTLV().getBGPLS_ID().toString();
}
if (linkNLRI.getLocalNodeDescriptors().getIGPRouterID() != null) {
IGP_type = linkNLRI.getLocalNodeDescriptors().getIGPRouterID().getIGP_router_id_type();
switch (IGP_type) {
case 1:
localIGPID = Integer.toString(linkNLRI.getLocalNodeDescriptors().getIGPRouterID().getISIS_ISO_NODE_ID());
break;
case 2:
localIGPID = Integer.toString(linkNLRI.getLocalNodeDescriptors().getIGPRouterID().getISIS_ISO_NODE_ID());
break;
case 3:
localIGPID = linkNLRI.getLocalNodeDescriptors().getIGPRouterID().getIpv4AddressOSPF().toString();
break;
default:
log.info("añadir este tipo de IGP Identifier por implementar ");
}
}
if (linkNLRI.getRemoteNodeDescriptorsTLV().getIGPRouterID() != null) {
IGP_type = linkNLRI.getRemoteNodeDescriptorsTLV().getIGPRouterID().getIGP_router_id_type();
switch (IGP_type) {
case 1:
remoteBgplsID = Integer.toString(linkNLRI.getRemoteNodeDescriptorsTLV().getIGPRouterID().getISIS_ISO_NODE_ID());
break;
case 2:
remoteBgplsID = Integer.toString(linkNLRI.getRemoteNodeDescriptorsTLV().getIGPRouterID().getISIS_ISO_NODE_ID());
case 3:
remoteIGPID = linkNLRI.getRemoteNodeDescriptorsTLV().getIGPRouterID().getIpv4AddressOSPF().toString();
break;
default:
log.info("añadir este tipo de IGP Identifier por implementar ");
}
}
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + localBgplsID.hashCode();
result = 31 * result + iPv4RouterIDLocalNodeLATLV.hashCode();
result = 31 * result + iPv4RouterIDNeighborNodeLATLV.hashCode();
return result;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof LinkNLRIMsg)) {
return false;
}
LinkNLRIMsg linkCk = (LinkNLRIMsg) o;
return linkCk.localBgplsID == localBgplsID && linkCk.iPv4RouterIDLocalNodeLATLV == iPv4RouterIDLocalNodeLATLV
&& linkCk.localBgplsID == localBgplsID
&& linkCk.iPv4RouterIDLocalNodeLATLV == iPv4RouterIDLocalNodeLATLV;
}
public String toString() {// check type
String out = "";
if (this.localBgplsID != null)
out = out + "ID: " + this.localBgplsID + " ";// esto es id router??
if (this.iPv4RouterIDLocalNodeLATLV != null)
out = out + this.iPv4RouterIDLocalNodeLATLV.toString();
if(this.localIGPID!=null)
out = out + " localIGPID: "+ this.localIGPID;
if (this.iPv4RouterIDNeighborNodeLATLV != null)
out = out + "---->" + this.iPv4RouterIDNeighborNodeLATLV.toString();
if(this.remoteIGPID!=null)
out = out + " remoteIGPID: "+ this.remoteIGPID;
if (this.remoteBgplsID != null)
out = out + "ID: " + this.remoteBgplsID + " ";
if (this.localDomainID != null)
out = out + "\n AS_ID local: " + this.localDomainID.toString() + " ";
if (this.remoteDomainID != null)
out = out + "\n AS_ID remote: " + this.remoteDomainID.toString() + " ";
if (this.availableBw != 0)
out = out + "\n availableBW: " + this.availableBw + " ";
if (this.residualBw != 0)
out = out + "\n residualBw: " + this.residualBw + " ";
if (this.linkDelay != 0)
out = out + "\n linkDelay: " + this.linkDelay + " ";
return out;
}
public String getLearntFrom() {
return learntFrom;
}
public void setLearntFrom(String learntFrom) {
this.learntFrom = learntFrom;
}
public String getiPv4RouterIDLocalNodeLATLV() {
if (iPv4RouterIDLocalNodeLATLV != null)
return iPv4RouterIDLocalNodeLATLV.toString();
else
return null;// NO DEBERIA SER NULL
}
public void setiPv4RouterIDLocalNodeLATLV(Inet4Address iPv4RouterIDLocalNodeLATLV) {
this.iPv4RouterIDLocalNodeLATLV = iPv4RouterIDLocalNodeLATLV;
}
public String getiPv4RouterIDNeighborNodeLATLV() {
if (iPv4RouterIDNeighborNodeLATLV != null)
return iPv4RouterIDNeighborNodeLATLV.toString();
else
return null;// NO DEBERIA SER NULL
}
public void setiPv4RouterIDNeighborNodeLATLV(Inet4Address iPv4RouterIDNeighborNodeLATLV) {
this.iPv4RouterIDNeighborNodeLATLV = iPv4RouterIDNeighborNodeLATLV;
}
public Inet4Address getLocalDomainID() {
return localDomainID;
}
public Inet4Address getRemoteDomainID() {
return remoteDomainID;
}
public String getLocalBgplsID() {
return this.localBgplsID;
}
public void setLocalBgplsID(String localBgplsID) {
this.localBgplsID = localBgplsID;
}
public String getRemoteBgplsID() {
return this.remoteBgplsID;
}
public void setRemoteBgplsID(String remoteBgplsID) {
this.remoteBgplsID = remoteBgplsID;
}
public Inet4Address getLocalNodeIGPId() {
return LocalNodeIGPId;
}
public Inet4Address getRemoteNodeIGPId() {
return RemoteNodeIGPId;
}
public int getLinkDelay() {
return linkDelay;
}
public int getLinkDelayVar() {
return linkDelayVar;
}
public int getMinDelay() {
return minDelay;
}
public int getMaxDelay() {
return maxDelay;
}
public int getResidualBw() {
return residualBw;
}
public int getAvailableBw() {
return availableBw;
}
public int getUtilizedBw() {
return utilizedBw;
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.models;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.net.InetAddresses;
import es.tid.bgp.bgp4.update.fields.LinkNLRI;
import es.tid.bgp.bgp4.update.fields.NodeNLRI;
import es.tid.bgp.bgp4.update.tlv.node_link_prefix_descriptor_subTLVs.NodeDescriptorsSubTLV;
public class NodeNLRIMsg {
private ArrayList<NodeDescriptorsSubTLV> nodeDescriptorsSubTLV;
// Dominios
private Inet4Address localDomainID;
private Inet4Address remoteDomainID;
private Inet4Address areaID;
private Inet4Address bgplsID;
private Inet4Address LocalNodeBGPId;
private Inet4Address iPv4RouterIDLocalNodeLATLV;
private Inet4Address iPv4RouterIDNeighborNodeLATLV;
private String localBgplsID;
private int remoteBgplsID;
private Inet4Address as_number;
private int IGP_type;
private Inet4Address IGPID = null;
private Logger log;
private String nodeName;
private String ISIS_ID_str;
private String router_id="-";
private String learntFrom;
public NodeNLRIMsg(NodeNLRI nodeNLRI, String learntFrom, String nodeName) {
log = LoggerFactory.getLogger("BGP4Server");// prueba logger
this.learntFrom = learntFrom;
if (nodeNLRI.getLocalNodeDescriptors().getAutonomousSystemSubTLV() != null) {
// inetAddr???
as_number = nodeNLRI.getLocalNodeDescriptors().getAutonomousSystemSubTLV().getAS_ID();
}
if (nodeNLRI.getLocalNodeDescriptors().getAreaID() != null) {
areaID = nodeNLRI.getLocalNodeDescriptors().getAreaID().getAREA_ID();
}
if (nodeNLRI.getLocalNodeDescriptors().getBGPLSIDSubTLV() != null) {
localBgplsID=nodeNLRI.getLocalNodeDescriptors().getBGPLSIDSubTLV().getBGPLS_ID().toString();
}
if (nodeNLRI.getLocalNodeDescriptors().getIGPRouterID() != null) {
IGP_type = nodeNLRI.getLocalNodeDescriptors().getIGPRouterID().getIGP_router_id_type();
switch (IGP_type) {
case 1:
ISIS_ID_str = Integer.toString(nodeNLRI.getLocalNodeDescriptors().getIGPRouterID().getISIS_ISO_NODE_ID());
router_id=ISIS_ID_str;
case 2:
ISIS_ID_str = Integer.toString(nodeNLRI.getLocalNodeDescriptors().getIGPRouterID().getISIS_ISO_NODE_ID());
router_id=ISIS_ID_str;
case 3:
IGPID = nodeNLRI.getLocalNodeDescriptors().getIGPRouterID().getIpv4AddressOSPF();
if(IGPID!=null){
router_id=IGPID.toString();
}else{
System.out.println("Null IGPID (type OSPF)");
}
break;
default:
log.info("añadir este tipo de IGP Identifier por implementar ");
}
}
if (nodeNLRI.getLocalNodeDescriptors().getBGPLSIDSubTLV() != null) {
if (nodeNLRI.getLocalNodeDescriptors().getBGPLSIDSubTLV().getBGPLS_ID() != null) {
LocalNodeBGPId = nodeNLRI.getLocalNodeDescriptors().getBGPLSIDSubTLV().getBGPLS_ID();
}
}
if (nodeName != null) {
this.nodeName = nodeName;
}else{
this.nodeName= this.router_id;
}
log.info("End node processing");
}
public String toString() {// check type
// TODO: concatenate with stringBuffer
String out = "";
if (this.router_id != null)
out = out + "ID: " + this.router_id + " ";// esto es id router??
if (this.iPv4RouterIDLocalNodeLATLV != null)
out = out + this.iPv4RouterIDLocalNodeLATLV.toString();
if (this.iPv4RouterIDNeighborNodeLATLV != null)
out = out + "---->" + this.iPv4RouterIDNeighborNodeLATLV.toString();
if(this.LocalNodeBGPId!=null)
out=out+"BGP_ID: "+this.LocalNodeBGPId+" ";
if(this.as_number!=null)
out=out+"AS_number: "+InetAddresses.coerceToInteger(this.as_number)+" ";
if (this.nodeName != null)
out = out + "Name node attribute: " + nodeName + " ";
if (this.ISIS_ID_str != null)
out = out + "ID node: " + this.ISIS_ID_str + " ";
if (this.as_number != null)
out = out + "AS number: " + this.as_number.toString() + " ";
return out;
}
public String getLearntFrom() {
return learntFrom;
}
public void setLearntFrom(String learntFrom) {
this.learntFrom = learntFrom;
}
public String getLocalBgplsID() {
return this.localBgplsID;
}
public void setLocalBgplsID(String localBgplsID) {
this.localBgplsID = localBgplsID;
}
public String getNodeName() {
return nodeName;
}
public Inet4Address getIGPID() {
return IGPID;
}
public Inet4Address getBgplsID() {
return bgplsID;
}
public String getRouterID(){
return router_id;
}
public void setBgplsID(Inet4Address bgplsID) {
this.bgplsID = bgplsID;
}
public Inet4Address getAs_number() {
return as_number;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + localBgplsID.hashCode();
result = 31 * result + iPv4RouterIDLocalNodeLATLV.hashCode();
result = 31 * result + iPv4RouterIDNeighborNodeLATLV.hashCode();
return result;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof NodeNLRIMsg)) {
return false;
}
NodeNLRIMsg nodeCk = (NodeNLRIMsg) o;
return nodeCk.localBgplsID == localBgplsID && nodeCk.iPv4RouterIDLocalNodeLATLV == iPv4RouterIDLocalNodeLATLV
&& nodeCk.localBgplsID == localBgplsID
&& nodeCk.iPv4RouterIDLocalNodeLATLV == iPv4RouterIDLocalNodeLATLV;
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.models;
import java.net.Inet4Address;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import es.tid.bgp.bgp4.update.fields.pathAttributes.LinkStateAttribute;
import es.tid.bgp.bgp4.update.tlv.BGP4TLVFormat;
import es.tid.bgp.bgp4.update.tlv.linkstate_attribute_tlvs.IPv4RouterIDLocalNodeLinkAttribTLV;
import es.tid.bgp.bgp4.update.tlv.linkstate_attribute_tlvs.NodeNameNodeAttribTLV;
public class PathAttributeMsg {
private NodeNameNodeAttribTLV nodeNameTLV;
private byte[] data;
private String nodeName;
private Inet4Address addrLocal;
public PathAttributeMsg(LinkStateAttribute att) {
if(att.getNodeNameTLV()!=null) {
nodeNameTLV=att.getNodeNameTLV();
data=nodeNameTLV.getTlv_bytes();
int b = nodeNameTLV.getTotalTLVLength();
int c = nodeNameTLV.getTLVValueLength();
byte [] fin= Arrays.copyOfRange(data, b - c, b);
nodeName = new String(fin , StandardCharsets.UTF_8);
}
if(att.getIPv4RouterIDLocalNodeLATLV()!=null) {
addrLocal=att.getIPv4RouterIDLocalNodeLATLV().getIpv4Address();
}
}
public String toString() {
String out="";
if(this.nodeName!=null)
out=out+"NODE name "+nodeName;
if(this.addrLocal!=null)
out=out+"NODE IP "+addrLocal.toString();
return out;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + nodeName.hashCode();
return result;
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof PathAttributeMsg)) {
return false;
}
PathAttributeMsg pathCk = (PathAttributeMsg) o;
return pathCk.nodeName == nodeName;
}
public Inet4Address getAddrLocal() {
return addrLocal;
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.models;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
public class UpdateMsg {
private int AFI;
private int asPathSegment;
private InetAddress nextHop;
private String learntFrom;
private NodeNLRIMsg node;
private LinkNLRIMsg link;
private PathAttributeMsg path;
private List <LinkNLRIMsg> linkList = new ArrayList<>();
private List <NodeNLRIMsg> nodeList = new ArrayList<>();
public List <LinkNLRIMsg> getLinkList(){
return this.linkList;
}
public List <NodeNLRIMsg> getNodeList(){
return this.nodeList;
}
public void addNode(NodeNLRIMsg node) {
this.nodeList.add(node);
}
public int getAFI() {
return AFI;
}
public String getLearntFrom() {
return learntFrom;
}
public void setLearntFrom(String learntFrom) {
this.learntFrom = learntFrom;
}
public void setAFI(int aFI) {
AFI = aFI;
}
public int getAsPathSegment() {
return asPathSegment;
}
public void setAsPathSegment(int asPathSegment) {
this.asPathSegment = asPathSegment;
}
public InetAddress getNextHop() {
return nextHop;
}
public void setNextHop(InetAddress nextHop) {
this.nextHop = nextHop;
}
public NodeNLRIMsg getNode() {
return node;
}
public void setNode(NodeNLRIMsg node) {
this.node = node;
}
// public LinkNLRIMsg getLink() {
// return link;
// }
public boolean linkCheck(){
return linkList.size()>0;
}
public boolean nodeCheck(){
return nodeList.size()>0;
}
public void setLink(LinkNLRIMsg link) {
this.link = link;
}
public void addLink(LinkNLRIMsg link) {
this.linkList.add(link);
}
public PathAttributeMsg getPath() {
return path;
}
public void setPath(PathAttributeMsg path) {
this.path = path;
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.models;
import java.net.InetAddress;
import java.util.LinkedList;
import java.util.List;
public class UpdateMsgList {
/* Print purposes and debug*/
List<NodeNLRIMsg> nodeList = new LinkedList<>();
List<LinkNLRIMsg> linkList = new LinkedList<>();
List<PathAttributeMsg> pathList = new LinkedList<>();
/**/
public UpdateMsgList() {
}
public String toString() {
String out ="Update Message: ";
if(nodeList!=null) {
out=out+nodeList.toString()+"\n";
}
if(linkList!=null) {
out=out+linkList.toString()+"\n";
}
if(pathList!=null) {
out=out+pathList.toString()+"\n";
}
return out;
}
public void addLinkToJson(LinkNLRIMsg link) {
if(link==null)
return;
boolean exists = false;
for (LinkNLRIMsg linkInList : linkList) { // list being the LinkedList
if (link.equals(linkInList)) {
exists = true;
break;
}
}
if (!exists) {
linkList.add(link);
}
}
public void addNodeToJson(NodeNLRIMsg node, String currentName) {//comprobar que existe?
if(node==null)
return;
boolean exists = false;
for (NodeNLRIMsg nodeInList : nodeList) { // list being the LinkedList
if (node.equals(nodeInList)) {
exists = true;
break;
}
}
if (!exists) {
nodeList.add(node);
}
}
public void addpathToJson(PathAttributeMsg path) {
boolean exists = false;
if(path.getNodeName()==null) {
return;
}
for (PathAttributeMsg pathInList : pathList) { // list being the LinkedList
if (path.equals(pathInList) ) {
exists = true;
break;
}
}
if (!exists) {
pathList.add(path);
}
}
public List<NodeNLRIMsg> getNodeList() {
return nodeList;
}
public List<LinkNLRIMsg> getLinkList() {
return linkList;
}
public List<PathAttributeMsg> getPathList() {
return pathList;
}
public void addNodeToList(NodeNLRIMsg node) {
nodeList.add(node);
}
public void addLinkToList(LinkNLRIMsg link) {
linkList.add(link);
}
public void addPathToList(PathAttributeMsg path) {
pathList.add(path);
}
public UpdateMsgList id2Name() {
UpdateMsgList update=new UpdateMsgList();
update.nodeList=this.nodeList;
update.pathList=this.pathList;
List<LinkNLRIMsg> newLinkList = new LinkedList<>();
for (LinkNLRIMsg linkInList : linkList) {
LinkNLRIMsg link=linkInList;
for(NodeNLRIMsg nodeInList: update.nodeList) {
if((linkInList.getLocalBgplsID().equals(nodeInList.getLocalBgplsID()))) {
link.setLocalBgplsID(nodeInList.getNodeName());
}
}
for(NodeNLRIMsg nodeInList: update.nodeList) {
if((linkInList.getRemoteBgplsID().equals(nodeInList.getLocalBgplsID()))) {
link.setRemoteBgplsID(nodeInList.getNodeName());
}
}
newLinkList.add(link);
}
update.linkList=newLinkList;
return update;
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.peer;
public class BGP4Exception extends Exception {
private static final long serialVersionUID = 1L;
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.peer;
import java.net.Inet4Address;
public class BGP4LSPeerInfo {
/**
* IP Address of the remote Peer
*/
private Inet4Address peerIP;
/**
* Experimental USE Only
* Default port is 179
* For testing and development, alternative ports are allowed.
*/
private int peerPort;
/**
* If the remote peer is a consumer and we need to send the topology
*/
private boolean sendToPeer;
/**
* If the remote peer is a generator of topology and we are consumers
*/
private boolean updateFromPeer;
public BGP4LSPeerInfo() {
this.peerPort=179;
}
public Inet4Address getPeerIP() {
return peerIP;
}
public void setPeerIP(Inet4Address peerIP) {
this.peerIP = peerIP;
}
public int getPeerPort() {
return peerPort;
}
public void setPeerPort(int peerPort) {
this.peerPort = peerPort;
}
public boolean isSendToPeer() {
return sendToPeer;
}
public void setSendToPeer(boolean sendToPeer) {
this.sendToPeer = sendToPeer;
}
public boolean isUpdateFromPeer() {
return updateFromPeer;
}
public void setUpdateFromPeer(boolean updateFromPeer) {
this.updateFromPeer = updateFromPeer;
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.peer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.LinkedList;
/**
* Parameters to configure the BGP4 session
* @author mcs
*
*/
public class BGP4Parameters {
private Logger log = LoggerFactory.getLogger("BGP4Peer");
/**
* TCP port where the BGP is listening for incoming bgp4 connections
* Experimental use only. Default and standard is 179
*/
private int BGP4Port = 179;
/**
* TCP port to connect to manage the BGP connection
*/
private int BGP4ManagementPort = 1112;
/**
* Local BGP4 address of this peer
*/
private String localBGPAddress = "127.0.0.1";
/**
* Local port to connect with BGP Peer.
*/
private int localBGPPort = 0;
/**
* Log file
*/
private String BGP4LogFile="BGP4Parser.log";
/**
* Log file Client
*/
private String BGP4LogFileClient="BGP4Client.log";
/**
* Log file Client
*/
private String BGP4LogFileServer="BGP4Server.log";
/**
* Name of the configuration file
*/
private String confFile;
/**
* If the tcp no delay option is used or not.
*/
private boolean nodelay=false;
/**
* Waiting Time to connect to clients
*/
long delay = 6000;
/**
* List of peers to establish connection.
*/
private LinkedList<BGP4LSPeerInfo> peersToConnect;
/**
* Parameter used to set traces meanwhile the execution.
*/
private boolean setTraces=true;
/**
* OPEN PARAMENTERS
*/
int holdTime=90;
/**
* OPEN PARAMENTERS
*/
private boolean isTest=false;
/**
* Time between sending keepalives
*/
int keepAliveTimer=30;
/**
* Time between topology updates
*/
long sendTopoDelay=30000;
private boolean saveTopologyDB=false;
private Inet4Address topologyDBIP;
private int topologyDBport;
public int getKeepAliveTimer() {
return keepAliveTimer;
}
public void setKeepAliveTimer(int keepAliveTimer) {
this.keepAliveTimer = keepAliveTimer;
}
String BGPIdentifier = null;
int myAutonomousSystem=1;
int version=0x04;
/**
* This parameter can have three options: fromXML, fromOSPF, fromBGP
* Explain the way the topology module learns the topology
*/
private String learnTopology="fromBGP";
/**
* XML File to read and generate the topology
*/
private String topologyFile;
private int numberTriesToConnect=3;
/**
* True: This peer sends the interdomain links of the topology to other peers
* False: This peer does NOT send the topology to other peers
*/
private boolean sendTopology=false;
/**
* True: This peer sends the whole topology to other peers
* False: This peer does NOT send the intradomain linksto other peers
*/
private boolean sendIntradomainLinks=false;
/**
* Instance identifier for NodeNLRI (Types defined in class InstanceIDTypes)
*/
private int instanceID=0;
/**
* Constructor
*/
BGP4Parameters(){
confFile="BGP4Parameters.xml";
peersToConnect =new LinkedList<BGP4LSPeerInfo>();
}
/**
* Constructor
*/
BGP4Parameters(String confFile){
peersToConnect =new LinkedList<BGP4LSPeerInfo>();
if (confFile!=null){
this.confFile=confFile;
}else {
confFile="BGP4Parameters.xml";
}
}
public void initialize(){
try {
System.out.println("Parsing Config File::"+confFile);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean peer = false;
boolean send = false;
boolean receive = false;
boolean peerPort = false;
BGP4LSPeerInfo peerInfo=null;
String tempVal;
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("configPeer")){
log.debug("Found peer configuration");
}
else if (qName.equalsIgnoreCase("peer")){
peer = true;
}
else if (qName.equalsIgnoreCase("export")){
send = true;
}
else if (qName.equalsIgnoreCase("import")){
receive = true;
}else if (qName.equalsIgnoreCase("peerPort")){
peerPort = true;
}
}
public void endElement(String uri, String localName,
String qName)
throws SAXException {
if(qName.equalsIgnoreCase("BGP4Port")) {
BGP4Port=Integer.parseInt(tempVal.trim());
}
else if (qName.equalsIgnoreCase("BGP4ManagementPort")){
BGP4ManagementPort = Integer.parseInt(tempVal.trim());
}
else if (qName.equalsIgnoreCase("BGP4LogFile")) {
BGP4LogFile=tempVal.trim();
}
else if (qName.equalsIgnoreCase("BGP4LogFileClient")) {
BGP4LogFileClient=tempVal.trim();
}
else if (qName.equalsIgnoreCase("BGP4LogFileServer")) {
BGP4LogFileServer=tempVal.trim();
}
else if (qName.equalsIgnoreCase("nodelay")) {
nodelay=Boolean.parseBoolean(tempVal.trim());
}
else if (qName.equalsIgnoreCase("isTest")) {
isTest=Boolean.parseBoolean(tempVal.trim());
}
else if (qName.equalsIgnoreCase("setTraces")) {
setTraces=Boolean.parseBoolean(tempVal.trim());
}
else if (qName.equalsIgnoreCase("saveTopologyDB")) {
saveTopologyDB=Boolean.parseBoolean(tempVal.trim());
}
else if (qName.equalsIgnoreCase("topologyDBIP")) {
try {
topologyDBIP =(Inet4Address)Inet4Address.getByName(tempVal.trim());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if (qName.equalsIgnoreCase("topologyDBport")) {
topologyDBport=Integer.parseInt(tempVal.trim());
}
else if (qName.equalsIgnoreCase("sendTopology")) {
sendTopology=Boolean.parseBoolean(tempVal.trim());
}
else if (qName.equalsIgnoreCase("sendIntradomainLinks")) {
sendIntradomainLinks=Boolean.parseBoolean(tempVal.trim());
sendTopology = true;//si se envian los intradomain entonces se enviara la topologia entera
}
else if(qName.equalsIgnoreCase("holdTime")) {
holdTime=Integer.parseInt(tempVal.trim());
}
else if(qName.equalsIgnoreCase("keepAliveTimer")) {
keepAliveTimer=Integer.parseInt(tempVal.trim());
}
else if (qName.equalsIgnoreCase("version")){
version = Integer.parseInt(tempVal.trim());
}
else if (qName.equalsIgnoreCase("myAutonomousSystem")){
myAutonomousSystem = Integer.parseInt(tempVal.trim());
}
else if (qName.equalsIgnoreCase("localBGPAddress")){//El BGP Identifier es la local BGP Address.
//BGPIdentifier = tempVal.trim();
localBGPAddress=tempVal.trim();
}
else if (qName.equalsIgnoreCase("BGPIdentifier")){//El BGP Identifier es la local BGP Address.
BGPIdentifier = tempVal.trim();
}
else if (qName.equalsIgnoreCase("delay")){
delay = Long.parseLong(tempVal.trim());
}
else if (qName.equalsIgnoreCase("sendTopoDelay")){
sendTopoDelay = Long.parseLong(tempVal.trim());
}
/*
else if (qName.equalsIgnoreCase("peer")){
String peerBGP_IPaddress = tempVal.trim();
peersToConnect.add(peerBGP_IPaddress);
}*/
else if (qName.equalsIgnoreCase("TopologyFile")) {
topologyFile=tempVal.trim();
}
else if (qName.equalsIgnoreCase("learnTopology")) {
learnTopology=tempVal.trim();
}
else if (qName.equalsIgnoreCase("numberTriesToConnect")){
numberTriesToConnect = Integer.parseInt(tempVal.trim());
}
else if (qName.equalsIgnoreCase("instanceID")){
instanceID = Integer.parseInt(tempVal.trim());
}
else if (qName.equalsIgnoreCase("localBGPPort")){
localBGPPort = Integer.parseInt(tempVal.trim());
}
// else if (qName.equalsIgnoreCase("configPeer")){
// log.info("peers....." + peersToConnect.toString());
// }
}
public void characters(char[] ch, int start, int length) throws SAXException {
tempVal = new String(ch,start,length);
if(peer){
peerInfo= new BGP4LSPeerInfo();
String peerBGP_IPaddress = new String(ch, start, length);
Inet4Address peerBGPIP;
try {
peerBGPIP=(Inet4Address)Inet4Address.getByName(peerBGP_IPaddress.trim());
peerInfo.setPeerIP(peerBGPIP);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
peersToConnect.add(peerInfo);
peer = false;
}
else if(send){
String sendInfo = new String(ch, start, length);
peerInfo.setSendToPeer(Boolean.parseBoolean(sendInfo.trim()));
send = false;
}
else if(receive){
String update_from = new String(ch, start, length);
peerInfo.setUpdateFromPeer(Boolean.parseBoolean(update_from.trim()));
receive = false;
}else if (peerPort){
String peer_port = new String(ch, start, length);
peerInfo.setPeerPort(Integer.parseInt(peer_port.trim()));
peerPort = false;
}
}
};
saxParser.parse(confFile, handler);
}catch (Exception e) {
log.error("Problems reading config");
e.printStackTrace();
System.exit(1);
}
}
public int getBGP4Port() {
return BGP4Port;
}
public void setBGP4Port(int bGP4Port) {
BGP4Port = bGP4Port;
}
public int getBGP4ManagementPort() {
return BGP4ManagementPort;
}
public void setBGP4ManagementPort(int bGP4ManagementPort) {
BGP4ManagementPort = bGP4ManagementPort;
}
public String getBGP4LogFile() {
return BGP4LogFile;
}
public void setBGP4LogFile(String bGP4LogFile) {
BGP4LogFile = bGP4LogFile;
}
public boolean isSetTraces() {
return setTraces;
}
public void setSetTraces(boolean setTraces) {
this.setTraces = setTraces;
}
public boolean isTest() {
return isTest;
}
public void setisTest(boolean test) {
this.isTest = test;
}
public String getConfFile() {
return confFile;
}
public void setConfFile(String confFile) {
this.confFile = confFile;
}
public boolean isNodelay() {
return nodelay;
}
public void setNodelay(boolean nodelay) {
this.nodelay = nodelay;
}
public int getHoldTime() {
return holdTime;
}
public void setHoldTime(int holdTime) {
this.holdTime = holdTime;
}
public String getBGPIdentifier() {
return BGPIdentifier;
}
public void setBGPIdentifier(String bGPIdentifier) {
BGPIdentifier = bGPIdentifier;
}
public int getMyAutonomousSystem() {
return myAutonomousSystem;
}
public void setMyAutonomousSystem(int myAutonomousSystem) {
this.myAutonomousSystem = myAutonomousSystem;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public LinkedList<BGP4LSPeerInfo> getPeersToConnect() {
return peersToConnect;
}
public void setPeersToConnect(LinkedList<BGP4LSPeerInfo> peersToConnect) {
this.peersToConnect = peersToConnect;
}
public String getLearnTopology() {
return learnTopology;
}
public void setLearnTopology(String learnTopology) {
this.learnTopology = learnTopology;
}
public String getTopologyFile() {
return topologyFile;
}
public void setTopologyFile(String topologyFile) {
this.topologyFile = topologyFile;
}
public int getNumberTriesToConnect() {
return numberTriesToConnect;
}
public void setNumberTriesToConnect(int numberTriesToConnect) {
this.numberTriesToConnect = numberTriesToConnect;
}
public long getDelay() {
return delay;
}
public void setDelay(long delay) {
this.delay = delay;
}
public boolean isSendTopology() {
return sendTopology;
}
public void setSendTopology(boolean sendTopology) {
this.sendTopology = sendTopology;
}
public String getBGP4LogFileClient() {
return BGP4LogFileClient;
}
public void setBGP4LogFileClient(String bGP4LogFileClient) {
BGP4LogFileClient = bGP4LogFileClient;
}
public String getBGP4LogFileServer() {
return BGP4LogFileServer;
}
public void setBGP4LogFileServer(String bGP4LogFileServer) {
BGP4LogFileServer = bGP4LogFileServer;
}
public int getInstanceID() {
return instanceID;
}
public void setInstanceID(int instanceID) {
this.instanceID = instanceID;
}
public boolean isSendIntradomainLinks() {
return sendIntradomainLinks;
}
public void setSendIntradomainLinks(boolean sendIntradomainLinks) {
this.sendIntradomainLinks = sendIntradomainLinks;
}
public String getLocalBGPAddress() {
return localBGPAddress;
}
public void setLocalBGPAddress(String localBGPAddress) {
this.localBGPAddress = localBGPAddress;
}
public int getLocalBGPPort() {
return localBGPPort;
}
public long getSendTopoDelay() {
return sendTopoDelay;
}
public void setSendTopoDelay(long sendTopoDelay) {
this.sendTopoDelay = sendTopoDelay;
}
public boolean isSaveTopologyDB() {
return saveTopologyDB;
}
public void setSaveTopologyDB(boolean saveTopologyDB) {
this.saveTopologyDB = saveTopologyDB;
}
public Inet4Address getTopologyDBIP() {
return topologyDBIP;
}
public void setTopologyDBIP(Inet4Address topologyDBIP) {
this.topologyDBIP = topologyDBIP;
}
public int getTopologyDBport() {
return topologyDBport;
}
public void setTopologyDBport(int topologyDBport) {
this.topologyDBport = topologyDBport;
}
}
// Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
// 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 eu.teraflow.tid.bgp4Peer.peer;
import eu.teraflow.tid.bgp4Peer.bgp4session.BGP4SessionClient;
import eu.teraflow.tid.bgp4Peer.bgp4session.BGP4SessionExistsException;
import eu.teraflow.tid.bgp4Peer.bgp4session.BGP4SessionsInformation;
import eu.teraflow.tid.bgp4Peer.updateTEDB.UpdateDispatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.Inet4Address;
/**
* Client session manager
* @author mcs
*
*/
public class BGP4SessionClientManager implements Runnable{
private BGP4SessionClient bgp4SessionClient;
private Logger log;
BGP4SessionsInformation bgp4SessionInformation;
/**
* peer contains the IP address and port where the peer listens.
*/
private BGP4LSPeerInfo peer;
private Inet4Address peerIP;
private String localBGP4Address;
private int localBGP4Port;
private int holdTime;
private int keepAliveTimer;
private Inet4Address BGPIdentifier;
private int version = 4;
private int myAutonomousSystem;
private UpdateDispatcher ud;
private Boolean updateFrom;
private Boolean sendTo;
public BGP4SessionClientManager(BGP4SessionsInformation bgp4SessionInformation,UpdateDispatcher ud, BGP4LSPeerInfo peer,int bgp4Port,String my_IPAddress,int my_bgp4Port , int holdTime,Inet4Address BGPIdentifier,int version,int myAutonomousSystem, int my_keepAliveTimer){
log=LoggerFactory.getLogger("BGP4Peer");
this.bgp4SessionInformation=bgp4SessionInformation;
this.holdTime=holdTime;
this.BGPIdentifier=BGPIdentifier;
this.version = version;
this.myAutonomousSystem=myAutonomousSystem;
this.peer = peer;
this.ud=ud;
this.localBGP4Address=my_IPAddress;
this.localBGP4Port=my_bgp4Port;
this.keepAliveTimer = my_keepAliveTimer;
this.peerIP=peer.getPeerIP();
this.setSendTo(peer.isSendToPeer());
this.setUpdateFrom(peer.isUpdateFromPeer());
}
/**
*
*
*
*/
public void run(){
if(bgp4SessionClient != null){
if (bgp4SessionClient.isAlive()){
if (bgp4SessionClient.isInterrupted()){
log.debug("Thread alive... backup session dead");
}
log.debug("Session alive and not interrupted");
return;
}
else{
try{
bgp4SessionInformation.notifySessionStart(peerIP);
log.debug("Session with BGP-LS peer"+peer +" dead, trying to establish new session");
bgp4SessionClient= new BGP4SessionClient(bgp4SessionInformation,ud,peer.getPeerIP(),peer.getPeerPort(),holdTime,BGPIdentifier,version,myAutonomousSystem,localBGP4Address, localBGP4Port,keepAliveTimer);
bgp4SessionClient.setSendTo(sendTo);
bgp4SessionClient.setUpdateFrom(updateFrom);
bgp4SessionClient.start();
} catch(BGP4SessionExistsException e){
log.debug("Checked that there is already a peer initiated session with "+this.peerIP);
}
return;
}
} else {
try{
bgp4SessionInformation.notifySessionStart(peerIP);
log.info("Trying to establish new session with peer "+ peer.getPeerIP()+" on port "+peer.getPeerPort());
bgp4SessionClient = new BGP4SessionClient(bgp4SessionInformation,ud, peer.getPeerIP(), peer.getPeerPort(), holdTime, BGPIdentifier,
version,myAutonomousSystem,localBGP4Address, localBGP4Port ,keepAliveTimer);
bgp4SessionClient.setSendTo(sendTo);
bgp4SessionClient.setUpdateFrom(updateFrom);
bgp4SessionClient.start();
} catch(BGP4SessionExistsException e){
log.debug("No need to start new connection with "+this.peerIP);
}
return;
}
}
public BGP4SessionClient getBgp4SessionClient() {
return bgp4SessionClient;
}
public void setBgp4SessionClient(BGP4SessionClient bgp4SessionClient) {
this.bgp4SessionClient = bgp4SessionClient;
}
public void killBGP4Session(){
bgp4SessionClient.killSession();
}
public void closeBGP4Session(){
log.info("Closing BGP4Session");
if (bgp4SessionClient.isAlive()){
//FIXME reason for close????
bgp4SessionClient.close();
}
}
public Boolean getUpdateFrom() {
return updateFrom;
}
public void setUpdateFrom(Boolean updateFrom) {
this.updateFrom = updateFrom;
}
public Boolean getSendTo() {
return sendTo;
}
public void setSendTo(Boolean sendTo) {
this.sendTo = sendTo;
}
}