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;
16 import io.netty.util.concurrent.FutureListener;
18 import java.net.InetAddress;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.HashMap;
22 import java.util.List;
24 import java.util.Map.Entry;
25 import java.util.concurrent.ExecutionException;
27 import javax.annotation.concurrent.GuardedBy;
29 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
30 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
31 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
32 import org.opendaylight.protocol.pcep.PCEPSession;
33 import org.opendaylight.protocol.pcep.PCEPSessionListener;
34 import org.opendaylight.protocol.pcep.PCEPTerminationReason;
35 import org.opendaylight.protocol.pcep.TerminationReason;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddressBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.MessageHeader;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.ProtocolVersion;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev130820.LspId;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1Builder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.OperationResult;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.PccSyncState;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.lsp.metadata.Metadata;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClient;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClientBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLsp;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLspBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLspKey;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.reported.lsp.Path;
52 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
53 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
54 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
55 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
56 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
57 import org.opendaylight.yangtools.yang.binding.DataContainer;
58 import org.opendaylight.yangtools.yang.binding.DataObject;
59 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
64 * Base class for PCEP topology providers. It handles the common tasks involved in managing a PCEP server (PCE)
65 * endpoint, and exposing a network topology based on it. It needs to be subclassed to form a fully functional block,
66 * where the subclass provides handling of incoming messages.
68 * @param <S> identifier type of requests
69 * @param <L> identifier type for LSPs
71 public abstract class AbstractTopologySessionListener<S, L> implements PCEPSessionListener, TopologySessionListener {
72 protected static final class MessageContext {
73 private final Collection<PCEPRequest> requests = new ArrayList<>();
74 private final WriteTransaction trans;
76 private MessageContext(final WriteTransaction trans) {
77 this.trans = Preconditions.checkNotNull(trans);
80 void resolveRequest(final PCEPRequest req) {
84 private void notifyRequests() {
85 for (PCEPRequest r : requests) {
86 r.done(OperationResults.SUCCESS);
91 protected static final MessageHeader MESSAGE_HEADER = new MessageHeader() {
92 private final ProtocolVersion version = new ProtocolVersion((short) 1);
95 public Class<? extends DataContainer> getImplementedInterface() {
96 return MessageHeader.class;
100 public ProtocolVersion getVersion() {
104 private static final Logger LOG = LoggerFactory.getLogger(AbstractTopologySessionListener.class);
106 private final Map<S, PCEPRequest> requests = new HashMap<>();
107 private final Map<String, ReportedLsp> lspData = new HashMap<>();
108 private final Map<L, String> lsps = new HashMap<>();
109 private final ServerSessionManager serverSessionManager;
110 private InstanceIdentifier<Node> topologyNode;
111 private InstanceIdentifier<Node1> topologyAugment;
112 private InstanceIdentifier<PathComputationClient> pccIdentifier;
113 private TopologyNodeState nodeState;
114 private boolean ownsTopology = false;
115 private boolean synced = false;
116 private PCEPSession session;
118 protected AbstractTopologySessionListener(final ServerSessionManager serverSessionManager) {
119 this.serverSessionManager = Preconditions.checkNotNull(serverSessionManager);
122 private static String createNodeId(final InetAddress addr) {
123 return "pcc://" + addr.getHostAddress();
126 private Node topologyNode(final ReadWriteTransaction trans, final InetAddress address) {
127 final String pccId = createNodeId(address);
129 // FIXME: Futures.transform...
131 Optional<Topology> topoMaybe = trans.read(LogicalDatastoreType.OPERATIONAL, this.serverSessionManager.getTopology()).get();
132 Preconditions.checkState(topoMaybe.isPresent(), "Failed to find topology.");
133 final Topology topo = topoMaybe.get();
134 for (final Node n : topo.getNode()) {
135 LOG.debug("Matching topology node {} to id {}", n, pccId);
136 if (n.getNodeId().getValue().equals(pccId)) {
137 this.topologyNode = this.serverSessionManager.getTopology().child(Node.class, n.getKey());
138 LOG.debug("Reusing topology node {} for id {} at {}", n, pccId, this.topologyNode);
142 } catch (InterruptedException | ExecutionException e) {
143 throw new IllegalStateException("Failed to ensure topology presence.", e);
147 * We failed to find a matching node. Let's create a dynamic one
148 * and note that we are the owner (so we clean it up afterwards).
150 final NodeId id = new NodeId(pccId);
151 final NodeKey nk = new NodeKey(id);
152 final InstanceIdentifier<Node> nti = this.serverSessionManager.getTopology().child(Node.class, nk);
154 final Node ret = new NodeBuilder().setKey(nk).setNodeId(id).build();
156 trans.put(LogicalDatastoreType.OPERATIONAL, nti, ret);
157 LOG.debug("Created topology node {} for id {} at {}", ret, pccId, nti);
158 this.ownsTopology = true;
159 this.topologyNode = nti;
164 public final synchronized void onSessionUp(final PCEPSession session) {
166 * The session went up. Look up the router in Inventory model,
167 * create it if it is not there (marking that fact for later
168 * deletion), and mark it as synchronizing. Also create it in
169 * the topology model, with empty LSP list.
171 final InetAddress peerAddress = session.getRemoteAddress();
172 final ReadWriteTransaction trans = this.serverSessionManager.rwTransaction();
174 final Node topoNode = topologyNode(trans, peerAddress);
175 LOG.trace("Peer {} resolved to topology node {}", peerAddress, topoNode);
177 // Our augmentation in the topology node
180 final PathComputationClientBuilder pccBuilder;
181 pccBuilder = new PathComputationClientBuilder();
182 pccBuilder.setIpAddress(IpAddressBuilder.getDefaultInstance(peerAddress.getHostAddress()));
184 onSessionUp(session, pccBuilder);
186 final Node1 ta = new Node1Builder().setPathComputationClient(pccBuilder.build()).build();
188 this.topologyAugment = this.topologyNode.augmentation(Node1.class);
189 this.pccIdentifier = topologyAugment.child(PathComputationClient.class);
191 trans.put(LogicalDatastoreType.OPERATIONAL, this.topologyAugment, ta);
192 LOG.trace("Peer data {} set to {}", this.topologyAugment, ta);
194 // All set, commit the modifications
195 Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
197 public void onSuccess(final Void result) {
198 LOG.trace("Internal state for session {} updated successfully", session);
202 public void onFailure(final Throwable t) {
203 LOG.error("Failed to update internal state for session {}, terminating it", session, t);
204 session.close(TerminationReason.Unknown);
208 this.nodeState = this.serverSessionManager.takeNodeState(topoNode.getNodeId(), this);
209 this.session = session;
210 LOG.info("Session with {} attached to topology node {}", session.getRemoteAddress(), topoNode.getNodeId());
214 private void tearDown(final PCEPSession session) {
215 this.serverSessionManager.releaseNodeState(this.nodeState);
216 this.nodeState = null;
219 // The session went down. Undo all the Topology changes we have done.
220 final WriteTransaction trans = this.serverSessionManager.beginTransaction();
221 trans.delete(LogicalDatastoreType.OPERATIONAL, this.topologyAugment);
222 if (this.ownsTopology) {
223 trans.delete(LogicalDatastoreType.OPERATIONAL, this.topologyNode);
226 Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
228 public void onSuccess(final Void result) {
229 LOG.trace("Internal state for session {} cleaned up successfully", session);
233 public void onFailure(final Throwable t) {
234 LOG.error("Failed to cleanup internal state for session {}", session, t);
238 // Clear all requests we know about
239 for (final Entry<S, PCEPRequest> e : this.requests.entrySet()) {
240 final PCEPRequest r = e.getValue();
241 switch (r.getState()) {
243 // Done is done, nothing to do
246 // Peer has not acked: results in failure
247 LOG.info("Request {} was incomplete when session went down, failing the instruction", e.getKey());
248 r.done(OperationResults.NOACK);
251 // Peer has not been sent to the peer: results in cancellation
252 LOG.debug("Request {} was not sent when session went down, cancelling the instruction", e.getKey());
253 r.done(OperationResults.UNSENT);
257 this.requests.clear();
261 public final synchronized void onSessionDown(final PCEPSession session, final Exception e) {
262 LOG.warn("Session {} went down unexpectedly", session, e);
267 public final synchronized void onSessionTerminated(final PCEPSession session, final PCEPTerminationReason reason) {
268 LOG.info("Session {} terminated by peer with reason {}", session, reason);
273 public final synchronized void onMessage(final PCEPSession session, final Message message) {
274 final MessageContext ctx = new MessageContext(this.serverSessionManager.beginTransaction());
276 if (onMessage(ctx, message)) {
277 LOG.info("Unhandled message {} on session {}", message, session);
281 Futures.addCallback(ctx.trans.submit(), new FutureCallback<Void>() {
283 public void onSuccess(final Void result) {
284 LOG.trace("Internal state for session {} updated successfully", session);
285 ctx.notifyRequests();
289 public void onFailure(final Throwable t) {
290 LOG.error("Failed to update internal state for session {}, closing it", session, t);
291 ctx.notifyRequests();
292 session.close(TerminationReason.Unknown);
298 public void close() {
299 if (this.session != null) {
300 this.session.close(TerminationReason.Unknown);
304 protected final synchronized PCEPRequest removeRequest(final S id) {
305 final PCEPRequest ret = this.requests.remove(id);
306 LOG.trace("Removed request {} object {}", id, ret);
310 protected final synchronized ListenableFuture<OperationResult> sendMessage(final Message message, final S requestId,
311 final Metadata metadata) {
312 final io.netty.util.concurrent.Future<Void> f = this.session.sendMessage(message);
313 final PCEPRequest req = new PCEPRequest(metadata);
314 this.requests.put(requestId, req);
316 f.addListener(new FutureListener<Void>() {
318 public void operationComplete(final io.netty.util.concurrent.Future<Void> future) {
319 if (!future.isSuccess()) {
320 synchronized (AbstractTopologySessionListener.this) {
321 requests.remove(requestId);
323 req.done(OperationResults.UNSENT);
324 LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
327 LOG.trace("Request {} sent to peer (object {})", requestId, req);
332 return req.getFuture();
336 * Update an LSP in the data store
338 * @param ctx Message context
339 * @param id Revision-specific LSP identifier
340 * @param lspName LSP name
341 * @param rlb Reported LSP builder
342 * @param solicited True if the update was solicited
343 * @param remove True if this is an LSP path removal
345 protected final synchronized void updateLsp(final MessageContext ctx, final L id, final String lspName,
346 final ReportedLspBuilder rlb, final boolean solicited, final boolean remove) {
349 if (lspName == null) {
350 name = this.lsps.get(id);
352 LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
359 LOG.debug("Saved LSP {} with name {}", id, name);
360 this.lsps.put(id, name);
362 // just one path should be reported
363 Preconditions.checkState(rlb.getPath().size() == 1);
364 LspId reportedLspId = rlb.getPath().get(0).getLspId();
365 // check previous report for existing paths
366 ReportedLsp previous = this.lspData.get(name);
367 // if no previous report about the lsp exist, just proceed
368 if (previous != null) {
369 List<Path> updatedPaths = new ArrayList<>(previous.getPath());
370 LOG.debug("Found previous paths {} to this lsp name {}", updatedPaths, name);
371 for (Path path : previous.getPath()) {
372 //we found reported path in previous reports
373 if (path.getLspId().getValue() == 0 || path.getLspId().equals(reportedLspId)) {
374 LOG.debug("Match on lsp-id {}", path.getLspId().getValue() );
375 // path that was reported previously and does have the same lsp-id, path will be updated
376 final boolean r = updatedPaths.remove(path);
377 LOG.trace("Request removed? {}", r);
380 // if the path does not exist in previous report, add it to path list, it's a new ERO
381 // only one path will be added
382 //lspId is 0 means confirmation message that shouldn't be added (because we have no means of deleting it later)
383 LOG.trace("Adding new path {} to {}", rlb.getPath(), updatedPaths);
384 updatedPaths.addAll(rlb.getPath());
386 if (reportedLspId.getValue() == 0) {
387 // if lsp-id also 0, remove all paths
388 LOG.debug("Removing all paths.");
389 updatedPaths.clear();
391 // path is marked to be removed
392 LOG.debug("Removing path {} from {}", rlb.getPath(), updatedPaths);
393 final boolean r = updatedPaths.removeAll(rlb.getPath());
394 LOG.trace("Request removed? {}", r);
397 // if all paths or the last path were deleted, delete whole tunnel
398 if (updatedPaths.isEmpty()) {
399 LOG.debug("All paths were removed, removing LSP with {}.", id);
403 LOG.debug("Setting new paths {} to lsp {}", updatedPaths, name);
404 rlb.setPath(updatedPaths);
406 Preconditions.checkState(name != null);
407 rlb.setKey(new ReportedLspKey(name));
410 // If this is an unsolicited update. We need to make sure we retain the metadata already present
412 this.nodeState.setLspMetadata(name, rlb.getMetadata());
414 rlb.setMetadata(this.nodeState.getLspMetadata(name));
417 final ReportedLsp rl = rlb.build();
418 ctx.trans.put(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier.child(ReportedLsp.class, rlb.getKey()), rl);
419 LOG.debug("LSP {} updated to MD-SAL", name);
421 this.lspData.put(name, rl);
425 * Indicate that the peer has completed state synchronization.
427 * @param ctx Message context
429 protected final synchronized void stateSynchronizationAchieved(final MessageContext ctx) {
431 LOG.debug("State synchronization achieved while synchronized, not updating state");
435 // Update synchronization flag
437 ctx.trans.merge(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier, new PathComputationClientBuilder().setStateSync(PccSyncState.Synchronized).build());
439 // The node has completed synchronization, cleanup metadata no longer reported back
440 this.nodeState.cleanupExcept(this.lsps.values());
441 LOG.debug("Session {} achieved synchronized state", this.session);
444 protected final InstanceIdentifier<ReportedLsp> lspIdentifier(final String name) {
445 return pccIdentifier.child(ReportedLsp.class, new ReportedLspKey(name));
449 * Remove LSP from the database.
451 * @param ctx Message Context
452 * @param id Revision-specific LSP identifier
454 protected final synchronized void removeLsp(final MessageContext ctx, final L id) {
455 final String name = this.lsps.remove(id);
456 LOG.debug("LSP {} removed", name);
457 ctx.trans.delete(LogicalDatastoreType.OPERATIONAL, lspIdentifier(name));
458 this.lspData.remove(name);
461 protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
464 * Perform revision-specific message processing when a message arrives.
466 * @param ctx Message processing context
467 * @param message Protocol message
468 * @return True if the message type is not handle.
470 protected abstract boolean onMessage(MessageContext ctx, Message message);
472 protected final String lookupLspName(final L id) {
473 Preconditions.checkNotNull(id, "ID parameter null.");
474 return this.lsps.get(id);
477 protected final <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(final InstanceIdentifier<T> id) {
478 return this.serverSessionManager.readOperationalData(id);