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