77ec63792a8a7c24d3fc038d604816f95c596cb9
[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.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import com.google.common.util.concurrent.MoreExecutors;
16 import java.util.Collection;
17 import java.util.HashMap;
18 import java.util.Map;
19 import javax.annotation.Nonnull;
20 import javax.annotation.concurrent.ThreadSafe;
21 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
22 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
23 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
24 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
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.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev171025.lsp.metadata.Metadata;
31 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
32 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
33 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
34 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
35 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
36 import org.opendaylight.yangtools.yang.binding.DataObject;
37 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
38 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 @ThreadSafe
43 final class TopologyNodeState implements AutoCloseable, TransactionChainListener {
44     private static final Logger LOG = LoggerFactory.getLogger(TopologyNodeState.class);
45     private final Map<String, Metadata> metadata = new HashMap<>();
46     private final KeyedInstanceIdentifier<Node, NodeKey> nodeId;
47     private final BindingTransactionChain chain;
48     private final long holdStateNanos;
49     private long lastReleased = 0;
50     //cache initial node state, if any node was persisted
51     private Node initialNodeState = null;
52
53     TopologyNodeState(final DataBroker broker, final InstanceIdentifier<Topology> topology, final NodeId id,
54             final long holdStateNanos) {
55         Preconditions.checkArgument(holdStateNanos >= 0);
56         this.nodeId = topology.child(Node.class, new NodeKey(id));
57         this.holdStateNanos = holdStateNanos;
58         this.chain = broker.createTransactionChain(this);
59     }
60
61     @Nonnull
62     KeyedInstanceIdentifier<Node, NodeKey> getNodeId() {
63         return this.nodeId;
64     }
65
66     synchronized Metadata getLspMetadata(final String name) {
67         return this.metadata.get(name);
68     }
69
70     synchronized void setLspMetadata(final String name, final Metadata value) {
71         if (value == null) {
72             this.metadata.remove(name);
73         } else {
74             this.metadata.put(name, value);
75         }
76     }
77
78     synchronized void cleanupExcept(final Collection<String> values) {
79         this.metadata.keySet().removeIf(s -> !values.contains(s));
80     }
81
82     synchronized void released(final boolean persist) {
83         // The session went down. Undo all the Topology changes we have done.
84         // We might want to persist topology node for later re-use.
85         if (!persist) {
86             final WriteTransaction trans = beginTransaction();
87             trans.delete(LogicalDatastoreType.OPERATIONAL, this.nodeId);
88             Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
89                 @Override
90                 public void onSuccess(final Void result) {
91                     LOG.trace("Internal state for node {} cleaned up successfully", TopologyNodeState.this.nodeId);
92                 }
93
94                 @Override
95                 public void onFailure(final Throwable throwable) {
96                     LOG.error("Failed to cleanup internal state for session {}",
97                             TopologyNodeState.this.nodeId, throwable);
98                 }
99             }, MoreExecutors.directExecutor());
100         }
101
102         this.lastReleased = System.nanoTime();
103     }
104
105     synchronized void taken(final boolean retrieveNode) {
106         final long now = System.nanoTime();
107
108         if (now - this.lastReleased > this.holdStateNanos) {
109             this.metadata.clear();
110         }
111
112         //try to get the topology's node
113         if (retrieveNode) {
114             Futures.addCallback(readOperationalData(this.nodeId), new FutureCallback<Optional<Node>>() {
115                 @Override
116                 public void onSuccess(@Nonnull final Optional<Node> result) {
117                     if (!result.isPresent()) {
118                         putTopologyNode();
119                     } else {
120                         //cache retrieved node
121                         TopologyNodeState.this.initialNodeState = result.get();
122                     }
123                 }
124
125                 @Override
126                 public void onFailure(final Throwable throwable) {
127                     LOG.error("Failed to get topology node {}", TopologyNodeState.this.nodeId, throwable);
128                 }
129             }, MoreExecutors.directExecutor());
130         } else {
131             putTopologyNode();
132         }
133     }
134
135     synchronized Node getInitialNodeState() {
136         return this.initialNodeState;
137     }
138
139     WriteTransaction beginTransaction() {
140         return this.chain.newWriteOnlyTransaction();
141     }
142
143     ReadWriteTransaction rwTransaction() {
144         return this.chain.newReadWriteTransaction();
145     }
146
147     <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(final InstanceIdentifier<T> id) {
148         try (ReadOnlyTransaction t = this.chain.newReadOnlyTransaction()) {
149             return t.read(LogicalDatastoreType.OPERATIONAL, id);
150         }
151     }
152
153     @Override
154     public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction,
155             final Throwable cause) {
156         // FIXME: flip internal state, so that the next attempt to update fails, triggering node reconnect
157         LOG.error("Unexpected transaction failure in node {} transaction {}",
158                 this.nodeId, transaction.getIdentifier(), cause);
159     }
160
161     @Override
162     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
163         LOG.info("Node {} shutdown successfully", this.nodeId);
164     }
165
166     @Override
167     public void close() {
168         this.chain.close();
169     }
170
171     private void putTopologyNode() {
172         final Node node = new NodeBuilder().setKey(this.nodeId.getKey())
173                 .setNodeId(this.nodeId.getKey().getNodeId()).build();
174         final WriteTransaction t = beginTransaction();
175         t.put(LogicalDatastoreType.OPERATIONAL, this.nodeId, node);
176         t.submit();
177     }
178
179 }