BGPCEP-580: Implement PCEP stats DS rendering
[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 t) {
96                     LOG.error("Failed to cleanup internal state for session {}", TopologyNodeState.this.nodeId, t);
97                 }
98             }, MoreExecutors.directExecutor());
99         }
100
101         this.lastReleased = System.nanoTime();
102     }
103
104     synchronized void taken(final boolean retrieveNode) {
105         final long now = System.nanoTime();
106
107         if (now - this.lastReleased > this.holdStateNanos) {
108             this.metadata.clear();
109         }
110
111         //try to get the topology's node
112         if (retrieveNode) {
113             Futures.addCallback(readOperationalData(this.nodeId), new FutureCallback<Optional<Node>>() {
114                 @Override
115                 public void onSuccess(final Optional<Node> result) {
116                     if (!result.isPresent()) {
117                         putTopologyNode();
118                     } else {
119                         //cache retrieved node
120                         TopologyNodeState.this.initialNodeState = result.get();
121                     }
122                 }
123
124                 @Override
125                 public void onFailure(final Throwable t) {
126                     LOG.error("Failed to get topology node {}", TopologyNodeState.this.nodeId, t);
127                 }
128             }, MoreExecutors.directExecutor());
129         } else {
130             putTopologyNode();
131         }
132     }
133
134     synchronized Node getInitialNodeState() {
135         return this.initialNodeState;
136     }
137
138     WriteTransaction beginTransaction() {
139         return this.chain.newWriteOnlyTransaction();
140     }
141
142     ReadWriteTransaction rwTransaction() {
143         return this.chain.newReadWriteTransaction();
144     }
145
146     <T extends DataObject> ListenableFuture<Optional<T>> readOperationalData(final InstanceIdentifier<T> id) {
147         try (final ReadOnlyTransaction t = this.chain.newReadOnlyTransaction()) {
148             return t.read(LogicalDatastoreType.OPERATIONAL, id);
149         }
150     }
151
152     @Override
153     public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, 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 {}", this.nodeId, transaction.getIdentifier(), cause);
156     }
157
158     @Override
159     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
160         LOG.info("Node {} shutdown successfully", this.nodeId);
161     }
162
163     @Override
164     public void close() {
165         this.chain.close();
166     }
167
168     private void putTopologyNode() {
169         final Node node = new NodeBuilder().setKey(this.nodeId.getKey()).setNodeId(this.nodeId.getKey().getNodeId()).build();
170         final WriteTransaction t = beginTransaction();
171         t.put(LogicalDatastoreType.OPERATIONAL, this.nodeId, node);
172         t.submit();
173     }
174
175 }