Merge "BUG-731 : removed more 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.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         if (ret != null) {
259             this.listenerState.processRequestStats(ret.getElapsedMillis());
260         }
261         LOG.trace("Removed request {} object {}", id, ret);
262         return ret;
263     }
264
265     protected final synchronized ListenableFuture<OperationResult> sendMessage(final Message message, final S requestId,
266         final Metadata metadata) {
267         final io.netty.util.concurrent.Future<Void> f = this.session.sendMessage(message);
268         this.listenerState.updateStatefulSentMsg(message);
269         final PCEPRequest req = new PCEPRequest(metadata);
270         this.requests.put(requestId, req);
271
272         f.addListener(new FutureListener<Void>() {
273             @Override
274             public void operationComplete(final io.netty.util.concurrent.Future<Void> future) {
275                 if (!future.isSuccess()) {
276                     synchronized (AbstractTopologySessionListener.this) {
277                         AbstractTopologySessionListener.this.requests.remove(requestId);
278                     }
279                     req.done(OperationResults.UNSENT);
280                     LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
281                 } else {
282                     req.sent();
283                     LOG.trace("Request {} sent to peer (object {})", requestId, req);
284                 }
285             }
286         });
287
288         return req.getFuture();
289     }
290
291     /**
292      * Update an LSP in the data store
293      *
294      * @param ctx Message context
295      * @param id Revision-specific LSP identifier
296      * @param lspName LSP name
297      * @param rlb Reported LSP builder
298      * @param solicited True if the update was solicited
299      * @param remove True if this is an LSP path removal
300      */
301     protected final synchronized void updateLsp(final MessageContext ctx, final L id, final String lspName,
302         final ReportedLspBuilder rlb, final boolean solicited, final boolean remove) {
303
304         final String name;
305         if (lspName == null) {
306             name = this.lsps.get(id);
307             if (name == null) {
308                 LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
309                 return;
310             }
311         } else {
312             name = lspName;
313         }
314
315         LOG.debug("Saved LSP {} with name {}", id, name);
316         this.lsps.put(id, name);
317
318
319         final ReportedLsp previous = this.lspData.get(name);
320         // if no previous report about the lsp exist, just proceed
321         if (previous != null) {
322             final List<Path> updatedPaths = makeBeforeBreak(rlb, previous, name, remove);
323             // if all paths or the last path were deleted, delete whole tunnel
324             if (updatedPaths == null || updatedPaths.isEmpty()) {
325                 LOG.debug("All paths were removed, removing LSP with {}.", id);
326                 removeLsp(ctx, id);
327                 return;
328             }
329             rlb.setPath(updatedPaths);
330         }
331         rlb.setKey(new ReportedLspKey(name));
332         rlb.setName(name);
333
334         // If this is an unsolicited update. We need to make sure we retain the metadata already present
335         if (solicited) {
336             this.nodeState.setLspMetadata(name, rlb.getMetadata());
337         } else {
338             rlb.setMetadata(this.nodeState.getLspMetadata(name));
339         }
340
341         final ReportedLsp rl = rlb.build();
342         ctx.trans.put(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier.child(ReportedLsp.class, rlb.getKey()), rl);
343         LOG.debug("LSP {} updated to MD-SAL", name);
344
345         this.lspData.put(name, rl);
346     }
347
348     private List<Path> makeBeforeBreak(final ReportedLspBuilder rlb, final ReportedLsp previous, final String name, final boolean remove) {
349         // just one path should be reported
350         Preconditions.checkState(rlb.getPath().size() == 1);
351         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev130820.LspId reportedLspId = rlb.getPath().get(0).getLspId();
352         // check previous report for existing paths
353         final List<Path> updatedPaths = new ArrayList<>(previous.getPath());
354         LOG.debug("Found previous paths {} to this lsp name {}", updatedPaths, name);
355         for (final Path path : previous.getPath()) {
356             //we found reported path in previous reports
357             if (path.getLspId().getValue() == 0 || path.getLspId().equals(reportedLspId)) {
358                 LOG.debug("Match on lsp-id {}", path.getLspId().getValue() );
359                 // path that was reported previously and does have the same lsp-id, path will be updated
360                 final boolean r = updatedPaths.remove(path);
361                 LOG.trace("Request removed? {}", r);
362             }
363         }
364         // if the path does not exist in previous report, add it to path list, it's a new ERO
365         // only one path will be added
366         //lspId is 0 means confirmation message that shouldn't be added (because we have no means of deleting it later)
367         LOG.trace("Adding new path {} to {}", rlb.getPath(), updatedPaths);
368         updatedPaths.addAll(rlb.getPath());
369         if (remove) {
370             if (reportedLspId.getValue() == 0) {
371                 // if lsp-id also 0, remove all paths
372                 LOG.debug("Removing all paths.");
373                 updatedPaths.clear();
374             } else {
375                 // path is marked to be removed
376                 LOG.debug("Removing path {} from {}", rlb.getPath(), updatedPaths);
377                 final boolean r = updatedPaths.removeAll(rlb.getPath());
378                 LOG.trace("Request removed? {}", r);
379             }
380         }
381         LOG.debug("Setting new paths {} to lsp {}", updatedPaths, name);
382         return updatedPaths;
383     }
384
385     /**
386      * Indicate that the peer has completed state synchronization.
387      *
388      * @param ctx Message context
389      */
390     protected final synchronized void stateSynchronizationAchieved(final MessageContext ctx) {
391         if (this.synced) {
392             LOG.debug("State synchronization achieved while synchronized, not updating state");
393             return;
394         }
395
396         // Update synchronization flag
397         this.synced = true;
398         ctx.trans.merge(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier, new PathComputationClientBuilder().setStateSync(PccSyncState.Synchronized).build());
399
400         // The node has completed synchronization, cleanup metadata no longer reported back
401         this.nodeState.cleanupExcept(this.lsps.values());
402         LOG.debug("Session {} achieved synchronized state", this.session);
403     }
404
405     protected final InstanceIdentifier<ReportedLsp> lspIdentifier(final String name) {
406         return this.pccIdentifier.child(ReportedLsp.class, new ReportedLspKey(name));
407     }
408
409     /**
410      * Remove LSP from the database.
411      *
412      * @param ctx Message Context
413      * @param id Revision-specific LSP identifier
414      */
415     protected final synchronized void removeLsp(final MessageContext ctx, final L id) {
416         final String name = this.lsps.remove(id);
417         LOG.debug("LSP {} removed", name);
418         ctx.trans.delete(LogicalDatastoreType.OPERATIONAL, lspIdentifier(name));
419         this.lspData.remove(name);
420     }
421
422     protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
423
424     /**
425      * Perform revision-specific message processing when a message arrives.
426      *
427      * @param ctx Message processing context
428      * @param message Protocol message
429      * @return True if the message type is not handle.
430      */
431     protected abstract boolean onMessage(MessageContext ctx, Message message);
432
433     protected final String lookupLspName(final L id) {
434         Preconditions.checkNotNull(id, "ID parameter null.");
435         return this.lsps.get(id);
436     }
437
438     protected final synchronized <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(final InstanceIdentifier<T> id) {
439         return this.nodeState.readOperationalData(id);
440     }
441
442     protected abstract Object validateReportedLsp(final Optional<ReportedLsp> rep, final LspId input);
443
444     protected SessionListenerState getSessionListenerState() {
445         return this.listenerState;
446     }
447
448     @Override
449     public Integer getDelegatedLspsCount() {
450         return this.lsps.size();
451     }
452
453     @Override
454     public Boolean getSynchronized() {
455         return this.synced;
456     }
457
458     @Override
459     public StatefulMessages getStatefulMessages() {
460         return this.listenerState.getStatefulMessages();
461     }
462
463     @Override
464     public synchronized void resetStats() {
465         this.listenerState.resetStats(this.session);
466     }
467
468     @Override
469     public ReplyTime getReplyTime() {
470         return this.listenerState.getReplyTime();
471     }
472
473     @Override
474     public PeerCapabilities getPeerCapabilities() {
475         return this.listenerState.getPeerCapabilities();
476     }
477
478     @Override
479     public void tearDownSession() {
480         this.close();
481     }
482
483     @Override
484     public synchronized SessionState getSessionState() {
485         return this.listenerState.getSessionState(this.session);
486     }
487
488     @Override
489     public synchronized String getPeerId() {
490         return this.session.getPeerPref().getIpAddress();
491     }
492 }