-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathClusterStateObserver.java
More file actions
426 lines (379 loc) · 16.7 KB
/
ClusterStateObserver.java
File metadata and controls
426 lines (379 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.cluster;
import org.apache.logging.log4j.Logger;
import org.opensearch.OpenSearchException;
import org.opensearch.cluster.service.ClusterApplierService;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.Nullable;
import org.opensearch.common.unit.TimeValue;
import org.opensearch.common.util.concurrent.ThreadContext;
import org.opensearch.threadpool.ThreadPool;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
* A utility class which simplifies interacting with the cluster state in cases where
* one tries to take action based on the current state but may want to wait for a new state
* and retry upon failure.
*
* @opensearch.internal
*/
public class ClusterStateObserver {
protected final Logger logger;
private final Predicate<ClusterState> MATCH_ALL_CHANGES_PREDICATE = state -> true;
private final ClusterApplierService clusterApplierService;
private final ThreadPool threadPool;
private final ThreadContext contextHolder;
volatile TimeValue timeOutValue;
final AtomicReference<StoredState> lastObservedState;
final TimeoutClusterStateListener clusterStateListener = new ObserverClusterStateListener();
// observingContext is not null when waiting on cluster state changes
final AtomicReference<ObservingContext> observingContext = new AtomicReference<>(null);
volatile Long startTimeMS;
volatile boolean timedOut;
public ClusterStateObserver(ClusterService clusterService, Logger logger, ThreadContext contextHolder) {
this(clusterService, new TimeValue(60000), logger, contextHolder);
}
/**
* @param timeout a global timeout for this observer. After it has expired the observer
* will fail any existing or new #waitForNextChange calls. Set to null
* to wait indefinitely
*/
public ClusterStateObserver(ClusterService clusterService, @Nullable TimeValue timeout, Logger logger, ThreadContext contextHolder) {
this(clusterService.state(), clusterService, timeout, logger, contextHolder);
}
/**
* @param timeout a global timeout for this observer. After it has expired the observer
* will fail any existing or new #waitForNextChange calls. Set to null
* to wait indefinitely
*/
public ClusterStateObserver(
ClusterState initialState,
ClusterService clusterService,
@Nullable TimeValue timeout,
Logger logger,
ThreadContext contextHolder
) {
this(initialState, clusterService.getClusterApplierService(), timeout, logger, contextHolder);
}
public ClusterStateObserver(
ClusterState initialState,
ClusterApplierService clusterApplierService,
@Nullable TimeValue timeout,
Logger logger,
ThreadContext contextHolder
) {
this.clusterApplierService = clusterApplierService;
this.threadPool = clusterApplierService.threadPool();
this.lastObservedState = new AtomicReference<>(new StoredState(initialState));
this.timeOutValue = timeout;
if (timeOutValue != null) {
this.startTimeMS = threadPool.relativeTimeInMillis();
}
this.logger = logger;
this.contextHolder = contextHolder;
}
public ClusterStateObserver(
String clusterManagerNodeId,
long version,
ClusterApplierService clusterApplierService,
@Nullable TimeValue timeout,
Logger logger,
ThreadContext contextHolder
) {
this.clusterApplierService = clusterApplierService;
this.threadPool = clusterApplierService.threadPool();
this.lastObservedState = new AtomicReference<>(new StoredState(clusterManagerNodeId, version));
this.timeOutValue = timeout;
if (timeOutValue != null) {
this.startTimeMS = threadPool.relativeTimeInMillis();
}
this.logger = logger;
this.contextHolder = contextHolder;
}
/** sets the last observed state to the currently applied cluster state and returns it */
public ClusterState setAndGetObservedState() {
if (observingContext.get() != null) {
throw new OpenSearchException("cannot set current cluster state while waiting for a cluster state change");
}
ClusterState clusterState = clusterApplierService.state();
lastObservedState.set(new StoredState(clusterState));
return clusterState;
}
/** indicates whether this observer has timed out */
public boolean isTimedOut() {
return timedOut;
}
public void waitForNextChange(Listener listener) {
waitForNextChange(listener, MATCH_ALL_CHANGES_PREDICATE);
}
public void waitForNextChange(Listener listener, @Nullable TimeValue timeOutValue) {
waitForNextChange(listener, MATCH_ALL_CHANGES_PREDICATE, timeOutValue);
}
public void waitForNextChange(Listener listener, Predicate<ClusterState> statePredicate) {
waitForNextChange(listener, statePredicate, null);
}
/**
* Wait for the next cluster state which satisfies statePredicate
*
* @param listener callback listener
* @param statePredicate predicate to check whether cluster state changes are relevant and the callback should be called
* @param timeOutValue a timeout for waiting. If null the global observer timeout will be used.
*/
public void waitForNextChange(Listener listener, Predicate<ClusterState> statePredicate, @Nullable TimeValue timeOutValue) {
listener = new ContextPreservingListener(listener, contextHolder.newRestorableContext(false));
if (observingContext.get() != null) {
throw new OpenSearchException("already waiting for a cluster state change");
}
Long timeoutTimeLeftMS;
if (timeOutValue == null) {
timeOutValue = this.timeOutValue;
if (timeOutValue != null) {
long timeSinceStartMS = threadPool.relativeTimeInMillis() - startTimeMS;
timeoutTimeLeftMS = timeOutValue.millis() - timeSinceStartMS;
if (timeoutTimeLeftMS <= 0L) {
// things have timeout while we were busy -> notify
logger.trace(
"observer timed out. notifying listener. timeout setting [{}], time since start [{}]",
timeOutValue,
new TimeValue(timeSinceStartMS)
);
// update to latest, in case people want to retry
timedOut = true;
lastObservedState.set(new StoredState(clusterApplierService.state()));
listener.onTimeout(timeOutValue);
return;
}
} else {
timeoutTimeLeftMS = null;
}
} else {
this.startTimeMS = threadPool.relativeTimeInMillis();
this.timeOutValue = timeOutValue;
timeoutTimeLeftMS = timeOutValue.millis();
timedOut = false;
}
// sample a new state. This state maybe *older* than the supplied state if we are called from an applier,
// which wants to wait for something else to happen
ClusterState newState = clusterApplierService.state();
if (lastObservedState.get().isOlderOrDifferentClusterManager(newState) && statePredicate.test(newState)) {
// good enough, let's go.
logger.trace("observer: sampled state accepted by predicate ({})", newState);
lastObservedState.set(new StoredState(newState));
listener.onNewClusterState(newState);
} else {
logger.trace("observer: sampled state rejected by predicate ({}). adding listener to ClusterService", newState);
final ObservingContext context = new ObservingContext(listener, statePredicate);
if (!observingContext.compareAndSet(null, context)) {
throw new OpenSearchException("already waiting for a cluster state change");
}
clusterApplierService.addTimeoutListener(
timeoutTimeLeftMS == null ? null : new TimeValue(timeoutTimeLeftMS),
clusterStateListener
);
}
}
/**
* An observer of the cluster state for changes.
*
* @opensearch.internal
*/
class ObserverClusterStateListener implements TimeoutClusterStateListener {
@Override
public void clusterChanged(ClusterChangedEvent event) {
ObservingContext context = observingContext.get();
if (context == null) {
// No need to remove listener as it is the responsibility of the thread that set observingContext to null
return;
}
final ClusterState state = event.state();
if (context.statePredicate.test(state)) {
if (observingContext.compareAndSet(context, null)) {
clusterApplierService.removeTimeoutListener(this);
logger.trace("observer: accepting cluster state change ({})", state);
lastObservedState.set(new StoredState(state));
context.listener.onNewClusterState(state);
} else {
logger.trace(
"observer: predicate approved change but observing context has changed "
+ "- ignoring (new cluster state version [{}])",
state.version()
);
}
} else {
logger.trace("observer: predicate rejected change (new cluster state version [{}])", state.version());
}
}
@Override
public void postAdded() {
ObservingContext context = observingContext.get();
if (context == null) {
// No need to remove listener as it is the responsibility of the thread that set observingContext to null
return;
}
ClusterState newState = clusterApplierService.state();
if (lastObservedState.get().isOlderOrDifferentClusterManager(newState) && context.statePredicate.test(newState)) {
// double check we're still listening
if (observingContext.compareAndSet(context, null)) {
logger.trace("observer: post adding listener: accepting current cluster state ({})", newState);
clusterApplierService.removeTimeoutListener(this);
lastObservedState.set(new StoredState(newState));
context.listener.onNewClusterState(newState);
} else {
logger.trace(
"observer: postAdded - predicate approved state but observing context has changed - ignoring ({})",
newState
);
}
} else {
logger.trace("observer: postAdded - predicate rejected state ({})", newState);
}
}
@Override
public void onClose() {
ObservingContext context = observingContext.getAndSet(null);
if (context != null) {
logger.trace("observer: cluster service closed. notifying listener.");
clusterApplierService.removeTimeoutListener(this);
context.listener.onClusterServiceClose();
}
}
@Override
public void onTimeout(TimeValue timeout) {
ObservingContext context = observingContext.getAndSet(null);
if (context != null) {
clusterApplierService.removeTimeoutListener(this);
long timeSinceStartMS = threadPool.relativeTimeInMillis() - startTimeMS;
logger.trace(
"observer: timeout notification from cluster service. timeout setting [{}], time since start [{}]",
timeOutValue,
new TimeValue(timeSinceStartMS)
);
// update to latest, in case people want to retry
lastObservedState.set(new StoredState(clusterApplierService.state()));
timedOut = true;
context.listener.onTimeout(timeOutValue);
}
}
@Override
public String toString() {
return "ClusterStateObserver[" + observingContext.get() + "]";
}
}
/**
* The observer considers two cluster states to be the same if they have the same version and cluster-manager node id (i.e. null or set)
*
* @opensearch.internal
*/
private static class StoredState {
private final String clusterManagerNodeId;
private final long version;
StoredState(ClusterState clusterState) {
this(clusterState.nodes().getClusterManagerNodeId(), clusterState.version());
}
StoredState(String clusterManagerNodeId, long version) {
this.clusterManagerNodeId = clusterManagerNodeId;
this.version = version;
}
/**
* returns true if stored state is older then given state or they are from a different cluster-manager, meaning they can't be compared
* */
public boolean isOlderOrDifferentClusterManager(ClusterState clusterState) {
return version < clusterState.version()
|| Objects.equals(clusterManagerNodeId, clusterState.nodes().getClusterManagerNodeId()) == false;
}
}
/**
* Listener for the observer.
*
* @opensearch.internal
*/
public interface Listener {
/** called when a new state is observed */
void onNewClusterState(ClusterState state);
/** called when the cluster service is closed */
void onClusterServiceClose();
void onTimeout(TimeValue timeout);
}
/**
* Context for the observer.
*
* @opensearch.internal
*/
static class ObservingContext {
public final Listener listener;
public final Predicate<ClusterState> statePredicate;
ObservingContext(Listener listener, Predicate<ClusterState> statePredicate) {
this.listener = listener;
this.statePredicate = statePredicate;
}
@Override
public String toString() {
return "ObservingContext[" + listener + "]";
}
}
/**
* A context preserving listener.
*
* @opensearch.internal
*/
private static final class ContextPreservingListener implements Listener {
private final Listener delegate;
private final Supplier<ThreadContext.StoredContext> contextSupplier;
private ContextPreservingListener(Listener delegate, Supplier<ThreadContext.StoredContext> contextSupplier) {
this.contextSupplier = contextSupplier;
this.delegate = delegate;
}
@Override
public void onNewClusterState(ClusterState state) {
try (ThreadContext.StoredContext context = contextSupplier.get()) {
delegate.onNewClusterState(state);
}
}
@Override
public void onClusterServiceClose() {
try (ThreadContext.StoredContext context = contextSupplier.get()) {
delegate.onClusterServiceClose();
}
}
@Override
public void onTimeout(TimeValue timeout) {
try (ThreadContext.StoredContext context = contextSupplier.get()) {
delegate.onTimeout(timeout);
}
}
@Override
public String toString() {
return "ContextPreservingListener[" + delegate + "]";
}
}
}