-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathProxyService.java
More file actions
270 lines (240 loc) · 9.72 KB
/
ProxyService.java
File metadata and controls
270 lines (240 loc) · 9.72 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
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
/**
* Copyright (C) 2011-2021 Red Hat, Inc. (https://github.com/Commonjava/indy-sidecar)
*
* 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 org.commonjava.util.sidecar.services;
import io.quarkus.vertx.ConsumeEvent;
import io.smallrye.mutiny.Uni;
import io.vertx.core.MultiMap;
import io.vertx.core.VertxException;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.mutiny.core.buffer.Buffer;
import io.vertx.mutiny.ext.web.client.HttpResponse;
import org.apache.commons.io.IOUtils;
import org.commonjava.util.sidecar.config.ProxyConfiguration;
import org.commonjava.util.sidecar.interceptor.ExceptionHandler;
import org.commonjava.util.sidecar.interceptor.MetricsHandler;
import org.commonjava.util.sidecar.util.BufferStreamingOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static io.vertx.core.http.impl.HttpUtils.normalizePath;
import static javax.ws.rs.core.HttpHeaders.HOST;
import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.commonjava.o11yphant.metrics.RequestContextConstants.EXTERNAL_ID;
import static org.commonjava.o11yphant.metrics.RequestContextConstants.TRACE_ID;
import static org.commonjava.util.sidecar.services.ProxyConstants.EVENT_PROXY_CONFIG_CHANGE;
@ApplicationScoped
@ExceptionHandler
@MetricsHandler
public class ProxyService
{
public final static String HEADER_PROXY_TRACE_ID = "Proxy-Trace-Id";
private final Logger logger = LoggerFactory.getLogger( getClass() );
private final String PROXY_ORIGIN = "proxy-origin";
private long DEFAULT_TIMEOUT = TimeUnit.MINUTES.toMillis( 30 ); // default 30 minutes
private long DEFAULT_BACKOFF_MILLIS = Duration.ofSeconds( 5 ).toMillis();
private volatile long timeout;
@Inject
ProxyConfiguration proxyConfiguration;
@Inject
Classifier classifier;
@PostConstruct
void init()
{
timeout = readTimeout();
logger.debug( "Init, timeout: {}", timeout );
}
long readTimeout()
{
long t = DEFAULT_TIMEOUT;
String readTimeout = proxyConfiguration.getReadTimeout();
if ( isNotBlank( readTimeout ) )
{
try
{
t = Duration.parse( "pt" + readTimeout ).toMillis();
}
catch ( Exception e )
{
logger.error( "Failed to parse proxy.read-timeout, use default " + DEFAULT_TIMEOUT, e );
}
}
return t;
}
@ConsumeEvent( value = EVENT_PROXY_CONFIG_CHANGE )
void handleConfigChange( String message )
{
timeout = readTimeout();
logger.debug( "Handle event {}, refresh timeout: {}", EVENT_PROXY_CONFIG_CHANGE, timeout );
}
@GET
public Uni<Response> doHead( String path, HttpServerRequest request ) throws Exception
{
return normalizePathAnd( path, p -> classifier.classifyAnd( p, request,
(client, service) -> wrapAsyncCall( client.head( p )
.putHeaders( getHeaders( request ) )
.timeout( timeout )
.send() ) ), request );
}
@GET
public Uni<Response> doGet( String path, HttpServerRequest request ) throws Exception
{
return normalizePathAnd( path, p -> classifier.classifyAnd( p, request,
(client, service) -> wrapAsyncCall( client.get( p )
.putHeaders( getHeaders( request ) )
.timeout( timeout )
.send()) ), request );
}
@GET
public Uni<Response> doPost( String path, InputStream is, HttpServerRequest request ) throws Exception
{
Buffer buf = Buffer.buffer( IOUtils.toByteArray( is ) );
return normalizePathAnd( path, p -> classifier.classifyAnd( p, request,
(client, service) -> wrapAsyncCall( client.post( p )
.putHeaders( getHeaders( request ) )
.timeout( timeout )
.sendBuffer( buf ) ) ), request );
}
@GET
public Uni<Response> doPut( String path, InputStream is, HttpServerRequest request ) throws Exception
{
Buffer buf = Buffer.buffer( IOUtils.toByteArray( is ) );
return normalizePathAnd( path, p -> classifier.classifyAnd( p, request,
(client, service) -> wrapAsyncCall( client.put( p )
.putHeaders( getHeaders( request ) )
.timeout( timeout )
.sendBuffer( buf ) ) ), request );
}
@GET
public Uni<Response> doDelete( String path, HttpServerRequest request ) throws Exception
{
return normalizePathAnd( path, p -> classifier.classifyAnd( p, request,
(client, service) -> wrapAsyncCall( client.delete( p )
.putHeaders( getHeaders( request ) )
.timeout( timeout )
.send() ) ), request );
}
private Uni<Response> wrapAsyncCall( Uni<HttpResponse<Buffer>> asyncCall )
{
ProxyConfiguration.Retry retry = proxyConfiguration.getRetry();
Uni<Response> ret = asyncCall.onItem().transform( this::convertProxyResp );
if ( retry.count > 0 )
{
long backOff = retry.interval;
if ( retry.interval <= 0 )
{
backOff = DEFAULT_BACKOFF_MILLIS;
}
ret = ret.onFailure( t -> ( t instanceof IOException || t instanceof VertxException ) )
.retry()
.withBackOff( Duration.ofMillis( backOff ) )
.atMost( retry.count );
}
return ret.onFailure().recoverWithItem( this::handleProxyException );
}
/**
* Send status 500 with error message body.
* @param t error
*/
Response handleProxyException( Throwable t )
{
logger.error( "Proxy error", t );
return Response.status( INTERNAL_SERVER_ERROR ).entity( t + ". Caused by: " + t.getCause() ).build();
}
/**
* Read status and headers from proxy resp and set them to direct response.
* @param resp proxy resp
*/
private Response convertProxyResp( HttpResponse<Buffer> resp )
{
logger.debug( "Proxy resp: {} {}", resp.statusCode(), resp.statusMessage() );
logger.trace( "Raw resp headers:\n{}", resp.headers() );
Response.ResponseBuilder builder = Response.status( resp.statusCode(), resp.statusMessage() );
resp.headers().forEach( header -> {
if ( respHeaderAllowed( header ) )
{
builder.header( header.getKey(), header.getValue() );
}
} );
if ( resp.body() != null )
{
StreamingOutput so = new BufferStreamingOutput( resp );
builder.entity( so );
}
return builder.build();
}
/**
* Raw content-length/connection header breaks http2 protocol. It is safe to exclude them.
*/
private boolean respHeaderAllowed( Map.Entry<String, String> header )
{
String key = header.getKey();
return !( key.equalsIgnoreCase( "content-length" ) || key.equalsIgnoreCase( "connection" ) );
}
private io.vertx.mutiny.core.MultiMap getHeaders( HttpServerRequest request )
{
MultiMap headers = request.headers();
io.vertx.mutiny.core.MultiMap ret = io.vertx.mutiny.core.MultiMap.newInstance( headers )
.remove( HOST )
.add( TRACE_ID, getTraceId( headers ) );
try
{
URL url = new URL( request.absoluteURI() );
String protocol = url.getProtocol();
String authority = url.getAuthority();
ret.add( PROXY_ORIGIN, String.format( "%s://%s", protocol, authority ) );
}
catch ( MalformedURLException e )
{
logger.error( "Failed to parse URI", e );
}
logger.trace( "Req headers:\n{}", ret );
return ret;
}
/**
* Get 'trace-id'. If client specify an 'external-id', use it. Otherwise, use an generated uuid. Services under the hook
* should use the hereby created 'trace-id', rather than to generate their own.
*/
private String getTraceId( MultiMap headers )
{
String externalID = headers.get( EXTERNAL_ID );
return isNotBlank( externalID ) ? externalID : UUID.randomUUID().toString();
}
@FunctionalInterface
private interface Function<T, R>
{
R apply( T t ) throws Exception;
}
private Uni<Response> normalizePathAnd( String path, Function<String, Uni<Response>> action, HttpServerRequest request ) throws Exception
{
String traceId = UUID.randomUUID().toString();
request.headers().set( HEADER_PROXY_TRACE_ID, traceId );
return action.apply( normalizePath( path ) );
}
}