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