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