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