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