Remove unused exceptions
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / LeaderFrontendState.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 java.util.HashMap;
13 import java.util.Iterator;
14 import java.util.Map;
15 import javax.annotation.Nullable;
16 import javax.annotation.concurrent.NotThreadSafe;
17 import org.opendaylight.controller.cluster.access.commands.CreateLocalHistoryRequest;
18 import org.opendaylight.controller.cluster.access.commands.DeadHistoryException;
19 import org.opendaylight.controller.cluster.access.commands.DestroyLocalHistoryRequest;
20 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
21 import org.opendaylight.controller.cluster.access.commands.LocalHistorySuccess;
22 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
23 import org.opendaylight.controller.cluster.access.commands.PurgeLocalHistoryRequest;
24 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
25 import org.opendaylight.controller.cluster.access.commands.TransactionSuccess;
26 import org.opendaylight.controller.cluster.access.commands.UnknownHistoryException;
27 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
28 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
29 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
30 import org.opendaylight.controller.cluster.access.concepts.RequestException;
31 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
32 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort.State;
33 import org.opendaylight.controller.cluster.datastore.utils.UnsignedLongRangeSet;
34 import org.opendaylight.yangtools.concepts.Identifiable;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  * Frontend state as observed by the shard leader. This class is responsible for tracking generations and sequencing
40  * in the frontend/backend conversation.
41  *
42  * @author Robert Varga
43  */
44 @NotThreadSafe
45 final class LeaderFrontendState implements Identifiable<ClientIdentifier> {
46     private static final Logger LOG = LoggerFactory.getLogger(LeaderFrontendState.class);
47
48     // Histories which have not been purged
49     private final Map<LocalHistoryIdentifier, LocalFrontendHistory> localHistories;
50
51     // RangeSet performs automatic merging, hence we keep minimal state tracking information
52     private final UnsignedLongRangeSet purgedHistories;
53
54     // Used for all standalone transactions
55     private final AbstractFrontendHistory standaloneHistory;
56     private final ShardDataTree tree;
57     private final ClientIdentifier clientId;
58     private final String persistenceId;
59
60     private long lastConnectTicks;
61     private long lastSeenTicks;
62     private long expectedTxSequence;
63     private Long lastSeenHistory = null;
64
65     // TODO: explicit failover notification
66     //       Record the ActorRef for the originating actor and when we switch to being a leader send a notification
67     //       to the frontend client -- that way it can immediately start sending requests
68
69     // TODO: add statistics:
70     // - number of requests processed
71     // - number of histories processed
72     // - per-RequestException throw counters
73
74     LeaderFrontendState(final String persistenceId, final ClientIdentifier clientId, final ShardDataTree tree) {
75         this(persistenceId, clientId, tree, UnsignedLongRangeSet.create(),
76             StandaloneFrontendHistory.create(persistenceId, clientId, tree), new HashMap<>());
77     }
78
79     LeaderFrontendState(final String persistenceId, final ClientIdentifier clientId, final ShardDataTree tree,
80         final UnsignedLongRangeSet purgedHistories, final AbstractFrontendHistory standaloneHistory,
81         final Map<LocalHistoryIdentifier, LocalFrontendHistory> localHistories) {
82         this.persistenceId = Preconditions.checkNotNull(persistenceId);
83         this.clientId = Preconditions.checkNotNull(clientId);
84         this.tree = Preconditions.checkNotNull(tree);
85         this.purgedHistories = Preconditions.checkNotNull(purgedHistories);
86         this.standaloneHistory = Preconditions.checkNotNull(standaloneHistory);
87         this.localHistories = Preconditions.checkNotNull(localHistories);
88         this.lastSeenTicks = tree.readTime();
89     }
90
91     @Override
92     public ClientIdentifier getIdentifier() {
93         return clientId;
94     }
95
96     private void checkRequestSequence(final RequestEnvelope envelope) throws OutOfSequenceEnvelopeException {
97         if (expectedTxSequence != envelope.getTxSequence()) {
98             throw new OutOfSequenceEnvelopeException(expectedTxSequence);
99         }
100     }
101
102     private void expectNextRequest() {
103         expectedTxSequence++;
104     }
105
106     @Nullable LocalHistorySuccess handleLocalHistoryRequest(final LocalHistoryRequest<?> request,
107             final RequestEnvelope envelope, final long now) throws RequestException {
108         checkRequestSequence(envelope);
109
110         try {
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);
117             } else {
118                 LOG.warn("{}: rejecting unsupported request {}", persistenceId, request);
119                 throw new UnsupportedRequestException(request);
120             }
121         } finally {
122             expectNextRequest();
123         }
124     }
125
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());
134         }
135
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(historyId.getHistoryId())) {
139             LOG.debug("{}: rejecting purged request {}", persistenceId, request);
140             throw new DeadHistoryException(purgedHistories.toImmutable());
141         }
142
143         // Update last history we have seen
144         if (lastSeenHistory == null || Long.compareUnsigned(lastSeenHistory, historyId.getHistoryId()) < 0) {
145             lastSeenHistory = historyId.getHistoryId();
146         }
147
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);
152         });
153
154         localHistories.put(historyId, LocalFrontendHistory.create(persistenceId, tree, chain));
155         LOG.debug("{}: created history {}", persistenceId, historyId);
156         return null;
157     }
158
159     private LocalHistorySuccess handleDestroyHistory(final DestroyLocalHistoryRequest request,
160             final RequestEnvelope envelope, final long now) {
161         final LocalHistoryIdentifier id = request.getTarget();
162         final LocalFrontendHistory existing = localHistories.get(id);
163         if (existing == null) {
164             // History does not exist: report success
165             LOG.debug("{}: history {} does not exist, nothing to destroy", persistenceId, id);
166             return new LocalHistorySuccess(id, request.getSequence());
167         }
168
169         existing.destroy(request.getSequence(), envelope, now);
170         return null;
171     }
172
173     private LocalHistorySuccess handlePurgeHistory(final PurgeLocalHistoryRequest request,
174             final RequestEnvelope envelope, final long now) {
175         final LocalHistoryIdentifier id = request.getTarget();
176         final LocalFrontendHistory existing = localHistories.remove(id);
177         if (existing == null) {
178             LOG.debug("{}: history {} has already been purged", persistenceId, id);
179             return new LocalHistorySuccess(id, request.getSequence());
180         }
181
182         LOG.debug("{}: purging history {}", persistenceId, id);
183         purgedHistories.add(id.getHistoryId());
184         existing.purge(request.getSequence(), envelope, now);
185         return null;
186     }
187
188     @Nullable TransactionSuccess<?> handleTransactionRequest(final TransactionRequest<?> request,
189             final RequestEnvelope envelope, final long now) throws RequestException {
190         checkRequestSequence(envelope);
191
192         try {
193             final LocalHistoryIdentifier lhId = request.getTarget().getHistoryId();
194             final AbstractFrontendHistory history;
195
196             if (lhId.getHistoryId() != 0) {
197                 history = localHistories.get(lhId);
198                 if (history == null) {
199                     if (purgedHistories.contains(lhId.getHistoryId())) {
200                         LOG.warn("{}: rejecting request {} to purged history", persistenceId, request);
201                         throw new DeadHistoryException(purgedHistories.toImmutable());
202                     }
203
204                     LOG.warn("{}: rejecting unknown history request {}", persistenceId, request);
205                     throw new UnknownHistoryException(lastSeenHistory);
206                 }
207             } else {
208                 history = standaloneHistory;
209             }
210
211             return history.handleTransactionRequest(request, envelope, now);
212         } finally {
213             expectNextRequest();
214         }
215     }
216
217     void reconnect() {
218         expectedTxSequence = 0;
219         lastConnectTicks = tree.readTime();
220     }
221
222     void retire() {
223         // Hunt down any transactions associated with this frontend
224         final Iterator<SimpleShardDataTreeCohort> it = tree.cohortIterator();
225         while (it.hasNext()) {
226             final SimpleShardDataTreeCohort cohort = it.next();
227             if (clientId.equals(cohort.getIdentifier().getHistoryId().getClientId())) {
228                 if (cohort.getState() != State.COMMIT_PENDING) {
229                     LOG.debug("{}: Retiring transaction {}", persistenceId, cohort.getIdentifier());
230                     it.remove();
231                 } else {
232                     LOG.debug("{}: Transaction {} already committing, not retiring it", persistenceId,
233                         cohort.getIdentifier());
234                 }
235             }
236         }
237
238         // Clear out all transaction chains
239         localHistories.values().forEach(AbstractFrontendHistory::retire);
240         localHistories.clear();
241         standaloneHistory.retire();
242     }
243
244     long getLastConnectTicks() {
245         return lastConnectTicks;
246     }
247
248     long getLastSeenTicks() {
249         return lastSeenTicks;
250     }
251
252     void touch() {
253         this.lastSeenTicks = tree.readTime();
254     }
255
256     @Override
257     public String toString() {
258         return MoreObjects.toStringHelper(LeaderFrontendState.class)
259                 .add("clientId", clientId)
260                 .add("nanosAgo", tree.readTime() - lastSeenTicks)
261                 .add("purgedHistories", purgedHistories)
262                 .toString();
263     }
264 }