-
Notifications
You must be signed in to change notification settings - Fork 1k
/
HttpAccessLogHandler.java
252 lines (232 loc) · 10.2 KB
/
HttpAccessLogHandler.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
/*
* Copyright 2017-2022 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.http.server.netty.handler.accesslog;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.http.server.netty.handler.accesslog.element.AccessLog;
import io.micronaut.http.server.netty.handler.accesslog.element.AccessLogFormatParser;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufHolder;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http2.Http2Exception;
import io.netty.handler.codec.http2.HttpConversionUtil.ExtensionHeaderNames;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
/**
* Logging handler for HTTP access logs.
* Access logs will be logged at info level.
*
* @author croudet
* @since 2.0
*/
@Sharable
public class HttpAccessLogHandler extends ChannelDuplexHandler {
/**
* The default logger name.
*/
public static final String HTTP_ACCESS_LOGGER = "HTTP_ACCESS_LOGGER";
private static final AttributeKey<AccessLogHolder> ACCESS_LOGGER = AttributeKey.valueOf("ACCESS_LOGGER");
private static final String H2_PROTOCOL_NAME = "HTTP/2.0";
private final Logger logger;
private final AccessLogFormatParser accessLogFormatParser;
private final Predicate<String> uriInclusion;
/**
* Creates a HttpAccessLogHandler.
*
* @param loggerName A logger name.
* @param spec The log format specification.
*/
public HttpAccessLogHandler(String loggerName, String spec) {
this(loggerName == null || loggerName.isEmpty() ? null : LoggerFactory.getLogger(loggerName), spec, null);
}
/**
* Creates a HttpAccessLogHandler.
*
* @param loggerName A logger name.
* @param spec The log format specification.
* @param uriInclusion A filtering Predicate that will be checked per URI.
*/
public HttpAccessLogHandler(String loggerName, String spec, Predicate<String> uriInclusion) {
this(loggerName == null || loggerName.isEmpty() ? null : LoggerFactory.getLogger(loggerName), spec, uriInclusion);
}
/**
* Creates a HttpAccessLogHandler.
*
* @param logger A logger. Will log at info level.
* @param spec The log format specification.
*/
public HttpAccessLogHandler(Logger logger, String spec) {
this(logger, spec, null);
}
/**
* Creates a HttpAccessLogHandler.
*
* @param logger A logger. Will log at info level.
* @param spec The log format specification.
* @param uriInclusion A filtering Predicate that will be checked per URI.
*/
public HttpAccessLogHandler(Logger logger, String spec, Predicate<String> uriInclusion) {
super();
this.logger = logger == null ? LoggerFactory.getLogger(HTTP_ACCESS_LOGGER) : logger;
this.accessLogFormatParser = new AccessLogFormatParser(spec);
this.uriInclusion = uriInclusion;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Http2Exception {
if (logger.isInfoEnabled() && msg instanceof HttpRequest) {
final SocketChannel channel = (SocketChannel) ctx.channel();
final HttpRequest request = (HttpRequest) msg;
AccessLogHolder accessLogHolder = getAccessLogHolder(ctx, true);
assert accessLogHolder != null; // can only return null when createIfMissing is false
if (uriInclusion == null || uriInclusion.test(request.uri())) {
final HttpHeaders headers = request.headers();
// Trying to detect http/2
String protocol;
if (headers.contains(ExtensionHeaderNames.STREAM_ID.text()) || headers.contains(ExtensionHeaderNames.SCHEME.text())) {
protocol = H2_PROTOCOL_NAME;
} else {
protocol = request.protocolVersion().text();
}
accessLogHolder.createLogForRequest(request).onRequestHeaders(channel, request.method().name(), request.headers(), request.uri(), protocol);
} else {
accessLogHolder.excludeRequest(request);
}
}
ctx.fireChannelRead(msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (logger.isInfoEnabled()) {
processWriteEvent(ctx, msg, promise);
} else {
super.write(ctx, msg, promise);
}
}
private void log(ChannelHandlerContext ctx, Object msg, ChannelPromise promise, AccessLog accessLog) {
ctx.write(msg, promise.unvoid()).addListener(future -> {
if (future.isSuccess()) {
accessLog.log(logger);
}
});
}
private void processWriteEvent(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
AccessLogHolder accessLogHolder = getAccessLogHolder(ctx, false);
if (accessLogHolder != null) {
boolean isContinueResponse = msg instanceof HttpResponse && ((HttpResponse) msg).status().equals(HttpResponseStatus.CONTINUE);
AccessLog accessLogger = accessLogHolder.getLogForResponse(
msg instanceof HttpMessage ? (HttpMessage) msg : null,
msg instanceof LastHttpContent && !isContinueResponse);
if (accessLogger != null && !isContinueResponse) {
if (msg instanceof HttpResponse) {
accessLogger.onResponseHeaders(ctx, ((HttpResponse) msg).headers(), ((HttpResponse) msg).status().codeAsText().toString());
}
if (msg instanceof LastHttpContent) {
accessLogger.onLastResponseWrite(((LastHttpContent) msg).content().readableBytes());
log(ctx, msg, promise, accessLogger);
return;
} else if (msg instanceof ByteBufHolder) {
accessLogger.onResponseWrite(((ByteBufHolder) msg).content().readableBytes());
} else if (msg instanceof ByteBuf) {
accessLogger.onResponseWrite(((ByteBuf) msg).readableBytes());
}
}
}
super.write(ctx, msg, promise);
}
@Nullable
private AccessLogHolder getAccessLogHolder(ChannelHandlerContext ctx, boolean createIfMissing) {
final Attribute<AccessLogHolder> attr = ctx.channel().attr(ACCESS_LOGGER);
AccessLogHolder holder = attr.get();
if (holder == null) {
if (!createIfMissing) {
return null;
}
holder = new AccessLogHolder();
attr.set(holder);
}
return holder;
}
/**
* Holder for {@link AccessLog} instances. {@link AccessLog} can only handle one concurrent request at a time, this
* class multiplexes access where necessary.
*/
private final class AccessLogHolder {
private final Map<Long, AccessLog> liveAccessLogsByStreamId = new HashMap<>();
// HTTP1 does not have stream IDs. To emulate them, we have two counters. One counts up on every request, and
// the other counts up on every *completed* response.
private long http1NextRequestStreamId = 0;
private long currentPendingResponseStreamId = 0;
private AccessLog logForReuse;
AccessLog createLogForRequest(HttpRequest request) {
long streamId = getOrCreateStreamId(request);
AccessLog log = logForReuse;
logForReuse = null;
if (log != null) {
log.reset();
} else {
log = accessLogFormatParser.newAccessLogger();
}
liveAccessLogsByStreamId.put(streamId, log);
return log;
}
void excludeRequest(HttpRequest request) {
getOrCreateStreamId(request); // claim stream id, but no access logger
}
private long getOrCreateStreamId(HttpRequest request) {
String streamIdHeader = request.headers().get(ExtensionHeaderNames.STREAM_ID.text());
if (streamIdHeader == null) {
return http1NextRequestStreamId++;
} else {
return Long.parseLong(streamIdHeader);
}
}
@Nullable
AccessLog getLogForResponse(@Nullable HttpMessage msg, boolean finishResponse) {
String streamIdHeader = msg == null ? null : msg.headers().get(ExtensionHeaderNames.STREAM_ID.text());
long streamId;
if (streamIdHeader == null) {
streamId = currentPendingResponseStreamId;
if (finishResponse) {
currentPendingResponseStreamId++;
}
} else {
streamId = Long.parseLong(streamIdHeader);
currentPendingResponseStreamId = streamId; // in case future HttpContent objects arrive without a stream_id header
}
if (finishResponse) {
AccessLog accessLog = liveAccessLogsByStreamId.remove(streamId);
logForReuse = accessLog;
return accessLog;
} else {
return liveAccessLogsByStreamId.get(streamId);
}
}
}
}