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;
+ }
+
+
+ // /**
+ // * Close the PCE session
+ // * List of reasons (RFC 5440):
+ // * 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 perrobjlist=new LinkedList();
+ // 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();
+ }
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/bgp4session/KeepAliveThread.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/bgp4session/KeepAliveThread.java
new file mode 100644
index 0000000000000000000000000000000000000000..70ebe101f4674582e62ed1c7607947e9ae2e3c33
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/bgp4session/KeepAliveThread.java
@@ -0,0 +1,98 @@
+// 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());
+ }
+ }
+
+ }
+
+
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/bgp4session/KeepWaitTimerTask.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/bgp4session/KeepWaitTimerTask.java
new file mode 100644
index 0000000000000000000000000000000000000000..3bc72c84d608db79cc28185b63e6ade8d4e1305e
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/bgp4session/KeepWaitTimerTask.java
@@ -0,0 +1,58 @@
+// 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;
+ }
+
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/bgp4session/OpenWaitTimerTask.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/bgp4session/OpenWaitTimerTask.java
new file mode 100644
index 0000000000000000000000000000000000000000..20b77ce4ee14821073bab2bf7b95aabef5fb8cea
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/bgp4session/OpenWaitTimerTask.java
@@ -0,0 +1,59 @@
+// 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;
+ }
+
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/grpc/grpcApp.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/grpc/grpcApp.java
new file mode 100644
index 0000000000000000000000000000000000000000..329404668263441348fa3583adb2b5b107ff71f3
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/grpc/grpcApp.java
@@ -0,0 +1,38 @@
+// 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();
+ }
+
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/grpc/grpcClient.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/grpc/grpcClient.java
new file mode 100644
index 0000000000000000000000000000000000000000..6e74dff00a565edd4197734483f3ca036f939c27
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/grpc/grpcClient.java
@@ -0,0 +1,368 @@
+// 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 l = new ArrayList<>();
+ List 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 () {
+
+ // 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 () {
+
+ 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 () {
+
+ 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();
+ }
+ });
+ }
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/grpc/updateServiceImpl.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/grpc/updateServiceImpl.java
new file mode 100644
index 0000000000000000000000000000000000000000..3010cbbfb9c29e7233adf3110db02192b2c6a1ff
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/grpc/updateServiceImpl.java
@@ -0,0 +1,42 @@
+// 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 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();
+
+ }
+
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/json/bgpMarshal.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/json/bgpMarshal.java
new file mode 100644
index 0000000000000000000000000000000000000000..87d141222e79c454a66d7002ae67bfe5767a998f
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/json/bgpMarshal.java
@@ -0,0 +1,82 @@
+// 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();
+ }
+
+
+
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/management/BGP4ManagementServer.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/management/BGP4ManagementServer.java
new file mode 100644
index 0000000000000000000000000000000000000000..f135a446d9f453cae51986fd5ee42666a80418a5
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/management/BGP4ManagementServer.java
@@ -0,0 +1,85 @@
+// 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 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 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();
+ }
+ }
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/management/BGP4ManagementSession.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/management/BGP4ManagementSession.java
new file mode 100644
index 0000000000000000000000000000000000000000..18a433e400e593cc66876c3ac264a6c668dd4f80
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/management/BGP4ManagementSession.java
@@ -0,0 +1,199 @@
+// 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 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 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 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;
+ }
+ }
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/models/LinkNLRIMsg.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/models/LinkNLRIMsg.java
new file mode 100644
index 0000000000000000000000000000000000000000..9455ccd1cb9e55ecb85925db19bf62f97cf12703
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/models/LinkNLRIMsg.java
@@ -0,0 +1,298 @@
+
+// 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;
+ // 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;
+ }
+
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/models/NodeNLRIMsg.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/models/NodeNLRIMsg.java
new file mode 100644
index 0000000000000000000000000000000000000000..958544f63b30a81480e25e78ae3ea3e578a9a7cd
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/models/NodeNLRIMsg.java
@@ -0,0 +1,197 @@
+// 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;
+ // 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;
+ }
+
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/models/PathAttributeMsg.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/models/PathAttributeMsg.java
new file mode 100644
index 0000000000000000000000000000000000000000..11bf355d06af41b76eac9fc63f1df7c63628c5df
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/models/PathAttributeMsg.java
@@ -0,0 +1,89 @@
+// 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;
+ }
+
+
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/models/UpdateMsg.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/models/UpdateMsg.java
new file mode 100644
index 0000000000000000000000000000000000000000..37d87e6836734989ec38d08741f51495262c7d3b
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/models/UpdateMsg.java
@@ -0,0 +1,99 @@
+// 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 linkList = new ArrayList<>();
+ private List nodeList = new ArrayList<>();
+
+ public List getLinkList(){
+ return this.linkList;
+ }
+ public List 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;
+ }
+
+
+
+
+
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/models/UpdateMsgList.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/models/UpdateMsgList.java
new file mode 100644
index 0000000000000000000000000000000000000000..6fd30c6cbf5f080676cc43eceaf267e6d2faedff
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/models/UpdateMsgList.java
@@ -0,0 +1,151 @@
+// 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 nodeList = new LinkedList<>();
+ List linkList = new LinkedList<>();
+ List 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 getNodeList() {
+ return nodeList;
+ }
+
+ public List getLinkList() {
+ return linkList;
+ }
+
+ public List 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 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;
+
+ }
+
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGP4Exception.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGP4Exception.java
new file mode 100644
index 0000000000000000000000000000000000000000..736f6cd3eee8e9ebac12875dcc30407a0e63e8de
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGP4Exception.java
@@ -0,0 +1,20 @@
+// 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;
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGP4LSPeerInfo.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGP4LSPeerInfo.java
new file mode 100644
index 0000000000000000000000000000000000000000..768e4a87b4d85e7355d3359b78e140880f2792d0
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGP4LSPeerInfo.java
@@ -0,0 +1,85 @@
+// 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;
+ }
+
+
+
+
+
+
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGP4Parameters.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGP4Parameters.java
new file mode 100644
index 0000000000000000000000000000000000000000..e8958d306e3d11e7a3a569d59773ad4351770eea
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGP4Parameters.java
@@ -0,0 +1,540 @@
+// 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 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();
+ }
+ /**
+ * Constructor
+ */
+ BGP4Parameters(String confFile){
+ peersToConnect =new LinkedList();
+
+ 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 getPeersToConnect() {
+ return peersToConnect;
+ }
+ public void setPeersToConnect(LinkedList 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;
+ }
+
+
+
+
+
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGP4SessionClientManager.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGP4SessionClientManager.java
new file mode 100644
index 0000000000000000000000000000000000000000..75694e90c9ffac9f5760943975f4a437d5fb9863
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGP4SessionClientManager.java
@@ -0,0 +1,160 @@
+// 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;
+ }
+
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGP4SessionServerManager.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGP4SessionServerManager.java
new file mode 100644
index 0000000000000000000000000000000000000000..ccb59fa2e1ace06f3cf4586a3325bbec1f5f2794
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGP4SessionServerManager.java
@@ -0,0 +1,160 @@
+// 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.BGP4PeerInitiatedSession;
+import eu.teraflow.tid.bgp4Peer.bgp4session.BGP4SessionsInformation;
+import eu.teraflow.tid.bgp4Peer.updateTEDB.UpdateDispatcher;
+import eu.teraflow.tid.tedb.TEDB;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.net.Inet4Address;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.LinkedList;
+
+public class BGP4SessionServerManager implements Runnable {
+ private BGP4PeerInitiatedSession bgp4SessionServer;
+ private Logger log;
+ BGP4SessionsInformation bgp4SessionsInformation;
+ int bgp4Port;
+ private int holdTime;
+ private int keepAliveTimer;
+ private Inet4Address BGPIdentifier;
+ private int version = 4;
+ private int myAutonomousSystem;
+ private boolean noDelay;
+ private boolean isTest=false;
+ private TEDB tedb;
+ private UpdateDispatcher ud;
+ Inet4Address localBGP4Address;
+ private Boolean updateFrom;
+ private Boolean sendTo;
+
+ private LinkedList peersToConnect;
+
+ public BGP4SessionServerManager(BGP4SessionsInformation bgp4SessionInformation, TEDB tedb,UpdateDispatcher ud, int bgp4Port,int holdTime,Inet4Address BGPIdentifier,int version,int myAutonomousSystem,boolean noDelay,Inet4Address localAddress ,int mykeepAliveTimer, LinkedList peersToConnect ){
+ log = LoggerFactory.getLogger("BGP4Peer");
+ this.holdTime=holdTime;
+ this.BGPIdentifier=BGPIdentifier;
+ this.version = version;
+ this.myAutonomousSystem=myAutonomousSystem;
+ this.bgp4SessionsInformation=bgp4SessionInformation;
+ this.bgp4Port=bgp4Port;
+ this.noDelay=noDelay;
+ this.tedb=tedb;
+ this.ud=ud;
+ this.localBGP4Address=localAddress;
+ this.keepAliveTimer = mykeepAliveTimer;
+ this.peersToConnect=peersToConnect;
+ }
+
+ public BGP4SessionServerManager(BGP4SessionsInformation bgp4SessionInformation, TEDB tedb,UpdateDispatcher ud, int bgp4Port,int holdTime,Inet4Address BGPIdentifier,int version,int myAutonomousSystem,boolean noDelay,Inet4Address localAddress ,int mykeepAliveTimer, LinkedList peersToConnect, boolean test){
+ log = LoggerFactory.getLogger("BGP4Peer");
+ this.holdTime=holdTime;
+ this.BGPIdentifier=BGPIdentifier;
+ this.version = version;
+ this.myAutonomousSystem=myAutonomousSystem;
+ this.bgp4SessionsInformation=bgp4SessionInformation;
+ this.bgp4Port=bgp4Port;
+ this.noDelay=noDelay;
+ this.tedb=tedb;
+ this.ud=ud;
+ this.localBGP4Address=localAddress;
+ this.keepAliveTimer = mykeepAliveTimer;
+ this.peersToConnect=peersToConnect;
+ this.isTest=test;
+ }
+
+
+ public Boolean getSendTo() {
+ return sendTo;
+ }
+
+ public void setSendTo(Boolean sendTo) {
+ this.sendTo = sendTo;
+ }
+
+ public Boolean getUpdateFrom() {
+ return updateFrom;
+ }
+
+ public void setUpdateFrom(Boolean updateFrom) {
+ this.updateFrom = updateFrom;
+ }
+
+ @Override
+ public void run() {
+
+
+
+ ServerSocket serverSocket = null;
+ boolean listening = true;
+ try {
+ log.debug("SERVER Listening on port: "+ bgp4Port);
+ log.debug("SERVER Listening on address: "+ localBGP4Address);
+ serverSocket = new ServerSocket( bgp4Port,0,localBGP4Address);
+ } catch (IOException e) {
+ log.error("Could not listen on port: "+ bgp4Port);
+ System.exit(-1);
+ }
+ while (listening) {
+ try {
+ Socket sock=serverSocket.accept();
+ bgp4SessionServer = new BGP4PeerInitiatedSession(sock,bgp4SessionsInformation,ud,holdTime,BGPIdentifier,version,myAutonomousSystem,noDelay,keepAliveTimer);
+ if (isTest){
+ log.info("isTest");
+ bgp4SessionServer.setSendTo(true);
+ bgp4SessionServer.start();
+ }
+ else {
+ log.info("Not Test");
+ for (int i = 0; i < this.peersToConnect.size(); i++) {
+ try {
+ Inet4Address add = peersToConnect.get(i).getPeerIP();
+ if (add == null) {
+ log.warn("peer IP address shouldn't be null");
+ } else {
+ if (add.equals(sock.getInetAddress())) {
+ log.debug("FOUND " + add);
+ bgp4SessionServer.setSendTo(this.peersToConnect.get(i).isSendToPeer());
+ }
+ }
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ }
+ bgp4SessionServer.start();
+ }
+ }catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ try {
+ log.info("Closing the socket");
+ serverSocket.close();
+
+ }catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ }
+
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGPPeer.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGPPeer.java
new file mode 100644
index 0000000000000000000000000000000000000000..bdddd4379af58b998b0236e701ea17bcecc14997
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGPPeer.java
@@ -0,0 +1,407 @@
+// 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.BGP4SessionsInformation;
+import eu.teraflow.tid.bgp4Peer.management.BGP4ManagementServer;
+import eu.teraflow.tid.bgp4Peer.updateTEDB.UpdateDispatcher;
+import eu.teraflow.tid.tedb.*;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.Inet4Address;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Hashtable;
+import java.util.LinkedList;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+
+/**
+ * BGP-LS Speaker.
+ * This class is a BGP-LS peer which has two modes:
+ * - Listens to incoming connections
+ * - Launches new BGP session with a list of peers.
+ * It can send periodically its learnt topology to other peers.
+ * TEDB can be initialized from:
+ * - XML file with the topolgoy
+ * - Other BGP-LS Sessions
+ *
+ * @author pac ogondio
+ *
+ */
+public class BGPPeer {
+ /**
+ * Session server. It opens a socket to listen to new connections.
+ */
+ private BGP4SessionServerManager bgp4SessionServer;
+ /**
+ * Session client. It connects to peers.
+ */
+ private BGP4SessionClientManager bgp4SessionClientManager;
+ /**
+ * BGP4 parameters. Needed to configure the connections.
+ */
+ private BGP4Parameters params;
+
+ /**
+ * List of opened BGP4 sessions.
+ */
+ private BGP4SessionsInformation bgp4SessionsInformation;
+
+ /**
+ * Topology database only for interDomain Links.
+ */
+ private MultiDomainTEDB multiDomainTEDB;
+
+ /**
+ * Table with domainID - TEDB.
+ * The BGP-LS Peer can have several domains
+ */
+ private Hashtable intraTEDBs;
+
+ /**
+ * Full TEDB with all Links
+ */
+
+ private SimpleTEDB fullTEDB;
+
+
+ /**
+ * Class to send periodically the topology
+ */
+ //private DomainTEDB readDomainTEDB;
+
+ /**
+ * True: This peer sends the topology to other peers
+ * False: This peer does NOT send the topology to other peers
+ */
+ private boolean sendTopology;
+ /**
+ *
+ */
+ private SendTopology sendTopologyTask;
+ /**
+ *
+ */
+ private boolean saveTopology;
+
+ private SaveTopologyinDB saveTopologyDB;
+
+ /**
+ *
+ */
+ /**
+ * List of peers to establish connections.
+ */
+ private LinkedList peersToConnect;
+
+ //Whitelist and blacklist not yet implemented
+
+ /**
+ * Loggers
+ */
+ private Logger logParser;
+ private Logger logClient;
+ private Logger logServer;
+ /**
+ * Class to read and process the BGP4 update messages
+ */
+ private UpdateDispatcher ud;
+ /**
+ * Executor. To execute the session server, to execute periodically the session client.
+ */
+ private ScheduledThreadPoolExecutor executor;
+
+ /**
+ * Function to configure the BGP4 Peer without specifying the file. It will read a file with name: BGP4Parameters.xml
+ */
+ public void configure (){
+ this.configure (null);
+ }
+
+ /**
+ * Function to configure the BGP4 peer.
+ * It created the loggers, the executor,
+ * @param nameParametersFile Name of the Parameters File
+ */
+ public void configure(String nameParametersFile){
+ configure(nameParametersFile, null, null);
+ }
+
+ /**
+ * Function to configure the BGP4 peer.
+ * It created the loggers, the executor,
+ * @param nameParametersFile Name of the Parameters File
+ * @param multiTEDB multidomain database
+ * @param iTEDBs internal domains database
+ */
+ public void configure(String nameParametersFile, MultiDomainTEDB multiTEDB, Hashtable iTEDBs){
+ //First of all, read the parameters
+ if (nameParametersFile != null){
+ params=new BGP4Parameters(nameParametersFile);
+ }else{
+ params=new BGP4Parameters();
+ }
+ params.initialize();
+ peersToConnect = params.getPeersToConnect();
+ sendTopology = params.isSendTopology();
+ saveTopology = params.isSaveTopologyDB();
+
+ //Initialize loggers
+// FileHandler fh;
+// FileHandler fh1;
+// FileHandler fh2;
+// try {
+// fh=new FileHandler(params.getBGP4LogFile());
+ logParser=LoggerFactory.getLogger("BGP4Parser");
+// logParser.addHandler(fh);
+// logParser.setLevel(Level.ALL);
+// fh1=new FileHandler(params.getBGP4LogFileClient());
+ logClient=LoggerFactory.getLogger("BGP4Client");
+// logClient.addHandler(fh1);
+// logClient.setLevel(Level.ALL);
+// fh2=new FileHandler(params.getBGP4LogFileServer());
+ logServer=LoggerFactory.getLogger("BGP4Peer");
+// logServer.addHandler(fh2);
+// logServer.setLevel(Level.ALL);
+//
+// } catch (Exception e1) {
+// e1.printStackTrace();
+// System.exit(1);
+// }
+ logServer.info("Inizializing BGP4 Peer");
+ if (iTEDBs!= null) intraTEDBs=iTEDBs;
+ else intraTEDBs=new Hashtable();
+
+ if (multiTEDB!= null) multiDomainTEDB = multiTEDB;
+ else multiDomainTEDB = new MDTEDB();
+
+ if (params.getLearnTopology().equals("fromXML")){
+ //intraTEDBs=new Hashtable();
+ //multiDomainTEDB = new MDTEDB();
+ //intraTEDBs = FileTEDBUpdater.readMultipleDomainSimpleNetworks(params.getTopologyFile(), null, false,0,Integer.MAX_VALUE, false);
+ logParser.info("BGPIdentifier: "+params.getBGPIdentifier());
+ intraTEDBs = FileTEDBUpdater.readMultipleDomainSimpleNetworks(params.getTopologyFile(), null, false,0,Integer.MAX_VALUE, false, params.getBGPIdentifier());
+
+ //multiDomainTEDB.initializeFromFile(params.getTopologyFile());
+ multiDomainTEDB.initializeFromFile(params.getTopologyFile(), params.getBGPIdentifier());
+
+ }
+ // Create Thread executor
+ //FIXME: Actualizar n�mero de threads que se crean
+ executor = new ScheduledThreadPoolExecutor(20);//1 para el servidor, 1 para el que lanza y vigila los clientes
+ // Information about all the sessions of the PCE
+ if (params.isTest()) {
+ bgp4SessionsInformation = new BGP4SessionsInformation(params.isTest());
+ }
+ else{
+ bgp4SessionsInformation = new BGP4SessionsInformation();
+ }
+ //Create the task to send the topology. It has to be created because you can start sending the topology in the management (wirting): send topology on.
+ sendTopologyTask = new SendTopology();
+ saveTopologyDB= new SaveTopologyinDB();
+ if (params.isSaveTopologyDB() == true){
+ saveTopologyDB.configure(intraTEDBs, multiDomainTEDB, params.isSaveTopologyDB(), params.getTopologyDBIP().getHostAddress(), params.getTopologyDBport());
+ }
+
+ }
+
+ public void setWriteMultiTEDB(MultiDomainTEDB multiTEDB) {
+
+ this.multiDomainTEDB = multiTEDB;
+ saveTopologyDB.setMultiDomainTEDB(multiTEDB);
+ }
+
+ /*
+ //new function from Andrea
+ public void setWriteMultiAndIntraTEDB(MultiDomainTEDB multiTEDB, Hashtable intraTEDBs) {
+
+ this.multiDomainTEDB = multiTEDB;
+ this.intraTEDBs = intraTEDBs;
+ saveTopologyDB.setMultiDomainTEDB(multiTEDB);
+ saveTopologyDB.setIntraTEDBs(intraTEDBs);
+ }
+ */
+
+
+ public void setReadDomainTEDB(DomainTEDB readDomainTEDB) {
+ //this.readDomainTEDB = readDomainTEDB;
+ //System.out.println("setReadDomain: readFomainTEDB().getDomainID()="+readDomainTEDB.getDomainID());
+ //System.out.println("setReadDomain: readFomainTEDB="+readDomainTEDB.printTopology());
+ if(readDomainTEDB.getDomainID() == null)
+ this.intraTEDBs.put("default", readDomainTEDB);
+ else
+ this.intraTEDBs.put(readDomainTEDB.getDomainID().toString(), readDomainTEDB);
+ }
+ public void createUpdateDispatcher(){
+ //Updater dispatcher
+ ud = new UpdateDispatcher(multiDomainTEDB,intraTEDBs);
+ }
+
+ /**
+ * Function to create the TEDBs of the peer.
+ * @param nameParametersFile Name of the Parameters File
+ */
+
+
+ /**
+ * Start the session for the management of the BGP4.
+ */
+ public void startManagementServer(){
+ logServer.debug("Initializing Management Server");
+ BGP4ManagementServer bms=new BGP4ManagementServer(params.getBGP4ManagementPort(),multiDomainTEDB,intraTEDBs,bgp4SessionsInformation,sendTopologyTask);
+ bms.start();
+ }
+ /**
+ * Function which start the peer as a client which try to establish new sessions with peers.
+ * It starts a new process for each peer.
+ */
+ public void startClient(){
+ logClient.debug("Initializing Session Manager to connect as client");
+ if (params.getBGPIdentifier() != null){
+ Inet4Address BGPIdentifier=null;
+ try {
+ BGPIdentifier = (Inet4Address) InetAddress.getByName(params.getBGPIdentifier());
+ } catch (UnknownHostException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ return;
+ }
+ for (int i =0;i.");
+ System.exit(1);
+ }
+
+ }
+ /**
+ * Function which starts the peer (listening BGP4 protocol) as a server.
+ * It starts once the session server manager.
+ */
+ public void startServer(){
+ logServer.info("Initializing Session Manager to connect as server");
+ Inet4Address localAddress=null;
+ Inet4Address BGPIdentifier=null;
+ if (params.getBGPIdentifier() != null){
+ try {
+ localAddress = (Inet4Address) InetAddress.getByName(params.getLocalBGPAddress());
+ BGPIdentifier = (Inet4Address) InetAddress.getByName(params.getBGPIdentifier());
+ } catch (UnknownHostException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ return;
+ }
+ if (params.isTest()) {
+ bgp4SessionServer = new BGP4SessionServerManager(bgp4SessionsInformation, multiDomainTEDB, ud, params.getBGP4Port(), params.getHoldTime(), BGPIdentifier, params.getVersion(), params.getMyAutonomousSystem(), params.isNodelay(), localAddress, params.getKeepAliveTimer(), peersToConnect, params.isTest());
+ executor.execute(bgp4SessionServer);
+ }
+ else {
+ bgp4SessionServer = new BGP4SessionServerManager(bgp4SessionsInformation, multiDomainTEDB, ud, params.getBGP4Port(), params.getHoldTime(), BGPIdentifier, params.getVersion(), params.getMyAutonomousSystem(), params.isNodelay(), localAddress, params.getKeepAliveTimer(), peersToConnect);
+ executor.execute(bgp4SessionServer);
+ }
+
+ }else{
+ logServer.error("ERROR: BGPIdentifier is not configured. To configure: XML file (BGP4Parameters.xml) .");
+ System.exit(1);
+ }
+ }
+
+ public void startSendTopology(){
+ if (params.isTest()) {
+ sendTopologyTask.configure(intraTEDBs, bgp4SessionsInformation, sendTopology, params.getInstanceID(),params.isSendIntradomainLinks(),this.multiDomainTEDB, params.isTest());
+ }
+ else{
+ sendTopologyTask.configure(intraTEDBs, bgp4SessionsInformation, sendTopology, params.getInstanceID(),params.isSendIntradomainLinks(),this.multiDomainTEDB);
+ }
+ executor.scheduleWithFixedDelay(sendTopologyTask, 0,params.getSendTopoDelay(), TimeUnit.MILLISECONDS);
+ }
+
+
+
+ public void startSaveTopology(){
+ //FIXME: ADD param to configure the delay
+ executor.scheduleWithFixedDelay(saveTopologyDB, 0,5000, TimeUnit.MILLISECONDS);
+ }
+
+
+ public SaveTopologyinDB getSaveTopologyDB() {
+ return saveTopologyDB;
+ }
+
+ public void setSaveTopologyDB(SaveTopologyinDB saveTopologyDB) {
+ this.saveTopologyDB = saveTopologyDB;
+ }
+
+ public boolean isSaveTopology() {
+ return saveTopology;
+ }
+
+ public void setSaveTopology(boolean saveTopology) {
+ this.saveTopology = saveTopology;
+ }
+
+ public UpdateDispatcher getUd() {
+ return ud;
+ }
+
+ public void setUd(UpdateDispatcher ud) {
+ this.ud = ud;
+ }
+
+ public void addSimpleTEDB(SimpleTEDB simpleTEDB, String domainID) {
+ this.intraTEDBs.put(domainID, simpleTEDB);
+ }
+
+ public void setSimpleTEDB(SimpleTEDB simpleTEDB) {
+ if(simpleTEDB.getDomainID() == null)
+ this.intraTEDBs.put("default", simpleTEDB);
+ else
+ this.intraTEDBs.put(simpleTEDB.getDomainID().toString(), simpleTEDB);
+ }
+
+
+ public void stopPeer(){
+ executor.shutdown();
+ }
+ public MultiDomainTEDB getMultiDomainTEDB() {
+ return multiDomainTEDB;
+ }
+
+
+ public Hashtable getIntraTEDBs() {
+ return intraTEDBs;
+ }
+
+ public void setIntraTEDBs(Hashtable intraTEDBs) {
+ this.intraTEDBs = intraTEDBs;
+ }
+
+ public void setMultiDomainTEDB(MultiDomainTEDB multiDomainTEDB) {
+ this.multiDomainTEDB = multiDomainTEDB;
+ }
+
+
+
+
+
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGPPeerMain.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGPPeerMain.java
new file mode 100644
index 0000000000000000000000000000000000000000..97e2702f5485ca848d383e5939a330137c49711b
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/BGPPeerMain.java
@@ -0,0 +1,37 @@
+// 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 BGPPeerMain {
+
+ /**
+ * @param args Command line arguments. First argument, config file.
+ */
+ public static void main(String[] args) {
+ BGPPeer bgpPeer = new BGPPeer();
+ if (args.length != 0)
+ bgpPeer.configure(args[0]);
+ else
+ bgpPeer.configure();
+
+ //bgpPeer.createTEDB("hola"); //did it in configure
+ bgpPeer.createUpdateDispatcher();
+ bgpPeer.startClient();
+ bgpPeer.startServer();
+ bgpPeer.startSaveTopology();
+ bgpPeer.startManagementServer();
+ bgpPeer.startSendTopology();
+ }
+}
diff --git a/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/SaveTopologyinDB.java b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/SaveTopologyinDB.java
new file mode 100644
index 0000000000000000000000000000000000000000..bd27bb87ab0d193f4f7c7de0720aac1cdff1e61c
--- /dev/null
+++ b/src/bgpls_speaker/service/java/netphony-topology/src/main/java/eu/teraflow/tid/bgp4Peer/peer/SaveTopologyinDB.java
@@ -0,0 +1,300 @@
+// 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;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Set;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import eu.teraflow.tid.tedb.DatabaseControlSimplifiedLSA;
+import eu.teraflow.tid.tedb.DomainTEDB;
+import eu.teraflow.tid.tedb.InterDomainEdge;
+import eu.teraflow.tid.tedb.IntraDomainEdge;
+import eu.teraflow.tid.tedb.MultiDomainTEDB;
+import eu.teraflow.tid.tedb.TEDB;
+import eu.teraflow.tid.tedb.TE_Information;
+import redis.clients.jedis.Jedis;
+
+/**
+ * Class to save periodically the topology. It sends the topology to the active BGP4 sessions.
+ * @author pac
+ *
+ */
+public class SaveTopologyinDB implements Runnable {
+
+ //FIXME: Configure from file
+ private Jedis jedis;
+ private String host="localhost";
+ private int port=6379;
+
+ //TEDBs
+ private Hashtable intraTEDBs;
+
+ // Multi-domain TEDB to redistribute Multi-domain Topology
+ private MultiDomainTEDB multiDomainTEDB;
+
+ private boolean writeTopology;
+
+ private Logger log;
+
+
+ public SaveTopologyinDB(){
+ log = LoggerFactory.getLogger("BGP4Peer");
+ jedis = new Jedis(host,port);
+ }
+
+ public void configure( Hashtable intraTEDBs,MultiDomainTEDB multiTED, boolean writeTopology, String host, int port){
+ this.intraTEDBs=intraTEDBs;
+ this.writeTopology=writeTopology;
+ this.multiDomainTEDB=multiTED;
+ //rdh.setHost(host);
+ //rdh.setPort(port);
+
+
+ if (writeTopology){
+ jedis = new Jedis(host,port);
+ jedis.connect();
+ }
+ }
+
+ /**
+ * Function to send the topology database.
+ */
+
+
+ public void run(){
+ try {
+ if (writeTopology){
+ log.info("Going to save Topology in Redis DB");
+ if (jedis==null){
+ jedis = new Jedis(host,port);
+ jedis.connect();
+ }else if (jedis.isConnected()==false){
+ jedis.connect();
+ }
+ if (multiDomainTEDB!=null){
+ log.info("save Multi-Domain TEDB");
+ writeLinkDBInter( multiDomainTEDB.getInterDomainLinks());
+ }
+ else {
+ log.info("save form TEDB");
+ Enumeration iter = intraTEDBs.elements();
+ while (iter.hasMoreElements()){
+ writeLinkDBInter( iter.nextElement().getInterDomainLinks());
+ }
+ }
+
+ log.info("sendIntraDomainLinks activated");
+ Enumeration iter = intraTEDBs.keys();
+ while (iter.hasMoreElements()){
+ String domainID = iter.nextElement();
+ log.info("Sending TED from domain "+domainID);
+ DomainTEDB ted=(DomainTEDB)intraTEDBs.get(domainID);
+ //writeLinkDB( ted.getNetworkGraph().edgeSet(),domainID);
+ writeLinkDB(ted.getIntraDomainLinks(),domainID);
+ }
+
+
+ }
+ }catch (Exception e) {
+ e.printStackTrace();
+ log.error("PROBLEM Writing TOPOLOGY: "+e.toString());
+ }
+
+ }
+
+ /**
+ * This function write a BGP4 update message in Data Base for each link in the list
+ * @param intradomainLinks
+ */
+ private void writeLinkDB(Set intradomainLinks, String domainID){
+
+ Iterator edgeIt = intradomainLinks.iterator();
+
+ while (edgeIt.hasNext()){
+
+ IntraDomainEdge edge = edgeIt.next();
+
+ DatabaseControlSimplifiedLSA dcsl =createSimplifiedLSA(edge);
+ String jsonLSA = dcsl.logJsonSimplifiedLSA();
+
+ if (jedis == null)
+ log.info("JEDIS IS NULL");
+
+ String ret = jedis.set("LSA:"+dcsl.getAdvertisingRouter().getHostAddress()+":"+dcsl.getLinkId().getHostAddress(), jsonLSA);
+ }
+
+ }
+
+ private DatabaseControlSimplifiedLSA createSimplifiedLSA(IntraDomainEdge edge){
+ DatabaseControlSimplifiedLSA dcsl = new DatabaseControlSimplifiedLSA();
+
+ //Inet4Address source = (Inet4Address)edge.getSrc_router_id();
+ //Inet4Address dst = (Inet4Address)edge.getDst_router_id();
+
+ Inet4Address source = (Inet4Address)edge.getSource();
+ dcsl.setAdvertisingRouter(source);
+ Inet4Address dst = (Inet4Address)edge.getTarget();
+ dcsl.setLinkId(dst);
+
+ TE_Information te_info = ((IntraDomainEdge) edge).getTE_info();
+
+ if (te_info != null){
+
+ if (te_info.getLinkLocalRemoteIdentifiers() != null){
+ dcsl.linkLocalIdentifier = te_info.getLinkLocalRemoteIdentifiers().getLinkLocalIdentifier();
+ }
+
+ if (te_info.getLinkLocalRemoteIdentifiers() != null){
+ dcsl.linkRemoteIdentifier = te_info.getLinkLocalRemoteIdentifiers().getLinkRemoteIdentifier();
+ }
+
+ if (te_info.getMaximumBandwidth() != null) {
+ dcsl.maximumBandwidth = te_info.getMaximumBandwidth().getMaximumBandwidth();
+ }
+
+ if (te_info.getUnreservedBandwidth() != null) {
+ dcsl.unreservedBandwidth = te_info.getUnreservedBandwidth().getUnreservedBandwidth()[0];
+ }
+
+ if (te_info.getMaximumReservableBandwidth() != null)
+ dcsl.maximumReservableBandwidth = te_info.getMaximumReservableBandwidth().getMaximumReservableBandwidth();
+
+ String ret = "";
+
+ if (te_info.getAvailableLabels() != null){
+
+ if (te_info.getAvailableLabels().getLabelSet() != null){
+
+ ret=ret+" Bitmap: {";
+
+ for (int i=0;i interdomainLinks){
+
+ Iterator edgeIt = interdomainLinks.iterator();
+
+ while (edgeIt.hasNext()){
+
+ InterDomainEdge edge = edgeIt.next();
+
+ DatabaseControlSimplifiedLSA dcsl =createSimplifiedLSAInter(edge);
+ String jsonLSA = dcsl.logJsonSimplifiedLSA();
+ //rdh.write("LSA:"+dcsl.getAdvertisingRouter().getHostAddress()+":"+dcsl.getLinkId().getHostAddress(),jsonLSA);
+ String ret = jedis.set("LSA:"+dcsl.getAdvertisingRouter().getHostAddress()+":"+dcsl.getLinkId().getHostAddress(), jsonLSA);
+ }
+
+ }
+
+ private DatabaseControlSimplifiedLSA createSimplifiedLSAInter(InterDomainEdge edge){
+ DatabaseControlSimplifiedLSA dcsl = new DatabaseControlSimplifiedLSA();
+
+ //Inet4Address source = (Inet4Address)edge.getSrc_router_id();
+ //Inet4Address dst = (Inet4Address)edge.getDst_router_id();
+
+ Inet4Address source = (Inet4Address)edge.getSource();
+ dcsl.setAdvertisingRouter(source);
+ Inet4Address dst = (Inet4Address)edge.getTarget();
+ dcsl.setLinkId(dst);
+
+ TE_Information te_info = ((InterDomainEdge) edge).getTE_info();
+
+ if (te_info != null){
+
+ if (te_info.getLinkLocalRemoteIdentifiers() != null){
+ dcsl.linkLocalIdentifier = te_info.getLinkLocalRemoteIdentifiers().getLinkLocalIdentifier();
+ }
+
+ if (te_info.getLinkLocalRemoteIdentifiers() != null){
+ dcsl.linkRemoteIdentifier = te_info.getLinkLocalRemoteIdentifiers().getLinkRemoteIdentifier();
+ }
+
+ if (te_info.getMaximumBandwidth() != null) {
+ dcsl.maximumBandwidth = te_info.getMaximumBandwidth().getMaximumBandwidth();
+ }
+
+ if (te_info.getUnreservedBandwidth() != null) {
+ dcsl.unreservedBandwidth = te_info.getUnreservedBandwidth().getUnreservedBandwidth()[0];
+ }
+
+ if (te_info.getMaximumReservableBandwidth() != null)
+ dcsl.maximumReservableBandwidth = te_info.getMaximumReservableBandwidth().getMaximumReservableBandwidth();
+
+ String ret = "";
+
+ if (te_info.getAvailableLabels() != null){
+
+ if (te_info.getAvailableLabels().getLabelSet() != null){
+
+ ret=ret+" Bitmap: {";
+
+ for (int i=0;i intraTEDBs;
+
+ // Multi-domain TEDB to redistribute Multi-domain Topology
+ private MultiDomainTEDB multiDomainTEDB;
+
+ private boolean sendTopology;
+ private boolean isTest=false;
+ private BGP4SessionsInformation bgp4SessionsInformation;
+ private Logger log;
+ private int instanceId=1;
+ private boolean sendIntraDomainLinks=false;
+
+ private boolean send4AS=false;
+
+
+
+
+ private Inet4Address localBGPLSIdentifer;
+ private Inet4Address localAreaID;
+
+ public SendTopology(){
+ log = LoggerFactory.getLogger("BGP4Peer");
+ }
+
+ public void configure( Hashtable intraTEDBs,BGP4SessionsInformation bgp4SessionsInformation,boolean sendTopology,int instanceId,boolean sendIntraDomainLinks, MultiDomainTEDB multiTED){
+ this.intraTEDBs=intraTEDBs;
+ this.bgp4SessionsInformation=bgp4SessionsInformation;
+ this.sendTopology= sendTopology;
+ this.instanceId = instanceId;
+ this.sendIntraDomainLinks=sendIntraDomainLinks;
+ this.multiDomainTEDB=multiTED;
+ try {
+ this.localAreaID=(Inet4Address)Inet4Address.getByName("0.0.0.0");
+ this.localBGPLSIdentifer=(Inet4Address)Inet4Address.getByName("1.1.1.1");
+ } catch (UnknownHostException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
+
+
+ public void configure( Hashtable intraTEDBs,BGP4SessionsInformation bgp4SessionsInformation,boolean sendTopology,int instanceId,boolean sendIntraDomainLinks, MultiDomainTEDB multiTED, boolean test){
+ this.intraTEDBs=intraTEDBs;
+ this.bgp4SessionsInformation=bgp4SessionsInformation;
+ this.sendTopology= sendTopology;
+ this.instanceId = instanceId;
+ this.sendIntraDomainLinks=sendIntraDomainLinks;
+ this.multiDomainTEDB=multiTED;
+ this.isTest=test;
+ try {
+ this.localAreaID=(Inet4Address)Inet4Address.getByName("0.0.0.0");
+ this.localBGPLSIdentifer=(Inet4Address)Inet4Address.getByName("1.1.1.1");
+ } catch (UnknownHostException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
+
+ /**
+ * Function to send the topology database.
+ */
+
+
+ public void run(){
+ try {
+ if (sendTopology){
+ if (!(bgp4SessionsInformation.getSessionList().isEmpty())){
+ if (multiDomainTEDB!=null){
+ log.debug("Sending Multi-Domain TEDB");
+ sendLinkNLRI( multiDomainTEDB.getInterDomainLinks());
+ }
+ else {
+ log.debug("Sending from TEDB");
+ Enumeration iter = intraTEDBs.elements();
+ while (iter.hasMoreElements()){
+ sendLinkNLRI( iter.nextElement().getInterDomainLinks());
+ }
+ }
+
+ if (sendIntraDomainLinks){//Intradomain Links
+ log.debug("sendIntraDomainLinks activated");
+ Enumeration iter = intraTEDBs.keys();
+ while (iter.hasMoreElements()){
+ String domainID = iter.nextElement();
+ //Andrea
+ log.debug("Sending TED from domain "+domainID);
+
+ TEDB ted=intraTEDBs.get(domainID);
+ if (ted instanceof DomainTEDB) {
+ sendLinkNLRI( ((DomainTEDB)ted).getIntraDomainLinks(),domainID);
+ //log.info(" XXXX ted.getNodeTable():"+ted.getNodeTable());
+ sendNodeNLRI( ((DomainTEDB)ted).getIntraDomainLinksvertexSet(), ((DomainTEDB)ted).getNodeTable());
+ if (((DomainTEDB)ted).getItResources()!=null){
+ sendITNodeNLRI( domainID, ((DomainTEDB)ted).getItResources());
+ }
+
+ }
+
+
+
+ }
+
+ }
+
+ }
+ }
+ }catch (Exception e) {
+ e.printStackTrace();
+ log.error("PROBLEM SENDING TOPOLOGY: "+e.toString());
+ }
+
+ }
+ /**
+ * This function sends a BGP4 update message (encoded in a NodeNLRI) for each node in the set
+ * @param vertexIt
+ */
+ private void sendNodeNLRI(Set