Debian Codegraph @

junixsocket-rmi/src/test/java/org/newsclub/net/unix/rmi/RemoteRegistryTest.java

raw
1 /*
2 * junixsocket
3 *
4 * Copyright 2009-2022 Christian Kohlschütter
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package org.newsclub.net.unix.rmi;
19
20 import static org.junit.jupiter.api.Assertions.assertEquals;
21 import static org.junit.jupiter.api.Assertions.assertNotNull;
22 import static org.junit.jupiter.api.Assertions.assertThrows;
23 import static org.junit.jupiter.api.Assertions.assertTrue;
24 import static org.junit.jupiter.api.Assumptions.assumeTrue;
25
26 import java.io.File;
27 import java.io.IOException;
28 import java.rmi.ServerException;
29 import java.util.Collections;
30 import java.util.List;
31 import java.util.concurrent.CompletableFuture;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.atomic.AtomicBoolean;
37
38 import org.junit.jupiter.api.Test;
39
40 import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;
41 import com.kohlschutter.testutil.ForkedVM;
42 import com.kohlschutter.testutil.ForkedVMRequirement;
43 import com.kohlschutter.testutil.OutputBridge;
44 import com.kohlschutter.testutil.OutputBridge.ProcessStream;
45
46 @ForkedVMRequirement(forkSupported = true)
47 @SuppressFBWarnings({
48 "THROWS_METHOD_THROWS_CLAUSE_THROWABLE", "THROWS_METHOD_THROWS_CLAUSE_BASIC_EXCEPTION"})
49 public class RemoteRegistryTest {
50 @Test
51 public void testRemoteRegistry() throws Exception {
52 File socketDir = tempSocketDir();
53
54 try (SpawnedRegistryAccess sra = new SpawnedRegistryAccess(TestRegistryServer.class
55 .getSimpleName(), socketDir) {
56
57 @Override
58 protected int exportHelloDelayMillis() {
59 return 500;
60 }
61
62 }) {
63 tryToSayHello(sra);
64 sra.shutdown();
65 } catch (Exception e) {
66 throw e;
67 }
68
69 assertEquals(0, countRMIFiles(socketDir));
70 assertTrue(socketDir.delete());
71 }
72
73 @Test
74 public void testRemoteRegistryStandardPath() throws Exception {
75 File socketDir = AFUNIXNaming.getDefaultSocketDirectory();
76 assumeTrue(countRMIFiles(socketDir) == 0,
77 "Test cannot be performed: *.rmi files exist in directory: " + socketDir);
78
79 for (int i = 1, n = 2; i <= n; i++) {
80 System.out.println("Attempt " + i + "/" + n);
81 try (SpawnedRegistryAccess sra = new SpawnedRegistryAccess(TestRegistryServer.class
82 .getSimpleName()) {
83
84 @Override
85 protected AFNaming getNamingInstance() throws IOException {
86 return AFUNIXNaming.getInstance();
87 }
88 }) {
89 tryToSayHello(sra);
90 sra.shutdown();
91 } catch (Exception e) {
92 throw e;
93 }
94 assertEquals(0, countRMIFiles(socketDir));
95 }
96 }
97
98 @Test
99 public void testRemoteShutdownNotAllowed() throws Exception {
100 File socketDir = tempSocketDir();
101
102 try (SpawnedRegistryAccess sra = new SpawnedRegistryAccess(TestRegistryServer.class
103 .getSimpleName(), socketDir) {
104
105 @Override
106 protected boolean remoteShutdownAllowed() {
107 return false;
108 }
109
110 @Override
111 protected int shutdownAfterSecs() {
112 return 30;
113 }
114 }) {
115 AFRegistry registry = sra.getRegistry();
116 assertNotNull(registry, "Could not access the AFUNIXRegistry created by the forked VM");
117
118 assertThrows(ServerException.class, () -> sra.getRegistry().getNaming().shutdownRegistry());
119
120 sra.shutdownAndWait(true);
121 } catch (Exception e) {
122 throw e;
123 }
124 assertEquals(0, countRMIFiles(socketDir));
125 }
126
127 private void tryToSayHello(SpawnedRegistryAccess sra) throws Exception {
128 AFRegistry registry = sra.getRegistry();
129 assertNotNull(registry, "Could not access the AFUNIXRegistry created by the forked VM");
130
131 AFNaming naming = registry.getNaming();
132 try {
133 Hello hello = (Hello) naming.lookup("hello", 20, TimeUnit.SECONDS);
134 assertEquals("Hello", hello.hello());
135 } finally {
136 naming.shutdownRegistry();
137
138 int rc = sra.shutdownAndWait();
139 assertEquals(0, rc, TestRegistryServer.class.getName()
140 + " process terminated with return code " + rc);
141 }
142 }
143
144 private static class SpawnedRegistryAccess implements AutoCloseable {
145 private final File socketDir;
146 private final ExecutorService executors;
147 private final Process registryProcess;
148 private final CompletableFuture<AFRegistry> registryFuture;
149 private final AtomicBoolean markedShutdown = new AtomicBoolean(false);
150 private final String prefix;
151 private final OutputBridge bridgeOut;
152 private final OutputBridge bridgeErr;
153
154 SpawnedRegistryAccess(String id) throws IOException {
155 this(id, AFUNIXNaming.getDefaultSocketDirectory());
156 }
157
158 SpawnedRegistryAccess(String id, File socketDir) throws IOException {
159 this.socketDir = socketDir;
160 this.executors = Executors.newCachedThreadPool();
161 this.registryFuture = new CompletableFuture<>();
162 this.registryProcess = launchRegistryProcess();
163
164 long pid;
165 try {
166 pid = registryProcess.pid();
167 } catch (UnsupportedOperationException e) {
168 pid = -1;
169 }
170 this.prefix = "(" + id + (pid != -1 ? (" " + registryProcess.pid()) : "") + ") ";
171
172 this.bridgeOut = new OutputBridge(registryProcess, ProcessStream.STDOUT, prefix);
173 this.bridgeErr = new OutputBridge(registryProcess, ProcessStream.STDERR, prefix);
174
175 watchProcessAsync();
176 asyncGetRegistry();
177 }
178
179 void shutdown() {
180 markedShutdown.set(true);
181 executors.shutdownNow();
182 }
183
184 int shutdownAndWait() throws InterruptedException {
185 return shutdownAndWait(false);
186 }
187
188 int shutdownAndWait(boolean destroy) throws InterruptedException {
189 shutdown();
190 if (destroy) {
191 registryProcess.destroy();
192 }
193 return registryProcess.waitFor();
194 }
195
196 private boolean isShutdown() {
197 return markedShutdown.get() || executors.isShutdown();
198 }
199
200 public AFRegistry getRegistry() throws InterruptedException, ExecutionException {
201 return registryFuture.get();
202 }
203
204 @Override
205 public void close() throws Exception {
206 shutdown();
207
208 registryProcess.destroyForcibly();
209 }
210
211 private Process launchRegistryProcess() throws IOException {
212 return new ForkedVM() {
213 @Override
214 protected void onJavaMainClass(String arg) {
215 super.onJavaOption("-Drmitest.junixsocket.socket-dir=" + socketDir.getPath());
216 super.onJavaOption("-Drmitest.junixsocket.create-registry=true");
217 super.onJavaOption("-Drmitest.junixsocket.export-hello=true");
218 super.onJavaOption("-Drmitest.junixsocket.export-hello.delay="
219 + exportHelloDelayMillis());
220 super.onJavaOption("-Drmitest.junixsocket.remote-shutdown.allowed="
221 + remoteShutdownAllowed());
222 super.onJavaOption("-Drmitest.junixsocket.shutdown-after.secs=" + shutdownAfterSecs());
223 super.onJavaMainClass(TestRegistryServer.class.getName());
224 }
225
226 @Override
227 protected void onArguments(List<String> args) {
228 super.onArguments(Collections.emptyList());
229 }
230 }.fork();
231 }
232
233 protected int shutdownAfterSecs() {
234 return -1;
235 }
236
237 private void watchProcessAsync() {
238 executors.submit(() -> {
239 try {
240 registryProcess.waitFor();
241 } catch (InterruptedException e) {
242 if (!markedShutdown.get()) {
243 registryFuture.completeExceptionally(e);
244 }
245 return;
246 }
247 if (!markedShutdown.get() && !registryProcess.isAlive()) {
248 registryFuture.completeExceptionally(new Exception(
249 "The spawned VM has terminated with RC=" + registryProcess.exitValue()));
250 }
251 });
252 executors.submit(bridgeOut);
253 executors.submit(bridgeErr);
254 }
255
256 private void asyncGetRegistry() {
257 executors.submit(() -> {
258 try {
259 AFNaming naming = getNamingInstance();
260 AFRegistry registry = naming.getRegistry(30, TimeUnit.SECONDS);
261 registryFuture.complete(registry);
262 } catch (RuntimeException | IOException e) {
263 if (!isShutdown()) {
264 registryFuture.completeExceptionally(e);
265 }
266 }
267 });
268 }
269
270 protected AFNaming getNamingInstance() throws IOException {
271 return AFUNIXNaming.getInstance(socketDir);
272 }
273
274 protected int exportHelloDelayMillis() {
275 return 0;
276 }
277
278 protected boolean remoteShutdownAllowed() {
279 return true;
280 }
281 }
282
283 private File tempSocketDir() throws IOException {
284 File socketDir = File.createTempFile("jux", "");
285 assumeTrue(countRMIFiles(socketDir) == 0,
286 "Test cannot be performed: *.rmi files exist in directory: " + socketDir);
287 assertTrue(socketDir.delete());
288 assertTrue(socketDir.mkdir());
289 return socketDir;
290 }
291
292 private int countRMIFiles(File dir) {
293 File[] files = dir.listFiles((d, name) -> name.endsWith(".rmi"));
294 return files == null ? 0 : files.length;
295 }
296 }