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;
188 // Clear all requests we know about
189 for (final Entry<S, PCEPRequest> e : this.requests.entrySet()) {
190 final PCEPRequest r = e.getValue();
191 switch (r.getState()) {
193 // Done is done, nothing to do
196 // Peer has not acked: results in failure
197 LOG.info("Request {} was incomplete when session went down, failing the instruction", e.getKey());
198 r.done(OperationResults.NOACK);
201 // Peer has not been sent to the peer: results in cancellation
202 LOG.debug("Request {} was not sent when session went down, cancelling the instruction", e.getKey());
203 r.done(OperationResults.UNSENT);
209 this.requests.clear();
213 public final synchronized void onSessionDown(final PCEPSession session, final Exception e) {
214 LOG.warn("Session {} went down unexpectedly", session, e);
219 public final synchronized void onSessionTerminated(final PCEPSession session, final PCEPTerminationReason reason) {
220 LOG.info("Session {} terminated by peer with reason {}", session, reason);
225 public final synchronized void onMessage(final PCEPSession session, final Message message) {
226 final MessageContext ctx = new MessageContext(this.nodeState.beginTransaction());
228 if (onMessage(ctx, message)) {
229 LOG.info("Unhandled message {} on session {}", message, session);
233 Futures.addCallback(ctx.trans.submit(), new FutureCallback<Void>() {
235 public void onSuccess(final Void result) {
236 LOG.trace("Internal state for session {} updated successfully", session);
237 ctx.notifyRequests();
241 public void onFailure(final Throwable t) {
242 LOG.error("Failed to update internal state for session {}, closing it", session, t);
243 ctx.notifyRequests();
244 session.close(TerminationReason.UNKNOWN);
250 public void close() {
252 if (this.session != null) {
253 this.session.close(TerminationReason.UNKNOWN);
257 private synchronized void unregister() {
258 if (this.registration != null) {
259 this.registration.close();
260 this.registration = null;
264 protected final synchronized PCEPRequest removeRequest(final S id) {
265 final PCEPRequest ret = this.requests.remove(id);
267 this.listenerState.processRequestStats(ret.getElapsedMillis());
269 LOG.trace("Removed request {} object {}", id, ret);
273 protected final synchronized ListenableFuture<OperationResult> sendMessage(final Message message, final S requestId,
274 final Metadata metadata) {
275 final io.netty.util.concurrent.Future<Void> f = this.session.sendMessage(message);
276 this.listenerState.updateStatefulSentMsg(message);
277 final PCEPRequest req = new PCEPRequest(metadata);
278 this.requests.put(requestId, req);
280 f.addListener(new FutureListener<Void>() {
282 public void operationComplete(final io.netty.util.concurrent.Future<Void> future) {
283 if (!future.isSuccess()) {
284 synchronized (AbstractTopologySessionListener.this) {
285 AbstractTopologySessionListener.this.requests.remove(requestId);
287 req.done(OperationResults.UNSENT);
288 LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
291 LOG.trace("Request {} sent to peer (object {})", requestId, req);
296 return req.getFuture();
300 * Update an LSP in the data store
302 * @param ctx Message context
303 * @param id Revision-specific LSP identifier
304 * @param lspName LSP name
305 * @param rlb Reported LSP builder
306 * @param solicited True if the update was solicited
307 * @param remove True if this is an LSP path removal
309 protected final synchronized void updateLsp(final MessageContext ctx, final L id, final String lspName,
310 final ReportedLspBuilder rlb, final boolean solicited, final boolean remove) {
313 if (lspName == null) {
314 name = this.lsps.get(id);
316 LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
323 LOG.debug("Saved LSP {} with name {}", id, name);
324 this.lsps.put(id, name);
327 final ReportedLsp previous = this.lspData.get(name);
328 // if no previous report about the lsp exist, just proceed
329 if (previous != null) {
330 final List<Path> updatedPaths = makeBeforeBreak(rlb, previous, name, remove);
331 // if all paths or the last path were deleted, delete whole tunnel
332 if (updatedPaths == null || updatedPaths.isEmpty()) {
333 LOG.debug("All paths were removed, removing LSP with {}.", id);
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);
356 private List<Path> makeBeforeBreak(final ReportedLspBuilder rlb, final ReportedLsp previous, final String name, final boolean remove) {
357 // just one path should be reported
358 Preconditions.checkState(rlb.getPath().size() == 1);
359 final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev130820.LspId reportedLspId = rlb.getPath().get(0).getLspId();
360 // check previous report for existing paths
361 final List<Path> updatedPaths = new ArrayList<>(previous.getPath());
362 LOG.debug("Found previous paths {} to this lsp name {}", updatedPaths, name);
363 for (final Path path : previous.getPath()) {
364 //we found reported path in previous reports
365 if (path.getLspId().getValue() == 0 || path.getLspId().equals(reportedLspId)) {
366 LOG.debug("Match on lsp-id {}", path.getLspId().getValue() );
367 // path that was reported previously and does have the same lsp-id, path will be updated
368 final boolean r = updatedPaths.remove(path);
369 LOG.trace("Request removed? {}", r);
372 // if the path does not exist in previous report, add it to path list, it's a new ERO
373 // only one path will be added
374 //lspId is 0 means confirmation message that shouldn't be added (because we have no means of deleting it later)
375 LOG.trace("Adding new path {} to {}", rlb.getPath(), updatedPaths);
376 updatedPaths.addAll(rlb.getPath());
378 if (reportedLspId.getValue() == 0) {
379 // if lsp-id also 0, remove all paths
380 LOG.debug("Removing all paths.");
381 updatedPaths.clear();
383 // path is marked to be removed
384 LOG.debug("Removing path {} from {}", rlb.getPath(), updatedPaths);
385 final boolean r = updatedPaths.removeAll(rlb.getPath());
386 LOG.trace("Request removed? {}", r);
389 LOG.debug("Setting new paths {} to lsp {}", updatedPaths, name);
394 * Indicate that the peer has completed state synchronization.
396 * @param ctx Message context
398 protected final synchronized void stateSynchronizationAchieved(final MessageContext ctx) {
400 LOG.debug("State synchronization achieved while synchronized, not updating state");
404 // Update synchronization flag
406 ctx.trans.merge(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier, new PathComputationClientBuilder().setStateSync(PccSyncState.Synchronized).build());
408 // The node has completed synchronization, cleanup metadata no longer reported back
409 this.nodeState.cleanupExcept(this.lsps.values());
410 LOG.debug("Session {} achieved synchronized state", this.session);
413 protected final InstanceIdentifier<ReportedLsp> lspIdentifier(final String name) {
414 return this.pccIdentifier.child(ReportedLsp.class, new ReportedLspKey(name));
418 * Remove LSP from the database.
420 * @param ctx Message Context
421 * @param id Revision-specific LSP identifier
423 protected final synchronized void removeLsp(final MessageContext ctx, final L id) {
424 final String name = this.lsps.remove(id);
425 LOG.debug("LSP {} removed", name);
426 ctx.trans.delete(LogicalDatastoreType.OPERATIONAL, lspIdentifier(name));
427 this.lspData.remove(name);
430 protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
433 * Perform revision-specific message processing when a message arrives.
435 * @param ctx Message processing context
436 * @param message Protocol message
437 * @return True if the message type is not handle.
439 protected abstract boolean onMessage(MessageContext ctx, Message message);
441 protected final String lookupLspName(final L id) {
442 Preconditions.checkNotNull(id, "ID parameter null.");
443 return this.lsps.get(id);
446 protected final synchronized <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(final InstanceIdentifier<T> id) {
447 return this.nodeState.readOperationalData(id);
450 protected abstract Object validateReportedLsp(final Optional<ReportedLsp> rep, final LspId input);
452 protected SessionListenerState getSessionListenerState() {
453 return this.listenerState;
457 public Integer getDelegatedLspsCount() {
458 return this.lsps.size();
462 public Boolean getSynchronized() {
467 public StatefulMessages getStatefulMessages() {
468 return this.listenerState.getStatefulMessages();
472 public synchronized void resetStats() {
473 this.listenerState.resetStats(this.session);
477 public ReplyTime getReplyTime() {
478 return this.listenerState.getReplyTime();
482 public PeerCapabilities getPeerCapabilities() {
483 return this.listenerState.getPeerCapabilities();
487 public void tearDownSession() {
492 public synchronized SessionState getSessionState() {
493 return this.listenerState.getSessionState(this.session);
497 public synchronized String getPeerId() {
498 return this.session.getPeerPref().getIpAddress();