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