Bump MDSAL to 4.0.0
[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.Preconditions;
11 import com.google.common.util.concurrent.FluentFuture;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.MoreExecutors;
14 import java.util.Collection;
15 import java.util.HashMap;
16 import java.util.Map;
17 import java.util.Optional;
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.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.rev181109.Node1;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev181109.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 @ThreadSafe
46 final class TopologyNodeState implements AutoCloseable, TransactionChainListener {
47     private static final Logger LOG = LoggerFactory.getLogger(TopologyNodeState.class);
48     private final Map<String, Metadata> metadata = new HashMap<>();
49     private final KeyedInstanceIdentifier<Node, NodeKey> nodeId;
50     private final TransactionChain chain;
51     private final long holdStateNanos;
52     private long lastReleased = 0;
53     //cache initial node state, if any node was persisted
54     @GuardedBy("this")
55     private Node initialNodeState = null;
56
57     TopologyNodeState(final DataBroker broker, final InstanceIdentifier<Topology> topology, final NodeId id,
58             final long holdStateNanos) {
59         Preconditions.checkArgument(holdStateNanos >= 0);
60         this.nodeId = topology.child(Node.class, new NodeKey(id));
61         this.holdStateNanos = holdStateNanos;
62         this.chain = broker.createMergingTransactionChain(this);
63     }
64
65     @Nonnull
66     KeyedInstanceIdentifier<Node, NodeKey> getNodeId() {
67         return this.nodeId;
68     }
69
70     synchronized Metadata getLspMetadata(final String name) {
71         return this.metadata.get(name);
72     }
73
74     synchronized void setLspMetadata(final String name, final Metadata value) {
75         if (value == null) {
76             this.metadata.remove(name);
77         } else {
78             this.metadata.put(name, value);
79         }
80     }
81
82     synchronized void cleanupExcept(final Collection<String> values) {
83         this.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 = this.chain.newWriteOnlyTransaction();
91             trans.delete(LogicalDatastoreType.OPERATIONAL, this.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", TopologyNodeState.this.nodeId);
96                 }
97
98                 @Override
99                 public void onFailure(final Throwable throwable) {
100                     LOG.error("Failed to cleanup internal state for session {}",
101                             TopologyNodeState.this.nodeId, throwable);
102                 }
103             }, MoreExecutors.directExecutor());
104         }
105
106         this.lastReleased = System.nanoTime();
107     }
108
109     synchronized void taken(final boolean retrieveNode) {
110         final long now = System.nanoTime();
111
112         if (now - this.lastReleased > this.holdStateNanos) {
113             this.metadata.clear();
114         }
115
116         //try to get the topology's node
117         if (retrieveNode) {
118             try {
119                 final Optional<Node> prevNode = readOperationalData(this.nodeId).get();
120                 if (!prevNode.isPresent()) {
121                     putTopologyNode();
122                 } else {
123                     //cache retrieved node
124                     TopologyNodeState.this.initialNodeState = prevNode.get();
125                 }
126             } catch (final ExecutionException | InterruptedException throwable) {
127                 LOG.error("Failed to get topology node {}", TopologyNodeState.this.nodeId, throwable);
128             }
129         } else {
130             putTopologyNode();
131         }
132     }
133
134     synchronized Node getInitialNodeState() {
135         return this.initialNodeState;
136     }
137
138     synchronized TransactionChain getChain() {
139         return this.chain;
140     }
141
142     synchronized <T extends DataObject> FluentFuture<Optional<T>> readOperationalData(
143             final InstanceIdentifier<T> id) {
144         try (ReadTransaction t = this.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 {}",
154                 this.nodeId, transaction.getIdentifier(), cause);
155     }
156
157     @Override
158     public void onTransactionChainSuccessful(final TransactionChain pchain) {
159         LOG.info("Node {} shutdown successfully", this.nodeId);
160     }
161
162     @Override
163     public synchronized void close() {
164         this.chain.close();
165     }
166
167     private synchronized void putTopologyNode() {
168         final Node node = new NodeBuilder().withKey(this.nodeId.getKey())
169                 .setNodeId(this.nodeId.getKey().getNodeId()).build();
170         final WriteTransaction t = this.chain.newWriteOnlyTransaction();
171         LOG.trace("Put topology Node {}, value {}", this.nodeId, node);
172         t.merge(LogicalDatastoreType.OPERATIONAL, this.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 {}", TopologyNodeState.this.nodeId, node);
177             }
178
179             @Override
180             public void onFailure(final Throwable throwable) {
181                 LOG.trace("Put topology Node failed {}, value {}", TopologyNodeState.this.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 = this.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",
202                         topologyAugment, session, throwable);
203                 session.close(TerminationReason.UNKNOWN);
204             }
205         }, MoreExecutors.directExecutor());
206     }
207 }