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