f6dee7ce7b32705a333fbf7f5cc23f5eb410a5ef
[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.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;
38
39 /**
40  * Abstract class for providing logical tracking of frontend local histories. This class is specialized for
41  * standalone transactions and chained transactions.
42  *
43  * @author Robert Varga
44  */
45 abstract class AbstractFrontendHistory implements Identifiable<LocalHistoryIdentifier> {
46     private static final Logger LOG = LoggerFactory.getLogger(AbstractFrontendHistory.class);
47     private static final OutOfOrderRequestException UNSEQUENCED_START = new OutOfOrderRequestException(0);
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.ticker().read();
74     }
75
76     final @Nullable TransactionSuccess<?> handleTransactionRequest(final TransactionRequest<?> request,
77             final RequestEnvelope envelope, final long now) throws RequestException {
78         final TransactionIdentifier id = request.getTarget();
79         final UnsignedLong ul = UnsignedLong.fromLongBits(id.getTransactionId());
80
81         if (request instanceof TransactionPurgeRequest) {
82             if (purgedTransactions.contains(ul)) {
83                 // Retransmitted purge request: nothing to do
84                 LOG.debug("{}: transaction {} already purged", persistenceId, id);
85                 return new TransactionPurgeResponse(id, request.getSequence());
86             }
87
88             // We perform two lookups instead of a straight remove, because once the map becomes empty we switch it
89             // to an ImmutableMap, which does not allow remove().
90             if (closedTransactions.containsKey(ul)) {
91                 tree.purgeTransaction(id, () -> {
92                     closedTransactions.remove(ul);
93                     if (closedTransactions.isEmpty()) {
94                         closedTransactions = ImmutableMap.of();
95                     }
96
97                     purgedTransactions.add(Range.singleton(ul));
98                     LOG.debug("{}: finished purging inherited transaction {}", persistenceId(), id);
99                     envelope.sendSuccess(new TransactionPurgeResponse(id, request.getSequence()), readTime() - now);
100                 });
101                 return null;
102             }
103
104             final FrontendTransaction tx = transactions.get(id);
105             if (tx == null) {
106                 // This should never happen because the purge callback removes the transaction and puts it into
107                 // purged transactions in one go. If it does, we warn about the situation and
108                 LOG.warn("{}: transaction {} not tracked in {}, but not present in active transactions", persistenceId,
109                     id, purgedTransactions);
110                 purgedTransactions.add(Range.singleton(ul));
111                 return new TransactionPurgeResponse(id, request.getSequence());
112             }
113
114             tree.purgeTransaction(id, () -> {
115                 purgedTransactions.add(Range.singleton(ul));
116                 transactions.remove(id);
117                 LOG.debug("{}: finished purging transaction {}", persistenceId(), id);
118                 envelope.sendSuccess(new TransactionPurgeResponse(id, request.getSequence()), readTime() - now);
119             });
120             return null;
121         }
122
123         if (purgedTransactions.contains(ul)) {
124             LOG.warn("{}: Request {} is contained purged transactions {}", persistenceId, request, purgedTransactions);
125             throw new DeadTransactionException(purgedTransactions);
126         }
127         final Boolean closed = closedTransactions.get(ul);
128         if (closed != null) {
129             final boolean successful = closed.booleanValue();
130             LOG.debug("{}: Request {} refers to a {} transaction", persistenceId, request, successful ? "successful"
131                     : "failed");
132             throw new ClosedTransactionException(successful);
133         }
134
135         FrontendTransaction tx = transactions.get(id);
136         if (tx == null) {
137             // The transaction does not exist and we are about to create it, check sequence number
138             if (request.getSequence() != 0) {
139                 LOG.debug("{}: no transaction state present, unexpected request {}", persistenceId(), request);
140                 throw UNSEQUENCED_START;
141             }
142
143             tx = createTransaction(request, id);
144             transactions.put(id, tx);
145         } else {
146             final Optional<TransactionSuccess<?>> maybeReplay = tx.replaySequence(request.getSequence());
147             if (maybeReplay.isPresent()) {
148                 final TransactionSuccess<?> replay = maybeReplay.get();
149                 LOG.debug("{}: envelope {} replaying response {}", persistenceId(), envelope, replay);
150                 return replay;
151             }
152         }
153
154         return tx.handleRequest(request, envelope, now);
155     }
156
157     void destroy(final long sequence, final RequestEnvelope envelope, final long now) {
158         LOG.debug("{}: closing history {}", persistenceId(), getIdentifier());
159         tree.closeTransactionChain(getIdentifier(),
160             () -> envelope.sendSuccess(new LocalHistorySuccess(getIdentifier(), sequence), readTime() - now));
161     }
162
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));
167     }
168
169     private FrontendTransaction createTransaction(final TransactionRequest<?> request, final TransactionIdentifier id)
170             throws RequestException {
171         if (request instanceof CommitLocalTransactionRequest) {
172             LOG.debug("{}: allocating new ready transaction {}", persistenceId(), id);
173             return createReadyTransaction(id, ((CommitLocalTransactionRequest) request).getModification());
174         }
175         if (request instanceof AbstractReadTransactionRequest) {
176             if (((AbstractReadTransactionRequest<?>) request).isSnapshotOnly()) {
177                 LOG.debug("{}: allocatint new open snapshot {}", persistenceId(), id);
178                 return createOpenSnapshot(id);
179             }
180         }
181
182         LOG.debug("{}: allocating new open transaction {}", persistenceId(), id);
183         return createOpenTransaction(id);
184     }
185
186     abstract FrontendTransaction createOpenSnapshot(TransactionIdentifier id) throws RequestException;
187
188     abstract FrontendTransaction createOpenTransaction(TransactionIdentifier id) throws RequestException;
189
190     abstract FrontendTransaction createReadyTransaction(TransactionIdentifier id, DataTreeModification mod)
191         throws RequestException;
192
193     abstract ShardDataTreeCohort createFailedCohort(TransactionIdentifier id, DataTreeModification mod,
194             Exception failure);
195
196     abstract ShardDataTreeCohort createReadyCohort(TransactionIdentifier id, DataTreeModification mod);
197
198     @Override
199     public String toString() {
200         return MoreObjects.toStringHelper(this).omitNullValues().add("identifier", getIdentifier())
201                 .add("persistenceId", persistenceId).add("transactions", transactions).toString();
202     }
203 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.