-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
ServletServerBuilder.java
295 lines (257 loc) · 9.31 KB
/
ServletServerBuilder.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
/*
* Copyright 2018 The gRPC 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
*
* http://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.grpc.servlet;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static io.grpc.internal.GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.ListenableFuture;
import io.grpc.Attributes;
import io.grpc.ExperimentalApi;
import io.grpc.ForwardingServerBuilder;
import io.grpc.Internal;
import io.grpc.InternalChannelz.SocketStats;
import io.grpc.InternalInstrumented;
import io.grpc.InternalLogId;
import io.grpc.Metadata;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.ServerInterceptor;
import io.grpc.ServerStreamTracer;
import io.grpc.Status;
import io.grpc.internal.GrpcUtil;
import io.grpc.internal.InternalServer;
import io.grpc.internal.ServerImplBuilder;
import io.grpc.internal.ServerListener;
import io.grpc.internal.ServerStream;
import io.grpc.internal.ServerTransport;
import io.grpc.internal.ServerTransportListener;
import io.grpc.internal.SharedResourceHolder;
import java.io.File;
import java.io.IOException;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
/**
* Builder to build a gRPC server that can run as a servlet. This is for advanced custom settings.
* Normally, users should consider extending the out-of-box {@link GrpcServlet} directly instead.
*
* <p>The API is experimental. The authors would like to know more about the real usecases. Users
* are welcome to provide feedback by commenting on
* <a href=https://github.com/grpc/grpc-java/issues/5066>the tracking issue</a>.
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/5066")
@NotThreadSafe
public final class ServletServerBuilder extends ForwardingServerBuilder<ServletServerBuilder> {
List<? extends ServerStreamTracer.Factory> streamTracerFactories;
int maxInboundMessageSize = DEFAULT_MAX_MESSAGE_SIZE;
private final ServerImplBuilder serverImplBuilder;
private ScheduledExecutorService scheduler;
private boolean internalCaller;
private boolean usingCustomScheduler;
private InternalServerImpl internalServer;
private final List<ServerInterceptor> interceptors = new ArrayList<>();
private boolean forceTrailers;
public ServletServerBuilder() {
serverImplBuilder = new ServerImplBuilder(this::buildTransportServers);
}
/**
* Builds a gRPC server that can run as a servlet.
*
* <p>The returned server will not be started or bound to a port.
*
* <p>Users should not call this method directly. Instead users should call
* {@link #buildServletAdapter()} which internally will call {@code build()} and {@code start()}
* appropriately.
*
* @throws IllegalStateException if this method is called by users directly
*/
@Override
public Server build() {
checkState(internalCaller, "build() method should not be called directly by an application");
return super.build();
}
/**
* Creates a {@link ServletAdapter}.
*/
public ServletAdapter buildServletAdapter() {
return new ServletAdapter(buildAndStart(), streamTracerFactories, maxInboundMessageSize);
}
private ServerTransportListener buildAndStart() {
interceptors.forEach(serverImplBuilder::intercept);
if (forceTrailers) {
serverImplBuilder.intercept(new ForceTrailersServerInterceptor());
}
Server server;
try {
internalCaller = true;
server = build().start();
} catch (IOException e) {
// actually this should never happen
throw new RuntimeException(e);
} finally {
internalCaller = false;
}
if (!usingCustomScheduler) {
scheduler = SharedResourceHolder.get(GrpcUtil.TIMER_SERVICE);
}
// Create only one "transport" for all requests because it has no knowledge of which request is
// associated with which client socket. This "transport" does not do socket connection, the
// container does.
ServerTransportImpl serverTransport = new ServerTransportImpl(scheduler);
ServerTransportListener delegate =
internalServer.serverListener.transportCreated(serverTransport);
return new ServerTransportListener() {
@Override
public void streamCreated(ServerStream stream, String method, Metadata headers) {
delegate.streamCreated(stream, method, headers);
}
@Override
public Attributes transportReady(Attributes attributes) {
return delegate.transportReady(attributes);
}
@Override
public void transportTerminated() {
server.shutdown();
delegate.transportTerminated();
if (!usingCustomScheduler) {
SharedResourceHolder.release(GrpcUtil.TIMER_SERVICE, scheduler);
}
}
};
}
@VisibleForTesting
InternalServer buildTransportServers(
List<? extends ServerStreamTracer.Factory> streamTracerFactories) {
checkNotNull(streamTracerFactories, "streamTracerFactories");
this.streamTracerFactories = streamTracerFactories;
internalServer = new InternalServerImpl();
return internalServer;
}
@Internal
@Override
protected ServerBuilder<?> delegate() {
return serverImplBuilder;
}
/**
* Throws {@code UnsupportedOperationException}. TLS should be configured by the servlet
* container.
*/
@Override
public ServletServerBuilder useTransportSecurity(File certChain, File privateKey) {
throw new UnsupportedOperationException("TLS should be configured by the servlet container");
}
@Override
public ServletServerBuilder maxInboundMessageSize(int bytes) {
checkArgument(bytes >= 0, "bytes must be >= 0");
maxInboundMessageSize = bytes;
return this;
}
/**
* Some servlet containers don't support sending trailers only (Tomcat).
* They send an empty data frame with an end_stream flag.
* This is not supported by gRPC as is expects end_stream flag in trailer or trailer-only frame
* To avoid this empty data frame, force the servlet container to either
* - send a header frame, an empty data frame and a trailer frame with end_stream (Tomcat)
* - send a header frame and a trailer frame with end_stream (Jetty, Undertow)
*/
public ServletServerBuilder forceTrailers(boolean forceTrailers) {
this.forceTrailers = forceTrailers;
return this;
}
@Override
public ServletServerBuilder intercept(ServerInterceptor interceptor) {
interceptors.add(checkNotNull(interceptor, "interceptor"));
return this;
}
/**
* Provides a custom scheduled executor service to the server builder.
*
* @return this
*/
public ServletServerBuilder scheduledExecutorService(ScheduledExecutorService scheduler) {
this.scheduler = checkNotNull(scheduler, "scheduler");
usingCustomScheduler = true;
return this;
}
private static final class InternalServerImpl implements InternalServer {
ServerListener serverListener;
InternalServerImpl() {}
@Override
public void start(ServerListener listener) {
serverListener = listener;
}
@Override
public void shutdown() {
if (serverListener != null) {
serverListener.serverShutdown();
}
}
@Override
public SocketAddress getListenSocketAddress() {
return new SocketAddress() {
@Override
public String toString() {
return "ServletServer";
}
};
}
@Override
public InternalInstrumented<SocketStats> getListenSocketStats() {
// sockets are managed by the servlet container, grpc is ignorant of that
return null;
}
@Override
public List<? extends SocketAddress> getListenSocketAddresses() {
return Collections.emptyList();
}
@Nullable
@Override
public List<InternalInstrumented<SocketStats>> getListenSocketStatsList() {
return null;
}
}
@VisibleForTesting
static final class ServerTransportImpl implements ServerTransport {
private final InternalLogId logId = InternalLogId.allocate(ServerTransportImpl.class, null);
private final ScheduledExecutorService scheduler;
ServerTransportImpl(ScheduledExecutorService scheduler) {
this.scheduler = checkNotNull(scheduler, "scheduler");
}
@Override
public void shutdown() {}
@Override
public void shutdownNow(Status reason) {}
@Override
public ScheduledExecutorService getScheduledExecutorService() {
return scheduler;
}
@Override
public ListenableFuture<SocketStats> getStats() {
// does not support instrumentation
return null;
}
@Override
public InternalLogId getLogId() {
return logId;
}
}
}