-
Notifications
You must be signed in to change notification settings - Fork 337
Expand file tree
/
Copy pathTomcatServer.groovy
More file actions
174 lines (155 loc) · 5.41 KB
/
TomcatServer.groovy
File metadata and controls
174 lines (155 loc) · 5.41 KB
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
import com.google.common.io.Files
import datadog.trace.agent.test.base.WebsocketServer
import datadog.trace.api.Config
import datadog.trace.api.ProcessTags
import datadog.trace.util.TraceUtils
import jakarta.servlet.ServletContextEvent
import jakarta.servlet.ServletContextListener
import jakarta.websocket.Session
import jakarta.websocket.server.ServerContainer
import org.apache.catalina.Context
import org.apache.catalina.core.StandardHost
import org.apache.catalina.startup.Tomcat
import org.apache.tomcat.JarScanFilter
import org.apache.tomcat.JarScanType
import org.apache.tomcat.websocket.server.WsSci
import java.nio.ByteBuffer
class TomcatServer implements WebsocketServer {
def port = 0
final Tomcat server
final String context
final boolean dispatch
volatile Session activeSession
final boolean wsAsyncSend
TomcatServer(String context, boolean dispatch, Closure setupServlets, Closure setupWebsockets, boolean wsAsyncSend = false) {
this.context = context
this.dispatch = dispatch
this.wsAsyncSend = wsAsyncSend
server = new Tomcat()
def baseDir = Files.createTempDir()
baseDir.deleteOnExit()
server.basedir = baseDir.absolutePath
server.port = 0 // select random open port
server.connector.enableLookups = true // get localhost instead of 127.0.0.1
final File applicationDir = new File(baseDir, "/webapps/ROOT")
if (!applicationDir.exists()) {
applicationDir.mkdirs()
applicationDir.deleteOnExit()
}
Context servletContext = server.addWebapp("/$context", applicationDir.getAbsolutePath())
servletContext.allowCasualMultipartParsing = true
// Speed up startup by disabling jar scanning:
servletContext.jarScanner.jarScanFilter = new JarScanFilter() {
@Override
boolean check(JarScanType jarScanType, String jarName) {
return false
}
}
setupServlets(servletContext)
servletContext.addServletContainerInitializer(new WsSci(), null)
def listeners = new ArrayList(Arrays.asList(servletContext.getApplicationLifecycleListeners()))
listeners.add(new EndpointDeployer(setupWebsockets))
servletContext.setApplicationLifecycleListeners(listeners.toArray())
(server.host as StandardHost).errorReportValveClass = TomcatServletTest.ErrorHandlerValve.name
}
@Override
void start() {
server.start()
port = server.service.findConnectors()[0].localPort
assert port > 0
if (Config.get().isExperimentalPropagateProcessTagsEnabled()) {
server.getEngine().setName("tomcat")
def serverName = TraceUtils.normalizeTag(server.getEngine().getName())
assert ProcessTags.getTagsAsStringList().containsAll(["server.type:tomcat", "server.name:" + serverName])
} else {
assert ProcessTags.getTagsAsStringList() == null
}
}
@Override
void stop() {
Thread.start {
sleep 50
// tomcat doesn't seem to interrupt accept() on stop()
// so connect to force the loop to continue
def sock = new Socket('localhost', port)
sock.close()
}
server.stop()
server.destroy()
}
@Override
URI address() {
if (dispatch) {
return new URI("http://localhost:$port/$context/dispatch/")
}
return new URI("http://localhost:$port/$context/")
}
@Override
String toString() {
return this.class.name
}
@Override
void serverSendText(String[] messages) {
if (wsAsyncSend && messages.length == 1) { // async does not support partial write
WsEndpoint.activeSession.getAsyncRemote().sendText(messages[0])
} else {
if (messages.length == 1) {
WsEndpoint.activeSession.getBasicRemote().sendText(messages[0])
} else {
def remoteEndpoint = WsEndpoint.activeSession.getBasicRemote()
for (int i = 0; i < messages.length; i++) {
remoteEndpoint.sendText(messages[i], i == messages.length - 1)
}
}
}
}
@Override
void serverSendBinary(byte[][] binaries) {
if (wsAsyncSend && binaries.length == 1) { // async does not support partial write
WsEndpoint.activeSession.getAsyncRemote().sendBinary(ByteBuffer.wrap(binaries[0]))
} else {
if (binaries.length == 1) {
WsEndpoint.activeSession.getBasicRemote().sendBinary(ByteBuffer.wrap(binaries[0]))
} else {
try (def stream = WsEndpoint.activeSession.getBasicRemote().getSendStream()) {
binaries.each { stream.write(it) }
}
}
}
}
@Override
synchronized void awaitConnected() {
synchronized (WsEndpoint) {
try {
while (WsEndpoint.activeSession == null) {
WsEndpoint.wait()
}
} catch (InterruptedException _) {
Thread.currentThread().interrupt()
}
}
}
@Override
void serverClose() {
WsEndpoint.activeSession.close()
WsEndpoint.activeSession = null
}
@Override
void setMaxPayloadSize(int size) {
WsEndpoint.activeSession.setMaxTextMessageBufferSize(size)
WsEndpoint.activeSession.setMaxBinaryMessageBufferSize(size)
}
static class EndpointDeployer implements ServletContextListener {
final Closure wsDeployCallback
EndpointDeployer(Closure wsDeployCallback) {
this.wsDeployCallback = wsDeployCallback
}
@Override
void contextInitialized(ServletContextEvent sce) {
wsDeployCallback.call((ServerContainer) sce.getServletContext().getAttribute(ServerContainer.name))
}
@Override
void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
}