Migrate deprecated submit() to commit() under PCEP
[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 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.ListenableFuture;
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.concurrent.ExecutionException;
19 import javax.annotation.Nonnull;
20 import javax.annotation.concurrent.GuardedBy;
21 import javax.annotation.concurrent.ThreadSafe;
22 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
23 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
24 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
25 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
26 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
27 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
28 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
29 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
30 import org.opendaylight.mdsal.common.api.CommitInfo;
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.rev171025.Node1;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev171025.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 @ThreadSafe
47 final class TopologyNodeState implements AutoCloseable, TransactionChainListener {
48     private static final Logger LOG = LoggerFactory.getLogger(TopologyNodeState.class);
49     private final Map<String, Metadata> metadata = new HashMap<>();
50     private final KeyedInstanceIdentifier<Node, NodeKey> nodeId;
51     private final BindingTransactionChain 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         Preconditions.checkArgument(holdStateNanos >= 0);
61         this.nodeId = topology.child(Node.class, new NodeKey(id));
62         this.holdStateNanos = holdStateNanos;
63         this.chain = broker.createTransactionChain(this);
64     }
65
66     @Nonnull
67     KeyedInstanceIdentifier<Node, NodeKey> getNodeId() {
68         return this.nodeId;
69     }
70
71     synchronized Metadata getLspMetadata(final String name) {
72         return this.metadata.get(name);
73     }
74
75     synchronized void setLspMetadata(final String name, final Metadata value) {
76         if (value == null) {
77             this.metadata.remove(name);
78         } else {
79             this.metadata.put(name, value);
80         }
81     }
82
83     synchronized void cleanupExcept(final Collection<String> values) {
84         this.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 = this.chain.newWriteOnlyTransaction();
92             trans.delete(LogicalDatastoreType.OPERATIONAL, this.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", TopologyNodeState.this.nodeId);
97                 }
98
99                 @Override
100                 public void onFailure(final Throwable throwable) {
101                     LOG.error("Failed to cleanup internal state for session {}",
102                             TopologyNodeState.this.nodeId, throwable);
103                 }
104             }, MoreExecutors.directExecutor());
105         }
106
107         this.lastReleased = System.nanoTime();
108     }
109
110     synchronized void taken(final boolean retrieveNode) {
111         final long now = System.nanoTime();
112
113         if (now - this.lastReleased > this.holdStateNanos) {
114             this.metadata.clear();
115         }
116
117         //try to get the topology's node
118         if (retrieveNode) {
119             try {
120                 final Optional<Node> prevNode = readOperationalData(this.nodeId).get();
121                 if (!prevNode.isPresent()) {
122                     putTopologyNode();
123                 } else {
124                     //cache retrieved node
125                     TopologyNodeState.this.initialNodeState = prevNode.get();
126                 }
127             } catch (final ExecutionException | InterruptedException throwable) {
128                 LOG.error("Failed to get topology node {}", TopologyNodeState.this.nodeId, throwable);
129             }
130         } else {
131             putTopologyNode();
132         }
133     }
134
135     synchronized Node getInitialNodeState() {
136         return this.initialNodeState;
137     }
138
139     synchronized BindingTransactionChain getChain() {
140         return this.chain;
141     }
142
143     synchronized <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(
144             final InstanceIdentifier<T> id) {
145         try (ReadOnlyTransaction t = this.chain.newReadOnlyTransaction()) {
146             return t.read(LogicalDatastoreType.OPERATIONAL, id);
147         }
148     }
149
150     @Override
151     public void onTransactionChainFailed(final TransactionChain<?, ?> pchain, final AsyncTransaction<?, ?> transaction,
152             final Throwable cause) {
153         // FIXME: flip internal state, so that the next attempt to update fails, triggering node reconnect
154         LOG.error("Unexpected transaction failure in node {} transaction {}",
155                 this.nodeId, transaction.getIdentifier(), cause);
156     }
157
158     @Override
159     public void onTransactionChainSuccessful(final TransactionChain<?, ?> pchain) {
160         LOG.info("Node {} shutdown successfully", this.nodeId);
161     }
162
163     @Override
164     public synchronized void close() {
165         this.chain.close();
166     }
167
168     private synchronized void putTopologyNode() {
169         final Node node = new NodeBuilder().setKey(this.nodeId.getKey())
170                 .setNodeId(this.nodeId.getKey().getNodeId()).build();
171         final WriteTransaction t = this.chain.newWriteOnlyTransaction();
172         LOG.trace("Put topology Node {}, value {}", this.nodeId, node);
173         t.merge(LogicalDatastoreType.OPERATIONAL, this.nodeId, node);
174         t.commit().addCallback(new FutureCallback<CommitInfo>() {
175             @Override
176             public void onSuccess(final CommitInfo result) {
177                 LOG.trace("Topology Node stored {}, value {}", TopologyNodeState.this.nodeId, node);
178             }
179
180             @Override
181             public void onFailure(final Throwable throwable) {
182                 LOG.trace("Put topology Node failed {}, value {}, {}", TopologyNodeState.this.nodeId, node, throwable);
183             }
184         }, MoreExecutors.directExecutor());
185     }
186
187     synchronized void storeNode(final InstanceIdentifier<Node1> topologyAugment, final Node1 ta,
188             final PCEPSession session) {
189         LOG.trace("Peer data {} set to {}", topologyAugment, ta);
190         final WriteTransaction trans = this.chain.newWriteOnlyTransaction();
191         trans.put(LogicalDatastoreType.OPERATIONAL, topologyAugment, ta);
192
193         // All set, commit the modifications
194         trans.commit().addCallback(new FutureCallback<CommitInfo>() {
195             @Override
196             public void onSuccess(final CommitInfo result) {
197                 LOG.trace("Node stored {} for session {} updated successfully", topologyAugment, session);
198             }
199
200             @Override
201             public void onFailure(final Throwable throwable) {
202                 LOG.error("Failed to store node {} for session {}, terminating it",
203                         topologyAugment, session, throwable);
204                 session.close(TerminationReason.UNKNOWN);
205             }
206         }, MoreExecutors.directExecutor());
207     }
208 }