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