-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathReconnectIT.java
408 lines (349 loc) · 18.3 KB
/
ReconnectIT.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
package io.tarantool.driver.integration;
import io.tarantool.driver.api.TarantoolClient;
import io.tarantool.driver.api.TarantoolClientConfig;
import io.tarantool.driver.api.TarantoolClientFactory;
import io.tarantool.driver.api.TarantoolClusterAddressProvider;
import io.tarantool.driver.api.TarantoolResult;
import io.tarantool.driver.api.TarantoolServerAddress;
import io.tarantool.driver.api.conditions.Conditions;
import io.tarantool.driver.api.space.TarantoolSpaceOperations;
import io.tarantool.driver.api.tuple.DefaultTarantoolTupleFactory;
import io.tarantool.driver.api.tuple.TarantoolTuple;
import io.tarantool.driver.api.tuple.TarantoolTupleFactory;
import io.tarantool.driver.auth.SimpleTarantoolCredentials;
import io.tarantool.driver.cluster.BinaryClusterDiscoveryEndpoint;
import io.tarantool.driver.cluster.BinaryDiscoveryClusterAddressProvider;
import io.tarantool.driver.cluster.TarantoolClusterDiscoveryConfig;
import io.tarantool.driver.cluster.TestWrappedClusterAddressProvider;
import io.tarantool.driver.core.TarantoolDaemonThreadFactory;
import io.tarantool.driver.exceptions.TarantoolNoSuchProcedureException;
import io.tarantool.driver.mappers.factories.DefaultMessagePackMapperFactory;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import static io.tarantool.driver.TarantoolUtils.retry;
import static io.tarantool.driver.api.retry.TarantoolRequestRetryPolicies.retryNetworkErrors;
import static io.tarantool.driver.api.retry.TarantoolRequestRetryPolicies.retryTarantoolNoSuchProcedureErrors;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Oleg Kuznetsov
* @author Ivan Dneprov
* <p>
* WARNING: If you updated the code in this file, don't forget to update the MultiInstanceConnecting.md and
* docs/RetryingTarantoolClient.md permalinks!
*/
@Testcontainers
public class ReconnectIT extends SharedCartridgeContainer {
private static final Logger logger = LoggerFactory.getLogger(ReconnectIT.class);
private static String USER_NAME;
private static String PASSWORD;
private static final String SPACE_NAME = "test__profile";
private static final String PK_FIELD_NAME = "profile_id";
private static AtomicInteger retryingCounter;
private static final DefaultMessagePackMapperFactory mapperFactory = DefaultMessagePackMapperFactory.getInstance();
private static final TarantoolTupleFactory tupleFactory =
new DefaultTarantoolTupleFactory(mapperFactory.defaultComplexTypesMapper());
@BeforeAll
public static void setUp() throws TimeoutException {
startCluster();
USER_NAME = container.getUsername();
PASSWORD = container.getPassword();
}
@Test
public void test_should_retryDelete_ifRecordsNotFound() throws InterruptedException {
// Creating multiple clients
TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> crudClient = getCrudClient();
TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> retryingClient =
getRetryingTarantoolClient(crudClient);
TarantoolSpaceOperations<TarantoolTuple, TarantoolResult<TarantoolTuple>> space =
crudClient.space(SPACE_NAME);
space.truncate().join();
// Use TarantoolTupleFactory for instantiating new tuples
TarantoolTupleFactory tupleFactory = new DefaultTarantoolTupleFactory(
crudClient.getConfig().getMessagePackMapper());
// Call delete_with_error_if_not_found before record was inserted
Conditions conditions = Conditions.equals(PK_FIELD_NAME, 1);
CompletableFuture deleteFuture = retryingClient.space(SPACE_NAME).delete(conditions);
retry(() -> assertEquals(1, retryingCounter.get()));
space.insert(tupleFactory.create(1, null, "FIO", 50, 100)).join();
deleteFuture.join();
TarantoolResult<TarantoolTuple> selectResult = space.select(conditions).join();
assertEquals(0, selectResult.size());
}
/**
* Checking if this test is valid is here
* {@link TarantoolErrorsIT#test_should_throwTarantoolNoSuchProcedureException_ifProcedureIsNil}
*/
@Test
public void test_should_reconnect_ifCrudProcedureIsNotDefined() {
//when
TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> crudClient = getCrudClient();
TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> retryingClient =
getRetryingTarantoolClient(crudClient);
try {
//save procedure to tmp variable set it to nil and call
crudClient.eval("rawset(_G, 'tmp_test_no_such_procedure', test_no_such_procedure)")
.thenAccept(c -> crudClient.eval("rawset(_G, 'test_no_such_procedure', nil)"))
.thenApply(c -> crudClient.call("test_no_such_procedure"))
.join();
} catch (CompletionException exception) {
assertTrue(exception.getCause() instanceof TarantoolNoSuchProcedureException);
}
//start another thread that will return the procedure back after 100 ms
new Thread(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
crudClient.eval("rawset(_G, 'test_no_such_procedure', tmp_test_no_such_procedure)").join();
}).start();
assertDoesNotThrow(() -> retryingClient.call("test_no_such_procedure").join());
assertEquals("test_no_such_procedure", retryingClient.call("test_no_such_procedure").join().get(0));
}
private TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> getCrudClient() {
return TarantoolClientFactory.createClient()
// You can connect to multiple routers
.withAddresses(
new TarantoolServerAddress(container.getRouterHost(), container.getMappedPort(3301)),
new TarantoolServerAddress(container.getRouterHost(), container.getMappedPort(3302)),
new TarantoolServerAddress(container.getRouterHost(), container.getMappedPort(3303))
)
// For connecting to a Cartridge application,
// use the value of cluster_cookie parameter in the init.lua file
.withCredentials(USER_NAME, PASSWORD)
// Number of connections per Tarantool instance
.withConnections(10)
// Specify using the default CRUD proxy operations mapping configuration
.withProxyMethodMapping()
.build();
}
@Test
public void test_should_reconnect_ifReconnectIsInvoked() throws Exception {
//when
TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> client =
getRetryingTarantoolClient(getCrudClient());
// getting all routers uuids
final Set<String> routerUuids = getInstancesUuids(client);
// stop routers
container.execInContainer("cartridge", "stop", "--run-dir=/tmp/run", "router");
container.execInContainer("cartridge", "stop", "--run-dir=/tmp/run", "second-router");
// check that there is only one instance left
assertEquals(getInstanceUuid(client), getInstanceUuid(client));
// start routers
container.execInContainer("cartridge", "start", "--run-dir=/tmp/run", "--data-dir=/tmp/data", "-d");
client.refresh();
Thread.sleep(3000);
// getting all routers uuids after restarting
final Set<String> uuidsAfterReconnect = getInstancesUuids(client);
// check that amount of routers is equal initial amount
assertEquals(routerUuids.size(), uuidsAfterReconnect.size());
}
private TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> getRetryingTarantoolClient(
TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> client) {
retryingCounter = new AtomicInteger();
return TarantoolClientFactory.configureClient(client)
// Configure a custom delete function
.withProxyMethodMapping(builder -> builder.withDeleteFunctionName("delete_with_error_if_not_found"))
// Set retrying policy
// First parameter is number of attempts
.withRetryingByNumberOfAttempts(5,
// You can use default predicates from TarantoolRequestRetryPolicies for checking errors
retryNetworkErrors()
// Also you can use your own predicates and combine them with each other
.or(e -> e.getMessage().contains("Unsuccessful attempt"))
.or(e -> {
retryingCounter.getAndIncrement();
return e.getMessage().contains("Records not found");
})
// Or with defaults
.or(retryTarantoolNoSuchProcedureErrors()),
// Also you can set delay in millisecond between attempts
factory -> factory.withDelay(300)
)
.build();
}
@Test
public void
test_should_removeUnavailableHostsFromAddressProvider_ifDiscoveryProcedureReturnStatusNotHealthyAndNotAvailable()
throws Exception {
initRouterStatuses();
final TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> client = initClientWithDiscovery();
final Set<String> instancesUuids = getInstancesUuids(client);
assertEquals(3, instancesUuids.size());
replaceInstancesInfo(client, 1, "unavailable", 3301);
replaceInstancesInfo(client, 2, "unavailable", 3302);
Thread.sleep(1000);
final Set<String> afterRoutersDisablingInstancesUuids = getInstancesUuids(client);
assertEquals(1, afterRoutersDisablingInstancesUuids.size());
replaceInstancesInfo(client, 1, "available", 3301);
replaceInstancesInfo(client, 2, "available", 3302);
Thread.sleep(1000);
final Set<String> afterRoutersEnablingInstancesUuids = getInstancesUuids(client);
assertEquals(3, afterRoutersEnablingInstancesUuids.size());
}
@Test
@SuppressWarnings("unchecked")
void test_should_closeConnections_ifAddressProviderReturnsNewAddresses() throws Exception {
// restart routers for resetting connections
stopInstances(Arrays.asList("router", "second-router"));
startCartridge();
final TarantoolServerAddress firstAddress =
new TarantoolServerAddress(container.getRouterHost(), container.getMappedPort(3301));
final TarantoolServerAddress secondAddress =
new TarantoolServerAddress(container.getRouterHost(), container.getMappedPort(3302));
final TarantoolServerAddress[] tarantoolServerAddresses = {firstAddress, secondAddress};
// create client for check number of connections
final TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> clientForCheck =
TarantoolClientFactory.createClient()
.withCredentials(container.getUsername(), container.getPassword())
.withAddresses(tarantoolServerAddresses)
.withRetryingByNumberOfAttempts(10, b -> b.withDelay(100))
.build();
// make a function which returns everytime a one of two addresses in order
AtomicBoolean isNextAddress = new AtomicBoolean(false);
Callable<List<TarantoolServerAddress>> getTarantoolServerAddresses = () -> {
if (isNextAddress.compareAndSet(true, false)) {
return Collections.singletonList(secondAddress);
}
isNextAddress.compareAndSet(false, true);
return Collections.singletonList(firstAddress);
};
// make client for testing
final AtomicBoolean isRefreshNeeded = new AtomicBoolean(false);
final AtomicInteger numberOfSwitching = new AtomicInteger(0);
final TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> client =
TarantoolClientFactory.createClient()
.withCredentials(container.getUsername(), container.getPassword())
.withAddressProvider(new TarantoolClusterAddressProvider() {
@Override
public Collection<TarantoolServerAddress> getAddresses() {
try {
return getTarantoolServerAddresses.call();
} catch (Exception exception) {
exception.printStackTrace();
return Collections.emptyList();
}
}
@Override
public void setRefreshCallback(Runnable runnable) {
// make a daemon that will refresh connections every 100ms
Executors.newSingleThreadScheduledExecutor(
new TarantoolDaemonThreadFactory("refresh-connections")
).scheduleAtFixedRate(() -> {
if (isRefreshNeeded.get()) {
numberOfSwitching.incrementAndGet();
runnable.run();
}
}, 500, 100, TimeUnit.MILLISECONDS);
}
}).build();
//initiate establish connection
client.getVersion();
isRefreshNeeded.set(true);
logger.info("Waiting while number of switching won't be 50");
while (numberOfSwitching.get() < 50) {
Thread.sleep(100);
}
final List<Map<String, Map<String, Integer>>> result = (List<Map<String, Map<String, Integer>>>)
clientForCheck.eval("return box.stat.net()").join();
assertTrue(result.get(0).get("CONNECTIONS").get("current") < 20);
}
private TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> initClientWithDiscovery() {
final BinaryClusterDiscoveryEndpoint discoveryEndpoint = BinaryClusterDiscoveryEndpoint.builder()
.withEntryFunction("get_routers_status")
.withEndpointProvider(this::getShuffledTarantoolServerAddresses)
.withClientConfig(TarantoolClientConfig.builder()
.withCredentials(new SimpleTarantoolCredentials(USER_NAME, PASSWORD))
.build()
)
.build();
final BinaryDiscoveryClusterAddressProvider binaryDiscoveryClusterAddressProvider =
new BinaryDiscoveryClusterAddressProvider(TarantoolClusterDiscoveryConfig.builder()
.withEndpoint(discoveryEndpoint)
.withDelay(50)
.build());
return TarantoolClientFactory.createClient()
.withAddressProvider(
new TestWrappedClusterAddressProvider(binaryDiscoveryClusterAddressProvider, container))
.withCredentials(USER_NAME, PASSWORD)
.withConnections(10)
.withProxyMethodMapping()
.build();
}
private void initRouterStatuses() {
final TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> initClient =
TarantoolClientFactory.createClient()
// You can connect to multiple routers
// Do not forget to shuffle your addresses if you are using multiple clients
.withAddresses(getShuffledTarantoolServerAddresses())
// For connecting to a Cartridge application,
// use the value of cluster_cookie parameter in the init.lua file
.withCredentials(USER_NAME, PASSWORD)
// Number of connections per Tarantool instance
.withConnections(1)
// Specify using the default CRUD proxy operations mapping configuration
.withProxyMethodMapping()
.build();
initClient.call("init_router_status").join();
}
private void replaceInstancesInfo(
TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> client,
int id, String status, Integer port) {
final TarantoolTuple tuple = tupleFactory
.create(id, 1, UUID.randomUUID().toString(), status, String.format("%s:%s", "localhost", port));
client.space("instances_info").replace(tuple).join();
}
@NotNull
private List<TarantoolServerAddress> getShuffledTarantoolServerAddresses() {
List<TarantoolServerAddress> addresses = Arrays.asList(
new TarantoolServerAddress(container.getRouterHost(), container.getMappedPort(3301)),
new TarantoolServerAddress(container.getRouterHost(), container.getMappedPort(3302)),
new TarantoolServerAddress(container.getRouterHost(), container.getMappedPort(3303))
);
Collections.shuffle(addresses);
return addresses;
}
/**
* Return all instances uuids from cluster, using round robin connection selection strategy
*
* @param client Tarantool client
* @return set of instances uuids from cluster
*/
private Set<String> getInstancesUuids(TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> client) {
String firstUuid = getInstanceUuid(client);
final Set<String> instancesUuids = new HashSet<>();
instancesUuids.add(firstUuid);
String currentUuid = "";
while (!firstUuid.equals(currentUuid)) {
currentUuid = getInstanceUuid(client);
instancesUuids.add(currentUuid);
}
return instancesUuids;
}
private String getInstanceUuid(TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> client) {
return (String) client.eval("return box.info().uuid").join().get(0);
}
}