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