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.ProtocolVersion;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev130820.LspId;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1Builder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.OperationResult;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.PccSyncState;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.lsp.metadata.Metadata;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClient;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClientBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLsp;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLspBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLspKey;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.reported.lsp.Path;
47 import org.opendaylight.yangtools.yang.binding.DataContainer;
48 import org.opendaylight.yangtools.yang.binding.DataObject;
49 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * Base class for PCEP topology providers. It handles the common tasks involved in managing a PCEP server (PCE)
55 * endpoint, and exposing a network topology based on it. It needs to be subclassed to form a fully functional block,
56 * where the subclass provides handling of incoming messages.
58 * @param <S> identifier type of requests
59 * @param <L> identifier type for LSPs
61 public abstract class AbstractTopologySessionListener<S, L> implements PCEPSessionListener, TopologySessionListener {
62 protected static final class MessageContext {
63 private final Collection<PCEPRequest> requests = new ArrayList<>();
64 private final WriteTransaction trans;
66 private MessageContext(final WriteTransaction trans) {
67 this.trans = Preconditions.checkNotNull(trans);
70 void resolveRequest(final PCEPRequest req) {
71 this.requests.add(req);
74 private void notifyRequests() {
75 for (final PCEPRequest r : this.requests) {
76 r.done(OperationResults.SUCCESS);
81 protected static final MessageHeader MESSAGE_HEADER = new MessageHeader() {
82 private final ProtocolVersion version = new ProtocolVersion((short) 1);
85 public Class<? extends DataContainer> getImplementedInterface() {
86 return MessageHeader.class;
90 public ProtocolVersion getVersion() {
94 private static final Logger LOG = LoggerFactory.getLogger(AbstractTopologySessionListener.class);
96 protected static final String MISSING_XML_TAG = "Mandatory XML tags are missing.";
99 private final Map<S, PCEPRequest> requests = new HashMap<>();
102 private final Map<String, ReportedLsp> lspData = new HashMap<>();
105 private final Map<L, String> lsps = new HashMap<>();
107 private final ServerSessionManager serverSessionManager;
108 private InstanceIdentifier<PathComputationClient> pccIdentifier;
109 private TopologyNodeState nodeState;
110 private boolean synced = false;
111 private PCEPSession session;
113 protected AbstractTopologySessionListener(final ServerSessionManager serverSessionManager) {
114 this.serverSessionManager = Preconditions.checkNotNull(serverSessionManager);
118 public final synchronized void onSessionUp(final PCEPSession session) {
120 * The session went up. Look up the router in Inventory model,
121 * create it if it is not there (marking that fact for later
122 * deletion), and mark it as synchronizing. Also create it in
123 * the topology model, with empty LSP list.
125 final InetAddress peerAddress = session.getRemoteAddress();
127 final TopologyNodeState state = this.serverSessionManager.takeNodeState(peerAddress, this);
129 LOG.trace("Peer {} resolved to topology node {}", peerAddress, state.getNodeId());
132 // Our augmentation in the topology node
133 final PathComputationClientBuilder pccBuilder = new PathComputationClientBuilder();
134 pccBuilder.setIpAddress(IpAddressBuilder.getDefaultInstance(peerAddress.getHostAddress()));
136 onSessionUp(session, pccBuilder);
138 final Node1 ta = new Node1Builder().setPathComputationClient(pccBuilder.build()).build();
139 final InstanceIdentifier<Node1> topologyAugment = state.getNodeId().augmentation(Node1.class);
140 this.pccIdentifier = topologyAugment.child(PathComputationClient.class);
142 final ReadWriteTransaction trans = state.rwTransaction();
143 trans.put(LogicalDatastoreType.OPERATIONAL, topologyAugment, ta);
144 LOG.trace("Peer data {} set to {}", topologyAugment, ta);
146 // All set, commit the modifications
147 Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
149 public void onSuccess(final Void result) {
150 LOG.trace("Internal state for session {} updated successfully", session);
154 public void onFailure(final Throwable t) {
155 LOG.error("Failed to update internal state for session {}, terminating it", session, t);
156 session.close(TerminationReason.Unknown);
160 this.session = session;
161 this.nodeState = state;
162 LOG.info("Session with {} attached to topology node {}", session.getRemoteAddress(), state.getNodeId());
166 private void tearDown(final PCEPSession session) {
167 this.serverSessionManager.releaseNodeState(this.nodeState, session);
168 this.nodeState = null;
171 // Clear all requests we know about
172 for (final Entry<S, PCEPRequest> e : this.requests.entrySet()) {
173 final PCEPRequest r = e.getValue();
174 switch (r.getState()) {
176 // Done is done, nothing to do
179 // Peer has not acked: results in failure
180 LOG.info("Request {} was incomplete when session went down, failing the instruction", e.getKey());
181 r.done(OperationResults.NOACK);
184 // Peer has not been sent to the peer: results in cancellation
185 LOG.debug("Request {} was not sent when session went down, cancelling the instruction", e.getKey());
186 r.done(OperationResults.UNSENT);
190 this.requests.clear();
194 public final synchronized void onSessionDown(final PCEPSession session, final Exception e) {
195 LOG.warn("Session {} went down unexpectedly", session, e);
200 public final synchronized void onSessionTerminated(final PCEPSession session, final PCEPTerminationReason reason) {
201 LOG.info("Session {} terminated by peer with reason {}", session, reason);
206 public final synchronized void onMessage(final PCEPSession session, final Message message) {
207 final MessageContext ctx = new MessageContext(this.nodeState.beginTransaction());
209 if (onMessage(ctx, message)) {
210 LOG.info("Unhandled message {} on session {}", message, session);
214 Futures.addCallback(ctx.trans.submit(), new FutureCallback<Void>() {
216 public void onSuccess(final Void result) {
217 LOG.trace("Internal state for session {} updated successfully", session);
218 ctx.notifyRequests();
222 public void onFailure(final Throwable t) {
223 LOG.error("Failed to update internal state for session {}, closing it", session, t);
224 ctx.notifyRequests();
225 session.close(TerminationReason.Unknown);
231 public void close() {
232 if (this.session != null) {
233 this.session.close(TerminationReason.Unknown);
237 protected final synchronized PCEPRequest removeRequest(final S id) {
238 final PCEPRequest ret = this.requests.remove(id);
239 LOG.trace("Removed request {} object {}", id, ret);
243 protected final synchronized ListenableFuture<OperationResult> sendMessage(final Message message, final S requestId,
244 final Metadata metadata) {
245 final io.netty.util.concurrent.Future<Void> f = this.session.sendMessage(message);
246 final PCEPRequest req = new PCEPRequest(metadata);
247 this.requests.put(requestId, req);
249 f.addListener(new FutureListener<Void>() {
251 public void operationComplete(final io.netty.util.concurrent.Future<Void> future) {
252 if (!future.isSuccess()) {
253 synchronized (AbstractTopologySessionListener.this) {
254 AbstractTopologySessionListener.this.requests.remove(requestId);
256 req.done(OperationResults.UNSENT);
257 LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
260 LOG.trace("Request {} sent to peer (object {})", requestId, req);
265 return req.getFuture();
269 * Update an LSP in the data store
271 * @param ctx Message context
272 * @param id Revision-specific LSP identifier
273 * @param lspName LSP name
274 * @param rlb Reported LSP builder
275 * @param solicited True if the update was solicited
276 * @param remove True if this is an LSP path removal
278 protected final synchronized void updateLsp(final MessageContext ctx, final L id, final String lspName,
279 final ReportedLspBuilder rlb, final boolean solicited, final boolean remove) {
282 if (lspName == null) {
283 name = this.lsps.get(id);
285 LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
292 LOG.debug("Saved LSP {} with name {}", id, name);
293 this.lsps.put(id, name);
295 // just one path should be reported
296 Preconditions.checkState(rlb.getPath().size() == 1);
297 final LspId reportedLspId = rlb.getPath().get(0).getLspId();
298 // check previous report for existing paths
299 final ReportedLsp previous = this.lspData.get(name);
300 // if no previous report about the lsp exist, just proceed
301 if (previous != null) {
302 final List<Path> updatedPaths = new ArrayList<>(previous.getPath());
303 LOG.debug("Found previous paths {} to this lsp name {}", updatedPaths, name);
304 for (final Path path : previous.getPath()) {
305 //we found reported path in previous reports
306 if (path.getLspId().getValue() == 0 || path.getLspId().equals(reportedLspId)) {
307 LOG.debug("Match on lsp-id {}", path.getLspId().getValue() );
308 // path that was reported previously and does have the same lsp-id, path will be updated
309 final boolean r = updatedPaths.remove(path);
310 LOG.trace("Request removed? {}", r);
313 // if the path does not exist in previous report, add it to path list, it's a new ERO
314 // only one path will be added
315 //lspId is 0 means confirmation message that shouldn't be added (because we have no means of deleting it later)
316 LOG.trace("Adding new path {} to {}", rlb.getPath(), updatedPaths);
317 updatedPaths.addAll(rlb.getPath());
319 if (reportedLspId.getValue() == 0) {
320 // if lsp-id also 0, remove all paths
321 LOG.debug("Removing all paths.");
322 updatedPaths.clear();
324 // path is marked to be removed
325 LOG.debug("Removing path {} from {}", rlb.getPath(), updatedPaths);
326 final boolean r = updatedPaths.removeAll(rlb.getPath());
327 LOG.trace("Request removed? {}", r);
330 // if all paths or the last path were deleted, delete whole tunnel
331 if (updatedPaths.isEmpty()) {
332 LOG.debug("All paths were removed, removing LSP with {}.", id);
336 LOG.debug("Setting new paths {} to lsp {}", updatedPaths, name);
337 rlb.setPath(updatedPaths);
339 rlb.setKey(new ReportedLspKey(name));
342 // If this is an unsolicited update. We need to make sure we retain the metadata already present
344 this.nodeState.setLspMetadata(name, rlb.getMetadata());
346 rlb.setMetadata(this.nodeState.getLspMetadata(name));
349 final ReportedLsp rl = rlb.build();
350 ctx.trans.put(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier.child(ReportedLsp.class, rlb.getKey()), rl);
351 LOG.debug("LSP {} updated to MD-SAL", name);
353 this.lspData.put(name, rl);
357 * Indicate that the peer has completed state synchronization.
359 * @param ctx Message context
361 protected final synchronized void stateSynchronizationAchieved(final MessageContext ctx) {
363 LOG.debug("State synchronization achieved while synchronized, not updating state");
367 // Update synchronization flag
369 ctx.trans.merge(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier, new PathComputationClientBuilder().setStateSync(PccSyncState.Synchronized).build());
371 // The node has completed synchronization, cleanup metadata no longer reported back
372 this.nodeState.cleanupExcept(this.lsps.values());
373 LOG.debug("Session {} achieved synchronized state", this.session);
376 protected final InstanceIdentifier<ReportedLsp> lspIdentifier(final String name) {
377 return this.pccIdentifier.child(ReportedLsp.class, new ReportedLspKey(name));
381 * Remove LSP from the database.
383 * @param ctx Message Context
384 * @param id Revision-specific LSP identifier
386 protected final synchronized void removeLsp(final MessageContext ctx, final L id) {
387 final String name = this.lsps.remove(id);
388 LOG.debug("LSP {} removed", name);
389 ctx.trans.delete(LogicalDatastoreType.OPERATIONAL, lspIdentifier(name));
390 this.lspData.remove(name);
393 protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
396 * Perform revision-specific message processing when a message arrives.
398 * @param ctx Message processing context
399 * @param message Protocol message
400 * @return True if the message type is not handle.
402 protected abstract boolean onMessage(MessageContext ctx, Message message);
404 protected final String lookupLspName(final L id) {
405 Preconditions.checkNotNull(id, "ID parameter null.");
406 return this.lsps.get(id);
409 protected final synchronized <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(final InstanceIdentifier<T> id) {
410 return this.nodeState.readOperationalData(id);