6e0eb2e5f23635d2756d98a995bef0df17742665
[bgpcep.git] / pcep / topology / 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 static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import io.netty.util.concurrent.FutureListener;
19 import java.net.InetAddress;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Objects;
27 import java.util.Timer;
28 import java.util.TimerTask;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.atomic.AtomicBoolean;
31 import javax.annotation.concurrent.GuardedBy;
32 import org.opendaylight.bgpcep.pcep.topology.provider.session.stats.SessionStateImpl;
33 import org.opendaylight.bgpcep.pcep.topology.provider.session.stats.TopologySessionStats;
34 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
35 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
36 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
37 import org.opendaylight.protocol.pcep.PCEPCloseTermination;
38 import org.opendaylight.protocol.pcep.PCEPSession;
39 import org.opendaylight.protocol.pcep.PCEPTerminationReason;
40 import org.opendaylight.protocol.pcep.TerminationReason;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev171025.LspObject;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev171025.Path1;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev171025.lsp.object.Lsp;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.MessageHeader;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Object;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.ProtocolVersion;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev171025.LspId;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev171025.Node1;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev171025.Node1Builder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev171025.OperationResult;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev171025.PccSyncState;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev171025.TearDownSessionInput;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev171025.lsp.metadata.Metadata;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev171025.pcep.client.attributes.PathComputationClient;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev171025.pcep.client.attributes.PathComputationClientBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev171025.pcep.client.attributes.path.computation.client.ReportedLsp;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev171025.pcep.client.attributes.path.computation.client.ReportedLspBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev171025.pcep.client.attributes.path.computation.client.ReportedLspKey;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev171025.pcep.client.attributes.path.computation.client.reported.lsp.Path;
62 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
63 import org.opendaylight.yangtools.yang.binding.DataContainer;
64 import org.opendaylight.yangtools.yang.binding.DataObject;
65 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
66 import org.opendaylight.yangtools.yang.common.RpcResult;
67 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70
71 /**
72  * Base class for PCEP topology providers. It handles the common tasks involved in managing a PCEP server (PCE)
73  * endpoint, and exposing a network topology based on it. It needs to be subclassed to form a fully functional block,
74  * where the subclass provides handling of incoming messages.
75  *
76  * @param <S> identifier type of requests
77  * @param <L> identifier type for LSPs
78  */
79 public abstract class AbstractTopologySessionListener<S, L> implements TopologySessionListener, TopologySessionStats {
80     static final MessageHeader MESSAGE_HEADER = new MessageHeader() {
81         private final ProtocolVersion version = new ProtocolVersion((short) 1);
82
83         @Override
84         public Class<? extends DataContainer> getImplementedInterface() {
85             return MessageHeader.class;
86         }
87
88         @Override
89         public ProtocolVersion getVersion() {
90             return this.version;
91         }
92     };
93     static final String MISSING_XML_TAG = "Mandatory XML tags are missing.";
94     private static final Logger LOG = LoggerFactory.getLogger(AbstractTopologySessionListener.class);
95     @GuardedBy("this")
96     final Map<L, String> lsps = new HashMap<>();
97     @GuardedBy("this")
98     final SessionStateImpl listenerState;
99     @GuardedBy("this")
100     private final Map<S, PCEPRequest> requests = new HashMap<>();
101     @GuardedBy("this")
102     private final Map<String, ReportedLsp> lspData = new HashMap<>();
103     private final ServerSessionManager serverSessionManager;
104     private InstanceIdentifier<PathComputationClient> pccIdentifier;
105     @GuardedBy("this")
106     private TopologyNodeState nodeState;
107     private AtomicBoolean synced = new AtomicBoolean(false);
108     @GuardedBy("this")
109     private PCEPSession session;
110     @GuardedBy("this")
111     private SyncOptimization syncOptimization;
112     @GuardedBy("this")
113     private boolean triggeredResyncInProcess;
114
115     AbstractTopologySessionListener(final ServerSessionManager serverSessionManager) {
116         this.serverSessionManager = requireNonNull(serverSessionManager);
117         this.listenerState = new SessionStateImpl(this);
118     }
119
120     @Override
121     public final synchronized void onSessionUp(final PCEPSession session) {
122         /*
123          * The session went up. Look up the router in Inventory model,
124          * create it if it is not there (marking that fact for later
125          * deletion), and mark it as synchronizing. Also create it in
126          * the topology model, with empty LSP list.
127          */
128         final InetAddress peerAddress = session.getRemoteAddress();
129
130         this.syncOptimization = new SyncOptimization(session);
131
132         final TopologyNodeState state = this.serverSessionManager.takeNodeState(peerAddress,
133                 this, isLspDbRetreived());
134
135         // takeNodeState(..) may fail when the server session manager is being restarted due to configuration change
136         if (state == null) {
137             LOG.error("Unable to fetch topology node state for PCEP session. Closing session {}", session);
138             session.close(TerminationReason.UNKNOWN);
139             this.onSessionTerminated(session, new PCEPCloseTermination(TerminationReason.UNKNOWN));
140             return;
141         }
142
143         if (this.session != null || this.nodeState != null) {
144             LOG.error("PCEP session is already up with {}. Closing session {}", session.getRemoteAddress(), session);
145             session.close(TerminationReason.UNKNOWN);
146             this.onSessionTerminated(session, new PCEPCloseTermination(TerminationReason.UNKNOWN));
147             return;
148         }
149         this.session = session;
150         this.nodeState = state;
151         this.serverSessionManager.bind(this.nodeState.getNodeId(), this.listenerState);
152
153         LOG.trace("Peer {} resolved to topology node {}", peerAddress, state.getNodeId());
154
155         // Our augmentation in the topology node
156         final PathComputationClientBuilder pccBuilder = new PathComputationClientBuilder();
157
158         onSessionUp(session, pccBuilder);
159         this.synced.set(isSynchronized());
160
161         pccBuilder.setIpAddress(IpAddressBuilder.getDefaultInstance(peerAddress.getHostAddress()));
162         final InstanceIdentifier<Node1> topologyAugment = state.getNodeId().augmentation(Node1.class);
163         this.pccIdentifier = topologyAugment.child(PathComputationClient.class);
164         final Node initialNodeState = state.getInitialNodeState();
165         final boolean isNodePresent = isLspDbRetreived() && initialNodeState != null;
166         if (isNodePresent) {
167             loadLspData(initialNodeState, this.lspData, this.lsps, isIncrementalSynchro());
168             pccBuilder.setReportedLsp(initialNodeState.getAugmentation(Node1.class)
169                     .getPathComputationClient().getReportedLsp());
170         }
171         writeNode(pccBuilder, state, topologyAugment);
172         this.listenerState.init(session);
173         LOG.info("Session with {} attached to topology node {}", session.getRemoteAddress(), state.getNodeId());
174     }
175
176     private void writeNode(final PathComputationClientBuilder pccBuilder, final TopologyNodeState state,
177             final InstanceIdentifier<Node1> topologyAugment) {
178         final Node1 ta = new Node1Builder().setPathComputationClient(pccBuilder.build()).build();
179
180         final ReadWriteTransaction trans = state.rwTransaction();
181         trans.put(LogicalDatastoreType.OPERATIONAL, topologyAugment, ta);
182         LOG.trace("Peer data {} set to {}", topologyAugment, ta);
183
184         // All set, commit the modifications
185         Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
186             @Override
187             public void onSuccess(final Void result) {
188                 LOG.trace("Internal state for session {} updated successfully",
189                         AbstractTopologySessionListener.this.session);
190             }
191
192             @Override
193             public void onFailure(final Throwable throwable) {
194                 LOG.error("Failed to update internal state for session {}, terminating it",
195                         AbstractTopologySessionListener.this.session, throwable);
196                 AbstractTopologySessionListener.this.session.close(TerminationReason.UNKNOWN);
197             }
198         }, MoreExecutors.directExecutor());
199     }
200
201     synchronized void updatePccState(final PccSyncState pccSyncState) {
202         if (this.nodeState == null) {
203             LOG.info("Server Session Manager is closed.");
204             AbstractTopologySessionListener.this.session.close(TerminationReason.UNKNOWN);
205             return;
206         }
207         final MessageContext ctx = new MessageContext(this.nodeState.beginTransaction());
208         updatePccNode(ctx, new PathComputationClientBuilder().setStateSync(pccSyncState).build());
209         if (pccSyncState != PccSyncState.Synchronized) {
210             this.synced.set(false);
211             this.triggeredResyncInProcess = true;
212         }
213         // All set, commit the modifications
214         Futures.addCallback(ctx.trans.submit(), new FutureCallback<Void>() {
215             @Override
216             public void onSuccess(final Void result) {
217                 LOG.trace("Internal state for session {} updated successfully",
218                         AbstractTopologySessionListener.this.session);
219             }
220
221             @Override
222             public void onFailure(final Throwable throwable) {
223                 LOG.error("Failed to update internal state for session {}",
224                         AbstractTopologySessionListener.this.session, throwable);
225                 AbstractTopologySessionListener.this.session.close(TerminationReason.UNKNOWN);
226             }
227         }, MoreExecutors.directExecutor());
228     }
229
230     synchronized boolean isTriggeredSyncInProcess() {
231         return this.triggeredResyncInProcess;
232     }
233
234     /**
235      * Tear down the given PCEP session. It's OK to call this method even after the session
236      * is already down. It always clear up the current session status.
237      */
238     @GuardedBy("this")
239     @SuppressWarnings("checkstyle:IllegalCatch")
240     private synchronized void tearDown(final PCEPSession session) {
241
242         requireNonNull(session);
243         this.serverSessionManager.releaseNodeState(this.nodeState, session, isLspDbPersisted());
244         clearNodeState();
245
246         try {
247             if (this.session != null) {
248                 this.session.close();
249             }
250             session.close();
251         } catch (final Exception e) {
252             LOG.error("Session {} cannot be closed.", session, e);
253         }
254         this.session = null;
255         this.syncOptimization = null;
256
257         // Clear all requests we know about
258         for (final Entry<S, PCEPRequest> e : this.requests.entrySet()) {
259             final PCEPRequest r = e.getValue();
260             switch (r.getState()) {
261                 case DONE:
262                     // Done is done, nothing to do
263                     LOG.trace("Request {} was done when session went down.", e.getKey());
264                     break;
265                 case UNACKED:
266                     // Peer has not acked: results in failure
267                     LOG.info("Request {} was incomplete when session went down, failing the instruction", e.getKey());
268                     r.done(OperationResults.NOACK);
269                     break;
270                 case UNSENT:
271                     // Peer has not been sent to the peer: results in cancellation
272                     LOG.debug("Request {} was not sent when session went down, cancelling the instruction", e.getKey());
273                     r.done(OperationResults.UNSENT);
274                     break;
275                 default:
276                     break;
277             }
278         }
279         this.requests.clear();
280     }
281
282     @Override
283     public final synchronized void onSessionDown(final PCEPSession session, final Exception exception) {
284         LOG.warn("Session {} went down unexpectedly", session, exception);
285         tearDown(session);
286     }
287
288     @Override
289     public final synchronized void onSessionTerminated(final PCEPSession session, final PCEPTerminationReason reason) {
290         LOG.info("Session {} terminated by peer with reason {}", session, reason);
291         tearDown(session);
292     }
293
294     @Override
295     public final synchronized void onMessage(final PCEPSession session, final Message message) {
296         if (this.nodeState == null) {
297             LOG.warn("Topology node state is null. Unhandled message {} on session {}", message, session);
298             session.close(TerminationReason.UNKNOWN);
299             return;
300         }
301         final MessageContext ctx = new MessageContext(this.nodeState.beginTransaction());
302
303         if (onMessage(ctx, message)) {
304             LOG.warn("Unhandled message {} on session {}", message, session);
305             //cancel not supported, submit empty transaction
306             ctx.trans.submit();
307             return;
308         }
309
310         Futures.addCallback(ctx.trans.submit(), new FutureCallback<Void>() {
311             @Override
312             public void onSuccess(final Void result) {
313                 LOG.trace("Internal state for session {} updated successfully", session);
314                 ctx.notifyRequests();
315             }
316
317             @Override
318             public void onFailure(final Throwable throwable) {
319                 LOG.error("Failed to update internal state for session {}, closing it", session, throwable);
320                 ctx.notifyRequests();
321                 session.close(TerminationReason.UNKNOWN);
322             }
323         }, MoreExecutors.directExecutor());
324     }
325
326     @Override
327     public synchronized void close() {
328         clearNodeState();
329         if (this.session != null) {
330             LOG.info("Closing session {}", session);
331             this.session.close(TerminationReason.UNKNOWN);
332         }
333     }
334
335     private synchronized void clearNodeState() {
336         if (this.nodeState != null) {
337             this.serverSessionManager.unbind(this.nodeState.getNodeId());
338             this.nodeState = null;
339         }
340     }
341
342     final synchronized PCEPRequest removeRequest(final S id) {
343         final PCEPRequest ret = this.requests.remove(id);
344         if (ret != null) {
345             this.listenerState.processRequestStats(ret.getElapsedMillis());
346         }
347         LOG.trace("Removed request {} object {}", id, ret);
348         return ret;
349     }
350
351     final synchronized ListenableFuture<OperationResult> sendMessage(final Message message, final S requestId,
352             final Metadata metadata) {
353         final io.netty.util.concurrent.Future<Void> f = this.session.sendMessage(message);
354         this.listenerState.updateStatefulSentMsg(message);
355         final PCEPRequest req = new PCEPRequest(metadata);
356         this.requests.put(requestId, req);
357         final short rpcTimeout = this.serverSessionManager.getRpcTimeout();
358         LOG.trace("RPC response timeout value is {} seconds", rpcTimeout);
359         if (rpcTimeout > 0) {
360             setupTimeoutHandler(requestId, req, rpcTimeout);
361         }
362
363         f.addListener((FutureListener<Void>) future -> {
364             if (!future.isSuccess()) {
365                 synchronized (AbstractTopologySessionListener.this) {
366                     AbstractTopologySessionListener.this.requests.remove(requestId);
367                 }
368                 req.done(OperationResults.UNSENT);
369                 LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
370             } else {
371                 req.sent();
372                 LOG.trace("Request {} sent to peer (object {})", requestId, req);
373             }
374         });
375
376         return req.getFuture();
377     }
378
379     private void setupTimeoutHandler(final S requestId, final PCEPRequest req, final short timeout) {
380         final Timer timer = req.getTimer();
381         timer.schedule(new TimerTask() {
382             @Override
383             public void run() {
384                 synchronized (AbstractTopologySessionListener.this) {
385                     AbstractTopologySessionListener.this.requests.remove(requestId);
386                 }
387                 req.done();
388                 LOG.info("Request {} timed-out waiting for response", requestId);
389             }
390         }, TimeUnit.SECONDS.toMillis(timeout));
391         LOG.trace("Set up response timeout handler for request {}", requestId);
392     }
393
394     /**
395      * Update an LSP in the data store.
396      *
397      * @param ctx       Message context
398      * @param id        Revision-specific LSP identifier
399      * @param lspName   LSP name
400      * @param rlb       Reported LSP builder
401      * @param solicited True if the update was solicited
402      * @param remove    True if this is an LSP path removal
403      */
404     protected final synchronized void updateLsp(final MessageContext ctx, final L id, final String lspName,
405             final ReportedLspBuilder rlb, final boolean solicited, final boolean remove) {
406
407         final String name;
408         if (lspName == null) {
409             name = this.lsps.get(id);
410             if (name == null) {
411                 LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
412                 return;
413             }
414         } else {
415             name = lspName;
416         }
417
418         LOG.debug("Saved LSP {} with name {}", id, name);
419         this.lsps.put(id, name);
420
421
422         final ReportedLsp previous = this.lspData.get(name);
423         // if no previous report about the lsp exist, just proceed
424         if (previous != null) {
425             final List<Path> updatedPaths = makeBeforeBreak(rlb, previous, name, remove);
426             // if all paths or the last path were deleted, delete whole tunnel
427             if (updatedPaths.isEmpty()) {
428                 LOG.debug("All paths were removed, removing LSP with {}.", id);
429                 removeLsp(ctx, id);
430                 return;
431             }
432             rlb.setPath(updatedPaths);
433         }
434         rlb.setKey(new ReportedLspKey(name));
435         rlb.setName(name);
436
437         // If this is an unsolicited update. We need to make sure we retain the metadata already present
438         if (solicited) {
439             this.nodeState.setLspMetadata(name, rlb.getMetadata());
440         } else {
441             rlb.setMetadata(this.nodeState.getLspMetadata(name));
442         }
443
444         final ReportedLsp rl = rlb.build();
445         ctx.trans.put(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier.child(ReportedLsp.class, rlb.getKey()), rl);
446         LOG.debug("LSP {} updated to MD-SAL", name);
447
448         this.lspData.put(name, rl);
449     }
450
451     private List<Path> makeBeforeBreak(final ReportedLspBuilder rlb, final ReportedLsp previous, final String name,
452             final boolean remove) {
453         // just one path should be reported
454         Preconditions.checkState(rlb.getPath().size() == 1);
455         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.LspId reportedLspId =
456                 rlb.getPath().get(0).getLspId();
457         final List<Path> updatedPaths;
458         //lspId = 0 and remove = false -> tunnel is down, still exists but no path is signaled
459         //remove existing tunnel's paths now, as explicit path remove will not come
460         if (!remove && reportedLspId.getValue() == 0) {
461             updatedPaths = new ArrayList<>();
462             LOG.debug("Remove previous paths {} to this lsp name {}", previous.getPath(), name);
463         } else {
464             // check previous report for existing paths
465             updatedPaths = new ArrayList<>(previous.getPath());
466             LOG.debug("Found previous paths {} to this lsp name {}", updatedPaths, name);
467             for (final Path path : previous.getPath()) {
468                 //we found reported path in previous reports
469                 if (path.getLspId().getValue() == 0 || path.getLspId().equals(reportedLspId)) {
470                     LOG.debug("Match on lsp-id {}", path.getLspId().getValue());
471                     // path that was reported previously and does have the same lsp-id, path will be updated
472                     final boolean r = updatedPaths.remove(path);
473                     LOG.trace("Request removed? {}", r);
474                 }
475             }
476         }
477         // if the path does not exist in previous report, add it to path list, it's a new ERO
478         // only one path will be added
479         //lspId is 0 means confirmation message that shouldn't be added (because we have no means of deleting it later)
480         LOG.trace("Adding new path {} to {}", rlb.getPath(), updatedPaths);
481         updatedPaths.addAll(rlb.getPath());
482         if (remove) {
483             if (reportedLspId.getValue() == 0) {
484                 // if lsp-id also 0, remove all paths
485                 LOG.debug("Removing all paths.");
486                 updatedPaths.clear();
487             } else {
488                 // path is marked to be removed
489                 LOG.debug("Removing path {} from {}", rlb.getPath(), updatedPaths);
490                 final boolean r = updatedPaths.removeAll(rlb.getPath());
491                 LOG.trace("Request removed? {}", r);
492             }
493         }
494         LOG.debug("Setting new paths {} to lsp {}", updatedPaths, name);
495         return updatedPaths;
496     }
497
498     /**
499      * Indicate that the peer has completed state synchronization.
500      *
501      * @param ctx Message context
502      */
503     protected final synchronized void stateSynchronizationAchieved(final MessageContext ctx) {
504         if (this.synced.getAndSet(true)) {
505             LOG.debug("State synchronization achieved while synchronizing, not updating state");
506             return;
507         }
508         if (this.triggeredResyncInProcess) {
509             this.triggeredResyncInProcess = false;
510         }
511         updatePccNode(ctx, new PathComputationClientBuilder().setStateSync(PccSyncState.Synchronized).build());
512
513         // The node has completed synchronization, cleanup metadata no longer reported back
514         this.nodeState.cleanupExcept(this.lsps.values());
515         LOG.debug("Session {} achieved synchronized state", this.session);
516     }
517
518     protected final synchronized void updatePccNode(final MessageContext ctx, final PathComputationClient pcc) {
519         ctx.trans.merge(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier, pcc);
520     }
521
522     protected final InstanceIdentifier<ReportedLsp> lspIdentifier(final String name) {
523         return this.pccIdentifier.child(ReportedLsp.class, new ReportedLspKey(name));
524     }
525
526     /**
527      * Remove LSP from the database.
528      *
529      * @param ctx Message Context
530      * @param id  Revision-specific LSP identifier
531      */
532     protected final synchronized void removeLsp(final MessageContext ctx, final L id) {
533         final String name = this.lsps.remove(id);
534         LOG.debug("LSP {} removed", name);
535         ctx.trans.delete(LogicalDatastoreType.OPERATIONAL, lspIdentifier(name));
536         this.lspData.remove(name);
537     }
538
539     @SuppressWarnings("checkstyle:OverloadMethodsDeclarationOrder")
540     protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
541
542     /**
543      * Perform revision-specific message processing when a message arrives.
544      *
545      * @param ctx     Message processing context
546      * @param message Protocol message
547      * @return True if the message type is not handle.
548      */
549     @SuppressWarnings("checkstyle:OverloadMethodsDeclarationOrder")
550     protected abstract boolean onMessage(MessageContext ctx, Message message);
551
552     final String lookupLspName(final L id) {
553         requireNonNull(id, "ID parameter null.");
554         return this.lsps.get(id);
555     }
556
557     /**
558      * Reads operational data on this node. Doesn't attempt to read the data,
559      * if the node does not exist. In this case returns null.
560      *
561      * @param id InstanceIdentifier of the node
562      * @return null if the node does not exists, or operational data
563      */
564     final synchronized <T extends DataObject> ListenableFuture<Optional<T>>
565         readOperationalData(final InstanceIdentifier<T> id) {
566         if (this.nodeState == null) {
567             return null;
568         }
569         return this.nodeState.readOperationalData(id);
570     }
571
572     protected abstract Object validateReportedLsp(Optional<ReportedLsp> rep, LspId input);
573
574     protected abstract void loadLspData(Node node, Map<String, ReportedLsp> lspData, Map<L, String> lsps,
575             boolean incrementalSynchro);
576
577     final boolean isLspDbPersisted() {
578         return this.syncOptimization != null && this.syncOptimization.isSyncAvoidanceEnabled();
579     }
580
581     final boolean isLspDbRetreived() {
582         return this.syncOptimization != null && this.syncOptimization.isDbVersionPresent();
583     }
584
585     /**
586      * Is Incremental synchronization if LSP-DB-VERSION are included,
587      * LSP-DB-VERSION TLV values doesnt match, and  LSP-SYNC-CAPABILITY is enabled.
588      */
589     final synchronized boolean isIncrementalSynchro() {
590         return this.syncOptimization != null && this.syncOptimization.isSyncAvoidanceEnabled()
591                 && this.syncOptimization.isDeltaSyncEnabled();
592     }
593
594     final synchronized boolean isTriggeredInitialSynchro() {
595         return this.syncOptimization != null && this.syncOptimization.isTriggeredInitSyncEnabled();
596     }
597
598     final synchronized boolean isTriggeredReSyncEnabled() {
599         return this.syncOptimization != null && this.syncOptimization.isTriggeredReSyncEnabled();
600     }
601
602     protected final synchronized boolean isSynchronized() {
603         return this.syncOptimization != null && this.syncOptimization.doesLspDbMatch();
604     }
605
606     @Override
607     public synchronized int getDelegatedLspsCount() {
608         return Math.toIntExact(this.lspData.values().stream()
609                 .map(ReportedLsp::getPath).filter(Objects::nonNull).filter(pathList -> !pathList.isEmpty())
610                 // pick the first path, as delegate status should be same in each path
611                 .map(pathList -> pathList.get(0))
612                 .map(path -> path.getAugmentation(Path1.class)).filter(Objects::nonNull)
613                 .map(LspObject::getLsp).filter(Objects::nonNull)
614                 .filter(Lsp::isDelegate)
615                 .count());
616     }
617
618     @Override
619     public boolean isSessionSynchronized() {
620         return this.synced.get();
621     }
622
623     @Override
624     public synchronized ListenableFuture<RpcResult<Void>> tearDownSession(final TearDownSessionInput input) {
625         close();
626         return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
627     }
628
629     static final class MessageContext {
630         private final Collection<PCEPRequest> requests = new ArrayList<>();
631         private final WriteTransaction trans;
632
633         private MessageContext(final WriteTransaction trans) {
634             this.trans = requireNonNull(trans);
635         }
636
637         void resolveRequest(final PCEPRequest req) {
638             this.requests.add(req);
639         }
640
641         private void notifyRequests() {
642             for (final PCEPRequest r : this.requests) {
643                 r.done(OperationResults.SUCCESS);
644             }
645         }
646     }
647 }