2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.bgpcep.pcep.topology.provider;
10 import static com.google.common.base.Preconditions.checkArgument;
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;
18 import java.util.Optional;
19 import java.util.concurrent.ExecutionException;
20 import org.checkerframework.checker.lock.qual.GuardedBy;
21 import org.eclipse.jdt.annotation.NonNull;
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.rev200120.Node1;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.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;
45 // This class is thread-safe
46 final class TopologyNodeState implements TransactionChainListener {
47 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 TransactionChain chain;
52 private final long holdStateNanos;
53 private long lastReleased = 0;
54 //cache initial node state, if any node was persisted
56 private Node initialNodeState = null;
58 TopologyNodeState(final DataBroker broker, final InstanceIdentifier<Topology> topology, final NodeId id,
59 final long holdStateNanos) {
60 checkArgument(holdStateNanos >= 0);
61 nodeId = topology.child(Node.class, new NodeKey(id));
62 this.holdStateNanos = holdStateNanos;
63 chain = broker.createMergingTransactionChain(this);
66 @NonNull KeyedInstanceIdentifier<Node, NodeKey> getNodeId() {
70 synchronized Metadata getLspMetadata(final String name) {
71 return metadata.get(name);
74 synchronized void setLspMetadata(final String name, final Metadata value) {
76 metadata.remove(name);
78 metadata.put(name, value);
82 synchronized void cleanupExcept(final Collection<String> values) {
83 metadata.keySet().removeIf(s -> !values.contains(s));
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.
90 final WriteTransaction trans = chain.newWriteOnlyTransaction();
91 trans.delete(LogicalDatastoreType.OPERATIONAL, nodeId);
92 trans.commit().addCallback(new FutureCallback<CommitInfo>() {
94 public void onSuccess(final CommitInfo result) {
95 LOG.trace("Internal state for node {} cleaned up successfully", nodeId);
99 public void onFailure(final Throwable throwable) {
100 LOG.error("Failed to cleanup internal state for session {}", nodeId, throwable);
102 }, MoreExecutors.directExecutor());
106 lastReleased = System.nanoTime();
109 synchronized void taken(final boolean retrieveNode) {
110 final long now = System.nanoTime();
112 if (now - lastReleased > holdStateNanos) {
116 //try to get the topology's node
119 final Optional<Node> prevNode = readOperationalData(nodeId).get();
120 if (!prevNode.isPresent()) {
123 //cache retrieved node
124 initialNodeState = prevNode.get();
126 } catch (final ExecutionException | InterruptedException throwable) {
127 LOG.error("Failed to get topology node {}", nodeId, throwable);
134 synchronized Node getInitialNodeState() {
135 return initialNodeState;
138 synchronized TransactionChain getChain() {
142 synchronized <T extends DataObject> FluentFuture<Optional<T>> readOperationalData(
143 final InstanceIdentifier<T> id) {
144 try (ReadTransaction t = chain.newReadOnlyTransaction()) {
145 return t.read(LogicalDatastoreType.OPERATIONAL, id);
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 {}", nodeId, transaction.getIdentifier(),
159 public void onTransactionChainSuccessful(final TransactionChain pchain) {
160 LOG.info("Node {} shutdown successfully", nodeId);
163 synchronized void close() {
167 private synchronized void putTopologyNode() {
168 final Node node = new NodeBuilder().withKey(nodeId.getKey())
169 .setNodeId(nodeId.getKey().getNodeId()).build();
170 final WriteTransaction t = chain.newWriteOnlyTransaction();
171 LOG.trace("Put topology Node {}, value {}", nodeId, node);
172 t.merge(LogicalDatastoreType.OPERATIONAL, nodeId, node);
173 t.commit().addCallback(new FutureCallback<CommitInfo>() {
175 public void onSuccess(final CommitInfo result) {
176 LOG.trace("Topology Node stored {}, value {}", nodeId, node);
180 public void onFailure(final Throwable throwable) {
181 LOG.error("Put topology Node failed {}, value {}", nodeId, node, throwable);
183 }, MoreExecutors.directExecutor());
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 = chain.newWriteOnlyTransaction();
190 trans.put(LogicalDatastoreType.OPERATIONAL, topologyAugment, ta);
192 // All set, commit the modifications
193 trans.commit().addCallback(new FutureCallback<CommitInfo>() {
195 public void onSuccess(final CommitInfo result) {
196 LOG.trace("Node stored {} for session {} updated successfully", topologyAugment, session);
200 public void onFailure(final Throwable throwable) {
201 LOG.error("Failed to store node {} for session {}, terminating it", topologyAugment, session,
203 session.close(TerminationReason.UNKNOWN);
205 }, MoreExecutors.directExecutor());