2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.bgpcep.pcep.topology.provider;
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;
17 import io.netty.util.concurrent.FutureListener;
19 import java.net.InetAddress;
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.List;
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;
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.
69 * @param <S> identifier type of requests
70 * @param <L> identifier type for LSPs
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);
77 public Class<? extends DataContainer> getImplementedInterface() {
78 return MessageHeader.class;
82 public ProtocolVersion getVersion() {
86 private static final Logger LOG = LoggerFactory.getLogger(AbstractTopologySessionListener.class);
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;
102 protected AbstractTopologySessionListener(final ServerSessionManager serverSessionManager) {
103 this.serverSessionManager = Preconditions.checkNotNull(serverSessionManager);
106 private static String createNodeId(final InetAddress addr) {
107 return "pcc://" + addr.getHostAddress();
110 private Node topologyNode(final ReadWriteTransaction trans, final InetAddress address) {
111 final String pccId = createNodeId(address);
113 // FIXME: Futures.transform...
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);
126 } catch (InterruptedException | ExecutionException e) {
127 throw new IllegalStateException("Failed to ensure topology presence.", e);
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).
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);
138 final Node ret = new NodeBuilder().setKey(nk).setNodeId(id).build();
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;
148 public final synchronized void onSessionUp(final PCEPSession session) {
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.
155 final InetAddress peerAddress = session.getRemoteAddress();
156 final ReadWriteTransaction trans = this.serverSessionManager.rwTransaction();
158 final Node topoNode = topologyNode(trans, peerAddress);
159 LOG.trace("Peer {} resolved to topology node {}", peerAddress, topoNode);
161 // Our augmentation in the topology node
163 this.pccBuilder = new PathComputationClientBuilder();
164 this.pccBuilder.setIpAddress(IpAddressBuilder.getDefaultInstance(peerAddress.getHostAddress()));
166 onSessionUp(session, this.pccBuilder);
168 this.topologyAugmentBuilder = new Node1Builder().setPathComputationClient(this.pccBuilder.build());
169 this.topologyAugment = this.topologyNode.augmentation(Node1.class);
170 final Node1 ta = this.topologyAugmentBuilder.build();
172 trans.put(LogicalDatastoreType.OPERATIONAL, this.topologyAugment, ta);
173 LOG.trace("Peer data {} set to {}", this.topologyAugment, ta);
175 // All set, commit the modifications
176 Futures.addCallback(trans.commit(), new FutureCallback<RpcResult<TransactionStatus>>() {
178 public void onSuccess(final RpcResult<TransactionStatus> result) {
179 LOG.trace("Internal state for session {} updated successfully", session);
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);
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());
195 private void tearDown(final PCEPSession session) {
196 this.serverSessionManager.releaseNodeState(this.nodeState);
197 this.nodeState = null;
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);
207 Futures.addCallback(trans.commit(), new FutureCallback<RpcResult<TransactionStatus>>() {
209 public void onSuccess(final RpcResult<TransactionStatus> result) {
210 LOG.trace("Internal state for session {} cleaned up successfully", session);
214 public void onFailure(final Throwable t) {
215 LOG.error("Failed to cleanup internal state for session {}", session, t);
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);
224 this.sendingRequests.clear();
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);
231 this.waitingRequests.clear();
235 public final synchronized void onSessionDown(final PCEPSession session, final Exception e) {
236 LOG.warn("Session {} went down unexpectedly", session, e);
241 public final synchronized void onSessionTerminated(final PCEPSession session, final PCEPTerminationReason reason) {
242 LOG.info("Session {} terminated by peer with reason {}", session, reason);
247 public final synchronized void onMessage(final PCEPSession session, final Message message) {
248 final WriteTransaction trans = this.serverSessionManager.beginTransaction();
252 if (onMessage(trans, message)) {
253 LOG.info("Unhandled message {} on session {}", message, session);
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();
263 trans.put(LogicalDatastoreType.OPERATIONAL, this.topologyAugment, ta);
264 LOG.trace("Peer data {} set to {}", this.topologyAugment, ta);
267 LOG.debug("State has not changed, skipping sync");
270 Futures.addCallback(trans.commit(), new FutureCallback<RpcResult<TransactionStatus>>() {
272 public void onSuccess(final RpcResult<TransactionStatus> result) {
273 LOG.trace("Internal state for session {} updated successfully", session);
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);
285 public void close() {
286 if (this.session != null) {
287 this.session.close(TerminationReason.Unknown);
291 protected InstanceIdentifierBuilder<PathComputationClient> pccIdentifier() {
292 return this.topologyAugment.builder().child(PathComputationClient.class);
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);
301 private synchronized void messageSendingComplete(final S requestId, final io.netty.util.concurrent.Future<Void> future) {
302 final PCEPRequest req = this.sendingRequests.remove(requestId);
304 if (future.isSuccess()) {
305 this.waitingRequests.put(requestId, req);
306 LOG.trace("Request {} sent to peer (object {})", requestId, req);
308 LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
309 req.setResult(OperationResults.UNSENT);
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);
318 this.sendingRequests.put(requestId, req);
320 f.addListener(new FutureListener<Void>() {
322 public void operationComplete(final io.netty.util.concurrent.Future<Void> future) {
323 messageSendingComplete(requestId, future);
327 return req.getFuture();
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) {
334 if (lspName == null) {
335 name = this.lsps.get(id);
337 LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
344 LOG.debug("Saved LSP {} with name {}", id, name);
345 this.lsps.put(id, name);
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);
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());
371 if (reportedLspId.getValue() == 0) {
372 // if lsp-id also 0, remove all paths
373 LOG.debug("Removing all paths.");
374 updatedPaths.clear();
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);
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);
388 LOG.debug("Setting new paths {} to lsp {}", updatedPaths, name);
389 rlb.setPath(updatedPaths);
391 Preconditions.checkState(name != null);
392 rlb.setKey(new ReportedLspKey(name));
395 // If this is an unsolicited update. We need to make sure we retain the metadata already present
397 this.nodeState.setLspMetadata(name, rlb.getMetadata());
399 rlb.setMetadata(this.nodeState.getLspMetadata(name));
402 LOG.debug("LSP {} forcing update to MD-SAL", name);
404 this.lspData.put(name, rlb.build());
407 protected final synchronized void stateSynchronizationAchieved(final WriteTransaction trans) {
409 LOG.debug("State synchronization achieved while synchronized, not updating state");
413 // Update synchronization flag
415 this.pccBuilder.setStateSync(PccSyncState.Synchronized).build();
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);
423 protected final InstanceIdentifierBuilder<ReportedLsp> lspIdentifier(final String name) {
424 return pccIdentifier().child(ReportedLsp.class, new ReportedLspKey(name));
427 protected final synchronized void removeLsp(final WriteTransaction trans, final L id) {
428 final String name = this.lsps.remove(id);
430 LOG.debug("LSP {} removed", name);
431 this.lspData.remove(name);
434 protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
436 protected abstract boolean onMessage(WriteTransaction trans, Message message);
438 protected String lookupLspName(final L id) {
439 Preconditions.checkNotNull(id, "ID parameter null.");
440 return this.lsps.get(id);
443 protected final <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(final InstanceIdentifier<T> id) {
444 return this.serverSessionManager.readOperationalData(id);