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 javax.annotation.concurrent.GuardedBy;
24 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
25 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
26 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
27 import org.opendaylight.protocol.pcep.PCEPSession;
28 import org.opendaylight.protocol.pcep.PCEPSessionListener;
29 import org.opendaylight.protocol.pcep.PCEPTerminationReason;
30 import org.opendaylight.protocol.pcep.TerminationReason;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddressBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.MessageHeader;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Object;
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.topology.pcep.rev131024.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.yangtools.yang.binding.DataContainer;
49 import org.opendaylight.yangtools.yang.binding.DataObject;
50 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
55 * Base class for PCEP topology providers. It handles the common tasks involved in managing a PCEP server (PCE)
56 * endpoint, and exposing a network topology based on it. It needs to be subclassed to form a fully functional block,
57 * where the subclass provides handling of incoming messages.
59 * @param <S> identifier type of requests
60 * @param <L> identifier type for LSPs
62 public abstract class AbstractTopologySessionListener<S, L> implements PCEPSessionListener, TopologySessionListener {
63 protected static final class MessageContext {
64 private final Collection<PCEPRequest> requests = new ArrayList<>();
65 private final WriteTransaction trans;
67 private MessageContext(final WriteTransaction trans) {
68 this.trans = Preconditions.checkNotNull(trans);
71 void resolveRequest(final PCEPRequest req) {
72 this.requests.add(req);
75 private void notifyRequests() {
76 for (final PCEPRequest r : this.requests) {
77 r.done(OperationResults.SUCCESS);
82 protected static final MessageHeader MESSAGE_HEADER = new MessageHeader() {
83 private final ProtocolVersion version = new ProtocolVersion((short) 1);
86 public Class<? extends DataContainer> getImplementedInterface() {
87 return MessageHeader.class;
91 public ProtocolVersion getVersion() {
95 private static final Logger LOG = LoggerFactory.getLogger(AbstractTopologySessionListener.class);
97 protected static final String MISSING_XML_TAG = "Mandatory XML tags are missing.";
100 private final Map<S, PCEPRequest> requests = new HashMap<>();
103 private final Map<String, ReportedLsp> lspData = new HashMap<>();
106 private final Map<L, String> lsps = new HashMap<>();
108 private final ServerSessionManager serverSessionManager;
109 private InstanceIdentifier<PathComputationClient> pccIdentifier;
110 private TopologyNodeState nodeState;
111 private boolean synced = false;
112 private PCEPSession session;
114 protected AbstractTopologySessionListener(final ServerSessionManager serverSessionManager) {
115 this.serverSessionManager = Preconditions.checkNotNull(serverSessionManager);
119 public final synchronized void onSessionUp(final PCEPSession session) {
121 * The session went up. Look up the router in Inventory model,
122 * create it if it is not there (marking that fact for later
123 * deletion), and mark it as synchronizing. Also create it in
124 * the topology model, with empty LSP list.
126 final InetAddress peerAddress = session.getRemoteAddress();
128 final TopologyNodeState state = this.serverSessionManager.takeNodeState(peerAddress, this);
130 LOG.trace("Peer {} resolved to topology node {}", peerAddress, state.getNodeId());
133 // Our augmentation in the topology node
134 final PathComputationClientBuilder pccBuilder = new PathComputationClientBuilder();
135 pccBuilder.setIpAddress(IpAddressBuilder.getDefaultInstance(peerAddress.getHostAddress()));
137 onSessionUp(session, pccBuilder);
139 final Node1 ta = new Node1Builder().setPathComputationClient(pccBuilder.build()).build();
140 final InstanceIdentifier<Node1> topologyAugment = state.getNodeId().augmentation(Node1.class);
141 this.pccIdentifier = topologyAugment.child(PathComputationClient.class);
143 final ReadWriteTransaction trans = state.rwTransaction();
144 trans.put(LogicalDatastoreType.OPERATIONAL, topologyAugment, ta);
145 LOG.trace("Peer data {} set to {}", topologyAugment, ta);
147 // All set, commit the modifications
148 Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
150 public void onSuccess(final Void result) {
151 LOG.trace("Internal state for session {} updated successfully", session);
155 public void onFailure(final Throwable t) {
156 LOG.error("Failed to update internal state for session {}, terminating it", session, t);
157 session.close(TerminationReason.Unknown);
161 this.session = session;
162 this.nodeState = state;
163 LOG.info("Session with {} attached to topology node {}", session.getRemoteAddress(), state.getNodeId());
167 private void tearDown(final PCEPSession session) {
168 this.serverSessionManager.releaseNodeState(this.nodeState, session);
169 this.nodeState = null;
172 // Clear all requests we know about
173 for (final Entry<S, PCEPRequest> e : this.requests.entrySet()) {
174 final PCEPRequest r = e.getValue();
175 switch (r.getState()) {
177 // Done is done, nothing to do
180 // Peer has not acked: results in failure
181 LOG.info("Request {} was incomplete when session went down, failing the instruction", e.getKey());
182 r.done(OperationResults.NOACK);
185 // Peer has not been sent to the peer: results in cancellation
186 LOG.debug("Request {} was not sent when session went down, cancelling the instruction", e.getKey());
187 r.done(OperationResults.UNSENT);
191 this.requests.clear();
195 public final synchronized void onSessionDown(final PCEPSession session, final Exception e) {
196 LOG.warn("Session {} went down unexpectedly", session, e);
201 public final synchronized void onSessionTerminated(final PCEPSession session, final PCEPTerminationReason reason) {
202 LOG.info("Session {} terminated by peer with reason {}", session, reason);
207 public final synchronized void onMessage(final PCEPSession session, final Message message) {
208 final MessageContext ctx = new MessageContext(this.nodeState.beginTransaction());
210 if (onMessage(ctx, message)) {
211 LOG.info("Unhandled message {} on session {}", message, session);
215 Futures.addCallback(ctx.trans.submit(), new FutureCallback<Void>() {
217 public void onSuccess(final Void result) {
218 LOG.trace("Internal state for session {} updated successfully", session);
219 ctx.notifyRequests();
223 public void onFailure(final Throwable t) {
224 LOG.error("Failed to update internal state for session {}, closing it", session, t);
225 ctx.notifyRequests();
226 session.close(TerminationReason.Unknown);
232 public void close() {
233 if (this.session != null) {
234 this.session.close(TerminationReason.Unknown);
238 protected final synchronized PCEPRequest removeRequest(final S id) {
239 final PCEPRequest ret = this.requests.remove(id);
240 LOG.trace("Removed request {} object {}", id, ret);
244 protected final synchronized ListenableFuture<OperationResult> sendMessage(final Message message, final S requestId,
245 final Metadata metadata) {
246 final io.netty.util.concurrent.Future<Void> f = this.session.sendMessage(message);
247 final PCEPRequest req = new PCEPRequest(metadata);
248 this.requests.put(requestId, req);
250 f.addListener(new FutureListener<Void>() {
252 public void operationComplete(final io.netty.util.concurrent.Future<Void> future) {
253 if (!future.isSuccess()) {
254 synchronized (AbstractTopologySessionListener.this) {
255 AbstractTopologySessionListener.this.requests.remove(requestId);
257 req.done(OperationResults.UNSENT);
258 LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
261 LOG.trace("Request {} sent to peer (object {})", requestId, req);
266 return req.getFuture();
270 * Update an LSP in the data store
272 * @param ctx Message context
273 * @param id Revision-specific LSP identifier
274 * @param lspName LSP name
275 * @param rlb Reported LSP builder
276 * @param solicited True if the update was solicited
277 * @param remove True if this is an LSP path removal
279 protected final synchronized void updateLsp(final MessageContext ctx, final L id, final String lspName,
280 final ReportedLspBuilder rlb, final boolean solicited, final boolean remove) {
283 if (lspName == null) {
284 name = this.lsps.get(id);
286 LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
293 LOG.debug("Saved LSP {} with name {}", id, name);
294 this.lsps.put(id, name);
297 final ReportedLsp previous = this.lspData.get(name);
298 // if no previous report about the lsp exist, just proceed
299 if (previous != null) {
300 final List<Path> updatedPaths = makeBeforeBreak(rlb, previous, name, remove);
301 // if all paths or the last path were deleted, delete whole tunnel
302 if (updatedPaths == null || updatedPaths.isEmpty()) {
303 LOG.debug("All paths were removed, removing LSP with {}.", id);
307 rlb.setPath(updatedPaths);
309 rlb.setKey(new ReportedLspKey(name));
312 // If this is an unsolicited update. We need to make sure we retain the metadata already present
314 this.nodeState.setLspMetadata(name, rlb.getMetadata());
316 rlb.setMetadata(this.nodeState.getLspMetadata(name));
319 final ReportedLsp rl = rlb.build();
320 ctx.trans.put(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier.child(ReportedLsp.class, rlb.getKey()), rl);
321 LOG.debug("LSP {} updated to MD-SAL", name);
323 this.lspData.put(name, rl);
326 private List<Path> makeBeforeBreak(final ReportedLspBuilder rlb, final ReportedLsp previous, final String name, final boolean remove) {
327 // just one path should be reported
328 Preconditions.checkState(rlb.getPath().size() == 1);
329 final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev130820.LspId reportedLspId = rlb.getPath().get(0).getLspId();
330 // check previous report for existing paths
331 final List<Path> updatedPaths = new ArrayList<>(previous.getPath());
332 LOG.debug("Found previous paths {} to this lsp name {}", updatedPaths, name);
333 for (final Path path : previous.getPath()) {
334 //we found reported path in previous reports
335 if (path.getLspId().getValue() == 0 || path.getLspId().equals(reportedLspId)) {
336 LOG.debug("Match on lsp-id {}", path.getLspId().getValue() );
337 // path that was reported previously and does have the same lsp-id, path will be updated
338 final boolean r = updatedPaths.remove(path);
339 LOG.trace("Request removed? {}", r);
342 // if the path does not exist in previous report, add it to path list, it's a new ERO
343 // only one path will be added
344 //lspId is 0 means confirmation message that shouldn't be added (because we have no means of deleting it later)
345 LOG.trace("Adding new path {} to {}", rlb.getPath(), updatedPaths);
346 updatedPaths.addAll(rlb.getPath());
348 if (reportedLspId.getValue() == 0) {
349 // if lsp-id also 0, remove all paths
350 LOG.debug("Removing all paths.");
351 updatedPaths.clear();
353 // path is marked to be removed
354 LOG.debug("Removing path {} from {}", rlb.getPath(), updatedPaths);
355 final boolean r = updatedPaths.removeAll(rlb.getPath());
356 LOG.trace("Request removed? {}", r);
359 LOG.debug("Setting new paths {} to lsp {}", updatedPaths, name);
364 * Indicate that the peer has completed state synchronization.
366 * @param ctx Message context
368 protected final synchronized void stateSynchronizationAchieved(final MessageContext ctx) {
370 LOG.debug("State synchronization achieved while synchronized, not updating state");
374 // Update synchronization flag
376 ctx.trans.merge(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier, new PathComputationClientBuilder().setStateSync(PccSyncState.Synchronized).build());
378 // The node has completed synchronization, cleanup metadata no longer reported back
379 this.nodeState.cleanupExcept(this.lsps.values());
380 LOG.debug("Session {} achieved synchronized state", this.session);
383 protected final InstanceIdentifier<ReportedLsp> lspIdentifier(final String name) {
384 return this.pccIdentifier.child(ReportedLsp.class, new ReportedLspKey(name));
388 * Remove LSP from the database.
390 * @param ctx Message Context
391 * @param id Revision-specific LSP identifier
393 protected final synchronized void removeLsp(final MessageContext ctx, final L id) {
394 final String name = this.lsps.remove(id);
395 LOG.debug("LSP {} removed", name);
396 ctx.trans.delete(LogicalDatastoreType.OPERATIONAL, lspIdentifier(name));
397 this.lspData.remove(name);
400 protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
403 * Perform revision-specific message processing when a message arrives.
405 * @param ctx Message processing context
406 * @param message Protocol message
407 * @return True if the message type is not handle.
409 protected abstract boolean onMessage(MessageContext ctx, Message message);
411 protected final String lookupLspName(final L id) {
412 Preconditions.checkNotNull(id, "ID parameter null.");
413 return this.lsps.get(id);
416 protected final synchronized <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(final InstanceIdentifier<T> id) {
417 return this.nodeState.readOperationalData(id);
420 protected abstract Object validateReportedLsp(final Optional<ReportedLsp> rep, final LspId input);