2 * Copyright (c) 2016 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.controller.cluster.datastore;
10 import com.google.common.base.MoreObjects;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.Range;
14 import com.google.common.collect.RangeSet;
15 import com.google.common.primitives.UnsignedLong;
16 import java.util.HashMap;
18 import java.util.Optional;
19 import java.util.SortedSet;
20 import javax.annotation.Nullable;
21 import org.opendaylight.controller.cluster.access.commands.AbstractReadTransactionRequest;
22 import org.opendaylight.controller.cluster.access.commands.ClosedTransactionException;
23 import org.opendaylight.controller.cluster.access.commands.CommitLocalTransactionRequest;
24 import org.opendaylight.controller.cluster.access.commands.DeadTransactionException;
25 import org.opendaylight.controller.cluster.access.commands.IncrementTransactionSequenceRequest;
26 import org.opendaylight.controller.cluster.access.commands.LocalHistorySuccess;
27 import org.opendaylight.controller.cluster.access.commands.OutOfOrderRequestException;
28 import org.opendaylight.controller.cluster.access.commands.TransactionPurgeRequest;
29 import org.opendaylight.controller.cluster.access.commands.TransactionPurgeResponse;
30 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
31 import org.opendaylight.controller.cluster.access.commands.TransactionSuccess;
32 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
33 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
34 import org.opendaylight.controller.cluster.access.concepts.RequestException;
35 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
36 import org.opendaylight.yangtools.concepts.Identifiable;
37 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
42 * Abstract class for providing logical tracking of frontend local histories. This class is specialized for
43 * standalone transactions and chained transactions.
45 * @author Robert Varga
47 abstract class AbstractFrontendHistory implements Identifiable<LocalHistoryIdentifier> {
48 private static final Logger LOG = LoggerFactory.getLogger(AbstractFrontendHistory.class);
50 private final Map<TransactionIdentifier, FrontendTransaction> transactions = new HashMap<>();
51 private final RangeSet<UnsignedLong> purgedTransactions;
52 private final String persistenceId;
53 private final ShardDataTree tree;
56 * Transactions closed by the previous leader. Boolean indicates whether the transaction was committed (true) or
57 * aborted (false). We only ever shrink these.
59 private Map<UnsignedLong, Boolean> closedTransactions;
61 AbstractFrontendHistory(final String persistenceId, final ShardDataTree tree,
62 final Map<UnsignedLong, Boolean> closedTransactions, final RangeSet<UnsignedLong> purgedTransactions) {
63 this.persistenceId = Preconditions.checkNotNull(persistenceId);
64 this.tree = Preconditions.checkNotNull(tree);
65 this.closedTransactions = Preconditions.checkNotNull(closedTransactions);
66 this.purgedTransactions = Preconditions.checkNotNull(purgedTransactions);
69 final String persistenceId() {
73 final long readTime() {
74 return tree.readTime();
78 final TransactionSuccess<?> handleTransactionRequest(final TransactionRequest<?> request,
79 final RequestEnvelope envelope, final long now) throws RequestException {
80 if (request instanceof TransactionPurgeRequest) {
81 return handleTransactionPurgeRequest(request, envelope, now);
84 final TransactionIdentifier id = request.getTarget();
85 final UnsignedLong ul = UnsignedLong.fromLongBits(id.getTransactionId());
86 if (purgedTransactions.contains(ul)) {
87 LOG.warn("{}: Request {} is contained purged transactions {}", persistenceId, request, purgedTransactions);
88 throw new DeadTransactionException(purgedTransactions);
90 final Boolean closed = closedTransactions.get(ul);
92 final boolean successful = closed.booleanValue();
93 LOG.debug("{}: Request {} refers to a {} transaction", persistenceId, request, successful ? "successful"
95 throw new ClosedTransactionException(successful);
98 FrontendTransaction tx = transactions.get(id);
100 // The transaction does not exist and we are about to create it, check sequence number
101 if (request.getSequence() != 0) {
102 LOG.warn("{}: no transaction state present, unexpected request {}", persistenceId(), request);
103 throw new OutOfOrderRequestException(0);
106 tx = createTransaction(request, id);
107 transactions.put(id, tx);
108 } else if (!(request instanceof IncrementTransactionSequenceRequest)) {
109 final Optional<TransactionSuccess<?>> maybeReplay = tx.replaySequence(request.getSequence());
110 if (maybeReplay.isPresent()) {
111 final TransactionSuccess<?> replay = maybeReplay.get();
112 LOG.debug("{}: envelope {} replaying response {}", persistenceId(), envelope, replay);
117 return tx.handleRequest(request, envelope, now);
120 private TransactionSuccess<?> handleTransactionPurgeRequest(final TransactionRequest<?> request,
121 final RequestEnvelope envelope, final long now) {
122 final TransactionIdentifier id = request.getTarget();
123 final UnsignedLong ul = UnsignedLong.fromLongBits(id.getTransactionId());
124 if (purgedTransactions.contains(ul)) {
125 // Retransmitted purge request: nothing to do
126 LOG.debug("{}: transaction {} already purged", persistenceId, id);
127 return new TransactionPurgeResponse(id, request.getSequence());
130 // We perform two lookups instead of a straight remove, because once the map becomes empty we switch it
131 // to an ImmutableMap, which does not allow remove().
132 if (closedTransactions.containsKey(ul)) {
133 tree.purgeTransaction(id, () -> {
134 closedTransactions.remove(ul);
135 if (closedTransactions.isEmpty()) {
136 closedTransactions = ImmutableMap.of();
139 purgedTransactions.add(Range.closedOpen(ul, UnsignedLong.ONE.plus(ul)));
140 LOG.debug("{}: finished purging inherited transaction {}", persistenceId(), id);
141 envelope.sendSuccess(new TransactionPurgeResponse(id, request.getSequence()), readTime() - now);
146 final FrontendTransaction tx = transactions.get(id);
148 // This should never happen because the purge callback removes the transaction and puts it into
149 // purged transactions in one go. If it does, we warn about the situation and
150 LOG.warn("{}: transaction {} not tracked in {}, but not present in active transactions", persistenceId,
151 id, purgedTransactions);
152 purgedTransactions.add(Range.closedOpen(ul, UnsignedLong.ONE.plus(ul)));
153 return new TransactionPurgeResponse(id, request.getSequence());
156 tree.purgeTransaction(id, () -> {
157 purgedTransactions.add(Range.closedOpen(ul, UnsignedLong.ONE.plus(ul)));
158 transactions.remove(id);
159 LOG.debug("{}: finished purging transaction {}", persistenceId(), id);
160 envelope.sendSuccess(new TransactionPurgeResponse(id, request.getSequence()), readTime() - now);
166 final void destroy(final long sequence, final RequestEnvelope envelope, final long now) {
167 LOG.debug("{}: closing history {}", persistenceId(), getIdentifier());
168 tree.closeTransactionChain(getIdentifier(),
169 () -> envelope.sendSuccess(new LocalHistorySuccess(getIdentifier(), sequence), readTime() - now));
172 final void purge(final long sequence, final RequestEnvelope envelope, final long now) {
173 LOG.debug("{}: purging history {}", persistenceId(), getIdentifier());
174 tree.purgeTransactionChain(getIdentifier(),
175 () -> envelope.sendSuccess(new LocalHistorySuccess(getIdentifier(), sequence), readTime() - now));
178 final void retire() {
179 transactions.values().forEach(FrontendTransaction::retire);
180 tree.removeTransactionChain(getIdentifier());
183 private FrontendTransaction createTransaction(final TransactionRequest<?> request, final TransactionIdentifier id) {
184 if (request instanceof CommitLocalTransactionRequest) {
185 LOG.debug("{}: allocating new ready transaction {}", persistenceId(), id);
186 tree.getStats().incrementReadWriteTransactionCount();
187 return createReadyTransaction(id, ((CommitLocalTransactionRequest) request).getModification());
189 if (request instanceof AbstractReadTransactionRequest
190 && ((AbstractReadTransactionRequest<?>) request).isSnapshotOnly()) {
191 LOG.debug("{}: allocating new open snapshot {}", persistenceId(), id);
192 tree.getStats().incrementReadOnlyTransactionCount();
193 return createOpenSnapshot(id);
196 LOG.debug("{}: allocating new open transaction {}", persistenceId(), id);
197 tree.getStats().incrementReadWriteTransactionCount();
198 return createOpenTransaction(id);
201 abstract FrontendTransaction createOpenSnapshot(TransactionIdentifier id);
203 abstract FrontendTransaction createOpenTransaction(TransactionIdentifier id);
205 abstract FrontendTransaction createReadyTransaction(TransactionIdentifier id, DataTreeModification mod)
208 abstract ShardDataTreeCohort createFailedCohort(TransactionIdentifier id, DataTreeModification mod,
211 abstract ShardDataTreeCohort createReadyCohort(TransactionIdentifier id, DataTreeModification mod,
212 Optional<SortedSet<String>> participatingShardNames);
215 public String toString() {
216 return MoreObjects.toStringHelper(this).omitNullValues().add("identifier", getIdentifier())
217 .add("persistenceId", persistenceId).add("transactions", transactions).toString();