index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/origins/OriginNameTest.java | /*
* Copyright 2021 Netflix, Inc.
*
* 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 com.netflix.zuul.origins;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class OriginNameTest {
@Test
void getAuthority() {
OriginName trusted = OriginName.fromVipAndApp("woodly-doodly", "westerndigital");
assertEquals("westerndigital", trusted.getAuthority());
}
@Test
void getMetrics() {
OriginName trusted = OriginName.fromVipAndApp("WOODLY-doodly", "westerndigital");
assertEquals("woodly-doodly", trusted.getMetricId());
assertEquals("WOODLY-doodly", trusted.getNiwsClientName());
}
@Test
void equals() {
OriginName name1 = OriginName.fromVipAndApp("woodly-doodly", "westerndigital");
OriginName name2 = OriginName.fromVipAndApp("woodly-doodly", "westerndigital", "woodly-doodly");
assertEquals(name1, name2);
assertEquals(name1.hashCode(), name2.hashCode());
}
@Test
@SuppressWarnings("deprecation")
void equals_legacy_niws() {
OriginName name1 = OriginName.fromVip("woodly-doodly", "westerndigital");
OriginName name2 = OriginName.fromVipAndApp("woodly-doodly", "woodly", "westerndigital");
assertEquals(name1, name2);
assertEquals(name1.hashCode(), name2.hashCode());
}
@Test
void equals_legacy() {
OriginName name1 = OriginName.fromVip("woodly-doodly");
OriginName name2 = OriginName.fromVipAndApp("woodly-doodly", "woodly", "woodly-doodly");
assertEquals(name1, name2);
assertEquals(name1.hashCode(), name2.hashCode());
}
@Test
void noNull() {
assertThrows(NullPointerException.class, () -> OriginName.fromVipAndApp(null, "app"));
assertThrows(NullPointerException.class, () -> OriginName.fromVipAndApp("vip", null));
assertThrows(NullPointerException.class, () -> OriginName.fromVipAndApp(null, "app", "niws"));
assertThrows(NullPointerException.class, () -> OriginName.fromVipAndApp("vip", null, "niws"));
assertThrows(NullPointerException.class, () -> OriginName.fromVipAndApp("vip", "app", null));
}
}
| 6,200 |
0 | Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/com/netflix/zuul/netty/server/push/PushConnectionTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.com.netflix.zuul.netty.server.push;
import com.netflix.zuul.netty.server.push.PushConnection;
import com.netflix.zuul.netty.server.push.PushProtocol;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Author: Susheel Aroskar
* Date: 10/18/2018
*/
class PushConnectionTest {
@Test
void testOneMessagePerSecond() throws InterruptedException {
final PushConnection conn = new PushConnection(PushProtocol.WEBSOCKET, null);
for (int i = 0; i < 5; i++) {
assertFalse(conn.isRateLimited());
Thread.sleep(1000);
}
}
@Test
void testThreeMessagesInSuccession() {
final PushConnection conn = new PushConnection(PushProtocol.WEBSOCKET, null);
assertFalse(conn.isRateLimited());
assertFalse(conn.isRateLimited());
assertFalse(conn.isRateLimited());
}
@Test
void testFourMessagesInSuccession() {
final PushConnection conn = new PushConnection(PushProtocol.WEBSOCKET, null);
assertFalse(conn.isRateLimited());
assertFalse(conn.isRateLimited());
assertFalse(conn.isRateLimited());
assertTrue(conn.isRateLimited());
}
@Test
void testFirstThreeMessagesSuccess() {
final PushConnection conn = new PushConnection(PushProtocol.WEBSOCKET, null);
for (int i = 0; i < 10; i++) {
if (i < 3) {
assertFalse(conn.isRateLimited());
} else {
assertTrue(conn.isRateLimited());
}
}
}
@Test
void testMessagesInBatches() throws InterruptedException {
final PushConnection conn = new PushConnection(PushProtocol.WEBSOCKET, null);
assertFalse(conn.isRateLimited());
assertFalse(conn.isRateLimited());
assertFalse(conn.isRateLimited());
assertTrue(conn.isRateLimited());
Thread.sleep(2000);
assertFalse(conn.isRateLimited());
assertFalse(conn.isRateLimited());
assertFalse(conn.isRateLimited());
assertTrue(conn.isRateLimited());
}
}
| 6,201 |
0 | Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/stats/RouteStatusCodeMonitorTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* 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 com.netflix.zuul.stats;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* Unit tests for {@link RouteStatusCodeMonitor}.
*/
class RouteStatusCodeMonitorTest {
@Test
void testUpdateStats() {
RouteStatusCodeMonitor sd = new RouteStatusCodeMonitor("test", 200);
assertEquals("test", sd.route);
sd.update();
assertEquals(1, sd.getCount());
sd.update();
assertEquals(2, sd.getCount());
}
@Test
void testEquals() {
RouteStatusCodeMonitor sd = new RouteStatusCodeMonitor("test", 200);
RouteStatusCodeMonitor sd1 = new RouteStatusCodeMonitor("test", 200);
RouteStatusCodeMonitor sd2 = new RouteStatusCodeMonitor("test1", 200);
RouteStatusCodeMonitor sd3 = new RouteStatusCodeMonitor("test", 201);
assertEquals(sd, sd1);
assertEquals(sd1, sd);
assertEquals(sd, sd);
assertNotEquals(sd, sd2);
assertNotEquals(sd, sd3);
assertNotEquals(sd2, sd3);
}
}
| 6,202 |
0 | Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/stats/StatsManagerTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* 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 com.netflix.zuul.stats;
import com.netflix.zuul.message.Headers;
import com.netflix.zuul.message.http.HttpRequestInfo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link StatsManager}.
*/
@ExtendWith(MockitoExtension.class)
class StatsManagerTest {
@Test
void testCollectRouteStats() {
String route = "test";
int status = 500;
StatsManager sm = StatsManager.getManager();
assertNotNull(sm);
// 1st request
sm.collectRouteStats(route, status);
ConcurrentHashMap<Integer, RouteStatusCodeMonitor> routeStatusMap = sm.routeStatusMap.get("test");
assertNotNull(routeStatusMap);
RouteStatusCodeMonitor routeStatusMonitor = routeStatusMap.get(status);
// 2nd request
sm.collectRouteStats(route, status);
}
@Test
void testGetRouteStatusCodeMonitor() {
StatsManager sm = StatsManager.getManager();
assertNotNull(sm);
sm.collectRouteStats("test", 500);
assertNotNull(sm.getRouteStatusCodeMonitor("test", 500));
}
@Test
void testCollectRequestStats() {
final String host = "api.netflix.com";
final String proto = "https";
final HttpRequestInfo req = Mockito.mock(HttpRequestInfo.class);
Headers headers = new Headers();
when(req.getHeaders()).thenReturn(headers);
headers.set(StatsManager.HOST_HEADER, host);
headers.set(StatsManager.X_FORWARDED_PROTO_HEADER, proto);
when(req.getClientIp()).thenReturn("127.0.0.1");
final StatsManager sm = StatsManager.getManager();
sm.collectRequestStats(req);
final NamedCountingMonitor hostMonitor = sm.getHostMonitor(host);
assertNotNull(hostMonitor, "hostMonitor should not be null");
final NamedCountingMonitor protoMonitor = sm.getProtocolMonitor(proto);
assertNotNull(protoMonitor, "protoMonitor should not be null");
assertEquals(1, hostMonitor.getCount());
assertEquals(1, protoMonitor.getCount());
}
@Test
void createsNormalizedHostKey() {
assertEquals("host_EC2.amazonaws.com", StatsManager.hostKey("ec2-174-129-179-89.compute-1.amazonaws.com"));
assertEquals("host_IP", StatsManager.hostKey("12.345.6.789"));
assertEquals("host_IP", StatsManager.hostKey("ip-10-86-83-168"));
assertEquals("host_CDN.nflxvideo.net", StatsManager.hostKey("002.ie.llnw.nflxvideo.net"));
assertEquals("host_CDN.llnwd.net", StatsManager.hostKey("netflix-635.vo.llnwd.net"));
assertEquals("host_CDN.nflximg.com", StatsManager.hostKey("cdn-0.nflximg.com"));
}
@Test
void extractsClientIpFromXForwardedFor() {
final String ip1 = "hi";
final String ip2 = "hey";
assertEquals(ip1, StatsManager.extractClientIpFromXForwardedFor(ip1));
assertEquals(ip1, StatsManager.extractClientIpFromXForwardedFor(String.format("%s,%s", ip1, ip2)));
assertEquals(ip1, StatsManager.extractClientIpFromXForwardedFor(String.format("%s, %s", ip1, ip2)));
}
@Test
void isIPv6() {
assertTrue(StatsManager.isIPv6("0:0:0:0:0:0:0:1"));
assertTrue(StatsManager.isIPv6("2607:fb10:2:232:72f3:95ff:fe03:a6e7"));
assertFalse(StatsManager.isIPv6("127.0.0.1"));
assertFalse(StatsManager.isIPv6("10.2.233.134"));
}
}
| 6,203 |
0 | Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/stats/ErrorStatsDataTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* 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 com.netflix.zuul.stats;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* Unit tests for {@link ErrorStatsData}.
*/
@ExtendWith(MockitoExtension.class)
class ErrorStatsDataTest {
@Test
void testUpdateStats() {
ErrorStatsData sd = new ErrorStatsData("route", "test");
sd.update();
assertEquals(1, sd.getCount());
sd.update();
assertEquals(2, sd.getCount());
}
@Test
void testEquals() {
ErrorStatsData sd = new ErrorStatsData("route", "test");
ErrorStatsData sd1 = new ErrorStatsData("route", "test");
ErrorStatsData sd2 = new ErrorStatsData("route", "test1");
ErrorStatsData sd3 = new ErrorStatsData("route", "test");
assertEquals(sd, sd1);
assertEquals(sd1, sd);
assertEquals(sd, sd);
assertNotEquals(sd, sd2);
assertNotEquals(sd2, sd3);
}
}
| 6,204 |
0 | Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/stats/ErrorStatsManagerTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* 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 com.netflix.zuul.stats;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Unit tests for {@link ErrorStatsManager}.
*/
@ExtendWith(MockitoExtension.class)
class ErrorStatsManagerTest {
@Test
void testPutStats() {
ErrorStatsManager sm = new ErrorStatsManager();
assertNotNull(sm);
sm.putStats("test", "cause");
assertNotNull(sm.routeMap.get("test"));
ConcurrentHashMap<String, ErrorStatsData> map = sm.routeMap.get("test");
ErrorStatsData sd = map.get("cause");
assertEquals(1, sd.getCount());
sm.putStats("test", "cause");
assertEquals(2, sd.getCount());
}
@Test
void testGetStats() {
ErrorStatsManager sm = new ErrorStatsManager();
assertNotNull(sm);
sm.putStats("test", "cause");
assertNotNull(sm.getStats("test", "cause"));
}
}
| 6,205 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/config/DynamicIntegerSetProperty.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.config;
import java.util.Set;
public class DynamicIntegerSetProperty extends DynamicSetProperty<Integer> {
public DynamicIntegerSetProperty(String propName, String defaultValue) {
super(propName, defaultValue);
}
public DynamicIntegerSetProperty(String propName, String defaultValue, String delimiterRegex) {
super(propName, defaultValue, delimiterRegex);
}
public DynamicIntegerSetProperty(String propName, Set<Integer> defaultValue) {
super(propName, defaultValue);
}
public DynamicIntegerSetProperty(String propName, Set<Integer> defaultValue, String delimiterRegex) {
super(propName, defaultValue, delimiterRegex);
}
@Override
protected Integer from(String value) {
return Integer.valueOf(value);
}
}
| 6,206 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/config/PatternListStringProperty.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* User: michaels@netflix.com
* Date: 5/15/17
* Time: 4:38 PM
*/
public class PatternListStringProperty extends DerivedStringProperty<List<Pattern>> {
private static final Logger LOG = LoggerFactory.getLogger(PatternListStringProperty.class);
public PatternListStringProperty(String name, String defaultValue) {
super(name, defaultValue);
}
@Override
protected List<Pattern> derive(String value) {
ArrayList<Pattern> ptns = new ArrayList<>();
if (value != null) {
for (String ptnTxt : value.split(",")) {
try {
ptns.add(Pattern.compile(ptnTxt.trim()));
} catch (Exception e) {
LOG.error(
"Error parsing regex pattern list from property! name = {}, value = {}, pattern = {}",
String.valueOf(this.getName()),
String.valueOf(this.getValue()),
String.valueOf(value));
}
}
}
return ptns;
}
}
| 6,207 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/Http1ConnectionCloseHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.LastHttpContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* User: michaels@netflix.com
* Date: 2/8/17
* Time: 2:03 PM
*/
public class Http1ConnectionCloseHandler extends ChannelDuplexHandler {
private static final Logger LOG = LoggerFactory.getLogger(Http1ConnectionCloseHandler.class);
private final AtomicBoolean requestInflight = new AtomicBoolean(Boolean.FALSE);
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
ChannelPromise closePromise = ctx.channel()
.attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE)
.get();
if (msg instanceof HttpResponse) {
HttpResponse response = (HttpResponse) msg;
if (closePromise != null) {
// Add header to tell client that they should close this connection.
response.headers().set(HttpHeaderNames.CONNECTION, "close");
}
}
super.write(ctx, msg, promise);
// Close the connection immediately after LastContent is written, rather than
// waiting until the graceful-delay is up if this flag is set.
if (msg instanceof LastHttpContent) {
if (closePromise != null) {
promise.addListener(future -> {
ConnectionCloseType type = ConnectionCloseType.fromChannel(ctx.channel());
closeChannel(ctx, type, closePromise);
});
}
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
// Track when there's an inflight request.
if (evt instanceof HttpLifecycleChannelHandler.StartEvent) {
requestInflight.set(Boolean.TRUE);
} else if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent) {
requestInflight.set(Boolean.FALSE);
}
super.userEventTriggered(ctx, evt);
}
protected void closeChannel(ChannelHandlerContext ctx, ConnectionCloseType evt, ChannelPromise promise) {
switch (evt) {
case DELAYED_GRACEFUL:
gracefully(ctx, promise);
break;
case GRACEFUL:
gracefully(ctx, promise);
break;
case IMMEDIATE:
immediately(ctx, promise);
break;
default:
throw new IllegalArgumentException("Unknown ConnectionCloseEvent type! - " + String.valueOf(evt));
}
}
protected void gracefully(ChannelHandlerContext ctx, ChannelPromise promise) {
final Channel channel = ctx.channel();
if (channel.isActive()) {
final String channelId = channel.id().asShortText();
// In gracefulCloseDelay secs time, go ahead and close the connection if it hasn't already been.
int gracefulCloseDelay = ConnectionCloseChannelAttributes.gracefulCloseDelay(channel);
ctx.executor()
.schedule(
() -> {
// Check that the client hasn't already closed the connection.
if (channel.isActive()) {
// If there is still an inflight request, then don't close the conn now. Instead
// assume that it will be closed
// either after the response finally gets written (due to us having set the
// CLOSE_AFTER_RESPONSE flag), or when the IdleTimeout
// for this conn fires.
if (requestInflight.get()) {
LOG.debug(
"gracefully: firing graceful_shutdown event to close connection, but request still inflight, so leaving. channel={}",
channelId);
} else {
LOG.debug(
"gracefully: firing graceful_shutdown event to close connection. channel={}",
channelId);
ctx.close(promise);
}
} else {
LOG.debug("gracefully: connection already closed. channel={}", channelId);
promise.setSuccess();
}
},
gracefulCloseDelay,
TimeUnit.SECONDS);
} else {
promise.setSuccess();
}
}
protected void immediately(ChannelHandlerContext ctx, ChannelPromise promise) {
if (ctx.channel().isActive()) {
ctx.close(promise);
} else {
promise.setSuccess();
}
}
}
| 6,208 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/ConnectionCloseType.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import io.netty.channel.Channel;
/**
* User: michaels@netflix.com
* Date: 2/8/17
* Time: 2:04 PM
*/
public enum ConnectionCloseType {
IMMEDIATE,
GRACEFUL,
DELAYED_GRACEFUL;
public static ConnectionCloseType fromChannel(Channel ch) {
ConnectionCloseType type =
ch.attr(ConnectionCloseChannelAttributes.CLOSE_TYPE).get();
if (type == null) {
// Default to immediate.
type = ConnectionCloseType.IMMEDIATE;
}
return type;
}
public static void setForChannel(Channel ch, ConnectionCloseType type) {
ch.attr(ConnectionCloseChannelAttributes.CLOSE_TYPE).set(type);
}
}
| 6,209 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/HttpChannelFlags.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
/**
* User: michaels@netflix.com
* Date: 7/10/17
* Time: 4:29 PM
*/
public class HttpChannelFlags {
public static final Flag IN_BROWNOUT = new Flag("_brownout");
public static final Flag CLOSING = new Flag("_connection_closing");
public static class Flag {
private final AttributeKey<Boolean> attributeKey;
public Flag(String name) {
attributeKey = AttributeKey.newInstance(name);
}
public void set(Channel ch) {
ch.attr(attributeKey).set(Boolean.TRUE);
}
public void remove(Channel ch) {
ch.attr(attributeKey).set(null);
}
public void set(ChannelHandlerContext ctx) {
set(ctx.channel());
}
public boolean get(Channel ch) {
Attribute<Boolean> attr = ch.attr(attributeKey);
Boolean value = attr.get();
return (value == null) ? false : value;
}
public boolean get(ChannelHandlerContext ctx) {
return get(ctx.channel());
}
}
}
| 6,210 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/HttpServerLifecycleChannelHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import com.netflix.zuul.passport.PassportState;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
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.util.ReferenceCountUtil;
/**
* @author michaels
*/
public final class HttpServerLifecycleChannelHandler extends HttpLifecycleChannelHandler {
public static final class HttpServerLifecycleInboundChannelHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpRequest) {
// Fire start event, and if that succeeded, then allow processing to
// continue to next handler in pipeline.
if (fireStartEvent(ctx, (HttpRequest) msg)) {
super.channelRead(ctx, msg);
} else {
ReferenceCountUtil.release(msg);
}
} else {
super.channelRead(ctx, msg);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
fireCompleteEventIfNotAlready(ctx, CompleteReason.INACTIVE);
super.channelInactive(ctx);
}
}
public static final class HttpServerLifecycleOutboundChannelHandler extends ChannelOutboundHandlerAdapter {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof HttpResponse) {
ctx.channel().attr(ATTR_HTTP_RESP).set((HttpResponse) msg);
}
try {
super.write(ctx, msg, promise);
} finally {
if (msg instanceof LastHttpContent) {
boolean dontFireCompleteYet = false;
if (msg instanceof HttpResponse) {
// Handle case of 100 CONTINUE, where server sends an initial 100 status response to indicate to
// client
// that it can continue sending the initial request body.
// ie. in this case we don't want to consider the state to be COMPLETE until after the 2nd
// response.
if (((HttpResponse) msg).status() == HttpResponseStatus.CONTINUE) {
dontFireCompleteYet = true;
}
}
if (!dontFireCompleteYet) {
if (promise.isDone()) {
fireCompleteEventIfNotAlready(ctx, CompleteReason.SESSION_COMPLETE);
} else {
promise.addListener(future -> {
fireCompleteEventIfNotAlready(ctx, CompleteReason.SESSION_COMPLETE);
});
}
}
}
}
}
@Override
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
fireCompleteEventIfNotAlready(ctx, CompleteReason.DISCONNECT);
super.disconnect(ctx, promise);
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
addPassportState(ctx, PassportState.SERVER_CH_CLOSE);
// This will likely expand based on more specific reasons for completion
if (ctx.channel()
.attr(HttpLifecycleChannelHandler.ATTR_HTTP_PIPELINE_REJECT)
.get()
== null) {
fireCompleteEventIfNotAlready(ctx, CompleteReason.CLOSE);
} else {
fireCompleteEventIfNotAlready(ctx, CompleteReason.PIPELINE_REJECT);
}
super.close(ctx, promise);
}
}
}
| 6,211 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/SwallowSomeHttp2ExceptionsHandler.java | /*
* Copyright 2019 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import com.netflix.spectator.api.Registry;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.unix.Errors;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2Exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ChannelHandler.Sharable
public class SwallowSomeHttp2ExceptionsHandler extends ChannelOutboundHandlerAdapter {
private static final Logger LOG = LoggerFactory.getLogger(SwallowSomeHttp2ExceptionsHandler.class);
private final Registry registry;
public SwallowSomeHttp2ExceptionsHandler(Registry registry) {
this.registry = registry;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
incrementExceptionCounter(cause);
if (cause instanceof Http2Exception) {
Http2Exception h2e = (Http2Exception) cause;
if (h2e.error() == Http2Error.NO_ERROR
&& Http2Exception.ShutdownHint.GRACEFUL_SHUTDOWN.equals(h2e.shutdownHint())) {
// This is the exception we threw ourselves to make the http2 codec gracefully close the connection. So
// just
// swallow it so that it doesn't propagate and get logged.
LOG.debug("Swallowed Http2Exception.ShutdownHint.GRACEFUL_SHUTDOWN ", cause);
} else {
super.exceptionCaught(ctx, cause);
}
} else if (cause instanceof Errors.NativeIoException) {
LOG.debug("Swallowed NativeIoException", cause);
} else {
super.exceptionCaught(ctx, cause);
}
}
private void incrementExceptionCounter(Throwable throwable) {
registry.counter(
"server.connection.pipeline.exception",
"id",
throwable.getClass().getSimpleName())
.increment();
}
}
| 6,212 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/Http2ConnectionExpiryHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import io.netty.channel.ChannelHandler;
import io.netty.handler.codec.http2.Http2HeadersFrame;
/**
* This needs to be inserted in the pipeline after the Http2 Codex, but before any h2->h1 conversion.
*
* User: michaels@netflix.com
* Date: 2/8/17
* Time: 9:58 AM
*/
@ChannelHandler.Sharable
public class Http2ConnectionExpiryHandler extends AbstrHttpConnectionExpiryHandler {
public Http2ConnectionExpiryHandler(int maxRequests, int maxRequestsUnderBrownout, int maxExpiry) {
super(ConnectionCloseType.DELAYED_GRACEFUL, maxRequestsUnderBrownout, maxRequests, maxExpiry);
}
@Override
protected boolean isResponseHeaders(Object msg) {
return msg instanceof Http2HeadersFrame;
}
}
| 6,213 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/RequestResponseCompleteEvent.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
/**
* User: michaels@netflix.com
* Date: 5/24/16
* Time: 1:04 PM
*/
public class RequestResponseCompleteEvent {}
| 6,214 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/HttpClientLifecycleChannelHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.LastHttpContent;
/**
* @author michaels
*/
public class HttpClientLifecycleChannelHandler extends HttpLifecycleChannelHandler {
public static final ChannelHandler INBOUND_CHANNEL_HANDLER = new HttpClientLifecycleInboundChannelHandler();
public static final ChannelHandler OUTBOUND_CHANNEL_HANDLER = new HttpClientLifecycleOutboundChannelHandler();
@ChannelHandler.Sharable
private static class HttpClientLifecycleInboundChannelHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpResponse) {
ctx.channel().attr(ATTR_HTTP_RESP).set((HttpResponse) msg);
}
try {
super.channelRead(ctx, msg);
} finally {
if (msg instanceof LastHttpContent) {
fireCompleteEventIfNotAlready(ctx, CompleteReason.SESSION_COMPLETE);
}
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
try {
super.channelInactive(ctx);
} finally {
fireCompleteEventIfNotAlready(ctx, CompleteReason.INACTIVE);
}
}
}
@ChannelHandler.Sharable
private static class HttpClientLifecycleOutboundChannelHandler extends ChannelOutboundHandlerAdapter {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof HttpRequest) {
fireStartEvent(ctx, (HttpRequest) msg);
}
super.write(ctx, msg, promise);
}
@Override
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
fireCompleteEventIfNotAlready(ctx, CompleteReason.DISCONNECT);
super.disconnect(ctx, promise);
}
@Override
public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
fireCompleteEventIfNotAlready(ctx, CompleteReason.DEREGISTER);
super.deregister(ctx, promise);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
fireCompleteEventIfNotAlready(ctx, CompleteReason.EXCEPTION);
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
fireCompleteEventIfNotAlready(ctx, CompleteReason.CLOSE);
super.close(ctx, promise);
}
}
}
| 6,215 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/HttpRequestReadTimeoutEvent.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
/**
* Indicates a timeout in reading the full http request.
*
* ie. time between receiving request headers and LastHttpContent of request body.
*/
public class HttpRequestReadTimeoutEvent {
public static final HttpRequestReadTimeoutEvent INSTANCE = new HttpRequestReadTimeoutEvent();
}
| 6,216 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/HttpLifecycleChannelHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.zuul.passport.CurrentPassport;
import com.netflix.zuul.passport.PassportState;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* User: michaels@netflix.com
* Date: 5/24/16
* Time: 4:09 PM
*/
public abstract class HttpLifecycleChannelHandler {
private static final Logger logger = LoggerFactory.getLogger(HttpLifecycleChannelHandler.class);
public static final AttributeKey<HttpRequest> ATTR_HTTP_REQ = AttributeKey.newInstance("_http_request");
public static final AttributeKey<HttpResponse> ATTR_HTTP_RESP = AttributeKey.newInstance("_http_response");
public static final AttributeKey<Boolean> ATTR_HTTP_PIPELINE_REJECT =
AttributeKey.newInstance("_http_pipeline_reject");
protected enum State {
STARTED,
COMPLETED
}
@VisibleForTesting
protected static final AttributeKey<State> ATTR_STATE = AttributeKey.newInstance("_httplifecycle_state");
protected static boolean fireStartEvent(ChannelHandlerContext ctx, HttpRequest request) {
// Only allow this method to run once per request.
Channel channel = ctx.channel();
Attribute<State> attr = channel.attr(ATTR_STATE);
State state = attr.get();
if (state == State.STARTED) {
// This could potentially happen if a bad client sends a 2nd request on the same connection
// without waiting for the response from the first. And we don't support HTTP Pipelining.
logger.debug(
"Received a http request on connection where we already have a request being processed. Closing the connection now. channel = {}",
channel.id().asLongText());
channel.attr(ATTR_HTTP_PIPELINE_REJECT).set(Boolean.TRUE);
channel.close();
return false;
}
channel.attr(ATTR_STATE).set(State.STARTED);
channel.attr(ATTR_HTTP_REQ).set(request);
ctx.pipeline().fireUserEventTriggered(new StartEvent(request));
return true;
}
protected static boolean fireCompleteEventIfNotAlready(ChannelHandlerContext ctx, CompleteReason reason) {
// Only allow this method to run once per request.
Attribute<State> attr = ctx.channel().attr(ATTR_STATE);
State state = attr.get();
if (state == null || state != State.STARTED) {
return false;
}
attr.set(State.COMPLETED);
HttpRequest request = ctx.channel().attr(ATTR_HTTP_REQ).get();
HttpResponse response = ctx.channel().attr(ATTR_HTTP_RESP).get();
// Cleanup channel attributes.
ctx.channel().attr(ATTR_HTTP_REQ).set(null);
ctx.channel().attr(ATTR_HTTP_RESP).set(null);
// Fire the event to whole pipeline.
ctx.pipeline().fireUserEventTriggered(new CompleteEvent(reason, request, response));
return true;
}
protected static void addPassportState(ChannelHandlerContext ctx, PassportState state) {
CurrentPassport passport = CurrentPassport.fromChannel(ctx.channel());
passport.add(state);
}
public enum CompleteReason {
SESSION_COMPLETE,
INACTIVE,
// IDLE,
DISCONNECT,
DEREGISTER,
PIPELINE_REJECT,
EXCEPTION,
CLOSE
// FAILURE_CLIENT_CANCELLED,
// FAILURE_CLIENT_TIMEOUT;
// private final NfStatus nfStatus;
// private final int responseStatus;
//
// CompleteReason(NfStatus nfStatus, int responseStatus) {
// this.nfStatus = nfStatus;
// this.responseStatus = responseStatus;
// }
//
// CompleteReason() {
// //For status that never gets returned back to client, like channel inactive
// nfStatus = null;
// responseStatus = 501;
// }
//
// public NfStatus getNfStatus() {
// return nfStatus;
// }
//
// public int getResponseStatus() {
// return responseStatus;
// }
}
public static class StartEvent {
private final HttpRequest request;
public StartEvent(HttpRequest request) {
this.request = request;
}
public HttpRequest getRequest() {
return request;
}
}
public static class CompleteEvent {
private final CompleteReason reason;
private final HttpRequest request;
private final HttpResponse response;
public CompleteEvent(CompleteReason reason, HttpRequest request, HttpResponse response) {
this.reason = reason;
this.request = request;
this.response = response;
}
public CompleteReason getReason() {
return reason;
}
public HttpRequest getRequest() {
return request;
}
public HttpResponse getResponse() {
return response;
}
}
}
| 6,217 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/HttpRequestReadTimeoutHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import com.netflix.spectator.api.Counter;
import com.netflix.zuul.passport.CurrentPassport;
import com.netflix.zuul.passport.PassportState;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.timeout.ReadTimeoutHandler;
import java.util.concurrent.TimeUnit;
/**
* This handler times from the point a HttpRequest is read until the LastHttpContent is read,
* and fires a HttpRequestTimeoutEvent if that time has exceed the configured timeout.
*
* Unlike ReadTimeoutHandler, this impl does NOT close the channel on a timeout. Only fires the
* event.
*
* @author michaels
*/
public class HttpRequestReadTimeoutHandler extends ChannelInboundHandlerAdapter {
private static final String HANDLER_NAME = "http_request_read_timeout_handler";
private static final String INTERNAL_HANDLER_NAME = "http_request_read_timeout_internal";
private final long timeout;
private final TimeUnit unit;
private final Counter httpRequestReadTimeoutCounter;
protected HttpRequestReadTimeoutHandler(long timeout, TimeUnit unit, Counter httpRequestReadTimeoutCounter) {
this.timeout = timeout;
this.unit = unit;
this.httpRequestReadTimeoutCounter = httpRequestReadTimeoutCounter;
}
/**
* Factory which ensures that this handler is added to the pipeline using the
* correct name.
*/
public static void addLast(
ChannelPipeline pipeline, long timeout, TimeUnit unit, Counter httpRequestReadTimeoutCounter) {
HttpRequestReadTimeoutHandler handler =
new HttpRequestReadTimeoutHandler(timeout, unit, httpRequestReadTimeoutCounter);
pipeline.addLast(HANDLER_NAME, handler);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof LastHttpContent) {
removeInternalHandler(ctx);
} else if (msg instanceof HttpRequest) {
// Start timeout handler.
InternalReadTimeoutHandler handler = new InternalReadTimeoutHandler(timeout, unit);
ctx.pipeline().addBefore(HANDLER_NAME, INTERNAL_HANDLER_NAME, handler);
}
super.channelRead(ctx, msg);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof HttpRequestReadTimeoutEvent) {
CurrentPassport.fromChannel(ctx.channel()).add(PassportState.IN_REQ_READ_TIMEOUT);
removeInternalHandler(ctx);
httpRequestReadTimeoutCounter.increment();
}
super.userEventTriggered(ctx, evt);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
removeInternalHandler(ctx);
super.handlerRemoved(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
removeInternalHandler(ctx);
super.channelInactive(ctx);
}
protected void removeInternalHandler(ChannelHandlerContext ctx) {
// Remove timeout handler if not already removed.
ChannelHandlerContext handlerContext = ctx.pipeline().context(INTERNAL_HANDLER_NAME);
if (handlerContext != null && !handlerContext.isRemoved()) {
ctx.pipeline().remove(INTERNAL_HANDLER_NAME);
}
}
static class InternalReadTimeoutHandler extends ReadTimeoutHandler {
public InternalReadTimeoutHandler(long timeout, TimeUnit unit) {
super(timeout, unit);
}
@Override
protected void readTimedOut(ChannelHandlerContext ctx) throws Exception {
ctx.fireUserEventTriggered(HttpRequestReadTimeoutEvent.INSTANCE);
}
}
}
| 6,218 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/AbstrHttpConnectionExpiryHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import com.netflix.config.CachedDynamicLongProperty;
import com.netflix.zuul.netty.ChannelUtils;
import com.netflix.zuul.util.HttpUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ThreadLocalRandom;
/**
* User: michaels@netflix.com
* Date: 7/17/17
* Time: 10:54 AM
*/
public abstract class AbstrHttpConnectionExpiryHandler extends ChannelOutboundHandlerAdapter {
protected static final Logger LOG = LoggerFactory.getLogger(AbstrHttpConnectionExpiryHandler.class);
protected static final CachedDynamicLongProperty MAX_EXPIRY_DELTA =
new CachedDynamicLongProperty("server.connection.expiry.delta", 20 * 1000);
protected final ConnectionCloseType connectionCloseType;
protected final int maxRequests;
protected final int maxExpiry;
protected final long connectionStartTime;
protected final long connectionExpiryTime;
protected int requestCount = 0;
protected int maxRequestsUnderBrownout = 0;
public AbstrHttpConnectionExpiryHandler(
ConnectionCloseType connectionCloseType, int maxRequestsUnderBrownout, int maxRequests, int maxExpiry) {
this.connectionCloseType = connectionCloseType;
this.maxRequestsUnderBrownout = maxRequestsUnderBrownout;
this.maxRequests = maxRequests;
this.maxExpiry = maxExpiry;
this.connectionStartTime = System.currentTimeMillis();
long randomDelta = ThreadLocalRandom.current().nextLong(MAX_EXPIRY_DELTA.get());
this.connectionExpiryTime = connectionStartTime + maxExpiry + randomDelta;
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (isResponseHeaders(msg)) {
// Update the request count attribute for this channel.
requestCount++;
if (isConnectionExpired(ctx.channel())) {
// Flag this channel to be closed after response is written.
Channel channel = HttpUtils.getMainChannel(ctx);
ctx.channel()
.attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE)
.set(ctx.newPromise());
ConnectionCloseType.setForChannel(channel, connectionCloseType);
}
}
super.write(ctx, msg, promise);
}
protected boolean isConnectionExpired(Channel channel) {
boolean expired = requestCount >= maxRequests(channel) || System.currentTimeMillis() > connectionExpiryTime;
if (expired) {
long lifetime = System.currentTimeMillis() - connectionStartTime;
LOG.info(
"Connection is expired. requestCount={}, lifetime={}, {}",
requestCount,
lifetime,
ChannelUtils.channelInfoForLogging(channel));
}
return expired;
}
protected abstract boolean isResponseHeaders(Object msg);
protected int maxRequests(Channel ch) {
if (HttpChannelFlags.IN_BROWNOUT.get(ch)) {
return this.maxRequestsUnderBrownout;
} else {
return this.maxRequests;
}
}
}
| 6,219 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/SourceAddressChannelHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import com.google.common.annotations.VisibleForTesting;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import javax.annotation.Nullable;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
/**
* Stores the source IP address as an attribute of the channel. This has the advantage of allowing us to overwrite it if
* we have more info (eg. ELB sends a HAProxyMessage with info of REAL source host + port).
* <p>
* User: michaels@netflix.com Date: 4/14/16 Time: 4:29 PM
*/
@ChannelHandler.Sharable
public final class SourceAddressChannelHandler extends ChannelInboundHandlerAdapter {
/**
* Indicates the actual source (remote) address of the channel. This can be different than the one {@link Channel}
* returns if the connection is being proxied. (e.g. over HAProxy)
*/
public static final AttributeKey<SocketAddress> ATTR_REMOTE_ADDR = AttributeKey.newInstance("_remote_addr");
/**
* Indicates the destination address received from Proxy Protocol. Not set otherwise
*/
public static final AttributeKey<InetSocketAddress> ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS =
AttributeKey.newInstance("_proxy_protocol_destination_address");
/**
* Use {@link #ATTR_REMOTE_ADDR} instead.
*/
@Deprecated
public static final AttributeKey<InetSocketAddress> ATTR_SOURCE_INET_ADDR =
AttributeKey.newInstance("_source_inet_addr");
/**
* The host address of the source. This is derived from {@link #ATTR_REMOTE_ADDR}. If the address is an IPv6
* address, the scope identifier is absent.
*/
public static final AttributeKey<String> ATTR_SOURCE_ADDRESS = AttributeKey.newInstance("_source_address");
/**
* Indicates the local address of the channel. This can be different than the one {@link Channel} returns if the
* connection is being proxied. (e.g. over HAProxy)
*/
public static final AttributeKey<SocketAddress> ATTR_LOCAL_ADDR = AttributeKey.newInstance("_local_addr");
/**
* Use {@link #ATTR_LOCAL_ADDR} instead.
*/
@Deprecated
public static final AttributeKey<InetSocketAddress> ATTR_LOCAL_INET_ADDR =
AttributeKey.newInstance("_local_inet_addr");
/**
* The local address of this channel. This is derived from {@code channel.localAddress()}, or from the Proxy
* Protocol preface if provided. If the address is an IPv6 address, the scope identifier is absent. Unlike {@link
* #ATTR_SERVER_LOCAL_ADDRESS}, this value is overwritten with the Proxy Protocol local address (e.g. the LB's local
* address), if enabled.
*/
public static final AttributeKey<String> ATTR_LOCAL_ADDRESS = AttributeKey.newInstance("_local_address");
/**
* The actual local address of the channel, in string form. If the address is an IPv6 address, the scope identifier
* is absent. Unlike {@link #ATTR_LOCAL_ADDRESS}, this is not overwritten by the Proxy Protocol message if
* present.
*
* @deprecated Use {@code channel.localAddress()} instead.
*/
@Deprecated
public static final AttributeKey<String> ATTR_SERVER_LOCAL_ADDRESS =
AttributeKey.newInstance("_server_local_address");
/**
* The port number of the local socket, or {@code -1} if not appropriate. This is not overwritten by the Proxy
* Protocol message if present.
*/
public static final AttributeKey<Integer> ATTR_SERVER_LOCAL_PORT = AttributeKey.newInstance("_server_local_port");
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.channel().attr(ATTR_REMOTE_ADDR).set(ctx.channel().remoteAddress());
InetSocketAddress sourceAddress = sourceAddress(ctx.channel());
ctx.channel().attr(ATTR_SOURCE_INET_ADDR).setIfAbsent(sourceAddress);
ctx.channel().attr(ATTR_SOURCE_ADDRESS).setIfAbsent(getHostAddress(sourceAddress));
ctx.channel().attr(ATTR_LOCAL_ADDR).set(ctx.channel().localAddress());
InetSocketAddress localAddress = localAddress(ctx.channel());
ctx.channel().attr(ATTR_LOCAL_INET_ADDR).setIfAbsent(localAddress);
ctx.channel().attr(ATTR_LOCAL_ADDRESS).setIfAbsent(getHostAddress(localAddress));
// ATTR_LOCAL_ADDRESS and ATTR_LOCAL_PORT get overwritten with what is received in
// Proxy Protocol (via the LB), so set local server's address, port explicitly
ctx.channel()
.attr(ATTR_SERVER_LOCAL_ADDRESS)
.setIfAbsent(localAddress.getAddress().getHostAddress());
ctx.channel().attr(ATTR_SERVER_LOCAL_PORT).setIfAbsent(localAddress.getPort());
super.channelActive(ctx);
}
/**
* Returns the String form of a socket address, or {@code null} if there isn't one.
*/
@VisibleForTesting
@Nullable
static String getHostAddress(InetSocketAddress socketAddress) {
InetAddress address = socketAddress.getAddress();
if (address instanceof Inet6Address) {
// Strip the scope from the address since some other classes choke on it.
// TODO(carl-mastrangelo): Consider adding this back in once issues like
// https://github.com/google/guava/issues/2587 are fixed.
try {
return InetAddress.getByAddress(address.getAddress()).getHostAddress();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
} else if (address instanceof Inet4Address) {
return address.getHostAddress();
} else {
assert address == null;
return null;
}
}
private InetSocketAddress sourceAddress(Channel channel) {
SocketAddress remoteSocketAddr = channel.remoteAddress();
if (null != remoteSocketAddr && InetSocketAddress.class.isAssignableFrom(remoteSocketAddr.getClass())) {
InetSocketAddress inetSocketAddress = (InetSocketAddress) remoteSocketAddr;
if (inetSocketAddress.getAddress() != null) {
return inetSocketAddress;
}
}
return null;
}
private InetSocketAddress localAddress(Channel channel) {
SocketAddress localSocketAddress = channel.localAddress();
if (null != localSocketAddress && InetSocketAddress.class.isAssignableFrom(localSocketAddress.getClass())) {
InetSocketAddress inetSocketAddress = (InetSocketAddress) localSocketAddress;
if (inetSocketAddress.getAddress() != null) {
return inetSocketAddress;
}
}
return null;
}
}
| 6,220 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/ConnectionCloseChannelAttributes.java | /*
* Copyright 2019 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import com.netflix.netty.common.channel.config.ChannelConfig;
import com.netflix.netty.common.channel.config.CommonChannelConfigKeys;
import com.netflix.zuul.netty.server.BaseZuulChannelInitializer;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPromise;
import io.netty.util.AttributeKey;
public class ConnectionCloseChannelAttributes {
public static final AttributeKey<ChannelPromise> CLOSE_AFTER_RESPONSE =
AttributeKey.newInstance("CLOSE_AFTER_RESPONSE");
public static final AttributeKey<ConnectionCloseType> CLOSE_TYPE = AttributeKey.newInstance("CLOSE_TYPE");
public static int gracefulCloseDelay(Channel channel) {
ChannelConfig channelConfig =
channel.attr(BaseZuulChannelInitializer.ATTR_CHANNEL_CONFIG).get();
Integer gracefulCloseDelay = channelConfig.get(CommonChannelConfigKeys.connCloseDelay);
return gracefulCloseDelay == null ? 0 : gracefulCloseDelay;
}
public static boolean allowGracefulDelayed(Channel channel) {
ChannelConfig channelConfig =
channel.attr(BaseZuulChannelInitializer.ATTR_CHANNEL_CONFIG).get();
Boolean value = channelConfig.get(CommonChannelConfigKeys.http2AllowGracefulDelayed);
return value == null ? false : value;
}
}
| 6,221 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/SslExceptionsHandler.java | /*
* Copyright 2023 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import com.netflix.spectator.api.Registry;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLHandshakeException;
/**
* Swallow specific SSL related exceptions to avoid propagating deep stack traces up the pipeline.
*
* @author Argha C
* @since 4/17/23
*/
@Sharable
public class SslExceptionsHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(SslExceptionsHandler.class);
private final Registry registry;
public SslExceptionsHandler(Registry registry) {
this.registry = registry;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// In certain cases, depending on the client, these stack traces can get very deep.
// We intentionally avoid propagating this up the pipeline, to avoid verbose disk logging.
if (cause.getCause() instanceof SSLHandshakeException) {
logger.debug("SSL handshake failed on channel {}", ctx.channel(), cause);
registry.counter("server.ssl.exception.swallowed", "cause", "SSLHandshakeException")
.increment();
} else {
super.exceptionCaught(ctx, cause);
}
}
}
| 6,222 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/CloseOnIdleStateHandler.java | /**
* Copyright 2018 Netflix, Inc.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 com.netflix.netty.common;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
/**
* Just listens for the IdleStateEvent and closes the channel if received.
*/
public class CloseOnIdleStateHandler extends ChannelInboundHandlerAdapter {
private final Counter counter;
public CloseOnIdleStateHandler(Registry registry, String metricId) {
this.counter = registry.counter("server.connections.idle.timeout", "id", metricId);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
super.userEventTriggered(ctx, evt);
if (evt instanceof IdleStateEvent) {
counter.increment();
ctx.close();
}
}
}
| 6,223 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/Http2ConnectionCloseHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.zuul.util.HttpUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.DelegatingChannelPromiseNotifier;
import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2Exception;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.util.concurrent.EventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.util.concurrent.TimeUnit;
/**
* User: michaels@netflix.com
* Date: 2/8/17
* Time: 2:03 PM
*/
@ChannelHandler.Sharable
public class Http2ConnectionCloseHandler extends ChannelDuplexHandler {
private static final Logger LOG = LoggerFactory.getLogger(Http2ConnectionCloseHandler.class);
private final Registry registry;
private final Id counterBaseId;
@Inject
public Http2ConnectionCloseHandler(Registry registry) {
super();
this.registry = registry;
this.counterBaseId = registry.createId("server.connection.close.handled");
}
private void incrementCounter(ConnectionCloseType closeType, int port) {
registry.counter(counterBaseId
.withTag("close_type", closeType.name())
.withTag("port", Integer.toString(port))
.withTag("protocol", "http2"))
.increment();
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
// Close the connection immediately after LastContent is written, rather than
// waiting until the graceful-delay is up if this flag is set.
if (isEndOfRequestResponse(msg)) {
final Channel parent = HttpUtils.getMainChannel(ctx);
final ChannelPromise closeAfterPromise = shouldCloseAfter(ctx, parent);
if (closeAfterPromise != null) {
// Add listener to close the channel AFTER response has been sent.
promise.addListener(future -> {
// Close the parent (tcp connection) channel.
closeChannel(ctx, closeAfterPromise);
});
}
}
super.write(ctx, msg, promise);
}
/**
* Look on both the stream channel, and the parent channel to see if the CLOSE_AFTER_RESPONSE flag has been set.
* If so, return that promise.
*
* @param ctx
* @param parent
* @return
*/
private ChannelPromise shouldCloseAfter(ChannelHandlerContext ctx, Channel parent) {
ChannelPromise closeAfterPromise = ctx.channel()
.attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE)
.get();
if (closeAfterPromise == null) {
closeAfterPromise = parent.attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE)
.get();
}
return closeAfterPromise;
}
private boolean isEndOfRequestResponse(Object msg) {
if (msg instanceof Http2HeadersFrame) {
return ((Http2HeadersFrame) msg).isEndStream();
}
if (msg instanceof Http2DataFrame) {
return ((Http2DataFrame) msg).isEndStream();
}
return false;
}
private void closeChannel(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
Channel child = ctx.channel();
Channel parent = HttpUtils.getMainChannel(ctx);
// 1. Check if already_closing flag on this stream channel. If there is, then success this promise and return.
// If not, then add already_closing flag to this stream channel.
// 2. Check if already_closing flag on the parent channel.
// If so, then just return.
// If not, then set already_closing on parent channel, and then allow through.
if (isAlreadyClosing(child)) {
promise.setSuccess();
return;
}
if (isAlreadyClosing(parent)) {
return;
}
// Close according to the specified close type.
ConnectionCloseType closeType = ConnectionCloseType.fromChannel(parent);
Integer port =
parent.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).get();
port = port == null ? -1 : port;
incrementCounter(closeType, port);
switch (closeType) {
case DELAYED_GRACEFUL:
gracefullyWithDelay(ctx.executor(), parent, promise);
break;
case GRACEFUL:
case IMMEDIATE:
immediate(parent, promise);
break;
default:
throw new IllegalArgumentException("Unknown ConnectionCloseEvent type! - " + closeType);
}
}
/**
* WARNING: Found the OkHttp client gets confused by this behaviour (it ends up putting itself in a bad shutdown state
* after receiving the first goaway frame, and then dropping any inflight responses but also timing out waiting for them).
*
* And worried that other http/2 stacks may be similar, so for now we should NOT use this.
*
* This is unfortunate, as FTL wanted this, and it is correct according to the spec.
*
* See this code in okhttp where it drops response header frame if state is already shutdown:
* https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/internal/http2/Http2Connection.java#L609
*/
private void gracefullyWithDelay(EventExecutor executor, Channel parent, ChannelPromise promise) {
// See javadoc for explanation of why this may be disabled.
boolean allowGracefulDelayed = ConnectionCloseChannelAttributes.allowGracefulDelayed(parent);
if (!allowGracefulDelayed) {
immediate(parent, promise);
return;
}
if (!parent.isActive()) {
promise.setSuccess();
return;
}
// First send a 'graceful shutdown' GOAWAY frame.
/*
"A server that is attempting to gracefully shut down a connection SHOULD send an initial GOAWAY frame with
the last stream identifier set to 231-1 and a NO_ERROR code. This signals to the client that a shutdown is
imminent and that initiating further requests is prohibited."
-- https://http2.github.io/http2-spec/#GOAWAY
*/
DefaultHttp2GoAwayFrame goaway = new DefaultHttp2GoAwayFrame(Http2Error.NO_ERROR);
goaway.setExtraStreamIds(Integer.MAX_VALUE);
parent.writeAndFlush(goaway);
LOG.debug(
"gracefullyWithDelay: flushed initial go_away frame. channel={}",
parent.id().asShortText());
// In N secs time, throw an error that causes the http2 codec to send another GOAWAY frame
// (this time with accurate lastStreamId) and then close the connection.
int gracefulCloseDelay = ConnectionCloseChannelAttributes.gracefulCloseDelay(parent);
executor.schedule(
() -> {
// Check that the client hasn't already closed the connection (due to the earlier goaway we sent).
if (parent.isActive()) {
// NOTE - the netty Http2ConnectionHandler specifically does not send another goaway when we
// call
// channel.close() if one has already been sent .... so when we want more than one sent, we need
// to do it
// explicitly ourselves like this.
LOG.debug(
"gracefullyWithDelay: firing graceful_shutdown event to make netty send a final go_away frame and then close connection. channel={}",
parent.id().asShortText());
Http2Exception h2e =
new Http2Exception(Http2Error.NO_ERROR, Http2Exception.ShutdownHint.GRACEFUL_SHUTDOWN);
parent.pipeline().fireExceptionCaught(h2e);
parent.close().addListener(future -> {
promise.setSuccess();
});
} else {
promise.setSuccess();
}
},
gracefulCloseDelay,
TimeUnit.SECONDS);
}
private void immediate(Channel parent, ChannelPromise promise) {
if (parent.isActive()) {
parent.close().addListener(new DelegatingChannelPromiseNotifier(promise));
} else {
promise.setSuccess();
}
}
protected boolean isAlreadyClosing(Channel parentChannel) {
// If already closing, then just return.
// This will happen because close() is called a 2nd time after sending the goaway frame.
if (HttpChannelFlags.CLOSING.get(parentChannel)) {
return true;
} else {
HttpChannelFlags.CLOSING.set(parentChannel);
return false;
}
}
}
| 6,224 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/ByteBufUtil.java | /*
* Copyright 2022 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import com.netflix.zuul.message.ZuulMessage;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.ReferenceCounted;
import io.netty.util.ResourceLeakDetector;
/**
* ByteBufUtil
*
* @author Arthur Gonigberg
* @since October 20, 2022
*/
public class ByteBufUtil {
private static final boolean isAdvancedLeakDetection =
ResourceLeakDetector.getLevel().ordinal() >= ResourceLeakDetector.Level.ADVANCED.ordinal();
public static void touch(ReferenceCounted byteBuf, String hint, ZuulMessage msg) {
if (isAdvancedLeakDetection) {
byteBuf.touch(hint + msg);
}
}
public static void touch(ReferenceCounted byteBuf, String hint) {
if (isAdvancedLeakDetection) {
byteBuf.touch(hint);
}
}
public static void touch(ReferenceCounted byteBuf, String hint, String filterName) {
if (isAdvancedLeakDetection) {
byteBuf.touch(hint + filterName);
}
}
public static void touch(HttpResponse originResponse, String hint, ZuulMessage msg) {
if (isAdvancedLeakDetection && originResponse instanceof ReferenceCounted) {
((ReferenceCounted) originResponse).touch(hint + msg);
}
}
}
| 6,225 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/CategorizedThreadFactory.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import io.netty.util.concurrent.FastThreadLocalThread;
import java.util.concurrent.ThreadFactory;
/**
* User: Mike Smith
* Date: 6/8/16
* Time: 11:49 AM
*/
public class CategorizedThreadFactory implements ThreadFactory {
private String category;
private int num = 0;
public CategorizedThreadFactory(String category) {
super();
this.category = category;
}
@Override
public Thread newThread(final Runnable r) {
final FastThreadLocalThread t = new FastThreadLocalThread(r, category + "-" + num++);
return t;
}
}
| 6,226 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/Http1ConnectionExpiryHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import io.netty.handler.codec.http.HttpResponse;
/**
* User: michaels@netflix.com
* Date: 2/8/17
* Time: 9:58 AM
*/
public class Http1ConnectionExpiryHandler extends AbstrHttpConnectionExpiryHandler {
public Http1ConnectionExpiryHandler(int maxRequests, int maxRequestsUnderBrownout, int maxExpiry) {
super(ConnectionCloseType.GRACEFUL, maxRequestsUnderBrownout, maxRequests, maxExpiry);
}
@Override
protected boolean isResponseHeaders(Object msg) {
return msg instanceof HttpResponse;
}
}
| 6,227 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/LeastConnsEventLoopChooserFactory.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common;
import com.netflix.netty.common.metrics.EventLoopGroupMetrics;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.EventExecutorChooserFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
/**
* User: michaels@netflix.com
* Date: 2/7/17
* Time: 2:44 PM
*/
public class LeastConnsEventLoopChooserFactory implements EventExecutorChooserFactory {
private static final Logger LOG = LoggerFactory.getLogger(LeastConnsEventLoopChooserFactory.class);
private final EventLoopGroupMetrics groupMetrics;
public LeastConnsEventLoopChooserFactory(EventLoopGroupMetrics groupMetrics) {
this.groupMetrics = groupMetrics;
}
@Override
public EventExecutorChooser newChooser(EventExecutor[] executors) {
return new LeastConnsEventExecutorChooser(executors, groupMetrics);
}
private static class LeastConnsEventExecutorChooser implements EventExecutorChooser {
private final List<EventExecutor> executors;
private final EventLoopGroupMetrics groupMetrics;
public LeastConnsEventExecutorChooser(EventExecutor[] executors, final EventLoopGroupMetrics groupMetrics) {
this.executors = Arrays.asList(executors);
this.groupMetrics = groupMetrics;
}
@Override
public EventExecutor next() {
return chooseWithLeastConns();
}
private EventExecutor chooseWithLeastConns() {
EventExecutor leastExec = null;
int leastValue = Integer.MAX_VALUE;
Map<Thread, Integer> connsPer = groupMetrics.connectionsPerEventLoop();
// Shuffle the list of executors each time so that if they all have the same number of connections, then
// we don't favour the 1st one.
Collections.shuffle(executors, ThreadLocalRandom.current());
for (EventExecutor executor : executors) {
int value = connsPer.getOrDefault(executor, 0);
if (value < leastValue) {
leastValue = value;
leastExec = executor;
}
}
// If none chosen, then just use first.
if (leastExec == null) {
leastExec = executors.get(0);
}
if (LOG.isDebugEnabled()) {
LOG.debug(
"Chose eventloop: {}, leastValue={}, connsPer={}",
String.valueOf(leastExec),
leastValue,
String.valueOf(connsPer));
}
return leastExec;
}
}
}
| 6,228 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/metrics/HttpMetricsChannelHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.metrics;
import com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent;
import com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason;
import com.netflix.netty.common.HttpServerLifecycleChannelHandler;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Gauge;
import com.netflix.spectator.api.Registry;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import java.util.concurrent.atomic.AtomicInteger;
/**
* User: michaels@netflix.com
* Date: 4/14/16
* Time: 3:51 PM
*/
@ChannelHandler.Sharable
public class HttpMetricsChannelHandler extends ChannelInboundHandlerAdapter {
private static final AttributeKey<Object> ATTR_REQ_INFLIGHT = AttributeKey.newInstance("_httpmetrics_inflight");
private static final Object INFLIGHT = "is_inflight";
private static final AttributeKey<AtomicInteger> ATTR_CURRENT_REQS =
AttributeKey.newInstance("_server_http_current_count");
private final AtomicInteger currentRequests = new AtomicInteger(0);
private final Registry registry;
private final Gauge currentRequestsGauge;
private final Counter unSupportedPipeliningCounter;
public HttpMetricsChannelHandler(Registry registry, String name, String id) {
super();
this.registry = registry;
this.currentRequestsGauge =
this.registry.gauge(this.registry.createId(name + ".http.requests.current", "id", id));
this.unSupportedPipeliningCounter = this.registry.counter(name + ".http.requests.pipelining.dropped", "id", id);
}
public static int getInflightRequestCountFromChannel(Channel ch) {
AtomicInteger current = ch.attr(ATTR_CURRENT_REQS).get();
return current == null ? 0 : current.get();
}
public int getInflightRequestsCount() {
return currentRequests.get();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// Store a ref to the count of current inflight requests onto this channel. So that
// other code can query it using getInflightRequestCountFromChannel().
ctx.channel().attr(ATTR_CURRENT_REQS).set(currentRequests);
super.channelActive(ctx);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof HttpServerLifecycleChannelHandler.StartEvent) {
incrementCurrentRequestsInFlight(ctx);
} else if (evt instanceof HttpServerLifecycleChannelHandler.CompleteEvent
&& ((CompleteEvent) evt).getReason() == CompleteReason.PIPELINE_REJECT) {
unSupportedPipeliningCounter.increment();
} else if (evt instanceof HttpServerLifecycleChannelHandler.CompleteEvent) {
decrementCurrentRequestsIfOneInflight(ctx);
}
super.userEventTriggered(ctx, evt);
}
private void incrementCurrentRequestsInFlight(ChannelHandlerContext ctx) {
currentRequestsGauge.set(currentRequests.incrementAndGet());
ctx.channel().attr(ATTR_REQ_INFLIGHT).set(INFLIGHT);
}
private void decrementCurrentRequestsIfOneInflight(ChannelHandlerContext ctx) {
if (ctx.channel().attr(ATTR_REQ_INFLIGHT).getAndSet(null) != null) {
currentRequestsGauge.set(currentRequests.decrementAndGet());
}
}
}
| 6,229 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/metrics/InstrumentedResourceLeakDetector.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.metrics;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.zuul.netty.SpectatorUtils;
import io.netty.util.ResourceLeakDetector;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Pluggable ResourceLeakDetector to track metrics for leaks
*
* Author: Arthur Gonigberg
* Date: September 20, 2016
*/
public class InstrumentedResourceLeakDetector<T> extends ResourceLeakDetector<T> {
private final AtomicInteger instancesLeakCounter;
@VisibleForTesting
final AtomicInteger leakCounter;
public InstrumentedResourceLeakDetector(Class<?> resourceType, int samplingInterval) {
super(resourceType, samplingInterval);
this.instancesLeakCounter = SpectatorUtils.newGauge(
"NettyLeakDetector_instances", resourceType.getSimpleName(), new AtomicInteger());
this.leakCounter =
SpectatorUtils.newGauge("NettyLeakDetector", resourceType.getSimpleName(), new AtomicInteger());
}
public InstrumentedResourceLeakDetector(Class<?> resourceType, int samplingInterval, long maxActive) {
this(resourceType, samplingInterval);
}
@Override
protected void reportTracedLeak(String resourceType, String records) {
super.reportTracedLeak(resourceType, records);
leakCounter.incrementAndGet();
resetReportedLeaks();
}
@Override
protected void reportUntracedLeak(String resourceType) {
super.reportUntracedLeak(resourceType);
leakCounter.incrementAndGet();
resetReportedLeaks();
}
/**
* This private field in the superclass needs to be reset so that we can continue reporting leaks even
* if they're duplicates. This is ugly but ideally should not be called frequently (or at all).
*/
private void resetReportedLeaks() {
try {
Field reportedLeaks = ResourceLeakDetector.class.getDeclaredField("reportedLeaks");
reportedLeaks.setAccessible(true);
Object f = reportedLeaks.get(this);
if (f instanceof Map) {
((Map) f).clear();
}
} catch (Throwable t) {
// do nothing
}
}
}
| 6,230 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/metrics/PerEventLoopMetricsChannelHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.metrics;
import com.netflix.netty.common.HttpLifecycleChannelHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
/**
* User: michaels@netflix.com
* Date: 2/6/17
* Time: 2:21 PM
*/
public class PerEventLoopMetricsChannelHandler {
private static final AttributeKey<Object> ATTR_REQ_INFLIGHT =
AttributeKey.newInstance("_eventloop_metrics_inflight");
private static final Object INFLIGHT = "eventloop_is_inflight";
private final EventLoopGroupMetrics groupMetrics;
public PerEventLoopMetricsChannelHandler(EventLoopGroupMetrics groupMetrics) {
this.groupMetrics = groupMetrics;
}
@ChannelHandler.Sharable
public class Connections extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
groupMetrics.getForCurrentEventLoop().incrementCurrentConnections();
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
try {
super.channelInactive(ctx);
} finally {
groupMetrics.getForCurrentEventLoop().decrementCurrentConnections();
}
}
}
@ChannelHandler.Sharable
public class HttpRequests extends ChannelInboundHandlerAdapter {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof HttpLifecycleChannelHandler.StartEvent) {
incrementCurrentRequestsInFlight(ctx);
} else if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent) {
decrementCurrentRequestsIfOneInflight(ctx);
}
super.userEventTriggered(ctx, evt);
}
private void incrementCurrentRequestsInFlight(ChannelHandlerContext ctx) {
groupMetrics.getForCurrentEventLoop().incrementCurrentRequests();
ctx.channel().attr(ATTR_REQ_INFLIGHT).set(INFLIGHT);
}
private void decrementCurrentRequestsIfOneInflight(ChannelHandlerContext ctx) {
if (ctx.channel().attr(ATTR_REQ_INFLIGHT).getAndSet(null) != null) {
groupMetrics.getForCurrentEventLoop().decrementCurrentRequests();
}
}
}
}
| 6,231 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/metrics/HttpBodySizeRecordingChannelHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.metrics;
import com.netflix.netty.common.HttpLifecycleChannelHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.util.AttributeKey;
import javax.inject.Provider;
/**
* User: michaels@netflix.com
* Date: 4/14/16
* Time: 3:51 PM
*/
public final class HttpBodySizeRecordingChannelHandler {
private static final AttributeKey<State> ATTR_STATE = AttributeKey.newInstance("_http_body_size_state");
public static Provider<Long> getCurrentInboundBodySize(Channel ch) {
return new InboundBodySizeProvider(ch);
}
public static Provider<Long> getCurrentOutboundBodySize(Channel ch) {
return new OutboundBodySizeProvider(ch);
}
private static State getOrCreateCurrentState(Channel ch) {
State state = ch.attr(ATTR_STATE).get();
if (state == null) {
state = createNewState(ch);
}
return state;
}
private static State createNewState(Channel ch) {
State state = new State();
ch.attr(ATTR_STATE).set(state);
return state;
}
public static final class InboundChannelHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
State state = null;
// Reset the state as each new inbound request comes in.
if (msg instanceof HttpRequest) {
state = createNewState(ctx.channel());
}
// Update the inbound body size with this chunk.
if (msg instanceof HttpContent) {
if (state == null) {
state = getOrCreateCurrentState(ctx.channel());
}
state.inboundBodySize += ((HttpContent) msg).content().readableBytes();
}
super.channelRead(ctx, msg);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
try {
super.userEventTriggered(ctx, evt);
} finally {
if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent) {
ctx.channel().attr(ATTR_STATE).set(null);
}
}
}
}
public static final class OutboundChannelHandler extends ChannelOutboundHandlerAdapter {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
State state = null;
// Reset the state as each new outbound request goes out.
if (msg instanceof HttpRequest) {
state = createNewState(ctx.channel());
}
// Update the outbound body size with this chunk.
if (msg instanceof HttpContent) {
if (state == null) {
state = getOrCreateCurrentState(ctx.channel());
}
state.outboundBodySize += ((HttpContent) msg).content().readableBytes();
}
super.write(ctx, msg, promise);
}
}
private static class State {
long inboundBodySize = 0;
long outboundBodySize = 0;
}
static class InboundBodySizeProvider implements Provider<Long> {
private final Channel channel;
public InboundBodySizeProvider(Channel channel) {
this.channel = channel;
}
@Override
public Long get() {
State state = getOrCreateCurrentState(channel);
return state == null ? 0 : state.inboundBodySize;
}
}
static class OutboundBodySizeProvider implements Provider<Long> {
private final Channel channel;
public OutboundBodySizeProvider(Channel channel) {
this.channel = channel;
}
@Override
public Long get() {
State state = getOrCreateCurrentState(channel);
return state == null ? 0 : state.outboundBodySize;
}
}
}
| 6,232 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/metrics/Http2MetricsChannelHandlers.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.metrics;
import com.netflix.spectator.api.Registry;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.Http2Exception;
import io.netty.handler.codec.http2.Http2Frame;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import io.netty.handler.codec.http2.Http2ResetFrame;
public class Http2MetricsChannelHandlers {
private final Inbound inbound;
private final Outbound outbound;
public Http2MetricsChannelHandlers(Registry registry, String metricPrefix, String metricId) {
super();
this.inbound = new Inbound(registry, metricId, metricPrefix);
this.outbound = new Outbound(registry, metricId, metricPrefix);
}
public Inbound inbound() {
return inbound;
}
public Outbound outbound() {
return outbound;
}
protected static void incrementErrorCounter(
Registry registry, String counterName, String metricId, Http2Exception h2e) {
String h2Error = h2e.error() != null ? h2e.error().name() : "NA";
String exceptionName = h2e.getClass().getSimpleName();
registry.counter(counterName, "id", metricId, "error", h2Error, "exception", exceptionName)
.increment();
}
protected static void incrementCounter(Registry registry, String counterName, String metricId, Http2Frame frame) {
long errorCode;
if (frame instanceof Http2ResetFrame) {
errorCode = ((Http2ResetFrame) frame).errorCode();
} else if (frame instanceof Http2GoAwayFrame) {
errorCode = ((Http2GoAwayFrame) frame).errorCode();
} else {
errorCode = -1;
}
registry.counter(counterName, "id", metricId, "frame", frame.name(), "error_code", Long.toString(errorCode))
.increment();
}
@ChannelHandler.Sharable
private static class Inbound extends ChannelInboundHandlerAdapter {
private final Registry registry;
private final String metricId;
private final String frameCounterName;
private final String errorCounterName;
public Inbound(Registry registry, String metricId, String metricPrefix) {
this.registry = registry;
this.metricId = metricId;
this.frameCounterName = metricPrefix + ".http2.frame.inbound";
this.errorCounterName = metricPrefix + ".http2.error.inbound";
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
if (msg instanceof Http2Frame) {
incrementCounter(registry, frameCounterName, metricId, (Http2Frame) msg);
}
} finally {
super.channelRead(ctx, msg);
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
try {
if (evt instanceof Http2Frame) {
incrementCounter(registry, frameCounterName, metricId, (Http2Frame) evt);
}
} finally {
super.userEventTriggered(ctx, evt);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
try {
if (cause instanceof Http2Exception) {
incrementErrorCounter(registry, errorCounterName, metricId, (Http2Exception) cause);
}
} finally {
super.exceptionCaught(ctx, cause);
}
}
}
@ChannelHandler.Sharable
private static class Outbound extends ChannelOutboundHandlerAdapter {
private final Registry registry;
private final String metricId;
private final String frameCounterName;
private final String errorCounterName;
public Outbound(Registry registry, String metricId, String metricPrefix) {
this.registry = registry;
this.metricId = metricId;
this.frameCounterName = metricPrefix + ".http2.frame.outbound";
this.errorCounterName = metricPrefix + ".http2.error.outbound";
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
super.write(ctx, msg, promise);
if (msg instanceof Http2Frame) {
incrementCounter(registry, frameCounterName, metricId, (Http2Frame) msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
try {
if (cause instanceof Http2Exception) {
incrementErrorCounter(registry, errorCounterName, metricId, (Http2Exception) cause);
}
} finally {
super.exceptionCaught(ctx, cause);
}
}
}
}
| 6,233 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/metrics/EventLoopGroupMetrics.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.metrics;
import com.netflix.spectator.api.Registry;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.HashMap;
import java.util.Map;
/**
* User: michaels@netflix.com
* Date: 2/7/17
* Time: 3:17 PM
*/
@Singleton
public class EventLoopGroupMetrics {
private final ThreadLocal<EventLoopMetrics> metricsForCurrentThread;
private final Map<Thread, EventLoopMetrics> byEventLoop = new HashMap<>();
private final Registry registry;
@Inject
public EventLoopGroupMetrics(Registry registry) {
this.registry = registry;
this.metricsForCurrentThread = ThreadLocal.withInitial(() -> {
String name = nameForCurrentEventLoop();
EventLoopMetrics metrics = new EventLoopMetrics(registry, name);
byEventLoop.put(Thread.currentThread(), metrics);
return metrics;
});
}
public Map<Thread, Integer> connectionsPerEventLoop() {
Map<Thread, Integer> map = new HashMap<>(byEventLoop.size());
for (Map.Entry<Thread, EventLoopMetrics> entry : byEventLoop.entrySet()) {
map.put(entry.getKey(), entry.getValue().currentConnectionsCount());
}
return map;
}
public Map<Thread, Integer> httpRequestsPerEventLoop() {
Map<Thread, Integer> map = new HashMap<>(byEventLoop.size());
for (Map.Entry<Thread, EventLoopMetrics> entry : byEventLoop.entrySet()) {
map.put(entry.getKey(), entry.getValue().currentHttpRequestsCount());
}
return map;
}
public EventLoopMetrics getForCurrentEventLoop() {
return metricsForCurrentThread.get();
}
private static String nameForCurrentEventLoop() {
// We're relying on the knowledge that we name the eventloop threads consistently.
String threadName = Thread.currentThread().getName();
String parts[] = threadName.split("-ClientToZuulWorker-");
if (parts.length == 2) {
return parts[1];
}
return threadName;
}
interface EventLoopInfo {
int currentConnectionsCount();
int currentHttpRequestsCount();
}
}
| 6,234 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/metrics/EventLoopMetrics.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.metrics;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import java.util.concurrent.atomic.AtomicInteger;
/**
* User: michaels@netflix.com
* Date: 2/7/17
* Time: 3:18 PM
*/
public class EventLoopMetrics implements EventLoopGroupMetrics.EventLoopInfo {
private final String name;
public final AtomicInteger currentRequests = new AtomicInteger(0);
public final AtomicInteger currentConnections = new AtomicInteger(0);
private final Registry registry;
private final Id currentRequestsId;
private final Id currentConnectionsId;
public EventLoopMetrics(Registry registry, String eventLoopName) {
this.name = eventLoopName;
this.registry = registry;
this.currentRequestsId = this.registry.createId("server.eventloop.http.requests.current");
this.currentConnectionsId = this.registry.createId("server.eventloop.connections.current");
}
@Override
public int currentConnectionsCount() {
return currentConnections.get();
}
@Override
public int currentHttpRequestsCount() {
return currentRequests.get();
}
public void incrementCurrentRequests() {
int value = this.currentRequests.incrementAndGet();
updateGauge(currentRequestsId, value);
}
public void decrementCurrentRequests() {
int value = this.currentRequests.decrementAndGet();
updateGauge(currentRequestsId, value);
}
public void incrementCurrentConnections() {
int value = this.currentConnections.incrementAndGet();
updateGauge(currentConnectionsId, value);
}
public void decrementCurrentConnections() {
int value = this.currentConnections.decrementAndGet();
updateGauge(currentConnectionsId, value);
}
private void updateGauge(Id gaugeId, int value) {
registry.gauge(gaugeId.withTag("eventloop", name)).set(value);
}
}
| 6,235 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/ssl/SslHandshakeInfo.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.ssl;
import io.netty.handler.ssl.ClientAuth;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
/**
* User: michaels@netflix.com Date: 3/29/16 Time: 11:06 AM
*/
public class SslHandshakeInfo {
private final String protocol;
private final String cipherSuite;
private final ClientAuth clientAuthRequirement;
private final Certificate serverCertificate;
private final X509Certificate clientCertificate;
private final boolean isOfIntermediary;
public SslHandshakeInfo(
boolean isOfIntermediary,
String protocol,
String cipherSuite,
ClientAuth clientAuthRequirement,
Certificate serverCertificate,
X509Certificate clientCertificate) {
this.protocol = protocol;
this.cipherSuite = cipherSuite;
this.clientAuthRequirement = clientAuthRequirement;
this.serverCertificate = serverCertificate;
this.clientCertificate = clientCertificate;
this.isOfIntermediary = isOfIntermediary;
}
public boolean isOfIntermediary() {
return isOfIntermediary;
}
public String getProtocol() {
return protocol;
}
public String getCipherSuite() {
return cipherSuite;
}
public ClientAuth getClientAuthRequirement() {
return clientAuthRequirement;
}
public Certificate getServerCertificate() {
return serverCertificate;
}
public X509Certificate getClientCertificate() {
return clientCertificate;
}
@Override
public String toString() {
return "SslHandshakeInfo{" + "protocol='"
+ protocol + '\'' + ", cipherSuite='"
+ cipherSuite + '\'' + ", clientAuthRequirement="
+ clientAuthRequirement + ", serverCertificate="
+ serverCertificate + ", clientCertificate="
+ clientCertificate + ", isOfIntermediary="
+ isOfIntermediary + '}';
}
}
| 6,236 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/ssl/ServerSslConfig.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.ssl;
import com.netflix.config.DynamicLongProperty;
import io.netty.handler.ssl.ClientAuth;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
/**
* User: michaels@netflix.com
* Date: 8/16/16
* Time: 2:40 PM
*/
public class ServerSslConfig {
private static final DynamicLongProperty DEFAULT_SESSION_TIMEOUT =
new DynamicLongProperty("server.ssl.session.timeout", (18 * 60)); // 18 hours
private static final String[] DEFAULT_CIPHERS;
static {
try {
SSLContext context = SSLContext.getDefault();
SSLSocketFactory sf = context.getSocketFactory();
DEFAULT_CIPHERS = sf.getSupportedCipherSuites();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private final String[] protocols;
private final List<String> ciphers;
private final File certChainFile;
private final File keyFile;
private final ClientAuth clientAuth;
private final File clientAuthTrustStoreFile;
private final String clientAuthTrustStorePassword;
private final File clientAuthTrustStorePasswordFile;
private final long sessionTimeout;
private final boolean sessionTicketsEnabled;
public ServerSslConfig(String[] protocols, String[] ciphers, File certChainFile, File keyFile) {
this(protocols, ciphers, certChainFile, keyFile, ClientAuth.NONE, null, (File) null, false);
}
public ServerSslConfig(
String[] protocols, String[] ciphers, File certChainFile, File keyFile, ClientAuth clientAuth) {
this(protocols, ciphers, certChainFile, keyFile, clientAuth, null, (File) null, true);
}
public ServerSslConfig(
String[] protocols,
String[] ciphers,
File certChainFile,
File keyFile,
ClientAuth clientAuth,
File clientAuthTrustStoreFile,
File clientAuthTrustStorePasswordFile,
boolean sessionTicketsEnabled) {
this.protocols = protocols;
this.ciphers = ciphers != null ? Arrays.asList(ciphers) : null;
this.certChainFile = certChainFile;
this.keyFile = keyFile;
this.clientAuth = clientAuth;
this.clientAuthTrustStoreFile = clientAuthTrustStoreFile;
this.clientAuthTrustStorePassword = null;
this.clientAuthTrustStorePasswordFile = clientAuthTrustStorePasswordFile;
this.sessionTimeout = DEFAULT_SESSION_TIMEOUT.get();
this.sessionTicketsEnabled = sessionTicketsEnabled;
}
public ServerSslConfig(
String[] protocols,
String[] ciphers,
File certChainFile,
File keyFile,
ClientAuth clientAuth,
File clientAuthTrustStoreFile,
String clientAuthTrustStorePassword,
boolean sessionTicketsEnabled) {
this.protocols = protocols;
this.ciphers = Arrays.asList(ciphers);
this.certChainFile = certChainFile;
this.keyFile = keyFile;
this.clientAuth = clientAuth;
this.clientAuthTrustStoreFile = clientAuthTrustStoreFile;
this.clientAuthTrustStorePassword = clientAuthTrustStorePassword;
this.clientAuthTrustStorePasswordFile = null;
this.sessionTimeout = DEFAULT_SESSION_TIMEOUT.get();
this.sessionTicketsEnabled = sessionTicketsEnabled;
}
public static String[] getDefaultCiphers() {
return DEFAULT_CIPHERS;
}
public static ServerSslConfig withDefaultCiphers(File certChainFile, File keyFile, String... protocols) {
return new ServerSslConfig(protocols, getDefaultCiphers(), certChainFile, keyFile);
}
public String[] getProtocols() {
return protocols;
}
public List<String> getCiphers() {
return ciphers;
}
public File getCertChainFile() {
return certChainFile;
}
public File getKeyFile() {
return keyFile;
}
public ClientAuth getClientAuth() {
return clientAuth;
}
public File getClientAuthTrustStoreFile() {
return clientAuthTrustStoreFile;
}
public String getClientAuthTrustStorePassword() {
return clientAuthTrustStorePassword;
}
public File getClientAuthTrustStorePasswordFile() {
return clientAuthTrustStorePasswordFile;
}
public long getSessionTimeout() {
return sessionTimeout;
}
public boolean sessionTicketsEnabled() {
return sessionTicketsEnabled;
}
@Override
public String toString() {
return "ServerSslConfig{" + "protocols="
+ Arrays.toString(protocols) + ", ciphers="
+ ciphers + ", certChainFile="
+ certChainFile + ", keyFile="
+ keyFile + ", clientAuth="
+ clientAuth + ", clientAuthTrustStoreFile="
+ clientAuthTrustStoreFile + ", sessionTimeout="
+ sessionTimeout + ", sessionTicketsEnabled="
+ sessionTicketsEnabled + '}';
}
}
| 6,237 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/throttle/MaxInboundConnectionsHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.throttle;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import com.netflix.zuul.passport.CurrentPassport;
import com.netflix.zuul.passport.PassportState;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Closes any incoming new connections if current count is above a configured threshold.
*
* When a connection is throttled, the channel is closed, and then a CONNECTION_THROTTLED_EVENT event is fired
* not notify any other interested handlers.
*
*/
@ChannelHandler.Sharable
public class MaxInboundConnectionsHandler extends ChannelInboundHandlerAdapter {
public static final AttributeKey<Boolean> ATTR_CH_THROTTLED = AttributeKey.newInstance("_channel_throttled");
private static final Logger LOG = LoggerFactory.getLogger(MaxInboundConnectionsHandler.class);
private static final AtomicInteger connections = new AtomicInteger(0);
private final Counter connectionThrottled;
private final int maxConnections;
public MaxInboundConnectionsHandler(Registry registry, String metricId, int maxConnections) {
this.maxConnections = maxConnections;
this.connectionThrottled = registry.counter("server.connections.throttled", "id", metricId);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
if (maxConnections > 0) {
int currentCount = connections.getAndIncrement();
if (currentCount + 1 > maxConnections) {
LOG.warn(
"Throttling incoming connection as above configured max connections threshold of {}",
maxConnections);
Channel channel = ctx.channel();
channel.attr(ATTR_CH_THROTTLED).set(Boolean.TRUE);
CurrentPassport.fromChannel(channel).add(PassportState.SERVER_CH_THROTTLING);
channel.close();
connectionThrottled.increment();
}
}
super.channelActive(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (ctx.channel().attr(ATTR_CH_THROTTLED).get() != null) {
// Discard this msg as channel is in process of being closed.
ReferenceCountUtil.safeRelease(msg);
} else {
super.channelRead(ctx, msg);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
if (maxConnections > 0) {
connections.decrementAndGet();
}
super.channelInactive(ctx);
}
}
| 6,238 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/throttle/RequestRejectedEvent.java | /*
* Copyright 2020 Netflix, Inc.
*
* 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 com.netflix.netty.common.throttle;
import com.netflix.zuul.stats.status.StatusCategory;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
public final class RequestRejectedEvent {
private final HttpRequest request;
private final StatusCategory nfStatus;
private final HttpResponseStatus httpStatus;
private final String reason;
public RequestRejectedEvent(
HttpRequest request, StatusCategory nfStatus, HttpResponseStatus httpStatus, String reason) {
this.request = request;
this.nfStatus = nfStatus;
this.httpStatus = httpStatus;
this.reason = reason;
}
public HttpRequest request() {
return request;
}
public StatusCategory getNfStatus() {
return nfStatus;
}
public HttpResponseStatus getHttpStatus() {
return httpStatus;
}
public String getReason() {
return reason;
}
}
| 6,239 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/throttle/RejectionUtils.java | /*
* Copyright 2020 Netflix, Inc.
*
* 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 com.netflix.netty.common.throttle;
import com.netflix.netty.common.ConnectionCloseChannelAttributes;
import com.netflix.netty.common.proxyprotocol.HAProxyMessageChannelHandler;
import com.netflix.zuul.passport.CurrentPassport;
import com.netflix.zuul.passport.PassportState;
import com.netflix.zuul.stats.status.StatusCategory;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.haproxy.HAProxyProtocolVersion;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.ReferenceCountUtil;
import javax.annotation.Nullable;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* A collection of rejection related utilities useful for failing requests. These are tightly coupled with the channel
* pipeline, but can be called from different handlers.
*/
public final class RejectionUtils {
// TODO(carl-mastrangelo): add tests for this.
public static final HttpResponseStatus REJECT_CLOSING_STATUS = new HttpResponseStatus(999, "Closing(Rejection)");
/**
* Closes the connection without sending a response, and fires a {@link RequestRejectedEvent} back up the pipeline.
*
* @param nfStatus the status to use for metric reporting
* @param reason the reason for rejecting the request. This is not sent back to the client.
* @param request the request that is being rejected.
* @param injectedLatencyMillis optional parameter to delay sending a response. The reject notification is still
* sent up the pipeline.
*/
public static void rejectByClosingConnection(
ChannelHandlerContext ctx,
StatusCategory nfStatus,
String reason,
HttpRequest request,
@Nullable Integer injectedLatencyMillis) {
if (injectedLatencyMillis != null && injectedLatencyMillis > 0) {
// Delay closing the connection for configured time.
ctx.executor()
.schedule(
() -> {
CurrentPassport.fromChannel(ctx.channel()).add(PassportState.SERVER_CH_REJECTING);
ctx.close();
},
injectedLatencyMillis,
TimeUnit.MILLISECONDS);
} else {
// Close the connection immediately.
CurrentPassport.fromChannel(ctx.channel()).add(PassportState.SERVER_CH_REJECTING);
ctx.close();
}
// Notify other handlers that we've rejected this request.
notifyHandlers(ctx, nfStatus, REJECT_CLOSING_STATUS, reason, request);
}
/**
* Sends a rejection response back to the client, and fires a {@link RequestRejectedEvent} back up the pipeline.
*
* @param ctx the channel handler processing the request
* @param nfStatus the status to use for metric reporting
* @param reason the reason for rejecting the request. This is not sent back to the client.
* @param request the request that is being rejected.
* @param injectedLatencyMillis optional parameter to delay sending a response. The reject notification is still
* sent up the pipeline.
* @param rejectedCode the HTTP code to send back to the client.
* @param rejectedBody the HTTP body to be sent back. It is assumed to be of type text/plain.
* @param rejectionHeaders additional HTTP headers to add to the rejection response
*/
public static void sendRejectionResponse(
ChannelHandlerContext ctx,
StatusCategory nfStatus,
String reason,
HttpRequest request,
@Nullable Integer injectedLatencyMillis,
HttpResponseStatus rejectedCode,
String rejectedBody,
Map<String, String> rejectionHeaders) {
boolean shouldClose = closeConnectionAfterReject(ctx.channel());
// Write out a rejection response message.
FullHttpResponse response = createRejectionResponse(rejectedCode, rejectedBody, shouldClose, rejectionHeaders);
if (injectedLatencyMillis != null && injectedLatencyMillis > 0) {
// Delay writing the response for configured time.
ctx.executor()
.schedule(
() -> {
CurrentPassport.fromChannel(ctx.channel()).add(PassportState.IN_REQ_REJECTED);
ctx.writeAndFlush(response);
},
injectedLatencyMillis,
TimeUnit.MILLISECONDS);
} else {
// Write the response immediately.
CurrentPassport.fromChannel(ctx.channel()).add(PassportState.IN_REQ_REJECTED);
ctx.writeAndFlush(response);
}
// Notify other handlers that we've rejected this request.
notifyHandlers(ctx, nfStatus, rejectedCode, reason, request);
}
/**
* Marks the given channel for being closed after the next response.
*
* @param ctx the channel handler processing the request
*/
public static void allowThenClose(ChannelHandlerContext ctx) {
// Just flag this channel to be closed after response complete.
ctx.channel()
.attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE)
.set(ctx.newPromise());
// And allow this request through without rejecting.
}
/**
* Throttle either by sending rejection response message, or by closing the connection now, or just drop the
* message. Only call this if ThrottleResult.shouldThrottle() returned {@code true}.
*
* @param ctx the channel handler processing the request
* @param msg the request that is being rejected.
* @param rejectionType the type of rejection
* @param nfStatus the status to use for metric reporting
* @param reason the reason for rejecting the request. This is not sent back to the client.
* @param injectedLatencyMillis optional parameter to delay sending a response. The reject notification is still
* sent up the pipeline.
* @param rejectedCode the HTTP code to send back to the client.
* @param rejectedBody the HTTP body to be sent back. It is assumed to be of type text/plain.
* @param rejectionHeaders additional HTTP headers to add to the rejection response
*/
public static void handleRejection(
ChannelHandlerContext ctx,
Object msg,
RejectionType rejectionType,
StatusCategory nfStatus,
String reason,
@Nullable Integer injectedLatencyMillis,
HttpResponseStatus rejectedCode,
String rejectedBody,
Map<String, String> rejectionHeaders)
throws Exception {
boolean shouldDropMessage = false;
if (rejectionType == RejectionType.REJECT || rejectionType == RejectionType.CLOSE) {
shouldDropMessage = true;
}
boolean shouldRejectNow = false;
if (rejectionType == RejectionType.REJECT && msg instanceof LastHttpContent) {
shouldRejectNow = true;
} else if (rejectionType == RejectionType.CLOSE && msg instanceof HttpRequest) {
shouldRejectNow = true;
} else if (rejectionType == RejectionType.ALLOW_THEN_CLOSE && msg instanceof HttpRequest) {
shouldRejectNow = true;
}
if (shouldRejectNow) {
// Send a rejection response.
HttpRequest request = msg instanceof HttpRequest ? (HttpRequest) msg : null;
reject(
ctx,
rejectionType,
nfStatus,
reason,
request,
injectedLatencyMillis,
rejectedCode,
rejectedBody,
rejectionHeaders);
}
if (shouldDropMessage) {
ReferenceCountUtil.safeRelease(msg);
} else {
ctx.fireChannelRead(msg);
}
}
/**
* Switches on the rejection type to decide how to reject the request and or close the conn.
*
* @param ctx the channel handler processing the request
* @param rejectionType the type of rejection
* @param nfStatus the status to use for metric reporting
* @param reason the reason for rejecting the request. This is not sent back to the client.
* @param request the request that is being rejected.
* @param injectedLatencyMillis optional parameter to delay sending a response. The reject notification is still
* sent up the pipeline.
* @param rejectedCode the HTTP code to send back to the client.
* @param rejectedBody the HTTP body to be sent back. It is assumed to be of type text/plain.
*/
public static void reject(
ChannelHandlerContext ctx,
RejectionType rejectionType,
StatusCategory nfStatus,
String reason,
HttpRequest request,
@Nullable Integer injectedLatencyMillis,
HttpResponseStatus rejectedCode,
String rejectedBody) {
reject(
ctx,
rejectionType,
nfStatus,
reason,
request,
injectedLatencyMillis,
rejectedCode,
rejectedBody,
Collections.emptyMap());
}
/**
* Switches on the rejection type to decide how to reject the request and or close the conn.
*
* @param ctx the channel handler processing the request
* @param rejectionType the type of rejection
* @param nfStatus the status to use for metric reporting
* @param reason the reason for rejecting the request. This is not sent back to the client.
* @param request the request that is being rejected.
* @param injectedLatencyMillis optional parameter to delay sending a response. The reject notification is still
* sent up the pipeline.
* @param rejectedCode the HTTP code to send back to the client.
* @param rejectedBody the HTTP body to be sent back. It is assumed to be of type text/plain.
* @param rejectionHeaders additional HTTP headers to add to the rejection response
*/
public static void reject(
ChannelHandlerContext ctx,
RejectionType rejectionType,
StatusCategory nfStatus,
String reason,
HttpRequest request,
@Nullable Integer injectedLatencyMillis,
HttpResponseStatus rejectedCode,
String rejectedBody,
Map<String, String> rejectionHeaders) {
switch (rejectionType) {
case REJECT:
sendRejectionResponse(
ctx,
nfStatus,
reason,
request,
injectedLatencyMillis,
rejectedCode,
rejectedBody,
rejectionHeaders);
return;
case CLOSE:
rejectByClosingConnection(ctx, nfStatus, reason, request, injectedLatencyMillis);
return;
case ALLOW_THEN_CLOSE:
allowThenClose(ctx);
return;
}
throw new AssertionError("Bad rejection type: " + rejectionType);
}
private static void notifyHandlers(
ChannelHandlerContext ctx,
StatusCategory nfStatus,
HttpResponseStatus status,
String reason,
HttpRequest request) {
RequestRejectedEvent event = new RequestRejectedEvent(request, nfStatus, status, reason);
// Send this from the beginning of the pipeline, as it may be sent from the ClientRequestReceiver.
ctx.pipeline().fireUserEventTriggered(event);
}
private static boolean closeConnectionAfterReject(Channel channel) {
if (channel.hasAttr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION)) {
return HAProxyProtocolVersion.V2
== channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION)
.get();
} else {
return false;
}
}
private static FullHttpResponse createRejectionResponse(
HttpResponseStatus status,
String plaintextMessage,
boolean closeConnection,
Map<String, String> rejectionHeaders) {
ByteBuf body = Unpooled.wrappedBuffer(plaintextMessage.getBytes(StandardCharsets.UTF_8));
int length = body.readableBytes();
DefaultHttpHeaders headers = new DefaultHttpHeaders();
headers.set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=utf-8");
headers.set(HttpHeaderNames.CONTENT_LENGTH, length);
if (closeConnection) {
headers.set(HttpHeaderNames.CONNECTION, "close");
}
rejectionHeaders.forEach(headers::add);
return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, body, headers, EmptyHttpHeaders.INSTANCE);
}
private RejectionUtils() {}
}
| 6,240 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/throttle/RejectionType.java | /*
* Copyright 2020 Netflix, Inc.
*
* 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 com.netflix.netty.common.throttle;
/**
* Indicates a rejection type for DoS protection. While similar, rejection is distinct from throttling in that
* throttling is intended for non-malicious traffic.
*/
public enum RejectionType {
// "It's not you, it's me."
/**
* Indicates that the request should not be allowed. An HTTP response will be generated as a result.
*/
REJECT,
/**
* Indicates that the connection should be closed, not allowing the request to proceed. No HTTP response will be
* returned.
*/
CLOSE,
/**
* Allows the request to proceed, followed by closing the connection. This is typically used in conjunction with
* throttling handling, where the response may need to be handled by the filter chain. It is not expected that the
* request will be proxied.
*/
ALLOW_THEN_CLOSE;
}
| 6,241 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/proxyprotocol/HAProxyMessageChannelHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.proxyprotocol;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.InetAddresses;
import com.netflix.netty.common.SourceAddressChannelHandler;
import com.netflix.zuul.Attrs;
import com.netflix.zuul.netty.server.Server;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyProtocolVersion;
import io.netty.util.AttributeKey;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
/**
* Copies any decoded HAProxyMessage into the channel attributes, and doesn't pass it any further along the pipeline.
* Use in conjunction with HAProxyMessageDecoder if proxy protocol is enabled on the ELB.
*/
public final class HAProxyMessageChannelHandler extends ChannelInboundHandlerAdapter {
public static final AttributeKey<HAProxyMessage> ATTR_HAPROXY_MESSAGE =
AttributeKey.newInstance("_haproxy_message");
public static final AttributeKey<HAProxyProtocolVersion> ATTR_HAPROXY_VERSION =
AttributeKey.newInstance("_haproxy_version");
@VisibleForTesting
static final Attrs.Key<Integer> HAPM_DEST_PORT = Attrs.newKey("hapm_port");
@VisibleForTesting
static final Attrs.Key<String> HAPM_DEST_IP_VERSION = Attrs.newKey("hapm_dst_ipproto");
@VisibleForTesting
static final Attrs.Key<String> HAPM_SRC_IP_VERSION = Attrs.newKey("hapm_src_ipproto");
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HAProxyMessage) {
HAProxyMessage hapm = (HAProxyMessage) msg;
Channel channel = ctx.channel();
channel.attr(ATTR_HAPROXY_MESSAGE).set(hapm);
ctx.channel().closeFuture().addListener((ChannelFutureListener) future -> hapm.release());
channel.attr(ATTR_HAPROXY_VERSION).set(hapm.protocolVersion());
// Get the real host and port that the client connected to ELB with.
String destinationAddress = hapm.destinationAddress();
if (destinationAddress != null) {
channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS).set(destinationAddress);
SocketAddress addr;
out:
{
switch (hapm.proxiedProtocol()) {
case UNKNOWN:
throw new IllegalArgumentException("unknown proxy protocol" + destinationAddress);
case TCP4:
case TCP6:
InetSocketAddress inetAddr = new InetSocketAddress(
InetAddresses.forString(destinationAddress), hapm.destinationPort());
addr = inetAddr;
// setting PPv2 explicitly because SourceAddressChannelHandler.ATTR_LOCAL_ADDR could be PPv2
// or not
channel.attr(SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS)
.set(inetAddr);
Attrs attrs =
ctx.channel().attr(Server.CONN_DIMENSIONS).get();
if (inetAddr.getAddress() instanceof Inet4Address) {
HAPM_DEST_IP_VERSION.put(attrs, "v4");
} else if (inetAddr.getAddress() instanceof Inet6Address) {
HAPM_DEST_IP_VERSION.put(attrs, "v6");
} else {
HAPM_DEST_IP_VERSION.put(attrs, "unknown");
}
HAPM_DEST_PORT.put(attrs, hapm.destinationPort());
break out;
case UNIX_STREAM: // TODO: implement
case UDP4:
case UDP6:
case UNIX_DGRAM:
throw new IllegalArgumentException("unknown proxy protocol" + destinationAddress);
}
throw new AssertionError(hapm.proxiedProtocol());
}
channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).set(addr);
}
// Get the real client IP from the ProxyProtocol message sent by the ELB, and overwrite the SourceAddress
// channel attribute.
String sourceAddress = hapm.sourceAddress();
if (sourceAddress != null) {
channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).set(sourceAddress);
SocketAddress addr;
out:
{
switch (hapm.proxiedProtocol()) {
case UNKNOWN:
throw new IllegalArgumentException("unknown proxy protocol" + sourceAddress);
case TCP4:
case TCP6:
InetSocketAddress inetAddr;
addr = inetAddr =
new InetSocketAddress(InetAddresses.forString(sourceAddress), hapm.sourcePort());
Attrs attrs =
ctx.channel().attr(Server.CONN_DIMENSIONS).get();
if (inetAddr.getAddress() instanceof Inet4Address) {
HAPM_SRC_IP_VERSION.put(attrs, "v4");
} else if (inetAddr.getAddress() instanceof Inet6Address) {
HAPM_SRC_IP_VERSION.put(attrs, "v6");
} else {
HAPM_SRC_IP_VERSION.put(attrs, "unknown");
}
break out;
case UNIX_STREAM: // TODO: implement
case UDP4:
case UDP6:
case UNIX_DGRAM:
throw new IllegalArgumentException("unknown proxy protocol" + sourceAddress);
}
throw new AssertionError(hapm.proxiedProtocol());
}
channel.attr(SourceAddressChannelHandler.ATTR_REMOTE_ADDR).set(addr);
}
// TODO - fire an additional event to notify interested parties that we now know the IP?
// Remove ourselves (this handler) from the channel now, as no more work to do.
ctx.pipeline().remove(this);
// Do not continue propagating the message.
return;
}
}
}
| 6,242 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/proxyprotocol/StripUntrustedProxyHeadersHandler.java | /*
* Copyright 2020 Netflix, Inc.
*
* 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 com.netflix.netty.common.proxyprotocol;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Sets;
import com.netflix.config.DynamicStringListProperty;
import com.netflix.netty.common.ssl.SslHandshakeInfo;
import com.netflix.zuul.netty.server.ssl.SslHandshakeInfoHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.ssl.ClientAuth;
import io.netty.util.AsciiString;
import java.util.Collection;
import java.util.List;
/**
* Strip out any X-Forwarded-* headers from inbound http requests if connection is not trusted.
*/
@ChannelHandler.Sharable
public class StripUntrustedProxyHeadersHandler extends ChannelInboundHandlerAdapter {
private static final DynamicStringListProperty XFF_BLACKLIST =
new DynamicStringListProperty("zuul.proxy.headers.host.blacklist", "");
public enum AllowWhen {
ALWAYS,
MUTUAL_SSL_AUTH,
NEVER
}
private static final Collection<AsciiString> HEADERS_TO_STRIP = Sets.newHashSet(
new AsciiString("x-forwarded-for"),
new AsciiString("x-forwarded-port"),
new AsciiString("x-forwarded-proto"),
new AsciiString("x-forwarded-proto-version"),
new AsciiString("x-real-ip"));
private final AllowWhen allowWhen;
public StripUntrustedProxyHeadersHandler(AllowWhen allowWhen) {
this.allowWhen = allowWhen;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpRequest) {
HttpRequest req = (HttpRequest) msg;
switch (allowWhen) {
case NEVER:
stripXFFHeaders(req);
break;
case MUTUAL_SSL_AUTH:
if (!connectionIsUsingMutualSSLWithAuthEnforced(ctx.channel())) {
stripXFFHeaders(req);
} else {
checkBlacklist(req, XFF_BLACKLIST.get());
}
break;
case ALWAYS:
checkBlacklist(req, XFF_BLACKLIST.get());
break;
default:
// default to not allow.
stripXFFHeaders(req);
}
}
super.channelRead(ctx, msg);
}
@VisibleForTesting
boolean connectionIsUsingMutualSSLWithAuthEnforced(Channel ch) {
boolean is = false;
SslHandshakeInfo sslHandshakeInfo =
ch.attr(SslHandshakeInfoHandler.ATTR_SSL_INFO).get();
if (sslHandshakeInfo != null) {
if (sslHandshakeInfo.getClientAuthRequirement() == ClientAuth.REQUIRE) {
is = true;
}
}
return is;
}
@VisibleForTesting
void stripXFFHeaders(HttpRequest req) {
HttpHeaders headers = req.headers();
for (AsciiString headerName : HEADERS_TO_STRIP) {
headers.remove(headerName);
}
}
@VisibleForTesting
void checkBlacklist(HttpRequest req, List<String> blacklist) {
// blacklist headers from
if (blacklist.stream().anyMatch(h -> h.equalsIgnoreCase(req.headers().get(HttpHeaderNames.HOST)))) {
stripXFFHeaders(req);
}
}
}
| 6,243 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/proxyprotocol/ElbProxyProtocolChannelHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.proxyprotocol;
import com.google.common.base.Preconditions;
import com.netflix.netty.common.SourceAddressChannelHandler;
import com.netflix.spectator.api.Registry;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.ProtocolDetectionState;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
/**
* Decides if we need to decode a HAProxyMessage. If so, adds the decoder followed by the handler.
* Else, removes itself from the pipeline.
*/
public final class ElbProxyProtocolChannelHandler extends ChannelInboundHandlerAdapter {
public static final String NAME = ElbProxyProtocolChannelHandler.class.getSimpleName();
private final boolean withProxyProtocol;
private final Registry registry;
public ElbProxyProtocolChannelHandler(Registry registry, boolean withProxyProtocol) {
this.withProxyProtocol = withProxyProtocol;
this.registry = Preconditions.checkNotNull(registry);
}
public void addProxyProtocol(ChannelPipeline pipeline) {
pipeline.addLast(NAME, this);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!withProxyProtocol) {
ctx.pipeline().remove(this);
super.channelRead(ctx, msg);
return;
}
ProtocolDetectionState haProxyState = getDetectionState(msg);
if (haProxyState == ProtocolDetectionState.DETECTED) {
ctx.pipeline()
.addAfter(NAME, null, new HAProxyMessageChannelHandler())
.replace(this, null, new HAProxyMessageDecoder());
} else {
final int port = ctx.channel()
.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT)
.get();
// This likely means initialization was requested with proxy protocol, but we encountered a non-ppv2
// message
registry.counter(
"zuul.hapm.decode",
"success",
"false",
"port",
String.valueOf(port),
"needs_more_data",
String.valueOf(haProxyState == ProtocolDetectionState.NEEDS_MORE_DATA))
.increment();
ctx.pipeline().remove(this);
}
super.channelRead(ctx, msg);
}
private ProtocolDetectionState getDetectionState(Object msg) {
return HAProxyMessageDecoder.detectProtocol((ByteBuf) msg).state();
}
}
| 6,244 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/status/ServerStatusManager.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.status;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* User: michaels@netflix.com
* Date: 7/6/17
* Time: 3:37 PM
*/
@Singleton
public class ServerStatusManager {
private final ApplicationInfoManager applicationInfoManager;
@Inject
public ServerStatusManager(ApplicationInfoManager applicationInfoManager) {
this.applicationInfoManager = applicationInfoManager;
}
public void localStatus(InstanceInfo.InstanceStatus status) {
applicationInfoManager.setInstanceStatus(status);
}
}
| 6,245 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/http2/DynamicHttp2FrameLogger.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.http2;
import com.netflix.config.DynamicStringSetProperty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http2.Http2Flags;
import io.netty.handler.codec.http2.Http2FrameLogger;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.logging.LogLevel;
import io.netty.util.AttributeKey;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.logging.InternalLogLevel;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
public class DynamicHttp2FrameLogger extends Http2FrameLogger {
public static final AttributeKey<Object> ATTR_ENABLE = AttributeKey.valueOf("http2.frame.logger.enabled");
private static final int BUFFER_LENGTH_THRESHOLD = 64;
private static final DynamicStringSetProperty FRAMES_TO_LOG = new DynamicStringSetProperty(
"server.http2.logger.framestolog",
"SETTINGS,WINDOW_UPDATE,HEADERS,GO_AWAY,RST_STREAM,PRIORITY,PING,PUSH_PROMISE");
private final InternalLogger logger;
private final InternalLogLevel level;
public DynamicHttp2FrameLogger(LogLevel level, Class<?> clazz) {
super(level, clazz);
this.level = ObjectUtil.checkNotNull(level.toInternalLevel(), "level");
this.logger = ObjectUtil.checkNotNull(InternalLoggerFactory.getInstance(clazz), "logger");
}
protected boolean enabled(ChannelHandlerContext ctx) {
return ctx.channel().hasAttr(ATTR_ENABLE);
}
protected boolean enabled() {
return logger.isEnabled(level);
}
@Override
public void logData(
Direction direction,
ChannelHandlerContext ctx,
int streamId,
ByteBuf data,
int padding,
boolean endStream) {
if (enabled()) {
log(
direction,
"DATA",
ctx,
"streamId=%d, endStream=%b, length=%d",
streamId,
endStream,
data.readableBytes());
}
}
@Override
public void logHeaders(
Direction direction,
ChannelHandlerContext ctx,
int streamId,
Http2Headers headers,
int padding,
boolean endStream) {
if (enabled()) {
log(direction, "HEADERS", ctx, "streamId=%d, headers=%s, endStream=%b", streamId, headers, endStream);
}
}
@Override
public void logHeaders(
Direction direction,
ChannelHandlerContext ctx,
int streamId,
Http2Headers headers,
int streamDependency,
short weight,
boolean exclusive,
int padding,
boolean endStream) {
if (enabled()) {
log(
direction,
"HEADERS",
ctx,
"streamId=%d, headers=%s, streamDependency=%d, weight=%d, " + "exclusive=%b, endStream=%b",
streamId,
headers,
streamDependency,
weight,
exclusive,
endStream);
}
}
@Override
public void logPriority(
Direction direction,
ChannelHandlerContext ctx,
int streamId,
int streamDependency,
short weight,
boolean exclusive) {
if (enabled()) {
log(
direction,
"PRIORITY",
ctx,
"streamId=%d, streamDependency=%d, weight=%d, exclusive=%b",
streamId,
streamDependency,
weight,
exclusive);
}
}
@Override
public void logRstStream(Direction direction, ChannelHandlerContext ctx, int streamId, long errorCode) {
if (enabled()) {
log(direction, "RST_STREAM", ctx, "streamId=%d, errorCode=%d", streamId, errorCode);
}
}
@Override
public void logSettingsAck(Direction direction, ChannelHandlerContext ctx) {
if (enabled()) {
log(direction, "SETTINGS", ctx, "ack=true");
}
}
@Override
public void logSettings(Direction direction, ChannelHandlerContext ctx, Http2Settings settings) {
if (enabled()) {
log(direction, "SETTINGS", ctx, "ack=false, settings=%s", settings);
}
}
@Override
public void logPing(Direction direction, ChannelHandlerContext ctx, long data) {
if (enabled()) {
log(direction, "PING", ctx, "ack=false, length=%d", data);
}
}
@Override
public void logPingAck(Direction direction, ChannelHandlerContext ctx, long data) {
if (enabled()) {
log(direction, "PING", ctx, "ack=true, length=%d", data);
}
}
@Override
public void logPushPromise(
Direction direction,
ChannelHandlerContext ctx,
int streamId,
int promisedStreamId,
Http2Headers headers,
int padding) {
if (enabled()) {
log(
direction,
"PUSH_PROMISE",
ctx,
"streamId=%d, promisedStreamId=%d, headers=%s, padding=%d",
streamId,
promisedStreamId,
headers,
padding);
}
}
@Override
public void logGoAway(
Direction direction, ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData) {
if (enabled()) {
log(
direction,
"GO_AWAY",
ctx,
"lastStreamId=%d, errorCode=%d, length=%d, bytes=%s",
lastStreamId,
errorCode,
debugData.readableBytes(),
toString(debugData));
}
}
@Override
public void logWindowsUpdate(
Direction direction, ChannelHandlerContext ctx, int streamId, int windowSizeIncrement) {
if (enabled()) {
log(direction, "WINDOW_UPDATE", ctx, "streamId=%d, windowSizeIncrement=%d", streamId, windowSizeIncrement);
}
}
@Override
public void logUnknownFrame(
Direction direction,
ChannelHandlerContext ctx,
byte frameType,
int streamId,
Http2Flags flags,
ByteBuf data) {
if (enabled()) {
log(
direction,
"UNKNOWN",
ctx,
"frameType=%d, streamId=%d, flags=%d, length=%d, bytes=%s",
frameType & 0xFF,
streamId,
flags.value(),
data.readableBytes(),
toString(data));
}
}
private String toString(ByteBuf buf) {
if (level == InternalLogLevel.TRACE || buf.readableBytes() <= BUFFER_LENGTH_THRESHOLD) {
// Log the entire buffer.
return ByteBufUtil.hexDump(buf);
}
// Otherwise just log the first 64 bytes.
int length = Math.min(buf.readableBytes(), BUFFER_LENGTH_THRESHOLD);
return ByteBufUtil.hexDump(buf, buf.readerIndex(), length) + "...";
}
private void log(Direction direction, String frame, ChannelHandlerContext ctx, String format, Object... args) {
if (shouldLogFrame(frame)) {
StringBuilder b = new StringBuilder(200)
.append(direction.name())
.append(": ")
.append(frame)
.append(": ")
.append(String.format(format, args))
.append(" -- ")
.append(String.valueOf(ctx.channel()));
logger.log(level, b.toString());
}
}
protected boolean shouldLogFrame(String frame) {
return FRAMES_TO_LOG.get().contains(frame);
}
}
| 6,246 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/channel | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/channel/config/ChannelConfig.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.channel.config;
import java.util.HashMap;
/**
* User: michaels@netflix.com
* Date: 2/8/17
* Time: 6:43 PM
*/
public class ChannelConfig implements Cloneable {
private final HashMap<ChannelConfigKey, ChannelConfigValue> parameters;
public ChannelConfig() {
parameters = new HashMap<>();
}
public ChannelConfig(HashMap<ChannelConfigKey, ChannelConfigValue> parameters) {
this.parameters = (HashMap<ChannelConfigKey, ChannelConfigValue>) parameters.clone();
}
public void add(ChannelConfigValue param) {
this.parameters.put(param.key(), param);
}
public <T> void set(ChannelConfigKey<T> key, T value) {
this.parameters.put(key, new ChannelConfigValue<>(key, value));
}
public <T> T get(ChannelConfigKey<T> key) {
ChannelConfigValue<T> ccv = parameters.get(key);
T value = ccv == null ? null : (T) ccv.value();
if (value == null) {
value = key.defaultValue();
}
return value;
}
public <T> ChannelConfigValue<T> getConfig(ChannelConfigKey<T> key) {
return (ChannelConfigValue<T>) parameters.get(key);
}
public <T> boolean contains(ChannelConfigKey<T> key) {
return parameters.containsKey(key);
}
@Override
public ChannelConfig clone() {
return new ChannelConfig(parameters);
}
}
| 6,247 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/channel | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/channel/config/CommonChannelConfigKeys.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.channel.config;
import com.netflix.netty.common.proxyprotocol.StripUntrustedProxyHeadersHandler;
import com.netflix.netty.common.ssl.ServerSslConfig;
import com.netflix.zuul.netty.server.ServerTimeout;
import com.netflix.zuul.netty.ssl.SslContextFactory;
import io.netty.handler.ssl.SslContext;
import io.netty.util.AsyncMapping;
/**
* User: michaels@netflix.com
* Date: 2/8/17
* Time: 6:21 PM
*/
public class CommonChannelConfigKeys {
public static final ChannelConfigKey<Boolean> withProxyProtocol =
new ChannelConfigKey<>("withProxyProtocol", false);
public static final ChannelConfigKey<StripUntrustedProxyHeadersHandler.AllowWhen> allowProxyHeadersWhen =
new ChannelConfigKey<>("allowProxyHeadersWhen", StripUntrustedProxyHeadersHandler.AllowWhen.ALWAYS);
public static final ChannelConfigKey<Boolean> preferProxyProtocolForClientIp =
new ChannelConfigKey<>("preferProxyProtocolForClientIp", true);
/** The Idle timeout of a connection, in milliseconds */
public static final ChannelConfigKey<Integer> idleTimeout = new ChannelConfigKey<>("idleTimeout", 65000);
public static final ChannelConfigKey<ServerTimeout> serverTimeout = new ChannelConfigKey<>("serverTimeout");
/** The HTTP request read timeout, in milliseconds */
public static final ChannelConfigKey<Integer> httpRequestReadTimeout =
new ChannelConfigKey<>("httpRequestReadTimeout", 5000);
/** The maximum number of inbound connections to proxy. */
public static final ChannelConfigKey<Integer> maxConnections = new ChannelConfigKey<>("maxConnections", 20000);
public static final ChannelConfigKey<Integer> maxRequestsPerConnection =
new ChannelConfigKey<>("maxRequestsPerConnection", 4000);
public static final ChannelConfigKey<Integer> maxRequestsPerConnectionInBrownout =
new ChannelConfigKey<>("maxRequestsPerConnectionInBrownout", 100);
public static final ChannelConfigKey<Integer> connectionExpiry =
new ChannelConfigKey<>("connectionExpiry", 20 * 60 * 1000);
// SSL:
public static final ChannelConfigKey<Boolean> isSSlFromIntermediary =
new ChannelConfigKey<>("isSSlFromIntermediary", false);
public static final ChannelConfigKey<ServerSslConfig> serverSslConfig = new ChannelConfigKey<>("serverSslConfig");
public static final ChannelConfigKey<SslContextFactory> sslContextFactory =
new ChannelConfigKey<>("sslContextFactory");
public static final ChannelConfigKey<AsyncMapping<String, SslContext>> sniMapping =
new ChannelConfigKey<>("sniMapping");
// HTTP/2 specific:
public static final ChannelConfigKey<Integer> maxConcurrentStreams =
new ChannelConfigKey<>("maxConcurrentStreams", 100);
public static final ChannelConfigKey<Integer> initialWindowSize =
new ChannelConfigKey<>("initialWindowSize", 5242880); // 5MB
/* The amount of time to wait before closing a connection that has the `Connection: Close` header, in seconds */
public static final ChannelConfigKey<Integer> connCloseDelay = new ChannelConfigKey<>("connCloseDelay", 10);
public static final ChannelConfigKey<Integer> maxHttp2HeaderTableSize =
new ChannelConfigKey<>("maxHttp2HeaderTableSize", 4096);
public static final ChannelConfigKey<Integer> maxHttp2HeaderListSize =
new ChannelConfigKey<>("maxHttp2HeaderListSize");
public static final ChannelConfigKey<Boolean> http2AllowGracefulDelayed =
new ChannelConfigKey<>("http2AllowGracefulDelayed", true);
public static final ChannelConfigKey<Boolean> http2SwallowUnknownExceptionsOnConnClose =
new ChannelConfigKey<>("http2SwallowUnknownExceptionsOnConnClose", false);
}
| 6,248 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/channel | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/channel/config/ChannelConfigValue.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.channel.config;
/**
* User: michaels@netflix.com
* Date: 2/8/17
* Time: 6:41 PM
*/
public class ChannelConfigValue<T> {
private final ChannelConfigKey<T> key;
private final T value;
public ChannelConfigValue(ChannelConfigKey<T> key, T value) {
this.key = key;
this.value = value;
}
public ChannelConfigKey<T> key() {
return key;
}
public T value() {
return value;
}
}
| 6,249 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/channel | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/channel/config/ChannelConfigKey.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.channel.config;
/**
* User: michaels@netflix.com
* Date: 2/8/17
* Time: 6:17 PM
*/
public class ChannelConfigKey<T> {
private final String key;
private final T defaultValue;
public ChannelConfigKey(String key, T defaultValue) {
this.key = key;
this.defaultValue = defaultValue;
}
public ChannelConfigKey(String key) {
this.key = key;
this.defaultValue = null;
}
public String key() {
return key;
}
public T defaultValue() {
return defaultValue;
}
public boolean hasDefaultValue() {
return defaultValue != null;
}
@Override
public String toString() {
return "ChannelConfigKey{" + "key='" + key + '\'' + ", defaultValue=" + defaultValue + '}';
}
}
| 6,250 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/accesslog/AccessLogChannelHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.accesslog;
import com.netflix.netty.common.HttpLifecycleChannelHandler;
import com.netflix.netty.common.SourceAddressChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
/**
* User: michaels@netflix.com
* Date: 4/14/16
* Time: 3:51 PM
*/
public final class AccessLogChannelHandler {
private static final AttributeKey<RequestState> ATTR_REQ_STATE =
AttributeKey.newInstance("_accesslog_requeststate");
private static final Logger LOG = LoggerFactory.getLogger(AccessLogChannelHandler.class);
public static final class AccessLogInboundChannelHandler extends ChannelInboundHandlerAdapter {
private final AccessLogPublisher publisher;
public AccessLogInboundChannelHandler(AccessLogPublisher publisher) {
this.publisher = publisher;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpRequest) {
RequestState state = new RequestState();
state.request = (HttpRequest) msg;
state.startTimeNs = System.nanoTime();
state.requestBodySize = 0;
ctx.channel().attr(ATTR_REQ_STATE).set(state);
}
if (msg instanceof HttpContent) {
RequestState state = ctx.channel().attr(ATTR_REQ_STATE).get();
if (state != null) {
state.requestBodySize += ((HttpContent) msg).content().readableBytes();
}
}
super.channelRead(ctx, msg);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent) {
// Get the stored request, and remove the attr from channel to cleanup.
RequestState state = ctx.channel().attr(ATTR_REQ_STATE).get();
ctx.channel().attr(ATTR_REQ_STATE).set(null);
// Response complete, so now write to access log.
long durationNs = System.nanoTime() - state.startTimeNs;
String remoteIp = ctx.channel()
.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS)
.get();
Integer localPort = ctx.channel()
.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT)
.get();
if (state.response == null) {
LOG.debug(
"Response null in AccessLog, Complete reason={}, duration={}, url={}, method={}",
((HttpLifecycleChannelHandler.CompleteEvent) evt).getReason(),
durationNs / (1000 * 1000),
state.request != null ? state.request.uri() : "-",
state.request != null ? state.request.method() : "-");
}
publisher.log(
ctx.channel(),
state.request,
state.response,
state.dateTime,
localPort,
remoteIp,
durationNs,
state.requestBodySize,
state.responseBodySize);
}
super.userEventTriggered(ctx, evt);
}
}
public static final class AccessLogOutboundChannelHandler extends ChannelOutboundHandlerAdapter {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
RequestState state = ctx.channel().attr(ATTR_REQ_STATE).get();
if (msg instanceof HttpResponse) {
state.response = (HttpResponse) msg;
state.responseBodySize = 0;
}
if (msg instanceof HttpContent) {
state.responseBodySize += ((HttpContent) msg).content().readableBytes();
}
super.write(ctx, msg, promise);
}
}
private static class RequestState {
LocalDateTime dateTime = LocalDateTime.now();
HttpRequest request;
HttpResponse response;
long startTimeNs;
int requestBodySize = 0;
int responseBodySize = 0;
}
}
| 6,251 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common | Create_ds/zuul/zuul-core/src/main/java/com/netflix/netty/common/accesslog/AccessLogPublisher.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.netty.common.accesslog;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicStringListProperty;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.function.BiFunction;
public class AccessLogPublisher {
private static final char DELIM = '\t';
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
private static final List<String> LOG_REQ_HEADERS = new DynamicStringListProperty(
"zuul.access.log.requestheaders",
"host,x-forwarded-for,x-forwarded-proto,x-forwarded-host,x-forwarded-port,user-agent")
.get();
private static final List<String> LOG_RESP_HEADERS =
new DynamicStringListProperty("zuul.access.log.responseheaders", "server,via,content-type").get();
private static final DynamicIntProperty URI_LENGTH_LIMIT =
new DynamicIntProperty("zuul.access.log.uri.length.limit", Integer.MAX_VALUE);
private final Logger logger;
private final BiFunction<Channel, HttpRequest, String> requestIdProvider;
private static final Logger LOG = LoggerFactory.getLogger(AccessLogPublisher.class);
public AccessLogPublisher(String loggerName, BiFunction<Channel, HttpRequest, String> requestIdProvider) {
this.logger = LoggerFactory.getLogger(loggerName);
this.requestIdProvider = requestIdProvider;
}
public void log(
Channel channel,
HttpRequest request,
HttpResponse response,
LocalDateTime dateTime,
Integer localPort,
String remoteIp,
Long durationNs,
Integer requestBodySize,
Integer responseBodySize) {
StringBuilder sb = new StringBuilder();
String dateTimeStr = dateTime != null ? dateTime.format(DATE_TIME_FORMATTER) : "-----T-:-:-";
String remoteIpStr = (remoteIp != null && !remoteIp.isEmpty()) ? remoteIp : "-";
String port = localPort != null ? localPort.toString() : "-";
String method = request != null ? request.method().toString().toUpperCase() : "-";
String uri = request != null ? request.uri() : "-";
if (uri.length() > URI_LENGTH_LIMIT.get()) {
uri = uri.substring(0, URI_LENGTH_LIMIT.get());
}
String status = response != null ? String.valueOf(response.status().code()) : "-";
String requestId = null;
try {
requestId = requestIdProvider.apply(channel, request);
} catch (Exception ex) {
LOG.error(
"requestIdProvider failed in AccessLogPublisher method={}, uri={}, status={}", method, uri, status);
}
requestId = requestId != null ? requestId : "-";
// Convert duration to microseconds.
String durationStr = (durationNs != null && durationNs > 0) ? String.valueOf(durationNs / 1000) : "-";
String requestBodySizeStr = (requestBodySize != null && requestBodySize > 0) ? requestBodySize.toString() : "-";
String responseBodySizeStr =
(responseBodySize != null && responseBodySize > 0) ? responseBodySize.toString() : "-";
// Build the line.
sb.append(dateTimeStr)
.append(DELIM)
.append(remoteIpStr)
.append(DELIM)
.append(port)
.append(DELIM)
.append(method)
.append(DELIM)
.append(uri)
.append(DELIM)
.append(status)
.append(DELIM)
.append(durationStr)
.append(DELIM)
.append(responseBodySizeStr)
.append(DELIM)
.append(requestId)
.append(DELIM)
.append(requestBodySizeStr);
if (request != null && request.headers() != null) {
includeMatchingHeaders(sb, LOG_REQ_HEADERS, request.headers());
}
if (response != null && response.headers() != null) {
includeMatchingHeaders(sb, LOG_RESP_HEADERS, response.headers());
}
// Write to logger.
final String access = sb.toString();
logger.info(access);
LOG.debug(access);
}
void includeMatchingHeaders(StringBuilder builder, List<String> requiredHeaders, HttpHeaders headers) {
for (String headerName : requiredHeaders) {
String value = headerAsString(headers, headerName);
builder.append(DELIM).append('\"').append(value).append('\"');
}
}
String headerAsString(HttpHeaders headers, String headerName) {
List<String> values = headers.getAll(headerName);
return (values.size() == 0) ? "-" : String.join(",", values);
}
}
| 6,252 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/FilterFileManager.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.config.DynamicIntProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* This class manages the directory polling for changes and new Groovy filters.
* Polling interval and directories are specified in the initialization of the class, and a poller will check
* for changes and additions.
*
* @author Mikey Cohen
* Date: 12/7/11
* Time: 12:09 PM
*/
@Singleton
public class FilterFileManager {
private static final Logger LOG = LoggerFactory.getLogger(FilterFileManager.class);
private static final DynamicIntProperty FILE_PROCESSOR_THREADS =
new DynamicIntProperty("zuul.filterloader.threads", 1);
private static final DynamicIntProperty FILE_PROCESSOR_TASKS_TIMEOUT_SECS =
new DynamicIntProperty("zuul.filterloader.tasks.timeout", 120);
Thread poller;
boolean bRunning = true;
private final FilterFileManagerConfig config;
private final FilterLoader filterLoader;
private ExecutorService processFilesService;
@Inject
public FilterFileManager(FilterFileManagerConfig config, FilterLoader filterLoader) {
this.config = config;
this.filterLoader = filterLoader;
}
/**
* Initialized the GroovyFileManager.
*
* @throws Exception
*/
@Inject
public void init() throws Exception {
if (!config.enabled) {
return;
}
long startTime = System.currentTimeMillis();
ThreadFactory tf = new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("FilterFileManager_ProcessFiles-%d")
.build();
this.processFilesService = Executors.newFixedThreadPool(FILE_PROCESSOR_THREADS.get(), tf);
filterLoader.putFiltersForClasses(config.getClassNames());
manageFiles();
startPoller();
LOG.warn("Finished loading all zuul filters. Duration = {} ms.", (System.currentTimeMillis() - startTime));
}
/**
* Shuts down the poller
*/
public void shutdown() {
stopPoller();
}
void stopPoller() {
bRunning = false;
}
void startPoller() {
poller = new Thread("GroovyFilterFileManagerPoller") {
{
setDaemon(true);
}
@Override
public void run() {
while (bRunning) {
try {
sleep(config.getPollingIntervalSeconds() * 1000);
manageFiles();
} catch (Exception e) {
LOG.error("Error checking and/or loading filter files from Poller thread.", e);
}
}
}
};
poller.start();
}
/**
* Returns the directory File for a path. A Runtime Exception is thrown if the directory is in valid
*
* @param sPath
* @return a File representing the directory path
*/
public File getDirectory(String sPath) {
File directory = new File(sPath);
if (!directory.isDirectory()) {
URL resource = FilterFileManager.class.getClassLoader().getResource(sPath);
try {
directory = new File(resource.toURI());
} catch (Exception e) {
LOG.error("Error accessing directory in classloader. path={}", sPath, e);
}
if (!directory.isDirectory()) {
throw new RuntimeException(directory.getAbsolutePath() + " is not a valid directory");
}
}
return directory;
}
/**
* Returns a List<File> of all Files from all polled directories
*
* @return
*/
List<File> getFiles() {
List<File> list = new ArrayList<File>();
for (String sDirectory : config.getDirectories()) {
if (sDirectory != null) {
File directory = getDirectory(sDirectory);
File[] aFiles = directory.listFiles(config.getFilenameFilter());
if (aFiles != null) {
list.addAll(Arrays.asList(aFiles));
}
}
}
return list;
}
/**
* puts files into the FilterLoader. The FilterLoader will only add new or changed filters
*
* @param aFiles a List<File>
* @throws IOException
* @throws InstantiationException
* @throws IllegalAccessException
*/
void processGroovyFiles(List<File> aFiles) throws Exception {
List<Callable<Boolean>> tasks = new ArrayList<>();
for (File file : aFiles) {
tasks.add(() -> {
try {
return filterLoader.putFilter(file);
} catch (Exception e) {
LOG.error("Error loading groovy filter from disk! file = {}", String.valueOf(file), e);
return false;
}
});
}
processFilesService.invokeAll(tasks, FILE_PROCESSOR_TASKS_TIMEOUT_SECS.get(), TimeUnit.SECONDS);
}
void manageFiles() {
try {
List<File> aFiles = getFiles();
processGroovyFiles(aFiles);
} catch (Exception e) {
String msg = "Error updating groovy filters from disk!";
LOG.error(msg, e);
throw new RuntimeException(msg, e);
}
}
public static class FilterFileManagerConfig {
private String[] directories;
private String[] classNames;
private int pollingIntervalSeconds;
private FilenameFilter filenameFilter;
boolean enabled;
public FilterFileManagerConfig(
String[] directories, String[] classNames, int pollingIntervalSeconds, FilenameFilter filenameFilter) {
this(directories, classNames, pollingIntervalSeconds, filenameFilter, true);
}
public FilterFileManagerConfig(
String[] directories,
String[] classNames,
int pollingIntervalSeconds,
FilenameFilter filenameFilter,
boolean enabled) {
this.directories = directories;
this.classNames = classNames;
this.pollingIntervalSeconds = pollingIntervalSeconds;
this.filenameFilter = filenameFilter;
this.enabled = enabled;
}
public String[] getDirectories() {
return directories;
}
public String[] getClassNames() {
return classNames;
}
public int getPollingIntervalSeconds() {
return pollingIntervalSeconds;
}
public FilenameFilter getFilenameFilter() {
return filenameFilter;
}
}
}
| 6,253 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/FilterLoader.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul;
import com.netflix.zuul.filters.FilterType;
import com.netflix.zuul.filters.ZuulFilter;
import java.io.File;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.SortedSet;
/**
* This class is one of the core classes in Zuul. It compiles, loads from a File, and checks if source code changed.
* It also holds ZuulFilters by filterType.
*/
public interface FilterLoader {
/**
* From a file this will read the ZuulFilter source code, compile it, and add it to the list of current filters
* a true response means that it was successful.
*
* @param file the file to load
* @return true if the filter in file successfully read, compiled, verified and added to Zuul
*/
boolean putFilter(File file);
/**
* Load and cache filters by className.
*
* @param classNames The class names to load
* @return List of the loaded filters
* @throws Exception If any specified filter fails to load, this will abort. This is a safety mechanism so we can
* prevent running in a partially loaded state.
*/
List<ZuulFilter<?, ?>> putFiltersForClasses(String[] classNames) throws Exception;
ZuulFilter<?, ?> putFilterForClassName(String className) throws Exception;
/**
* Returns a sorted set of filters by the filterType specified.
*/
SortedSet<ZuulFilter<?, ?>> getFiltersByType(FilterType filterType);
ZuulFilter<?, ?> getFilterByNameAndType(String name, FilterType type);
Comparator<ZuulFilter<?, ?>> FILTER_COMPARATOR =
Comparator.<ZuulFilter<?, ?>>comparingInt(ZuulFilter::filterOrder).thenComparing(ZuulFilter::filterName);
Comparator<Class<? extends ZuulFilter<?, ?>>> FILTER_CLASS_COMPARATOR =
Comparator.<Class<? extends ZuulFilter<?, ?>>>comparingInt(
c -> Objects.requireNonNull(c.getAnnotation(Filter.class), () -> "missing annotation: " + c)
.order())
.thenComparing(Class::getName);
}
| 6,254 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/FilterFactory.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul;
import com.netflix.zuul.filters.ZuulFilter;
/**
* Interface to provide instances of ZuulFilter from a given class.
*/
public interface FilterFactory {
/**
* Returns an instance of the specified class.
*
* @param clazz the Class to instantiate
* @return an instance of ZuulFilter
* @throws Exception if an error occurs
*/
ZuulFilter<?, ?> newInstance(Class<?> clazz) throws Exception;
}
| 6,255 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/FilterCategory.java | /*
* Copyright 2022 Netflix, Inc.
*
* 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 com.netflix.zuul;
/**
* Categorization of filters.
*/
public enum FilterCategory {
ABUSE(
"abuse",
"Abuse detection and protection filters, such as rate-limiting, malicious request detection, geo-blocking"),
ACCESS("access", "Authentication and authorization filters"),
ADMIN("admin", "Admin only filters providing operational support"),
CHAOS("chaos", "Failure injection testing and resilience support"),
CONTEXT_DECORATOR("context-decorator", "Decorate context based on request and detected client"),
HEALTHCHECK("healthcheck", "Support for healthcheck endpoints"),
HTTP("http", "Filter operating on HTTP request/response protocol features"),
ORIGIN("origin", "Origin connectivity filters"),
OBSERVABILITY("observability", "Filters providing observability features"),
OVERLOAD("overload", "Filters to respond on the server being in an overloaded state such as brownout"),
ROUTING("routing", "Filters which make routing decisions"),
;
private final String code;
private final String description;
FilterCategory(String code, String description) {
this.code = code;
this.description = description;
}
public String getCode() {
return code;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return code;
}
}
| 6,256 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/ExecutionStatus.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul;
public enum ExecutionStatus {
SUCCESS(1),
SKIPPED(-1),
DISABLED(-2),
FAILED(-3),
BODY_AWAIT(-4),
ASYNC_AWAIT(-5);
private int status;
ExecutionStatus(int status) {
this.status = status;
}
} | 6,257 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/BasicFilterUsageNotifier.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul;
import com.netflix.spectator.api.Registry;
import com.netflix.zuul.filters.ZuulFilter;
import javax.inject.Inject;
/**
* Publishes a counter metric for each filter on each use.
*/
public class BasicFilterUsageNotifier implements FilterUsageNotifier {
private static final String METRIC_PREFIX = "zuul.filter-";
private final Registry registry;
@Inject
BasicFilterUsageNotifier(Registry registry) {
this.registry = registry;
}
@Override
public void notify(ZuulFilter<?, ?> filter, ExecutionStatus status) {
registry.counter(
"zuul.filter-" + filter.getClass().getSimpleName(),
"status",
status.name(),
"filtertype",
filter.filterType().toString())
.increment();
}
}
| 6,258 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/FilterUsageNotifier.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul;
import com.netflix.zuul.filters.ZuulFilter;
/**
* Interface to implement for registering a callback for each time a filter
* is used.
*
* User: michaels
* Date: 5/13/14
* Time: 9:55 PM
*/
public interface FilterUsageNotifier {
void notify(ZuulFilter<?, ?> filter, ExecutionStatus status);
}
| 6,259 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/StaticFilterLoader.java | /*
* Copyright 2020 Netflix, Inc.
*
* 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 com.netflix.zuul;
import com.google.errorprone.annotations.DoNotCall;
import com.netflix.zuul.filters.FilterType;
import com.netflix.zuul.filters.ZuulFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* An immutable static collection of filters.
*/
public final class StaticFilterLoader implements FilterLoader {
private static final Logger logger = LoggerFactory.getLogger(StaticFilterLoader.class);
public static final String RESOURCE_NAME = "META-INF/zuul/allfilters";
private final Map<FilterType, ? extends SortedSet<ZuulFilter<?, ?>>> filtersByType;
private final Map<FilterType, ? extends Map<String, ZuulFilter<?, ?>>> filtersByTypeAndName;
@Inject
public StaticFilterLoader(
FilterFactory filterFactory, Set<? extends Class<? extends ZuulFilter<?, ?>>> filterTypes) {
Map<FilterType, SortedSet<ZuulFilter<?, ?>>> filtersByType = new EnumMap<>(FilterType.class);
Map<FilterType, Map<String, ZuulFilter<?, ?>>> filtersByName = new EnumMap<>(FilterType.class);
for (Class<? extends ZuulFilter<?, ?>> clz : filterTypes) {
try {
ZuulFilter<?, ?> f = filterFactory.newInstance(clz);
filtersByType
.computeIfAbsent(f.filterType(), k -> new TreeSet<>(FILTER_COMPARATOR))
.add(f);
filtersByName
.computeIfAbsent(f.filterType(), k -> new HashMap<>())
.put(f.filterName(), f);
} catch (RuntimeException | Error e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
for (Entry<FilterType, SortedSet<ZuulFilter<?, ?>>> entry : filtersByType.entrySet()) {
entry.setValue(Collections.unmodifiableSortedSet(entry.getValue()));
}
Map<FilterType, Map<String, ZuulFilter<?, ?>>> immutableFiltersByName = new EnumMap<>(FilterType.class);
for (Entry<FilterType, Map<String, ZuulFilter<?, ?>>> entry : filtersByName.entrySet()) {
immutableFiltersByName.put(entry.getKey(), Collections.unmodifiableMap(entry.getValue()));
}
this.filtersByTypeAndName = Collections.unmodifiableMap(immutableFiltersByName);
this.filtersByType = Collections.unmodifiableMap(filtersByType);
}
public static Set<Class<ZuulFilter<?, ?>>> loadFilterTypesFromResources(ClassLoader loader) throws IOException {
Set<Class<ZuulFilter<?, ?>>> filterTypes = new LinkedHashSet<>();
for (URL url : Collections.list(loader.getResources(RESOURCE_NAME))) {
try (InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr)) {
String line;
while ((line = br.readLine()) != null) {
String trimmed = line.trim();
if (!trimmed.isEmpty()) {
Class<?> clz;
try {
clz = Class.forName(trimmed, false, loader);
} catch (ClassNotFoundException e) {
// This can happen if a filter is deleted, but the annotation processor doesn't
// remove it from the list. This is mainly a problem with IntelliJ, which
// forces append only annotation processors. Incremental recompilation drops
// most of the classpath, making the processor unable to reconstruct the filter
// list. To work around this problem, use the stale, cached filter list from
// the initial full compilation and add to it. This makes incremental
// compilation work later, at the cost of polluting the filter list. It's a
// better experience to log a warning (and do a clean build), than to
// mysteriously classes.
logger.warn("Missing Filter", e);
continue;
}
@SuppressWarnings("unchecked")
Class<ZuulFilter<?, ?>> filterClz = (Class<ZuulFilter<?, ?>>) clz.asSubclass(ZuulFilter.class);
filterTypes.add(filterClz);
}
}
}
}
return Collections.unmodifiableSet(filterTypes);
}
@Override
@DoNotCall
public boolean putFilter(File file) {
throw new UnsupportedOperationException();
}
@Override
@DoNotCall
public List<ZuulFilter<?, ?>> putFiltersForClasses(String[] classNames) {
throw new UnsupportedOperationException();
}
@Override
@DoNotCall
public ZuulFilter<?, ?> putFilterForClassName(String className) {
throw new UnsupportedOperationException();
}
@Override
public SortedSet<ZuulFilter<?, ?>> getFiltersByType(FilterType filterType) {
return filtersByType.get(filterType);
}
@Override
@Nullable
public ZuulFilter<?, ?> getFilterByNameAndType(String name, FilterType type) {
Map<String, ZuulFilter<?, ?>> filtersByName = filtersByTypeAndName.get(type);
if (filtersByName == null) {
return null;
}
return filtersByName.get(name);
}
}
| 6,260 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/BasicRequestCompleteHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul;
import com.netflix.zuul.context.SessionContext;
import com.netflix.zuul.message.http.HttpRequestInfo;
import com.netflix.zuul.message.http.HttpResponseMessage;
import com.netflix.zuul.stats.RequestMetricsPublisher;
import javax.annotation.Nullable;
import javax.inject.Inject;
/**
* User: michaels@netflix.com
* Date: 6/4/15
* Time: 4:26 PM
*/
public class BasicRequestCompleteHandler implements RequestCompleteHandler {
@Inject
@Nullable
private RequestMetricsPublisher requestMetricsPublisher;
@Override
public void handle(HttpRequestInfo inboundRequest, HttpResponseMessage response) {
SessionContext context = inboundRequest.getContext();
// Publish request-level metrics.
if (requestMetricsPublisher != null) {
requestMetricsPublisher.collectAndPublish(context);
}
}
}
| 6,261 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/DynamicFilterLoader.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul;
import com.netflix.zuul.filters.FilterRegistry;
import com.netflix.zuul.filters.FilterType;
import com.netflix.zuul.filters.ZuulFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.File;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@Singleton
public final class DynamicFilterLoader implements FilterLoader {
private static final Logger LOG = LoggerFactory.getLogger(DynamicFilterLoader.class);
private final ConcurrentMap<String, Long> filterClassLastModified = new ConcurrentHashMap<>();
private final ConcurrentMap<String, String> filterClassCode = new ConcurrentHashMap<>();
private final ConcurrentMap<String, String> filterCheck = new ConcurrentHashMap<>();
private final ConcurrentMap<FilterType, SortedSet<ZuulFilter<?, ?>>> hashFiltersByType = new ConcurrentHashMap<>();
private final ConcurrentMap<String, ZuulFilter<?, ?>> filtersByNameAndType = new ConcurrentHashMap<>();
private final FilterRegistry filterRegistry;
private final DynamicCodeCompiler compiler;
private final FilterFactory filterFactory;
@Inject
public DynamicFilterLoader(
FilterRegistry filterRegistry, DynamicCodeCompiler compiler, FilterFactory filterFactory) {
this.filterRegistry = filterRegistry;
this.compiler = compiler;
this.filterFactory = filterFactory;
}
/**
* Given source and name will compile and store the filter if it detects that the filter code
* has changed or the filter doesn't exist. Otherwise it will return an instance of the
* requested ZuulFilter.
*
* @deprecated it is unclear to me why this method is needed. Nothing seems to use it, and the
* swapping of code seems to happen elsewhere. This will be removed in a later
* Zuul release.
*/
@Deprecated
public ZuulFilter<?, ?> getFilter(String sourceCode, String filterName) throws Exception {
if (filterCheck.get(filterName) == null) {
filterCheck.putIfAbsent(filterName, filterName);
if (!sourceCode.equals(filterClassCode.get(filterName))) {
if (filterRegistry.isMutable()) {
LOG.info("reloading code {}", filterName);
filterRegistry.remove(filterName);
} else {
LOG.warn("Filter registry is not mutable, discarding {}", filterName);
}
}
}
ZuulFilter<?, ?> filter = filterRegistry.get(filterName);
if (filter == null) {
Class<?> clazz = compiler.compile(sourceCode, filterName);
if (!Modifier.isAbstract(clazz.getModifiers())) {
filter = filterFactory.newInstance(clazz);
}
}
return filter;
}
/**
* @return the total number of Zuul filters
*/
public int filterInstanceMapSize() {
return filterRegistry.size();
}
/**
* From a file this will read the ZuulFilter source code, compile it, and add it to the list of current filters
* a true response means that it was successful.
*
* @param file the file to load
* @return true if the filter in file successfully read, compiled, verified and added to Zuul
*/
@Override
public boolean putFilter(File file) {
if (!filterRegistry.isMutable()) {
return false;
}
try {
String sName = file.getAbsolutePath();
if (filterClassLastModified.get(sName) != null
&& (file.lastModified() != filterClassLastModified.get(sName))) {
LOG.debug("reloading filter {}", sName);
filterRegistry.remove(sName);
}
ZuulFilter<?, ?> filter = filterRegistry.get(sName);
if (filter == null) {
Class<?> clazz = compiler.compile(file);
if (!Modifier.isAbstract(clazz.getModifiers())) {
filter = filterFactory.newInstance(clazz);
putFilter(sName, filter, file.lastModified());
return true;
}
}
} catch (Exception e) {
LOG.error("Error loading filter! Continuing. file={}", file, e);
return false;
}
return false;
}
private void putFilter(String filterName, ZuulFilter<?, ?> filter, long lastModified) {
if (!filterRegistry.isMutable()) {
LOG.warn("Filter registry is not mutable, discarding {}", filterName);
return;
}
SortedSet<ZuulFilter<?, ?>> set = hashFiltersByType.get(filter.filterType());
if (set != null) {
hashFiltersByType.remove(filter.filterType()); // rebuild this list
}
String nameAndType = filter.filterType() + ":" + filter.filterName();
filtersByNameAndType.put(nameAndType, filter);
filterRegistry.put(filterName, filter);
filterClassLastModified.put(filterName, lastModified);
}
/**
* Load and cache filters by className
*
* @param classNames The class names to load
* @return List of the loaded filters
* @throws Exception If any specified filter fails to load, this will abort. This is a safety mechanism so we can
* prevent running in a partially loaded state.
*/
@Override
public List<ZuulFilter<?, ?>> putFiltersForClasses(String[] classNames) throws Exception {
List<ZuulFilter<?, ?>> newFilters = new ArrayList<>();
for (String className : classNames) {
newFilters.add(putFilterForClassName(className));
}
return Collections.unmodifiableList(newFilters);
}
@Override
public ZuulFilter<?, ?> putFilterForClassName(String className) throws Exception {
Class<?> clazz = Class.forName(className);
if (!ZuulFilter.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException("Specified filter class does not implement ZuulFilter interface!");
} else {
ZuulFilter<?, ?> filter = filterFactory.newInstance(clazz);
putFilter(className, filter, System.currentTimeMillis());
return filter;
}
}
/**
* Returns a list of filters by the filterType specified
*/
@Override
public SortedSet<ZuulFilter<?, ?>> getFiltersByType(FilterType filterType) {
SortedSet<ZuulFilter<?, ?>> set = hashFiltersByType.get(filterType);
if (set != null) {
return set;
}
set = new TreeSet<>(FILTER_COMPARATOR);
for (ZuulFilter<?, ?> filter : filterRegistry.getAllFilters()) {
if (filter.filterType().equals(filterType)) {
set.add(filter);
}
}
hashFiltersByType.putIfAbsent(filterType, set);
return Collections.unmodifiableSortedSet(set);
}
@Override
public ZuulFilter<?, ?> getFilterByNameAndType(String name, FilterType type) {
if (name == null || type == null) {
return null;
}
String nameAndType = type + ":" + name;
return filtersByNameAndType.get(nameAndType);
}
}
| 6,262 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/RequestCompleteHandler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul;
import com.netflix.zuul.message.http.HttpRequestInfo;
import com.netflix.zuul.message.http.HttpResponseMessage;
public interface RequestCompleteHandler {
void handle(HttpRequestInfo inboundRequest, HttpResponseMessage response);
}
| 6,263 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/Attrs.java | /*
* Copyright 2020 Netflix, Inc.
*
* 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 com.netflix.zuul;
import com.google.common.annotations.VisibleForTesting;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiConsumer;
/**
* A heterogeneous map of attributes.
*
* <p>Implementation Note: this class is not a proper Map or Collection, in order to encourage callers
* to refer to the keys by their literal name. In the past, finding where a Key was used was difficult,
* so this class is somewhat of an experiment to try to make tracking down usage easier. If it becomes
* too onerous to use this, consider making this class extend AbstractMap.
*/
public final class Attrs {
final Map<Key<?>, Object> storage = new IdentityHashMap<>();
public static <T> Key<T> newKey(String keyName) {
return new Key<>(keyName);
}
public static final class Key<T> {
private final String name;
/**
* Returns the value in the attributes, or {@code null} if absent.
*/
@Nullable
@SuppressWarnings("unchecked")
public T get(Attrs attrs) {
Objects.requireNonNull(attrs, "attrs");
return (T) attrs.storage.get(this);
}
/**
* Returns the value in the attributes or {@code defaultValue} if absent.
* @throws NullPointerException if defaultValue is null.
*/
@SuppressWarnings("unchecked")
public T getOrDefault(Attrs attrs, T defaultValue) {
Objects.requireNonNull(attrs, "attrs");
Objects.requireNonNull(defaultValue, "defaultValue");
T result = (T) attrs.storage.get(this);
if (result != null) {
return result;
}
return defaultValue;
}
public void put(Attrs attrs, T value) {
Objects.requireNonNull(attrs, "attrs");
Objects.requireNonNull(value);
attrs.storage.put(this, value);
}
public String name() {
return name;
}
private Key(String name) {
this.name = Objects.requireNonNull(name);
}
@Override
public String toString() {
return "Key{" + name + '}';
}
}
private Attrs() {}
public static Attrs newInstance() {
return new Attrs();
}
public Set<Key<?>> keySet() {
return Collections.unmodifiableSet(new LinkedHashSet<>(storage.keySet()));
}
public void forEach(BiConsumer<? super Key<?>, Object> consumer) {
storage.forEach(consumer);
}
public int size() {
return storage.size();
}
@Override
public String toString() {
return "Attrs{" + storage + '}';
}
@Override
@VisibleForTesting
public boolean equals(Object other) {
if (!(other instanceof Attrs)) {
return false;
}
Attrs that = (Attrs) other;
return Objects.equals(this.storage, that.storage);
}
@Override
@VisibleForTesting
public int hashCode() {
return Objects.hash(storage);
}
}
| 6,264 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/DefaultFilterFactory.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul;
import com.netflix.zuul.filters.ZuulFilter;
/**
* Default factory for creating instances of ZuulFilter.
*/
public class DefaultFilterFactory implements FilterFactory {
/**
* Returns a new implementation of ZuulFilter as specified by the provided
* Class. The Class is instantiated using its nullary constructor.
*
* @param clazz the Class to instantiate
* @return A new instance of ZuulFilter
*/
@Override
public ZuulFilter newInstance(Class clazz) throws InstantiationException, IllegalAccessException {
return (ZuulFilter) clazz.newInstance();
}
}
| 6,265 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/DynamicCodeCompiler.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul;
import java.io.File;
/**
* Interface to generate Classes from source code
* User: mcohen
* Date: 5/30/13
* Time: 11:35 AM
*/
public interface DynamicCodeCompiler {
Class<?> compile(String sCode, String sName) throws Exception;
Class<?> compile(File file) throws Exception;
}
| 6,266 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/Filter.java | /*
* Copyright 2020 Netflix, Inc.
*
* 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 com.netflix.zuul;
import com.netflix.zuul.filters.FilterSyncType;
import com.netflix.zuul.filters.FilterType;
import com.netflix.zuul.filters.ZuulFilter;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Identifies a {@link ZuulFilter}.
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Filter {
/**
* The order in which to run. See {@link ZuulFilter#filterOrder()}.
*/
int order();
/**
* Indicates the type of this filter.
*/
FilterType type() default FilterType.INBOUND;
/**
* Category of the filter.
*/
FilterCategory category() default FilterCategory.HTTP;
/**
* Indicates if this is a synchronous filter.
*/
FilterSyncType sync() default FilterSyncType.SYNC;
@Target({ElementType.PACKAGE})
@Retention(RetentionPolicy.CLASS)
@Documented
@interface FilterPackageName {
String value();
}
/**
* Indicates that the annotated filter should run after another filter in the chain, if the other filter is present.
* In the case of inbound filters, this implies that the annotated filter should have an order greater than the
* filters listed. For outbound filters, the order of this filter should be less than the ones listed. Usage of
* this annotation should be used on homogeneous filter types. Additionally, this should not be applied to endpoint
* filters.
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface ApplyAfter {
Class<? extends ZuulFilter<?, ?>>[] value();
}
/**
* Indicates that the annotated filter should run before another filter in the chain, if the other filter is present.
* In the case of inbound filters, this implies that the annotated filter should have an order less than the
* filters listed. For outbound filters, the order of this filter should be greater than the ones listed. Usage of
* this annotation should be used on homogeneous filter types. Additionally, this should not be applied to endpoint
* filters.
*
* <p>Prefer to use this {@link ApplyAfter} instead. This annotation is meant in case where it may be infeasible
* to use {@linkplain ApplyAfter}. (such as due to dependency cycles)
*
* @see ApplyAfter
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface ApplyBefore {
Class<? extends ZuulFilter<?, ?>>[] value();
}
}
| 6,267 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/ZuulApplicationInfo.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul;
/**
* Metadata about the Zuul instance/ application name and "stack"
* @author Mikey Cohen
* Date: 2/15/13
* Time: 1:56 PM
*/
public class ZuulApplicationInfo {
public static String applicationName;
public static String stack;
public static String getApplicationName() {
return applicationName;
}
public static void setApplicationName(String applicationName) {
ZuulApplicationInfo.applicationName = applicationName;
}
public static String getStack() {
return stack;
}
public static void setStack(String stack) {
ZuulApplicationInfo.stack = stack;
}
}
| 6,268 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/BaseSyncFilter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters;
import com.netflix.zuul.message.ZuulMessage;
import rx.Observable;
/**
* User: michaels@netflix.com
* Date: 5/8/15
* Time: 2:46 PM
*/
public abstract class BaseSyncFilter<I extends ZuulMessage, O extends ZuulMessage> extends BaseFilter<I, O>
implements SyncZuulFilter<I, O> {
/**
* A wrapper implementation of applyAsync() that is intended just to aggregate a non-blocking apply() method
* in an Observable.
*
* A subclass filter should override this method if doing any IO.
*/
@Override
public Observable<O> applyAsync(I input) {
return Observable.just(this.apply(input));
}
@Override
public FilterSyncType getSyncType() {
return FilterSyncType.SYNC;
}
}
| 6,269 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/FilterSyncType.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters;
/**
* User: Mike Smith
* Date: 11/13/15
* Time: 9:13 PM
*/
public enum FilterSyncType {
SYNC,
ASYNC
}
| 6,270 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/BaseFilter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters;
import com.netflix.config.CachedDynamicBooleanProperty;
import com.netflix.config.CachedDynamicIntProperty;
import com.netflix.spectator.api.Counter;
import com.netflix.zuul.exception.ZuulFilterConcurrencyExceededException;
import com.netflix.zuul.message.ZuulMessage;
import com.netflix.zuul.netty.SpectatorUtils;
import io.netty.handler.codec.http.HttpContent;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Base abstract class for ZuulFilters. The base class defines abstract methods to define:
* filterType() - to classify a filter by type. Standard types in Zuul are "pre" for pre-routing filtering,
* "route" for routing to an origin, "post" for post-routing filters, "error" for error handling.
* We also support a "static" type for static responses see StaticResponseFilter.
* <p>
* filterOrder() must also be defined for a filter. Filters may have the same filterOrder if precedence is not
* important for a filter. filterOrders do not need to be sequential.
* <p>
* ZuulFilters may be disabled using Archaius Properties.
* <p>
* By default ZuulFilters are static; they don't carry state. This may be overridden by overriding the isStaticFilter() property to false
*
* @author Mikey Cohen
* Date: 10/26/11
* Time: 4:29 PM
*/
public abstract class BaseFilter<I extends ZuulMessage, O extends ZuulMessage> implements ZuulFilter<I, O> {
private final String baseName;
private final AtomicInteger concurrentCount;
private final Counter concurrencyRejections;
private final CachedDynamicBooleanProperty filterDisabled;
private final CachedDynamicIntProperty filterConcurrencyLimit;
private static final CachedDynamicBooleanProperty concurrencyProtectEnabled =
new CachedDynamicBooleanProperty("zuul.filter.concurrency.protect.enabled", true);
protected BaseFilter() {
baseName = getClass().getSimpleName() + "." + filterType();
concurrentCount = SpectatorUtils.newGauge("zuul.filter.concurrency.current", baseName, new AtomicInteger(0));
concurrencyRejections = SpectatorUtils.newCounter("zuul.filter.concurrency.rejected", baseName);
filterDisabled = new CachedDynamicBooleanProperty(disablePropertyName(), false);
filterConcurrencyLimit = new CachedDynamicIntProperty(maxConcurrencyPropertyName(), 4000);
}
@Override
public String filterName() {
return getClass().getName();
}
@Override
public boolean overrideStopFilterProcessing() {
return false;
}
/**
* The name of the Archaius property to disable this filter. by default it is zuul.[classname].[filtertype].disable
*/
public String disablePropertyName() {
return "zuul." + baseName + ".disable";
}
/**
* The name of the Archaius property for this filter's max concurrency. by default it is
* zuul.[classname].[filtertype].concurrency.limit
*/
public String maxConcurrencyPropertyName() {
return "zuul." + baseName + ".concurrency.limit";
}
/**
* If true, the filter has been disabled by archaius and will not be run.
*/
@Override
public boolean isDisabled() {
return filterDisabled.get();
}
@Override
public O getDefaultOutput(I input) {
return (O) input;
}
@Override
public FilterSyncType getSyncType() {
return FilterSyncType.ASYNC;
}
@Override
public String toString() {
return String.valueOf(filterType()) + ":" + String.valueOf(filterName());
}
@Override
public boolean needsBodyBuffered(I input) {
return false;
}
@Override
public HttpContent processContentChunk(ZuulMessage zuulMessage, HttpContent chunk) {
return chunk;
}
@Override
public void incrementConcurrency() throws ZuulFilterConcurrencyExceededException {
final int limit = filterConcurrencyLimit.get();
if ((concurrencyProtectEnabled.get()) && (concurrentCount.get() >= limit)) {
concurrencyRejections.increment();
throw new ZuulFilterConcurrencyExceededException(this, limit);
}
concurrentCount.incrementAndGet();
}
@Override
public void decrementConcurrency() {
concurrentCount.decrementAndGet();
}
}
| 6,271 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/FilterRegistry.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters;
import javax.annotation.Nullable;
import java.util.Collection;
public interface FilterRegistry {
@Nullable
ZuulFilter<?, ?> get(String key);
int size();
Collection<ZuulFilter<?, ?>> getAllFilters();
/**
* Indicates if this registry can be modified. Implementations should not change the return;
* they return the same value each time.
*/
boolean isMutable();
/**
* Removes the filter from the registry, and returns it. Returns {@code null} no such filter
* was found. Callers should check {@link #isMutable()} before calling this method.
*
* @throws IllegalStateException if this registry is not mutable.
*/
@Nullable
ZuulFilter<?, ?> remove(String key);
/**
* Stores the filter into the registry. If an existing filter was present with the same key,
* it is removed. Callers should check {@link #isMutable()} before calling this method.
*
* @throws IllegalStateException if this registry is not mutable.
*/
void put(String key, ZuulFilter<?, ?> filter);
}
| 6,272 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/MutableFilterRegistry.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters;
import javax.annotation.Nullable;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
@Singleton
public final class MutableFilterRegistry implements FilterRegistry {
private final ConcurrentHashMap<String, ZuulFilter<?, ?>> filters = new ConcurrentHashMap<>();
@Nullable
@Override
public ZuulFilter<?, ?> remove(String key) {
return filters.remove(Objects.requireNonNull(key, "key"));
}
@Override
@Nullable
public ZuulFilter<?, ?> get(String key) {
return filters.get(Objects.requireNonNull(key, "key"));
}
@Override
public void put(String key, ZuulFilter<?, ?> filter) {
filters.putIfAbsent(Objects.requireNonNull(key, "key"), Objects.requireNonNull(filter, "filter"));
}
@Override
public int size() {
return filters.size();
}
@Override
public Collection<ZuulFilter<?, ?>> getAllFilters() {
return Collections.unmodifiableList(new ArrayList<>(filters.values()));
}
@Override
public boolean isMutable() {
return true;
}
}
| 6,273 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/ZuulFilter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters;
import com.netflix.zuul.Filter;
import com.netflix.zuul.FilterCategory;
import com.netflix.zuul.exception.ZuulFilterConcurrencyExceededException;
import com.netflix.zuul.message.ZuulMessage;
import io.netty.handler.codec.http.HttpContent;
import rx.Observable;
/**
* Base interface for ZuulFilters
*
* @author Mikey Cohen
* Date: 10/27/11
* Time: 3:03 PM
*/
public interface ZuulFilter<I extends ZuulMessage, O extends ZuulMessage> extends ShouldFilter<I> {
boolean isDisabled();
String filterName();
/**
* filterOrder() must also be defined for a filter. Filters may have the same filterOrder if precedence is not
* important for a filter. filterOrders do not need to be sequential.
*
* @return the int order of a filter
*/
default int filterOrder() {
Filter f = getClass().getAnnotation(Filter.class);
if (f != null) {
return f.order();
}
throw new UnsupportedOperationException("not implemented");
}
/**
* to classify a filter by type. Standard types in Zuul are "in" for pre-routing filtering,
* "end" for routing to an origin, "out" for post-routing filters.
*
* @return FilterType
*/
default FilterType filterType() {
Filter f = getClass().getAnnotation(Filter.class);
if (f != null) {
return f.type();
}
throw new UnsupportedOperationException("not implemented");
}
/**
* Classify a filter by category.
*
* @return FilterCategory the classification of this filter
*/
default FilterCategory category() {
Filter f = getClass().getAnnotation(Filter.class);
if (f != null) {
return f.category();
}
throw new UnsupportedOperationException("not implemented");
}
/**
* Whether this filter's shouldFilter() method should be checked, and apply() called, even
* if SessionContext.stopFilterProcessing has been set.
*
* @return boolean
*/
boolean overrideStopFilterProcessing();
/**
* Called by zuul filter runner before sending request through this filter. The filter can throw
* ZuulFilterConcurrencyExceededException if it has reached its concurrent requests limit and does
* not wish to process the request. Generally only useful for async filters.
*/
void incrementConcurrency() throws ZuulFilterConcurrencyExceededException;
/**
* if shouldFilter() is true, this method will be invoked. this method is the core method of a ZuulFilter
*/
Observable<O> applyAsync(I input);
/**
* Called by zuul filter after request is processed by this filter.
*
*/
void decrementConcurrency();
default FilterSyncType getSyncType() {
Filter f = getClass().getAnnotation(Filter.class);
if (f != null) {
return f.sync();
}
throw new UnsupportedOperationException("not implemented");
}
/**
* Choose a default message to use if the applyAsync() method throws an exception.
*
* @return ZuulMessage
*/
O getDefaultOutput(I input);
/**
* Filter indicates it needs to read and buffer whole body before it can operate on the messages by returning true.
* The decision can be made at runtime, looking at the request type. For example if the incoming message is a MSL
* message MSL decryption filter can return true here to buffer whole MSL message before it tries to decrypt it.
* @return true if this filter needs to read whole body before it can run, false otherwise
*/
boolean needsBodyBuffered(I input);
/**
* Optionally transform HTTP content chunk received.
*/
HttpContent processContentChunk(ZuulMessage zuulMessage, HttpContent chunk);
}
| 6,274 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/Endpoint.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters;
import com.netflix.zuul.message.ZuulMessage;
/**
* User: Mike Smith
* Date: 5/16/15
* Time: 1:57 PM
*/
public abstract class Endpoint<I extends ZuulMessage, O extends ZuulMessage> extends BaseFilter<I, O> {
@Override
public int filterOrder() {
// Set all Endpoint filters to order of 0, because they are not processed sequentially like other filter types.
return 0;
}
@Override
public FilterType filterType() {
return FilterType.ENDPOINT;
}
@Override
public boolean shouldFilter(I msg) {
// Always true, because Endpoint filters are chosen by name instead.
return true;
}
}
| 6,275 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/ShouldFilter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters;
import com.netflix.zuul.message.ZuulMessage;
/**
* User: michaels@netflix.com
* Date: 5/7/15
* Time: 3:31 PM
*/
public interface ShouldFilter<T extends ZuulMessage> {
/**
* a "true" return from this method means that the apply() method should be invoked
*
* @return true if the apply() method should be invoked. false will not invoke the apply() method
*/
boolean shouldFilter(T msg);
}
| 6,276 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/FilterError.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters;
/**
* User: michaels@netflix.com
* Date: 5/7/15
* Time: 10:19 AM
*/
public class FilterError implements Cloneable {
private String filterName;
private String filterType;
private Throwable exception = null;
public FilterError(String filterName, String filterType, Throwable exception) {
this.filterName = filterName;
this.filterType = filterType;
this.exception = exception;
}
public String getFilterName() {
return filterName;
}
public String getFilterType() {
return filterType;
}
public Throwable getException() {
return exception;
}
@Override
public Object clone() {
return new FilterError(filterName, filterType, exception);
}
@Override
public String toString() {
return "FilterError{" + "filterName='"
+ filterName + '\'' + ", filterType='"
+ filterType + '\'' + ", exception="
+ exception + '}';
}
}
| 6,277 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/SyncZuulFilterAdapter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters;
import com.netflix.zuul.message.ZuulMessage;
import io.netty.handler.codec.http.HttpContent;
import rx.Observable;
/**
* Base class to help implement SyncZuulFilter. Note that the class BaseSyncFilter does exist but it derives from
* BaseFilter which in turn creates a new instance of CachedDynamicBooleanProperty for "filterDisabled" every time you
* create a new instance of the ZuulFilter. Normally it is not too much of a concern as the instances of ZuulFilters
* are "effectively" singleton and are cached by ZuulFilterLoader. However, if you ever have a need for instantiating a
* new ZuulFilter instance per request - aka EdgeProxyEndpoint or Inbound/Outbound PassportStampingFilter creating new
* instances of CachedDynamicBooleanProperty per instance of ZuulFilter will quickly kill your server's performance in
* two ways -
* a) Instances of CachedDynamicBooleanProperty are *very* heavy CPU wise to create due to extensive hookups machinery
* in their constructor
* b) They leak memory as they add themselves to some ConcurrentHashMap and are never garbage collected.
*
* TL;DR use this as a base class for your ZuulFilter if you intend to create new instances of ZuulFilter
* Created by saroskar on 6/8/17.
*/
public abstract class SyncZuulFilterAdapter<I extends ZuulMessage, O extends ZuulMessage>
implements SyncZuulFilter<I, O> {
@Override
public boolean isDisabled() {
return false;
}
@Override
public boolean shouldFilter(I msg) {
return true;
}
@Override
public int filterOrder() {
// Set all Endpoint filters to order of 0, because they are not processed sequentially like other filter types.
return 0;
}
@Override
public FilterType filterType() {
return FilterType.ENDPOINT;
}
@Override
public boolean overrideStopFilterProcessing() {
return false;
}
@Override
public Observable<O> applyAsync(I input) {
return Observable.just(apply(input));
}
@Override
public FilterSyncType getSyncType() {
return FilterSyncType.SYNC;
}
@Override
public boolean needsBodyBuffered(I input) {
return false;
}
@Override
public HttpContent processContentChunk(ZuulMessage zuulMessage, HttpContent chunk) {
return chunk;
}
@Override
public void incrementConcurrency() {
// NOOP for sync filters
}
@Override
public void decrementConcurrency() {
// NOOP for sync filters
}
} | 6,278 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/SyncZuulFilter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters;
import com.netflix.zuul.message.ZuulMessage;
/**
* User: michaels@netflix.com
* Date: 11/16/15
* Time: 2:07 PM
*/
public interface SyncZuulFilter<I extends ZuulMessage, O extends ZuulMessage> extends ZuulFilter<I, O> {
O apply(I input);
}
| 6,279 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/FilterType.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters;
/**
* User: Mike Smith
* Date: 11/13/15
* Time: 7:50 PM
*/
public enum FilterType {
INBOUND("in"),
ENDPOINT("end"),
OUTBOUND("out");
private final String shortName;
private FilterType(String shortName) {
this.shortName = shortName;
}
@Override
public String toString() {
return shortName;
}
public static FilterType parse(String str) {
str = str.toLowerCase();
switch (str) {
case "in":
return INBOUND;
case "out":
return OUTBOUND;
case "end":
return ENDPOINT;
default:
throw new IllegalArgumentException("Unknown filter type! type=" + String.valueOf(str));
}
}
}
| 6,280 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/passport/OutboundPassportStampingFilter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters.passport;
import com.netflix.zuul.Filter;
import com.netflix.zuul.filters.FilterType;
import com.netflix.zuul.message.http.HttpResponseMessage;
import com.netflix.zuul.passport.PassportState;
/**
* Created by saroskar on 3/14/17.
*/
@Filter(order = 0, type = FilterType.OUTBOUND)
public final class OutboundPassportStampingFilter extends PassportStampingFilter<HttpResponseMessage> {
public OutboundPassportStampingFilter(PassportState stamp) {
super(stamp);
}
@Override
public FilterType filterType() {
return FilterType.OUTBOUND;
}
}
| 6,281 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/passport/InboundPassportStampingFilter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters.passport;
import com.netflix.zuul.Filter;
import com.netflix.zuul.filters.FilterType;
import com.netflix.zuul.message.http.HttpRequestMessage;
import com.netflix.zuul.passport.PassportState;
/**
* Created by saroskar on 3/14/17.
*/
@Filter(order = 0, type = FilterType.INBOUND)
public final class InboundPassportStampingFilter extends PassportStampingFilter<HttpRequestMessage> {
public InboundPassportStampingFilter(PassportState stamp) {
super(stamp);
}
@Override
public FilterType filterType() {
return FilterType.INBOUND;
}
}
| 6,282 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/passport/PassportStampingFilter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters.passport;
import com.netflix.zuul.filters.SyncZuulFilterAdapter;
import com.netflix.zuul.message.ZuulMessage;
import com.netflix.zuul.passport.CurrentPassport;
import com.netflix.zuul.passport.PassportState;
/**
* Created by saroskar on 2/18/17.
*/
public abstract class PassportStampingFilter<T extends ZuulMessage> extends SyncZuulFilterAdapter<T, T> {
private final PassportState stamp;
private final String name;
public PassportStampingFilter(PassportState stamp) {
this.stamp = stamp;
this.name = filterType().name() + "-" + stamp.name() + "-Filter";
}
@Override
public String filterName() {
return name;
}
@Override
public T getDefaultOutput(T input) {
return input;
}
@Override
public T apply(T input) {
CurrentPassport.fromSessionContext(input.getContext()).add(stamp);
return input;
}
}
| 6,283 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/common/SurgicalDebugFilter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters.common;
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicStringProperty;
import com.netflix.zuul.Filter;
import com.netflix.zuul.constants.ZuulConstants;
import com.netflix.zuul.constants.ZuulHeaders;
import com.netflix.zuul.context.SessionContext;
import com.netflix.zuul.filters.FilterType;
import com.netflix.zuul.filters.http.HttpInboundSyncFilter;
import com.netflix.zuul.message.http.HttpQueryParams;
import com.netflix.zuul.message.http.HttpRequestMessage;
/**
* This is an abstract filter that will route requests that match the patternMatches() method to a debug Eureka "VIP" or
* host specified by zuul.debug.vip or zuul.debug.host.
*
* @author Mikey Cohen
* Date: 6/27/12
* Time: 12:54 PM
*/
@Filter(order = 99, type = FilterType.INBOUND)
public class SurgicalDebugFilter extends HttpInboundSyncFilter {
/**
* Returning true by the pattern or logic implemented in this method will route the request to the specified origin
*
* Override this method when using this filter to add your own pattern matching logic.
*
* @return true if this request should be routed to the debug origin
*/
protected boolean patternMatches(HttpRequestMessage request) {
return false;
}
@Override
public int filterOrder() {
return 99;
}
@Override
public boolean shouldFilter(HttpRequestMessage request) {
DynamicBooleanProperty debugFilterShutoff =
new DynamicBooleanProperty(ZuulConstants.ZUUL_DEBUGFILTERS_DISABLED, false);
if (debugFilterShutoff.get()) {
return false;
}
if (isDisabled()) {
return false;
}
String isSurgicalFilterRequest = request.getHeaders().getFirst(ZuulHeaders.X_ZUUL_SURGICAL_FILTER);
// dont' apply filter if it was already applied
boolean notAlreadyFiltered = !("true".equals(isSurgicalFilterRequest));
return notAlreadyFiltered && patternMatches(request);
}
@Override
public HttpRequestMessage apply(HttpRequestMessage request) {
DynamicStringProperty routeVip = new DynamicStringProperty(ZuulConstants.ZUUL_DEBUG_VIP, null);
DynamicStringProperty routeHost = new DynamicStringProperty(ZuulConstants.ZUUL_DEBUG_HOST, null);
SessionContext ctx = request.getContext();
if (routeVip.get() != null || routeHost.get() != null) {
ctx.set("routeHost", routeHost.get());
ctx.set("routeVIP", routeVip.get());
request.getHeaders().set(ZuulHeaders.X_ZUUL_SURGICAL_FILTER, "true");
HttpQueryParams queryParams = request.getQueryParams();
queryParams.set("debugRequest", "true");
ctx.setDebugRequest(true);
ctx.set("zuulToZuul", true);
}
return request;
}
}
| 6,284 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/common/GZipResponseFilter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters.common;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.config.CachedDynamicBooleanProperty;
import com.netflix.config.CachedDynamicIntProperty;
import com.netflix.config.DynamicStringSetProperty;
import com.netflix.zuul.Filter;
import com.netflix.zuul.context.CommonContextKeys;
import com.netflix.zuul.filters.FilterType;
import com.netflix.zuul.filters.http.HttpOutboundSyncFilter;
import com.netflix.zuul.message.Headers;
import com.netflix.zuul.message.ZuulMessage;
import com.netflix.zuul.message.http.HttpHeaderNames;
import com.netflix.zuul.message.http.HttpRequestInfo;
import com.netflix.zuul.message.http.HttpResponseMessage;
import com.netflix.zuul.util.Gzipper;
import com.netflix.zuul.util.HttpUtils;
import io.netty.handler.codec.http.DefaultHttpContent;
import io.netty.handler.codec.http.DefaultLastHttpContent;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.LastHttpContent;
/**
* General-purpose filter for gzipping/ungzipping response bodies if requested/needed. This should be run as late as
* possible to ensure final encoded body length is considered
*
* <p>You can just subclass this in your project, and use as-is.
*
* @author Mike Smith
*/
@Filter(order = 110, type = FilterType.OUTBOUND)
public class GZipResponseFilter extends HttpOutboundSyncFilter {
private static DynamicStringSetProperty GZIPPABLE_CONTENT_TYPES = new DynamicStringSetProperty(
"zuul.gzip.contenttypes",
"text/html,application/x-javascript,text/css,application/javascript,text/javascript,text/plain,text/xml,"
+ "application/json,application/vnd.ms-fontobject,application/x-font-opentype,application/x-font-truetype,"
+ "application/x-font-ttf,application/xml,font/eot,font/opentype,font/otf,image/svg+xml,image/vnd.microsoft.icon,"
+ "text/event-stream",
",");
// https://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits
private static final CachedDynamicIntProperty MIN_BODY_SIZE_FOR_GZIP =
new CachedDynamicIntProperty("zuul.min.gzip.body.size", 860);
private static final CachedDynamicBooleanProperty ENABLED =
new CachedDynamicBooleanProperty("zuul.response.gzip.filter.enabled", true);
@Override
public boolean shouldFilter(HttpResponseMessage response) {
if (!ENABLED.get() || !response.hasBody() || response.getContext().isInBrownoutMode()) {
return false;
}
if (response.getContext().get(CommonContextKeys.GZIPPER) != null) {
return true;
}
// A flag on SessionContext can be set to override normal mechanism of checking if client accepts gzip.;
final HttpRequestInfo request = response.getInboundRequest();
final Boolean overrideIsGzipRequested =
(Boolean) response.getContext().get(CommonContextKeys.OVERRIDE_GZIP_REQUESTED);
final boolean isGzipRequested = (overrideIsGzipRequested == null)
? HttpUtils.acceptsGzip(request.getHeaders())
: overrideIsGzipRequested;
// Check the headers to see if response is already gzipped.
final Headers respHeaders = response.getHeaders();
boolean isResponseCompressed = HttpUtils.isCompressed(respHeaders);
// Decide what to do.;
final boolean shouldGzip = isGzippableContentType(response)
&& isGzipRequested
&& !isResponseCompressed
&& isRightSizeForGzip(response);
if (shouldGzip) {
response.getContext().set(CommonContextKeys.GZIPPER, getGzipper());
}
return shouldGzip;
}
protected Gzipper getGzipper() {
return new Gzipper();
}
@VisibleForTesting
boolean isRightSizeForGzip(HttpResponseMessage response) {
final Integer bodySize = HttpUtils.getBodySizeIfKnown(response);
// bodySize == null is chunked encoding which is eligible for gzip compression
return (bodySize == null) || (bodySize >= MIN_BODY_SIZE_FOR_GZIP.get());
}
@Override
public HttpResponseMessage apply(HttpResponseMessage response) {
// set Gzip headers
final Headers respHeaders = response.getHeaders();
respHeaders.set(HttpHeaderNames.CONTENT_ENCODING, "gzip");
respHeaders.remove(HttpHeaderNames.CONTENT_LENGTH);
return response;
}
private boolean isGzippableContentType(HttpResponseMessage response) {
String ct = response.getHeaders().getFirst(HttpHeaderNames.CONTENT_TYPE);
if (ct != null) {
int charsetIndex = ct.indexOf(';');
if (charsetIndex > 0) {
ct = ct.substring(0, charsetIndex);
}
return GZIPPABLE_CONTENT_TYPES.get().contains(ct.toLowerCase());
}
return false;
}
@Override
public HttpContent processContentChunk(ZuulMessage resp, HttpContent chunk) {
final Gzipper gzipper = (Gzipper) resp.getContext().get(CommonContextKeys.GZIPPER);
gzipper.write(chunk);
if (chunk instanceof LastHttpContent) {
gzipper.finish();
return new DefaultLastHttpContent(gzipper.getByteBuf());
} else {
return new DefaultHttpContent(gzipper.getByteBuf());
}
}
}
| 6,285 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpOutboundFilter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters.http;
import com.netflix.zuul.filters.BaseFilter;
import com.netflix.zuul.filters.FilterType;
import com.netflix.zuul.message.http.HttpResponseMessage;
/**
* User: michaels@netflix.com
* Date: 5/29/15
* Time: 3:23 PM
*/
public abstract class HttpOutboundFilter extends BaseFilter<HttpResponseMessage, HttpResponseMessage> {
@Override
public FilterType filterType() {
return FilterType.OUTBOUND;
}
@Override
public HttpResponseMessage getDefaultOutput(HttpResponseMessage input) {
return input;
}
}
| 6,286 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpSyncEndpoint.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters.http;
import com.netflix.config.CachedDynamicBooleanProperty;
import com.netflix.zuul.filters.Endpoint;
import com.netflix.zuul.filters.SyncZuulFilter;
import com.netflix.zuul.message.ZuulMessage;
import com.netflix.zuul.message.http.HttpRequestMessage;
import com.netflix.zuul.message.http.HttpResponseMessage;
import com.netflix.zuul.message.http.HttpResponseMessageImpl;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.LastHttpContent;
import rx.Observable;
import rx.Subscriber;
/**
* User: Mike Smith
* Date: 6/16/15
* Time: 12:23 AM
*/
public abstract class HttpSyncEndpoint extends Endpoint<HttpRequestMessage, HttpResponseMessage>
implements SyncZuulFilter<HttpRequestMessage, HttpResponseMessage> {
// Feature flag for enabling this while we get some real data for the impact.
private static final CachedDynamicBooleanProperty WAIT_FOR_LASTCONTENT =
new CachedDynamicBooleanProperty("zuul.endpoint.sync.wait_for_lastcontent", true);
private static final String KEY_FOR_SUBSCRIBER = "_HttpSyncEndpoint_subscriber";
@Override
public HttpResponseMessage getDefaultOutput(HttpRequestMessage request) {
return HttpResponseMessageImpl.defaultErrorResponse(request);
}
@Override
public Observable<HttpResponseMessage> applyAsync(HttpRequestMessage input) {
if (WAIT_FOR_LASTCONTENT.get() && !input.hasCompleteBody()) {
// Return an observable that won't complete until after we have received the LastContent from client (ie.
// that we've
// received the whole request body), so that we can't potentially corrupt the clients' http state on this
// connection.
return Observable.create(subscriber -> {
ZuulMessage response = this.apply(input);
ResponseState state = new ResponseState(response, subscriber);
input.getContext().set(KEY_FOR_SUBSCRIBER, state);
});
} else {
return Observable.just(this.apply(input));
}
}
@Override
public HttpContent processContentChunk(ZuulMessage zuulMessage, HttpContent chunk) {
// Only call onNext() after we've received the LastContent of request from client.
if (chunk instanceof LastHttpContent) {
ResponseState state = (ResponseState) zuulMessage.getContext().get(KEY_FOR_SUBSCRIBER);
if (state != null) {
state.subscriber.onNext(state.response);
state.subscriber.onCompleted();
zuulMessage.getContext().remove(KEY_FOR_SUBSCRIBER);
}
}
return super.processContentChunk(zuulMessage, chunk);
}
@Override
public void incrementConcurrency() {
// NOOP, since this is supposed to be a SYNC filter in spirit
}
@Override
public void decrementConcurrency() {
// NOOP, since this is supposed to be a SYNC filter in spirit
}
private static class ResponseState {
final ZuulMessage response;
final Subscriber subscriber;
public ResponseState(ZuulMessage response, Subscriber subscriber) {
this.response = response;
this.subscriber = subscriber;
}
}
}
| 6,287 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpInboundSyncFilter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters.http;
import com.netflix.zuul.filters.BaseSyncFilter;
import com.netflix.zuul.filters.FilterType;
import com.netflix.zuul.message.http.HttpRequestMessage;
/**
* User: michaels@netflix.com
* Date: 5/29/15
* Time: 3:22 PM
*/
public abstract class HttpInboundSyncFilter extends BaseSyncFilter<HttpRequestMessage, HttpRequestMessage> {
@Override
public FilterType filterType() {
return FilterType.INBOUND;
}
}
| 6,288 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpInboundFilter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters.http;
import com.netflix.zuul.filters.BaseFilter;
import com.netflix.zuul.filters.FilterType;
import com.netflix.zuul.message.http.HttpRequestMessage;
/**
* User: michaels@netflix.com
* Date: 5/29/15
* Time: 3:22 PM
*/
public abstract class HttpInboundFilter extends BaseFilter<HttpRequestMessage, HttpRequestMessage> {
@Override
public FilterType filterType() {
return FilterType.INBOUND;
}
}
| 6,289 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/http/HttpOutboundSyncFilter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters.http;
import com.netflix.zuul.filters.BaseSyncFilter;
import com.netflix.zuul.filters.FilterType;
import com.netflix.zuul.message.http.HttpResponseMessage;
/**
* User: michaels@netflix.com
* Date: 5/29/15
* Time: 3:23 PM
*/
public abstract class HttpOutboundSyncFilter extends BaseSyncFilter<HttpResponseMessage, HttpResponseMessage> {
@Override
public FilterType filterType() {
return FilterType.OUTBOUND;
}
}
| 6,290 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/endpoint/ProxyEndpoint.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters.endpoint;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.errorprone.annotations.ForOverride;
import com.netflix.client.ClientException;
import com.netflix.client.config.IClientConfigKey;
import com.netflix.config.CachedDynamicLongProperty;
import com.netflix.config.DynamicIntegerSetProperty;
import com.netflix.netty.common.ByteBufUtil;
import com.netflix.spectator.api.Counter;
import com.netflix.zuul.Filter;
import com.netflix.zuul.context.CommonContextKeys;
import com.netflix.zuul.context.Debug;
import com.netflix.zuul.context.SessionContext;
import com.netflix.zuul.discovery.DiscoveryResult;
import com.netflix.zuul.exception.ErrorType;
import com.netflix.zuul.exception.OutboundErrorType;
import com.netflix.zuul.exception.OutboundException;
import com.netflix.zuul.exception.RequestExpiredException;
import com.netflix.zuul.exception.ZuulException;
import com.netflix.zuul.filters.FilterType;
import com.netflix.zuul.filters.SyncZuulFilterAdapter;
import com.netflix.zuul.message.HeaderName;
import com.netflix.zuul.message.Headers;
import com.netflix.zuul.message.ZuulMessage;
import com.netflix.zuul.message.http.HttpHeaderNames;
import com.netflix.zuul.message.http.HttpQueryParams;
import com.netflix.zuul.message.http.HttpRequestInfo;
import com.netflix.zuul.message.http.HttpRequestMessage;
import com.netflix.zuul.message.http.HttpResponseMessage;
import com.netflix.zuul.message.http.HttpResponseMessageImpl;
import com.netflix.zuul.netty.ChannelUtils;
import com.netflix.zuul.netty.NettyRequestAttemptFactory;
import com.netflix.zuul.netty.SpectatorUtils;
import com.netflix.zuul.netty.connectionpool.BasicRequestStat;
import com.netflix.zuul.netty.connectionpool.ClientTimeoutHandler;
import com.netflix.zuul.netty.connectionpool.DefaultOriginChannelInitializer;
import com.netflix.zuul.netty.connectionpool.PooledConnection;
import com.netflix.zuul.netty.connectionpool.RequestStat;
import com.netflix.zuul.netty.filter.FilterRunner;
import com.netflix.zuul.netty.server.ClientRequestReceiver;
import com.netflix.zuul.netty.server.MethodBinding;
import com.netflix.zuul.netty.server.OriginResponseReceiver;
import com.netflix.zuul.netty.timeouts.OriginTimeoutManager;
import com.netflix.zuul.niws.RequestAttempt;
import com.netflix.zuul.niws.RequestAttempts;
import com.netflix.zuul.origins.NettyOrigin;
import com.netflix.zuul.origins.Origin;
import com.netflix.zuul.origins.OriginManager;
import com.netflix.zuul.origins.OriginName;
import com.netflix.zuul.passport.CurrentPassport;
import com.netflix.zuul.passport.PassportState;
import com.netflix.zuul.stats.status.StatusCategory;
import com.netflix.zuul.stats.status.StatusCategoryUtils;
import com.netflix.zuul.stats.status.ZuulStatusCategory;
import com.netflix.zuul.util.HttpUtils;
import com.netflix.zuul.util.ProxyUtils;
import com.netflix.zuul.util.VipUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultLastHttpContent;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;
import io.perfmark.PerfMark;
import io.perfmark.TaskCloseable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.atomic.AtomicReference;
/**
* Not thread safe! New instance of this class is created per HTTP/1.1 request proxied to the origin but NOT for each
* attempt/retry. All the retry attempts for a given HTTP/1.1 request proxied share the same EdgeProxyEndpoint instance
* Created by saroskar on 5/31/17.
*/
@Filter(order = 0, type = FilterType.ENDPOINT)
public class ProxyEndpoint extends SyncZuulFilterAdapter<HttpRequestMessage, HttpResponseMessage>
implements GenericFutureListener<Future<PooledConnection>> {
private static final String ZUUL_ORIGIN_ATTEMPT_IPADDR_MAP_KEY = "_zuul_origin_attempt_ipaddr_map";
private static final String ZUUL_ORIGIN_REQUEST_URI = "_zuul_origin_request_uri";
private final ChannelHandlerContext channelCtx;
private final FilterRunner<HttpResponseMessage, ?> responseFilters;
protected final AtomicReference<DiscoveryResult> chosenServer;
protected final AtomicReference<InetAddress> chosenHostAddr;
/* Individual request related state */
protected final HttpRequestMessage zuulRequest;
protected final SessionContext context;
@Nullable
protected final NettyOrigin origin;
protected final RequestAttempts requestAttempts;
protected final CurrentPassport passport;
protected final NettyRequestAttemptFactory requestAttemptFactory;
protected final OriginTimeoutManager originTimeoutManager;
protected MethodBinding<?> methodBinding;
protected HttpResponseMessage zuulResponse;
protected boolean startedSendingResponseToClient;
protected Duration timeLeftForAttempt;
/* Individual retry related state */
private volatile PooledConnection originConn;
private volatile OriginResponseReceiver originResponseReceiver;
private volatile int concurrentReqCount;
private volatile boolean proxiedRequestWithoutBuffering;
protected int attemptNum;
protected RequestAttempt currentRequestAttempt;
protected List<RequestStat> requestStats = new ArrayList<>();
protected RequestStat currentRequestStat;
public static final Set<String> IDEMPOTENT_HTTP_METHODS = Sets.newHashSet("GET", "HEAD", "OPTIONS");
private static final DynamicIntegerSetProperty RETRIABLE_STATUSES_FOR_IDEMPOTENT_METHODS =
new DynamicIntegerSetProperty("zuul.retry.allowed.statuses.idempotent", "500");
/**
* Indicates how long Zuul should remember throttle events for an origin. As of this writing, throttling is used
* to decide to cache request bodies.
*/
private static final CachedDynamicLongProperty THROTTLE_MEMORY_SECONDS = new CachedDynamicLongProperty(
"zuul.proxy.throttle_memory_seconds", Duration.ofMinutes(5).getSeconds());
private static final Set<HeaderName> REQUEST_HEADERS_TO_REMOVE =
Sets.newHashSet(HttpHeaderNames.CONNECTION, HttpHeaderNames.KEEP_ALIVE);
private static final Set<HeaderName> RESPONSE_HEADERS_TO_REMOVE =
Sets.newHashSet(HttpHeaderNames.CONNECTION, HttpHeaderNames.KEEP_ALIVE);
public static final String POOLED_ORIGIN_CONNECTION_KEY = "_origin_pooled_conn";
private static final Logger logger = LoggerFactory.getLogger(ProxyEndpoint.class);
private static final Counter NO_RETRY_INCOMPLETE_BODY =
SpectatorUtils.newCounter("zuul.no.retry", "incomplete_body");
private static final Counter NO_RETRY_RESP_STARTED = SpectatorUtils.newCounter("zuul.no.retry", "resp_started");
public ProxyEndpoint(
final HttpRequestMessage inMesg,
final ChannelHandlerContext ctx,
final FilterRunner<HttpResponseMessage, ?> filters,
MethodBinding<?> methodBinding) {
this(inMesg, ctx, filters, methodBinding, new NettyRequestAttemptFactory());
}
public ProxyEndpoint(
final HttpRequestMessage inMesg,
final ChannelHandlerContext ctx,
final FilterRunner<HttpResponseMessage, ?> filters,
MethodBinding<?> methodBinding,
NettyRequestAttemptFactory requestAttemptFactory) {
channelCtx = ctx;
responseFilters = filters;
zuulRequest = transformRequest(inMesg);
context = zuulRequest.getContext();
origin = getOrigin(zuulRequest);
originTimeoutManager = getTimeoutManager(origin);
requestAttempts = RequestAttempts.getFromSessionContext(context);
passport = CurrentPassport.fromSessionContext(context);
chosenServer = new AtomicReference<>(DiscoveryResult.EMPTY);
chosenHostAddr = new AtomicReference<>();
this.methodBinding = methodBinding;
this.requestAttemptFactory = requestAttemptFactory;
}
public int getAttemptNum() {
return attemptNum;
}
public RequestAttempts getRequestAttempts() {
return requestAttempts;
}
protected RequestAttempt getCurrentRequestAttempt() {
return currentRequestAttempt;
}
public CurrentPassport getPassport() {
return passport;
}
public NettyOrigin getOrigin() {
return origin;
}
public HttpRequestMessage getZuulRequest() {
return zuulRequest;
}
// Unlink OriginResponseReceiver from origin channel pipeline so that we no longer receive events
private Channel unlinkFromOrigin() {
if (originResponseReceiver != null) {
originResponseReceiver.unlinkFromClientRequest();
originResponseReceiver = null;
}
if (concurrentReqCount > 0) {
origin.recordProxyRequestEnd();
concurrentReqCount--;
}
Channel origCh = null;
if (originConn != null) {
origCh = originConn.getChannel();
originConn = null;
}
return origCh;
}
private void releasePartialResponse(HttpResponse partialResponse) {
if (partialResponse != null && ReferenceCountUtil.refCnt(partialResponse) > 0) {
ReferenceCountUtil.safeRelease(partialResponse);
}
}
public void finish(boolean error) {
final Channel origCh = unlinkFromOrigin();
while (concurrentReqCount > 0) {
origin.recordProxyRequestEnd();
concurrentReqCount--;
}
if (currentRequestStat != null) {
if (error) {
currentRequestStat.generalError();
}
}
// Publish each of the request stats (ie. one for each attempt).
if (!requestStats.isEmpty()) {
int indexFinal = requestStats.size() - 1;
for (int i = 0; i < requestStats.size(); i++) {
RequestStat stat = requestStats.get(i);
// Tag the final and non-final attempts.
stat.finalAttempt(i == indexFinal);
stat.finishIfNotAlready();
}
}
if ((error) && (origCh != null)) {
origCh.close();
}
}
/* Zuul filter methods */
@Override
public String filterName() {
return "ProxyEndpoint";
}
@Override
public HttpResponseMessage apply(final HttpRequestMessage input) {
// If no Origin has been selected, then just return a 404 static response.
// handle any exception here
try {
if (origin == null) {
handleNoOriginSelected();
return null;
}
origin.onRequestExecutionStart(zuulRequest);
proxyRequestToOrigin();
// Doesn't return origin response to caller, calls invokeNext() internally in response filter chain
return null;
} catch (Exception ex) {
handleError(ex);
return null;
}
}
@Override
public HttpContent processContentChunk(final ZuulMessage zuulReq, final HttpContent chunk) {
if (originConn != null) {
// Connected to origin, stream request body without buffering
proxiedRequestWithoutBuffering = true;
ByteBufUtil.touch(chunk, "ProxyEndpoint writing chunk to origin, request: ", zuulReq);
originConn.getChannel().writeAndFlush(chunk);
return null;
}
// Not connected to origin yet, let caller buffer the request body
ByteBufUtil.touch(chunk, "ProxyEndpoint buffering chunk to origin, request: ", zuulReq);
return chunk;
}
@Override
public HttpResponseMessage getDefaultOutput(final HttpRequestMessage input) {
return null;
}
public void invokeNext(final HttpResponseMessage zuulResponse) {
try {
methodBinding.bind(() -> filterResponse(zuulResponse));
} catch (Exception ex) {
unlinkFromOrigin();
logger.error("Error in invokeNext resp", ex);
channelCtx.fireExceptionCaught(ex);
}
}
private void filterResponse(final HttpResponseMessage zuulResponse) {
if (responseFilters != null) {
responseFilters.filter(zuulResponse);
} else {
channelCtx.fireChannelRead(zuulResponse);
}
}
public void invokeNext(final HttpContent chunk) {
try {
ByteBufUtil.touch(chunk, "ProxyEndpoint received chunk from origin, request: ", zuulRequest);
methodBinding.bind(() -> filterResponseChunk(chunk));
} catch (Exception ex) {
ByteBufUtil.touch(chunk, "ProxyEndpoint exception processing chunk from origin, request: ", zuulRequest);
unlinkFromOrigin();
logger.error("Error in invokeNext content", ex);
channelCtx.fireExceptionCaught(ex);
}
}
private void filterResponseChunk(final HttpContent chunk) {
if (context.isCancelled() || !channelCtx.channel().isActive()) {
SpectatorUtils.newCounter(
"zuul.origin.strayChunk",
origin == null ? "none" : origin.getName().getMetricId())
.increment();
unlinkFromOrigin();
ReferenceCountUtil.safeRelease(chunk);
return;
}
if (chunk instanceof LastHttpContent) {
unlinkFromOrigin();
}
if (responseFilters != null) {
responseFilters.filter(zuulResponse, chunk);
} else {
channelCtx.fireChannelRead(chunk);
}
}
private void storeAndLogOriginRequestInfo() {
final Map<String, Object> eventProps = context.getEventProperties();
// These two maps appear to be almost the same but are slightly different. Also, the types in the map don't
// match exactly what needs to happen, so this is more of a To-Do. ZUUL_ORIGIN_ATTEMPT_IPADDR_MAP_KEY is
// supposed to be the mapping of IP addresses of the server. This is (AFAICT) only used for logging. It is
// an IP address semantically, but a String here. The two should be swapped.
// ZUUL_ORIGIN_CHOSEN_HOST_ADDR_MAP_KEY is almost always an IP address, but may some times be a hostname in
// case the discovery info is not an IP.
Map<Integer, String> attemptToIpAddressMap =
(Map<Integer, String>) eventProps.get(ZUUL_ORIGIN_ATTEMPT_IPADDR_MAP_KEY);
Map<Integer, InetAddress> attemptToChosenHostMap = (Map<Integer, InetAddress>)
eventProps.get(CommonContextKeys.ZUUL_ORIGIN_CHOSEN_HOST_ADDR_MAP_KEY.name());
if (attemptToIpAddressMap == null) {
attemptToIpAddressMap = new HashMap<>();
}
if (attemptToChosenHostMap == null) {
attemptToChosenHostMap = new HashMap<>();
}
// the chosen server can be null in the case of a timeout exception that skips acquiring a new origin connection
String ipAddr = origin.getIpAddrFromServer(chosenServer.get());
if (ipAddr != null) {
attemptToIpAddressMap.put(attemptNum, ipAddr);
eventProps.put(ZUUL_ORIGIN_ATTEMPT_IPADDR_MAP_KEY, attemptToIpAddressMap);
}
if (chosenHostAddr.get() != null) {
attemptToChosenHostMap.put(attemptNum, chosenHostAddr.get());
eventProps.put(CommonContextKeys.ZUUL_ORIGIN_CHOSEN_HOST_ADDR_MAP_KEY.name(), attemptToChosenHostMap);
context.put(CommonContextKeys.ZUUL_ORIGIN_CHOSEN_HOST_ADDR_MAP_KEY, attemptToChosenHostMap);
}
eventProps.put(ZUUL_ORIGIN_REQUEST_URI, zuulRequest.getPathAndQuery());
}
protected void updateOriginRpsTrackers(NettyOrigin origin, int attempt) {
// override
}
private void proxyRequestToOrigin() {
Promise<PooledConnection> promise = null;
try {
attemptNum += 1;
/*
* Before connecting to the origin, we need to compute how much time we have left for this attempt. This
* method is also intended to validate deadline and timeouts boundaries for the request as a whole and could
* throw an exception, skipping the logic below.
*/
timeLeftForAttempt = originTimeoutManager.computeReadTimeout(zuulRequest, attemptNum);
currentRequestStat = createRequestStat();
origin.preRequestChecks(zuulRequest);
concurrentReqCount++;
// update RPS trackers
updateOriginRpsTrackers(origin, attemptNum);
// We pass this AtomicReference<Server> here and the origin impl will assign the chosen server to it.
promise = origin.connectToOrigin(
zuulRequest, channelCtx.channel().eventLoop(), attemptNum, passport, chosenServer, chosenHostAddr);
storeAndLogOriginRequestInfo();
currentRequestAttempt =
origin.newRequestAttempt(chosenServer.get(), chosenHostAddr.get(), context, attemptNum);
requestAttempts.add(currentRequestAttempt);
passport.add(PassportState.ORIGIN_CONN_ACQUIRE_START);
if (promise.isDone()) {
operationComplete(promise);
} else {
promise.addListener(this);
}
} catch (Exception ex) {
if (ex instanceof RequestExpiredException) {
logger.debug("Request deadline expired while connecting to origin, UUID {}", context.getUUID(), ex);
} else {
logger.error("Error while connecting to origin, UUID {}", context.getUUID(), ex);
}
storeAndLogOriginRequestInfo();
if (promise != null && !promise.isDone()) {
promise.setFailure(ex);
} else {
errorFromOrigin(ex);
}
}
}
/**
* Override to track your own request stats.
*/
protected RequestStat createRequestStat() {
BasicRequestStat basicRequestStat = new BasicRequestStat();
requestStats.add(basicRequestStat);
RequestStat.putInSessionContext(basicRequestStat, context);
return basicRequestStat;
}
@Override
public void operationComplete(final Future<PooledConnection> connectResult) {
// MUST run this within bindingcontext to support ThreadVariables.
try {
methodBinding.bind(() -> {
DiscoveryResult server = chosenServer.get();
/** TODO(argha-c): This reliance on mutable update of the `chosenServer` must be improved.
* @see DiscoveryResult.EMPTY indicates that the loadbalancer found no available servers.
*/
if (server != DiscoveryResult.EMPTY) {
if (currentRequestStat != null) {
currentRequestStat.server(server);
}
origin.onRequestStartWithServer(zuulRequest, server, attemptNum);
}
// Handle the connection establishment result.
if (connectResult.isSuccess()) {
onOriginConnectSucceeded(connectResult.getNow(), timeLeftForAttempt);
} else {
onOriginConnectFailed(connectResult.cause());
}
});
} catch (Throwable ex) {
logger.error(
"Uncaught error in operationComplete(). Closing the server channel now. {}",
ChannelUtils.channelInfoForLogging(channelCtx.channel()),
ex);
unlinkFromOrigin();
// Fire exception here to ensure that server channel gets closed, so clients don't hang.
channelCtx.fireExceptionCaught(ex);
}
}
private void onOriginConnectSucceeded(PooledConnection conn, Duration readTimeout) {
passport.add(PassportState.ORIGIN_CONN_ACQUIRE_END);
if (context.isCancelled()) {
logger.info("Client cancelled after successful origin connect: {}", conn.getChannel());
// conn isn't actually busy so we can put it in the pool
conn.setConnectionState(PooledConnection.ConnectionState.WRITE_READY);
conn.release();
} else {
// Update the RequestAttempt to reflect the readTimeout chosen.
currentRequestAttempt.setReadTimeout(readTimeout.toMillis());
// Start sending the request to origin now.
writeClientRequestToOrigin(conn, readTimeout);
}
}
private void onOriginConnectFailed(Throwable cause) {
passport.add(PassportState.ORIGIN_CONN_ACQUIRE_FAILED);
if (!context.isCancelled()) {
errorFromOrigin(cause);
}
}
private void writeClientRequestToOrigin(final PooledConnection conn, Duration readTimeout) {
final Channel ch = conn.getChannel();
passport.setOnChannel(ch);
// set read timeout on origin channel
ch.attr(ClientTimeoutHandler.ORIGIN_RESPONSE_READ_TIMEOUT).set(readTimeout);
context.put(CommonContextKeys.ORIGIN_CHANNEL, ch);
context.set(POOLED_ORIGIN_CONNECTION_KEY, conn);
preWriteToOrigin(chosenServer.get(), zuulRequest);
final ChannelPipeline pipeline = ch.pipeline();
originResponseReceiver = getOriginResponseReceiver();
pipeline.addBefore(
DefaultOriginChannelInitializer.CONNECTION_POOL_HANDLER,
OriginResponseReceiver.CHANNEL_HANDLER_NAME,
originResponseReceiver);
ch.write(zuulRequest);
writeBufferedBodyContent(zuulRequest, ch);
ch.flush();
// Get ready to read origin's response
ch.read();
originConn = conn;
channelCtx.read();
}
protected OriginResponseReceiver getOriginResponseReceiver() {
return new OriginResponseReceiver(this);
}
protected void preWriteToOrigin(DiscoveryResult chosenServer, HttpRequestMessage zuulRequest) {
// override for custom metrics or processing
}
private static void writeBufferedBodyContent(final HttpRequestMessage zuulRequest, final Channel channel) {
zuulRequest.getBodyContents().forEach((chunk) -> {
channel.write(chunk.retain());
});
}
protected boolean isRemoteZuulRetriesBelowRetryLimit(int maxAllowedRetries) {
// override for custom header checking..
return true;
}
protected boolean isBelowRetryLimit() {
int maxAllowedRetries = origin.getMaxRetriesForRequest(context);
return (attemptNum <= maxAllowedRetries) && isRemoteZuulRetriesBelowRetryLimit(maxAllowedRetries);
}
public void errorFromOrigin(final Throwable ex) {
try {
// Flag that there was an origin server related error for the loadbalancer to choose
// whether to circuit-trip this server.
if (originConn != null) {
// NOTE: if originConn is null, then these stats will have been incremented within
// PerServerConnectionPool
// so don't need to be here.
originConn.getServer().incrementSuccessiveConnectionFailureCount();
originConn.getServer().addToFailureCount();
originConn.flagShouldClose();
}
// detach from current origin
final Channel originCh = unlinkFromOrigin();
methodBinding.bind(() -> processErrorFromOrigin(ex, originCh));
} catch (Exception e) {
channelCtx.fireExceptionCaught(ex);
}
}
private void processErrorFromOrigin(final Throwable ex, final Channel origCh) {
try {
final SessionContext zuulCtx = context;
final ErrorType err = requestAttemptFactory.mapNettyToOutboundErrorType(ex);
// Be cautious about how much we log about errors from origins, as it can have perf implications at high
// rps.
if (zuulCtx.isInBrownoutMode()) {
// Don't include the stacktrace or the channel info.
logger.warn(
"{}, origin = {}: {}", err.getStatusCategory().name(), origin.getName(), String.valueOf(ex));
} else {
final String origChInfo = (origCh != null) ? ChannelUtils.channelInfoForLogging(origCh) : "";
if (logger.isInfoEnabled()) {
// Include the stacktrace.
logger.warn(
"{}, origin = {}, origin channel info = {}",
err.getStatusCategory().name(),
origin.getName(),
origChInfo,
ex);
} else {
logger.warn(
"{}, origin = {}, {}, origin channel info = {}",
err.getStatusCategory().name(),
origin.getName(),
String.valueOf(ex),
origChInfo);
}
}
// Update the NIWS stat.
if (currentRequestStat != null) {
currentRequestStat.failAndSetErrorCode(err);
}
// Update RequestAttempt info.
if (currentRequestAttempt != null) {
currentRequestAttempt.complete(-1, currentRequestStat.duration(), ex);
}
postErrorProcessing(ex, zuulCtx, err, chosenServer.get(), attemptNum);
final ClientException niwsEx = new ClientException(
ClientException.ErrorType.valueOf(err.getClientErrorType().name()));
if (chosenServer.get() != DiscoveryResult.EMPTY) {
origin.onRequestExceptionWithServer(zuulRequest, chosenServer.get(), attemptNum, niwsEx);
}
if ((isBelowRetryLimit()) && (isRetryable(err))) {
// retry request with different origin
passport.add(PassportState.ORIGIN_RETRY_START);
origin.adjustRetryPolicyIfNeeded(zuulRequest);
proxyRequestToOrigin();
} else {
// Record the exception in context. An error filter should later run which can translate this into an
// app-specific error response if needed.
zuulCtx.setError(ex);
zuulCtx.setShouldSendErrorResponse(true);
StatusCategoryUtils.storeStatusCategoryIfNotAlreadyFailure(zuulCtx, err.getStatusCategory());
origin.recordFinalError(zuulRequest, ex);
origin.onRequestExecutionFailed(zuulRequest, chosenServer.get(), attemptNum - 1, niwsEx);
// Send error response to client
handleError(ex);
}
} catch (Exception e) {
// Use original origin returned exception
handleError(ex);
}
}
protected void postErrorProcessing(
Throwable ex, SessionContext zuulCtx, ErrorType err, DiscoveryResult chosenServer, int attemptNum) {
// override for custom processing
}
private void handleError(final Throwable cause) {
final ZuulException ze = (cause instanceof ZuulException)
? (ZuulException) cause
: requestAttemptFactory.mapNettyToOutboundException(cause, context);
logger.debug("Proxy endpoint failed.", cause);
if (!startedSendingResponseToClient) {
startedSendingResponseToClient = true;
zuulResponse = new HttpResponseMessageImpl(context, zuulRequest, ze.getStatusCode());
zuulResponse
.getHeaders()
.add(
"Connection",
"close"); // TODO - why close the connection? maybe don't always want this to happen ...
zuulResponse.finishBufferedBodyIfIncomplete();
invokeNext(zuulResponse);
} else {
channelCtx.fireExceptionCaught(ze);
}
}
private void handleNoOriginSelected() {
StatusCategoryUtils.setStatusCategory(context, ZuulStatusCategory.SUCCESS_LOCAL_NO_ROUTE);
startedSendingResponseToClient = true;
zuulResponse = new HttpResponseMessageImpl(context, zuulRequest, 404);
zuulResponse.finishBufferedBodyIfIncomplete();
invokeNext(zuulResponse);
}
protected boolean isRetryable(final ErrorType err) {
if ((err == OutboundErrorType.RESET_CONNECTION)
|| (err == OutboundErrorType.CONNECT_ERROR)
|| (err == OutboundErrorType.READ_TIMEOUT
&& IDEMPOTENT_HTTP_METHODS.contains(
zuulRequest.getMethod().toUpperCase()))) {
return isRequestReplayable();
}
return false;
}
/**
* Request is replayable on a different origin IFF
* A) we have not started to send response back to the client AND
* B) we have not lost any of its body chunks
*/
protected boolean isRequestReplayable() {
if (startedSendingResponseToClient) {
NO_RETRY_RESP_STARTED.increment();
return false;
}
if (proxiedRequestWithoutBuffering) {
NO_RETRY_INCOMPLETE_BODY.increment();
return false;
}
return true;
}
public void responseFromOrigin(final HttpResponse originResponse) {
try (TaskCloseable ignore = PerfMark.traceTask("ProxyEndpoint.responseFromOrigin")) {
PerfMark.attachTag("uuid", zuulRequest, r -> r.getContext().getUUID());
PerfMark.attachTag("path", zuulRequest, HttpRequestInfo::getPath);
ByteBufUtil.touch(originResponse, "ProxyEndpoint handling response from origin, request: ", zuulRequest);
methodBinding.bind(() -> processResponseFromOrigin(originResponse));
} catch (Exception ex) {
unlinkFromOrigin();
releasePartialResponse(originResponse);
logger.error("Error in responseFromOrigin", ex);
channelCtx.fireExceptionCaught(ex);
}
}
private void processResponseFromOrigin(final HttpResponse originResponse) {
if (originResponse.status().code() >= 500) {
handleOriginNonSuccessResponse(originResponse, chosenServer.get());
} else {
handleOriginSuccessResponse(originResponse, chosenServer.get());
}
}
protected void handleOriginSuccessResponse(final HttpResponse originResponse, DiscoveryResult chosenServer) {
origin.recordSuccessResponse();
if (originConn != null) {
originConn.getServer().clearSuccessiveConnectionFailureCount();
}
final int respStatus = originResponse.status().code();
long duration = 0;
if (currentRequestStat != null) {
currentRequestStat.updateWithHttpStatusCode(respStatus);
duration = currentRequestStat.duration();
}
if (currentRequestAttempt != null) {
currentRequestAttempt.complete(respStatus, duration, null);
}
// separate nfstatus for 404 so that we can notify origins
ByteBufUtil.touch(originResponse, "ProxyEndpoint handling successful response, request: ", zuulRequest);
final StatusCategory statusCategory =
respStatus == 404 ? ZuulStatusCategory.SUCCESS_NOT_FOUND : ZuulStatusCategory.SUCCESS;
zuulResponse = buildZuulHttpResponse(originResponse, statusCategory, context.getError());
invokeNext(zuulResponse);
}
private HttpResponseMessage buildZuulHttpResponse(
final HttpResponse httpResponse, final StatusCategory statusCategory, final Throwable ex) {
startedSendingResponseToClient = true;
// Translate the netty HttpResponse into a zuul HttpResponseMessage.
final SessionContext zuulCtx = context;
final int respStatus = httpResponse.status().code();
final HttpResponseMessage zuulResponse = new HttpResponseMessageImpl(zuulCtx, zuulRequest, respStatus);
final Headers respHeaders = zuulResponse.getHeaders();
for (Map.Entry<String, String> entry : httpResponse.headers()) {
respHeaders.add(entry.getKey(), entry.getValue());
}
// Try to decide if this response has a body or not based on the headers (as we won't yet have
// received any of the content).
// NOTE that we also later may override this if it is Chunked encoding, but we receive
// a LastHttpContent without any prior HttpContent's.
if (HttpUtils.hasChunkedTransferEncodingHeader(zuulResponse)
|| HttpUtils.hasNonZeroContentLengthHeader(zuulResponse)) {
zuulResponse.setHasBody(true);
}
// Store this original response info for future reference (ie. for metrics and access logging purposes).
zuulResponse.storeInboundResponse();
channelCtx.channel().attr(ClientRequestReceiver.ATTR_ZUUL_RESP).set(zuulResponse);
if (httpResponse instanceof DefaultFullHttpResponse) {
ByteBufUtil.touch(
httpResponse, "ProxyEndpoint converting Netty response to Zuul response, request: ", zuulRequest);
final ByteBuf chunk = ((DefaultFullHttpResponse) httpResponse).content();
zuulResponse.bufferBodyContents(new DefaultLastHttpContent(chunk));
}
// Invoke any Ribbon execution listeners.
// Request was a success even if server may have responded with an error code 5XX, except for 503.
if (originConn != null) {
if (statusCategory == ZuulStatusCategory.FAILURE_ORIGIN_THROTTLED) {
origin.onRequestExecutionFailed(
zuulRequest,
originConn.getServer(),
attemptNum,
new ClientException(ClientException.ErrorType.SERVER_THROTTLED));
} else {
origin.onRequestExecutionSuccess(zuulRequest, zuulResponse, originConn.getServer(), attemptNum);
}
}
// Collect some info about the received response.
origin.recordFinalResponse(zuulResponse);
origin.recordFinalError(zuulRequest, ex);
StatusCategoryUtils.setStatusCategory(zuulCtx, statusCategory);
zuulCtx.setError(ex);
zuulCtx.put("origin_http_status", Integer.toString(respStatus));
return transformResponse(zuulResponse);
}
private HttpResponseMessage transformResponse(HttpResponseMessage resp) {
RESPONSE_HEADERS_TO_REMOVE.stream().forEach(s -> resp.getHeaders().remove(s));
return resp;
}
protected void handleOriginNonSuccessResponse(final HttpResponse originResponse, DiscoveryResult chosenServer) {
final int respStatus = originResponse.status().code();
OutboundException obe;
StatusCategory statusCategory;
ClientException.ErrorType niwsErrorType;
if (respStatus == 503) {
statusCategory = ZuulStatusCategory.FAILURE_ORIGIN_THROTTLED;
niwsErrorType = ClientException.ErrorType.SERVER_THROTTLED;
obe = new OutboundException(OutboundErrorType.SERVICE_UNAVAILABLE, requestAttempts);
if (currentRequestStat != null) {
currentRequestStat.updateWithHttpStatusCode(respStatus);
currentRequestStat.serviceUnavailable();
}
} else {
statusCategory = ZuulStatusCategory.FAILURE_ORIGIN;
niwsErrorType = ClientException.ErrorType.GENERAL;
obe = new OutboundException(OutboundErrorType.ERROR_STATUS_RESPONSE, requestAttempts);
if (currentRequestStat != null) {
currentRequestStat.updateWithHttpStatusCode(respStatus);
currentRequestStat.generalError();
}
}
obe.setStatusCode(respStatus);
long duration = 0;
if (currentRequestStat != null) {
duration = currentRequestStat.duration();
}
if (currentRequestAttempt != null) {
currentRequestAttempt.complete(respStatus, duration, obe);
}
// Flag this error with the ExecutionListener.
origin.onRequestExceptionWithServer(zuulRequest, chosenServer, attemptNum, new ClientException(niwsErrorType));
if ((isBelowRetryLimit()) && (isRetryable5xxResponse(zuulRequest, originResponse))) {
logger.debug(
"Retrying: status={}, attemptNum={}, maxRetries={}, startedSendingResponseToClient={}, hasCompleteBody={}, method={}",
respStatus,
attemptNum,
origin.getMaxRetriesForRequest(context),
startedSendingResponseToClient,
zuulRequest.hasCompleteBody(),
zuulRequest.getMethod());
// detach from current origin.
ByteBufUtil.touch(originResponse, "ProxyEndpoint handling non-success retry, request: ", zuulRequest);
unlinkFromOrigin();
releasePartialResponse(originResponse);
// ensure body reader indexes are reset so retry is able to access the body buffer
// otherwise when the body is read by netty (in writeBufferedBodyContent) the body will appear empty
zuulRequest.resetBodyReader();
// retry request with different origin
passport.add(PassportState.ORIGIN_RETRY_START);
origin.adjustRetryPolicyIfNeeded(zuulRequest);
proxyRequestToOrigin();
} else {
SessionContext zuulCtx = context;
logger.info(
"Sending error to client: status={}, attemptNum={}, maxRetries={}, startedSendingResponseToClient={}, hasCompleteBody={}, method={}",
respStatus,
attemptNum,
origin.getMaxRetriesForRequest(zuulCtx),
startedSendingResponseToClient,
zuulRequest.hasCompleteBody(),
zuulRequest.getMethod());
// This is a final response after all retries that will go to the client
ByteBufUtil.touch(originResponse, "ProxyEndpoint handling non-success response, request: ", zuulRequest);
zuulResponse = buildZuulHttpResponse(originResponse, statusCategory, obe);
invokeNext(zuulResponse);
}
}
public boolean isRetryable5xxResponse(
final HttpRequestMessage zuulRequest, HttpResponse originResponse) { // int retryNum, int maxRetries) {
if (isRequestReplayable()) {
int status = originResponse.status().code();
if (status == 503 || originIndicatesRetryableInternalServerError(originResponse)) {
return true;
}
// Retry if this is an idempotent http method AND status code was retriable for idempotent methods.
else if (RETRIABLE_STATUSES_FOR_IDEMPOTENT_METHODS.get().contains(status)
&& IDEMPOTENT_HTTP_METHODS.contains(zuulRequest.getMethod().toUpperCase())) {
return true;
}
}
return false;
}
protected boolean originIndicatesRetryableInternalServerError(final HttpResponse response) {
// override for custom origin headers for retry
return false;
}
/* static utility methods */
protected HttpRequestMessage transformRequest(HttpRequestMessage requestMsg) {
final HttpRequestMessage massagedRequest = massageRequestURI(requestMsg);
Headers headers = massagedRequest.getHeaders();
REQUEST_HEADERS_TO_REMOVE.forEach(headerName -> headers.remove(headerName.getName()));
addCustomRequestHeaders(headers);
// Add X-Forwarded headers if not already there.
ProxyUtils.addXForwardedHeaders(massagedRequest);
return massagedRequest;
}
protected void addCustomRequestHeaders(Headers headers) {
// override to add custom headers
}
private static HttpRequestMessage massageRequestURI(HttpRequestMessage request) {
final SessionContext context = request.getContext();
String modifiedPath;
HttpQueryParams modifiedQueryParams = null;
String uri = null;
if (context.get("requestURI") != null) {
uri = (String) context.get("requestURI");
}
// If another filter has specified an overrideURI, then use that instead of requested URI.
final Object override = context.get("overrideURI");
if (override != null) {
uri = override.toString();
}
if (null != uri) {
int index = uri.indexOf('?');
if (index != -1) {
// Strip the query string off of the URI.
String paramString = uri.substring(index + 1);
modifiedPath = uri.substring(0, index);
try {
paramString = URLDecoder.decode(paramString, "UTF-8");
modifiedQueryParams = new HttpQueryParams();
StringTokenizer stk = new StringTokenizer(paramString, "&");
while (stk.hasMoreTokens()) {
String token = stk.nextToken();
int idx = token.indexOf("=");
if (idx != -1) {
String key = token.substring(0, idx);
String val = token.substring(idx + 1);
modifiedQueryParams.add(key, val);
}
}
} catch (UnsupportedEncodingException e) {
logger.error("Error decoding url query param - {}", paramString, e);
}
} else {
modifiedPath = uri;
}
request.setPath(modifiedPath);
if (null != modifiedQueryParams) {
request.setQueryParams(modifiedQueryParams);
}
}
return request;
}
/**
* Get the implementing origin.
*
* Note: this method gets called in the constructor so if overloading it or any methods called within, you cannot
* rely on your own constructor parameters.
*/
@Nullable
protected NettyOrigin getOrigin(HttpRequestMessage request) {
SessionContext context = request.getContext();
OriginManager<NettyOrigin> originManager =
(OriginManager<NettyOrigin>) context.get(CommonContextKeys.ORIGIN_MANAGER);
if (Debug.debugRequest(context)) {
ImmutableList.Builder<String> routingLogEntries = context.get(CommonContextKeys.ROUTING_LOG);
if (routingLogEntries != null) {
for (String entry : routingLogEntries.build()) {
Debug.addRequestDebug(context, "RoutingLog: " + entry);
}
}
}
String primaryRoute = context.getRouteVIP();
if (Strings.isNullOrEmpty(primaryRoute)) {
// If no vip selected, leave origin null, then later the handleNoOriginSelected() method will be invoked.
return null;
}
// make sure the restClientName will never be a raw VIP in cases where it's the fallback for another route
// assignment
String restClientVIP = primaryRoute;
boolean useFullName = context.getBoolean(CommonContextKeys.USE_FULL_VIP_NAME);
String restClientName = useFullName ? restClientVIP : VipUtils.getVIPPrefix(restClientVIP);
NettyOrigin origin = null;
// allow implementors to override the origin with custom injection logic
OriginName overrideOriginName = injectCustomOriginName(request);
if (overrideOriginName != null) {
// Use the custom vip instead if one has been provided.
origin = getOrCreateOrigin(originManager, overrideOriginName, request.reconstructURI(), context);
} else if (restClientName != null) {
// This is the normal flow - that a RoutingFilter has assigned a route
OriginName originName = OriginName.fromVip(restClientVIP, restClientName);
origin = getOrCreateOrigin(originManager, originName, request.reconstructURI(), context);
}
verifyOrigin(context, request, restClientName, origin);
// Update the routeVip on context to show the actual raw VIP from the clientConfig of the chosen Origin.
if (origin != null) {
context.set(
CommonContextKeys.ACTUAL_VIP,
origin.getClientConfig().get(IClientConfigKey.Keys.DeploymentContextBasedVipAddresses));
context.set(
CommonContextKeys.ORIGIN_VIP_SECURE,
origin.getClientConfig().get(IClientConfigKey.Keys.IsSecure));
}
return origin;
}
/**
* Inject your own custom VIP based on your own processing
*
* Note: this method gets called in the constructor so if overloading it or any methods called within, you cannot
* rely on your own constructor parameters.
*
* @return {@code null} if unused.
*/
@Nullable
protected OriginName injectCustomOriginName(HttpRequestMessage request) {
// override for custom vip injection
return null;
}
private NettyOrigin getOrCreateOrigin(
OriginManager<NettyOrigin> originManager, OriginName originName, String uri, SessionContext ctx) {
NettyOrigin origin = originManager.getOrigin(originName, uri, ctx);
if (origin == null) {
// If no pre-registered and configured RestClient found for this VIP, then register one using default NIWS
// properties.
logger.warn(
"Attempting to register RestClient for client that has not been configured. originName={}, uri={}",
originName,
uri);
origin = originManager.createOrigin(originName, uri, ctx);
}
return origin;
}
private void verifyOrigin(
SessionContext context, HttpRequestMessage request, String restClientName, Origin primaryOrigin) {
if (primaryOrigin == null) {
// If no origin found then add specific error-cause metric tag, and throw an exception with 404 status.
StatusCategoryUtils.setStatusCategory(
context,
ZuulStatusCategory.SUCCESS_LOCAL_NO_ROUTE,
"Unable to find an origin client matching `" + restClientName + "` to handle request");
String causeName = "RESTCLIENT_NOTFOUND";
originNotFound(context, causeName);
ZuulException ze = new ZuulException(
"No origin found for request. name=" + restClientName + ", uri=" + request.reconstructURI(),
causeName);
ze.setStatusCode(404);
throw ze;
}
}
@ForOverride
protected void originNotFound(SessionContext context, String causeName) {
// override for metrics or custom processing
}
@ForOverride
protected OriginTimeoutManager getTimeoutManager(NettyOrigin origin) {
return new OriginTimeoutManager(origin);
}
}
| 6,291 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/filters/endpoint/MissingEndpointHandlingFilter.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.filters.endpoint;
import com.netflix.zuul.Filter;
import com.netflix.zuul.context.SessionContext;
import com.netflix.zuul.exception.ZuulException;
import com.netflix.zuul.filters.FilterType;
import com.netflix.zuul.filters.SyncZuulFilterAdapter;
import com.netflix.zuul.message.http.HttpRequestMessage;
import com.netflix.zuul.message.http.HttpResponseMessage;
import com.netflix.zuul.message.http.HttpResponseMessageImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by saroskar on 2/13/17.
*/
@Filter(order = 0, type = FilterType.ENDPOINT)
public final class MissingEndpointHandlingFilter
extends SyncZuulFilterAdapter<HttpRequestMessage, HttpResponseMessage> {
private final String name;
private static final Logger LOG = LoggerFactory.getLogger(MissingEndpointHandlingFilter.class);
public MissingEndpointHandlingFilter(String name) {
this.name = name;
}
@Override
public HttpResponseMessage apply(HttpRequestMessage request) {
final SessionContext zuulCtx = request.getContext();
zuulCtx.setErrorResponseSent(true);
final String errMesg = "Missing Endpoint filter, name = " + name;
zuulCtx.setError(new ZuulException(errMesg, true));
LOG.error(errMesg);
return new HttpResponseMessageImpl(zuulCtx, request, 500);
}
@Override
public String filterName() {
return name;
}
@Override
public HttpResponseMessage getDefaultOutput(final HttpRequestMessage input) {
return HttpResponseMessageImpl.defaultErrorResponse(input);
}
}
| 6,292 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/metrics/OriginStats.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.metrics;
/**
* User: michaels@netflix.com
* Date: 3/20/15
* Time: 5:55 PM
*/
public interface OriginStats {
public void started();
public void completed(boolean success, long totalTimeMS);
}
| 6,293 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/metrics/OriginStatsFactory.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.metrics;
/**
* User: michaels@netflix.com
* Date: 3/20/15
* Time: 6:14 PM
*/
public interface OriginStatsFactory {
public OriginStats create(String name);
}
| 6,294 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/niws/RequestAttempt.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.niws;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Throwables;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.client.config.IClientConfig;
import com.netflix.client.config.IClientConfigKey;
import com.netflix.zuul.discovery.DiscoveryResult;
import com.netflix.zuul.discovery.SimpleMetaInfo;
import com.netflix.zuul.exception.OutboundException;
import com.netflix.zuul.netty.connectionpool.OriginConnectException;
import io.netty.handler.timeout.ReadTimeoutException;
import javax.net.ssl.SSLHandshakeException;
import java.net.InetAddress;
/**
* User: michaels@netflix.com
* Date: 9/2/14
* Time: 2:52 PM
*/
public class RequestAttempt {
private static final ObjectMapper JACKSON_MAPPER = new ObjectMapper();
private int attempt;
private int status;
private long duration;
private String cause;
private String error;
private String exceptionType;
private String app;
private String asg;
private String instanceId;
private String host;
private int port;
private String ipAddress;
private String vip;
private String region;
private String availabilityZone;
private long readTimeout;
private int connectTimeout;
private int maxRetries;
public RequestAttempt(
int attemptNumber,
InstanceInfo server,
InetAddress serverAddr,
String targetVip,
String chosenWarmupLB,
int status,
String error,
String exceptionType,
int readTimeout,
int connectTimeout,
int maxRetries) {
if (attemptNumber < 1) {
throw new IllegalArgumentException("Attempt number must be greater than 0! - " + attemptNumber);
}
this.attempt = attemptNumber;
this.vip = targetVip;
if (server != null) {
this.app = server.getAppName().toLowerCase();
this.asg = server.getASGName();
this.instanceId = server.getInstanceId();
this.host = server.getHostName();
this.port = server.getPort();
// If targetVip is null, then try to use the actual server's vip.
if (targetVip == null) {
this.vip = server.getVIPAddress();
}
if (server.getDataCenterInfo() instanceof AmazonInfo) {
this.availabilityZone =
((AmazonInfo) server.getDataCenterInfo()).getMetadata().get("availability-zone");
// HACK - get region by just removing the last char from zone.
String az = getAvailabilityZone();
if (az != null && az.length() > 0) {
this.region = az.substring(0, az.length() - 1);
}
}
}
if (serverAddr != null) {
ipAddress = serverAddr.getHostAddress();
}
this.status = status;
this.error = error;
this.exceptionType = exceptionType;
this.readTimeout = readTimeout;
this.connectTimeout = connectTimeout;
this.maxRetries = maxRetries;
}
public RequestAttempt(
final DiscoveryResult server,
InetAddress serverAddr,
final IClientConfig clientConfig,
int attemptNumber,
int readTimeout) {
this.status = -1;
this.attempt = attemptNumber;
this.readTimeout = readTimeout;
if (server != null && server != DiscoveryResult.EMPTY) {
this.host = server.getHost();
this.port = server.getPort();
this.availabilityZone = server.getZone();
if (server.isDiscoveryEnabled()) {
this.app = server.getAppName().toLowerCase();
this.asg = server.getASGName();
this.instanceId = server.getServerId();
this.host = server.getHost();
this.port = server.getPort();
this.vip = server.getTarget();
this.availabilityZone = server.getAvailabilityZone();
} else {
SimpleMetaInfo metaInfo = server.getMetaInfo();
if (metaInfo != null) {
this.asg = metaInfo.getServerGroup();
this.vip = metaInfo.getServiceIdForDiscovery();
this.instanceId = metaInfo.getInstanceId();
}
}
// HACK - get region by just removing the last char from zone.
if (availabilityZone != null && availabilityZone.length() > 0) {
region = availabilityZone.substring(0, availabilityZone.length() - 1);
}
}
if (serverAddr != null) {
ipAddress = serverAddr.getHostAddress();
}
if (clientConfig != null) {
this.connectTimeout = clientConfig.get(IClientConfigKey.Keys.ConnectTimeout);
}
}
private RequestAttempt() {}
public void complete(int responseStatus, long durationMs, Throwable exception) {
if (responseStatus > -1) {
setStatus(responseStatus);
}
this.duration = durationMs;
if (exception != null) {
setException(exception);
}
}
public int getAttempt() {
return attempt;
}
public String getVip() {
return vip;
}
public int getStatus() {
return this.status;
}
public long getDuration() {
return this.duration;
}
public String getError() {
return error;
}
public String getApp() {
return app;
}
public String getAsg() {
return asg;
}
public String getInstanceId() {
return instanceId;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public String getIpAddress() {
return ipAddress;
}
public String getRegion() {
return region;
}
public String getAvailabilityZone() {
return availabilityZone;
}
public String getExceptionType() {
return exceptionType;
}
public long getReadTimeout() {
return readTimeout;
}
public int getConnectTimeout() {
return connectTimeout;
}
public int getMaxRetries() {
return maxRetries;
}
public void setStatus(int status) {
this.status = status;
}
public void setError(String error) {
this.error = error;
}
public void setExceptionType(String exceptionType) {
this.exceptionType = exceptionType;
}
public void setApp(String app) {
this.app = app;
}
public void setAsg(String asg) {
this.asg = asg;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public void setHost(String host) {
this.host = host;
}
public void setPort(int port) {
this.port = port;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public void setVip(String vip) {
this.vip = vip;
}
public void setRegion(String region) {
this.region = region;
}
public void setAvailabilityZone(String availabilityZone) {
this.availabilityZone = availabilityZone;
}
public void setReadTimeout(long readTimeout) {
this.readTimeout = readTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public void setException(Throwable t) {
if (t != null) {
if (t instanceof ReadTimeoutException) {
error = "READ_TIMEOUT";
exceptionType = t.getClass().getSimpleName();
} else if (t instanceof OriginConnectException) {
OriginConnectException oce = (OriginConnectException) t;
if (oce.getErrorType() != null) {
error = oce.getErrorType().toString();
} else {
error = "ORIGIN_CONNECT_ERROR";
}
final Throwable cause = t.getCause();
if (cause != null) {
exceptionType = t.getCause().getClass().getSimpleName();
} else {
exceptionType = t.getClass().getSimpleName();
}
} else if (t instanceof OutboundException) {
OutboundException obe = (OutboundException) t;
error = obe.getOutboundErrorType().toString();
exceptionType = OutboundException.class.getSimpleName();
} else if (t instanceof SSLHandshakeException) {
error = t.getMessage();
exceptionType = t.getClass().getSimpleName();
cause = t.getCause().getMessage();
} else {
error = t.getMessage();
exceptionType = t.getClass().getSimpleName();
cause = Throwables.getStackTraceAsString(t);
}
}
}
public void setMaxRetries(int maxRetries) {
this.maxRetries = maxRetries;
}
@Override
public String toString() {
try {
return JACKSON_MAPPER.writeValueAsString(toJsonNode());
} catch (JsonProcessingException e) {
throw new RuntimeException("Error serializing RequestAttempt!", e);
}
}
public ObjectNode toJsonNode() {
ObjectNode root = JACKSON_MAPPER.createObjectNode();
root.put("status", status);
root.put("duration", duration);
root.put("attempt", attempt);
putNullableAttribute(root, "error", error);
putNullableAttribute(root, "cause", cause);
putNullableAttribute(root, "exceptionType", exceptionType);
putNullableAttribute(root, "region", region);
putNullableAttribute(root, "availabilityZone", availabilityZone);
putNullableAttribute(root, "asg", asg);
putNullableAttribute(root, "instanceId", instanceId);
putNullableAttribute(root, "vip", vip);
putNullableAttribute(root, "ipAddress", ipAddress);
if (port > 0) {
root.put("port", port);
}
if (status < 1) {
root.put("readTimeout", readTimeout);
root.put("connectTimeout", connectTimeout);
}
return root;
}
private static ObjectNode putNullableAttribute(ObjectNode node, String name, String value) {
if (value != null) {
node.put(name, value);
}
return node;
}
}
| 6,295 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/niws/RequestAttempts.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.niws;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.netflix.zuul.context.CommonContextKeys;
import com.netflix.zuul.context.SessionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.ArrayList;
/**
* User: michaels@netflix.com
* Date: 6/25/15
* Time: 1:03 PM
*/
public class RequestAttempts extends ArrayList<RequestAttempt> {
private static final Logger LOG = LoggerFactory.getLogger(RequestAttempts.class);
private static final ObjectMapper JACKSON_MAPPER = new ObjectMapper();
public RequestAttempts() {
super();
}
@Nullable
public RequestAttempt getFinalAttempt() {
if (size() > 0) {
return get(size() - 1);
} else {
return null;
}
}
public static RequestAttempts getFromSessionContext(SessionContext ctx) {
return ctx.get(CommonContextKeys.REQUEST_ATTEMPTS);
}
public static RequestAttempts parse(String attemptsJson) throws IOException {
return JACKSON_MAPPER.readValue(attemptsJson, RequestAttempts.class);
}
public String toJSON() {
ArrayNode array = JACKSON_MAPPER.createArrayNode();
for (RequestAttempt attempt : this) {
array.add(attempt.toJsonNode());
}
try {
return JACKSON_MAPPER.writeValueAsString(array);
} catch (JsonProcessingException e) {
throw new RuntimeException("Error serializing RequestAttempts!", e);
}
}
@Override
public String toString() {
try {
return toJSON();
} catch (Throwable e) {
LOG.error(e.getMessage(), e);
return "";
}
}
}
| 6,296 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/context/CommonContextKeys.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.context;
import com.google.common.collect.ImmutableList;
import com.netflix.client.config.IClientConfig;
import com.netflix.zuul.filters.ZuulFilter;
import com.netflix.zuul.message.http.HttpRequestMessage;
import com.netflix.zuul.message.http.HttpResponseMessage;
import com.netflix.zuul.niws.RequestAttempts;
import com.netflix.zuul.passport.CurrentPassport;
import com.netflix.zuul.stats.status.StatusCategory;
import io.netty.channel.Channel;
import javax.inject.Provider;
import java.net.InetAddress;
import java.util.Map;
/**
* Common Context Keys
*
* Author: Arthur Gonigberg
* Date: November 21, 2017
*/
public class CommonContextKeys {
public static final SessionContext.Key<StatusCategory> STATUS_CATEGORY = SessionContext.newKey("status_category");
public static final SessionContext.Key<String> STATUS_CATEGORY_REASON =
SessionContext.newKey("status_category_reason");
public static final SessionContext.Key<StatusCategory> ORIGIN_STATUS_CATEGORY =
SessionContext.newKey("origin_status_category");
public static final SessionContext.Key<String> ORIGIN_STATUS_CATEGORY_REASON =
SessionContext.newKey("origin_status_category_reason");
public static final SessionContext.Key<Integer> ORIGIN_STATUS = SessionContext.newKey("origin_status");
public static final SessionContext.Key<RequestAttempts> REQUEST_ATTEMPTS =
SessionContext.newKey("request_attempts");
public static final SessionContext.Key<IClientConfig> REST_CLIENT_CONFIG =
SessionContext.newKey("rest_client_config");
public static final SessionContext.Key<ZuulFilter<HttpRequestMessage, HttpResponseMessage>> ZUUL_ENDPOINT =
SessionContext.newKey("_zuul_endpoint");
public static final SessionContext.Key<Map<Integer, InetAddress>> ZUUL_ORIGIN_CHOSEN_HOST_ADDR_MAP_KEY =
SessionContext.newKey("_zuul_origin_chosen_host_addr_map");
public static final SessionContext.Key<Channel> ORIGIN_CHANNEL = SessionContext.newKey("_origin_channel");
public static final String ORIGIN_MANAGER = "origin_manager";
public static final SessionContext.Key<ImmutableList.Builder<String>> ROUTING_LOG =
SessionContext.newKey("routing_log");
public static final String USE_FULL_VIP_NAME = "use_full_vip_name";
public static final String ACTUAL_VIP = "origin_vip_actual";
public static final String ORIGIN_VIP_SECURE = "origin_vip_secure";
/**
* The original client destination address Zuul by a proxy running Proxy Protocol.
* Will only be set if both Zuul and the connected proxy are both using set to use Proxy Protocol.
*/
public static final String PROXY_PROTOCOL_DESTINATION_ADDRESS = "proxy_protocol_destination_address";
public static final String SSL_HANDSHAKE_INFO = "ssl_handshake_info";
public static final String GZIPPER = "gzipper";
public static final String OVERRIDE_GZIP_REQUESTED = "overrideGzipRequested";
/* Netty-specific keys */
public static final String NETTY_HTTP_REQUEST = "_netty_http_request";
public static final String NETTY_SERVER_CHANNEL_HANDLER_CONTEXT = "_netty_server_channel_handler_context";
public static final String REQ_BODY_DCS = "_request_body_dcs";
public static final String RESP_BODY_DCS = "_response_body_dcs";
public static final SessionContext.Key<Provider<Long>> REQ_BODY_SIZE_PROVIDER =
SessionContext.newKey("request_body_size");
public static final SessionContext.Key<Provider<Long>> RESP_BODY_SIZE_PROVIDER =
SessionContext.newKey("response_body_size");
public static final SessionContext.Key<CurrentPassport> PASSPORT = SessionContext.newKey("_passport");
public static final SessionContext.Key<Boolean> ZUUL_USE_DECODED_URI =
SessionContext.newKey("zuul_use_decoded_uri");
}
| 6,297 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/context/ZuulSessionContextDecorator.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.context;
import com.netflix.netty.common.metrics.HttpBodySizeRecordingChannelHandler;
import com.netflix.util.UUIDFactory;
import com.netflix.util.concurrent.ConcurrentUUIDFactory;
import com.netflix.zuul.niws.RequestAttempts;
import com.netflix.zuul.origins.OriginManager;
import com.netflix.zuul.passport.CurrentPassport;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* Base Session Context Decorator
*
* Author: Arthur Gonigberg
* Date: November 21, 2017
*/
@Singleton
public class ZuulSessionContextDecorator implements SessionContextDecorator {
private static final UUIDFactory UUID_FACTORY = new ConcurrentUUIDFactory();
private final OriginManager originManager;
@Inject
public ZuulSessionContextDecorator(OriginManager originManager) {
this.originManager = originManager;
}
@Override
public SessionContext decorate(SessionContext ctx) {
// TODO split out commons parts from BaseSessionContextDecorator
ChannelHandlerContext nettyCtx =
(ChannelHandlerContext) ctx.get(CommonContextKeys.NETTY_SERVER_CHANNEL_HANDLER_CONTEXT);
if (nettyCtx == null) {
return null;
}
Channel channel = nettyCtx.channel();
// set injected origin manager
ctx.put(CommonContextKeys.ORIGIN_MANAGER, originManager);
// TODO
/* // The throttle result info.
ThrottleResult throttleResult = channel.attr(HttpRequestThrottleChannelHandler.ATTR_THROTTLE_RESULT).get();
ctx.set(CommonContextKeys.THROTTLE_RESULT, throttleResult);*/
// Add a container for request attempts info.
ctx.put(CommonContextKeys.REQUEST_ATTEMPTS, new RequestAttempts());
// Providers for getting the size of read/written request and response body sizes from channel.
ctx.put(
CommonContextKeys.REQ_BODY_SIZE_PROVIDER,
HttpBodySizeRecordingChannelHandler.getCurrentInboundBodySize(channel));
ctx.put(
CommonContextKeys.RESP_BODY_SIZE_PROVIDER,
HttpBodySizeRecordingChannelHandler.getCurrentOutboundBodySize(channel));
CurrentPassport passport = CurrentPassport.fromChannel(channel);
ctx.put(CommonContextKeys.PASSPORT, passport);
ctx.setUUID(UUID_FACTORY.generateRandomUuid().toString());
return ctx;
}
}
| 6,298 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/context/SessionCleaner.java | /*
* Copyright 2018 Netflix, Inc.
*
* 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 com.netflix.zuul.context;
import rx.Observable;
/**
* User: michaels@netflix.com
* Date: 8/3/15
* Time: 12:30 PM
*/
public interface SessionCleaner {
Observable<Void> cleanup(SessionContext context);
}
| 6,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.