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