2424fec4857e30ccef33bdf53dd9b789a5adb42f
[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 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;
21 import java.util.Map;
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;
53
54 /**
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.
58  *
59  * @param <S> identifier type of requests
60  * @param <L> identifier type for LSPs
61  */
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;
66
67         private MessageContext(final WriteTransaction trans) {
68             this.trans = Preconditions.checkNotNull(trans);
69         }
70
71         void resolveRequest(final PCEPRequest req) {
72             this.requests.add(req);
73         }
74
75         private void notifyRequests() {
76             for (final PCEPRequest r : this.requests) {
77                 r.done(OperationResults.SUCCESS);
78             }
79         }
80     }
81
82     protected static final MessageHeader MESSAGE_HEADER = new MessageHeader() {
83         private final ProtocolVersion version = new ProtocolVersion((short) 1);
84
85         @Override
86         public Class<? extends DataContainer> getImplementedInterface() {
87             return MessageHeader.class;
88         }
89
90         @Override
91         public ProtocolVersion getVersion() {
92             return this.version;
93         }
94     };
95     private static final Logger LOG = LoggerFactory.getLogger(AbstractTopologySessionListener.class);
96
97     protected static final String MISSING_XML_TAG = "Mandatory XML tags are missing.";
98
99     @GuardedBy("this")
100     private final Map<S, PCEPRequest> requests = new HashMap<>();
101
102     @GuardedBy("this")
103     private final Map<String, ReportedLsp> lspData = new HashMap<>();
104
105     @GuardedBy("this")
106     private final Map<L, String> lsps = new HashMap<>();
107
108     private final ServerSessionManager serverSessionManager;
109     private InstanceIdentifier<PathComputationClient> pccIdentifier;
110     private TopologyNodeState nodeState;
111     private boolean synced = false;
112     private PCEPSession session;
113
114     protected AbstractTopologySessionListener(final ServerSessionManager serverSessionManager) {
115         this.serverSessionManager = Preconditions.checkNotNull(serverSessionManager);
116     }
117
118     @Override
119     public final synchronized void onSessionUp(final PCEPSession session) {
120         /*
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.
125          */
126         final InetAddress peerAddress = session.getRemoteAddress();
127
128         final TopologyNodeState state = this.serverSessionManager.takeNodeState(peerAddress, this);
129
130         LOG.trace("Peer {} resolved to topology node {}", peerAddress, state.getNodeId());
131         this.synced = false;
132
133         // Our augmentation in the topology node
134         final PathComputationClientBuilder pccBuilder = new PathComputationClientBuilder();
135         pccBuilder.setIpAddress(IpAddressBuilder.getDefaultInstance(peerAddress.getHostAddress()));
136
137         onSessionUp(session, pccBuilder);
138
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);
142
143         final ReadWriteTransaction trans = state.rwTransaction();
144         trans.put(LogicalDatastoreType.OPERATIONAL, topologyAugment, ta);
145         LOG.trace("Peer data {} set to {}", topologyAugment, ta);
146
147         // All set, commit the modifications
148         Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
149             @Override
150             public void onSuccess(final Void result) {
151                 LOG.trace("Internal state for session {} updated successfully", session);
152             }
153
154             @Override
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);
158             }
159         });
160
161         this.session = session;
162         this.nodeState = state;
163         LOG.info("Session with {} attached to topology node {}", session.getRemoteAddress(), state.getNodeId());
164     }
165
166     @GuardedBy("this")
167     private void tearDown(final PCEPSession session) {
168         this.serverSessionManager.releaseNodeState(this.nodeState, session);
169         this.nodeState = null;
170         this.session = null;
171
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()) {
176             case DONE:
177                 // Done is done, nothing to do
178                 break;
179             case UNACKED:
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);
183                 break;
184             case UNSENT:
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);
188                 break;
189             }
190         }
191         this.requests.clear();
192     }
193
194     @Override
195     public final synchronized void onSessionDown(final PCEPSession session, final Exception e) {
196         LOG.warn("Session {} went down unexpectedly", session, e);
197         tearDown(session);
198     }
199
200     @Override
201     public final synchronized void onSessionTerminated(final PCEPSession session, final PCEPTerminationReason reason) {
202         LOG.info("Session {} terminated by peer with reason {}", session, reason);
203         tearDown(session);
204     }
205
206     @Override
207     public final synchronized void onMessage(final PCEPSession session, final Message message) {
208         final MessageContext ctx = new MessageContext(this.nodeState.beginTransaction());
209
210         if (onMessage(ctx, message)) {
211             LOG.info("Unhandled message {} on session {}", message, session);
212             return;
213         }
214
215         Futures.addCallback(ctx.trans.submit(), new FutureCallback<Void>() {
216             @Override
217             public void onSuccess(final Void result) {
218                 LOG.trace("Internal state for session {} updated successfully", session);
219                 ctx.notifyRequests();
220             }
221
222             @Override
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);
227             }
228         });
229     }
230
231     @Override
232     public void close() {
233         if (this.session != null) {
234             this.session.close(TerminationReason.Unknown);
235         }
236     }
237
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);
241         return ret;
242     }
243
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);
249
250         f.addListener(new FutureListener<Void>() {
251             @Override
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);
256                     }
257                     req.done(OperationResults.UNSENT);
258                     LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
259                 } else {
260                     req.sent();
261                     LOG.trace("Request {} sent to peer (object {})", requestId, req);
262                 }
263             }
264         });
265
266         return req.getFuture();
267     }
268
269     /**
270      * Update an LSP in the data store
271      *
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
278      */
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) {
281
282         final String name;
283         if (lspName == null) {
284             name = this.lsps.get(id);
285             if (name == null) {
286                 LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
287                 return;
288             }
289         } else {
290             name = lspName;
291         }
292
293         LOG.debug("Saved LSP {} with name {}", id, name);
294         this.lsps.put(id, name);
295
296
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);
304                 removeLsp(ctx, id);
305                 return;
306             }
307             rlb.setPath(updatedPaths);
308         }
309         rlb.setKey(new ReportedLspKey(name));
310         rlb.setName(name);
311
312         // If this is an unsolicited update. We need to make sure we retain the metadata already present
313         if (solicited) {
314             this.nodeState.setLspMetadata(name, rlb.getMetadata());
315         } else {
316             rlb.setMetadata(this.nodeState.getLspMetadata(name));
317         }
318
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);
322
323         this.lspData.put(name, rl);
324     }
325
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);
340             }
341         }
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());
347         if (remove) {
348             if (reportedLspId.getValue() == 0) {
349                 // if lsp-id also 0, remove all paths
350                 LOG.debug("Removing all paths.");
351                 updatedPaths.clear();
352             } else {
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);
357             }
358         }
359         LOG.debug("Setting new paths {} to lsp {}", updatedPaths, name);
360         return updatedPaths;
361     }
362
363     /**
364      * Indicate that the peer has completed state synchronization.
365      *
366      * @param ctx Message context
367      */
368     protected final synchronized void stateSynchronizationAchieved(final MessageContext ctx) {
369         if (this.synced) {
370             LOG.debug("State synchronization achieved while synchronized, not updating state");
371             return;
372         }
373
374         // Update synchronization flag
375         this.synced = true;
376         ctx.trans.merge(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier, new PathComputationClientBuilder().setStateSync(PccSyncState.Synchronized).build());
377
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);
381     }
382
383     protected final InstanceIdentifier<ReportedLsp> lspIdentifier(final String name) {
384         return this.pccIdentifier.child(ReportedLsp.class, new ReportedLspKey(name));
385     }
386
387     /**
388      * Remove LSP from the database.
389      *
390      * @param ctx Message Context
391      * @param id Revision-specific LSP identifier
392      */
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);
398     }
399
400     protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
401
402     /**
403      * Perform revision-specific message processing when a message arrives.
404      *
405      * @param ctx Message processing context
406      * @param message Protocol message
407      * @return True if the message type is not handle.
408      */
409     protected abstract boolean onMessage(MessageContext ctx, Message message);
410
411     protected final String lookupLspName(final L id) {
412         Preconditions.checkNotNull(id, "ID parameter null.");
413         return this.lsps.get(id);
414     }
415
416     protected final synchronized <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(final InstanceIdentifier<T> id) {
417         return this.nodeState.readOperationalData(id);
418     }
419
420     protected abstract Object validateReportedLsp(final Optional<ReportedLsp> rep, final LspId input);
421 }