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;
26 import javax.annotation.concurrent.GuardedBy;
28 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
29 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
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.yangtools.yang.binding.DataContainer;
52 import org.opendaylight.yangtools.yang.binding.DataObject;
53 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 * Base class for PCEP topology providers. It handles the common tasks involved in managing a PCEP server (PCE)
59 * endpoint, and exposing a network topology based on it. It needs to be subclassed to form a fully functional block,
60 * where the subclass provides handling of incoming messages.
62 * @param <S> identifier type of requests
63 * @param <L> identifier type for LSPs
65 public abstract class AbstractTopologySessionListener<S, L> implements PCEPSessionListener, TopologySessionListener {
66 protected static final class MessageContext {
67 private final Collection<PCEPRequest> requests = new ArrayList<>();
68 private final WriteTransaction trans;
70 private MessageContext(final WriteTransaction trans) {
71 this.trans = Preconditions.checkNotNull(trans);
74 void resolveRequest(final PCEPRequest req) {
75 this.requests.add(req);
78 private void notifyRequests() {
79 for (final PCEPRequest r : this.requests) {
80 r.done(OperationResults.SUCCESS);
85 protected static final MessageHeader MESSAGE_HEADER = new MessageHeader() {
86 private final ProtocolVersion version = new ProtocolVersion((short) 1);
89 public Class<? extends DataContainer> getImplementedInterface() {
90 return MessageHeader.class;
94 public ProtocolVersion getVersion() {
98 private static final Logger LOG = LoggerFactory.getLogger(AbstractTopologySessionListener.class);
100 protected static final String MISSING_XML_TAG = "Mandatory XML tags are missing.";
103 private final Map<S, PCEPRequest> requests = new HashMap<>();
106 private final Map<String, ReportedLsp> lspData = new HashMap<>();
109 private final Map<L, String> lsps = new HashMap<>();
111 private final ServerSessionManager serverSessionManager;
112 private InstanceIdentifier<PathComputationClient> pccIdentifier;
113 private TopologyNodeState nodeState;
114 private boolean synced = false;
115 private PCEPSession session;
117 protected AbstractTopologySessionListener(final ServerSessionManager serverSessionManager) {
118 this.serverSessionManager = Preconditions.checkNotNull(serverSessionManager);
122 public final synchronized void onSessionUp(final PCEPSession session) {
124 * The session went up. Look up the router in Inventory model,
125 * create it if it is not there (marking that fact for later
126 * deletion), and mark it as synchronizing. Also create it in
127 * the topology model, with empty LSP list.
129 final InetAddress peerAddress = session.getRemoteAddress();
131 final TopologyNodeState state = serverSessionManager.takeNodeState(peerAddress, this);
133 session.close(TerminationReason.Unknown);
137 LOG.trace("Peer {} resolved to topology node {}", peerAddress, state.getNodeId());
140 // Our augmentation in the topology node
141 final PathComputationClientBuilder pccBuilder = new PathComputationClientBuilder();
142 pccBuilder.setIpAddress(IpAddressBuilder.getDefaultInstance(peerAddress.getHostAddress()));
144 onSessionUp(session, pccBuilder);
146 final Node1 ta = new Node1Builder().setPathComputationClient(pccBuilder.build()).build();
147 final InstanceIdentifier<Node1> topologyAugment = state.getNodeId().augmentation(Node1.class);
148 this.pccIdentifier = topologyAugment.child(PathComputationClient.class);
150 final ReadWriteTransaction trans = state.rwTransaction();
151 trans.put(LogicalDatastoreType.OPERATIONAL, topologyAugment, ta);
152 LOG.trace("Peer data {} set to {}", topologyAugment, ta);
154 // All set, commit the modifications
155 Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
157 public void onSuccess(final Void result) {
158 LOG.trace("Internal state for session {} updated successfully", session);
162 public void onFailure(final Throwable t) {
163 LOG.error("Failed to update internal state for session {}, terminating it", session, t);
164 session.close(TerminationReason.Unknown);
168 this.session = session;
169 this.nodeState = state;
170 LOG.info("Session with {} attached to topology node {}", session.getRemoteAddress(), state.getNodeId());
174 private void tearDown(final PCEPSession session) {
175 this.serverSessionManager.releaseNodeState(this.nodeState);
176 this.nodeState = null;
179 // Clear all requests we know about
180 for (final Entry<S, PCEPRequest> e : this.requests.entrySet()) {
181 final PCEPRequest r = e.getValue();
182 switch (r.getState()) {
184 // Done is done, nothing to do
187 // Peer has not acked: results in failure
188 LOG.info("Request {} was incomplete when session went down, failing the instruction", e.getKey());
189 r.done(OperationResults.NOACK);
192 // Peer has not been sent to the peer: results in cancellation
193 LOG.debug("Request {} was not sent when session went down, cancelling the instruction", e.getKey());
194 r.done(OperationResults.UNSENT);
198 this.requests.clear();
202 public final synchronized void onSessionDown(final PCEPSession session, final Exception e) {
203 LOG.warn("Session {} went down unexpectedly", session, e);
208 public final synchronized void onSessionTerminated(final PCEPSession session, final PCEPTerminationReason reason) {
209 LOG.info("Session {} terminated by peer with reason {}", session, reason);
214 public final synchronized void onMessage(final PCEPSession session, final Message message) {
215 final MessageContext ctx = new MessageContext(this.nodeState.beginTransaction());
217 if (onMessage(ctx, message)) {
218 LOG.info("Unhandled message {} on session {}", message, session);
222 Futures.addCallback(ctx.trans.submit(), new FutureCallback<Void>() {
224 public void onSuccess(final Void result) {
225 LOG.trace("Internal state for session {} updated successfully", session);
226 ctx.notifyRequests();
230 public void onFailure(final Throwable t) {
231 LOG.error("Failed to update internal state for session {}, closing it", session, t);
232 ctx.notifyRequests();
233 session.close(TerminationReason.Unknown);
239 public void close() {
240 if (this.session != null) {
241 this.session.close(TerminationReason.Unknown);
245 protected final synchronized PCEPRequest removeRequest(final S id) {
246 final PCEPRequest ret = this.requests.remove(id);
247 LOG.trace("Removed request {} object {}", id, ret);
251 protected final synchronized ListenableFuture<OperationResult> sendMessage(final Message message, final S requestId,
252 final Metadata metadata) {
253 final io.netty.util.concurrent.Future<Void> f = this.session.sendMessage(message);
254 final PCEPRequest req = new PCEPRequest(metadata);
255 this.requests.put(requestId, req);
257 f.addListener(new FutureListener<Void>() {
259 public void operationComplete(final io.netty.util.concurrent.Future<Void> future) {
260 if (!future.isSuccess()) {
261 synchronized (AbstractTopologySessionListener.this) {
262 AbstractTopologySessionListener.this.requests.remove(requestId);
264 req.done(OperationResults.UNSENT);
265 LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
268 LOG.trace("Request {} sent to peer (object {})", requestId, req);
273 return req.getFuture();
277 * Update an LSP in the data store
279 * @param ctx Message context
280 * @param id Revision-specific LSP identifier
281 * @param lspName LSP name
282 * @param rlb Reported LSP builder
283 * @param solicited True if the update was solicited
284 * @param remove True if this is an LSP path removal
286 protected final synchronized void updateLsp(final MessageContext ctx, final L id, final String lspName,
287 final ReportedLspBuilder rlb, final boolean solicited, final boolean remove) {
290 if (lspName == null) {
291 name = this.lsps.get(id);
293 LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
300 LOG.debug("Saved LSP {} with name {}", id, name);
301 this.lsps.put(id, name);
303 // just one path should be reported
304 Preconditions.checkState(rlb.getPath().size() == 1);
305 final LspId reportedLspId = rlb.getPath().get(0).getLspId();
306 // check previous report for existing paths
307 final ReportedLsp previous = this.lspData.get(name);
308 // if no previous report about the lsp exist, just proceed
309 if (previous != null) {
310 final List<Path> updatedPaths = new ArrayList<>(previous.getPath());
311 LOG.debug("Found previous paths {} to this lsp name {}", updatedPaths, name);
312 for (final Path path : previous.getPath()) {
313 //we found reported path in previous reports
314 if (path.getLspId().getValue() == 0 || path.getLspId().equals(reportedLspId)) {
315 LOG.debug("Match on lsp-id {}", path.getLspId().getValue() );
316 // path that was reported previously and does have the same lsp-id, path will be updated
317 final boolean r = updatedPaths.remove(path);
318 LOG.trace("Request removed? {}", r);
321 // if the path does not exist in previous report, add it to path list, it's a new ERO
322 // only one path will be added
323 //lspId is 0 means confirmation message that shouldn't be added (because we have no means of deleting it later)
324 LOG.trace("Adding new path {} to {}", rlb.getPath(), updatedPaths);
325 updatedPaths.addAll(rlb.getPath());
327 if (reportedLspId.getValue() == 0) {
328 // if lsp-id also 0, remove all paths
329 LOG.debug("Removing all paths.");
330 updatedPaths.clear();
332 // path is marked to be removed
333 LOG.debug("Removing path {} from {}", rlb.getPath(), updatedPaths);
334 final boolean r = updatedPaths.removeAll(rlb.getPath());
335 LOG.trace("Request removed? {}", r);
338 // if all paths or the last path were deleted, delete whole tunnel
339 if (updatedPaths.isEmpty()) {
340 LOG.debug("All paths were removed, removing LSP with {}.", id);
344 LOG.debug("Setting new paths {} to lsp {}", updatedPaths, name);
345 rlb.setPath(updatedPaths);
347 Preconditions.checkState(name != null);
348 rlb.setKey(new ReportedLspKey(name));
351 // If this is an unsolicited update. We need to make sure we retain the metadata already present
353 this.nodeState.setLspMetadata(name, rlb.getMetadata());
355 rlb.setMetadata(this.nodeState.getLspMetadata(name));
358 final ReportedLsp rl = rlb.build();
359 ctx.trans.put(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier.child(ReportedLsp.class, rlb.getKey()), rl);
360 LOG.debug("LSP {} updated to MD-SAL", name);
362 this.lspData.put(name, rl);
366 * Indicate that the peer has completed state synchronization.
368 * @param ctx Message context
370 protected final synchronized void stateSynchronizationAchieved(final MessageContext ctx) {
372 LOG.debug("State synchronization achieved while synchronized, not updating state");
376 // Update synchronization flag
378 ctx.trans.merge(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier, new PathComputationClientBuilder().setStateSync(PccSyncState.Synchronized).build());
380 // The node has completed synchronization, cleanup metadata no longer reported back
381 this.nodeState.cleanupExcept(this.lsps.values());
382 LOG.debug("Session {} achieved synchronized state", this.session);
385 protected final InstanceIdentifier<ReportedLsp> lspIdentifier(final String name) {
386 return this.pccIdentifier.child(ReportedLsp.class, new ReportedLspKey(name));
390 * Remove LSP from the database.
392 * @param ctx Message Context
393 * @param id Revision-specific LSP identifier
395 protected final synchronized void removeLsp(final MessageContext ctx, final L id) {
396 final String name = this.lsps.remove(id);
397 LOG.debug("LSP {} removed", name);
398 ctx.trans.delete(LogicalDatastoreType.OPERATIONAL, lspIdentifier(name));
399 this.lspData.remove(name);
402 protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
405 * Perform revision-specific message processing when a message arrives.
407 * @param ctx Message processing context
408 * @param message Protocol message
409 * @return True if the message type is not handle.
411 protected abstract boolean onMessage(MessageContext ctx, Message message);
413 protected final String lookupLspName(final L id) {
414 Preconditions.checkNotNull(id, "ID parameter null.");
415 return this.lsps.get(id);
418 protected synchronized final <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(final InstanceIdentifier<T> id) {
419 return this.nodeState.readOperationalData(id);