89dd59a5f59a165073dccbd899383cf874d628c6
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / AbstractFrontendHistory.java
1 /*
2  * Copyright (c) 2016 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.controller.cluster.datastore;
9
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;
17 import java.util.Map;
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.IncrementTransactionSequenceRequest;
25 import org.opendaylight.controller.cluster.access.commands.LocalHistorySuccess;
26 import org.opendaylight.controller.cluster.access.commands.OutOfOrderRequestException;
27 import org.opendaylight.controller.cluster.access.commands.TransactionPurgeRequest;
28 import org.opendaylight.controller.cluster.access.commands.TransactionPurgeResponse;
29 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
30 import org.opendaylight.controller.cluster.access.commands.TransactionSuccess;
31 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
32 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
33 import org.opendaylight.controller.cluster.access.concepts.RequestException;
34 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
35 import org.opendaylight.yangtools.concepts.Identifiable;
36 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * Abstract class for providing logical tracking of frontend local histories. This class is specialized for
42  * standalone transactions and chained transactions.
43  *
44  * @author Robert Varga
45  */
46 abstract class AbstractFrontendHistory implements Identifiable<LocalHistoryIdentifier> {
47     private static final Logger LOG = LoggerFactory.getLogger(AbstractFrontendHistory.class);
48
49     private final Map<TransactionIdentifier, FrontendTransaction> transactions = new HashMap<>();
50     private final RangeSet<UnsignedLong> purgedTransactions;
51     private final String persistenceId;
52     private final ShardDataTree tree;
53
54     /**
55      * Transactions closed by the previous leader. Boolean indicates whether the transaction was committed (true) or
56      * aborted (false). We only ever shrink these.
57      */
58     private Map<UnsignedLong, Boolean> closedTransactions;
59
60     AbstractFrontendHistory(final String persistenceId, final ShardDataTree tree,
61         final Map<UnsignedLong, Boolean> closedTransactions, final RangeSet<UnsignedLong> purgedTransactions) {
62         this.persistenceId = Preconditions.checkNotNull(persistenceId);
63         this.tree = Preconditions.checkNotNull(tree);
64         this.closedTransactions = Preconditions.checkNotNull(closedTransactions);
65         this.purgedTransactions = Preconditions.checkNotNull(purgedTransactions);
66     }
67
68     final String persistenceId() {
69         return persistenceId;
70     }
71
72     final long readTime() {
73         return tree.readTime();
74     }
75
76     @Nullable
77     final TransactionSuccess<?> handleTransactionRequest(final TransactionRequest<?> request,
78             final RequestEnvelope envelope, final long now) throws RequestException {
79         if (request instanceof TransactionPurgeRequest) {
80             return handleTransactionPurgeRequest(request, envelope, now);
81         }
82
83         final TransactionIdentifier id = request.getTarget();
84         final UnsignedLong ul = UnsignedLong.fromLongBits(id.getTransactionId());
85         if (purgedTransactions.contains(ul)) {
86             LOG.warn("{}: Request {} is contained purged transactions {}", persistenceId, request, purgedTransactions);
87             throw new DeadTransactionException(purgedTransactions);
88         }
89         final Boolean closed = closedTransactions.get(ul);
90         if (closed != null) {
91             final boolean successful = closed.booleanValue();
92             LOG.debug("{}: Request {} refers to a {} transaction", persistenceId, request, successful ? "successful"
93                     : "failed");
94             throw new ClosedTransactionException(successful);
95         }
96
97         FrontendTransaction tx = transactions.get(id);
98         if (tx == null) {
99             // The transaction does not exist and we are about to create it, check sequence number
100             if (request.getSequence() != 0) {
101                 LOG.warn("{}: no transaction state present, unexpected request {}", persistenceId(), request);
102                 throw new OutOfOrderRequestException(0);
103             }
104
105             tx = createTransaction(request, id);
106             transactions.put(id, tx);
107         } else if (!(request instanceof IncrementTransactionSequenceRequest)) {
108             final Optional<TransactionSuccess<?>> maybeReplay = tx.replaySequence(request.getSequence());
109             if (maybeReplay.isPresent()) {
110                 final TransactionSuccess<?> replay = maybeReplay.get();
111                 LOG.debug("{}: envelope {} replaying response {}", persistenceId(), envelope, replay);
112                 return replay;
113             }
114         }
115
116         return tx.handleRequest(request, envelope, now);
117     }
118
119     private TransactionSuccess<?> handleTransactionPurgeRequest(final TransactionRequest<?> request,
120             final RequestEnvelope envelope, final long now) {
121         final TransactionIdentifier id = request.getTarget();
122         final UnsignedLong ul = UnsignedLong.fromLongBits(id.getTransactionId());
123         if (purgedTransactions.contains(ul)) {
124             // Retransmitted purge request: nothing to do
125             LOG.debug("{}: transaction {} already purged", persistenceId, id);
126             return new TransactionPurgeResponse(id, request.getSequence());
127         }
128
129         // We perform two lookups instead of a straight remove, because once the map becomes empty we switch it
130         // to an ImmutableMap, which does not allow remove().
131         if (closedTransactions.containsKey(ul)) {
132             tree.purgeTransaction(id, () -> {
133                 closedTransactions.remove(ul);
134                 if (closedTransactions.isEmpty()) {
135                     closedTransactions = ImmutableMap.of();
136                 }
137
138                 purgedTransactions.add(Range.closedOpen(ul, UnsignedLong.ONE.plus(ul)));
139                 LOG.debug("{}: finished purging inherited transaction {}", persistenceId(), id);
140                 envelope.sendSuccess(new TransactionPurgeResponse(id, request.getSequence()), readTime() - now);
141             });
142             return null;
143         }
144
145         final FrontendTransaction tx = transactions.get(id);
146         if (tx == null) {
147             // This should never happen because the purge callback removes the transaction and puts it into
148             // purged transactions in one go. If it does, we warn about the situation and
149             LOG.warn("{}: transaction {} not tracked in {}, but not present in active transactions", persistenceId,
150                 id, purgedTransactions);
151             purgedTransactions.add(Range.closedOpen(ul, UnsignedLong.ONE.plus(ul)));
152             return new TransactionPurgeResponse(id, request.getSequence());
153         }
154
155         tree.purgeTransaction(id, () -> {
156             purgedTransactions.add(Range.closedOpen(ul, UnsignedLong.ONE.plus(ul)));
157             transactions.remove(id);
158             LOG.debug("{}: finished purging transaction {}", persistenceId(), id);
159             envelope.sendSuccess(new TransactionPurgeResponse(id, request.getSequence()), readTime() - now);
160         });
161
162         return null;
163     }
164
165     final void destroy(final long sequence, final RequestEnvelope envelope, final long now) {
166         LOG.debug("{}: closing history {}", persistenceId(), getIdentifier());
167         tree.closeTransactionChain(getIdentifier(),
168             () -> envelope.sendSuccess(new LocalHistorySuccess(getIdentifier(), sequence), readTime() - now));
169     }
170
171     final void purge(final long sequence, final RequestEnvelope envelope, final long now) {
172         LOG.debug("{}: purging history {}", persistenceId(), getIdentifier());
173         tree.purgeTransactionChain(getIdentifier(),
174             () -> envelope.sendSuccess(new LocalHistorySuccess(getIdentifier(), sequence), readTime() - now));
175     }
176
177     final void retire() {
178         transactions.values().forEach(FrontendTransaction::retire);
179         tree.removeTransactionChain(getIdentifier());
180     }
181
182     private FrontendTransaction createTransaction(final TransactionRequest<?> request, final TransactionIdentifier id)
183             throws RequestException {
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());
188         }
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);
194         }
195
196         LOG.debug("{}: allocating new open transaction {}", persistenceId(), id);
197         tree.getStats().incrementReadWriteTransactionCount();
198         return createOpenTransaction(id);
199     }
200
201     abstract FrontendTransaction createOpenSnapshot(TransactionIdentifier id) throws RequestException;
202
203     abstract FrontendTransaction createOpenTransaction(TransactionIdentifier id) throws RequestException;
204
205     abstract FrontendTransaction createReadyTransaction(TransactionIdentifier id, DataTreeModification mod)
206         throws RequestException;
207
208     abstract ShardDataTreeCohort createFailedCohort(TransactionIdentifier id, DataTreeModification mod,
209             Exception failure);
210
211     abstract ShardDataTreeCohort createReadyCohort(TransactionIdentifier id, DataTreeModification mod);
212
213     @Override
214     public String toString() {
215         return MoreObjects.toStringHelper(this).omitNullValues().add("identifier", getIdentifier())
216                 .add("persistenceId", persistenceId).add("transactions", transactions).toString();
217     }
218 }