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 javax.annotation.Nullable;
20 import org.opendaylight.controller.cluster.access.commands.AbstractReadTransactionRequest;
21 import org.opendaylight.controller.cluster.access.commands.ClosedTransactionException;
22 import org.opendaylight.controller.cluster.access.commands.CommitLocalTransactionRequest;
23 import org.opendaylight.controller.cluster.access.commands.DeadTransactionException;
24 import org.opendaylight.controller.cluster.access.commands.LocalHistorySuccess;
25 import org.opendaylight.controller.cluster.access.commands.OutOfOrderRequestException;
26 import org.opendaylight.controller.cluster.access.commands.TransactionPurgeRequest;
27 import org.opendaylight.controller.cluster.access.commands.TransactionPurgeResponse;
28 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
29 import org.opendaylight.controller.cluster.access.commands.TransactionSuccess;
30 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
31 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
32 import org.opendaylight.controller.cluster.access.concepts.RequestException;
33 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
34 import org.opendaylight.yangtools.concepts.Identifiable;
35 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
40 * Abstract class for providing logical tracking of frontend local histories. This class is specialized for
41 * standalone transactions and chained transactions.
43 * @author Robert Varga
45 abstract class AbstractFrontendHistory implements Identifiable<LocalHistoryIdentifier> {
46 private static final Logger LOG = LoggerFactory.getLogger(AbstractFrontendHistory.class);
48 private final Map<TransactionIdentifier, FrontendTransaction> transactions = new HashMap<>();
49 private final RangeSet<UnsignedLong> purgedTransactions;
50 private final String persistenceId;
51 private final ShardDataTree tree;
54 * Transactions closed by the previous leader. Boolean indicates whether the transaction was committed (true) or
55 * aborted (false). We only ever shrink these.
57 private Map<UnsignedLong, Boolean> closedTransactions;
59 AbstractFrontendHistory(final String persistenceId, final ShardDataTree tree,
60 final Map<UnsignedLong, Boolean> closedTransactions, final RangeSet<UnsignedLong> purgedTransactions) {
61 this.persistenceId = Preconditions.checkNotNull(persistenceId);
62 this.tree = Preconditions.checkNotNull(tree);
63 this.closedTransactions = Preconditions.checkNotNull(closedTransactions);
64 this.purgedTransactions = Preconditions.checkNotNull(purgedTransactions);
67 final String persistenceId() {
71 final long readTime() {
72 return tree.ticker().read();
75 final @Nullable TransactionSuccess<?> handleTransactionRequest(final TransactionRequest<?> request,
76 final RequestEnvelope envelope, final long now) throws RequestException {
77 final TransactionIdentifier id = request.getTarget();
78 final UnsignedLong ul = UnsignedLong.fromLongBits(id.getTransactionId());
80 if (request instanceof TransactionPurgeRequest) {
81 if (purgedTransactions.contains(ul)) {
82 // Retransmitted purge request: nothing to do
83 LOG.debug("{}: transaction {} already purged", persistenceId, id);
84 return new TransactionPurgeResponse(id, request.getSequence());
87 // We perform two lookups instead of a straight remove, because once the map becomes empty we switch it
88 // to an ImmutableMap, which does not allow remove().
89 if (closedTransactions.containsKey(ul)) {
90 tree.purgeTransaction(id, () -> {
91 closedTransactions.remove(ul);
92 if (closedTransactions.isEmpty()) {
93 closedTransactions = ImmutableMap.of();
96 purgedTransactions.add(Range.singleton(ul));
97 LOG.debug("{}: finished purging inherited transaction {}", persistenceId(), id);
98 envelope.sendSuccess(new TransactionPurgeResponse(id, request.getSequence()), readTime() - now);
103 final FrontendTransaction tx = transactions.get(id);
105 // This should never happen because the purge callback removes the transaction and puts it into
106 // purged transactions in one go. If it does, we warn about the situation and
107 LOG.warn("{}: transaction {} not tracked in {}, but not present in active transactions", persistenceId,
108 id, purgedTransactions);
109 purgedTransactions.add(Range.singleton(ul));
110 return new TransactionPurgeResponse(id, request.getSequence());
113 tree.purgeTransaction(id, () -> {
114 purgedTransactions.add(Range.singleton(ul));
115 transactions.remove(id);
116 LOG.debug("{}: finished purging transaction {}", persistenceId(), id);
117 envelope.sendSuccess(new TransactionPurgeResponse(id, request.getSequence()), readTime() - now);
122 if (purgedTransactions.contains(ul)) {
123 LOG.warn("{}: Request {} is contained purged transactions {}", persistenceId, request, purgedTransactions);
124 throw new DeadTransactionException(purgedTransactions);
126 final Boolean closed = closedTransactions.get(ul);
127 if (closed != null) {
128 final boolean successful = closed.booleanValue();
129 LOG.debug("{}: Request {} refers to a {} transaction", persistenceId, request, successful ? "successful"
131 throw new ClosedTransactionException(successful);
134 FrontendTransaction tx = transactions.get(id);
136 // The transaction does not exist and we are about to create it, check sequence number
137 if (request.getSequence() != 0) {
138 LOG.debug("{}: no transaction state present, unexpected request {}", persistenceId(), request);
139 throw new OutOfOrderRequestException(0);
142 tx = createTransaction(request, id);
143 transactions.put(id, tx);
145 final Optional<TransactionSuccess<?>> maybeReplay = tx.replaySequence(request.getSequence());
146 if (maybeReplay.isPresent()) {
147 final TransactionSuccess<?> replay = maybeReplay.get();
148 LOG.debug("{}: envelope {} replaying response {}", persistenceId(), envelope, replay);
153 return tx.handleRequest(request, envelope, now);
156 void destroy(final long sequence, final RequestEnvelope envelope, final long now) {
157 LOG.debug("{}: closing history {}", persistenceId(), getIdentifier());
158 tree.closeTransactionChain(getIdentifier(), () -> {
159 envelope.sendSuccess(new LocalHistorySuccess(getIdentifier(), sequence), readTime() - now);
163 void purge(final long sequence, final RequestEnvelope envelope, final long now) {
164 LOG.debug("{}: purging history {}", persistenceId(), getIdentifier());
165 tree.purgeTransactionChain(getIdentifier(), () -> {
166 envelope.sendSuccess(new LocalHistorySuccess(getIdentifier(), sequence), readTime() - now);
170 private FrontendTransaction createTransaction(final TransactionRequest<?> request, final TransactionIdentifier id)
171 throws RequestException {
172 if (request instanceof CommitLocalTransactionRequest) {
173 LOG.debug("{}: allocating new ready transaction {}", persistenceId(), id);
174 tree.getStats().incrementReadWriteTransactionCount();
175 return createReadyTransaction(id, ((CommitLocalTransactionRequest) request).getModification());
177 if (request instanceof AbstractReadTransactionRequest) {
178 if (((AbstractReadTransactionRequest<?>) request).isSnapshotOnly()) {
179 LOG.debug("{}: allocating new open snapshot {}", persistenceId(), id);
180 tree.getStats().incrementReadOnlyTransactionCount();
181 return createOpenSnapshot(id);
185 LOG.debug("{}: allocating new open transaction {}", persistenceId(), id);
186 tree.getStats().incrementReadWriteTransactionCount();
187 return createOpenTransaction(id);
190 abstract FrontendTransaction createOpenSnapshot(TransactionIdentifier id) throws RequestException;
192 abstract FrontendTransaction createOpenTransaction(TransactionIdentifier id) throws RequestException;
194 abstract FrontendTransaction createReadyTransaction(TransactionIdentifier id, DataTreeModification mod)
195 throws RequestException;
197 abstract ShardDataTreeCohort createFailedCohort(TransactionIdentifier id, DataTreeModification mod,
200 abstract ShardDataTreeCohort createReadyCohort(TransactionIdentifier id, DataTreeModification mod);
203 public String toString() {
204 return MoreObjects.toStringHelper(this).omitNullValues().add("identifier", getIdentifier())
205 .add("persistenceId", persistenceId).add("transactions", transactions).toString();