0fc3f2c56f845717c7b01996703fc52250ccb3f9
[bgpcep.git] / pcep / topology-provider / src / main / java / org / opendaylight / bgpcep / pcep / topology / provider / AbstractTopologySessionListener.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.bgpcep.pcep.topology.provider;
9
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
16 import io.netty.util.concurrent.FutureListener;
17
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;
23 import java.util.Map;
24 import java.util.Map.Entry;
25
26 import javax.annotation.concurrent.GuardedBy;
27
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;
56
57 /**
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.
61  *
62  * @param <S> identifier type of requests
63  * @param <L> identifier type for LSPs
64  */
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;
69
70         private MessageContext(final WriteTransaction trans) {
71             this.trans = Preconditions.checkNotNull(trans);
72         }
73
74         void resolveRequest(final PCEPRequest req) {
75             this.requests.add(req);
76         }
77
78         private void notifyRequests() {
79             for (final PCEPRequest r : this.requests) {
80                 r.done(OperationResults.SUCCESS);
81             }
82         }
83     }
84
85     protected static final MessageHeader MESSAGE_HEADER = new MessageHeader() {
86         private final ProtocolVersion version = new ProtocolVersion((short) 1);
87
88         @Override
89         public Class<? extends DataContainer> getImplementedInterface() {
90             return MessageHeader.class;
91         }
92
93         @Override
94         public ProtocolVersion getVersion() {
95             return this.version;
96         }
97     };
98     private static final Logger LOG = LoggerFactory.getLogger(AbstractTopologySessionListener.class);
99
100     protected static final String MISSING_XML_TAG = "Mandatory XML tags are missing.";
101
102     @GuardedBy("this")
103     private final Map<S, PCEPRequest> requests = new HashMap<>();
104
105     @GuardedBy("this")
106     private final Map<String, ReportedLsp> lspData = new HashMap<>();
107
108     @GuardedBy("this")
109     private final Map<L, String> lsps = new HashMap<>();
110
111     private final ServerSessionManager serverSessionManager;
112     private InstanceIdentifier<PathComputationClient> pccIdentifier;
113     private TopologyNodeState nodeState;
114     private boolean synced = false;
115     private PCEPSession session;
116
117     protected AbstractTopologySessionListener(final ServerSessionManager serverSessionManager) {
118         this.serverSessionManager = Preconditions.checkNotNull(serverSessionManager);
119     }
120
121     @Override
122     public final synchronized void onSessionUp(final PCEPSession session) {
123         /*
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.
128          */
129         final InetAddress peerAddress = session.getRemoteAddress();
130
131         final TopologyNodeState state = serverSessionManager.takeNodeState(peerAddress, this);
132         if (state == null) {
133             session.close(TerminationReason.Unknown);
134             return;
135         }
136
137         LOG.trace("Peer {} resolved to topology node {}", peerAddress, state.getNodeId());
138         this.synced = false;
139
140         // Our augmentation in the topology node
141         final PathComputationClientBuilder pccBuilder = new PathComputationClientBuilder();
142         pccBuilder.setIpAddress(IpAddressBuilder.getDefaultInstance(peerAddress.getHostAddress()));
143
144         onSessionUp(session, pccBuilder);
145
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);
149
150         final ReadWriteTransaction trans = state.rwTransaction();
151         trans.put(LogicalDatastoreType.OPERATIONAL, topologyAugment, ta);
152         LOG.trace("Peer data {} set to {}", topologyAugment, ta);
153
154         // All set, commit the modifications
155         Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
156             @Override
157             public void onSuccess(final Void result) {
158                 LOG.trace("Internal state for session {} updated successfully", session);
159             }
160
161             @Override
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);
165             }
166         });
167
168         this.session = session;
169         this.nodeState = state;
170         LOG.info("Session with {} attached to topology node {}", session.getRemoteAddress(), state.getNodeId());
171     }
172
173     @GuardedBy("this")
174     private void tearDown(final PCEPSession session) {
175         this.serverSessionManager.releaseNodeState(this.nodeState);
176         this.nodeState = null;
177         this.session = null;
178
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()) {
183             case DONE:
184                 // Done is done, nothing to do
185                 break;
186             case UNACKED:
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);
190                 break;
191             case UNSENT:
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);
195                 break;
196             }
197         }
198         this.requests.clear();
199     }
200
201     @Override
202     public final synchronized void onSessionDown(final PCEPSession session, final Exception e) {
203         LOG.warn("Session {} went down unexpectedly", session, e);
204         tearDown(session);
205     }
206
207     @Override
208     public final synchronized void onSessionTerminated(final PCEPSession session, final PCEPTerminationReason reason) {
209         LOG.info("Session {} terminated by peer with reason {}", session, reason);
210         tearDown(session);
211     }
212
213     @Override
214     public final synchronized void onMessage(final PCEPSession session, final Message message) {
215         final MessageContext ctx = new MessageContext(this.nodeState.beginTransaction());
216
217         if (onMessage(ctx, message)) {
218             LOG.info("Unhandled message {} on session {}", message, session);
219             return;
220         }
221
222         Futures.addCallback(ctx.trans.submit(), new FutureCallback<Void>() {
223             @Override
224             public void onSuccess(final Void result) {
225                 LOG.trace("Internal state for session {} updated successfully", session);
226                 ctx.notifyRequests();
227             }
228
229             @Override
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);
234             }
235         });
236     }
237
238     @Override
239     public void close() {
240         if (this.session != null) {
241             this.session.close(TerminationReason.Unknown);
242         }
243     }
244
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);
248         return ret;
249     }
250
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);
256
257         f.addListener(new FutureListener<Void>() {
258             @Override
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);
263                     }
264                     req.done(OperationResults.UNSENT);
265                     LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
266                 } else {
267                     req.sent();
268                     LOG.trace("Request {} sent to peer (object {})", requestId, req);
269                 }
270             }
271         });
272
273         return req.getFuture();
274     }
275
276     /**
277      * Update an LSP in the data store
278      *
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
285      */
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) {
288
289         final String name;
290         if (lspName == null) {
291             name = this.lsps.get(id);
292             if (name == null) {
293                 LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
294                 return;
295             }
296         } else {
297             name = lspName;
298         }
299
300         LOG.debug("Saved LSP {} with name {}", id, name);
301         this.lsps.put(id, name);
302
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);
319                 }
320             }
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());
326             if (remove) {
327                 if (reportedLspId.getValue() == 0) {
328                     // if lsp-id also 0, remove all paths
329                     LOG.debug("Removing all paths.");
330                     updatedPaths.clear();
331                 } else {
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);
336                 }
337             }
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);
341                 removeLsp(ctx, id);
342                 return;
343             }
344             LOG.debug("Setting new paths {} to lsp {}", updatedPaths, name);
345             rlb.setPath(updatedPaths);
346         }
347         Preconditions.checkState(name != null);
348         rlb.setKey(new ReportedLspKey(name));
349         rlb.setName(name);
350
351         // If this is an unsolicited update. We need to make sure we retain the metadata already present
352         if (solicited) {
353             this.nodeState.setLspMetadata(name, rlb.getMetadata());
354         } else {
355             rlb.setMetadata(this.nodeState.getLspMetadata(name));
356         }
357
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);
361
362         this.lspData.put(name, rl);
363     }
364
365     /**
366      * Indicate that the peer has completed state synchronization.
367      *
368      * @param ctx Message context
369      */
370     protected final synchronized void stateSynchronizationAchieved(final MessageContext ctx) {
371         if (this.synced) {
372             LOG.debug("State synchronization achieved while synchronized, not updating state");
373             return;
374         }
375
376         // Update synchronization flag
377         this.synced = true;
378         ctx.trans.merge(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier, new PathComputationClientBuilder().setStateSync(PccSyncState.Synchronized).build());
379
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);
383     }
384
385     protected final InstanceIdentifier<ReportedLsp> lspIdentifier(final String name) {
386         return this.pccIdentifier.child(ReportedLsp.class, new ReportedLspKey(name));
387     }
388
389     /**
390      * Remove LSP from the database.
391      *
392      * @param ctx Message Context
393      * @param id Revision-specific LSP identifier
394      */
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);
400     }
401
402     protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
403
404     /**
405      * Perform revision-specific message processing when a message arrives.
406      *
407      * @param ctx Message processing context
408      * @param message Protocol message
409      * @return True if the message type is not handle.
410      */
411     protected abstract boolean onMessage(MessageContext ctx, Message message);
412
413     protected final String lookupLspName(final L id) {
414         Preconditions.checkNotNull(id, "ID parameter null.");
415         return this.lsps.get(id);
416     }
417
418     protected synchronized final <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(final InstanceIdentifier<T> id) {
419         return this.nodeState.readOperationalData(id);
420     }
421 }