PCEP sucessfull connection now implemented. Fixed minor bug in parsing.
[bgpcep.git] / pcep / testtool / src / main / java / org / opendaylight / protocol / pcep / testtool / TestingSessionListener.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.protocol.pcep.testtool;
9
10 import groovy.lang.GroovyClassLoader;
11
12 import java.io.BufferedReader;
13 import java.io.File;
14 import java.io.InputStream;
15 import java.io.InputStreamReader;
16 import java.util.ArrayList;
17 import java.util.LinkedList;
18 import java.util.List;
19 import java.util.Queue;
20 import java.util.Timer;
21 import java.util.TimerTask;
22
23 import org.opendaylight.protocol.concepts.IPv4Address;
24 import org.opendaylight.protocol.concepts.IPv4Prefix;
25 import org.opendaylight.protocol.concepts.Prefix;
26 import org.opendaylight.protocol.framework.TerminationReason;
27 import org.opendaylight.protocol.pcep.PCEPMessage;
28 import org.opendaylight.protocol.pcep.PCEPSession;
29 import org.opendaylight.protocol.pcep.PCEPSessionListener;
30 import org.opendaylight.protocol.pcep.message.PCEPXRAddTunnelMessage;
31 import org.opendaylight.protocol.pcep.object.PCEPCloseObject;
32 import org.opendaylight.protocol.pcep.object.PCEPEndPointsObject;
33 import org.opendaylight.protocol.pcep.object.PCEPExplicitRouteObject;
34 import org.opendaylight.protocol.pcep.object.PCEPLspObject;
35 import org.opendaylight.protocol.pcep.object.PCEPOpenObject;
36 import org.opendaylight.protocol.pcep.subobject.EROIPPrefixSubobject;
37 import org.opendaylight.protocol.pcep.subobject.ExplicitRouteSubobject;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 public class TestingSessionListener extends PCEPSessionListener {
42
43         public List<PCEPMessage> messages = new ArrayList<PCEPMessage>();
44
45         private static final Logger logger = LoggerFactory.getLogger(TestingSessionListener.class);
46
47         public final Queue<PCEPMessage> replyMessages;
48         public final Queue<PCEPMessage> sendNowMessages;
49         public final Queue<PCEPMessage> periodicalMessages;
50         public final int period;
51
52         private class MessageTimer extends TimerTask {
53                 private final PCEPMessage message;
54                 private final PCEPSession session;
55
56                 MessageTimer(final PCEPMessage message, final PCEPSession session) {
57                         this.message = message;
58                         this.session = session;
59                 }
60
61                 @Override
62                 public void run() {
63                         this.session.sendMessage(this.message);
64                 }
65         }
66
67         public TestingSessionListener() {
68                 /**
69                  * default messages are set to null
70                  */
71                 this.period = 0;
72                 this.replyMessages = new LinkedList<PCEPMessage>();
73                 this.sendNowMessages = new LinkedList<PCEPMessage>();
74                 this.periodicalMessages = new LinkedList<PCEPMessage>();
75         }
76
77         public TestingSessionListener(final String autoResponseMessagesSrc, final String periodicallySendMessagesSrc, final int period,
78                         final String sendNowMessageSrc) {
79                 this.period = period;
80                 this.replyMessages = this.loadMessageGeneratorFromFile(autoResponseMessagesSrc).generateMessages();
81                 this.sendNowMessages = this.loadMessageGeneratorFromFile(sendNowMessageSrc).generateMessages();
82                 this.periodicalMessages = this.loadMessageGeneratorFromFile(periodicallySendMessagesSrc).generateMessages();
83         }
84
85         /**
86          * Periodically send messages from loaded queue.
87          * 
88          * @param session the session used to send message
89          * @param period the time between two sent messages
90          */
91         public void sendPeriodically(final PCEPSession session, final int seconds) {
92                 if (!this.periodicalMessages.isEmpty()) {
93                         this.sendPeriodically(session, this.periodicalMessages.poll(), seconds);
94                 } else
95                         logger.debug("DON'T starting PERIODICAL sender. Messages queue is empty.");
96         }
97
98         /**
99          * Periodically send specified message.
100          * 
101          * @param session the session used to send message
102          * @param message the message to send
103          * @param period the time between two sent messages
104          */
105         public void sendPeriodically(final PCEPSession session, final PCEPMessage message, final int seconds) {
106                 final Timer timer = new Timer();
107
108                 logger.debug("Starting periodical sending of messages with {} seconds delay.", seconds);
109                 timer.schedule(new MessageTimer(message, session), seconds * 1000);
110         }
111
112         public void sendNow(final PCEPSession session) {
113                 if (!this.sendNowMessages.isEmpty()) {
114                         final PCEPMessage msg = this.sendNowMessages.poll();
115                         this.sendNow(session, msg);
116                 } else
117                         logger.debug("DON'T sending NOW. Messages queue is empty.");
118         }
119
120         public void sendNow(final PCEPSession session, final PCEPMessage message) {
121                 logger.debug("Sending NOW.");
122                 session.sendMessage(message);
123         }
124
125         @Override
126         public void onMessage(final PCEPSession session, final PCEPMessage message) {
127                 logger.debug("Received message: {}", message);
128                 this.messages.add(message);
129
130                 // if (!this.replyMessages.isEmpty()) {
131                 // this.logger.debug("Remaining messages in queue: {}", this.replyMessages.size());
132                 // session.sendMessage(this.replyMessages.poll());
133                 // } else
134                 // this.logger.debug("Reply messages queue is empty.");
135         }
136
137         @Override
138         public void onSessionUp(final PCEPSession session, final PCEPOpenObject local, final PCEPOpenObject remote) {
139                 logger.debug("Session up.");
140                 final List<ExplicitRouteSubobject> subs = new ArrayList<ExplicitRouteSubobject>();
141                 subs.add(new EROIPPrefixSubobject<Prefix<?>>(new IPv4Prefix(new IPv4Address(new byte[] { 10, 1, 1, 2 }), 32), false));
142                 subs.add(new EROIPPrefixSubobject<Prefix<?>>(new IPv4Prefix(new IPv4Address(new byte[] { 2, 2, 2, 2 }), 32), false));
143                 session.sendMessage(new PCEPXRAddTunnelMessage(new PCEPLspObject(23, false, false, false, false), new PCEPEndPointsObject<IPv4Address>(new IPv4Address(new byte[] {
144                                 1, 1, 1, 1 }), new IPv4Address(new byte[] { 2, 2, 2, 2 })), new PCEPExplicitRouteObject(subs, false)));
145                 this.sendNow(session);
146                 this.sendPeriodically(session, this.period);
147         }
148
149         @Override
150         public void onSessionDown(final PCEPSession session, final PCEPCloseObject reason, final Exception e) {
151                 logger.debug("Session down because: {}", reason);
152         }
153
154         @Override
155         public void onSessionTerminated(final PCEPSession session, final TerminationReason cause) {
156                 logger.debug("Session terminated. Cause : " + cause.toString());
157         }
158
159         private MessageGeneratorService loadMessageGeneratorFromFile(final String path) {
160                 try {
161                         final GroovyClassLoader l = new GroovyClassLoader();
162                         final Class<?> scriptClass = l.parseClass(new File(path));
163                         l.close();
164                         logger.debug("Loaded '{}'", path);
165                         final MessageGeneratorService generator = (MessageGeneratorService) scriptClass.newInstance();
166                         logger.debug("Instantiated '{}'", path);
167                         return generator;
168                 } catch (final Exception e) {
169                         logger.error("Failed to load '{}'. Using empty queue.", path);
170                         return new MessageGeneratorService() {
171
172                                 @Override
173                                 public Queue<PCEPMessage> generateMessages() {
174                                         return new LinkedList<PCEPMessage>();
175                                 }
176                         };
177                 }
178
179         }
180
181         @SuppressWarnings("unused")
182         private MessageGeneratorService loadMessageGeneratorFormSysResource(final String path) {
183                 try {
184                         final InputStream is = this.getClass().getResourceAsStream(path);
185                         final BufferedReader buffReader = new BufferedReader(new InputStreamReader(is));
186                         final StringBuilder script = new StringBuilder();
187                         String scriptLine;
188                         while ((scriptLine = buffReader.readLine()) != null) {
189                                 script.append(scriptLine + "\n");
190                         }
191                         final GroovyClassLoader l = new GroovyClassLoader();
192                         final Class<?> scriptClass = l.parseClass(script.toString());
193                         l.close();
194                         logger.debug("Loaded '{}'", path);
195                         final MessageGeneratorService generator = (MessageGeneratorService) scriptClass.newInstance();
196                         logger.debug("Instantiated '{}'", path);
197                         return generator;
198
199                 } catch (final Exception e) {
200                         logger.error("Failed to load '{}' from system resources. Using empty queue.", path);
201                         return new MessageGeneratorService() {
202
203                                 @Override
204                                 public Queue<PCEPMessage> generateMessages() {
205                                         return new LinkedList<PCEPMessage>();
206                                 }
207                         };
208                 }
209         }
210 }