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