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