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