Skip to content

Commit 7618b2b

Browse files
committed
[java] Stopping sessions when the Node is gracefully shutdown
A manager for shutdown hooks was added, so the http client is closed after all shutdown hooks that potentially need it are executed. This will help to stop running Docker containers when the Node or Standalone are gracefully shutdown and sessions are still running.
1 parent f3b307c commit 7618b2b

File tree

4 files changed

+117
-14
lines changed

4 files changed

+117
-14
lines changed

java/src/org/openqa/selenium/grid/node/httpd/NodeServer.java

+10-9
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,14 @@
1717

1818
package org.openqa.selenium.grid.node.httpd;
1919

20+
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
21+
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
22+
import static org.openqa.selenium.grid.config.StandardGridRoles.EVENT_BUS_ROLE;
23+
import static org.openqa.selenium.grid.config.StandardGridRoles.HTTPD_ROLE;
24+
import static org.openqa.selenium.grid.config.StandardGridRoles.NODE_ROLE;
25+
import static org.openqa.selenium.grid.data.Availability.DOWN;
26+
import static org.openqa.selenium.remote.http.Route.get;
27+
2028
import com.google.auto.service.AutoService;
2129
import com.google.common.collect.ImmutableSet;
2230
import com.google.common.net.MediaType;
@@ -46,6 +54,7 @@
4654
import org.openqa.selenium.grid.server.NetworkOptions;
4755
import org.openqa.selenium.grid.server.Server;
4856
import org.openqa.selenium.internal.Require;
57+
import org.openqa.selenium.internal.ShutdownHooks;
4958
import org.openqa.selenium.netty.server.NettyServer;
5059
import org.openqa.selenium.remote.http.Contents;
5160
import org.openqa.selenium.remote.http.HttpClient;
@@ -60,14 +69,6 @@
6069
import java.util.concurrent.atomic.AtomicBoolean;
6170
import java.util.logging.Logger;
6271

63-
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
64-
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
65-
import static org.openqa.selenium.grid.config.StandardGridRoles.EVENT_BUS_ROLE;
66-
import static org.openqa.selenium.grid.config.StandardGridRoles.HTTPD_ROLE;
67-
import static org.openqa.selenium.grid.config.StandardGridRoles.NODE_ROLE;
68-
import static org.openqa.selenium.grid.data.Availability.DOWN;
69-
import static org.openqa.selenium.remote.http.Route.get;
70-
7172
@AutoService(CliCommand.class)
7273
public class NodeServer extends TemplateGridServerCommand {
7374

@@ -226,7 +227,7 @@ public NettyServer start() {
226227
protected void execute(Config config) {
227228
Require.nonNull("Config", config);
228229

229-
Runtime.getRuntime().addShutdownHook(shutdownHook);
230+
ShutdownHooks.add(shutdownHook);
230231
Server<?> server = asServer(config).start();
231232

232233
BuildInfo info = new BuildInfo();

java/src/org/openqa/selenium/grid/node/local/LocalNode.java

+15-4
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,10 @@
6666
import org.openqa.selenium.grid.node.SessionFactory;
6767
import org.openqa.selenium.grid.node.config.NodeOptions;
6868
import org.openqa.selenium.grid.security.Secret;
69+
import org.openqa.selenium.internal.Debug;
6970
import org.openqa.selenium.internal.Either;
7071
import org.openqa.selenium.internal.Require;
72+
import org.openqa.selenium.internal.ShutdownHooks;
7173
import org.openqa.selenium.io.TemporaryFilesystem;
7274
import org.openqa.selenium.io.Zip;
7375
import org.openqa.selenium.json.Json;
@@ -141,16 +143,17 @@ private LocalNode(
141143
Require.nonNull("Registration secret", registrationSecret);
142144

143145
this.healthCheck = healthCheck == null ?
144-
() -> new HealthCheck.Result(
145-
isDraining() ? DRAINING : UP,
146-
String.format("%s is %s", uri, isDraining() ? "draining" : "up")) :
147-
healthCheck;
146+
() -> new HealthCheck.Result(
147+
isDraining() ? DRAINING : UP,
148+
String.format("%s is %s", uri, isDraining() ? "draining" : "up")) :
149+
healthCheck;
148150

149151
this.currentSessions = CacheBuilder.newBuilder()
150152
.expireAfterAccess(sessionTimeout)
151153
.ticker(ticker)
152154
.removalListener((RemovalListener<SessionId, SessionSlot>) notification -> {
153155
// Attempt to stop the session
156+
LOG.log(Debug.getDebugLogLevel(), "Stopping session %s", notification.getKey().toString());
154157
SessionSlot slot = notification.getValue();
155158
if (!slot.isAvailable()) {
156159
slot.stop();
@@ -185,6 +188,7 @@ private LocalNode(
185188
}
186189
}));
187190

191+
ShutdownHooks.add(new Thread(this::stopAllSessions));
188192
new JMXHelper().register(this);
189193
}
190194

@@ -438,6 +442,13 @@ public void stop(SessionId id) throws NoSuchSessionException {
438442
tempFileSystems.invalidate(id);
439443
}
440444

445+
private void stopAllSessions() {
446+
if (currentSessions.size() > 0) {
447+
LOG.info("Trying to stop all running sessions before shutting down...");
448+
currentSessions.invalidateAll();
449+
}
450+
}
451+
441452
private Session createExternalSession(ActiveSession other, URI externalUri,
442453
boolean isSupportingCdp) {
443454
Capabilities toUse = ImmutableCapabilities.copyOf(other.getCapabilities());
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
// Licensed to the Software Freedom Conservancy (SFC) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The SFC licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
package org.openqa.selenium.internal;
19+
20+
import java.util.Collection;
21+
import java.util.IdentityHashMap;
22+
23+
/**
24+
* A simple manager for shutdown hooks, with plenty of room for improvement.
25+
*/
26+
public class ShutdownHooks {
27+
28+
private static IdentityHashMap<Thread, Thread> defaultHooks;
29+
private static IdentityHashMap<Thread, Thread> atEndHooks;
30+
31+
static {
32+
defaultHooks = new IdentityHashMap<>();
33+
atEndHooks = new IdentityHashMap<>();
34+
Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHooks::runShutdownHooks));
35+
}
36+
37+
private ShutdownHooks() {
38+
// Utility class
39+
}
40+
41+
public static void add(Thread hook, HookExecutionStrategy strategy) {
42+
if (strategy.equals(HookExecutionStrategy.DEFAULT)) {
43+
defaultHooks.put(hook, hook);
44+
} else {
45+
atEndHooks.put(hook, hook);
46+
}
47+
}
48+
49+
public static void add(Thread hook) {
50+
add(hook, HookExecutionStrategy.DEFAULT);
51+
}
52+
53+
static void runShutdownHooks() {
54+
Collection<Thread> threads;
55+
synchronized (ShutdownHooks.class) {
56+
threads = defaultHooks.keySet();
57+
defaultHooks = null;
58+
}
59+
runHooks(threads);
60+
Collection<Thread> atEndThreads;
61+
synchronized (ShutdownHooks.class) {
62+
atEndThreads = atEndHooks.keySet();
63+
atEndHooks = null;
64+
}
65+
runHooks(atEndThreads);
66+
}
67+
68+
private static void runHooks(Collection<Thread> threads) {
69+
for (Thread hook : threads) {
70+
hook.start();
71+
}
72+
for (Thread hook : threads) {
73+
while (true) {
74+
try {
75+
hook.join();
76+
break;
77+
} catch (InterruptedException ignored) {
78+
}
79+
}
80+
}
81+
}
82+
83+
public enum HookExecutionStrategy {
84+
AT_END, // Hook will be executed after all DEFAULT ones are executed
85+
DEFAULT // Hook will be executed before all AT_END ones
86+
}
87+
88+
}

java/src/org/openqa/selenium/remote/http/netty/NettyClient.java

+4-1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717

1818
package org.openqa.selenium.remote.http.netty;
1919

20+
import static org.openqa.selenium.internal.ShutdownHooks.HookExecutionStrategy.AT_END;
21+
2022
import com.google.auto.service.AutoService;
2123

2224
import org.asynchttpclient.AsyncHttpClient;
@@ -27,6 +29,7 @@
2729
import org.openqa.selenium.Credentials;
2830
import org.openqa.selenium.UsernameAndPassword;
2931
import org.openqa.selenium.internal.Require;
32+
import org.openqa.selenium.internal.ShutdownHooks;
3033
import org.openqa.selenium.remote.http.ClientConfig;
3134
import org.openqa.selenium.remote.http.Filter;
3235
import org.openqa.selenium.remote.http.HttpClient;
@@ -71,7 +74,7 @@ private NettyClient(ClientConfig config) {
7174
this.handler = new NettyHttpHandler(config, client).with(config.filter());
7275
this.toWebSocket = NettyWebSocket.create(config, client);
7376
if (!addedHook.get()) {
74-
Runtime.getRuntime().addShutdownHook(new Thread(this::shutdownClient));
77+
ShutdownHooks.add(new Thread(this::shutdownClient), AT_END);
7578
addedHook.set(true);
7679
}
7780
}

0 commit comments

Comments
 (0)