Enforce checkstyle and findbug under PCE Api
[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     private TopologyNodeState nodeState;
106     private AtomicBoolean synced = new AtomicBoolean(false);
107     private PCEPSession session;
108     private SyncOptimization syncOptimization;
109     private boolean triggeredResyncInProcess;
110
111     AbstractTopologySessionListener(final ServerSessionManager serverSessionManager) {
112         this.serverSessionManager = requireNonNull(serverSessionManager);
113         this.listenerState = new SessionStateImpl(this);
114     }
115
116     @Override
117     public final synchronized void onSessionUp(final PCEPSession session) {
118         /*
119          * The session went up. Look up the router in Inventory model,
120          * create it if it is not there (marking that fact for later
121          * deletion), and mark it as synchronizing. Also create it in
122          * the topology model, with empty LSP list.
123          */
124         final InetAddress peerAddress = session.getRemoteAddress();
125
126         this.syncOptimization = new SyncOptimization(session);
127
128         final TopologyNodeState state = this.serverSessionManager.takeNodeState(peerAddress,
129                 this, isLspDbRetreived());
130
131         // takeNodeState(..) may fail when the server session manager is being restarted due to configuration change
132         if (state == null) {
133             LOG.error("Unable to fetch topology node state for PCEP session. Closing session {}", session);
134             session.close(TerminationReason.UNKNOWN);
135             this.onSessionTerminated(session, new PCEPCloseTermination(TerminationReason.UNKNOWN));
136             return;
137         }
138
139         if (this.session != null || this.nodeState != null) {
140             LOG.error("PCEP session is already up with {}. Closing session {}", session.getRemoteAddress(), session);
141             session.close(TerminationReason.UNKNOWN);
142             this.onSessionTerminated(session, new PCEPCloseTermination(TerminationReason.UNKNOWN));
143             return;
144         }
145         this.session = session;
146         this.nodeState = state;
147         this.serverSessionManager.bind(this.nodeState.getNodeId(), this.listenerState);
148
149         LOG.trace("Peer {} resolved to topology node {}", peerAddress, state.getNodeId());
150
151         // Our augmentation in the topology node
152         final PathComputationClientBuilder pccBuilder = new PathComputationClientBuilder();
153
154         onSessionUp(session, pccBuilder);
155         this.synced.set(isSynchronized());
156
157         pccBuilder.setIpAddress(IpAddressBuilder.getDefaultInstance(peerAddress.getHostAddress()));
158         final InstanceIdentifier<Node1> topologyAugment = state.getNodeId().augmentation(Node1.class);
159         this.pccIdentifier = topologyAugment.child(PathComputationClient.class);
160         final Node initialNodeState = state.getInitialNodeState();
161         final boolean isNodePresent = isLspDbRetreived() && initialNodeState != null;
162         if (isNodePresent) {
163             loadLspData(initialNodeState, this.lspData, this.lsps, isIncrementalSynchro());
164             pccBuilder.setReportedLsp(initialNodeState.getAugmentation(Node1.class)
165                     .getPathComputationClient().getReportedLsp());
166         }
167         writeNode(pccBuilder, state, topologyAugment);
168         this.listenerState.init(session);
169         LOG.info("Session with {} attached to topology node {}", session.getRemoteAddress(), state.getNodeId());
170     }
171
172     private void writeNode(final PathComputationClientBuilder pccBuilder, final TopologyNodeState state,
173             final InstanceIdentifier<Node1> topologyAugment) {
174         final Node1 ta = new Node1Builder().setPathComputationClient(pccBuilder.build()).build();
175
176         final ReadWriteTransaction trans = state.rwTransaction();
177         trans.put(LogicalDatastoreType.OPERATIONAL, topologyAugment, ta);
178         LOG.trace("Peer data {} set to {}", topologyAugment, ta);
179
180         // All set, commit the modifications
181         Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
182             @Override
183             public void onSuccess(final Void result) {
184                 LOG.trace("Internal state for session {} updated successfully",
185                         AbstractTopologySessionListener.this.session);
186             }
187
188             @Override
189             public void onFailure(final Throwable t) {
190                 LOG.error("Failed to update internal state for session {}, terminating it",
191                         AbstractTopologySessionListener.this.session, t);
192                 AbstractTopologySessionListener.this.session.close(TerminationReason.UNKNOWN);
193             }
194         }, MoreExecutors.directExecutor());
195     }
196
197     void updatePccState(final PccSyncState pccSyncState) {
198         if (this.nodeState == null) {
199             LOG.info("Server Session Manager is closed.");
200             AbstractTopologySessionListener.this.session.close(TerminationReason.UNKNOWN);
201             return;
202         }
203         final MessageContext ctx = new MessageContext(this.nodeState.beginTransaction());
204         updatePccNode(ctx, new PathComputationClientBuilder().setStateSync(pccSyncState).build());
205         if (pccSyncState != PccSyncState.Synchronized) {
206             this.synced.set(false);
207             this.triggeredResyncInProcess = true;
208         }
209         // All set, commit the modifications
210         Futures.addCallback(ctx.trans.submit(), new FutureCallback<Void>() {
211             @Override
212             public void onSuccess(final Void result) {
213                 LOG.trace("Internal state for session {} updated successfully", AbstractTopologySessionListener.this.session);
214             }
215
216             @Override
217             public void onFailure(final Throwable t) {
218                 LOG.error("Failed to update internal state for session {}", AbstractTopologySessionListener.this.session, t);
219                 AbstractTopologySessionListener.this.session.close(TerminationReason.UNKNOWN);
220             }
221         }, MoreExecutors.directExecutor());
222     }
223
224     boolean isTriggeredSyncInProcess() {
225         return this.triggeredResyncInProcess;
226     }
227
228     /**
229      * Tear down the given PCEP session. It's OK to call this method even after the session
230      * is already down. It always clear up the current session status.
231      *
232      * @param session
233      */
234     @GuardedBy("this")
235     private synchronized void tearDown(final PCEPSession session) {
236
237         requireNonNull(session);
238         this.serverSessionManager.releaseNodeState(this.nodeState, session, isLspDbPersisted());
239         if (this.nodeState != null) {
240             this.serverSessionManager.unbind(this.nodeState.getNodeId());
241             this.nodeState = null;
242         }
243
244         try {
245             if (this.session != null) {
246                 this.session.close();
247             }
248             session.close();
249         } catch (final Exception e) {
250             LOG.error("Session {} cannot be closed.", session, e);
251         }
252         this.session = null;
253         this.syncOptimization = null;
254
255         // Clear all requests we know about
256         for (final Entry<S, PCEPRequest> e : this.requests.entrySet()) {
257             final PCEPRequest r = e.getValue();
258             switch (r.getState()) {
259                 case DONE:
260                     // Done is done, nothing to do
261                     LOG.trace("Request {} was done when session went down.", e.getKey());
262                     break;
263                 case UNACKED:
264                     // Peer has not acked: results in failure
265                     LOG.info("Request {} was incomplete when session went down, failing the instruction", e.getKey());
266                     r.done(OperationResults.NOACK);
267                     break;
268                 case UNSENT:
269                     // Peer has not been sent to the peer: results in cancellation
270                     LOG.debug("Request {} was not sent when session went down, cancelling the instruction", e.getKey());
271                     r.done(OperationResults.UNSENT);
272                     break;
273                 default:
274                     break;
275             }
276         }
277         this.requests.clear();
278     }
279
280     @Override
281     public final synchronized void onSessionDown(final PCEPSession session, final Exception exception) {
282         LOG.warn("Session {} went down unexpectedly", session, exception);
283         tearDown(session);
284     }
285
286     @Override
287     public final synchronized void onSessionTerminated(final PCEPSession session, final PCEPTerminationReason reason) {
288         LOG.info("Session {} terminated by peer with reason {}", session, reason);
289         tearDown(session);
290     }
291
292     @Override
293     public final synchronized void onMessage(final PCEPSession session, final Message message) {
294         if (this.nodeState == null) {
295             LOG.warn("Topology node state is null. Unhandled message {} on session {}", message, session);
296             session.close(TerminationReason.UNKNOWN);
297             return;
298         }
299         final MessageContext ctx = new MessageContext(this.nodeState.beginTransaction());
300
301         if (onMessage(ctx, message)) {
302             LOG.warn("Unhandled message {} on session {}", message, session);
303             //cancel not supported, submit empty transaction
304             ctx.trans.submit();
305             return;
306         }
307
308         Futures.addCallback(ctx.trans.submit(), new FutureCallback<Void>() {
309             @Override
310             public void onSuccess(final Void result) {
311                 LOG.trace("Internal state for session {} updated successfully", session);
312                 ctx.notifyRequests();
313             }
314
315             @Override
316             public void onFailure(final Throwable t) {
317                 LOG.error("Failed to update internal state for session {}, closing it", session, t);
318                 ctx.notifyRequests();
319                 session.close(TerminationReason.UNKNOWN);
320             }
321         }, MoreExecutors.directExecutor());
322     }
323
324     @Override
325     public void close() {
326         if (this.session != null) {
327             LOG.info("Closing session {}", session);
328             this.session.close(TerminationReason.UNKNOWN);
329         }
330     }
331
332     final synchronized PCEPRequest removeRequest(final S id) {
333         final PCEPRequest ret = this.requests.remove(id);
334         if (ret != null) {
335             this.listenerState.processRequestStats(ret.getElapsedMillis());
336         }
337         LOG.trace("Removed request {} object {}", id, ret);
338         return ret;
339     }
340
341     final synchronized ListenableFuture<OperationResult> sendMessage(final Message message, final S requestId,
342             final Metadata metadata) {
343         final io.netty.util.concurrent.Future<Void> f = this.session.sendMessage(message);
344         this.listenerState.updateStatefulSentMsg(message);
345         final PCEPRequest req = new PCEPRequest(metadata);
346         this.requests.put(requestId, req);
347         final short rpcTimeout = this.serverSessionManager.getRpcTimeout();
348         LOG.trace("RPC response timeout value is {} seconds", rpcTimeout);
349         if (rpcTimeout > 0) {
350             setupTimeoutHandler(requestId, req, rpcTimeout);
351         }
352
353         f.addListener((FutureListener<Void>) future -> {
354             if (!future.isSuccess()) {
355                 synchronized (AbstractTopologySessionListener.this) {
356                     AbstractTopologySessionListener.this.requests.remove(requestId);
357                 }
358                 req.done(OperationResults.UNSENT);
359                 LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
360             } else {
361                 req.sent();
362                 LOG.trace("Request {} sent to peer (object {})", requestId, req);
363             }
364         });
365
366         return req.getFuture();
367     }
368
369     private void setupTimeoutHandler(final S requestId, final PCEPRequest req, final short timeout) {
370         final Timer timer = req.getTimer();
371         timer.schedule(new TimerTask() {
372             @Override
373             public void run() {
374                 synchronized (AbstractTopologySessionListener.this) {
375                     AbstractTopologySessionListener.this.requests.remove(requestId);
376                 }
377                 req.done();
378                 LOG.info("Request {} timed-out waiting for response", requestId);
379             }
380         }, TimeUnit.SECONDS.toMillis(timeout));
381         LOG.trace("Set up response timeout handler for request {}", requestId);
382     }
383
384     /**
385      * Update an LSP in the data store
386      *
387      * @param ctx       Message context
388      * @param id        Revision-specific LSP identifier
389      * @param lspName   LSP name
390      * @param rlb       Reported LSP builder
391      * @param solicited True if the update was solicited
392      * @param remove    True if this is an LSP path removal
393      */
394     protected final synchronized void updateLsp(final MessageContext ctx, final L id, final String lspName,
395             final ReportedLspBuilder rlb, final boolean solicited, final boolean remove) {
396
397         final String name;
398         if (lspName == null) {
399             name = this.lsps.get(id);
400             if (name == null) {
401                 LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
402                 return;
403             }
404         } else {
405             name = lspName;
406         }
407
408         LOG.debug("Saved LSP {} with name {}", id, name);
409         this.lsps.put(id, name);
410
411
412         final ReportedLsp previous = this.lspData.get(name);
413         // if no previous report about the lsp exist, just proceed
414         if (previous != null) {
415             final List<Path> updatedPaths = makeBeforeBreak(rlb, previous, name, remove);
416             // if all paths or the last path were deleted, delete whole tunnel
417             if (updatedPaths == null || updatedPaths.isEmpty()) {
418                 LOG.debug("All paths were removed, removing LSP with {}.", id);
419                 removeLsp(ctx, id);
420                 return;
421             }
422             rlb.setPath(updatedPaths);
423         }
424         rlb.setKey(new ReportedLspKey(name));
425         rlb.setName(name);
426
427         // If this is an unsolicited update. We need to make sure we retain the metadata already present
428         if (solicited) {
429             this.nodeState.setLspMetadata(name, rlb.getMetadata());
430         } else {
431             rlb.setMetadata(this.nodeState.getLspMetadata(name));
432         }
433
434         final ReportedLsp rl = rlb.build();
435         ctx.trans.put(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier.child(ReportedLsp.class, rlb.getKey()), rl);
436         LOG.debug("LSP {} updated to MD-SAL", name);
437
438         this.lspData.put(name, rl);
439     }
440
441     private List<Path> makeBeforeBreak(final ReportedLspBuilder rlb, final ReportedLsp previous, final String name, final boolean remove) {
442         // just one path should be reported
443         Preconditions.checkState(rlb.getPath().size() == 1);
444         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.LspId reportedLspId = 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     protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
528
529     /**
530      * Perform revision-specific message processing when a message arrives.
531      *
532      * @param ctx     Message processing context
533      * @param message Protocol message
534      * @return True if the message type is not handle.
535      */
536     protected abstract boolean onMessage(MessageContext ctx, Message message);
537
538     final String lookupLspName(final L id) {
539         requireNonNull(id, "ID parameter null.");
540         return this.lsps.get(id);
541     }
542
543     /**
544      * Reads operational data on this node. Doesn't attempt to read the data,
545      * if the node does not exist. In this case returns null.
546      *
547      * @param id InstanceIdentifier of the node
548      * @return null if the node does not exists, or operational data
549      */
550     final synchronized <T extends DataObject> ListenableFuture<Optional<T>>
551     readOperationalData(final InstanceIdentifier<T> id) {
552         if (this.nodeState == null) {
553             return null;
554         }
555         return this.nodeState.readOperationalData(id);
556     }
557
558     protected abstract Object validateReportedLsp(final Optional<ReportedLsp> rep, final LspId input);
559
560     protected abstract void loadLspData(final Node node, final Map<String, ReportedLsp> lspData,
561             final Map<L, String> lsps, final boolean incrementalSynchro);
562
563     final boolean isLspDbPersisted() {
564         return this.syncOptimization != null && this.syncOptimization.isSyncAvoidanceEnabled();
565     }
566
567     final boolean isLspDbRetreived() {
568         return this.syncOptimization != null && this.syncOptimization.isDbVersionPresent();
569     }
570
571     /**
572      * Is Incremental synchronization if LSP-DB-VERSION are included,
573      * LSP-DB-VERSION TLV values doesnt match, and  LSP-SYNC-CAPABILITY is enabled
574      *
575      * @return
576      */
577     final boolean isIncrementalSynchro() {
578         return this.syncOptimization != null &&
579                 this.syncOptimization.isSyncAvoidanceEnabled() &&
580                 this.syncOptimization.isDeltaSyncEnabled();
581     }
582
583     final boolean isTriggeredInitialSynchro() {
584         return this.syncOptimization != null &&
585                 this.syncOptimization.isTriggeredInitSyncEnabled();
586     }
587
588     final boolean isTriggeredReSyncEnabled() {
589         return this.syncOptimization != null &&
590                 this.syncOptimization.isTriggeredReSyncEnabled();
591     }
592
593     protected final boolean isSynchronized() {
594         return this.syncOptimization != null &&
595                 this.syncOptimization.doesLspDbMatch();
596     }
597
598     @Override
599     public synchronized int getDelegatedLspsCount() {
600         return Math.toIntExact(this.lspData.values().stream()
601                 .map(ReportedLsp::getPath).filter(Objects::nonNull).filter(pathList -> !pathList.isEmpty())
602                 // pick the first path, as delegate status should be same in each path
603                 .map(pathList -> pathList.get(0))
604                 .map(path -> path.getAugmentation(Path1.class)).filter(Objects::nonNull)
605                 .map(LspObject::getLsp).filter(Objects::nonNull)
606                 .filter(Lsp::isDelegate)
607                 .count());
608     }
609
610     @Override
611     public boolean isSessionSynchronized() {
612         return this.synced.get();
613     }
614
615     @Override
616     public synchronized ListenableFuture<RpcResult<Void>> tearDownSession(final TearDownSessionInput input) {
617         close();
618         return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
619     }
620
621     static final class MessageContext {
622         private final Collection<PCEPRequest> requests = new ArrayList<>();
623         private final WriteTransaction trans;
624
625         private MessageContext(final WriteTransaction trans) {
626             this.trans = requireNonNull(trans);
627         }
628
629         void resolveRequest(final PCEPRequest req) {
630             this.requests.add(req);
631         }
632
633         private void notifyRequests() {
634             for (final PCEPRequest r : this.requests) {
635                 r.done(OperationResults.SUCCESS);
636             }
637         }
638     }
639 }