Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a server idle timeout #453

Merged
merged 1 commit into from
Nov 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
projectVersion=2.2.1-SNAPSHOT
projectVersion=2.3.0-SNAPSHOT
projectGroup=io.micronaut.testresources

title=Micronaut Test Resources
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,18 @@ public final class ServerSettings {
private final int port;
private final String accessToken;
private final Integer clientTimeout;
private final Integer idleTimeoutMinutes;

@Deprecated
public ServerSettings(int port, String accessToken, Integer clientTimeout) {
this(port, accessToken, clientTimeout, null);
}

public ServerSettings(int port, String accessToken, Integer clientTimeout, Integer idleTimeoutMinutes) {
this.port = port;
this.accessToken = accessToken;
this.clientTimeout = clientTimeout;
this.idleTimeoutMinutes = idleTimeoutMinutes;
}

public int getPort() {
Expand All @@ -44,6 +51,10 @@ public Optional<Integer> getClientTimeout() {
return Optional.ofNullable(clientTimeout);
}

public Optional<Integer> getIdleTimeoutMinutes() {
return Optional.ofNullable(idleTimeoutMinutes);
}

@Override
public boolean equals(Object o) {
if (this == o) {
Expand All @@ -61,14 +72,18 @@ public boolean equals(Object o) {
if (!Objects.equals(accessToken, that.accessToken)) {
return false;
}
return Objects.equals(clientTimeout, that.clientTimeout);
if (!Objects.equals(clientTimeout, that.clientTimeout)) {
return false;
}
return Objects.equals(idleTimeoutMinutes, that.idleTimeoutMinutes);
}

@Override
public int hashCode() {
int result = port;
result = 31 * result + (accessToken != null ? accessToken.hashCode() : 0);
result = 31 * result + (clientTimeout != null ? clientTimeout.hashCode() : 0);
result = 31 * result + (idleTimeoutMinutes != null ? idleTimeoutMinutes.hashCode() : 0);
return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ public class ServerUtils {
private static final String SERVER_ACCESS_TOKEN_MICRONAUT_PROPERTY = "server.access-token";
private static final String SERVER_ACCESS_TOKEN = "server.access.token";
private static final String SERVER_CLIENT_READ_TIMEOUT = "server.client.read.timeout";
private static final String SERVER_IDLE_TIMEOUT_MINUTES = "server.idle.timeout.minutes";
private static final String SERVER_ENTRY_POINT = "io.micronaut.testresources.server.TestResourcesService";
private static final String MICRONAUT_SERVER_PORT = "micronaut.server.port";
private static final String JMX_SYSTEM_PROPERTY = "com.sun.management.jmxremote";
Expand Down Expand Up @@ -106,6 +107,9 @@ public static Optional<ServerSettings> readServerSettings(Path settingsDirectory
new URI(props.getProperty(SERVER_URI)).getPort(),
props.getProperty(SERVER_ACCESS_TOKEN),
Optional.ofNullable(props.getProperty(SERVER_CLIENT_READ_TIMEOUT))
.map(Integer::parseInt)
.orElse(null),
Optional.ofNullable(props.getProperty(SERVER_IDLE_TIMEOUT_MINUTES))
.map(Integer::parseInt)
.orElse(null)
));
Expand Down Expand Up @@ -144,6 +148,7 @@ public static boolean isServerStarted(int port) {
* @param cdsDirectory the CDS directory. If not null, class data sharing will be enabled
* @param serverClasspath the server classpath
* @param clientTimeoutMs the client timeout
* @param serverIdleTimeoutMinutes the server idle timeout
* @param serverFactory the server factory, responsible for forking a process
* @return the server settings once the server is started
* @throws IOException if an error occurs
Expand All @@ -155,6 +160,7 @@ public static ServerSettings startOrConnectToExistingServer(Integer explicitPort
Path cdsDirectory,
Collection<File> serverClasspath,
Integer clientTimeoutMs,
Integer serverIdleTimeoutMinutes,
ServerFactory serverFactory) throws IOException {
Optional<ServerSettings> maybeServerSettings = readServerSettings(serverSettingsDirectory);
if (maybeServerSettings.isPresent()) {
Expand All @@ -175,7 +181,7 @@ public static ServerSettings startOrConnectToExistingServer(Integer explicitPort
}

Files.createDirectories(portFilePath.getParent());
startAndWait(serverFactory, explicitPort, portFilePath, accessToken, serverClasspath, cdsDirectory);
startAndWait(serverFactory, explicitPort, serverIdleTimeoutMinutes, portFilePath, accessToken, serverClasspath, cdsDirectory);
int port;
if (explicitPort == null) {
List<String> lines = Files.readAllLines(portFilePath);
Expand All @@ -197,7 +203,7 @@ public static ServerSettings startOrConnectToExistingServer(Integer explicitPort
} else {
port = explicitPort;
}
ServerSettings settings = new ServerSettings(port, accessToken, clientTimeoutMs);
ServerSettings settings = new ServerSettings(port, accessToken, clientTimeoutMs, serverIdleTimeoutMinutes);
writeServerSettings(serverSettingsDirectory, settings);
return settings;
}
Expand All @@ -212,6 +218,7 @@ public static ServerSettings startOrConnectToExistingServer(Integer explicitPort
* @param accessToken the access token, if any
* @param serverClasspath the server classpath
* @param clientTimeoutMs the client timeout
* @param serverIdleTimeoutMinutes the server idle timeout
* @param serverFactory the server factory, responsible for forking a process
* @return the server settings once the server is started
* @throws IOException if an error occurs
Expand All @@ -222,6 +229,7 @@ public static ServerSettings startOrConnectToExistingServer(Integer explicitPort
String accessToken,
Collection<File> serverClasspath,
Integer clientTimeoutMs,
Integer serverIdleTimeoutMinutes,
ServerFactory serverFactory) throws IOException {
return startOrConnectToExistingServer(
explicitPort,
Expand All @@ -231,6 +239,7 @@ public static ServerSettings startOrConnectToExistingServer(Integer explicitPort
null,
serverClasspath,
clientTimeoutMs,
serverIdleTimeoutMinutes,
serverFactory
);
}
Expand Down Expand Up @@ -283,16 +292,17 @@ public static Path getDefaultSharedSettingsPath(String namespace) {

private static void startAndWait(ServerFactory serverFactory,
Integer explicitPort,
Integer idleTimeoutMinutes,
Path portFilePath,
String accessToken,
Collection<File> serverClasspath,
Path cdsDirectory) throws IOException {
ProcessParameters processParameters = createProcessParameters(explicitPort, portFilePath, accessToken, serverClasspath, cdsDirectory);
ProcessParameters processParameters = createProcessParameters(explicitPort, idleTimeoutMinutes, portFilePath, accessToken, serverClasspath, cdsDirectory);
serverFactory.startServer(processParameters);
// If the call is a CDS dump, we need to perform a second invocation
// which doesn't dump
if (processParameters.isCDSDumpInvocation()) {
startAndWait(serverFactory, explicitPort, portFilePath, accessToken, serverClasspath, cdsDirectory);
startAndWait(serverFactory, explicitPort, idleTimeoutMinutes, portFilePath, accessToken, serverClasspath, cdsDirectory);
return;
}
if (explicitPort != null) {
Expand All @@ -307,8 +317,8 @@ private static void startAndWait(ServerFactory serverFactory,
}
}

private static ProcessParameters createProcessParameters(Integer explicitPort, Path portFilePath, String accessToken, Collection<File> serverClasspath, Path cdsDirectory) {
return new DefaultProcessParameters(explicitPort, accessToken, cdsDirectory, serverClasspath, portFilePath);
private static ProcessParameters createProcessParameters(Integer explicitPort, Integer serverIdleTimeoutMinutes, Path portFilePath, String accessToken, Collection<File> serverClasspath, Path cdsDirectory) {
return new DefaultProcessParameters(explicitPort, serverIdleTimeoutMinutes, accessToken, cdsDirectory, serverClasspath, portFilePath);

}

Expand Down Expand Up @@ -362,12 +372,19 @@ private static class DefaultProcessParameters implements ProcessParameters {
private final Path cdsDirectory;
private final Collection<File> serverClasspath;
private final Path portFilePath;
private final Integer idleTimeoutMinutes;
private List<String> jvmArgs;
private List<File> classpath;
private File flatDirsJar;

public DefaultProcessParameters(Integer explicitPort, String accessToken, Path cdsDirectory, Collection<File> serverClasspath, Path portFilePath) {
public DefaultProcessParameters(Integer explicitPort,
Integer idleTimeoutMinutes,
String accessToken,
Path cdsDirectory,
Collection<File> serverClasspath,
Path portFilePath) {
this.explicitPort = explicitPort;
this.idleTimeoutMinutes = idleTimeoutMinutes;
this.accessToken = accessToken;
this.cdsDirectory = cdsDirectory;
this.serverClasspath = serverClasspath;
Expand Down Expand Up @@ -396,6 +413,9 @@ public Map<String, String> getSystemProperties() {
if (accessToken != null) {
systemProperties.put(SERVER_ACCESS_TOKEN_MICRONAUT_PROPERTY, accessToken);
}
if (idleTimeoutMinutes != null) {
systemProperties.put(SERVER_IDLE_TIMEOUT_MINUTES, String.valueOf(idleTimeoutMinutes));
}
return systemProperties;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class ServerUtilsTest extends Specification {
embeddedServer.start()

when:
def settings = ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, token, classpath, timeout, factory)
def settings = ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, token, classpath, timeout, null, factory)

then:
1 * factory.startServer(_) >> { ServerUtils.ProcessParameters params ->
Expand Down Expand Up @@ -98,17 +98,17 @@ class ServerUtilsTest extends Specification {
def applicationContext = ApplicationContext.builder().start()
def embeddedServer = applicationContext.getBean(EmbeddedServer)
embeddedServer.start()
ServerUtils.writeServerSettings(settingsDir, new ServerSettings(embeddedServer.port, null, null))
ServerUtils.writeServerSettings(settingsDir, new ServerSettings(embeddedServer.port, null, null, null))

when: "no explicit port"
ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, null, [], null, factory)
ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, null, [], null, null, factory)

then:
0 * factory.startServer(_)
0 * factory.waitFor(_)

when: "explicit port"
ServerUtils.startOrConnectToExistingServer(embeddedServer.port, portFile, settingsDir, null, [], null, factory)
ServerUtils.startOrConnectToExistingServer(embeddedServer.port, portFile, settingsDir, null, [], null, null, factory)

then:
0 * factory.startServer(_)
Expand Down Expand Up @@ -137,7 +137,7 @@ class ServerUtilsTest extends Specification {
embeddedServer.start()

when: "first call with CDS support enabled"
ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, null, cdsDir, [cdsClasspathDir.toFile()], null, factory)
ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, null, cdsDir, [cdsClasspathDir.toFile()], null, null, factory)

then:
1 * factory.startServer(_) >> { ServerUtils.ProcessParameters params ->
Expand All @@ -154,7 +154,7 @@ class ServerUtilsTest extends Specification {
settingsDir.toFile().deleteDir()

when: "second call dumps CDS then starts server"
ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, null, cdsDir, [cdsClasspathDir.toFile()], null, factory)
ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, null, cdsDir, [cdsClasspathDir.toFile()], null, null, factory)

then:
1 * factory.startServer(_) >> { ServerUtils.ProcessParameters params ->
Expand All @@ -177,7 +177,7 @@ class ServerUtilsTest extends Specification {
settingsDir.toFile().deleteDir()

when: "third call starts server with CDS"
ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, null, cdsDir, [cdsClasspathDir.toFile()], null, factory)
ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, null, cdsDir, [cdsClasspathDir.toFile()], null, null, factory)

then:
1 * factory.startServer(_) >> { ServerUtils.ProcessParameters params ->
Expand All @@ -193,7 +193,7 @@ class ServerUtilsTest extends Specification {
settingsDir.toFile().deleteDir()

when: "removes CDS files if classpath changes"
ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, null, cdsDir, [], null, factory)
ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, null, cdsDir, [], null, null, factory)

then:
1 * factory.startServer(_) >> { ServerUtils.ProcessParameters params ->
Expand All @@ -220,7 +220,7 @@ class ServerUtilsTest extends Specification {
embeddedServer.start()

when:
def settings = ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, null, [], null, factory)
def settings = ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, null, [], null, null, factory)

then:
1 * factory.startServer(_) >> { ServerUtils.ProcessParameters params ->
Expand All @@ -247,7 +247,7 @@ class ServerUtilsTest extends Specification {
embeddedServer.start()

when:
def settings = ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, null, [], null, factory)
def settings = ServerUtils.startOrConnectToExistingServer(null, portFile, settingsDir, null, [], null, null, factory)

then:
1 * factory.startServer(_) >> { ServerUtils.ProcessParameters params ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,16 @@ default List<String> getResolvableProperties() {

/**
* Closes all test resources.
* @return true if the operation was successful
*/
@Get("/close/all")
boolean closeAll();

/**
* Closes a test resource scope
* @param id the scope id
* @return true if the operation was successful
*/
@Get("/close/{id}")
boolean closeScope(@Nullable String id);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright 2017-2021 original authors
*
* Licensed 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
*
* https://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.
*/
package io.micronaut.testresources.client;

import io.micronaut.context.ApplicationContext;
import io.micronaut.scheduling.annotation.Scheduled;
import jakarta.inject.Singleton;

/**
* An application component which sends periodic keep alive requests to the server.
*/
@Singleton
public class TestResourcesKeepAlive {
/**
* Sends periodic keep alive requests to the server.
* @param applicationContext the application context
*/
@Scheduled(fixedRate = "1m")
public void keepAlive(ApplicationContext applicationContext) {
var client = TestResourcesClientFactory.extractFrom(applicationContext);
if (client != null) {
// Call any method to keep the service alive
client.getResolvableProperties();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright 2017-2021 original authors
*
* Licensed 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
*
* https://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.
*/
package io.micronaut.testresources.server;

import io.micronaut.aop.InterceptorBean;
import io.micronaut.aop.MethodInterceptor;
import io.micronaut.aop.MethodInvocationContext;
import io.micronaut.context.annotation.Value;
import io.micronaut.core.annotation.Nullable;
import jakarta.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* The expiry manager will handle pings from the client to keep the server alive.
*/
@Singleton
@InterceptorBean(Ping.class)
public final class ExpiryManager implements MethodInterceptor<Object, Object> {
private static final Logger LOGGER = LoggerFactory.getLogger(ExpiryManager.class);

private static final long MS_IN_ONE_MINUTE = 60_000;
private final long timeoutMs;

private long lastAccess;

public ExpiryManager(@Value("${server.idle.timeout.minutes:60}") int keepAliveMinutes) {
this.timeoutMs = keepAliveMinutes * MS_IN_ONE_MINUTE;
ping();
LOGGER.info("Test resources server will automatically be shutdown if it doesn't receive requests for {} minutes", keepAliveMinutes);
}

private void ping() {
this.lastAccess = System.currentTimeMillis();
}

public boolean isExpired() {
return System.currentTimeMillis() - lastAccess > timeoutMs;
}

@Override
public @Nullable Object intercept(MethodInvocationContext<Object, Object> context) {
ping();
return context.proceed();
}
}
Loading
Loading