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