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