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