Bug-2081: PCEP statistics
[bgpcep.git] / pcep / topology-provider / src / main / java / org / opendaylight / bgpcep / pcep / topology / provider / AbstractTopologySessionListener.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.bgpcep.pcep.topology.provider;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import io.netty.util.concurrent.FutureListener;
16 import java.net.InetAddress;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.HashMap;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Map.Entry;
23 import javax.annotation.concurrent.GuardedBy;
24 import org.opendaylight.controller.config.yang.pcep.topology.provider.ListenerStateRuntimeMXBean;
25 import org.opendaylight.controller.config.yang.pcep.topology.provider.ListenerStateRuntimeRegistration;
26 import org.opendaylight.controller.config.yang.pcep.topology.provider.PeerCapabilities;
27 import org.opendaylight.controller.config.yang.pcep.topology.provider.ReplyTime;
28 import org.opendaylight.controller.config.yang.pcep.topology.provider.SessionState;
29 import org.opendaylight.controller.config.yang.pcep.topology.provider.StatefulMessages;
30 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
31 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
32 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
33 import org.opendaylight.protocol.pcep.PCEPSession;
34 import org.opendaylight.protocol.pcep.PCEPSessionListener;
35 import org.opendaylight.protocol.pcep.PCEPTerminationReason;
36 import org.opendaylight.protocol.pcep.TerminationReason;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddressBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.MessageHeader;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Object;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.ProtocolVersion;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.LspId;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1Builder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.OperationResult;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.PccSyncState;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.lsp.metadata.Metadata;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClient;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClientBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLsp;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLspBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLspKey;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.reported.lsp.Path;
54 import org.opendaylight.yangtools.yang.binding.DataContainer;
55 import org.opendaylight.yangtools.yang.binding.DataObject;
56 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 /**
61  * Base class for PCEP topology providers. It handles the common tasks involved in managing a PCEP server (PCE)
62  * endpoint, and exposing a network topology based on it. It needs to be subclassed to form a fully functional block,
63  * where the subclass provides handling of incoming messages.
64  *
65  * @param <S> identifier type of requests
66  * @param <L> identifier type for LSPs
67  */
68 public abstract class AbstractTopologySessionListener<S, L> implements PCEPSessionListener, TopologySessionListener, ListenerStateRuntimeMXBean {
69     protected static final class MessageContext {
70         private final Collection<PCEPRequest> requests = new ArrayList<>();
71         private final WriteTransaction trans;
72
73         private MessageContext(final WriteTransaction trans) {
74             this.trans = Preconditions.checkNotNull(trans);
75         }
76
77         void resolveRequest(final PCEPRequest req) {
78             this.requests.add(req);
79         }
80
81         private void notifyRequests() {
82             for (final PCEPRequest r : this.requests) {
83                 r.done(OperationResults.SUCCESS);
84             }
85         }
86     }
87
88     protected static final MessageHeader MESSAGE_HEADER = new MessageHeader() {
89         private final ProtocolVersion version = new ProtocolVersion((short) 1);
90
91         @Override
92         public Class<? extends DataContainer> getImplementedInterface() {
93             return MessageHeader.class;
94         }
95
96         @Override
97         public ProtocolVersion getVersion() {
98             return this.version;
99         }
100     };
101
102     private static final Logger LOG = LoggerFactory.getLogger(AbstractTopologySessionListener.class);
103
104     protected static final String MISSING_XML_TAG = "Mandatory XML tags are missing.";
105
106     @GuardedBy("this")
107     private final Map<S, PCEPRequest> requests = new HashMap<>();
108
109     @GuardedBy("this")
110     private final Map<String, ReportedLsp> lspData = new HashMap<>();
111
112     @GuardedBy("this")
113     private final Map<L, String> lsps = new HashMap<>();
114
115     private final ServerSessionManager serverSessionManager;
116     private InstanceIdentifier<PathComputationClient> pccIdentifier;
117     private TopologyNodeState nodeState;
118     private boolean synced = false;
119     private PCEPSession session;
120
121     private ListenerStateRuntimeRegistration registration;
122     private final SessionListenerState listenerState;
123
124     protected AbstractTopologySessionListener(final ServerSessionManager serverSessionManager) {
125         this.serverSessionManager = Preconditions.checkNotNull(serverSessionManager);
126         this.listenerState = new SessionListenerState();
127     }
128
129     @Override
130     public final synchronized void onSessionUp(final PCEPSession session) {
131         /*
132          * The session went up. Look up the router in Inventory model,
133          * create it if it is not there (marking that fact for later
134          * deletion), and mark it as synchronizing. Also create it in
135          * the topology model, with empty LSP list.
136          */
137         final InetAddress peerAddress = session.getRemoteAddress();
138
139         final TopologyNodeState state = this.serverSessionManager.takeNodeState(peerAddress, this);
140
141         LOG.trace("Peer {} resolved to topology node {}", peerAddress, state.getNodeId());
142         this.synced = false;
143
144         // Our augmentation in the topology node
145         final PathComputationClientBuilder pccBuilder = new PathComputationClientBuilder();
146         pccBuilder.setIpAddress(IpAddressBuilder.getDefaultInstance(peerAddress.getHostAddress()));
147
148         onSessionUp(session, pccBuilder);
149
150         final Node1 ta = new Node1Builder().setPathComputationClient(pccBuilder.build()).build();
151         final InstanceIdentifier<Node1> topologyAugment = state.getNodeId().augmentation(Node1.class);
152         this.pccIdentifier = topologyAugment.child(PathComputationClient.class);
153
154         final ReadWriteTransaction trans = state.rwTransaction();
155         trans.put(LogicalDatastoreType.OPERATIONAL, topologyAugment, ta);
156         LOG.trace("Peer data {} set to {}", topologyAugment, ta);
157
158         // All set, commit the modifications
159         Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
160             @Override
161             public void onSuccess(final Void result) {
162                 LOG.trace("Internal state for session {} updated successfully", session);
163             }
164
165             @Override
166             public void onFailure(final Throwable t) {
167                 LOG.error("Failed to update internal state for session {}, terminating it", session, t);
168                 session.close(TerminationReason.Unknown);
169             }
170         });
171
172         this.session = session;
173         this.nodeState = state;
174         this.listenerState.init(session);
175         if (this.serverSessionManager.getRuntimeRootRegistration().isPresent()) {
176             this.registration = this.serverSessionManager.getRuntimeRootRegistration().get().register(this);
177         }
178         LOG.info("Session with {} attached to topology node {}", session.getRemoteAddress(), state.getNodeId());
179     }
180
181     @GuardedBy("this")
182     private void tearDown(final PCEPSession session) {
183         this.serverSessionManager.releaseNodeState(this.nodeState, session);
184         this.nodeState = null;
185         this.session = null;
186
187         // Clear all requests we know about
188         for (final Entry<S, PCEPRequest> e : this.requests.entrySet()) {
189             final PCEPRequest r = e.getValue();
190             switch (r.getState()) {
191             case DONE:
192                 // Done is done, nothing to do
193                 break;
194             case UNACKED:
195                 // Peer has not acked: results in failure
196                 LOG.info("Request {} was incomplete when session went down, failing the instruction", e.getKey());
197                 r.done(OperationResults.NOACK);
198                 break;
199             case UNSENT:
200                 // Peer has not been sent to the peer: results in cancellation
201                 LOG.debug("Request {} was not sent when session went down, cancelling the instruction", e.getKey());
202                 r.done(OperationResults.UNSENT);
203                 break;
204             }
205         }
206         this.requests.clear();
207     }
208
209     @Override
210     public final synchronized void onSessionDown(final PCEPSession session, final Exception e) {
211         LOG.warn("Session {} went down unexpectedly", session, e);
212         tearDown(session);
213     }
214
215     @Override
216     public final synchronized void onSessionTerminated(final PCEPSession session, final PCEPTerminationReason reason) {
217         LOG.info("Session {} terminated by peer with reason {}", session, reason);
218         tearDown(session);
219     }
220
221     @Override
222     public final synchronized void onMessage(final PCEPSession session, final Message message) {
223         final MessageContext ctx = new MessageContext(this.nodeState.beginTransaction());
224
225         if (onMessage(ctx, message)) {
226             LOG.info("Unhandled message {} on session {}", message, session);
227             return;
228         }
229
230         Futures.addCallback(ctx.trans.submit(), new FutureCallback<Void>() {
231             @Override
232             public void onSuccess(final Void result) {
233                 LOG.trace("Internal state for session {} updated successfully", session);
234                 ctx.notifyRequests();
235             }
236
237             @Override
238             public void onFailure(final Throwable t) {
239                 LOG.error("Failed to update internal state for session {}, closing it", session, t);
240                 ctx.notifyRequests();
241                 session.close(TerminationReason.Unknown);
242             }
243         });
244     }
245
246     @Override
247     public void close() {
248         if (this.registration != null) {
249             this.registration.close();
250         }
251         if (this.session != null) {
252             this.session.close(TerminationReason.Unknown);
253         }
254     }
255
256     protected final synchronized PCEPRequest removeRequest(final S id) {
257         final PCEPRequest ret = this.requests.remove(id);
258         this.listenerState.processRequestStats(ret.getElapsedMillis());
259         LOG.trace("Removed request {} object {}", id, ret);
260         return ret;
261     }
262
263     protected final synchronized ListenableFuture<OperationResult> sendMessage(final Message message, final S requestId,
264         final Metadata metadata) {
265         final io.netty.util.concurrent.Future<Void> f = this.session.sendMessage(message);
266         this.listenerState.updateStatefulSentMsg(message);
267         final PCEPRequest req = new PCEPRequest(metadata);
268         this.requests.put(requestId, req);
269
270         f.addListener(new FutureListener<Void>() {
271             @Override
272             public void operationComplete(final io.netty.util.concurrent.Future<Void> future) {
273                 if (!future.isSuccess()) {
274                     synchronized (AbstractTopologySessionListener.this) {
275                         AbstractTopologySessionListener.this.requests.remove(requestId);
276                     }
277                     req.done(OperationResults.UNSENT);
278                     LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
279                 } else {
280                     req.sent();
281                     LOG.trace("Request {} sent to peer (object {})", requestId, req);
282                 }
283             }
284         });
285
286         return req.getFuture();
287     }
288
289     /**
290      * Update an LSP in the data store
291      *
292      * @param ctx Message context
293      * @param id Revision-specific LSP identifier
294      * @param lspName LSP name
295      * @param rlb Reported LSP builder
296      * @param solicited True if the update was solicited
297      * @param remove True if this is an LSP path removal
298      */
299     protected final synchronized void updateLsp(final MessageContext ctx, final L id, final String lspName,
300         final ReportedLspBuilder rlb, final boolean solicited, final boolean remove) {
301
302         final String name;
303         if (lspName == null) {
304             name = this.lsps.get(id);
305             if (name == null) {
306                 LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
307                 return;
308             }
309         } else {
310             name = lspName;
311         }
312
313         LOG.debug("Saved LSP {} with name {}", id, name);
314         this.lsps.put(id, name);
315
316
317         final ReportedLsp previous = this.lspData.get(name);
318         // if no previous report about the lsp exist, just proceed
319         if (previous != null) {
320             final List<Path> updatedPaths = makeBeforeBreak(rlb, previous, name, remove);
321             // if all paths or the last path were deleted, delete whole tunnel
322             if (updatedPaths == null || updatedPaths.isEmpty()) {
323                 LOG.debug("All paths were removed, removing LSP with {}.", id);
324                 removeLsp(ctx, id);
325                 return;
326             }
327             rlb.setPath(updatedPaths);
328         }
329         rlb.setKey(new ReportedLspKey(name));
330         rlb.setName(name);
331
332         // If this is an unsolicited update. We need to make sure we retain the metadata already present
333         if (solicited) {
334             this.nodeState.setLspMetadata(name, rlb.getMetadata());
335         } else {
336             rlb.setMetadata(this.nodeState.getLspMetadata(name));
337         }
338
339         final ReportedLsp rl = rlb.build();
340         ctx.trans.put(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier.child(ReportedLsp.class, rlb.getKey()), rl);
341         LOG.debug("LSP {} updated to MD-SAL", name);
342
343         this.lspData.put(name, rl);
344     }
345
346     private List<Path> makeBeforeBreak(final ReportedLspBuilder rlb, final ReportedLsp previous, final String name, final boolean remove) {
347         // just one path should be reported
348         Preconditions.checkState(rlb.getPath().size() == 1);
349         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev130820.LspId reportedLspId = rlb.getPath().get(0).getLspId();
350         // check previous report for existing paths
351         final List<Path> updatedPaths = new ArrayList<>(previous.getPath());
352         LOG.debug("Found previous paths {} to this lsp name {}", updatedPaths, name);
353         for (final Path path : previous.getPath()) {
354             //we found reported path in previous reports
355             if (path.getLspId().getValue() == 0 || path.getLspId().equals(reportedLspId)) {
356                 LOG.debug("Match on lsp-id {}", path.getLspId().getValue() );
357                 // path that was reported previously and does have the same lsp-id, path will be updated
358                 final boolean r = updatedPaths.remove(path);
359                 LOG.trace("Request removed? {}", r);
360             }
361         }
362         // if the path does not exist in previous report, add it to path list, it's a new ERO
363         // only one path will be added
364         //lspId is 0 means confirmation message that shouldn't be added (because we have no means of deleting it later)
365         LOG.trace("Adding new path {} to {}", rlb.getPath(), updatedPaths);
366         updatedPaths.addAll(rlb.getPath());
367         if (remove) {
368             if (reportedLspId.getValue() == 0) {
369                 // if lsp-id also 0, remove all paths
370                 LOG.debug("Removing all paths.");
371                 updatedPaths.clear();
372             } else {
373                 // path is marked to be removed
374                 LOG.debug("Removing path {} from {}", rlb.getPath(), updatedPaths);
375                 final boolean r = updatedPaths.removeAll(rlb.getPath());
376                 LOG.trace("Request removed? {}", r);
377             }
378         }
379         LOG.debug("Setting new paths {} to lsp {}", updatedPaths, name);
380         return updatedPaths;
381     }
382
383     /**
384      * Indicate that the peer has completed state synchronization.
385      *
386      * @param ctx Message context
387      */
388     protected final synchronized void stateSynchronizationAchieved(final MessageContext ctx) {
389         if (this.synced) {
390             LOG.debug("State synchronization achieved while synchronized, not updating state");
391             return;
392         }
393
394         // Update synchronization flag
395         this.synced = true;
396         ctx.trans.merge(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier, new PathComputationClientBuilder().setStateSync(PccSyncState.Synchronized).build());
397
398         // The node has completed synchronization, cleanup metadata no longer reported back
399         this.nodeState.cleanupExcept(this.lsps.values());
400         LOG.debug("Session {} achieved synchronized state", this.session);
401     }
402
403     protected final InstanceIdentifier<ReportedLsp> lspIdentifier(final String name) {
404         return this.pccIdentifier.child(ReportedLsp.class, new ReportedLspKey(name));
405     }
406
407     /**
408      * Remove LSP from the database.
409      *
410      * @param ctx Message Context
411      * @param id Revision-specific LSP identifier
412      */
413     protected final synchronized void removeLsp(final MessageContext ctx, final L id) {
414         final String name = this.lsps.remove(id);
415         LOG.debug("LSP {} removed", name);
416         ctx.trans.delete(LogicalDatastoreType.OPERATIONAL, lspIdentifier(name));
417         this.lspData.remove(name);
418     }
419
420     protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
421
422     /**
423      * Perform revision-specific message processing when a message arrives.
424      *
425      * @param ctx Message processing context
426      * @param message Protocol message
427      * @return True if the message type is not handle.
428      */
429     protected abstract boolean onMessage(MessageContext ctx, Message message);
430
431     protected final String lookupLspName(final L id) {
432         Preconditions.checkNotNull(id, "ID parameter null.");
433         return this.lsps.get(id);
434     }
435
436     protected final synchronized <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(final InstanceIdentifier<T> id) {
437         return this.nodeState.readOperationalData(id);
438     }
439
440     protected abstract Object validateReportedLsp(final Optional<ReportedLsp> rep, final LspId input);
441
442     protected SessionListenerState getSessionListenerState() {
443         return this.listenerState;
444     }
445
446     @Override
447     public Integer getDelegatedLspsCount() {
448         return this.lsps.size();
449     }
450
451     @Override
452     public Boolean getSynchronized() {
453         return this.synced;
454     }
455
456     @Override
457     public StatefulMessages getStatefulMessages() {
458         return this.listenerState.getStatefulMessages();
459     }
460
461     @Override
462     public void resetStats() {
463         this.listenerState.resetStats(this.session);
464     }
465
466     @Override
467     public ReplyTime getReplyTime() {
468         return this.listenerState.getReplyTime();
469     }
470
471     @Override
472     public PeerCapabilities getPeerCapabilities() {
473         return this.listenerState.getPeerCapabilities();
474     }
475
476     @Override
477     public void tearDownSession() {
478         this.close();
479     }
480
481     @Override
482     public SessionState getSessionState() {
483         return this.listenerState.getSessionState(this.session);
484     }
485
486     @Override
487     public String getPeerId() {
488         return this.session.getPeerPref().getIpAddress();
489     }
490 }