-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathIndexingMemoryControllerTests.java
499 lines (428 loc) · 19.2 KB
/
IndexingMemoryControllerTests.java
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
/*
* 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.indices;
import org.apache.lucene.search.ReferenceManager;
import org.opensearch.Version;
import org.opensearch.cluster.node.DiscoveryNode;
import org.opensearch.common.SetOnce;
import org.opensearch.common.settings.Settings;
import org.opensearch.core.common.unit.ByteSizeUnit;
import org.opensearch.core.common.unit.ByteSizeValue;
import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.index.codec.CodecService;
import org.opensearch.index.engine.EngineConfig;
import org.opensearch.index.engine.InternalEngine;
import org.opensearch.index.refresh.RefreshStats;
import org.opensearch.index.shard.IndexShard;
import org.opensearch.index.shard.IndexShardTestCase;
import org.opensearch.indices.recovery.RecoveryState;
import org.opensearch.threadpool.Scheduler.Cancellable;
import org.opensearch.threadpool.ThreadPool;
import org.opensearch.threadpool.ThreadPoolStats;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
public class IndexingMemoryControllerTests extends IndexShardTestCase {
static class MockController extends IndexingMemoryController {
// Size of each shard's indexing buffer
final Map<IndexShard, Long> indexBufferRAMBytesUsed = new HashMap<>();
// How many bytes this shard is currently moving to disk
final Map<IndexShard, Long> writingBytes = new HashMap<>();
// Shards that are currently throttled
final Set<IndexShard> throttled = new HashSet<>();
MockController(Settings settings) {
super(
Settings.builder()
.put("indices.memory.interval", "200h") // disable it
.put(settings)
.build(),
null,
null
);
}
public void deleteShard(IndexShard shard) {
indexBufferRAMBytesUsed.remove(shard);
writingBytes.remove(shard);
}
@Override
protected List<IndexShard> availableShards() {
return new ArrayList<>(indexBufferRAMBytesUsed.keySet());
}
@Override
protected long getIndexBufferRAMBytesUsed(IndexShard shard) {
return indexBufferRAMBytesUsed.get(shard) + writingBytes.get(shard);
}
@Override
protected long getShardWritingBytes(IndexShard shard) {
Long bytes = writingBytes.get(shard);
if (bytes == null) {
return 0;
} else {
return bytes;
}
}
@Override
protected void checkIdle(IndexShard shard, long inactiveTimeNS) {}
@Override
public void writeIndexingBufferAsync(IndexShard shard) {
long bytes = indexBufferRAMBytesUsed.put(shard, 0L);
writingBytes.put(shard, writingBytes.get(shard) + bytes);
indexBufferRAMBytesUsed.put(shard, 0L);
}
@Override
public void activateThrottling(IndexShard shard) {
assertTrue(throttled.add(shard));
}
@Override
public void deactivateThrottling(IndexShard shard) {
assertTrue(throttled.remove(shard));
}
public void doneWriting(IndexShard shard) {
writingBytes.put(shard, 0L);
}
public void assertBuffer(IndexShard shard, int expectedMB) {
Long actual = indexBufferRAMBytesUsed.get(shard);
if (actual == null) {
actual = 0L;
}
assertEquals(expectedMB * 1024 * 1024, actual.longValue());
}
public void assertThrottled(IndexShard shard) {
assertTrue(throttled.contains(shard));
}
public void assertNotThrottled(IndexShard shard) {
assertFalse(throttled.contains(shard));
}
public void assertWriting(IndexShard shard, int expectedMB) {
Long actual = writingBytes.get(shard);
if (actual == null) {
actual = 0L;
}
assertEquals(expectedMB * 1024 * 1024, actual.longValue());
}
public void simulateIndexing(IndexShard shard) {
Long bytes = indexBufferRAMBytesUsed.get(shard);
if (bytes == null) {
bytes = 0L;
// First time we are seeing this shard:
writingBytes.put(shard, 0L);
}
// Each doc we index takes up a megabyte!
bytes += 1024 * 1024;
indexBufferRAMBytesUsed.put(shard, bytes);
forceCheck();
}
@Override
protected Cancellable scheduleTask(ThreadPool threadPool) {
return null;
}
}
public void testShardAdditionAndRemoval() throws IOException {
MockController controller = new MockController(Settings.builder().put("indices.memory.index_buffer_size", "4mb").build());
IndexShard shard0 = newStartedShard();
controller.simulateIndexing(shard0);
controller.assertBuffer(shard0, 1);
// add another shard
IndexShard shard1 = newStartedShard();
controller.simulateIndexing(shard1);
controller.assertBuffer(shard0, 1);
controller.assertBuffer(shard1, 1);
// remove first shard
controller.deleteShard(shard0);
controller.forceCheck();
controller.assertBuffer(shard1, 1);
// remove second shard
controller.deleteShard(shard1);
controller.forceCheck();
// add a new one
IndexShard shard2 = newStartedShard();
controller.simulateIndexing(shard2);
controller.assertBuffer(shard2, 1);
closeShards(shard0, shard1, shard2);
}
public void testActiveInactive() throws IOException {
MockController controller = new MockController(Settings.builder().put("indices.memory.index_buffer_size", "5mb").build());
IndexShard shard0 = newStartedShard();
controller.simulateIndexing(shard0);
IndexShard shard1 = newStartedShard();
controller.simulateIndexing(shard1);
controller.assertBuffer(shard0, 1);
controller.assertBuffer(shard1, 1);
controller.simulateIndexing(shard0);
controller.simulateIndexing(shard1);
controller.assertBuffer(shard0, 2);
controller.assertBuffer(shard1, 2);
// index into one shard only, crosses the 5mb limit, so shard1 is refreshed
controller.simulateIndexing(shard0);
controller.simulateIndexing(shard0);
controller.assertBuffer(shard0, 0);
controller.assertBuffer(shard1, 2);
controller.simulateIndexing(shard1);
controller.simulateIndexing(shard1);
controller.assertBuffer(shard1, 4);
controller.simulateIndexing(shard1);
controller.simulateIndexing(shard1);
// shard1 crossed 5 mb and is now cleared:
controller.assertBuffer(shard1, 0);
closeShards(shard0, shard1);
}
public void testMinBufferSizes() {
MockController controller = new MockController(
Settings.builder().put("indices.memory.index_buffer_size", "0.001%").put("indices.memory.min_index_buffer_size", "6mb").build()
);
assertThat(controller.indexingBufferSize(), equalTo(new ByteSizeValue(6, ByteSizeUnit.MB)));
}
public void testNegativeMinIndexBufferSize() {
Exception e = expectThrows(
IllegalArgumentException.class,
() -> new MockController(Settings.builder().put("indices.memory.min_index_buffer_size", "-6mb").build())
);
assertEquals("failed to parse setting [indices.memory.min_index_buffer_size] with value [-6mb] as a size in bytes", e.getMessage());
}
public void testNegativeInterval() {
Exception e = expectThrows(
IllegalArgumentException.class,
() -> new MockController(Settings.builder().put("indices.memory.interval", "-42s").build())
);
assertEquals(
"failed to parse setting [indices.memory.interval] with value "
+ "[-42s] as a time value: negative durations are not supported",
e.getMessage()
);
}
public void testNegativeShardInactiveTime() {
Exception e = expectThrows(
IllegalArgumentException.class,
() -> new MockController(Settings.builder().put("indices.memory.shard_inactive_time", "-42s").build())
);
assertEquals(
"failed to parse setting [indices.memory.shard_inactive_time] with value "
+ "[-42s] as a time value: negative durations are not supported",
e.getMessage()
);
}
public void testNegativeMaxIndexBufferSize() {
Exception e = expectThrows(
IllegalArgumentException.class,
() -> new MockController(Settings.builder().put("indices.memory.max_index_buffer_size", "-6mb").build())
);
assertEquals("failed to parse setting [indices.memory.max_index_buffer_size] with value [-6mb] as a size in bytes", e.getMessage());
}
public void testMaxBufferSizes() {
MockController controller = new MockController(
Settings.builder().put("indices.memory.index_buffer_size", "90%").put("indices.memory.max_index_buffer_size", "6mb").build()
);
assertThat(controller.indexingBufferSize(), equalTo(new ByteSizeValue(6, ByteSizeUnit.MB)));
}
public void testThrottling() throws Exception {
MockController controller = new MockController(Settings.builder().put("indices.memory.index_buffer_size", "4mb").build());
IndexShard shard0 = newStartedShard();
IndexShard shard1 = newStartedShard();
controller.simulateIndexing(shard0);
controller.simulateIndexing(shard0);
controller.simulateIndexing(shard0);
controller.assertBuffer(shard0, 3);
controller.simulateIndexing(shard1);
controller.simulateIndexing(shard1);
// We are now using 5 MB, so we should be writing shard0 since it's using the most heap:
controller.assertWriting(shard0, 3);
controller.assertWriting(shard1, 0);
controller.assertBuffer(shard0, 0);
controller.assertBuffer(shard1, 2);
controller.simulateIndexing(shard0);
controller.simulateIndexing(shard1);
controller.simulateIndexing(shard1);
// Now we are still writing 3 MB (shard0), and using 5 MB index buffers, so we should now 1) be writing shard1,
// and 2) be throttling shard1:
controller.assertWriting(shard0, 3);
controller.assertWriting(shard1, 4);
controller.assertBuffer(shard0, 1);
controller.assertBuffer(shard1, 0);
controller.assertNotThrottled(shard0);
controller.assertThrottled(shard1);
logger.info("--> Indexing more data");
// More indexing to shard0
controller.simulateIndexing(shard0);
controller.simulateIndexing(shard0);
controller.simulateIndexing(shard0);
controller.simulateIndexing(shard0);
// Now we are using 5 MB again, so shard0 should also be writing and now also be throttled:
controller.assertWriting(shard0, 8);
controller.assertWriting(shard1, 4);
controller.assertBuffer(shard0, 0);
controller.assertBuffer(shard1, 0);
controller.assertThrottled(shard0);
controller.assertThrottled(shard1);
// Both shards finally finish writing, and throttling should stop:
controller.doneWriting(shard0);
controller.doneWriting(shard1);
controller.forceCheck();
controller.assertNotThrottled(shard0);
controller.assertNotThrottled(shard1);
closeShards(shard0, shard1);
}
public void testTranslogRecoveryWorksWithIMC() throws IOException {
IndexShard shard = newStartedShard(true);
for (int i = 0; i < 100; i++) {
indexDoc(shard, Integer.toString(i), "{\"foo\" : \"bar\"}", MediaTypeRegistry.JSON, null);
}
shard.close("simon says", false, false);
AtomicReference<IndexShard> shardRef = new AtomicReference<>();
Settings settings = Settings.builder().put("indices.memory.index_buffer_size", "50kb").build();
Iterable<IndexShard> iterable = () -> (shardRef.get() == null)
? Collections.emptyIterator()
: Collections.singleton(shardRef.get()).iterator();
AtomicInteger flushes = new AtomicInteger();
IndexingMemoryController imc = new IndexingMemoryController(settings, threadPool, iterable) {
@Override
protected void writeIndexingBufferAsync(IndexShard shard) {
assertEquals(shard, shardRef.get());
flushes.incrementAndGet();
shard.writeIndexingBuffer();
}
};
shard = reinitShard(shard, imc);
shardRef.set(shard);
assertEquals(0, imc.availableShards().size());
DiscoveryNode localNode = new DiscoveryNode("foo", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT);
shard.markAsRecovering("store", new RecoveryState(shard.routingEntry(), localNode, null));
assertEquals(1, imc.availableShards().size());
assertTrue(recoverFromStore(shard));
assertThat("we should have flushed in IMC at least once", flushes.get(), greaterThanOrEqualTo(1));
closeShards(shard);
}
EngineConfig configWithRefreshListener(EngineConfig config, ReferenceManager.RefreshListener listener) {
final List<ReferenceManager.RefreshListener> internalRefreshListener = new ArrayList<>(config.getInternalRefreshListener());
;
internalRefreshListener.add(listener);
return new EngineConfig.Builder().shardId(config.getShardId())
.threadPool(config.getThreadPool())
.indexSettings(config.getIndexSettings())
.warmer(config.getWarmer())
.store(config.getStore())
.mergePolicy(config.getMergePolicy())
.analyzer(config.getAnalyzer())
.similarity(config.getSimilarity())
.codecService(new CodecService(null, config.getIndexSettings(), logger))
.eventListener(config.getEventListener())
.queryCache(config.getQueryCache())
.queryCachingPolicy(config.getQueryCachingPolicy())
.translogConfig(config.getTranslogConfig())
.flushMergesAfter(config.getFlushMergesAfter())
.externalRefreshListener(config.getExternalRefreshListener())
.internalRefreshListener(internalRefreshListener)
.indexSort(config.getIndexSort())
.circuitBreakerService(config.getCircuitBreakerService())
.globalCheckpointSupplier(config.getGlobalCheckpointSupplier())
.retentionLeasesSupplier(config.retentionLeasesSupplier())
.primaryTermSupplier(config.getPrimaryTermSupplier())
.tombstoneDocSupplier(config.getTombstoneDocSupplier())
.build();
}
ThreadPoolStats.Stats getRefreshThreadPoolStats() {
final ThreadPoolStats stats = threadPool.stats();
for (ThreadPoolStats.Stats s : stats) {
if (s.getName().equals(ThreadPool.Names.REFRESH)) {
return s;
}
}
throw new AssertionError("refresh thread pool stats not found [" + stats + "]");
}
public void testSkipRefreshIfShardIsRefreshingAlready() throws Exception {
SetOnce<CountDownLatch> refreshLatch = new SetOnce<>();
ReferenceManager.RefreshListener refreshListener = new ReferenceManager.RefreshListener() {
@Override
public void beforeRefresh() {
if (refreshLatch.get() != null) {
try {
refreshLatch.get().await();
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}
}
@Override
public void afterRefresh(boolean didRefresh) {
}
};
IndexShard shard = newStartedShard(
randomBoolean(),
Settings.EMPTY,
config -> new InternalEngine(configWithRefreshListener(config, refreshListener))
);
refreshLatch.set(new CountDownLatch(1)); // block refresh
final RefreshStats refreshStats = shard.refreshStats();
final IndexingMemoryController controller = new IndexingMemoryController(
Settings.builder()
.put("indices.memory.interval", "200h") // disable it
.put("indices.memory.index_buffer_size", "1024b")
.build(),
threadPool,
Collections.singleton(shard)
) {
@Override
protected long getIndexBufferRAMBytesUsed(IndexShard shard) {
return randomLongBetween(1025, 10 * 1024 * 1024);
}
@Override
protected long getShardWritingBytes(IndexShard shard) {
return 0L;
}
};
int iterations = randomIntBetween(10, 100);
ThreadPoolStats.Stats beforeStats = getRefreshThreadPoolStats();
for (int i = 0; i < iterations; i++) {
controller.forceCheck();
}
assertBusy(() -> {
ThreadPoolStats.Stats stats = getRefreshThreadPoolStats();
assertThat(stats.getCompleted(), equalTo(beforeStats.getCompleted() + iterations - 1));
});
refreshLatch.get().countDown(); // allow refresh
assertBusy(() -> {
ThreadPoolStats.Stats stats = getRefreshThreadPoolStats();
assertThat(stats.getCompleted(), equalTo(beforeStats.getCompleted() + iterations));
});
assertThat(shard.refreshStats().getTotal(), equalTo(refreshStats.getTotal() + 1));
closeShards(shard);
}
}