BUG-8618: record LeaderFrontendState time
[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             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());
168         }
169
170         existing.destroy(request.getSequence(), envelope, now);
171         return null;
172     }
173
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());
181         }
182
183         LOG.debug("{}: purging history {}", persistenceId, id);
184         purgedHistories.add(id.getHistoryId());
185         existing.purge(request.getSequence(), envelope, now);
186         return null;
187     }
188
189     @Nullable TransactionSuccess<?> handleTransactionRequest(final TransactionRequest<?> request,
190             final RequestEnvelope envelope, final long now) throws RequestException {
191         checkRequestSequence(envelope);
192
193         try {
194             final LocalHistoryIdentifier lhId = request.getTarget().getHistoryId();
195             final AbstractFrontendHistory history;
196
197             if (lhId.getHistoryId() != 0) {
198                 history = localHistories.get(lhId);
199                 if (history == null) {
200                     if (purgedHistories.contains(lhId.getHistoryId())) {
201                         LOG.warn("{}: rejecting request {} to purged history", persistenceId, request);
202                         throw new DeadHistoryException(purgedHistories.toImmutable());
203                     }
204
205                     LOG.warn("{}: rejecting unknown history request {}", persistenceId, request);
206                     throw new UnknownHistoryException(lastSeenHistory);
207                 }
208             } else {
209                 history = standaloneHistory;
210             }
211
212             return history.handleTransactionRequest(request, envelope, now);
213         } finally {
214             expectNextRequest();
215         }
216     }
217
218     void reconnect() {
219         expectedTxSequence = 0;
220         lastConnectTicks = tree.readTime();
221     }
222
223     void retire() {
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());
231                     it.remove();
232                 } else {
233                     LOG.debug("{}: Transaction {} already committing, not retiring it", persistenceId,
234                         cohort.getIdentifier());
235                 }
236             }
237         }
238
239         // Clear out all transaction chains
240         localHistories.values().forEach(AbstractFrontendHistory::retire);
241         localHistories.clear();
242         standaloneHistory.retire();
243     }
244
245     long getLastConnectTicks() {
246         return lastConnectTicks;
247     }
248
249     long getLastSeenTicks() {
250         return lastSeenTicks;
251     }
252
253     void touch() {
254         this.lastSeenTicks = tree.readTime();
255     }
256
257     @Override
258     public String toString() {
259         return MoreObjects.toStringHelper(LeaderFrontendState.class)
260                 .add("clientId", clientId)
261                 .add("nanosAgo", tree.readTime() - lastSeenTicks)
262                 .add("purgedHistories", purgedHistories)
263                 .toString();
264     }
265 }