Move onSessionUp()/onMessage() method declarations
[bgpcep.git] / pcep / topology / topology-provider / src / main / java / org / opendaylight / bgpcep / pcep / topology / provider / TopologyNodeState.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 com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.util.concurrent.FluentFuture;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.MoreExecutors;
15 import java.util.Collection;
16 import java.util.HashMap;
17 import java.util.Map;
18 import java.util.Optional;
19 import java.util.concurrent.ExecutionException;
20 import org.checkerframework.checker.lock.qual.GuardedBy;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.opendaylight.mdsal.binding.api.DataBroker;
23 import org.opendaylight.mdsal.binding.api.ReadTransaction;
24 import org.opendaylight.mdsal.binding.api.Transaction;
25 import org.opendaylight.mdsal.binding.api.TransactionChain;
26 import org.opendaylight.mdsal.binding.api.TransactionChainListener;
27 import org.opendaylight.mdsal.binding.api.WriteTransaction;
28 import org.opendaylight.mdsal.common.api.CommitInfo;
29 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
30 import org.opendaylight.protocol.pcep.PCEPSession;
31 import org.opendaylight.protocol.pcep.TerminationReason;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.Node1;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.lsp.metadata.Metadata;
34 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
35 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
36 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
37 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
38 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
39 import org.opendaylight.yangtools.yang.binding.DataObject;
40 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
41 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 // This class is thread-safe
46 final class TopologyNodeState implements TransactionChainListener {
47     private static final Logger LOG = LoggerFactory.getLogger(TopologyNodeState.class);
48
49     private final Map<String, Metadata> metadata = new HashMap<>();
50     private final KeyedInstanceIdentifier<Node, NodeKey> nodeId;
51     private final TransactionChain chain;
52     private final long holdStateNanos;
53     private long lastReleased = 0;
54     //cache initial node state, if any node was persisted
55     @GuardedBy("this")
56     private Node initialNodeState = null;
57
58     TopologyNodeState(final DataBroker broker, final InstanceIdentifier<Topology> topology, final NodeId id,
59             final long holdStateNanos) {
60         checkArgument(holdStateNanos >= 0);
61         nodeId = topology.child(Node.class, new NodeKey(id));
62         this.holdStateNanos = holdStateNanos;
63         chain = broker.createMergingTransactionChain(this);
64     }
65
66     @NonNull KeyedInstanceIdentifier<Node, NodeKey> getNodeId() {
67         return nodeId;
68     }
69
70     synchronized Metadata getLspMetadata(final String name) {
71         return metadata.get(name);
72     }
73
74     synchronized void setLspMetadata(final String name, final Metadata value) {
75         if (value == null) {
76             metadata.remove(name);
77         } else {
78             metadata.put(name, value);
79         }
80     }
81
82     synchronized void cleanupExcept(final Collection<String> values) {
83         metadata.keySet().removeIf(s -> !values.contains(s));
84     }
85
86     synchronized void released(final boolean persist) {
87         // The session went down. Undo all the Topology changes we have done.
88         // We might want to persist topology node for later re-use.
89         if (!persist) {
90             final WriteTransaction trans = chain.newWriteOnlyTransaction();
91             trans.delete(LogicalDatastoreType.OPERATIONAL, nodeId);
92             trans.commit().addCallback(new FutureCallback<CommitInfo>() {
93                 @Override
94                 public void onSuccess(final CommitInfo result) {
95                     LOG.trace("Internal state for node {} cleaned up successfully", nodeId);
96                 }
97
98                 @Override
99                 public void onFailure(final Throwable throwable) {
100                     LOG.error("Failed to cleanup internal state for session {}", nodeId, throwable);
101                 }
102             }, MoreExecutors.directExecutor());
103         }
104
105         close();
106         lastReleased = System.nanoTime();
107     }
108
109     synchronized void taken(final boolean retrieveNode) {
110         final long now = System.nanoTime();
111
112         if (now - lastReleased > holdStateNanos) {
113             metadata.clear();
114         }
115
116         //try to get the topology's node
117         if (retrieveNode) {
118             try {
119                 final Optional<Node> prevNode = readOperationalData(nodeId).get();
120                 if (!prevNode.isPresent()) {
121                     putTopologyNode();
122                 } else {
123                     //cache retrieved node
124                     initialNodeState = prevNode.get();
125                 }
126             } catch (final ExecutionException | InterruptedException throwable) {
127                 LOG.error("Failed to get topology node {}", nodeId, throwable);
128             }
129         } else {
130             putTopologyNode();
131         }
132     }
133
134     synchronized Node getInitialNodeState() {
135         return initialNodeState;
136     }
137
138     synchronized TransactionChain getChain() {
139         return chain;
140     }
141
142     synchronized <T extends DataObject> FluentFuture<Optional<T>> readOperationalData(
143             final InstanceIdentifier<T> id) {
144         try (ReadTransaction t = chain.newReadOnlyTransaction()) {
145             return t.read(LogicalDatastoreType.OPERATIONAL, id);
146         }
147     }
148
149     @Override
150     public void onTransactionChainFailed(final TransactionChain pchain, final Transaction transaction,
151             final Throwable cause) {
152         // FIXME: flip internal state, so that the next attempt to update fails, triggering node reconnect
153         LOG.error("Unexpected transaction failure in node {} transaction {}", nodeId, transaction.getIdentifier(),
154             cause);
155         close();
156     }
157
158     @Override
159     public void onTransactionChainSuccessful(final TransactionChain pchain) {
160         LOG.info("Node {} shutdown successfully", nodeId);
161     }
162
163     synchronized void close() {
164         chain.close();
165     }
166
167     private synchronized void putTopologyNode() {
168         final Node node = new NodeBuilder().withKey(nodeId.getKey())
169                 .setNodeId(nodeId.getKey().getNodeId()).build();
170         final WriteTransaction t = chain.newWriteOnlyTransaction();
171         LOG.trace("Put topology Node {}, value {}", nodeId, node);
172         t.merge(LogicalDatastoreType.OPERATIONAL, nodeId, node);
173         t.commit().addCallback(new FutureCallback<CommitInfo>() {
174             @Override
175             public void onSuccess(final CommitInfo result) {
176                 LOG.trace("Topology Node stored {}, value {}", nodeId, node);
177             }
178
179             @Override
180             public void onFailure(final Throwable throwable) {
181                 LOG.error("Put topology Node failed {}, value {}", nodeId, node, throwable);
182             }
183         }, MoreExecutors.directExecutor());
184     }
185
186     synchronized void storeNode(final InstanceIdentifier<Node1> topologyAugment, final Node1 ta,
187             final PCEPSession session) {
188         LOG.trace("Peer data {} set to {}", topologyAugment, ta);
189         final WriteTransaction trans = chain.newWriteOnlyTransaction();
190         trans.put(LogicalDatastoreType.OPERATIONAL, topologyAugment, ta);
191
192         // All set, commit the modifications
193         trans.commit().addCallback(new FutureCallback<CommitInfo>() {
194             @Override
195             public void onSuccess(final CommitInfo result) {
196                 LOG.trace("Node stored {} for session {} updated successfully", topologyAugment, session);
197             }
198
199             @Override
200             public void onFailure(final Throwable throwable) {
201                 LOG.error("Failed to store node {} for session {}, terminating it", topologyAugment, session,
202                     throwable);
203                 session.close(TerminationReason.UNKNOWN);
204             }
205         }, MoreExecutors.directExecutor());
206     }
207 }