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.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;
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;
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.
64 * @param <S> identifier type of requests
65 * @param <L> identifier type for LSPs
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;
72 private MessageContext(final WriteTransaction trans) {
73 this.trans = Preconditions.checkNotNull(trans);
76 void resolveRequest(final PCEPRequest req) {
77 this.requests.add(req);
80 private void notifyRequests() {
81 for (final PCEPRequest r : this.requests) {
82 r.done(OperationResults.SUCCESS);
87 protected static final MessageHeader MESSAGE_HEADER = new MessageHeader() {
88 private final ProtocolVersion version = new ProtocolVersion((short) 1);
91 public Class<? extends DataContainer> getImplementedInterface() {
92 return MessageHeader.class;
96 public ProtocolVersion getVersion() {
100 private static final Logger LOG = LoggerFactory.getLogger(AbstractTopologySessionListener.class);
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;
114 protected AbstractTopologySessionListener(final ServerSessionManager serverSessionManager) {
115 this.serverSessionManager = Preconditions.checkNotNull(serverSessionManager);
118 private static String createNodeId(final InetAddress addr) {
119 return "pcc://" + addr.getHostAddress();
122 private Node topologyNode(final ReadWriteTransaction trans, final InetAddress address) {
123 final String pccId = createNodeId(address);
125 // FIXME: Futures.transform...
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);
138 } catch (InterruptedException | ExecutionException e) {
139 throw new IllegalStateException("Failed to ensure topology presence.", e);
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).
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);
150 final Node ret = new NodeBuilder().setKey(nk).setNodeId(id).build();
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;
160 public final synchronized void onSessionUp(final PCEPSession session) {
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.
167 final InetAddress peerAddress = session.getRemoteAddress();
168 final ReadWriteTransaction trans = this.serverSessionManager.rwTransaction();
170 final Node topoNode = topologyNode(trans, peerAddress);
171 LOG.trace("Peer {} resolved to topology node {}", peerAddress, topoNode);
173 // Our augmentation in the topology node
176 final PathComputationClientBuilder pccBuilder;
177 pccBuilder = new PathComputationClientBuilder();
178 pccBuilder.setIpAddress(IpAddressBuilder.getDefaultInstance(peerAddress.getHostAddress()));
180 onSessionUp(session, pccBuilder);
182 final Node1 ta = new Node1Builder().setPathComputationClient(pccBuilder.build()).build();
184 this.topologyAugment = this.topologyNode.augmentation(Node1.class);
185 this.pccIdentifier = this.topologyAugment.child(PathComputationClient.class);
187 trans.put(LogicalDatastoreType.OPERATIONAL, this.topologyAugment, ta);
188 LOG.trace("Peer data {} set to {}", this.topologyAugment, ta);
190 // All set, commit the modifications
191 Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
193 public void onSuccess(final Void result) {
194 LOG.trace("Internal state for session {} updated successfully", session);
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);
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());
210 private void tearDown(final PCEPSession session) {
211 this.serverSessionManager.releaseNodeState(this.nodeState);
212 this.nodeState = null;
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);
222 Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
224 public void onSuccess(final Void result) {
225 LOG.trace("Internal state for session {} cleaned up successfully", session);
229 public void onFailure(final Throwable t) {
230 LOG.error("Failed to cleanup internal state for session {}", session, t);
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()) {
239 // Done is done, nothing to do
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);
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);
253 this.requests.clear();
257 public final synchronized void onSessionDown(final PCEPSession session, final Exception e) {
258 LOG.warn("Session {} went down unexpectedly", session, e);
263 public final synchronized void onSessionTerminated(final PCEPSession session, final PCEPTerminationReason reason) {
264 LOG.info("Session {} terminated by peer with reason {}", session, reason);
269 public final synchronized void onMessage(final PCEPSession session, final Message message) {
270 final MessageContext ctx = new MessageContext(this.serverSessionManager.beginTransaction());
272 if (onMessage(ctx, message)) {
273 LOG.info("Unhandled message {} on session {}", message, session);
277 Futures.addCallback(ctx.trans.submit(), new FutureCallback<Void>() {
279 public void onSuccess(final Void result) {
280 LOG.trace("Internal state for session {} updated successfully", session);
281 ctx.notifyRequests();
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);
294 public void close() {
295 if (this.session != null) {
296 this.session.close(TerminationReason.Unknown);
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);
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);
312 f.addListener(new FutureListener<Void>() {
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);
319 req.done(OperationResults.UNSENT);
320 LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
323 LOG.trace("Request {} sent to peer (object {})", requestId, req);
328 return req.getFuture();
332 * Update an LSP in the data store
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
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) {
345 if (lspName == null) {
346 name = this.lsps.get(id);
348 LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
355 LOG.debug("Saved LSP {} with name {}", id, name);
356 this.lsps.put(id, name);
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);
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());
382 if (reportedLspId.getValue() == 0) {
383 // if lsp-id also 0, remove all paths
384 LOG.debug("Removing all paths.");
385 updatedPaths.clear();
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);
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);
399 LOG.debug("Setting new paths {} to lsp {}", updatedPaths, name);
400 rlb.setPath(updatedPaths);
402 Preconditions.checkState(name != null);
403 rlb.setKey(new ReportedLspKey(name));
406 // If this is an unsolicited update. We need to make sure we retain the metadata already present
408 this.nodeState.setLspMetadata(name, rlb.getMetadata());
410 rlb.setMetadata(this.nodeState.getLspMetadata(name));
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);
417 this.lspData.put(name, rl);
421 * Indicate that the peer has completed state synchronization.
423 * @param ctx Message context
425 protected final synchronized void stateSynchronizationAchieved(final MessageContext ctx) {
427 LOG.debug("State synchronization achieved while synchronized, not updating state");
431 // Update synchronization flag
433 ctx.trans.merge(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier, new PathComputationClientBuilder().setStateSync(PccSyncState.Synchronized).build());
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);
440 protected final InstanceIdentifier<ReportedLsp> lspIdentifier(final String name) {
441 return this.pccIdentifier.child(ReportedLsp.class, new ReportedLspKey(name));
445 * Remove LSP from the database.
447 * @param ctx Message Context
448 * @param id Revision-specific LSP identifier
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);
457 protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
460 * Perform revision-specific message processing when a message arrives.
462 * @param ctx Message processing context
463 * @param message Protocol message
464 * @return True if the message type is not handle.
466 protected abstract boolean onMessage(MessageContext ctx, Message message);
468 protected final String lookupLspName(final L id) {
469 Preconditions.checkNotNull(id, "ID parameter null.");
470 return this.lsps.get(id);
473 protected final <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(final InstanceIdentifier<T> id) {
474 return this.serverSessionManager.readOperationalData(id);