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.Range;
13 import com.google.common.collect.RangeSet;
14 import com.google.common.collect.TreeRangeSet;
15 import com.google.common.primitives.UnsignedLong;
16 import java.util.HashMap;
17 import java.util.Iterator;
19 import javax.annotation.Nullable;
20 import javax.annotation.concurrent.NotThreadSafe;
21 import org.opendaylight.controller.cluster.access.commands.CreateLocalHistoryRequest;
22 import org.opendaylight.controller.cluster.access.commands.DeadHistoryException;
23 import org.opendaylight.controller.cluster.access.commands.DestroyLocalHistoryRequest;
24 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
25 import org.opendaylight.controller.cluster.access.commands.LocalHistorySuccess;
26 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
27 import org.opendaylight.controller.cluster.access.commands.PurgeLocalHistoryRequest;
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.commands.UnknownHistoryException;
31 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
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.UnsupportedRequestException;
36 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
37 import org.opendaylight.yangtools.concepts.Identifiable;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
42 * Frontend state as observed by the shard leader. This class is responsible for tracking generations and sequencing
43 * in the frontend/backend conversation.
45 * @author Robert Varga
48 final class LeaderFrontendState implements Identifiable<ClientIdentifier> {
49 private static final Logger LOG = LoggerFactory.getLogger(LeaderFrontendState.class);
51 // Histories which have not been purged
52 private final Map<LocalHistoryIdentifier, LocalFrontendHistory> localHistories;
54 // RangeSet performs automatic merging, hence we keep minimal state tracking information
55 private final RangeSet<UnsignedLong> purgedHistories;
57 // Used for all standalone transactions
58 private final AbstractFrontendHistory standaloneHistory;
59 private final ShardDataTree tree;
60 private final ClientIdentifier clientId;
61 private final String persistenceId;
63 private long expectedTxSequence;
64 private Long lastSeenHistory = null;
66 // TODO: explicit failover notification
67 // Record the ActorRef for the originating actor and when we switch to being a leader send a notification
68 // to the frontend client -- that way it can immediately start sending requests
70 // TODO: add statistics:
71 // - number of requests processed
72 // - number of histories processed
73 // - per-RequestException throw counters
75 LeaderFrontendState(final String persistenceId, final ClientIdentifier clientId, final ShardDataTree tree) {
76 this(persistenceId, clientId, tree, TreeRangeSet.create(), StandaloneFrontendHistory.create(persistenceId,
77 clientId, tree), new HashMap<>());
80 LeaderFrontendState(final String persistenceId, final ClientIdentifier clientId, final ShardDataTree tree,
81 final RangeSet<UnsignedLong> purgedHistories, final AbstractFrontendHistory standaloneHistory,
82 final Map<LocalHistoryIdentifier, LocalFrontendHistory> localHistories) {
83 this.persistenceId = Preconditions.checkNotNull(persistenceId);
84 this.clientId = Preconditions.checkNotNull(clientId);
85 this.tree = Preconditions.checkNotNull(tree);
86 this.purgedHistories = Preconditions.checkNotNull(purgedHistories);
87 this.standaloneHistory = Preconditions.checkNotNull(standaloneHistory);
88 this.localHistories = Preconditions.checkNotNull(localHistories);
92 public ClientIdentifier getIdentifier() {
96 private void checkRequestSequence(final RequestEnvelope envelope) throws OutOfSequenceEnvelopeException {
97 if (expectedTxSequence != envelope.getTxSequence()) {
98 throw new OutOfSequenceEnvelopeException(expectedTxSequence);
102 private void expectNextRequest() {
103 expectedTxSequence++;
106 @Nullable LocalHistorySuccess handleLocalHistoryRequest(final LocalHistoryRequest<?> request,
107 final RequestEnvelope envelope, final long now) throws RequestException {
108 checkRequestSequence(envelope);
111 if (request instanceof CreateLocalHistoryRequest) {
112 return handleCreateHistory((CreateLocalHistoryRequest) request, envelope, now);
113 } else if (request instanceof DestroyLocalHistoryRequest) {
114 return handleDestroyHistory((DestroyLocalHistoryRequest) request, envelope, now);
115 } else if (request instanceof PurgeLocalHistoryRequest) {
116 return handlePurgeHistory((PurgeLocalHistoryRequest)request, envelope, now);
118 LOG.warn("{}: rejecting unsupported request {}", persistenceId, request);
119 throw new UnsupportedRequestException(request);
126 private LocalHistorySuccess handleCreateHistory(final CreateLocalHistoryRequest request,
127 final RequestEnvelope envelope, final long now) throws RequestException {
128 final LocalHistoryIdentifier historyId = request.getTarget();
129 final AbstractFrontendHistory existing = localHistories.get(historyId);
130 if (existing != null) {
131 // History already exists: report success
132 LOG.debug("{}: history {} already exists", persistenceId, historyId);
133 return new LocalHistorySuccess(historyId, request.getSequence());
136 // We have not found the history. Before we create it we need to check history ID sequencing so that we do not
137 // end up resurrecting a purged history.
138 if (purgedHistories.contains(UnsignedLong.fromLongBits(historyId.getHistoryId()))) {
139 LOG.debug("{}: rejecting purged request {}", persistenceId, request);
140 throw new DeadHistoryException(purgedHistories);
143 // Update last history we have seen
144 if (lastSeenHistory == null || Long.compareUnsigned(lastSeenHistory, historyId.getHistoryId()) < 0) {
145 lastSeenHistory = historyId.getHistoryId();
148 // We have to send the response only after persistence has completed
149 final ShardDataTreeTransactionChain chain = tree.ensureTransactionChain(historyId, () -> {
150 LOG.debug("{}: persisted history {}", persistenceId, historyId);
151 envelope.sendSuccess(new LocalHistorySuccess(historyId, request.getSequence()), tree.readTime() - now);
154 localHistories.put(historyId, LocalFrontendHistory.create(persistenceId, tree, chain));
155 LOG.debug("{}: created history {}", persistenceId, historyId);
159 private LocalHistorySuccess handleDestroyHistory(final DestroyLocalHistoryRequest request,
160 final RequestEnvelope envelope, final long now)
161 throws RequestException {
162 final LocalHistoryIdentifier id = request.getTarget();
163 final LocalFrontendHistory existing = localHistories.get(id);
164 if (existing == null) {
165 // History does not exist: report success
166 LOG.debug("{}: history {} does not exist, nothing to destroy", persistenceId, id);
167 return new LocalHistorySuccess(id, request.getSequence());
170 existing.destroy(request.getSequence(), envelope, now);
174 private LocalHistorySuccess handlePurgeHistory(final PurgeLocalHistoryRequest request,
175 final RequestEnvelope envelope, final long now) throws RequestException {
176 final LocalHistoryIdentifier id = request.getTarget();
177 final LocalFrontendHistory existing = localHistories.remove(id);
178 if (existing == null) {
179 LOG.debug("{}: history {} has already been purged", persistenceId, id);
180 return new LocalHistorySuccess(id, request.getSequence());
183 LOG.debug("{}: purging history {}", persistenceId, id);
184 final UnsignedLong ul = UnsignedLong.fromLongBits(id.getHistoryId());
185 purgedHistories.add(Range.closedOpen(ul, UnsignedLong.ONE.plus(ul)));
186 existing.purge(request.getSequence(), envelope, now);
190 @Nullable TransactionSuccess<?> handleTransactionRequest(final TransactionRequest<?> request,
191 final RequestEnvelope envelope, final long now) throws RequestException {
192 checkRequestSequence(envelope);
195 final LocalHistoryIdentifier lhId = request.getTarget().getHistoryId();
196 final AbstractFrontendHistory history;
198 if (lhId.getHistoryId() != 0) {
199 history = localHistories.get(lhId);
200 if (history == null) {
201 if (purgedHistories.contains(UnsignedLong.fromLongBits(lhId.getHistoryId()))) {
202 LOG.warn("{}: rejecting request {} to purged history", persistenceId, request);
203 throw new DeadHistoryException(purgedHistories);
206 LOG.warn("{}: rejecting unknown history request {}", persistenceId, request);
207 throw new UnknownHistoryException(lastSeenHistory);
210 history = standaloneHistory;
213 return history.handleTransactionRequest(request, envelope, now);
220 expectedTxSequence = 0;
224 // Hunt down any transactions associated with this frontend
225 final Iterator<SimpleShardDataTreeCohort> it = tree.cohortIterator();
226 while (it.hasNext()) {
227 final SimpleShardDataTreeCohort cohort = it.next();
228 if (clientId.equals(cohort.getIdentifier().getHistoryId().getClientId())) {
229 if (cohort.getState() != State.COMMIT_PENDING) {
230 LOG.debug("{}: Retiring transaction {}", persistenceId, cohort.getIdentifier());
233 LOG.debug("{}: Transaction {} already committing, not retiring it", persistenceId,
234 cohort.getIdentifier());
239 // Clear out all transaction chains
240 localHistories.values().forEach(AbstractFrontendHistory::retire);
241 localHistories.clear();
242 standaloneHistory.retire();
246 public String toString() {
247 return MoreObjects.toStringHelper(LeaderFrontendState.class).add("clientId", clientId)
248 .add("purgedHistories", purgedHistories).toString();