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.config.yang.pcep.topology.provider.ListenerStateRuntimeMXBean;
25 import org.opendaylight.controller.config.yang.pcep.topology.provider.ListenerStateRuntimeRegistration;
26 import org.opendaylight.controller.config.yang.pcep.topology.provider.PeerCapabilities;
27 import org.opendaylight.controller.config.yang.pcep.topology.provider.ReplyTime;
28 import org.opendaylight.controller.config.yang.pcep.topology.provider.SessionState;
29 import org.opendaylight.controller.config.yang.pcep.topology.provider.StatefulMessages;
30 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
31 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
32 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
33 import org.opendaylight.protocol.pcep.PCEPSession;
34 import org.opendaylight.protocol.pcep.PCEPSessionListener;
35 import org.opendaylight.protocol.pcep.PCEPTerminationReason;
36 import org.opendaylight.protocol.pcep.TerminationReason;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddressBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.MessageHeader;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Object;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.ProtocolVersion;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.LspId;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1Builder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.OperationResult;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.PccSyncState;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.lsp.metadata.Metadata;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClient;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClientBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLsp;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLspBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLspKey;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.reported.lsp.Path;
54 import org.opendaylight.yangtools.yang.binding.DataContainer;
55 import org.opendaylight.yangtools.yang.binding.DataObject;
56 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
61 * Base class for PCEP topology providers. It handles the common tasks involved in managing a PCEP server (PCE)
62 * endpoint, and exposing a network topology based on it. It needs to be subclassed to form a fully functional block,
63 * where the subclass provides handling of incoming messages.
65 * @param <S> identifier type of requests
66 * @param <L> identifier type for LSPs
68 public abstract class AbstractTopologySessionListener<S, L> implements PCEPSessionListener, TopologySessionListener, ListenerStateRuntimeMXBean {
69 protected static final class MessageContext {
70 private final Collection<PCEPRequest> requests = new ArrayList<>();
71 private final WriteTransaction trans;
73 private MessageContext(final WriteTransaction trans) {
74 this.trans = Preconditions.checkNotNull(trans);
77 void resolveRequest(final PCEPRequest req) {
78 this.requests.add(req);
81 private void notifyRequests() {
82 for (final PCEPRequest r : this.requests) {
83 r.done(OperationResults.SUCCESS);
88 protected static final MessageHeader MESSAGE_HEADER = new MessageHeader() {
89 private final ProtocolVersion version = new ProtocolVersion((short) 1);
92 public Class<? extends DataContainer> getImplementedInterface() {
93 return MessageHeader.class;
97 public ProtocolVersion getVersion() {
102 private static final Logger LOG = LoggerFactory.getLogger(AbstractTopologySessionListener.class);
104 protected static final String MISSING_XML_TAG = "Mandatory XML tags are missing.";
107 private final Map<S, PCEPRequest> requests = new HashMap<>();
110 private final Map<String, ReportedLsp> lspData = new HashMap<>();
113 private final Map<L, String> lsps = new HashMap<>();
115 private final ServerSessionManager serverSessionManager;
116 private InstanceIdentifier<PathComputationClient> pccIdentifier;
117 private TopologyNodeState nodeState;
118 private boolean synced = false;
119 private PCEPSession session;
121 private ListenerStateRuntimeRegistration registration;
122 private final SessionListenerState listenerState;
124 protected AbstractTopologySessionListener(final ServerSessionManager serverSessionManager) {
125 this.serverSessionManager = Preconditions.checkNotNull(serverSessionManager);
126 this.listenerState = new SessionListenerState();
130 public final synchronized void onSessionUp(final PCEPSession session) {
132 * The session went up. Look up the router in Inventory model,
133 * create it if it is not there (marking that fact for later
134 * deletion), and mark it as synchronizing. Also create it in
135 * the topology model, with empty LSP list.
137 final InetAddress peerAddress = session.getRemoteAddress();
139 final TopologyNodeState state = this.serverSessionManager.takeNodeState(peerAddress, this);
141 LOG.trace("Peer {} resolved to topology node {}", peerAddress, state.getNodeId());
144 // Our augmentation in the topology node
145 final PathComputationClientBuilder pccBuilder = new PathComputationClientBuilder();
146 pccBuilder.setIpAddress(IpAddressBuilder.getDefaultInstance(peerAddress.getHostAddress()));
148 onSessionUp(session, pccBuilder);
150 final Node1 ta = new Node1Builder().setPathComputationClient(pccBuilder.build()).build();
151 final InstanceIdentifier<Node1> topologyAugment = state.getNodeId().augmentation(Node1.class);
152 this.pccIdentifier = topologyAugment.child(PathComputationClient.class);
154 final ReadWriteTransaction trans = state.rwTransaction();
155 trans.put(LogicalDatastoreType.OPERATIONAL, topologyAugment, ta);
156 LOG.trace("Peer data {} set to {}", topologyAugment, ta);
158 // All set, commit the modifications
159 Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
161 public void onSuccess(final Void result) {
162 LOG.trace("Internal state for session {} updated successfully", session);
166 public void onFailure(final Throwable t) {
167 LOG.error("Failed to update internal state for session {}, terminating it", session, t);
168 session.close(TerminationReason.Unknown);
172 this.session = session;
173 this.nodeState = state;
174 this.listenerState.init(session);
175 if (this.serverSessionManager.getRuntimeRootRegistration().isPresent()) {
176 this.registration = this.serverSessionManager.getRuntimeRootRegistration().get().register(this);
178 LOG.info("Session with {} attached to topology node {}", session.getRemoteAddress(), state.getNodeId());
182 private void tearDown(final PCEPSession session) {
183 this.serverSessionManager.releaseNodeState(this.nodeState, session);
184 this.nodeState = null;
187 // Clear all requests we know about
188 for (final Entry<S, PCEPRequest> e : this.requests.entrySet()) {
189 final PCEPRequest r = e.getValue();
190 switch (r.getState()) {
192 // Done is done, nothing to do
195 // Peer has not acked: results in failure
196 LOG.info("Request {} was incomplete when session went down, failing the instruction", e.getKey());
197 r.done(OperationResults.NOACK);
200 // Peer has not been sent to the peer: results in cancellation
201 LOG.debug("Request {} was not sent when session went down, cancelling the instruction", e.getKey());
202 r.done(OperationResults.UNSENT);
206 this.requests.clear();
210 public final synchronized void onSessionDown(final PCEPSession session, final Exception e) {
211 LOG.warn("Session {} went down unexpectedly", session, e);
216 public final synchronized void onSessionTerminated(final PCEPSession session, final PCEPTerminationReason reason) {
217 LOG.info("Session {} terminated by peer with reason {}", session, reason);
222 public final synchronized void onMessage(final PCEPSession session, final Message message) {
223 final MessageContext ctx = new MessageContext(this.nodeState.beginTransaction());
225 if (onMessage(ctx, message)) {
226 LOG.info("Unhandled message {} on session {}", message, session);
230 Futures.addCallback(ctx.trans.submit(), new FutureCallback<Void>() {
232 public void onSuccess(final Void result) {
233 LOG.trace("Internal state for session {} updated successfully", session);
234 ctx.notifyRequests();
238 public void onFailure(final Throwable t) {
239 LOG.error("Failed to update internal state for session {}, closing it", session, t);
240 ctx.notifyRequests();
241 session.close(TerminationReason.Unknown);
247 public void close() {
248 if (this.registration != null) {
249 this.registration.close();
251 if (this.session != null) {
252 this.session.close(TerminationReason.Unknown);
256 protected final synchronized PCEPRequest removeRequest(final S id) {
257 final PCEPRequest ret = this.requests.remove(id);
258 this.listenerState.processRequestStats(ret.getElapsedMillis());
259 LOG.trace("Removed request {} object {}", id, ret);
263 protected final synchronized ListenableFuture<OperationResult> sendMessage(final Message message, final S requestId,
264 final Metadata metadata) {
265 final io.netty.util.concurrent.Future<Void> f = this.session.sendMessage(message);
266 this.listenerState.updateStatefulSentMsg(message);
267 final PCEPRequest req = new PCEPRequest(metadata);
268 this.requests.put(requestId, req);
270 f.addListener(new FutureListener<Void>() {
272 public void operationComplete(final io.netty.util.concurrent.Future<Void> future) {
273 if (!future.isSuccess()) {
274 synchronized (AbstractTopologySessionListener.this) {
275 AbstractTopologySessionListener.this.requests.remove(requestId);
277 req.done(OperationResults.UNSENT);
278 LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
281 LOG.trace("Request {} sent to peer (object {})", requestId, req);
286 return req.getFuture();
290 * Update an LSP in the data store
292 * @param ctx Message context
293 * @param id Revision-specific LSP identifier
294 * @param lspName LSP name
295 * @param rlb Reported LSP builder
296 * @param solicited True if the update was solicited
297 * @param remove True if this is an LSP path removal
299 protected final synchronized void updateLsp(final MessageContext ctx, final L id, final String lspName,
300 final ReportedLspBuilder rlb, final boolean solicited, final boolean remove) {
303 if (lspName == null) {
304 name = this.lsps.get(id);
306 LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
313 LOG.debug("Saved LSP {} with name {}", id, name);
314 this.lsps.put(id, name);
317 final ReportedLsp previous = this.lspData.get(name);
318 // if no previous report about the lsp exist, just proceed
319 if (previous != null) {
320 final List<Path> updatedPaths = makeBeforeBreak(rlb, previous, name, remove);
321 // if all paths or the last path were deleted, delete whole tunnel
322 if (updatedPaths == null || updatedPaths.isEmpty()) {
323 LOG.debug("All paths were removed, removing LSP with {}.", id);
327 rlb.setPath(updatedPaths);
329 rlb.setKey(new ReportedLspKey(name));
332 // If this is an unsolicited update. We need to make sure we retain the metadata already present
334 this.nodeState.setLspMetadata(name, rlb.getMetadata());
336 rlb.setMetadata(this.nodeState.getLspMetadata(name));
339 final ReportedLsp rl = rlb.build();
340 ctx.trans.put(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier.child(ReportedLsp.class, rlb.getKey()), rl);
341 LOG.debug("LSP {} updated to MD-SAL", name);
343 this.lspData.put(name, rl);
346 private List<Path> makeBeforeBreak(final ReportedLspBuilder rlb, final ReportedLsp previous, final String name, final boolean remove) {
347 // just one path should be reported
348 Preconditions.checkState(rlb.getPath().size() == 1);
349 final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev130820.LspId reportedLspId = rlb.getPath().get(0).getLspId();
350 // check previous report for existing paths
351 final List<Path> updatedPaths = new ArrayList<>(previous.getPath());
352 LOG.debug("Found previous paths {} to this lsp name {}", updatedPaths, name);
353 for (final Path path : previous.getPath()) {
354 //we found reported path in previous reports
355 if (path.getLspId().getValue() == 0 || path.getLspId().equals(reportedLspId)) {
356 LOG.debug("Match on lsp-id {}", path.getLspId().getValue() );
357 // path that was reported previously and does have the same lsp-id, path will be updated
358 final boolean r = updatedPaths.remove(path);
359 LOG.trace("Request removed? {}", r);
362 // if the path does not exist in previous report, add it to path list, it's a new ERO
363 // only one path will be added
364 //lspId is 0 means confirmation message that shouldn't be added (because we have no means of deleting it later)
365 LOG.trace("Adding new path {} to {}", rlb.getPath(), updatedPaths);
366 updatedPaths.addAll(rlb.getPath());
368 if (reportedLspId.getValue() == 0) {
369 // if lsp-id also 0, remove all paths
370 LOG.debug("Removing all paths.");
371 updatedPaths.clear();
373 // path is marked to be removed
374 LOG.debug("Removing path {} from {}", rlb.getPath(), updatedPaths);
375 final boolean r = updatedPaths.removeAll(rlb.getPath());
376 LOG.trace("Request removed? {}", r);
379 LOG.debug("Setting new paths {} to lsp {}", updatedPaths, name);
384 * Indicate that the peer has completed state synchronization.
386 * @param ctx Message context
388 protected final synchronized void stateSynchronizationAchieved(final MessageContext ctx) {
390 LOG.debug("State synchronization achieved while synchronized, not updating state");
394 // Update synchronization flag
396 ctx.trans.merge(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier, new PathComputationClientBuilder().setStateSync(PccSyncState.Synchronized).build());
398 // The node has completed synchronization, cleanup metadata no longer reported back
399 this.nodeState.cleanupExcept(this.lsps.values());
400 LOG.debug("Session {} achieved synchronized state", this.session);
403 protected final InstanceIdentifier<ReportedLsp> lspIdentifier(final String name) {
404 return this.pccIdentifier.child(ReportedLsp.class, new ReportedLspKey(name));
408 * Remove LSP from the database.
410 * @param ctx Message Context
411 * @param id Revision-specific LSP identifier
413 protected final synchronized void removeLsp(final MessageContext ctx, final L id) {
414 final String name = this.lsps.remove(id);
415 LOG.debug("LSP {} removed", name);
416 ctx.trans.delete(LogicalDatastoreType.OPERATIONAL, lspIdentifier(name));
417 this.lspData.remove(name);
420 protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
423 * Perform revision-specific message processing when a message arrives.
425 * @param ctx Message processing context
426 * @param message Protocol message
427 * @return True if the message type is not handle.
429 protected abstract boolean onMessage(MessageContext ctx, Message message);
431 protected final String lookupLspName(final L id) {
432 Preconditions.checkNotNull(id, "ID parameter null.");
433 return this.lsps.get(id);
436 protected final synchronized <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(final InstanceIdentifier<T> id) {
437 return this.nodeState.readOperationalData(id);
440 protected abstract Object validateReportedLsp(final Optional<ReportedLsp> rep, final LspId input);
442 protected SessionListenerState getSessionListenerState() {
443 return this.listenerState;
447 public Integer getDelegatedLspsCount() {
448 return this.lsps.size();
452 public Boolean getSynchronized() {
457 public StatefulMessages getStatefulMessages() {
458 return this.listenerState.getStatefulMessages();
462 public void resetStats() {
463 this.listenerState.resetStats(this.session);
467 public ReplyTime getReplyTime() {
468 return this.listenerState.getReplyTime();
472 public PeerCapabilities getPeerCapabilities() {
473 return this.listenerState.getPeerCapabilities();
477 public void tearDownSession() {
482 public SessionState getSessionState() {
483 return this.listenerState.getSessionState(this.session);
487 public String getPeerId() {
488 return this.session.getPeerPref().getIpAddress();