-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
StandaloneClusterClientIT.java
345 lines (316 loc) · 12.6 KB
/
StandaloneClusterClientIT.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
/*
* Copyright (c) 2002-2016 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.server.enterprise;
import org.apache.commons.lang3.SystemUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.AccessibleObject;
import java.net.URI;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import org.neo4j.cluster.InstanceId;
import org.neo4j.cluster.client.ClusterClient;
import org.neo4j.cluster.client.ClusterClientModule;
import org.neo4j.cluster.protocol.cluster.ClusterConfiguration;
import org.neo4j.cluster.protocol.cluster.ClusterListener;
import org.neo4j.cluster.protocol.cluster.ClusterListener.Adapter;
import org.neo4j.cluster.protocol.election.ServerIdElectionCredentialsProvider;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.impl.logging.NullLogService;
import org.neo4j.kernel.impl.util.Dependencies;
import org.neo4j.kernel.lifecycle.LifeSupport;
import org.neo4j.kernel.monitoring.Monitors;
import org.neo4j.server.configuration.ServerSettings;
import org.neo4j.server.enterprise.functional.DumpPortListenerOnNettyBindFailure;
import org.neo4j.test.InputStreamAwaiter;
import org.neo4j.test.ProcessStreamHandler;
import org.neo4j.test.TargetDirectory;
import static java.lang.Runtime.getRuntime;
import static java.lang.String.format;
import static java.lang.System.getProperty;
import static java.util.Arrays.asList;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import static org.neo4j.cluster.ClusterSettings.cluster_server;
import static org.neo4j.cluster.ClusterSettings.initial_hosts;
import static org.neo4j.cluster.ClusterSettings.server_id;
import static org.neo4j.helpers.collection.MapUtil.store;
import static org.neo4j.helpers.collection.MapUtil.stringMap;
import static org.neo4j.server.enterprise.StandaloneClusterClientTestProxy.START_SIGNAL;
import static org.neo4j.test.StreamConsumer.IGNORE_FAILURES;
public class StandaloneClusterClientIT
{
@Test
public void canJoinWithExplicitInitialHosts() throws Exception
{
startAndAssertJoined( 5003,
// Config file
stringMap(),
// Arguments
stringMap(
initial_hosts.name(), ":5001",
server_id.name(), "3" )
);
}
@Test
public void willFailJoinIfIncorrectInitialHostsSet() throws Exception
{
assumeFalse( "Cannot kill processes on windows.", SystemUtils.IS_OS_WINDOWS );
startAndAssertJoined( SHOULD_NOT_JOIN,
// Config file
stringMap(),
// Arguments
stringMap(
initial_hosts.name(), ":5011",
server_id.name(), "3" )
);
}
@Test
public void canJoinWithInitialHostsInConfigFile() throws Exception
{
startAndAssertJoined( 5003,
// Config file
stringMap( initial_hosts.name(), ":5001" ),
// Arguments
stringMap( server_id.name(), "3" ) );
}
@Test
public void willFailJoinIfIncorrectInitialHostsSetInConfigFile() throws Exception
{
assumeFalse( "Cannot kill processes on windows.", SystemUtils.IS_OS_WINDOWS );
startAndAssertJoined( SHOULD_NOT_JOIN,
// Config file
stringMap( initial_hosts.name(), ":5011" ),
// Arguments
stringMap( server_id.name(), "3" ) );
}
@Test
public void canOverrideInitialHostsConfigFromConfigFile() throws Exception
{
startAndAssertJoined( 5003,
// Config file
stringMap( initial_hosts.name(), ":5011" ),
// Arguments
stringMap(
initial_hosts.name(), ":5001",
server_id.name(), "3" )
);
}
@Test
public void canSetSpecificPort() throws Exception
{
startAndAssertJoined( 5010,
// Config file
stringMap(),
// Arguments
stringMap(
initial_hosts.name(), ":5001",
server_id.name(), "3",
cluster_server.name(), ":5010" )
);
}
@Test
public void usesPortRangeFromConfigFile() throws Exception
{
startAndAssertJoined( 5012,
// Config file
stringMap(
initial_hosts.name(), ":5001",
cluster_server.name(), ":5012-5020" ),
// Arguments
stringMap( server_id.name(), "3" )
);
}
// === Everything else ===
private static Integer SHOULD_NOT_JOIN = null;
@Rule
public TestRule dumpPorts = new DumpPortListenerOnNettyBindFailure();
@Rule
public TargetDirectory.TestDirectory testDirectory = TargetDirectory.testDirForTest( getClass() );
private File directory;
private LifeSupport life;
private ClusterClient[] clients;
@Before
public void before() throws Exception
{
directory = testDirectory.directory( "temp" );
life = new LifeSupport();
life.start(); // So that the clients get started as they are added
clients = new ClusterClient[2];
for ( int i = 1; i <= clients.length; i++ )
{
Map<String, String> config = stringMap();
config.put( cluster_server.name(), ":" + (5000 + i) );
config.put( server_id.name(), "" + i );
config.put( initial_hosts.name(), ":5001" );
LifeSupport moduleLife = new LifeSupport();
ClusterClientModule clusterClientModule = new ClusterClientModule( moduleLife, new Dependencies(),
new Monitors(), new Config( config ), NullLogService.getInstance(),
new ServerIdElectionCredentialsProvider() );
ClusterClient client = clusterClientModule.clusterClient;
CountDownLatch latch = new CountDownLatch( 1 );
client.addClusterListener( new ClusterListener.Adapter()
{
@Override
public void enteredCluster( ClusterConfiguration configuration )
{
latch.countDown();
client.removeClusterListener( this );
}
} );
life.add( moduleLife );
clients[i - 1] = client;
assertTrue( "Didn't join the cluster", latch.await( 20, SECONDS ) );
}
}
@After
public void after() throws Exception
{
life.shutdown();
}
private File configFile( Map<String, String> config ) throws IOException
{
File configFile = new File( directory, "config-file" );
store( config, configFile );
return configFile;
}
private void startAndAssertJoined( Integer expectedAssignedPort, Map<String, String> configInConfigFile,
Map<String, String> config ) throws Exception
{
Map<String,String> localCopy = new HashMap<>( configInConfigFile );
localCopy.put( GraphDatabaseSettings.auth_store.name(), Files.createTempFile("auth", "").toString() );
File configFile = configFile( localCopy );
CountDownLatch latch = new CountDownLatch( 1 );
AtomicInteger port = new AtomicInteger();
clients[0].addClusterListener( joinAwaitingListener( latch, port ) );
boolean clientStarted = startStandaloneClusterClient( configFile, config, latch );
if ( expectedAssignedPort == null )
{
assertFalse( format( "Should not be able to start cluster client given config file:%s " +
"and arguments:%s", configInConfigFile, config ), clientStarted );
}
else
{
assertTrue( format( "Should be able to start client client given config file:%s " +
"and arguments:%s", configInConfigFile, config ), clientStarted );
assertEquals( expectedAssignedPort.intValue(), port.get() );
}
}
private Adapter joinAwaitingListener( final CountDownLatch latch, final AtomicInteger port )
{
return new ClusterListener.Adapter()
{
@Override
public void joinedCluster( InstanceId member, URI memberUri )
{
port.set( memberUri.getPort() );
latch.countDown();
clients[0].removeClusterListener( this );
}
};
}
private boolean startStandaloneClusterClient( File configFile, Map<String, String> config, CountDownLatch latch )
throws Exception
{
Process process = null;
ProcessStreamHandler handler = null;
try
{
process = startStandaloneClusterClientProcess( configFile, config );
new InputStreamAwaiter( process.getInputStream() ).awaitLine( START_SIGNAL, 20, SECONDS );
handler = new ProcessStreamHandler( process, false, "", IGNORE_FAILURES );
handler.launch();
// Latch is triggered when this cluster client we just spawned joins the cluster,
// or rather when the first client sees it as joined. If the latch awaiting times out it
// (most likely) means that this cluster client couldn't be started. The reason for not
// being able to start is assumed in this test to be that the specified port already is in use.
return latch.await( 10, SECONDS );
}
finally
{
if ( process != null )
{
// Tell it to leave the cluster and shut down now
try ( OutputStream inputToOtherProcess = process.getOutputStream() )
{
inputToOtherProcess.write( 0 );
inputToOtherProcess.flush();
}
if ( !process.waitFor( 10, SECONDS ) )
{
kill( process );
}
}
if ( handler != null )
{
handler.done();
}
}
}
private Process startStandaloneClusterClientProcess( File configFile, Map<String, String> config )
throws Exception
{
List<String> args = new ArrayList<>( asList( "java", "-cp", getProperty( "java.class.path" ),
"-Dorg.neo4j.cluster.logdirectory=" + directory.getAbsolutePath() ) );
if ( configFile != null )
{
args.add( "-D" + ServerSettings.SERVER_CONFIG_FILE_KEY + "=" + configFile.getAbsolutePath() );
}
args.add( StandaloneClusterClientTestProxy.class.getName() );
for ( Map.Entry<String, String> entry : config.entrySet() )
{
args.add( "-" + entry.getKey() + "=" + entry.getValue() );
}
return getRuntime().exec( args.toArray( new String[args.size()] ) );
}
private static void kill( Process process )
throws NoSuchFieldException, IllegalAccessException, IOException, InterruptedException
{
if ( SystemUtils.IS_OS_WINDOWS )
{
process.destroy();
}
else
{
int pid = ((Number) accessible( process.getClass().getDeclaredField( "pid" ) ).get( process )).intValue();
new ProcessBuilder( "kill", "-9", "" + pid ).start().waitFor();
}
}
private static <T extends AccessibleObject> T accessible( T obj )
{
obj.setAccessible( true );
return obj;
}
}