Switch statements should end with a default case.
[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         unregister();
187
188         // Clear all requests we know about
189         for (final Entry<S, PCEPRequest> e : this.requests.entrySet()) {
190             final PCEPRequest r = e.getValue();
191             switch (r.getState()) {
192             case DONE:
193                 // Done is done, nothing to do
194                 break;
195             case UNACKED:
196                 // Peer has not acked: results in failure
197                 LOG.info("Request {} was incomplete when session went down, failing the instruction", e.getKey());
198                 r.done(OperationResults.NOACK);
199                 break;
200             case UNSENT:
201                 // Peer has not been sent to the peer: results in cancellation
202                 LOG.debug("Request {} was not sent when session went down, cancelling the instruction", e.getKey());
203                 r.done(OperationResults.UNSENT);
204                 break;
205             default:
206                 break;
207             }
208         }
209         this.requests.clear();
210     }
211
212     @Override
213     public final synchronized void onSessionDown(final PCEPSession session, final Exception e) {
214         LOG.warn("Session {} went down unexpectedly", session, e);
215         tearDown(session);
216     }
217
218     @Override
219     public final synchronized void onSessionTerminated(final PCEPSession session, final PCEPTerminationReason reason) {
220         LOG.info("Session {} terminated by peer with reason {}", session, reason);
221         tearDown(session);
222     }
223
224     @Override
225     public final synchronized void onMessage(final PCEPSession session, final Message message) {
226         final MessageContext ctx = new MessageContext(this.nodeState.beginTransaction());
227
228         if (onMessage(ctx, message)) {
229             LOG.info("Unhandled message {} on session {}", message, session);
230             return;
231         }
232
233         Futures.addCallback(ctx.trans.submit(), new FutureCallback<Void>() {
234             @Override
235             public void onSuccess(final Void result) {
236                 LOG.trace("Internal state for session {} updated successfully", session);
237                 ctx.notifyRequests();
238             }
239
240             @Override
241             public void onFailure(final Throwable t) {
242                 LOG.error("Failed to update internal state for session {}, closing it", session, t);
243                 ctx.notifyRequests();
244                 session.close(TerminationReason.UNKNOWN);
245             }
246         });
247     }
248
249     @Override
250     public void close() {
251         unregister();
252         if (this.session != null) {
253             this.session.close(TerminationReason.UNKNOWN);
254         }
255     }
256
257     private synchronized void unregister() {
258         if (this.registration != null) {
259             this.registration.close();
260             this.registration = null;
261         }
262     }
263
264     protected final synchronized PCEPRequest removeRequest(final S id) {
265         final PCEPRequest ret = this.requests.remove(id);
266         if (ret != null) {
267             this.listenerState.processRequestStats(ret.getElapsedMillis());
268         }
269         LOG.trace("Removed request {} object {}", id, ret);
270         return ret;
271     }
272
273     protected final synchronized ListenableFuture<OperationResult> sendMessage(final Message message, final S requestId,
274         final Metadata metadata) {
275         final io.netty.util.concurrent.Future<Void> f = this.session.sendMessage(message);
276         this.listenerState.updateStatefulSentMsg(message);
277         final PCEPRequest req = new PCEPRequest(metadata);
278         this.requests.put(requestId, req);
279
280         f.addListener(new FutureListener<Void>() {
281             @Override
282             public void operationComplete(final io.netty.util.concurrent.Future<Void> future) {
283                 if (!future.isSuccess()) {
284                     synchronized (AbstractTopologySessionListener.this) {
285                         AbstractTopologySessionListener.this.requests.remove(requestId);
286                     }
287                     req.done(OperationResults.UNSENT);
288                     LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
289                 } else {
290                     req.sent();
291                     LOG.trace("Request {} sent to peer (object {})", requestId, req);
292                 }
293             }
294         });
295
296         return req.getFuture();
297     }
298
299     /**
300      * Update an LSP in the data store
301      *
302      * @param ctx Message context
303      * @param id Revision-specific LSP identifier
304      * @param lspName LSP name
305      * @param rlb Reported LSP builder
306      * @param solicited True if the update was solicited
307      * @param remove True if this is an LSP path removal
308      */
309     protected final synchronized void updateLsp(final MessageContext ctx, final L id, final String lspName,
310         final ReportedLspBuilder rlb, final boolean solicited, final boolean remove) {
311
312         final String name;
313         if (lspName == null) {
314             name = this.lsps.get(id);
315             if (name == null) {
316                 LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
317                 return;
318             }
319         } else {
320             name = lspName;
321         }
322
323         LOG.debug("Saved LSP {} with name {}", id, name);
324         this.lsps.put(id, name);
325
326
327         final ReportedLsp previous = this.lspData.get(name);
328         // if no previous report about the lsp exist, just proceed
329         if (previous != null) {
330             final List<Path> updatedPaths = makeBeforeBreak(rlb, previous, name, remove);
331             // if all paths or the last path were deleted, delete whole tunnel
332             if (updatedPaths == null || updatedPaths.isEmpty()) {
333                 LOG.debug("All paths were removed, removing LSP with {}.", id);
334                 removeLsp(ctx, id);
335                 return;
336             }
337             rlb.setPath(updatedPaths);
338         }
339         rlb.setKey(new ReportedLspKey(name));
340         rlb.setName(name);
341
342         // If this is an unsolicited update. We need to make sure we retain the metadata already present
343         if (solicited) {
344             this.nodeState.setLspMetadata(name, rlb.getMetadata());
345         } else {
346             rlb.setMetadata(this.nodeState.getLspMetadata(name));
347         }
348
349         final ReportedLsp rl = rlb.build();
350         ctx.trans.put(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier.child(ReportedLsp.class, rlb.getKey()), rl);
351         LOG.debug("LSP {} updated to MD-SAL", name);
352
353         this.lspData.put(name, rl);
354     }
355
356     private List<Path> makeBeforeBreak(final ReportedLspBuilder rlb, final ReportedLsp previous, final String name, final boolean remove) {
357         // just one path should be reported
358         Preconditions.checkState(rlb.getPath().size() == 1);
359         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev130820.LspId reportedLspId = rlb.getPath().get(0).getLspId();
360         // check previous report for existing paths
361         final List<Path> updatedPaths = new ArrayList<>(previous.getPath());
362         LOG.debug("Found previous paths {} to this lsp name {}", updatedPaths, name);
363         for (final Path path : previous.getPath()) {
364             //we found reported path in previous reports
365             if (path.getLspId().getValue() == 0 || path.getLspId().equals(reportedLspId)) {
366                 LOG.debug("Match on lsp-id {}", path.getLspId().getValue() );
367                 // path that was reported previously and does have the same lsp-id, path will be updated
368                 final boolean r = updatedPaths.remove(path);
369                 LOG.trace("Request removed? {}", r);
370             }
371         }
372         // if the path does not exist in previous report, add it to path list, it's a new ERO
373         // only one path will be added
374         //lspId is 0 means confirmation message that shouldn't be added (because we have no means of deleting it later)
375         LOG.trace("Adding new path {} to {}", rlb.getPath(), updatedPaths);
376         updatedPaths.addAll(rlb.getPath());
377         if (remove) {
378             if (reportedLspId.getValue() == 0) {
379                 // if lsp-id also 0, remove all paths
380                 LOG.debug("Removing all paths.");
381                 updatedPaths.clear();
382             } else {
383                 // path is marked to be removed
384                 LOG.debug("Removing path {} from {}", rlb.getPath(), updatedPaths);
385                 final boolean r = updatedPaths.removeAll(rlb.getPath());
386                 LOG.trace("Request removed? {}", r);
387             }
388         }
389         LOG.debug("Setting new paths {} to lsp {}", updatedPaths, name);
390         return updatedPaths;
391     }
392
393     /**
394      * Indicate that the peer has completed state synchronization.
395      *
396      * @param ctx Message context
397      */
398     protected final synchronized void stateSynchronizationAchieved(final MessageContext ctx) {
399         if (this.synced) {
400             LOG.debug("State synchronization achieved while synchronized, not updating state");
401             return;
402         }
403
404         // Update synchronization flag
405         this.synced = true;
406         ctx.trans.merge(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier, new PathComputationClientBuilder().setStateSync(PccSyncState.Synchronized).build());
407
408         // The node has completed synchronization, cleanup metadata no longer reported back
409         this.nodeState.cleanupExcept(this.lsps.values());
410         LOG.debug("Session {} achieved synchronized state", this.session);
411     }
412
413     protected final InstanceIdentifier<ReportedLsp> lspIdentifier(final String name) {
414         return this.pccIdentifier.child(ReportedLsp.class, new ReportedLspKey(name));
415     }
416
417     /**
418      * Remove LSP from the database.
419      *
420      * @param ctx Message Context
421      * @param id Revision-specific LSP identifier
422      */
423     protected final synchronized void removeLsp(final MessageContext ctx, final L id) {
424         final String name = this.lsps.remove(id);
425         LOG.debug("LSP {} removed", name);
426         ctx.trans.delete(LogicalDatastoreType.OPERATIONAL, lspIdentifier(name));
427         this.lspData.remove(name);
428     }
429
430     protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
431
432     /**
433      * Perform revision-specific message processing when a message arrives.
434      *
435      * @param ctx Message processing context
436      * @param message Protocol message
437      * @return True if the message type is not handle.
438      */
439     protected abstract boolean onMessage(MessageContext ctx, Message message);
440
441     protected final String lookupLspName(final L id) {
442         Preconditions.checkNotNull(id, "ID parameter null.");
443         return this.lsps.get(id);
444     }
445
446     protected final synchronized <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(final InstanceIdentifier<T> id) {
447         return this.nodeState.readOperationalData(id);
448     }
449
450     protected abstract Object validateReportedLsp(final Optional<ReportedLsp> rep, final LspId input);
451
452     protected SessionListenerState getSessionListenerState() {
453         return this.listenerState;
454     }
455
456     @Override
457     public Integer getDelegatedLspsCount() {
458         return this.lsps.size();
459     }
460
461     @Override
462     public Boolean getSynchronized() {
463         return this.synced;
464     }
465
466     @Override
467     public StatefulMessages getStatefulMessages() {
468         return this.listenerState.getStatefulMessages();
469     }
470
471     @Override
472     public synchronized void resetStats() {
473         this.listenerState.resetStats(this.session);
474     }
475
476     @Override
477     public ReplyTime getReplyTime() {
478         return this.listenerState.getReplyTime();
479     }
480
481     @Override
482     public PeerCapabilities getPeerCapabilities() {
483         return this.listenerState.getPeerCapabilities();
484     }
485
486     @Override
487     public void tearDownSession() {
488         this.close();
489     }
490
491     @Override
492     public synchronized SessionState getSessionState() {
493         return this.listenerState.getSessionState(this.session);
494     }
495
496     @Override
497     public synchronized String getPeerId() {
498         return this.session.getPeerPref().getIpAddress();
499     }
500 }