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/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/context/Debug.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.zuul.message.Header;
import com.netflix.zuul.message.ZuulMessage;
import com.netflix.zuul.message.http.HttpRequestInfo;
import com.netflix.zuul.message.http.HttpResponseInfo;
import io.netty.util.ReferenceCounted;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Simple wrapper class around the RequestContext for setting and managing Request level Debug data.
* @author Mikey Cohen
* Date: 1/25/12
* Time: 2:26 PM
*/
public class Debug {
private static final Logger LOG = LoggerFactory.getLogger(Debug.class);
public static void setDebugRequest(SessionContext ctx, boolean bDebug) {
ctx.setDebugRequest(bDebug);
}
public static void setDebugRequestHeadersOnly(SessionContext ctx, boolean bHeadersOnly) {
ctx.setDebugRequestHeadersOnly(bHeadersOnly);
}
public static boolean debugRequestHeadersOnly(SessionContext ctx) {
return ctx.debugRequestHeadersOnly();
}
public static void setDebugRouting(SessionContext ctx, boolean bDebug) {
ctx.setDebugRouting(bDebug);
}
public static boolean debugRequest(SessionContext ctx) {
return ctx.debugRequest();
}
public static boolean debugRouting(SessionContext ctx) {
return ctx.debugRouting();
}
public static void addRoutingDebug(SessionContext ctx, String line) {
List<String> rd = getRoutingDebug(ctx);
rd.add(line);
}
public static void addRequestDebugForMessage(SessionContext ctx, ZuulMessage message, String prefix) {
for (Header header : message.getHeaders().entries()) {
Debug.addRequestDebug(ctx, prefix + " " + header.getKey() + " " + header.getValue());
}
if (message.hasBody()) {
String bodyStr = message.getBodyAsText();
Debug.addRequestDebug(ctx, prefix + " " + bodyStr);
}
}
/**
*
* @return Returns the list of routiong debug messages
*/
public static List<String> getRoutingDebug(SessionContext ctx) {
List<String> rd = (List<String>) ctx.get("routingDebug");
if (rd == null) {
rd = new ArrayList<String>();
ctx.set("routingDebug", rd);
}
return rd;
}
/**
* Adds a line to the Request debug messages
* @param line
*/
public static void addRequestDebug(SessionContext ctx, String line) {
List<String> rd = getRequestDebug(ctx);
rd.add(line);
}
/**
*
* @return returns the list of request debug messages
*/
public static List<String> getRequestDebug(SessionContext ctx) {
List<String> rd = (List<String>) ctx.get("requestDebug");
if (rd == null) {
rd = new ArrayList<String>();
ctx.set("requestDebug", rd);
}
return rd;
}
/**
* Adds debug details about changes that a given filter made to the request context.
* @param filterName
* @param copy
*/
public static void compareContextState(String filterName, SessionContext context, SessionContext copy) {
// TODO - only comparing Attributes. Need to compare the messages too.
// Ensure that the routingDebug property already exists, otherwise we'll have a ConcurrentModificationException
// below
getRoutingDebug(context);
Iterator<String> it = context.keySet().iterator();
String key = it.next();
while (key != null) {
if ((!key.equals("routingDebug") && !key.equals("requestDebug"))) {
Object newValue = context.get(key);
Object oldValue = copy.get(key);
if (!(newValue instanceof ReferenceCounted) && !(oldValue instanceof ReferenceCounted)) {
if (oldValue == null && newValue != null) {
addRoutingDebug(context, "{" + filterName + "} added " + key + "=" + newValue.toString());
} else if (oldValue != null && newValue != null) {
if (!(oldValue.equals(newValue))) {
addRoutingDebug(context, "{" + filterName + "} changed " + key + "=" + newValue.toString());
}
}
}
}
if (it.hasNext()) {
key = it.next();
} else {
key = null;
}
}
}
public static Observable<Boolean> writeDebugRequest(
SessionContext context, HttpRequestInfo request, boolean isInbound) {
Observable<Boolean> obs = null;
if (Debug.debugRequest(context)) {
String prefix = isInbound ? "REQUEST_INBOUND" : "REQUEST_OUTBOUND";
String arrow = ">";
Debug.addRequestDebug(
context,
String.format(
"%s:: %s LINE: %s %s %s",
prefix,
arrow,
request.getMethod().toUpperCase(),
request.getPathAndQuery(),
request.getProtocol()));
obs = Debug.writeDebugMessage(context, request, prefix, arrow);
}
if (obs == null) {
obs = Observable.just(Boolean.FALSE);
}
return obs;
}
public static Observable<Boolean> writeDebugResponse(
SessionContext context, HttpResponseInfo response, boolean isInbound) {
Observable<Boolean> obs = null;
if (Debug.debugRequest(context)) {
String prefix = isInbound ? "RESPONSE_INBOUND" : "RESPONSE_OUTBOUND";
String arrow = "<";
Debug.addRequestDebug(context, String.format("%s:: %s STATUS: %s", prefix, arrow, response.getStatus()));
obs = Debug.writeDebugMessage(context, response, prefix, arrow);
}
if (obs == null) {
obs = Observable.just(Boolean.FALSE);
}
return obs;
}
public static Observable<Boolean> writeDebugMessage(
SessionContext context, ZuulMessage msg, String prefix, String arrow) {
Observable<Boolean> obs = null;
for (Header header : msg.getHeaders().entries()) {
Debug.addRequestDebug(
context, String.format("%s:: %s HDR: %s:%s", prefix, arrow, header.getKey(), header.getValue()));
}
// Capture the response body into a Byte array for later usage.
if (msg.hasBody()) {
if (!Debug.debugRequestHeadersOnly(context)) {
// Convert body to a String and add to debug log.
String body = msg.getBodyAsText();
Debug.addRequestDebug(context, String.format("%s:: %s BODY: %s", prefix, arrow, body));
}
}
if (obs == null) {
obs = Observable.just(Boolean.FALSE);
}
return obs;
}
}
| 6,300 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/context/SessionContext.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.errorprone.annotations.CanIgnoreReturnValue;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.zuul.filters.FilterError;
import com.netflix.zuul.message.http.HttpResponseMessage;
import javax.annotation.Nullable;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* Represents the context between client and origin server for the duration of the dedicated connection/session
* between them. But we're currently still only modelling single request/response pair per session.
*
* NOTE: Not threadsafe, and not intended to be used concurrently.
*
* User: Mike Smith
* Date: 4/28/15
* Time: 6:45 PM
*/
public final class SessionContext extends HashMap<String, Object> implements Cloneable {
private static final int INITIAL_SIZE = DynamicPropertyFactory.getInstance()
.getIntProperty("com.netflix.zuul.context.SessionContext.initialSize", 60)
.get();
private boolean brownoutMode = false;
private boolean shouldStopFilterProcessing = false;
private boolean shouldSendErrorResponse = false;
private boolean errorResponseSent = false;
private boolean debugRouting = false;
private boolean debugRequest = false;
private boolean debugRequestHeadersOnly = false;
private boolean cancelled = false;
private static final String KEY_UUID = "_uuid";
private static final String KEY_VIP = "routeVIP";
private static final String KEY_ENDPOINT = "_endpoint";
private static final String KEY_STATIC_RESPONSE = "_static_response";
private static final String KEY_EVENT_PROPS = "eventProperties";
private static final String KEY_FILTER_ERRORS = "_filter_errors";
private static final String KEY_FILTER_EXECS = "_filter_executions";
private final IdentityHashMap<Key<?>, ?> typedMap = new IdentityHashMap<>();
/**
* A Key is type-safe, identity-based key into the Session Context.
* @param <T>
*/
public static final class Key<T> {
private final String name;
private Key(String name) {
this.name = Objects.requireNonNull(name, "name");
}
@Override
public String toString() {
return "Key{" + name + '}';
}
public String name() {
return name;
}
/**
* This method exists solely to indicate that Keys are based on identity and not name.
*/
@Override
public boolean equals(Object o) {
return super.equals(o);
}
/**
* This method exists solely to indicate that Keys are based on identity and not name.
*/
@Override
public int hashCode() {
return super.hashCode();
}
}
public SessionContext() {
// Use a higher than default initial capacity for the hashmap as we generally have more than the default
// 16 entries.
super(INITIAL_SIZE);
put(KEY_FILTER_EXECS, new StringBuilder());
put(KEY_EVENT_PROPS, new HashMap<String, Object>());
put(KEY_FILTER_ERRORS, new ArrayList<FilterError>());
}
public static <T> Key<T> newKey(String name) {
return new Key<>(name);
}
/**
* {@inheritDoc}
*
* <p>This method exists for static analysis.
*/
@Override
public Object get(Object key) {
return super.get(key);
}
/**
* Returns the value in the context, or {@code null} if absent.
*/
@SuppressWarnings("unchecked")
@Nullable
public <T> T get(Key<T> key) {
return (T) typedMap.get(Objects.requireNonNull(key, "key"));
}
/**
* Returns the value in the context, or {@code defaultValue} if absent.
*/
@SuppressWarnings("unchecked")
public <T> T getOrDefault(Key<T> key, T defaultValue) {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(defaultValue, "defaultValue");
T value = (T) typedMap.get(Objects.requireNonNull(key));
if (value != null) {
return value;
}
return defaultValue;
}
/**
* {@inheritDoc}
*
* <p>This method exists for static analysis.
*/
@Override
public Object put(String key, Object value) {
return super.put(key, value);
}
/**
* Returns the previous value associated with key, or {@code null} if there was no mapping for key. Unlike
* {@link #put(String, Object)}, this will never return a null value if the key is present in the map.
*/
@Nullable
@CanIgnoreReturnValue
public <T> T put(Key<T> key, T value) {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(value, "value");
@SuppressWarnings("unchecked") // Sorry.
T res = ((Map<Key<T>, T>) (Map) typedMap).put(key, value);
return res;
}
/**
* {@inheritDoc}
*
* <p>This method exists for static analysis.
*/
@Override
public boolean remove(Object key, Object value) {
return super.remove(key, value);
}
public <T> boolean remove(Key<T> key, T value) {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(value, "value");
@SuppressWarnings("unchecked") // sorry
boolean res = ((Map<Key<T>, T>) (Map) typedMap).remove(key, value);
return res;
}
/**
* {@inheritDoc}
*
* <p>This method exists for static analysis.
*/
@Override
public Object remove(Object key) {
return super.remove(key);
}
public <T> T remove(Key<T> key) {
Objects.requireNonNull(key, "key");
@SuppressWarnings("unchecked") // sorry
T res = ((Map<Key<T>, T>) (Map) typedMap).remove(key);
return res;
}
public Set<Key<?>> keys() {
return Collections.unmodifiableSet(new HashSet<>(typedMap.keySet()));
}
/**
* Makes a copy of the RequestContext. This is used for debugging.
*/
@Override
public SessionContext clone() {
// TODO(carl-mastrangelo): copy over the type safe keys
return (SessionContext) super.clone();
}
public String getString(String key) {
return (String) get(key);
}
/**
* Convenience method to return a boolean value for a given key
*
* @return true or false depending what was set. default is false
*/
public boolean getBoolean(String key) {
return getBoolean(key, false);
}
/**
* Convenience method to return a boolean value for a given key
*
* @return true or false depending what was set. default defaultResponse
*/
public boolean getBoolean(String key, boolean defaultResponse) {
Boolean b = (Boolean) get(key);
if (b != null) {
return b;
}
return defaultResponse;
}
/**
* sets a key value to Boolean.TRUE
*/
public void set(String key) {
put(key, Boolean.TRUE);
}
/**
* puts the key, value into the map. a null value will remove the key from the map
*
*/
public void set(String key, Object value) {
if (value != null) {
put(key, value);
} else {
remove(key);
}
}
public String getUUID() {
return getString(KEY_UUID);
}
public void setUUID(String uuid) {
set(KEY_UUID, uuid);
}
public void setStaticResponse(HttpResponseMessage response) {
set(KEY_STATIC_RESPONSE, response);
}
public HttpResponseMessage getStaticResponse() {
return (HttpResponseMessage) get(KEY_STATIC_RESPONSE);
}
/**
* Gets the throwable that will be use in the Error endpoint.
*
*/
public Throwable getError() {
return (Throwable) get("_error");
}
/**
* Sets throwable to use for generating a response in the Error endpoint.
*/
public void setError(Throwable th) {
put("_error", th);
}
public String getErrorEndpoint() {
return (String) get("_error-endpoint");
}
public void setErrorEndpoint(String name) {
put("_error-endpoint", name);
}
/**
* sets debugRouting
*/
public void setDebugRouting(boolean bDebug) {
this.debugRouting = bDebug;
}
/**
* @return "debugRouting"
*/
public boolean debugRouting() {
return debugRouting;
}
/**
* sets "debugRequestHeadersOnly" to bHeadersOnly
*
*/
public void setDebugRequestHeadersOnly(boolean bHeadersOnly) {
this.debugRequestHeadersOnly = bHeadersOnly;
}
/**
* @return "debugRequestHeadersOnly"
*/
public boolean debugRequestHeadersOnly() {
return this.debugRequestHeadersOnly;
}
/**
* sets "debugRequest"
*/
public void setDebugRequest(boolean bDebug) {
this.debugRequest = bDebug;
}
/**
* gets debugRequest
*
* @return debugRequest
*/
public boolean debugRequest() {
return this.debugRequest;
}
/**
* removes "routeHost" key
*/
public void removeRouteHost() {
remove("routeHost");
}
/**
* sets routeHost
*
* @param routeHost a URL
*/
public void setRouteHost(URL routeHost) {
set("routeHost", routeHost);
}
/**
* @return "routeHost" URL
*/
public URL getRouteHost() {
return (URL) get("routeHost");
}
/**
* appends filter name and status to the filter execution history for the
* current request
*/
public void addFilterExecutionSummary(String name, String status, long time) {
StringBuilder sb = getFilterExecutionSummary();
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(name)
.append('[')
.append(status)
.append(']')
.append('[')
.append(time)
.append("ms]");
}
/**
* @return String that represents the filter execution history for the current request
*/
public StringBuilder getFilterExecutionSummary() {
return (StringBuilder) get(KEY_FILTER_EXECS);
}
public boolean shouldSendErrorResponse() {
return this.shouldSendErrorResponse;
}
/**
* Set this to true to indicate that the Error endpoint should be applied after
* the end of the current filter processing phase.
*
*/
public void setShouldSendErrorResponse(boolean should) {
this.shouldSendErrorResponse = should;
}
public boolean errorResponseSent() {
return this.errorResponseSent;
}
public void setErrorResponseSent(boolean should) {
this.errorResponseSent = should;
}
/**
* This can be used by filters for flagging if the server is getting overloaded, and then choose
* to disable/sample/rate-limit some optional features.
*
*/
public boolean isInBrownoutMode() {
return brownoutMode;
}
public void setInBrownoutMode() {
this.brownoutMode = true;
}
/**
* This is typically set by a filter when wanting to reject a request, and also reduce load on the server
* by not processing any subsequent filters for this request.
*/
public void stopFilterProcessing() {
shouldStopFilterProcessing = true;
}
public boolean shouldStopFilterProcessing() {
return shouldStopFilterProcessing;
}
/**
* returns the routeVIP; that is the Eureka "vip" of registered instances
*
*/
public String getRouteVIP() {
return (String) get(KEY_VIP);
}
/**
* sets routeVIP; that is the Eureka "vip" of registered instances
*/
public void setRouteVIP(String sVip) {
set(KEY_VIP, sVip);
}
public void setEndpoint(String endpoint) {
put(KEY_ENDPOINT, endpoint);
}
public String getEndpoint() {
return (String) get(KEY_ENDPOINT);
}
public void setEventProperty(String key, Object value) {
getEventProperties().put(key, value);
}
public Map<String, Object> getEventProperties() {
return (Map<String, Object>) this.get(KEY_EVENT_PROPS);
}
public List<FilterError> getFilterErrors() {
return (List<FilterError>) get(KEY_FILTER_ERRORS);
}
public void setOriginReportedDuration(int duration) {
put("_originReportedDuration", duration);
}
public int getOriginReportedDuration() {
Object value = get("_originReportedDuration");
if (value != null) {
return (Integer) value;
}
return -1;
}
public boolean isCancelled() {
return cancelled;
}
public void cancel() {
this.cancelled = true;
}
} | 6,301 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/context/SessionContextFactory.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.zuul.message.ZuulMessage;
import rx.Observable;
public interface SessionContextFactory<T, V> {
public ZuulMessage create(SessionContext context, T nativeRequest, V nativeResponse);
public Observable<ZuulMessage> write(ZuulMessage msg, V nativeResponse);
}
| 6,302 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/context/SessionContextDecorator.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;
/**
* User: michaels@netflix.com
* Date: 2/25/15
* Time: 4:09 PM
*/
public interface SessionContextDecorator {
public SessionContext decorate(SessionContext ctx);
}
| 6,303 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/util/Gzipper.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.util;
import com.netflix.zuul.exception.ZuulException;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.HttpContent;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
/**
* Refactored this out of our GZipResponseFilter
*
* User: michaels@netflix.com
* Date: 5/10/16
* Time: 12:31 PM
*/
public class Gzipper {
private final ByteArrayOutputStream baos;
private final GZIPOutputStream gzos;
public Gzipper() throws RuntimeException {
try {
baos = new ByteArrayOutputStream(256);
gzos = new GZIPOutputStream(baos, true);
} catch (IOException e) {
throw new RuntimeException("Error finalizing the GzipOutputstream", e);
}
}
private void write(ByteBuf bb) throws IOException {
byte[] bytes;
int offset;
final int length = bb.readableBytes();
if (bb.hasArray()) {
/* avoid memory copy if possible */
bytes = bb.array();
offset = bb.arrayOffset();
} else {
bytes = new byte[length];
bb.getBytes(bb.readerIndex(), bytes);
offset = 0;
}
gzos.write(bytes, offset, length);
}
public void write(final HttpContent chunk) {
try {
write(chunk.content());
gzos.flush();
} catch (IOException ioEx) {
throw new ZuulException(ioEx, "Error Gzipping response content chunk", true);
} finally {
chunk.release();
}
}
public void finish() throws RuntimeException {
try {
gzos.finish();
gzos.flush();
gzos.close();
} catch (IOException ioEx) {
throw new ZuulException(ioEx, "Error finalizing the GzipOutputStream", true);
}
}
public ByteBuf getByteBuf() {
final ByteBuf copy = Unpooled.copiedBuffer(baos.toByteArray());
baos.reset();
return copy;
}
}
| 6,304 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/util/VipUtils.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.util;
public final class VipUtils {
public static String getVIPPrefix(String vipAddress) {
for (int i = 0; i < vipAddress.length(); i++) {
char c = vipAddress.charAt(i);
if (c == '.' || c == ':') {
return vipAddress.substring(0, i);
}
}
return vipAddress;
}
/**
* Use {@link #extractUntrustedAppNameFromVIP} instead.
*/
@Deprecated
public static String extractAppNameFromVIP(String vipAddress) {
String vipPrefix = getVIPPrefix(vipAddress);
return vipPrefix.split("-")[0];
}
/**
* Attempts to derive an app name from the VIP. Because the VIP is an arbitrary collection of characters, the
* value is just a best guess and not suitable for security purposes.
*/
public static String extractUntrustedAppNameFromVIP(String vipAddress) {
for (int i = 0; i < vipAddress.length(); i++) {
char c = vipAddress.charAt(i);
if (c == '-' || c == '.' || c == ':') {
return vipAddress.substring(0, i);
}
}
return vipAddress;
}
private VipUtils() {}
}
| 6,305 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/util/JsonUtility.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.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
/**
* Utility for generating JSON from Maps/Lists
*/
public class JsonUtility {
private static final Logger logger = LoggerFactory.getLogger(JsonUtility.class);
/**
* Pass in a Map and this method will return a JSON string.
*
* <p>The map can contain Objects, int[], Object[] and Collections and they will be converted
* into string representations.
*
* <p>Nested maps can be included as values and the JSON will have nested object notation.
*
* <p>Arrays/Collections can have Maps in them as well.
*
* <p>See the unit tests for examples.
*
* @param jsonData
*/
public static String jsonFromMap(Map<String, Object> jsonData) {
try {
JsonDocument json = new JsonDocument();
json.startGroup();
for (String key : jsonData.keySet()) {
Object data = jsonData.get(key);
if (data instanceof Map) {
/* it's a nested map, so we'll recursively add the JSON of this map to the current JSON */
json.addValue(key, jsonFromMap((Map<String, Object>) data));
} else if (data instanceof Object[]) {
/* it's an object array, so we'll iterate the elements and put them all in here */
json.addValue(key, "[" + stringArrayFromObjectArray((Object[]) data) + "]");
} else if (data instanceof Collection) {
/* it's a collection, so we'll iterate the elements and put them all in here */
json.addValue(key, "[" + stringArrayFromObjectArray(((Collection) data).toArray()) + "]");
} else if (data instanceof int[]) {
/* it's an int array, so we'll get the string representation */
String intArray = Arrays.toString((int[]) data);
/* remove whitespace */
intArray = intArray.replaceAll(" ", "");
json.addValue(key, intArray);
} else if (data instanceof JsonCapableObject) {
json.addValue(key, jsonFromMap(((JsonCapableObject) data).jsonMap()));
} else {
/* all other objects we assume we are to just put the string value in */
json.addValue(key, String.valueOf(data));
}
}
json.endGroup();
logger.debug("created json from map => {}", json);
return json.toString();
} catch (Exception e) {
logger.error("Could not create JSON from Map. ", e);
return "{}";
}
}
/*
* return a string like: "one","two","three"
*/
private static String stringArrayFromObjectArray(Object data[]) {
StringBuilder arrayAsString = new StringBuilder();
for (Object o : data) {
if (arrayAsString.length() > 0) {
arrayAsString.append(",");
}
if (o instanceof Map) {
arrayAsString.append(jsonFromMap((Map<String, Object>) o));
} else if (o instanceof JsonCapableObject) {
arrayAsString.append(jsonFromMap(((JsonCapableObject) o).jsonMap()));
} else {
arrayAsString.append("\"").append(String.valueOf(o)).append("\"");
}
}
return arrayAsString.toString();
}
private static class JsonDocument {
StringBuilder json = new StringBuilder();
private boolean newGroup = false;
public JsonDocument startGroup() {
newGroup = true;
json.append("{");
return this;
}
public JsonDocument endGroup() {
json.append("}");
return this;
}
public JsonDocument addValue(String key, String value) {
if (!newGroup) {
// if this is not the first value in a group, put a comma
json.append(",");
}
/* once we're here, the group is no longer "new" */
newGroup = false;
/* append the key/value */
json.append("\"").append(key).append("\"");
json.append(":");
if (value.trim().startsWith("{") || value.trim().startsWith("[")) {
// the value is either JSON or an array, so we won't aggregate with quotes
json.append(value);
} else {
json.append("\"").append(value).append("\"");
}
return this;
}
@Override
public String toString() {
return json.toString();
}
}
public static interface JsonCapableObject {
public Map<String, Object> jsonMap();
}
}
| 6,306 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/util/HttpUtils.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.util;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
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 io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http2.Http2StreamChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
/**
* User: Mike Smith
* Date: 4/28/15
* Time: 11:05 PM
*/
public class HttpUtils {
private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class);
private static final char[] MALICIOUS_HEADER_CHARS = {'\r', '\n'};
/**
* Get the IP address of client making the request.
*
* Uses the "x-forwarded-for" HTTP header if available, otherwise uses the remote
* IP of requester.
*
* @param request <code>HttpRequestMessage</code>
* @return <code>String</code> IP address
*/
public static String getClientIP(HttpRequestInfo request) {
final String xForwardedFor = request.getHeaders().getFirst(HttpHeaderNames.X_FORWARDED_FOR);
String clientIP;
if (xForwardedFor == null) {
clientIP = request.getClientIp();
} else {
clientIP = extractClientIpFromXForwardedFor(xForwardedFor);
}
return clientIP;
}
/**
* Extract the client IP address from an x-forwarded-for header. Returns null if there is no x-forwarded-for header
*
* @param xForwardedFor a <code>String</code> value
* @return a <code>String</code> value
*/
public static String extractClientIpFromXForwardedFor(String xForwardedFor) {
if (xForwardedFor == null) {
return null;
}
xForwardedFor = xForwardedFor.trim();
String tokenized[] = xForwardedFor.split(",");
if (tokenized.length == 0) {
return null;
} else {
return tokenized[0].trim();
}
}
@VisibleForTesting
static boolean isCompressed(String contentEncoding) {
return contentEncoding.contains(HttpHeaderValues.GZIP.toString())
|| contentEncoding.contains(HttpHeaderValues.DEFLATE.toString())
|| contentEncoding.contains(HttpHeaderValues.BR.toString())
|| contentEncoding.contains(HttpHeaderValues.COMPRESS.toString());
}
public static boolean isCompressed(Headers headers) {
String ce = headers.getFirst(HttpHeaderNames.CONTENT_ENCODING);
return ce != null && isCompressed(ce);
}
public static boolean acceptsGzip(Headers headers) {
String ae = headers.getFirst(HttpHeaderNames.ACCEPT_ENCODING);
return ae != null && ae.contains(HttpHeaderValues.GZIP.toString());
}
/**
* Ensure decoded new lines are not propagated in headers, in order to prevent XSS
*
* @param input - decoded header string
* @return - clean header string
*/
public static String stripMaliciousHeaderChars(@Nullable String input) {
if (input == null) {
return null;
}
// TODO(carl-mastrangelo): implement this more efficiently.
for (char c : MALICIOUS_HEADER_CHARS) {
if (input.indexOf(c) != -1) {
input = input.replace(Character.toString(c), "");
}
}
return input;
}
public static boolean hasNonZeroContentLengthHeader(ZuulMessage msg) {
final Integer contentLengthVal = getContentLengthIfPresent(msg);
return (contentLengthVal != null) && (contentLengthVal > 0);
}
public static Integer getContentLengthIfPresent(ZuulMessage msg) {
final String contentLengthValue =
msg.getHeaders().getFirst(com.netflix.zuul.message.http.HttpHeaderNames.CONTENT_LENGTH);
if (!Strings.isNullOrEmpty(contentLengthValue)) {
try {
return Integer.valueOf(contentLengthValue);
} catch (NumberFormatException e) {
LOG.info("Invalid Content-Length header value on request. " + "value = {}", contentLengthValue, e);
}
}
return null;
}
public static Integer getBodySizeIfKnown(ZuulMessage msg) {
final Integer bodySize = getContentLengthIfPresent(msg);
if (bodySize != null) {
return bodySize;
}
if (msg.hasCompleteBody()) {
return msg.getBodyLength();
}
return null;
}
public static boolean hasChunkedTransferEncodingHeader(ZuulMessage msg) {
boolean isChunked = false;
String teValue = msg.getHeaders().getFirst(com.netflix.zuul.message.http.HttpHeaderNames.TRANSFER_ENCODING);
if (!Strings.isNullOrEmpty(teValue)) {
isChunked = "chunked".equals(teValue.toLowerCase());
}
return isChunked;
}
/**
* If http/1 then will always want to just use ChannelHandlerContext.channel(), but for http/2
* will want the parent channel (as the child channel is different for each h2 stream).
*/
public static Channel getMainChannel(ChannelHandlerContext ctx) {
return getMainChannel(ctx.channel());
}
public static Channel getMainChannel(Channel channel) {
if (channel instanceof Http2StreamChannel) {
return channel.parent();
}
return channel;
}
}
| 6,307 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/util/ProxyUtils.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.util;
import com.netflix.config.CachedDynamicBooleanProperty;
import com.netflix.zuul.message.HeaderName;
import com.netflix.zuul.message.Headers;
import com.netflix.zuul.message.http.HttpHeaderNames;
import com.netflix.zuul.message.http.HttpRequestMessage;
import java.util.HashSet;
import java.util.Set;
/**
* User: michaels@netflix.com
* Date: 6/8/15
* Time: 11:50 AM
*/
public class ProxyUtils {
private static final CachedDynamicBooleanProperty OVERWRITE_XF_HEADERS =
new CachedDynamicBooleanProperty("zuul.headers.xforwarded.overwrite", false);
private static final Set<HeaderName> RESP_HEADERS_TO_STRIP = new HashSet<>();
static {
RESP_HEADERS_TO_STRIP.add(HttpHeaderNames.CONNECTION);
RESP_HEADERS_TO_STRIP.add(HttpHeaderNames.TRANSFER_ENCODING);
RESP_HEADERS_TO_STRIP.add(HttpHeaderNames.KEEP_ALIVE);
}
private static final Set<HeaderName> REQ_HEADERS_TO_STRIP = new HashSet<>();
static {
REQ_HEADERS_TO_STRIP.add(
HttpHeaderNames
.CONTENT_LENGTH); // Because the httpclient library sets this itself, and doesn't like it if set
REQ_HEADERS_TO_STRIP.add(HttpHeaderNames.CONNECTION);
REQ_HEADERS_TO_STRIP.add(HttpHeaderNames.TRANSFER_ENCODING);
REQ_HEADERS_TO_STRIP.add(HttpHeaderNames.KEEP_ALIVE);
}
public static boolean isValidRequestHeader(HeaderName headerName) {
return !REQ_HEADERS_TO_STRIP.contains(headerName);
}
public static boolean isValidResponseHeader(HeaderName headerName) {
return !RESP_HEADERS_TO_STRIP.contains(headerName);
}
public static void addXForwardedHeaders(HttpRequestMessage request) {
// Add standard Proxy request headers.
Headers headers = request.getHeaders();
addXForwardedHeader(headers, HttpHeaderNames.X_FORWARDED_HOST, request.getOriginalHost());
addXForwardedHeader(headers, HttpHeaderNames.X_FORWARDED_PORT, Integer.toString(request.getPort()));
addXForwardedHeader(headers, HttpHeaderNames.X_FORWARDED_PROTO, request.getScheme());
addXForwardedHeader(headers, HttpHeaderNames.X_FORWARDED_FOR, request.getClientIp());
}
public static void addXForwardedHeader(Headers headers, HeaderName name, String latestValue) {
if (OVERWRITE_XF_HEADERS.get()) {
headers.set(name, latestValue);
} else {
// If this proxy header already exists (possibly due to an upstream ELB or reverse proxy
// setting it) then keep that value.
String existingValue = headers.getFirst(name);
if (existingValue == null) {
// Otherwise set new value.
if (latestValue != null) {
headers.set(name, latestValue);
}
}
}
}
}
| 6,308 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/plugins/Tracer.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.plugins;
import com.netflix.spectator.api.Spectator;
import com.netflix.zuul.monitoring.TracerFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
/**
* Plugin to hook up Servo Tracers
*
* @author Mikey Cohen
* Date: 4/10/13
* Time: 4:51 PM
*/
public class Tracer extends TracerFactory {
@Override
public com.netflix.zuul.monitoring.Tracer startMicroTracer(String name) {
return new SpectatorTracer(name);
}
class SpectatorTracer implements com.netflix.zuul.monitoring.Tracer {
private String name;
private final long start;
private SpectatorTracer(String name) {
this.name = name;
start = System.nanoTime();
}
@Override
public void stopAndLog() {
Spectator.globalRegistry()
.timer(name, "hostname", getHostName(), "ip", getIp())
.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
@Override
public void setName(String name) {
this.name = name;
}
}
private static String getHostName() {
return (loadAddress() != null) ? loadAddress().getHostName() : "unkownHost";
}
private static String getIp() {
return (loadAddress() != null) ? loadAddress().getHostAddress() : "unknownHost";
}
private static InetAddress loadAddress() {
try {
return InetAddress.getLocalHost();
} catch (UnknownHostException e) {
return null;
}
}
}
| 6,309 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/constants/ZuulHeaders.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.constants;
/**
* HTTP Headers that are accessed or added by Zuul
* User: mcohen
* Date: 5/15/13
* Time: 4:38 PM
*/
public class ZuulHeaders {
/* Standard headers */
public static final String TRANSFER_ENCODING = "transfer-encoding";
public static final String CHUNKED = "chunked";
public static final String ORIGIN = "Origin";
public static final String CONTENT_ENCODING = "Content-Encoding";
public static final String ACCEPT_ENCODING = "accept-encoding";
public static final String CONNECTION = "Connection";
public static final String KEEP_ALIVE = "keep-alive";
public static final String X_FORWARDED_PROTO = "X-Forwarded-Proto";
public static final String X_FORWARDED_FOR = "X-Forwarded-For";
public static final String HOST = "Host";
public static final String X_ORIGINATING_URL = "X-Originating-URL";
/* X-Zuul headers */
public static final String X_ZUUL = "X-Zuul";
public static final String X_ZUUL_STATUS = X_ZUUL + "-Status";
public static final String X_ZUUL_PROXY_ATTEMPTS = X_ZUUL + "-Proxy-Attempts";
public static final String X_ZUUL_INSTANCE = X_ZUUL + "-Instance";
public static final String X_ZUUL_ERROR_CAUSE = X_ZUUL + "-Error-Cause";
public static final String X_ZUUL_SURGICAL_FILTER = X_ZUUL + "-Surgical-Filter";
public static final String X_ZUUL_FILTER_EXECUTION_STATUS = X_ZUUL + "-Filter-Executions";
// Prevent instantiation
private ZuulHeaders() {
throw new AssertionError("Must not instantiate constant utility class");
}
}
| 6,310 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/constants/ZuulConstants.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.constants;
/**
* property constants
* Date: 5/15/13
* Time: 2:22 PM
*/
public class ZuulConstants {
public static final String ZUUL_NIWS_CLIENTLIST = "zuul.niws.clientlist";
public static final String DEFAULT_NFASTYANAX_READCONSISTENCY = "default.nfastyanax.readConsistency";
public static final String DEFAULT_NFASTYANAX_WRITECONSISTENCY = "default.nfastyanax.writeConsistency";
public static final String DEFAULT_NFASTYANAX_SOCKETTIMEOUT = "default.nfastyanax.socketTimeout";
public static final String DEFAULT_NFASTYANAX_MAXCONNSPERHOST = "default.nfastyanax.maxConnsPerHost";
public static final String DEFAULT_NFASTYANAX_MAXTIMEOUTWHENEXHAUSTED =
"default.nfastyanax.maxTimeoutWhenExhausted";
public static final String DEFAULT_NFASTYANAX_MAXFAILOVERCOUNT = "default.nfastyanax.maxFailoverCount";
public static final String DEFAULT_NFASTYANAX_FAILOVERWAITTIME = "default.nfastyanax.failoverWaitTime";
public static final String ZUUL_CASSANDRA_KEYSPACE = "zuul.cassandra.keyspace";
public static final String ZUUL_CASSANDRA_MAXCONNECTIONSPERHOST = "zuul.cassandra.maxConnectionsPerHost";
public static final String ZUUL_CASSANDRA_HOST = "zuul.cassandra.host";
public static final String ZUUL_CASSANDRA_PORT = "zuul.cassandra.port";
public static final String ZUUL_EUREKA = "zuul.eureka.";
public static final String ZUUL_AUTODETECT_BACKEND_VIPS = "zuul.autodetect-backend-vips";
public static final String ZUUL_RIBBON_NAMESPACE = "zuul.ribbon.namespace";
public static final String ZUUL_RIBBON_VIPADDRESS_TEMPLATE = "zuul.ribbon.vipAddress.template";
public static final String ZUUL_CASSANDRA_CACHE_MAX_SIZE = "zuul.cassandra.cache.max-size";
public static final String ZUUL_HTTPCLIENT = "zuul.httpClient.";
public static final String ZUUL_USE_ACTIVE_FILTERS = "zuul.use.active.filters";
public static final String ZUUL_USE_CANARY_FILTERS = "zuul.use.canary.filters";
public static final String ZUUL_FILTER_PRE_PATH = "zuul.filter.pre.path";
public static final String ZUUL_FILTER_POST_PATH = "zuul.filter.post.path";
public static final String ZUUL_FILTER_ROUTING_PATH = "zuul.filter.routing.path";
public static final String ZUUL_FILTER_CUSTOM_PATH = "zuul.filter.custom.path";
public static final String ZUUL_FILTER_ADMIN_ENABLED = "zuul.filter.admin.enabled";
public static final String ZUUL_FILTER_ADMIN_REDIRECT = "zuul.filter.admin.redirect.path";
public static final String ZUUL_DEBUG_REQUEST = "zuul.debug.request";
public static final String ZUUL_DEBUG_PARAMETER = "zuul.debug.parameter";
public static final String ZUUL_ROUTER_ALT_ROUTE_VIP = "zuul.router.alt.route.vip";
public static final String ZUUL_ROUTER_ALT_ROUTE_HOST = "zuul.router.alt.route.host";
public static final String ZUUL_ROUTER_ALT_ROUTE_PERMYRIAD = "zuul.router.alt.route.permyriad";
public static final String ZUUL_ROUTER_ALT_ROUTE_MAXLIMIT = "zuul.router.alt.route.maxlimit";
public static final String ZUUL_NIWS_DEFAULTCLIENT = "zuul.niws.defaultClient";
public static final String ZUUL_DEFAULT_HOST = "zuul.default.host";
public static final String ZUUL_HOST_SOCKET_TIMEOUT_MILLIS = "zuul.host.socket-timeout-millis";
public static final String ZUUL_HOST_CONNECT_TIMEOUT_MILLIS = "zuul.host.connect-timeout-millis";
public static final String ZUUL_INCLUDE_DEBUG_HEADER = "zuul.include-debug-header";
public static final String ZUUL_INITIAL_STREAM_BUFFER_SIZE = "zuul.initial-stream-buffer-size";
public static final String ZUUL_SET_CONTENT_LENGTH = "zuul.set-content-length";
public static final String ZUUL_DEBUGFILTERS_DISABLED = "zuul.debugFilters.disabled";
public static final String ZUUL_DEBUG_VIP = "zuul.debug.vip";
public static final String ZUUL_DEBUG_HOST = "zuul.debug.host";
public static final String ZUUL_REQUEST_BODY_MAX_SIZE = "zuul.body.request.max.size";
public static final String ZUUL_RESPONSE_BODY_MAX_SIZE = "zuul.body.response.max.size";
// Prevent instantiation
private ZuulConstants() {
throw new AssertionError("Must not instantiate constant utility class");
}
}
| 6,311 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/HeaderName.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.message;
import java.util.Locale;
/**
* Immutable, case-insensitive wrapper around Header name.
*
* User: Mike Smith
* Date: 7/29/15
* Time: 1:07 PM
*/
public final class HeaderName {
private final String name;
private final String normalised;
private final int hashCode;
public HeaderName(String name) {
if (name == null) {
throw new NullPointerException("HeaderName cannot be null!");
}
this.name = name;
this.normalised = normalize(name);
this.hashCode = this.normalised.hashCode();
}
HeaderName(String name, String normalised) {
this.name = name;
this.normalised = normalised;
this.hashCode = normalised.hashCode();
}
/**
* Gets the original, non-normalized name for this header.
*/
public String getName() {
return name;
}
public String getNormalised() {
return normalised;
}
static String normalize(String s) {
return s.toLowerCase(Locale.ROOT);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof HeaderName)) {
return false;
}
HeaderName that = (HeaderName) o;
return this.normalised.equals(that.normalised);
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public String toString() {
return name;
}
}
| 6,312 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/Headers.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.message;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Spectator;
import com.netflix.zuul.exception.ZuulException;
import javax.annotation.Nullable;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
/**
* An abstraction over a collection of http headers. Allows multiple headers with same name, and header names are
* compared case insensitively.
*
* There are methods for getting and setting headers by String AND by HeaderName. When possible, use the HeaderName
* variants and cache the HeaderName instances somewhere, to avoid case-insensitive String comparisons.
*/
public final class Headers {
private static final int ABSENT = -1;
private final List<String> originalNames;
private final List<String> names;
private final List<String> values;
private static final Counter invalidHeaderCounter =
Spectator.globalRegistry().counter("zuul.header.invalid.char");
public static Headers copyOf(Headers original) {
return new Headers(Objects.requireNonNull(original, "original"));
}
public Headers() {
originalNames = new ArrayList<>();
names = new ArrayList<>();
values = new ArrayList<>();
}
public Headers(int initialSize) {
originalNames = new ArrayList<>(initialSize);
names = new ArrayList<>(initialSize);
values = new ArrayList<>(initialSize);
}
private Headers(Headers original) {
originalNames = new ArrayList<>(original.originalNames);
names = new ArrayList<>(original.names);
values = new ArrayList<>(original.values);
}
/**
* Get the first value found for this key even if there are multiple. If none, then
* return {@code null}.
*/
@Nullable
public String getFirst(String headerName) {
String normalName = HeaderName.normalize(Objects.requireNonNull(headerName, "headerName"));
return getFirstNormal(normalName);
}
/**
* Get the first value found for this key even if there are multiple. If none, then
* return {@code null}.
*/
@Nullable
public String getFirst(HeaderName headerName) {
String normalName = Objects.requireNonNull(headerName, "headerName").getNormalised();
return getFirstNormal(normalName);
}
@Nullable
private String getFirstNormal(String name) {
for (int i = 0; i < size(); i++) {
if (name(i).equals(name)) {
return value(i);
}
}
return null;
}
/**
* Get the first value found for this key even if there are multiple. If none, then
* return the specified defaultValue.
*/
public String getFirst(String headerName, String defaultValue) {
Objects.requireNonNull(defaultValue, "defaultValue");
String value = getFirst(headerName);
if (value != null) {
return value;
}
return defaultValue;
}
/**
* Get the first value found for this key even if there are multiple. If none, then
* return the specified defaultValue.
*/
public String getFirst(HeaderName headerName, String defaultValue) {
Objects.requireNonNull(defaultValue, "defaultValue");
String value = getFirst(headerName);
if (value != null) {
return value;
}
return defaultValue;
}
/**
* Returns all header values associated with the name.
*/
public List<String> getAll(String headerName) {
String normalName = HeaderName.normalize(Objects.requireNonNull(headerName, "headerName"));
return getAllNormal(normalName);
}
/**
* Returns all header values associated with the name.
*/
public List<String> getAll(HeaderName headerName) {
String normalName = Objects.requireNonNull(headerName, "headerName").getNormalised();
return getAllNormal(normalName);
}
private List<String> getAllNormal(String normalName) {
List<String> results = null;
for (int i = 0; i < size(); i++) {
if (name(i).equals(normalName)) {
if (results == null) {
results = new ArrayList<>(1);
}
results.add(value(i));
}
}
if (results == null) {
return Collections.emptyList();
} else {
return Collections.unmodifiableList(results);
}
}
/**
* Iterates over the header entries with the given consumer. The first argument will be the normalised header
* name as returned by {@link HeaderName#getNormalised()}. The second argument will be the value. Do not modify
* the headers during iteration.
*/
public void forEachNormalised(BiConsumer<? super String, ? super String> entryConsumer) {
for (int i = 0; i < size(); i++) {
entryConsumer.accept(name(i), value(i));
}
}
/**
* Replace any/all entries with this key, with this single entry.
*
* If value is {@code null}, then not added, but any existing header of same name is removed.
*/
public void set(String headerName, @Nullable String value) {
String normalName = HeaderName.normalize(Objects.requireNonNull(headerName, "headerName"));
setNormal(headerName, normalName, value);
}
/**
* Replace any/all entries with this key, with this single entry.
*
* If value is {@code null}, then not added, but any existing header of same name is removed.
*/
public void set(HeaderName headerName, String value) {
String normalName = Objects.requireNonNull(headerName, "headerName").getNormalised();
setNormal(headerName.getName(), normalName, value);
}
/**
* Replace any/all entries with this key, with this single entry and validate.
*
* If value is {@code null}, then not added, but any existing header of same name is removed.
*
* @throws ZuulException on invalid name or value
*/
public void setAndValidate(String headerName, @Nullable String value) {
String normalName = HeaderName.normalize(Objects.requireNonNull(headerName, "headerName"));
setNormal(validateField(headerName), validateField(normalName), validateField(value));
}
/**
* Replace any/all entries with this key, with this single entry if the key and entry are valid.
*
* If value is {@code null}, then not added, but any existing header of same name is removed.
*/
public void setIfValid(HeaderName headerName, String value) {
Objects.requireNonNull(headerName, "headerName");
if (isValid(headerName.getName()) && isValid(value)) {
String normalName = headerName.getNormalised();
setNormal(headerName.getName(), normalName, value);
}
}
/**
* Replace any/all entries with this key, with this single entry if the key and entry are valid.
*
* If value is {@code null}, then not added, but any existing header of same name is removed.
*/
public void setIfValid(String headerName, @Nullable String value) {
Objects.requireNonNull(headerName, "headerName");
if (isValid(headerName) && isValid(value)) {
String normalName = HeaderName.normalize(headerName);
setNormal(headerName, normalName, value);
}
}
/**
* Replace any/all entries with this key, with this single entry and validate.
*
* If value is {@code null}, then not added, but any existing header of same name is removed.
*
* @throws ZuulException on invalid name or value
*/
public void setAndValidate(HeaderName headerName, String value) {
String normalName = Objects.requireNonNull(headerName, "headerName").getNormalised();
setNormal(validateField(headerName.getName()), validateField(normalName), validateField(value));
}
private void setNormal(String originalName, String normalName, @Nullable String value) {
int i = findNormal(normalName);
if (i == ABSENT) {
if (value != null) {
addNormal(originalName, normalName, value);
}
return;
}
if (value != null) {
value(i, value);
originalName(i, originalName);
i++;
}
clearMatchingStartingAt(i, normalName, /* removed= */ null);
}
/**
* Returns the first index entry that has a matching name. Returns {@link #ABSENT} if absent.
*/
private int findNormal(String normalName) {
for (int i = 0; i < size(); i++) {
if (name(i).equals(normalName)) {
return i;
}
}
return -1;
}
/**
* Removes entries that match the name, starting at the given index.
*/
private void clearMatchingStartingAt(int i, String normalName, @Nullable Collection<? super String> removed) {
// This works by having separate read and write indexes, that iterate along the list.
// Values that don't match are moved to the front, leaving garbage values in place.
// At the end, all values at and values are garbage and are removed.
int w = i;
for (int r = i; r < size(); r++) {
if (!name(r).equals(normalName)) {
originalName(w, originalName(r));
name(w, name(r));
value(w, value(r));
w++;
} else if (removed != null) {
removed.add(value(r));
}
}
truncate(w);
}
/**
* Adds the name and value to the headers, except if the name is already present. Unlike
* {@link #set(String, String)}, this method does not accept a {@code null} value.
*
* @return if the value was successfully added.
*/
public boolean setIfAbsent(String headerName, String value) {
Objects.requireNonNull(value, "value");
String normalName = HeaderName.normalize(Objects.requireNonNull(headerName, "headerName"));
return setIfAbsentNormal(headerName, normalName, value);
}
/**
* Adds the name and value to the headers, except if the name is already present. Unlike
* {@link #set(HeaderName, String)}, this method does not accept a {@code null} value.
*
* @return if the value was successfully added.
*/
public boolean setIfAbsent(HeaderName headerName, String value) {
Objects.requireNonNull(value, "value");
String normalName = Objects.requireNonNull(headerName, "headerName").getNormalised();
return setIfAbsentNormal(headerName.getName(), normalName, value);
}
private boolean setIfAbsentNormal(String originalName, String normalName, String value) {
int i = findNormal(normalName);
if (i != ABSENT) {
return false;
}
addNormal(originalName, normalName, value);
return true;
}
/**
* Validates and adds the name and value to the headers, except if the name is already present. Unlike
* {@link #set(String, String)}, this method does not accept a {@code null} value.
*
* @return if the value was successfully added.
*/
public boolean setIfAbsentAndValid(String headerName, String value) {
Objects.requireNonNull(value, "value");
Objects.requireNonNull(headerName, "headerName");
if (isValid(headerName) && isValid(value)) {
String normalName = HeaderName.normalize(headerName);
return setIfAbsentNormal(headerName, normalName, value);
}
return false;
}
/**
* Validates and adds the name and value to the headers, except if the name is already present. Unlike
* {@link #set(HeaderName, String)}, this method does not accept a {@code null} value.
*
* @return if the value was successfully added.
*/
public boolean setIfAbsentAndValid(HeaderName headerName, String value) {
Objects.requireNonNull(value, "value");
Objects.requireNonNull(headerName, "headerName");
if (isValid(headerName.getName()) && isValid((value))) {
String normalName = headerName.getNormalised();
return setIfAbsentNormal(headerName.getName(), normalName, value);
}
return false;
}
/**
* Adds the name and value to the headers.
*/
public void add(String headerName, String value) {
String normalName = HeaderName.normalize(Objects.requireNonNull(headerName, "headerName"));
Objects.requireNonNull(value, "value");
addNormal(headerName, normalName, value);
}
/**
* Adds the name and value to the headers.
*/
public void add(HeaderName headerName, String value) {
String normalName = Objects.requireNonNull(headerName, "headerName").getNormalised();
Objects.requireNonNull(value, "value");
addNormal(headerName.getName(), normalName, value);
}
/**
* Adds the name and value to the headers and validate.
*
* @throws ZuulException on invalid name or value
*/
public void addAndValidate(String headerName, String value) {
String normalName = HeaderName.normalize(Objects.requireNonNull(headerName, "headerName"));
Objects.requireNonNull(value, "value");
addNormal(validateField(headerName), validateField(normalName), validateField(value));
}
/**
* Adds the name and value to the headers and validate
*
* @throws ZuulException on invalid name or value
*/
public void addAndValidate(HeaderName headerName, String value) {
String normalName = Objects.requireNonNull(headerName, "headerName").getNormalised();
Objects.requireNonNull(value, "value");
addNormal(validateField(headerName.getName()), validateField(normalName), validateField(value));
}
/**
* Adds the name and value to the headers if valid
*/
public void addIfValid(String headerName, String value) {
Objects.requireNonNull(headerName, "headerName");
Objects.requireNonNull(value, "value");
if (isValid(headerName) && isValid(value)) {
String normalName = HeaderName.normalize(headerName);
addNormal(headerName, normalName, value);
}
}
/**
* Adds the name and value to the headers if valid
*/
public void addIfValid(HeaderName headerName, String value) {
Objects.requireNonNull(headerName, "headerName");
Objects.requireNonNull(value, "value");
if (isValid(headerName.getName()) && isValid(value)) {
String normalName = headerName.getNormalised();
addNormal(headerName.getName(), normalName, value);
}
}
/**
* Adds all the headers into this headers object.
*/
public void putAll(Headers headers) {
for (int i = 0; i < headers.size(); i++) {
addNormal(headers.originalName(i), headers.name(i), headers.value(i));
}
}
/**
* Removes the header entries that match the given header name, and returns them as a list.
*/
public List<String> remove(String headerName) {
String normalName = HeaderName.normalize(Objects.requireNonNull(headerName, "headerName"));
return removeNormal(normalName);
}
/**
* Removes the header entries that match the given header name, and returns them as a list.
*/
public List<String> remove(HeaderName headerName) {
String normalName = Objects.requireNonNull(headerName, "headerName").getNormalised();
return removeNormal(normalName);
}
private List<String> removeNormal(String normalName) {
List<String> removed = new ArrayList<>();
clearMatchingStartingAt(0, normalName, removed);
return Collections.unmodifiableList(removed);
}
/**
* Removes all header entries that match the given predicate. Do not access the header list from inside the
* {@link Predicate#test} body.
*
* @return if any elements were removed.
*/
public boolean removeIf(Predicate<? super Map.Entry<HeaderName, String>> filter) {
Objects.requireNonNull(filter, "filter");
boolean removed = false;
int w = 0;
for (int r = 0; r < size(); r++) {
if (filter.test(new SimpleImmutableEntry<>(new HeaderName(originalName(r), name(r)), value(r)))) {
removed = true;
} else {
originalName(w, originalName(r));
name(w, name(r));
value(w, value(r));
w++;
}
}
truncate(w);
return removed;
}
/**
* Returns the collection of headers.
*/
public Collection<Header> entries() {
List<Header> entries = new ArrayList<>(size());
for (int i = 0; i < size(); i++) {
entries.add(new Header(new HeaderName(originalName(i), name(i)), value(i)));
}
return Collections.unmodifiableList(entries);
}
/**
* Returns a set of header names found in this headers object. If there are duplicate header names, the first
* one present takes precedence.
*/
public Set<HeaderName> keySet() {
Set<HeaderName> headerNames = new LinkedHashSet<>(size());
for (int i = 0; i < size(); i++) {
HeaderName headerName = new HeaderName(originalName(i), name(i));
// We actually do need to check contains before adding to the set because the original name may change.
// In this case, the first name wins.
if (!headerNames.contains(headerName)) {
headerNames.add(headerName);
}
}
return Collections.unmodifiableSet(headerNames);
}
/**
* Returns if there is a header entry that matches the given name.
*/
public boolean contains(String headerName) {
String normalName = HeaderName.normalize(Objects.requireNonNull(headerName, "headerName"));
return findNormal(normalName) != ABSENT;
}
/**
* Returns if there is a header entry that matches the given name.
*/
public boolean contains(HeaderName headerName) {
String normalName = Objects.requireNonNull(headerName, "headerName").getNormalised();
return findNormal(normalName) != ABSENT;
}
/**
* Returns if there is a header entry that matches the given name and value.
*/
public boolean contains(String headerName, String value) {
String normalName = HeaderName.normalize(Objects.requireNonNull(headerName, "headerName"));
Objects.requireNonNull(value, "value");
return containsNormal(normalName, value);
}
/**
* Returns if there is a header entry that matches the given name and value.
*/
public boolean contains(HeaderName headerName, String value) {
String normalName = Objects.requireNonNull(headerName, "headerName").getNormalised();
Objects.requireNonNull(value, "value");
return containsNormal(normalName, value);
}
private boolean containsNormal(String normalName, String value) {
for (int i = 0; i < size(); i++) {
if (name(i).equals(normalName) && value(i).equals(value)) {
return true;
}
}
return false;
}
/**
* Returns the number of header entries.
*/
public int size() {
return names.size();
}
/**
* This method should only be used for testing, as it is expensive to call.
*/
@Override
@VisibleForTesting
public int hashCode() {
return asMap().hashCode();
}
/**
* Equality on headers is not clearly defined, but this method makes an attempt to do so. This method should
* only be used for testing, as it is expensive to call. Two headers object are considered equal if they have
* the same, normalized header names, and have the corresponding header values in the same order.
*/
@Override
@VisibleForTesting
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Headers)) {
return false;
}
Headers other = (Headers) obj;
return asMap().equals(other.asMap());
}
private Map<String, List<String>> asMap() {
Map<String, List<String>> map = new LinkedHashMap<>(size());
for (int i = 0; i < size(); i++) {
map.computeIfAbsent(name(i), k -> new ArrayList<>(1)).add(value(i));
}
// Return an unwrapped collection since it should not ever be returned on the API.
return map;
}
/**
* This is used for debugging. It is fairly expensive to construct, so don't call it on a hot path.
*/
@Override
public String toString() {
return asMap().toString();
}
private String originalName(int i) {
return originalNames.get(i);
}
private void originalName(int i, String originalName) {
originalNames.set(i, originalName);
}
private String name(int i) {
return names.get(i);
}
private void name(int i, String name) {
names.set(i, name);
}
private String value(int i) {
return values.get(i);
}
private void value(int i, String val) {
values.set(i, val);
}
private void addNormal(String originalName, String normalName, String value) {
originalNames.add(originalName);
names.add(normalName);
values.add(value);
}
/**
* Removes all elements at and after the given index.
*/
private void truncate(int i) {
for (int k = size() - 1; k >= i; k--) {
originalNames.remove(k);
names.remove(k);
values.remove(k);
}
}
/**
* Checks if the given value is compliant with our RFC 7230 based check
*/
private static boolean isValid(@Nullable String value) {
if (value == null || findInvalid(value) == ABSENT) {
return true;
}
invalidHeaderCounter.increment();
return false;
}
/**
* Checks if the input value is compliant with our RFC 7230 based check
* Returns input value if valid, raises ZuulException otherwise
*/
private static String validateField(@Nullable String value) {
if (value != null) {
int pos = findInvalid(value);
if (pos != ABSENT) {
invalidHeaderCounter.increment();
throw new ZuulException("Invalid header field: char " + (int) value.charAt(pos) + " in string " + value
+ " does not comply with RFC 7230");
}
}
return value;
}
/**
* Validated the input value based on RFC 7230 but more lenient.
* Currently, only ASCII control characters are considered invalid.
*
* Returns the index of first invalid character. Returns {@link #ABSENT} if absent.
*/
private static int findInvalid(String value) {
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
// ASCII non-control characters, per RFC 7230 but slightly more lenient
if (c < 31 || c == 127) {
return i;
}
}
return ABSENT;
}
}
| 6,313 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/ZuulMessage.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.message;
import com.netflix.zuul.context.SessionContext;
import com.netflix.zuul.filters.ZuulFilter;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.LastHttpContent;
import javax.annotation.Nullable;
/**
* Represents a message that propagates through the Zuul filter chain.
*/
public interface ZuulMessage extends Cloneable {
/**
* Returns the session context of this message.
*/
SessionContext getContext();
/**
* Returns the headers for this message. They may be request or response headers, depending on the underlying type
* of this object. For some messages, there may be no headers, such as with chunked requests or responses. In this
* case, a non-{@code null} default headers value will be returned.
*/
Headers getHeaders();
/**
* Sets the headers for this message.
*
* @throws NullPointerException if newHeaders is {@code null}.
*/
void setHeaders(Headers newHeaders);
/**
* Returns if this message has an attached body. For requests, this is typically an HTTP POST body. For
* responses, this is typically the HTTP response.
*/
boolean hasBody();
/**
* Declares that this message has a body. This method is automatically called when {@link #bufferBodyContents}
* is invoked.
*/
void setHasBody(boolean hasBody);
/**
* Returns the message body. If there is no message body, this returns {@code null}.
*/
@Nullable
byte[] getBody();
/**
* Returns the length of the message body, or {@code 0} if there isn't a message present.
*/
int getBodyLength();
/**
* Sets the message body. Note: if the {@code body} is {@code null}, this may not reset the body presence as
* returned by {@link #hasBody}. The body is considered complete after calling this method.
*/
void setBody(@Nullable byte[] body);
/**
* Sets the message body as UTF-8 encoded text. Note that this does NOT set any headers related to the
* Content-Type; callers must set or reset the content type to UTF-8. The body is considered complete after
* calling this method.
*/
void setBodyAsText(@Nullable String bodyText);
/**
* Appends an HTTP content chunk to this message. Callers should be careful not to add multiple chunks that
* implement {@link LastHttpContent}.
*
* @throws NullPointerException if {@code chunk} is {@code null}.
*/
void bufferBodyContents(HttpContent chunk);
/**
* Returns the HTTP content chunks that are part of this message. Callers should avoid retaining the return value,
* as the contents may change with subsequent body mutations.
*/
Iterable<HttpContent> getBodyContents();
/**
* Sets the message body to be complete if it was not already so.
*
* @return {@code true} if the body was not yet complete, or else false.
*/
boolean finishBufferedBodyIfIncomplete();
/**
* Indicates that the message contains a content chunk the implements {@link LastHttpContent}.
*/
boolean hasCompleteBody();
/**
* Passes the body content chunks through the given filter, and sets them back into this message.
*/
void runBufferedBodyContentThroughFilter(ZuulFilter<?, ?> filter);
/**
* Clears the content chunks of this body, calling {@code release()} in the process. Users SHOULD call this method
* when the body content is no longer needed.
*/
void disposeBufferedBody();
/**
* Gets the body of this message as UTF-8 text, or {@code null} if there is no body.
*/
@Nullable
String getBodyAsText();
/**
* Reset the chunked body reader indexes. Users SHOULD call this method before retrying requests
* as the chunked body buffer will have had the reader indexes changed during channel writes.
*/
void resetBodyReader();
/**
* Returns the maximum body size that this message is willing to hold. This value value should be more than the
* sum of lengths of the body chunks. The max body size may not be strictly enforced, and is informational.
*/
int getMaxBodySize();
/**
* Returns a copy of this message.
*/
ZuulMessage clone();
/**
* Returns a string that reprsents this message which is suitable for debugging.
*/
String getInfoForLogging();
}
| 6,314 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/ZuulMessageImpl.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.message;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.netty.common.ByteBufUtil;
import com.netflix.zuul.context.SessionContext;
import com.netflix.zuul.filters.ZuulFilter;
import com.netflix.zuul.message.http.HttpHeaderNames;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultLastHttpContent;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.LastHttpContent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* User: michaels@netflix.com
* Date: 2/20/15
* Time: 3:10 PM
*/
public class ZuulMessageImpl implements ZuulMessage {
protected static final DynamicIntProperty MAX_BODY_SIZE_PROP =
DynamicPropertyFactory.getInstance().getIntProperty("zuul.message.body.max.size", 25 * 1000 * 1024);
protected final SessionContext context;
protected Headers headers;
private boolean hasBody;
private boolean bodyBufferedCompletely;
private List<HttpContent> bodyChunks;
public ZuulMessageImpl(SessionContext context) {
this(context, new Headers());
}
public ZuulMessageImpl(SessionContext context, Headers headers) {
this.context = context == null ? new SessionContext() : context;
this.headers = headers == null ? new Headers() : headers;
this.bodyChunks = new ArrayList<>(16);
}
@Override
public SessionContext getContext() {
return context;
}
@Override
public Headers getHeaders() {
return headers;
}
@Override
public void setHeaders(Headers newHeaders) {
this.headers = newHeaders;
}
@Override
public int getMaxBodySize() {
return MAX_BODY_SIZE_PROP.get();
}
@Override
public void setHasBody(boolean hasBody) {
this.hasBody = hasBody;
}
@Override
public boolean hasBody() {
return hasBody;
}
@Override
public boolean hasCompleteBody() {
return bodyBufferedCompletely;
}
@Override
public void bufferBodyContents(final HttpContent chunk) {
setHasBody(true);
ByteBufUtil.touch(chunk, "ZuulMessage buffering body content.");
bodyChunks.add(chunk);
if (chunk instanceof LastHttpContent) {
ByteBufUtil.touch(chunk, "ZuulMessage buffering body content complete.");
bodyBufferedCompletely = true;
}
}
private void setContentLength(int length) {
headers.remove(HttpHeaderNames.TRANSFER_ENCODING);
headers.set(HttpHeaderNames.CONTENT_LENGTH, Integer.toString(length));
}
@Override
public void setBodyAsText(String bodyText) {
disposeBufferedBody();
if (!Strings.isNullOrEmpty(bodyText)) {
byte[] bytes = bodyText.getBytes(Charsets.UTF_8);
bufferBodyContents(new DefaultLastHttpContent(Unpooled.wrappedBuffer(bytes)));
setContentLength(bytes.length);
} else {
bufferBodyContents(new DefaultLastHttpContent());
setContentLength(0);
}
}
@Override
public void setBody(byte[] body) {
disposeBufferedBody();
if (body != null && body.length > 0) {
final ByteBuf content = Unpooled.copiedBuffer(body);
bufferBodyContents(new DefaultLastHttpContent(content));
setContentLength(body.length);
} else {
bufferBodyContents(new DefaultLastHttpContent());
setContentLength(0);
}
}
@Override
public String getBodyAsText() {
final byte[] body = getBody();
return (body != null && body.length > 0) ? new String(getBody(), Charsets.UTF_8) : null;
}
@Override
public byte[] getBody() {
if (bodyChunks.size() == 0) {
return null;
}
int size = 0;
for (final HttpContent chunk : bodyChunks) {
size += chunk.content().readableBytes();
}
final byte[] body = new byte[size];
int offset = 0;
for (final HttpContent chunk : bodyChunks) {
final ByteBuf content = chunk.content();
final int len = content.readableBytes();
content.getBytes(content.readerIndex(), body, offset, len);
offset += len;
}
return body;
}
@Override
public int getBodyLength() {
int size = 0;
for (final HttpContent chunk : bodyChunks) {
size += chunk.content().readableBytes();
}
return size;
}
@Override
public Iterable<HttpContent> getBodyContents() {
return Collections.unmodifiableList(bodyChunks);
}
@Override
public void resetBodyReader() {
for (final HttpContent chunk : bodyChunks) {
chunk.content().resetReaderIndex();
}
}
@Override
public boolean finishBufferedBodyIfIncomplete() {
if (!bodyBufferedCompletely) {
bufferBodyContents(new DefaultLastHttpContent());
return true;
}
return false;
}
@Override
public void disposeBufferedBody() {
bodyChunks.forEach(chunk -> {
if ((chunk != null) && (chunk.refCnt() > 0)) {
ByteBufUtil.touch(chunk, "ZuulMessage disposing buffered body");
chunk.release();
}
});
bodyChunks.clear();
}
@Override
public void runBufferedBodyContentThroughFilter(ZuulFilter<?, ?> filter) {
// Loop optimized for the common case: Most filters' processContentChunk() return
// original chunk passed in as is without any processing
final String filterName = filter.filterName();
for (int i = 0; i < bodyChunks.size(); i++) {
final HttpContent origChunk = bodyChunks.get(i);
ByteBufUtil.touch(origChunk, "ZuulMessage processing chunk, filter: ", filterName);
final HttpContent filteredChunk = filter.processContentChunk(this, origChunk);
ByteBufUtil.touch(filteredChunk, "ZuulMessage processing filteredChunk, filter: ", filterName);
if ((filteredChunk != null) && (filteredChunk != origChunk)) {
// filter actually did some processing, set the new chunk in and release the old chunk.
bodyChunks.set(i, filteredChunk);
final int refCnt = origChunk.refCnt();
if (refCnt > 0) {
origChunk.release(refCnt);
}
}
}
}
@Override
public ZuulMessage clone() {
final ZuulMessageImpl copy = new ZuulMessageImpl(context.clone(), Headers.copyOf(headers));
this.bodyChunks.forEach(chunk -> {
chunk.retain();
copy.bufferBodyContents(chunk);
});
return copy;
}
/**
* Override this in more specific subclasses to add request/response info for logging purposes.
*/
@Override
public String getInfoForLogging() {
return "ZuulMessage";
}
}
| 6,315 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/Header.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.message;
/**
* Represents a single header from a {@link Headers} object.
*/
public final class Header {
private final HeaderName name;
private final String value;
public Header(HeaderName name, String value) {
if (name == null) {
throw new NullPointerException("Header name cannot be null!");
}
this.name = name;
this.value = value;
}
public String getKey() {
return name.getName();
}
public HeaderName getName() {
return name;
}
public String getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Header header = (Header) o;
if (!name.equals(header.name)) {
return false;
}
return !(value != null ? !value.equals(header.value) : header.value != null);
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return String.format("%s: %s", name, value);
}
}
| 6,316 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/util/HttpRequestBuilder.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.message.util;
import com.netflix.zuul.context.SessionContext;
import com.netflix.zuul.message.Headers;
import com.netflix.zuul.message.http.HttpQueryParams;
import com.netflix.zuul.message.http.HttpRequestMessage;
import com.netflix.zuul.message.http.HttpRequestMessageImpl;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;
import java.util.Objects;
/**
* Builder for a zuul http request. *exclusively* for use in unit tests.
*
* For default values initialized in the constructor:
* <pre>
* {@code new HttpRequestBuilder(context).withDefaults();}
*</pre>
*
* For overrides :
* <pre>
* {@code new HttpRequestBuilder(context).withHeaders(httpHeaders).withQueryParams(requestParams).build();}
* </pre>
* @author Argha C
* @since 5/11/21
*/
public final class HttpRequestBuilder {
private SessionContext sessionContext;
private String protocol;
private String method;
private String path;
private HttpQueryParams queryParams;
private Headers headers;
private String clientIp;
private String scheme;
private int port;
private String serverName;
private boolean isBuilt;
public HttpRequestBuilder(SessionContext context) {
sessionContext = Objects.requireNonNull(context);
protocol = HttpVersion.HTTP_1_1.text();
method = "get";
path = "/";
queryParams = new HttpQueryParams();
headers = new Headers();
clientIp = "::1";
scheme = "https";
port = 443;
isBuilt = false;
}
/**
* Builds a request with basic defaults
*
* @return `HttpRequestMessage`
*/
public HttpRequestMessage withDefaults() {
return build();
}
public HttpRequestBuilder withHost(String hostName) {
serverName = Objects.requireNonNull(hostName);
return this;
}
public HttpRequestBuilder withHeaders(Headers requestHeaders) {
headers = Objects.requireNonNull(requestHeaders);
return this;
}
public HttpRequestBuilder withQueryParams(HttpQueryParams requestParams) {
this.queryParams = Objects.requireNonNull(requestParams);
return this;
}
public HttpRequestBuilder withMethod(HttpMethod httpMethod) {
method = Objects.requireNonNull(httpMethod).name();
return this;
}
public HttpRequestBuilder withUri(String uri) {
path = Objects.requireNonNull(uri);
return this;
}
/**
* Used to build a request with overridden values
*
* @return `HttpRequestMessage`
*/
public HttpRequestMessage build() {
if (isBuilt) {
throw new IllegalStateException("Builder must only be invoked once!");
}
isBuilt = true;
return new HttpRequestMessageImpl(
sessionContext, protocol, method, path, queryParams, headers, clientIp, scheme, port, serverName);
}
}
| 6,317 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpResponseMessageImpl.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.message.http;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.zuul.context.SessionContext;
import com.netflix.zuul.filters.ZuulFilter;
import com.netflix.zuul.message.Header;
import com.netflix.zuul.message.Headers;
import com.netflix.zuul.message.ZuulMessage;
import com.netflix.zuul.message.ZuulMessageImpl;
import io.netty.handler.codec.http.Cookie;
import io.netty.handler.codec.http.CookieDecoder;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.ServerCookieEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* User: michaels
* Date: 2/24/15
* Time: 10:54 AM
*/
public class HttpResponseMessageImpl implements HttpResponseMessage {
private static final DynamicIntProperty MAX_BODY_SIZE_PROP = DynamicPropertyFactory.getInstance()
.getIntProperty("zuul.HttpResponseMessage.body.max.size", 25 * 1000 * 1024);
private static final Logger LOG = LoggerFactory.getLogger(HttpResponseMessageImpl.class);
private ZuulMessage message;
private HttpRequestMessage outboundRequest;
private int status;
private HttpResponseInfo inboundResponse = null;
public HttpResponseMessageImpl(SessionContext context, HttpRequestMessage request, int status) {
this(context, new Headers(), request, status);
}
public HttpResponseMessageImpl(SessionContext context, Headers headers, HttpRequestMessage request, int status) {
this.message = new ZuulMessageImpl(context, headers);
this.outboundRequest = request;
if (this.outboundRequest.getInboundRequest() == null) {
LOG.warn(
"HttpResponseMessage created with a request that does not have a stored inboundRequest! Probably a bug in the filter that is creating this response.",
new RuntimeException("Invalid HttpRequestMessage"));
}
this.status = status;
}
public static HttpResponseMessage defaultErrorResponse(HttpRequestMessage request) {
final HttpResponseMessage resp = new HttpResponseMessageImpl(request.getContext(), request, 500);
resp.finishBufferedBodyIfIncomplete();
return resp;
}
@Override
public Headers getHeaders() {
return message.getHeaders();
}
@Override
public SessionContext getContext() {
return message.getContext();
}
@Override
public void setHeaders(Headers newHeaders) {
message.setHeaders(newHeaders);
}
@Override
public void setHasBody(boolean hasBody) {
message.setHasBody(hasBody);
}
@Override
public boolean hasBody() {
return message.hasBody();
}
@Override
public void bufferBodyContents(HttpContent chunk) {
message.bufferBodyContents(chunk);
}
@Override
public void setBodyAsText(String bodyText) {
message.setBodyAsText(bodyText);
}
@Override
public void setBody(byte[] body) {
message.setBody(body);
}
@Override
public String getBodyAsText() {
return message.getBodyAsText();
}
@Override
public byte[] getBody() {
return message.getBody();
}
@Override
public int getBodyLength() {
return message.getBodyLength();
}
@Override
public boolean hasCompleteBody() {
return message.hasCompleteBody();
}
@Override
public boolean finishBufferedBodyIfIncomplete() {
return message.finishBufferedBodyIfIncomplete();
}
@Override
public Iterable<HttpContent> getBodyContents() {
return message.getBodyContents();
}
@Override
public void resetBodyReader() {
message.resetBodyReader();
}
@Override
public void runBufferedBodyContentThroughFilter(ZuulFilter filter) {
message.runBufferedBodyContentThroughFilter(filter);
}
@Override
public void disposeBufferedBody() {
message.disposeBufferedBody();
}
@Override
public HttpRequestInfo getInboundRequest() {
return outboundRequest.getInboundRequest();
}
@Override
public HttpRequestMessage getOutboundRequest() {
return outboundRequest;
}
@Override
public int getStatus() {
return status;
}
@Override
public void setStatus(int status) {
this.status = status;
}
@Override
public int getMaxBodySize() {
return MAX_BODY_SIZE_PROP.get();
}
@Override
public Cookies parseSetCookieHeader(String setCookieValue) {
Cookies cookies = new Cookies();
for (Cookie cookie : CookieDecoder.decode(setCookieValue)) {
cookies.add(cookie);
}
return cookies;
}
@Override
public boolean hasSetCookieWithName(String cookieName) {
boolean has = false;
for (String setCookieValue : getHeaders().getAll(HttpHeaderNames.SET_COOKIE)) {
for (Cookie cookie : CookieDecoder.decode(setCookieValue)) {
if (cookie.getName().equalsIgnoreCase(cookieName)) {
has = true;
break;
}
}
}
return has;
}
@Override
public boolean removeExistingSetCookie(String cookieName) {
String cookieNamePrefix = cookieName + "=";
boolean dirty = false;
Headers filtered = new Headers();
for (Header hdr : getHeaders().entries()) {
if (HttpHeaderNames.SET_COOKIE.equals(hdr.getName())) {
String value = hdr.getValue();
// Strip out this set-cookie as requested.
if (value.startsWith(cookieNamePrefix)) {
// Don't copy it.
dirty = true;
} else {
// Copy all other headers.
filtered.add(hdr.getName(), hdr.getValue());
}
} else {
// Copy all other headers.
filtered.add(hdr.getName(), hdr.getValue());
}
}
if (dirty) {
setHeaders(filtered);
}
return dirty;
}
@Override
public void addSetCookie(Cookie cookie) {
getHeaders().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode(cookie));
}
@Override
public void setSetCookie(Cookie cookie) {
getHeaders().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode(cookie));
}
@Override
public ZuulMessage clone() {
// TODO - not sure if should be cloning the outbound request object here or not....
HttpResponseMessageImpl clone = new HttpResponseMessageImpl(
getContext().clone(), Headers.copyOf(getHeaders()), getOutboundRequest(), getStatus());
if (getInboundResponse() != null) {
clone.inboundResponse = (HttpResponseInfo) getInboundResponse().clone();
}
return clone;
}
protected HttpResponseInfo copyResponseInfo() {
HttpResponseMessageImpl response = new HttpResponseMessageImpl(
getContext(), Headers.copyOf(getHeaders()), getOutboundRequest(), getStatus());
response.setHasBody(hasBody());
return response;
}
@Override
public String toString() {
return "HttpResponseMessageImpl{" + "message="
+ message + ", outboundRequest="
+ outboundRequest + ", status="
+ status + ", inboundResponse="
+ inboundResponse + '}';
}
@Override
public void storeInboundResponse() {
inboundResponse = copyResponseInfo();
}
@Override
public HttpResponseInfo getInboundResponse() {
return inboundResponse;
}
@Override
public String getInfoForLogging() {
HttpRequestInfo req = getInboundRequest() == null ? getOutboundRequest() : getInboundRequest();
StringBuilder sb = new StringBuilder()
.append(req.getInfoForLogging())
.append(",proxy-status=")
.append(getStatus());
return sb.toString();
}
}
| 6,318 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpHeaderNamesCache.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.message.http;
import com.netflix.zuul.message.HeaderName;
import java.util.concurrent.ConcurrentHashMap;
/**
* User: Mike Smith
* Date: 8/5/15
* Time: 1:08 PM
*/
public class HttpHeaderNamesCache {
private final ConcurrentHashMap<String, HeaderName> cache;
private final int maxSize;
public HttpHeaderNamesCache(int initialSize, int maxSize) {
this.cache = new ConcurrentHashMap<>(initialSize);
this.maxSize = maxSize;
}
public boolean isFull() {
return cache.size() >= maxSize;
}
public HeaderName get(String name) {
// Check in the static cache for this headername if available.
// NOTE: we do this lookup case-sensitively, as doing case-INSENSITIVELY removes the purpose of
// caching the object in the first place (ie. the expensive operation we want to avoid by caching
// is the case-insensitive string comparisons).
HeaderName hn = cache.get(name);
if (hn == null) {
// Here we're accepting that the isFull check is not happening atomically with the put, as we don't mind
// too much if the cache overfills a bit.
if (isFull()) {
hn = new HeaderName(name);
} else {
hn = cache.computeIfAbsent(name, (newName) -> new HeaderName(newName));
}
}
return hn;
}
}
| 6,319 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpHeaderNames.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.message.http;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.zuul.message.HeaderName;
/**
* A cache of both constants for common HTTP header names, and custom added header names.
*
* Primarily to be used as a performance optimization for avoiding repeatedly doing lower-casing and
* case-insensitive comparisons of StringS.
*
* User: Mike Smith
* Date: 8/5/15
* Time: 12:33 PM
*/
public final class HttpHeaderNames {
private static final DynamicIntProperty MAX_CACHE_SIZE = DynamicPropertyFactory.getInstance()
.getIntProperty("com.netflix.zuul.message.http.HttpHeaderNames.maxCacheSize", 30);
private static final HttpHeaderNamesCache HEADER_NAME_CACHE = new HttpHeaderNamesCache(100, MAX_CACHE_SIZE.get());
public static final HeaderName COOKIE = HEADER_NAME_CACHE.get("Cookie");
public static final HeaderName SET_COOKIE = HEADER_NAME_CACHE.get("Set-Cookie");
public static final HeaderName DATE = HEADER_NAME_CACHE.get("Date");
public static final HeaderName CONNECTION = HEADER_NAME_CACHE.get("Connection");
public static final HeaderName KEEP_ALIVE = HEADER_NAME_CACHE.get("Keep-Alive");
public static final HeaderName HOST = HEADER_NAME_CACHE.get("Host");
public static final HeaderName SERVER = HEADER_NAME_CACHE.get("Server");
public static final HeaderName VIA = HEADER_NAME_CACHE.get("Via");
public static final HeaderName USER_AGENT = HEADER_NAME_CACHE.get("User-Agent");
public static final HeaderName REFERER = HEADER_NAME_CACHE.get("Referer");
public static final HeaderName ORIGIN = HEADER_NAME_CACHE.get("Origin");
public static final HeaderName LOCATION = HEADER_NAME_CACHE.get("Location");
public static final HeaderName UPGRADE = HEADER_NAME_CACHE.get("Upgrade");
public static final HeaderName CONTENT_TYPE = HEADER_NAME_CACHE.get("Content-Type");
public static final HeaderName CONTENT_LENGTH = HEADER_NAME_CACHE.get("Content-Length");
public static final HeaderName CONTENT_ENCODING = HEADER_NAME_CACHE.get("Content-Encoding");
public static final HeaderName ACCEPT = HEADER_NAME_CACHE.get("Accept");
public static final HeaderName ACCEPT_ENCODING = HEADER_NAME_CACHE.get("Accept-Encoding");
public static final HeaderName ACCEPT_LANGUAGE = HEADER_NAME_CACHE.get("Accept-Language");
public static final HeaderName TRANSFER_ENCODING = HEADER_NAME_CACHE.get("Transfer-Encoding");
public static final HeaderName TE = HEADER_NAME_CACHE.get("TE");
public static final HeaderName RANGE = HEADER_NAME_CACHE.get("Range");
public static final HeaderName ACCEPT_RANGES = HEADER_NAME_CACHE.get("Accept-Ranges");
public static final HeaderName ALLOW = HEADER_NAME_CACHE.get("Allow");
public static final HeaderName VARY = HEADER_NAME_CACHE.get("Vary");
public static final HeaderName LAST_MODIFIED = HEADER_NAME_CACHE.get("Last-Modified");
public static final HeaderName ETAG = HEADER_NAME_CACHE.get("ETag");
public static final HeaderName EXPIRES = HEADER_NAME_CACHE.get("Expires");
public static final HeaderName CACHE_CONTROL = HEADER_NAME_CACHE.get("Cache-Control");
public static final HeaderName EDGE_CONTROL = HEADER_NAME_CACHE.get("Edge-Control");
public static final HeaderName PRAGMA = HEADER_NAME_CACHE.get("Pragma");
public static final HeaderName X_FORWARDED_HOST = HEADER_NAME_CACHE.get("X-Forwarded-Host");
public static final HeaderName X_FORWARDED_FOR = HEADER_NAME_CACHE.get("X-Forwarded-For");
public static final HeaderName X_FORWARDED_PORT = HEADER_NAME_CACHE.get("X-Forwarded-Port");
public static final HeaderName X_FORWARDED_PROTO = HEADER_NAME_CACHE.get("X-Forwarded-Proto");
public static final HeaderName X_FORWARDED_PROTO_VERSION = HEADER_NAME_CACHE.get("X-Forwarded-Proto-Version");
public static final HeaderName ACCESS_CONTROL_ALLOW_ORIGIN = HEADER_NAME_CACHE.get("Access-Control-Allow-Origin");
public static final HeaderName ACCESS_CONTROL_ALLOW_CREDENTIALS =
HEADER_NAME_CACHE.get("Access-Control-Allow-Credentials");
public static final HeaderName ACCESS_CONTROL_ALLOW_HEADERS = HEADER_NAME_CACHE.get("Access-Control-Allow-Headers");
public static final HeaderName ACCESS_CONTROL_ALLOW_METHODS = HEADER_NAME_CACHE.get("Access-Control-Allow-Methods");
public static final HeaderName ACCESS_CONTROL_REQUEST_HEADERS =
HEADER_NAME_CACHE.get("Access-Control-Request-Headers");
public static final HeaderName ACCESS_CONTROL_EXPOSE_HEADERS =
HEADER_NAME_CACHE.get("Access-Control-Expose-Headers");
public static final HeaderName ACCESS_CONTROL_MAX_AGE_HEADERS = HEADER_NAME_CACHE.get("Access-Control-Max-Age");
public static final HeaderName STRICT_TRANSPORT_SECURITY = HEADER_NAME_CACHE.get("Strict-Transport-Security");
public static final HeaderName LINK = HEADER_NAME_CACHE.get("Link");
/**
* Looks up the name in the cache, and if does not exist, then creates and adds a new one
* (up to the max cache size).
*
* @param name
* @return HeaderName - never null.
*/
public static HeaderName get(String name) {
return HEADER_NAME_CACHE.get(name);
}
}
| 6,320 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/http/Cookies.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.message.http;
import io.netty.handler.codec.http.Cookie;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User: Mike Smith
* Date: 6/18/15
* Time: 12:04 AM
*/
public class Cookies {
private Map<String, List<Cookie>> map = new HashMap<>();
private List<Cookie> all = new ArrayList<>();
public void add(Cookie cookie) {
List<Cookie> existing = map.get(cookie.getName());
if (existing == null) {
existing = new ArrayList<>();
map.put(cookie.getName(), existing);
}
existing.add(cookie);
all.add(cookie);
}
public List<Cookie> getAll() {
return all;
}
public List<Cookie> get(String name) {
return map.get(name);
}
public Cookie getFirst(String name) {
List<Cookie> found = map.get(name);
if (found == null || found.size() == 0) {
return null;
}
return found.get(0);
}
public String getFirstValue(String name) {
Cookie c = getFirst(name);
String value;
if (c != null) {
value = c.getValue();
} else {
value = null;
}
return value;
}
}
| 6,321 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpRequestInfo.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.message.http;
import com.netflix.zuul.message.Headers;
import com.netflix.zuul.message.ZuulMessage;
import java.util.Optional;
/**
* User: Mike Smith
* Date: 7/15/15
* Time: 1:18 PM
*/
public interface HttpRequestInfo extends ZuulMessage {
String getProtocol();
String getMethod();
String getPath();
HttpQueryParams getQueryParams();
String getPathAndQuery();
@Override
Headers getHeaders();
String getClientIp();
String getScheme();
int getPort();
String getServerName();
@Override
int getMaxBodySize();
@Override
String getInfoForLogging();
String getOriginalHost();
String getOriginalScheme();
String getOriginalProtocol();
int getOriginalPort();
/**
* Reflects the actual destination port that the client intended to communicate with,
* in preference to the port Zuul was listening on. In the case where proxy protocol is
* enabled, this should reflect the destination IP encoded in the TCP payload by the load balancer.
*/
default Optional<Integer> getClientDestinationPort() {
throw new UnsupportedOperationException();
}
String reconstructURI();
/** Parse and lazily cache the request cookies. */
Cookies parseCookies();
/**
* Force parsing/re-parsing of the cookies. May want to do this if headers
* have been mutated since cookies were first parsed.
*/
Cookies reParseCookies();
}
| 6,322 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpResponseMessage.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.message.http;
import io.netty.handler.codec.http.Cookie;
/**
* User: Mike Smith
* Date: 7/16/15
* Time: 12:45 AM
*/
public interface HttpResponseMessage extends HttpResponseInfo {
void setStatus(int status);
@Override
int getMaxBodySize();
void addSetCookie(Cookie cookie);
void setSetCookie(Cookie cookie);
boolean removeExistingSetCookie(String cookieName);
/** The mutable request that will be sent to Origin. */
HttpRequestMessage getOutboundRequest();
/** The immutable response that was received from Origin. */
HttpResponseInfo getInboundResponse();
/** This should be called after response received from Origin, to store
* a copy of the response as-is. */
void storeInboundResponse();
}
| 6,323 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpRequestMessage.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.message.http;
import com.netflix.zuul.message.ZuulMessage;
/**
* User: Mike Smith
* Date: 7/15/15
* Time: 5:36 PM
*/
public interface HttpRequestMessage extends HttpRequestInfo {
void setProtocol(String protocol);
void setMethod(String method);
void setPath(String path);
void setScheme(String scheme);
void setServerName(String serverName);
@Override
ZuulMessage clone();
void storeInboundRequest();
HttpRequestInfo getInboundRequest();
void setQueryParams(HttpQueryParams queryParams);
}
| 6,324 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpQueryParams.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.message.http;
import com.google.common.base.Strings;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
/**
* User: michaels
* Date: 2/24/15
* Time: 10:58 AM
*/
public class HttpQueryParams implements Cloneable {
private final ListMultimap<String, String> delegate;
private final boolean immutable;
private final HashMap<String, Boolean> trailingEquals;
public HttpQueryParams() {
delegate = ArrayListMultimap.create();
immutable = false;
trailingEquals = new HashMap<>();
}
private HttpQueryParams(ListMultimap<String, String> delegate) {
this.delegate = delegate;
immutable = ImmutableListMultimap.class.isAssignableFrom(delegate.getClass());
trailingEquals = new HashMap<>();
}
public static HttpQueryParams parse(String queryString) {
HttpQueryParams queryParams = new HttpQueryParams();
if (queryString == null) {
return queryParams;
}
StringTokenizer st = new StringTokenizer(queryString, "&");
int i;
while (st.hasMoreTokens()) {
String s = st.nextToken();
i = s.indexOf("=");
// key-value query param
if (i > 0) {
String name = s.substring(0, i);
String value = s.substring(i + 1);
try {
name = URLDecoder.decode(name, "UTF-8");
value = URLDecoder.decode(value, "UTF-8");
} catch (Exception e) {
// do nothing
}
queryParams.add(name, value);
// respect trailing equals for key-only params
if (s.endsWith("=") && value.isEmpty()) {
queryParams.setTrailingEquals(name, true);
}
}
// key only
else if (s.length() > 0) {
String name = s;
try {
name = URLDecoder.decode(name, "UTF-8");
} catch (Exception e) {
// do nothing
}
queryParams.add(name, "");
}
}
return queryParams;
}
/**
* Get the first value found for this key even if there are multiple. If none, then
* return null.
*/
public String getFirst(String name) {
List<String> values = delegate.get(name);
if (values != null) {
if (values.size() > 0) {
return values.get(0);
}
}
return null;
}
public List<String> get(String name) {
return delegate.get(name.toLowerCase());
}
public boolean contains(String name) {
return delegate.containsKey(name);
}
/**
* Per https://tools.ietf.org/html/rfc7230#page-19, query params are to be treated as case sensitive.
* However, as an utility, this exists to allow us to do a case insensitive match on demand.
*/
public boolean containsIgnoreCase(String name) {
return delegate.containsKey(name) || delegate.containsKey(name.toLowerCase(Locale.ROOT));
}
public boolean contains(String name, String value) {
return delegate.containsEntry(name, value);
}
/**
* Replace any/all entries with this key, with this single entry.
*/
public void set(String name, String value) {
delegate.removeAll(name);
delegate.put(name, value);
}
public void add(String name, String value) {
delegate.put(name, value);
}
public void removeAll(String name) {
delegate.removeAll(name);
}
public void clear() {
delegate.clear();
}
public Collection<Map.Entry<String, String>> entries() {
return delegate.entries();
}
public Set<String> keySet() {
return delegate.keySet();
}
public String toEncodedString() {
StringBuilder sb = new StringBuilder();
try {
for (Map.Entry<String, String> entry : entries()) {
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
if (!Strings.isNullOrEmpty(entry.getValue())) {
sb.append('=');
sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
} else if (isTrailingEquals(entry.getKey())) {
sb.append('=');
}
sb.append('&');
}
// Remove trailing '&'.
if (sb.length() > 0 && '&' == sb.charAt(sb.length() - 1)) {
sb.deleteCharAt(sb.length() - 1);
}
} catch (UnsupportedEncodingException e) {
// Won't happen.
e.printStackTrace();
}
return sb.toString();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : entries()) {
sb.append(entry.getKey());
if (!Strings.isNullOrEmpty(entry.getValue())) {
sb.append('=');
sb.append(entry.getValue());
}
sb.append('&');
}
// Remove trailing '&'.
if (sb.length() > 0 && '&' == sb.charAt(sb.length() - 1)) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
@Override
protected HttpQueryParams clone() {
HttpQueryParams copy = new HttpQueryParams();
copy.delegate.putAll(this.delegate);
return copy;
}
public HttpQueryParams immutableCopy() {
return new HttpQueryParams(ImmutableListMultimap.copyOf(delegate));
}
public boolean isImmutable() {
return immutable;
}
public boolean isTrailingEquals(String key) {
return trailingEquals.getOrDefault(key, false);
}
public void setTrailingEquals(String key, boolean trailingEquals) {
this.trailingEquals.put(key, trailingEquals);
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof HttpQueryParams)) {
return false;
}
HttpQueryParams hqp2 = (HttpQueryParams) obj;
return Iterables.elementsEqual(delegate.entries(), hqp2.delegate.entries());
}
}
| 6,325 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpRequestMessageImpl.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.message.http;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.config.CachedDynamicBooleanProperty;
import com.netflix.config.CachedDynamicIntProperty;
import com.netflix.config.DynamicStringProperty;
import com.netflix.util.Pair;
import com.netflix.zuul.context.CommonContextKeys;
import com.netflix.zuul.context.SessionContext;
import com.netflix.zuul.filters.ZuulFilter;
import com.netflix.zuul.message.Headers;
import com.netflix.zuul.message.ZuulMessage;
import com.netflix.zuul.message.ZuulMessageImpl;
import com.netflix.zuul.util.HttpUtils;
import io.netty.handler.codec.http.Cookie;
import io.netty.handler.codec.http.CookieDecoder;
import io.netty.handler.codec.http.HttpContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* User: michaels
* Date: 2/24/15
* Time: 10:54 AM
*/
public class HttpRequestMessageImpl implements HttpRequestMessage {
private static final Logger LOG = LoggerFactory.getLogger(HttpRequestMessageImpl.class);
private static final CachedDynamicBooleanProperty STRICT_HOST_HEADER_VALIDATION =
new CachedDynamicBooleanProperty("zuul.HttpRequestMessage.host.header.strict.validation", true);
private static final CachedDynamicIntProperty MAX_BODY_SIZE_PROP =
new CachedDynamicIntProperty("zuul.HttpRequestMessage.body.max.size", 15 * 1000 * 1024);
private static final CachedDynamicBooleanProperty CLEAN_COOKIES =
new CachedDynamicBooleanProperty("zuul.HttpRequestMessage.cookies.clean", false);
/** ":::"-delimited list of regexes to strip out of the cookie headers. */
private static final DynamicStringProperty REGEX_PTNS_TO_STRIP_PROP =
new DynamicStringProperty("zuul.request.cookie.cleaner.strip", " Secure,");
private static final List<Pattern> RE_STRIP;
static {
RE_STRIP = new ArrayList<>();
for (String ptn : REGEX_PTNS_TO_STRIP_PROP.get().split(":::")) {
RE_STRIP.add(Pattern.compile(ptn));
}
}
private static final String URI_SCHEME_SEP = "://";
private static final String URI_SCHEME_HTTP = "http";
private static final String URI_SCHEME_HTTPS = "https";
private final boolean immutable;
private ZuulMessage message;
private String protocol;
private String method;
private String path;
private String decodedPath;
private HttpQueryParams queryParams;
private String clientIp;
private String scheme;
private int port;
private String serverName;
private SocketAddress clientRemoteAddress;
private HttpRequestInfo inboundRequest = null;
private Cookies parsedCookies = null;
// These attributes are populated only if immutable=true.
private String reconstructedUri = null;
private String pathAndQuery = null;
private String infoForLogging = null;
private static final SocketAddress UNDEFINED_CLIENT_DEST_ADDRESS = new SocketAddress() {
@Override
public String toString() {
return "Undefined destination address.";
}
};
public HttpRequestMessageImpl(
SessionContext context,
String protocol,
String method,
String path,
HttpQueryParams queryParams,
Headers headers,
String clientIp,
String scheme,
int port,
String serverName) {
this(
context,
protocol,
method,
path,
queryParams,
headers,
clientIp,
scheme,
port,
serverName,
UNDEFINED_CLIENT_DEST_ADDRESS,
false);
}
public HttpRequestMessageImpl(
SessionContext context,
String protocol,
String method,
String path,
HttpQueryParams queryParams,
Headers headers,
String clientIp,
String scheme,
int port,
String serverName,
SocketAddress clientRemoteAddress,
boolean immutable) {
this.immutable = immutable;
this.message = new ZuulMessageImpl(context, headers);
this.protocol = protocol;
this.method = method;
this.path = path;
try {
this.decodedPath = URLDecoder.decode(path, "UTF-8");
} catch (Exception e) {
// fail to decode URI
// just set decodedPath to original path
this.decodedPath = path;
}
// Don't allow this to be null.
this.queryParams = queryParams == null ? new HttpQueryParams() : queryParams;
this.clientIp = clientIp;
this.scheme = scheme;
this.port = port;
this.serverName = serverName;
this.clientRemoteAddress = clientRemoteAddress;
}
private void immutableCheck() {
if (immutable) {
throw new IllegalStateException(
"This HttpRequestMessageImpl is immutable. No mutating operations allowed!");
}
}
@Override
public SessionContext getContext() {
return message.getContext();
}
@Override
public Headers getHeaders() {
return message.getHeaders();
}
@Override
public void setHeaders(Headers newHeaders) {
immutableCheck();
message.setHeaders(newHeaders);
}
@Override
public void setHasBody(boolean hasBody) {
message.setHasBody(hasBody);
}
@Override
public boolean hasBody() {
return message.hasBody();
}
@Override
public void bufferBodyContents(HttpContent chunk) {
message.bufferBodyContents(chunk);
}
@Override
public void setBodyAsText(String bodyText) {
message.setBodyAsText(bodyText);
}
@Override
public void setBody(byte[] body) {
message.setBody(body);
}
@Override
public boolean finishBufferedBodyIfIncomplete() {
return message.finishBufferedBodyIfIncomplete();
}
@Override
public Iterable<HttpContent> getBodyContents() {
return message.getBodyContents();
}
@Override
public void runBufferedBodyContentThroughFilter(ZuulFilter filter) {
message.runBufferedBodyContentThroughFilter(filter);
}
@Override
public String getBodyAsText() {
return message.getBodyAsText();
}
@Override
public byte[] getBody() {
return message.getBody();
}
@Override
public int getBodyLength() {
return message.getBodyLength();
}
@Override
public void resetBodyReader() {
message.resetBodyReader();
}
@Override
public boolean hasCompleteBody() {
return message.hasCompleteBody();
}
@Override
public void disposeBufferedBody() {
message.disposeBufferedBody();
}
@Override
public String getProtocol() {
return protocol;
}
@Override
public void setProtocol(String protocol) {
immutableCheck();
this.protocol = protocol;
}
@Override
public String getMethod() {
return method;
}
@Override
public void setMethod(String method) {
immutableCheck();
this.method = method;
}
@Override
public String getPath() {
if (message.getContext().get(CommonContextKeys.ZUUL_USE_DECODED_URI) == Boolean.TRUE) {
return decodedPath;
}
return path;
}
@Override
public void setPath(String path) {
immutableCheck();
this.path = path;
this.decodedPath = path;
}
@Override
public HttpQueryParams getQueryParams() {
return queryParams;
}
@Override
public String getPathAndQuery() {
// If this instance is immutable, then lazy-cache.
if (immutable) {
if (pathAndQuery == null) {
pathAndQuery = generatePathAndQuery();
}
return pathAndQuery;
} else {
return generatePathAndQuery();
}
}
protected String generatePathAndQuery() {
if (queryParams != null && queryParams.entries().size() > 0) {
return getPath() + "?" + queryParams.toEncodedString();
} else {
return getPath();
}
}
@Override
public String getClientIp() {
return clientIp;
}
@Deprecated
@VisibleForTesting
void setClientIp(String clientIp) {
immutableCheck();
this.clientIp = clientIp;
}
/**
* Note: this is meant to be used typically in cases where TLS termination happens on instance.
* For CLB/ALB fronted traffic, consider using {@link #getOriginalScheme()} instead.
*/
@Override
public String getScheme() {
return scheme;
}
@Override
public void setScheme(String scheme) {
immutableCheck();
this.scheme = scheme;
}
@Override
public int getPort() {
return port;
}
@Deprecated
@VisibleForTesting
void setPort(int port) {
immutableCheck();
this.port = port;
}
@Override
public String getServerName() {
return serverName;
}
@Override
public void setServerName(String serverName) {
immutableCheck();
this.serverName = serverName;
}
@Override
public Cookies parseCookies() {
if (parsedCookies == null) {
parsedCookies = reParseCookies();
}
return parsedCookies;
}
@Override
public Cookies reParseCookies() {
Cookies cookies = new Cookies();
for (String aCookieHeader : getHeaders().getAll(HttpHeaderNames.COOKIE)) {
try {
if (CLEAN_COOKIES.get()) {
aCookieHeader = cleanCookieHeader(aCookieHeader);
}
Set<Cookie> decoded = CookieDecoder.decode(aCookieHeader, false);
for (Cookie cookie : decoded) {
cookies.add(cookie);
}
} catch (Exception e) {
LOG.warn(
"Error parsing request Cookie header. cookie={}, request-info={}",
aCookieHeader,
getInfoForLogging(),
e);
}
}
parsedCookies = cookies;
return cookies;
}
@VisibleForTesting
static String cleanCookieHeader(String cookie) {
for (Pattern stripPtn : RE_STRIP) {
Matcher matcher = stripPtn.matcher(cookie);
if (matcher.find()) {
cookie = matcher.replaceAll("");
}
}
return cookie;
}
@Override
public int getMaxBodySize() {
return MAX_BODY_SIZE_PROP.get();
}
@Override
public ZuulMessage clone() {
HttpRequestMessageImpl clone = new HttpRequestMessageImpl(
message.getContext().clone(),
protocol,
method,
path,
queryParams.clone(),
Headers.copyOf(message.getHeaders()),
clientIp,
scheme,
port,
serverName,
clientRemoteAddress,
immutable);
if (getInboundRequest() != null) {
clone.inboundRequest = (HttpRequestInfo) getInboundRequest().clone();
}
return clone;
}
protected HttpRequestInfo copyRequestInfo() {
HttpRequestMessageImpl req = new HttpRequestMessageImpl(
message.getContext(),
protocol,
method,
path,
queryParams.immutableCopy(),
Headers.copyOf(message.getHeaders()),
clientIp,
scheme,
port,
serverName,
clientRemoteAddress,
true);
req.setHasBody(hasBody());
return req;
}
@Override
public void storeInboundRequest() {
inboundRequest = copyRequestInfo();
}
@Override
public HttpRequestInfo getInboundRequest() {
return inboundRequest;
}
@Override
public void setQueryParams(HttpQueryParams queryParams) {
immutableCheck();
this.queryParams = queryParams;
}
@Override
public String getInfoForLogging() {
// If this instance is immutable, then lazy-cache generating this info.
if (immutable) {
if (infoForLogging == null) {
infoForLogging = generateInfoForLogging();
}
return infoForLogging;
} else {
return generateInfoForLogging();
}
}
protected String generateInfoForLogging() {
HttpRequestInfo req = getInboundRequest() == null ? this : getInboundRequest();
StringBuilder sb = new StringBuilder()
.append("uri=")
.append(req.reconstructURI())
.append(", method=")
.append(req.getMethod())
.append(", clientip=")
.append(HttpUtils.getClientIP(req));
return sb.toString();
}
/**
* The originally request host. This will NOT include port.
*
* The Host header may contain port, but in this method we strip it out for consistency - use the
* getOriginalPort method for that.
*/
@Override
public String getOriginalHost() {
try {
return getOriginalHost(getHeaders(), getServerName());
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
@VisibleForTesting
static String getOriginalHost(Headers headers, String serverName) throws URISyntaxException {
String xForwardedHost = headers.getFirst(HttpHeaderNames.X_FORWARDED_HOST);
if (xForwardedHost != null) {
return xForwardedHost;
}
Pair<String, Integer> host = parseHostHeader(headers);
if (host.first() != null) {
return host.first();
}
return serverName;
}
@Override
public String getOriginalScheme() {
String scheme = getHeaders().getFirst(HttpHeaderNames.X_FORWARDED_PROTO);
if (scheme == null) {
scheme = getScheme();
}
return scheme;
}
@Override
public String getOriginalProtocol() {
String proto = getHeaders().getFirst(HttpHeaderNames.X_FORWARDED_PROTO_VERSION);
if (proto == null) {
proto = getProtocol();
}
return proto;
}
@Override
public int getOriginalPort() {
try {
return getOriginalPort(getContext(), getHeaders(), getPort());
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
@VisibleForTesting
static int getOriginalPort(SessionContext context, Headers headers, int serverPort) throws URISyntaxException {
if (context.containsKey(CommonContextKeys.PROXY_PROTOCOL_DESTINATION_ADDRESS)) {
return ((InetSocketAddress) context.get(CommonContextKeys.PROXY_PROTOCOL_DESTINATION_ADDRESS)).getPort();
}
String portStr = headers.getFirst(HttpHeaderNames.X_FORWARDED_PORT);
if (portStr != null && !portStr.isEmpty()) {
return Integer.parseInt(portStr);
}
try {
// Check if port was specified on a Host header.
Pair<String, Integer> host = parseHostHeader(headers);
if (host.second() != -1) {
return host.second();
}
} catch (URISyntaxException e) {
LOG.debug("Invalid host header, falling back to serverPort", e);
}
return serverPort;
}
@Override
public Optional<Integer> getClientDestinationPort() {
if (clientRemoteAddress instanceof InetSocketAddress) {
InetSocketAddress inetSocketAddress = (InetSocketAddress) this.clientRemoteAddress;
return Optional.of(inetSocketAddress.getPort());
} else {
return Optional.empty();
}
}
/**
* Attempt to parse the Host header from the collection of headers
* and return the hostname and port components.
*
* @return Hostname and Port pair.
* Hostname may be null. Port may be -1 when no valid port is found in the host header.
*/
private static Pair<String, Integer> parseHostHeader(Headers headers) throws URISyntaxException {
String host = headers.getFirst(HttpHeaderNames.HOST);
if (host == null) {
return new Pair<>(null, -1);
}
try {
// attempt to use default URI parsing - this can fail when not strictly following RFC2396,
// for example, having underscores in host names will fail parsing
URI uri = new URI(/* scheme= */ null, host, /* path= */ null, /* query= */ null, /* fragment= */ null);
if (uri.getHost() != null) {
return new Pair<>(uri.getHost(), uri.getPort());
}
} catch (URISyntaxException e) {
LOG.debug("URI parsing failed", e);
}
if (STRICT_HOST_HEADER_VALIDATION.get()) {
throw new URISyntaxException(host, "Invalid host");
}
// fallback to using a colon split
// valid IPv6 addresses would have been handled already so any colon is safely assumed a port separator
String[] components = host.split(":");
if (components.length > 2) {
// handle case with unbracketed IPv6 addresses
return new Pair<>(null, -1);
}
String parsedHost = components[0];
int parsedPort = -1;
if (components.length > 1) {
try {
parsedPort = Integer.parseInt(components[1]);
} catch (NumberFormatException e) {
// ignore failing to parse port numbers and fallback to default port
LOG.debug("Parsing of host port component failed", e);
}
}
return new Pair<>(parsedHost, parsedPort);
}
/**
* Attempt to reconstruct the full URI that the client used.
*
* @return String
*/
@Override
public String reconstructURI() {
// If this instance is immutable, then lazy-cache reconstructing the uri.
if (immutable) {
if (reconstructedUri == null) {
reconstructedUri = _reconstructURI();
}
return reconstructedUri;
} else {
return _reconstructURI();
}
}
protected String _reconstructURI() {
try {
StringBuilder uri = new StringBuilder(100);
String scheme = getOriginalScheme().toLowerCase();
uri.append(scheme);
uri.append(URI_SCHEME_SEP).append(getOriginalHost(getHeaders(), getServerName()));
int port = getOriginalPort();
if ((URI_SCHEME_HTTP.equals(scheme) && 80 == port) || (URI_SCHEME_HTTPS.equals(scheme) && 443 == port)) {
// Don't need to include port.
} else {
uri.append(':').append(port);
}
uri.append(getPathAndQuery());
return uri.toString();
} catch (URISyntaxException e) {
// This is not really so bad, just debug log it and move on.
LOG.debug("Error reconstructing request URI!", e);
return "";
} catch (Exception e) {
LOG.error("Error reconstructing request URI!", e);
return "";
}
}
@Override
public String toString() {
return "HttpRequestMessageImpl{" + "immutable="
+ immutable + ", message="
+ message + ", protocol='"
+ protocol + '\'' + ", method='"
+ method + '\'' + ", path='"
+ path + '\'' + ", queryParams="
+ queryParams + ", clientIp='"
+ clientIp + '\'' + ", scheme='"
+ scheme + '\'' + ", port="
+ port + ", serverName='"
+ serverName + '\'' + ", inboundRequest="
+ inboundRequest + ", parsedCookies="
+ parsedCookies + ", reconstructedUri='"
+ reconstructedUri + '\'' + ", pathAndQuery='"
+ pathAndQuery + '\'' + ", infoForLogging='"
+ infoForLogging + '\'' + '}';
}
}
| 6,326 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/message/http/HttpResponseInfo.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.message.http;
import com.netflix.zuul.message.ZuulMessage;
/**
* User: michaels@netflix.com
* Date: 7/6/15
* Time: 5:27 PM
*/
public interface HttpResponseInfo extends ZuulMessage {
int getStatus();
/** The immutable request that was originally received from client. */
HttpRequestInfo getInboundRequest();
@Override
ZuulMessage clone();
@Override
String getInfoForLogging();
Cookies parseSetCookieHeader(String setCookieValue);
boolean hasSetCookieWithName(String cookieName);
}
| 6,327 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/RequestCancelledEvent.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.netty;
/**
* User: michaels@netflix.com
* Date: 4/13/17
* Time: 6:09 PM
*/
public class RequestCancelledEvent {}
| 6,328 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/SpectatorUtils.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.netty;
import com.netflix.spectator.api.CompositeRegistry;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Spectator;
import com.netflix.spectator.api.Timer;
public final class SpectatorUtils {
private SpectatorUtils() {}
public static Counter newCounter(String name, String id) {
return Spectator.globalRegistry().counter(name, "id", id);
}
public static Counter newCounter(String name, String id, String... tags) {
String[] allTags = getTagsWithId(id, tags);
return Spectator.globalRegistry().counter(name, allTags);
}
public static Timer newTimer(String name, String id) {
return Spectator.registry().timer(name, "id", id);
}
public static Timer newTimer(String name, String id, String... tags) {
return Spectator.globalRegistry().timer(name, getTagsWithId(id, tags));
}
public static <T extends Number> T newGauge(String name, String id, T number) {
final CompositeRegistry registry = Spectator.globalRegistry();
Id gaugeId = registry.createId(name, "id", id);
return registry.gauge(gaugeId, number);
}
public static <T extends Number> T newGauge(String name, String id, T number, String... tags) {
final CompositeRegistry registry = Spectator.globalRegistry();
Id gaugeId = registry.createId(name, getTagsWithId(id, tags));
return registry.gauge(gaugeId, number);
}
private static String[] getTagsWithId(String id, String[] tags) {
String[] allTags = new String[tags.length + 2];
System.arraycopy(tags, 0, allTags, 0, tags.length);
allTags[allTags.length - 2] = "id";
allTags[allTags.length - 1] = id;
return allTags;
}
}
| 6,329 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/ChannelUtils.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.netty;
import com.netflix.zuul.passport.CurrentPassport;
import io.netty.channel.Channel;
public class ChannelUtils {
public static String channelInfoForLogging(Channel ch) {
if (ch == null) {
return "null";
}
String channelInfo = ch.toString()
+ ", active=" + ch.isActive()
+ ", open=" + ch.isOpen()
+ ", registered=" + ch.isRegistered()
+ ", writable=" + ch.isWritable()
+ ", id=" + ch.id();
CurrentPassport passport = CurrentPassport.fromChannel(ch);
return "Channel: " + channelInfo + ", Passport: " + String.valueOf(passport);
}
}
| 6,330 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/NettyRequestAttemptFactory.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.netty;
import com.netflix.zuul.context.SessionContext;
import com.netflix.zuul.exception.ErrorType;
import com.netflix.zuul.exception.OutboundErrorType;
import com.netflix.zuul.exception.OutboundException;
import com.netflix.zuul.netty.connectionpool.OriginConnectException;
import com.netflix.zuul.niws.RequestAttempts;
import com.netflix.zuul.origins.OriginConcurrencyExceededException;
import io.netty.channel.unix.Errors;
import io.netty.handler.timeout.ReadTimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.channels.ClosedChannelException;
public class NettyRequestAttemptFactory {
private static final Logger LOG = LoggerFactory.getLogger(NettyRequestAttemptFactory.class);
public ErrorType mapNettyToOutboundErrorType(final Throwable t) {
if (t instanceof ReadTimeoutException) {
return OutboundErrorType.READ_TIMEOUT;
}
if (t instanceof OriginConcurrencyExceededException) {
return OutboundErrorType.ORIGIN_CONCURRENCY_EXCEEDED;
}
if (t instanceof OriginConnectException) {
return ((OriginConnectException) t).getErrorType();
}
if (t instanceof OutboundException) {
return ((OutboundException) t).getOutboundErrorType();
}
if (t instanceof Errors.NativeIoException
&& Errors.ERRNO_ECONNRESET_NEGATIVE == ((Errors.NativeIoException) t).expectedErr()) {
// This is a "Connection reset by peer" which we see fairly often happening when Origin servers are
// overloaded.
LOG.warn("ERRNO_ECONNRESET_NEGATIVE mapped to RESET_CONNECTION", t);
return OutboundErrorType.RESET_CONNECTION;
}
if (t instanceof ClosedChannelException) {
return OutboundErrorType.RESET_CONNECTION;
}
final Throwable cause = t.getCause();
if (cause instanceof IllegalStateException && cause.getMessage().contains("server")) {
LOG.warn("IllegalStateException mapped to NO_AVAILABLE_SERVERS", cause);
return OutboundErrorType.NO_AVAILABLE_SERVERS;
}
return OutboundErrorType.OTHER;
}
public OutboundException mapNettyToOutboundException(final Throwable t, final SessionContext context) {
if (t instanceof OutboundException) {
return (OutboundException) t;
}
// Map this throwable to zuul's OutboundException.
final ErrorType errorType = mapNettyToOutboundErrorType(t);
final RequestAttempts attempts = RequestAttempts.getFromSessionContext(context);
if (errorType == OutboundErrorType.OTHER) {
return new OutboundException(errorType, attempts, t);
}
return new OutboundException(errorType, attempts);
}
}
| 6,331 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateListener.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.netty.insights;
import com.netflix.zuul.passport.CurrentPassport;
import com.netflix.zuul.passport.PassportState;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
public class PassportStateListener implements GenericFutureListener {
private final CurrentPassport passport;
private final PassportState successState;
private final PassportState failState;
public PassportStateListener(CurrentPassport passport, PassportState successState) {
this.passport = passport;
this.successState = successState;
this.failState = null;
}
public PassportStateListener(CurrentPassport passport, PassportState successState, PassportState failState) {
this.passport = passport;
this.successState = successState;
this.failState = failState;
}
@Override
public void operationComplete(Future future) throws Exception {
if (future.isSuccess()) {
passport.add(successState);
} else {
if (failState != null) {
// only capture a single failure state event,
// as sending content errors will fire for all content chunks,
// and we only need the first one
passport.addIfNotAlready(failState);
}
}
}
} | 6,332 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateOriginHandler.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.netty.insights;
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.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import java.net.SocketAddress;
/**
* User: Mike Smith
* Date: 9/24/16
* Time: 2:41 PM
*/
public final class PassportStateOriginHandler {
private static CurrentPassport passport(ChannelHandlerContext ctx) {
return CurrentPassport.fromChannel(ctx.channel());
}
public static final class InboundHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
passport(ctx).add(PassportState.ORIGIN_CH_ACTIVE);
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
passport(ctx).add(PassportState.ORIGIN_CH_INACTIVE);
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
passport(ctx).add(PassportState.ORIGIN_CH_EXCEPTION);
super.exceptionCaught(ctx, cause);
}
}
public static final class OutboundHandler extends ChannelOutboundHandlerAdapter {
@Override
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
passport(ctx).add(PassportState.ORIGIN_CH_DISCONNECT);
super.disconnect(ctx, promise);
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
passport(ctx).add(PassportState.ORIGIN_CH_CLOSE);
super.close(ctx, promise);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
passport(ctx).add(PassportState.ORIGIN_CH_EXCEPTION);
super.exceptionCaught(ctx, cause);
}
@Override
public void connect(
ChannelHandlerContext ctx,
SocketAddress remoteAddress,
SocketAddress localAddress,
ChannelPromise promise)
throws Exception {
// We would prefer to set this passport state here, but if we do then it will be run _after_ the http
// request
// has actually been written to the channel. Because another listener is added before this one.
// So instead we have to add this listener in the PerServerConnectionPool.handleConnectCompletion() method
// instead.
// passport.add(PassportState.ORIGIN_CH_CONNECTING);
// promise.addListener(new PassportStateListener(passport, PassportState.ORIGIN_CH_CONNECTED));
super.connect(ctx, remoteAddress, localAddress, promise);
}
}
}
| 6,333 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateHttpClientHandler.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.netty.insights;
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.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.handler.codec.http.LastHttpContent;
/**
* User: Mike Smith
* Date: 9/24/16
* Time: 2:41 PM
*/
public final class PassportStateHttpClientHandler {
private static CurrentPassport passport(ChannelHandlerContext ctx) {
return CurrentPassport.fromChannel(ctx.channel());
}
public static final class InboundHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
CurrentPassport passport = passport(ctx);
if (msg instanceof HttpResponse) {
passport.add(PassportState.IN_RESP_HEADERS_RECEIVED);
}
if (msg instanceof LastHttpContent) {
passport.add(PassportState.IN_RESP_LAST_CONTENT_RECEIVED);
} else if (msg instanceof HttpContent) {
passport.add(PassportState.IN_RESP_CONTENT_RECEIVED);
}
} finally {
super.channelRead(ctx, msg);
}
}
}
public static final class OutboundHandler extends ChannelOutboundHandlerAdapter {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
try {
CurrentPassport passport = passport(ctx);
if (msg instanceof HttpRequest) {
passport.add(PassportState.OUT_REQ_HEADERS_SENDING);
promise.addListener(new PassportStateListener(
passport, PassportState.OUT_REQ_HEADERS_SENT, PassportState.OUT_REQ_HEADERS_ERROR_SENDING));
}
if (msg instanceof LastHttpContent) {
passport.add(PassportState.OUT_REQ_LAST_CONTENT_SENDING);
promise.addListener(new PassportStateListener(
passport,
PassportState.OUT_REQ_LAST_CONTENT_SENT,
PassportState.OUT_REQ_LAST_CONTENT_ERROR_SENDING));
} else if (msg instanceof HttpContent) {
passport.add(PassportState.OUT_REQ_CONTENT_SENDING);
promise.addListener(new PassportStateListener(
passport, PassportState.OUT_REQ_CONTENT_SENT, PassportState.OUT_REQ_CONTENT_ERROR_SENDING));
}
} finally {
super.write(ctx, msg, promise);
}
}
}
}
| 6,334 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportLoggingHandler.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.netty.insights;
import com.netflix.config.CachedDynamicLongProperty;
import com.netflix.netty.common.HttpLifecycleChannelHandler;
import com.netflix.netty.common.metrics.HttpMetricsChannelHandler;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import com.netflix.zuul.context.SessionContext;
import com.netflix.zuul.message.http.HttpRequestMessage;
import com.netflix.zuul.message.http.HttpResponseMessage;
import com.netflix.zuul.monitoring.ConnCounter;
import com.netflix.zuul.netty.ChannelUtils;
import com.netflix.zuul.netty.server.ClientRequestReceiver;
import com.netflix.zuul.niws.RequestAttempts;
import com.netflix.zuul.passport.CurrentPassport;
import com.netflix.zuul.passport.PassportState;
import com.netflix.zuul.passport.StartAndEnd;
import com.netflix.zuul.stats.status.StatusCategoryUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* User: michaels@netflix.com
* Date: 2/28/17
* Time: 5:41 PM
*/
@ChannelHandler.Sharable
public class PassportLoggingHandler extends ChannelInboundHandlerAdapter {
private static final Logger LOG = LoggerFactory.getLogger(PassportLoggingHandler.class);
private static final CachedDynamicLongProperty WARN_REQ_PROCESSING_TIME_NS =
new CachedDynamicLongProperty("zuul.passport.log.request.time.threshold", 1000 * 1000 * 1000); // 1000 ms
private static final CachedDynamicLongProperty WARN_RESP_PROCESSING_TIME_NS =
new CachedDynamicLongProperty("zuul.passport.log.response.time.threshold", 1000 * 1000 * 1000); // 1000 ms
private final Counter incompleteProxySessionCounter;
public PassportLoggingHandler(Registry spectatorRegistry) {
incompleteProxySessionCounter = spectatorRegistry.counter("server.http.session.incomplete");
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
try {
super.userEventTriggered(ctx, evt);
} finally {
if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent) {
try {
logPassport(ctx.channel());
} catch (Exception e) {
LOG.error("Error logging passport info after request completed!", e);
}
}
}
}
private void logPassport(Channel channel) {
// Collect attributes.
CurrentPassport passport = CurrentPassport.fromChannel(channel);
HttpRequestMessage request = ClientRequestReceiver.getRequestFromChannel(channel);
HttpResponseMessage response = ClientRequestReceiver.getResponseFromChannel(channel);
SessionContext ctx = request == null ? null : request.getContext();
String topLevelRequestId = getRequestId(channel, ctx);
// Do some debug logging of the Passport.
if (LOG.isDebugEnabled()) {
LOG.debug(
"State after complete. , current-server-conns = {}, current-http-reqs = {}, status = {}, nfstatus = {}, toplevelid = {}, req = {}, passport = {}",
ConnCounter.from(channel).getCurrentActiveConns(),
HttpMetricsChannelHandler.getInflightRequestCountFromChannel(channel),
(response == null ? getRequestId(channel, ctx) : response.getStatus()),
String.valueOf(StatusCategoryUtils.getStatusCategory(ctx)),
topLevelRequestId,
request.getInfoForLogging(),
String.valueOf(passport));
}
// Some logging of session states if certain criteria match:
if (LOG.isInfoEnabled()) {
if (passport.wasProxyAttempt()) {
if (passport.findStateBackwards(PassportState.OUT_RESP_LAST_CONTENT_SENDING) == null) {
incompleteProxySessionCounter.increment();
LOG.info(
"Incorrect final state! toplevelid = {}, {}",
topLevelRequestId,
ChannelUtils.channelInfoForLogging(channel));
}
}
if (!passport.wasProxyAttempt()) {
if (ctx != null && !isHealthcheckRequest(request)) {
// Why did we fail to attempt to proxy this request?
RequestAttempts attempts = RequestAttempts.getFromSessionContext(ctx);
LOG.debug(
"State after complete. , context-error = {}, current-http-reqs = {}, toplevelid = {}, req = {}, attempts = {}, passport = {}",
String.valueOf(ctx.getError()),
HttpMetricsChannelHandler.getInflightRequestCountFromChannel(channel),
topLevelRequestId,
request.getInfoForLogging(),
String.valueOf(attempts),
String.valueOf(passport));
}
}
StartAndEnd inReqToOutResp = passport.findFirstStartAndLastEndStates(
PassportState.IN_REQ_HEADERS_RECEIVED, PassportState.OUT_REQ_LAST_CONTENT_SENT);
if (passport.calculateTimeBetween(inReqToOutResp) > WARN_REQ_PROCESSING_TIME_NS.get()) {
LOG.info(
"Request processing took longer than threshold! toplevelid = {}, {}",
topLevelRequestId,
ChannelUtils.channelInfoForLogging(channel));
}
StartAndEnd inRespToOutResp = passport.findLastStartAndFirstEndStates(
PassportState.IN_RESP_HEADERS_RECEIVED, PassportState.OUT_RESP_LAST_CONTENT_SENT);
if (passport.calculateTimeBetween(inRespToOutResp) > WARN_RESP_PROCESSING_TIME_NS.get()) {
LOG.info(
"Response processing took longer than threshold! toplevelid = {}, {}",
topLevelRequestId,
ChannelUtils.channelInfoForLogging(channel));
}
}
}
protected boolean isHealthcheckRequest(HttpRequestMessage req) {
return req.getPath().equals("/healthcheck");
}
protected String getRequestId(Channel channel, SessionContext ctx) {
return ctx == null ? "-" : ctx.getUUID();
}
}
| 6,335 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/insights/PassportStateHttpServerHandler.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.netty.insights;
import com.netflix.netty.common.HttpLifecycleChannelHandler;
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.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.handler.codec.http.LastHttpContent;
/**
* User: Mike Smith
* Date: 9/24/16
* Time: 2:41 PM
*/
public final class PassportStateHttpServerHandler {
private static CurrentPassport passport(ChannelHandlerContext ctx) {
return CurrentPassport.fromChannel(ctx.channel());
}
public static final class InboundHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// Get existing passport or create new if none already.
CurrentPassport passport = passport(ctx);
if (msg instanceof HttpRequest) {
// If the current passport for this channel already contains an inbound http request, then
// we know it's used, so discard and create a new one.
// NOTE: we do this because we want to include the initial conn estab + ssl handshake into the passport
// of the 1st request on a channel, but not on subsequent requests.
if (passport.findState(PassportState.IN_REQ_HEADERS_RECEIVED) != null) {
passport = CurrentPassport.createForChannel(ctx.channel());
}
passport.add(PassportState.IN_REQ_HEADERS_RECEIVED);
}
if (msg instanceof LastHttpContent) {
passport.add(PassportState.IN_REQ_LAST_CONTENT_RECEIVED);
} else if (msg instanceof HttpContent) {
passport.add(PassportState.IN_REQ_CONTENT_RECEIVED);
}
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) {
CurrentPassport.clearFromChannel(ctx.channel());
}
}
}
}
public static final class OutboundHandler extends ChannelOutboundHandlerAdapter {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
CurrentPassport passport = passport(ctx);
// Set into the SENDING state.
if (msg instanceof HttpResponse) {
passport.add(PassportState.OUT_RESP_HEADERS_SENDING);
promise.addListener(new PassportStateListener(
passport, PassportState.OUT_RESP_HEADERS_SENT, PassportState.OUT_RESP_HEADERS_ERROR_SENDING));
}
if (msg instanceof LastHttpContent) {
passport.add(PassportState.OUT_RESP_LAST_CONTENT_SENDING);
promise.addListener(new PassportStateListener(
passport,
PassportState.OUT_RESP_LAST_CONTENT_SENT,
PassportState.OUT_RESP_LAST_CONTENT_ERROR_SENDING));
} else if (msg instanceof HttpContent) {
passport.add(PassportState.OUT_RESP_CONTENT_SENDING);
promise.addListener(new PassportStateListener(
passport, PassportState.OUT_RESP_CONTENT_SENT, PassportState.OUT_RESP_CONTENT_ERROR_SENDING));
}
// Continue with the write.
super.write(ctx, msg, promise);
}
}
}
| 6,336 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/insights/ServerStateHandler.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.netty.insights;
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.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.unix.Errors;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* User: Mike Smith Date: 9/24/16 Time: 2:41 PM
*/
public final class ServerStateHandler {
private static final Logger logger = LoggerFactory.getLogger(ServerStateHandler.class);
private static CurrentPassport passport(ChannelHandlerContext ctx) {
return CurrentPassport.fromChannel(ctx.channel());
}
public static final class InboundHandler extends ChannelInboundHandlerAdapter {
private final Registry registry;
private final Counter totalConnections;
private final Counter connectionClosed;
private final Counter connectionErrors;
public InboundHandler(Registry registry, String metricId) {
this.registry = registry;
this.totalConnections = registry.counter("server.connections.connect", "id", metricId);
this.connectionClosed = registry.counter("server.connections.close", "id", metricId);
this.connectionErrors = registry.counter("server.connections.errors", "id", metricId);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
totalConnections.increment();
passport(ctx).add(PassportState.SERVER_CH_ACTIVE);
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
connectionClosed.increment();
passport(ctx).add(PassportState.SERVER_CH_INACTIVE);
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
connectionErrors.increment();
registry.counter(
"server.connection.exception.inbound",
"handler",
"ServerStateHandler.InboundHandler",
"id",
cause.getClass().getSimpleName())
.increment();
passport(ctx).add(PassportState.SERVER_CH_EXCEPTION);
logger.info("Connection error on Inbound: {} ", cause);
super.exceptionCaught(ctx, cause);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
final CurrentPassport passport = CurrentPassport.fromChannel(ctx.channel());
if (passport != null) {
passport.add(PassportState.SERVER_CH_IDLE_TIMEOUT);
}
}
super.userEventTriggered(ctx, evt);
}
}
public static final class OutboundHandler extends ChannelOutboundHandlerAdapter {
private final Registry registry;
public OutboundHandler(Registry registry) {
this.registry = registry;
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
passport(ctx).add(PassportState.SERVER_CH_CLOSE);
super.close(ctx, promise);
}
@Override
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
passport(ctx).add(PassportState.SERVER_CH_DISCONNECT);
super.disconnect(ctx, promise);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
passport(ctx).add(PassportState.SERVER_CH_EXCEPTION);
if (cause instanceof Errors.NativeIoException) {
logger.debug("PassportStateServerHandler Outbound NativeIoException {}", cause);
registry.counter(
"server.connection.exception.outbound",
"handler",
"ServerStateHandler.OutboundHandler",
"id",
cause.getClass().getSimpleName())
.increment();
} else {
super.exceptionCaught(ctx, cause);
}
}
}
}
| 6,337 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/ssl/SslContextFactory.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.netty.ssl;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import java.security.NoSuchAlgorithmException;
import java.util.List;
/**
* User: michaels@netflix.com
* Date: 11/8/16
* Time: 1:01 PM
*/
public interface SslContextFactory {
SslContextBuilder createBuilderForServer();
String[] getProtocols();
List<String> getCiphers() throws NoSuchAlgorithmException;
void enableSessionTickets(SslContext sslContext);
void configureOpenSslStatsMetrics(SslContext sslContext, String sslContextId);
}
| 6,338 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/ssl/ClientSslContextFactory.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.netty.ssl;
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.netty.common.ssl.ServerSslConfig;
import com.netflix.spectator.api.Registry;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Client Ssl Context Factory
*
* Author: Arthur Gonigberg
* Date: May 14, 2018
*/
public final class ClientSslContextFactory extends BaseSslContextFactory {
private static final DynamicBooleanProperty ENABLE_CLIENT_TLS13 =
new DynamicBooleanProperty("com.netflix.zuul.netty.ssl.enable_tls13", false);
private static final Logger log = LoggerFactory.getLogger(ClientSslContextFactory.class);
private static final ServerSslConfig DEFAULT_CONFIG = new ServerSslConfig(
maybeAddTls13(ENABLE_CLIENT_TLS13.get(), "TLSv1.2"), ServerSslConfig.getDefaultCiphers(), null, null);
public ClientSslContextFactory(Registry spectatorRegistry) {
super(spectatorRegistry, DEFAULT_CONFIG);
}
public ClientSslContextFactory(Registry spectatorRegistry, ServerSslConfig serverSslConfig) {
super(spectatorRegistry, serverSslConfig);
}
public SslContext getClientSslContext() {
try {
return SslContextBuilder.forClient()
.sslProvider(chooseSslProvider())
.ciphers(getCiphers(), getCiphersFilter())
.protocols(getProtocols())
.build();
} catch (Exception e) {
log.error("Error loading SslContext client request.", e);
throw new RuntimeException("Error configuring SslContext for client request!", e);
}
}
static String[] maybeAddTls13(boolean enableTls13, String... defaultProtocols) {
if (enableTls13) {
String[] protocols = new String[defaultProtocols.length + 1];
System.arraycopy(defaultProtocols, 0, protocols, 1, defaultProtocols.length);
protocols[0] = "TLSv1.3";
return protocols;
} else {
return defaultProtocols;
}
}
}
| 6,339 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/ssl/BaseSslContextFactory.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.netty.ssl;
import com.google.errorprone.annotations.ForOverride;
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.netty.common.ssl.ServerSslConfig;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.patterns.PolledMeter;
import io.netty.handler.ssl.CipherSuiteFilter;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.OpenSsl;
import io.netty.handler.ssl.OpenSslSessionStats;
import io.netty.handler.ssl.ReferenceCountedOpenSslContext;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslProvider;
import io.netty.handler.ssl.SupportedCipherSuiteFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import java.util.function.ToDoubleFunction;
/**
* User: michaels@netflix.com
* Date: 3/4/16
* Time: 4:00 PM
*/
public class BaseSslContextFactory implements SslContextFactory {
private static final Logger LOG = LoggerFactory.getLogger(BaseSslContextFactory.class);
private static final DynamicBooleanProperty ALLOW_USE_OPENSSL =
new DynamicBooleanProperty("zuul.ssl.openssl.allow", true);
static {
// Install BouncyCastle provider.
java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
protected final Registry spectatorRegistry;
protected final ServerSslConfig serverSslConfig;
public BaseSslContextFactory(Registry spectatorRegistry, ServerSslConfig serverSslConfig) {
this.spectatorRegistry = Objects.requireNonNull(spectatorRegistry);
this.serverSslConfig = Objects.requireNonNull(serverSslConfig);
}
@Override
public SslContextBuilder createBuilderForServer() {
try {
ArrayList<X509Certificate> trustedCerts = getTrustedX509Certificates();
SslProvider sslProvider = chooseSslProvider();
LOG.debug("Using SslProvider of type {}", sslProvider.name());
SslContextBuilder builder = newBuilderForServer()
.ciphers(getCiphers(), getCiphersFilter())
.sessionTimeout(serverSslConfig.getSessionTimeout())
.sslProvider(sslProvider);
if (serverSslConfig.getClientAuth() != null && trustedCerts != null && !trustedCerts.isEmpty()) {
builder = builder.trustManager(trustedCerts.toArray(new X509Certificate[0]))
.clientAuth(serverSslConfig.getClientAuth());
}
return builder;
} catch (Exception e) {
throw new RuntimeException("Error configuring SslContext!", e);
}
}
/**
* This function is meant to call the correct overload of {@code SslContextBuilder.forServer()}. It should not
* apply any other customization.
*/
@ForOverride
protected SslContextBuilder newBuilderForServer() throws IOException {
LOG.debug("Using certChainFile {}", serverSslConfig.getCertChainFile());
try (InputStream keyInput = getKeyInputStream();
InputStream certChainInput = new FileInputStream(serverSslConfig.getCertChainFile())) {
return SslContextBuilder.forServer(certChainInput, keyInput);
}
}
@Override
public void enableSessionTickets(SslContext sslContext) {
// TODO
}
@Override
public void configureOpenSslStatsMetrics(SslContext sslContext, String sslContextId) {
// Setup metrics tracking the OpenSSL stats.
if (sslContext instanceof ReferenceCountedOpenSslContext) {
OpenSslSessionStats stats = ((ReferenceCountedOpenSslContext) sslContext)
.sessionContext()
.stats();
openSslStatGauge(stats, sslContextId, "accept", OpenSslSessionStats::accept);
openSslStatGauge(stats, sslContextId, "accept_good", OpenSslSessionStats::acceptGood);
openSslStatGauge(stats, sslContextId, "accept_renegotiate", OpenSslSessionStats::acceptRenegotiate);
openSslStatGauge(stats, sslContextId, "number", OpenSslSessionStats::number);
openSslStatGauge(stats, sslContextId, "connect", OpenSslSessionStats::connect);
openSslStatGauge(stats, sslContextId, "connect_good", OpenSslSessionStats::connectGood);
openSslStatGauge(stats, sslContextId, "connect_renegotiate", OpenSslSessionStats::connectRenegotiate);
openSslStatGauge(stats, sslContextId, "hits", OpenSslSessionStats::hits);
openSslStatGauge(stats, sslContextId, "cb_hits", OpenSslSessionStats::cbHits);
openSslStatGauge(stats, sslContextId, "misses", OpenSslSessionStats::misses);
openSslStatGauge(stats, sslContextId, "timeouts", OpenSslSessionStats::timeouts);
openSslStatGauge(stats, sslContextId, "cache_full", OpenSslSessionStats::cacheFull);
openSslStatGauge(stats, sslContextId, "ticket_key_fail", OpenSslSessionStats::ticketKeyFail);
openSslStatGauge(stats, sslContextId, "ticket_key_new", OpenSslSessionStats::ticketKeyNew);
openSslStatGauge(stats, sslContextId, "ticket_key_renew", OpenSslSessionStats::ticketKeyRenew);
openSslStatGauge(stats, sslContextId, "ticket_key_resume", OpenSslSessionStats::ticketKeyResume);
}
}
private void openSslStatGauge(
OpenSslSessionStats stats,
String sslContextId,
String statName,
ToDoubleFunction<OpenSslSessionStats> value) {
Id id = spectatorRegistry.createId("server.ssl.stats", "id", sslContextId, "stat", statName);
PolledMeter.using(spectatorRegistry).withId(id).monitorValue(stats, value);
LOG.debug("Registered spectator gauge - {}", id.name());
}
public static SslProvider chooseSslProvider() {
// Use openssl only if available and has ALPN support (ie. version > 1.0.2).
SslProvider sslProvider;
if (ALLOW_USE_OPENSSL.get() && OpenSsl.isAvailable() && SslProvider.isAlpnSupported(SslProvider.OPENSSL)) {
sslProvider = SslProvider.OPENSSL;
} else {
sslProvider = SslProvider.JDK;
}
return sslProvider;
}
public ServerSslConfig getServerSslConfig() {
return serverSslConfig;
}
@Override
public String[] getProtocols() {
return serverSslConfig.getProtocols();
}
@Override
public List<String> getCiphers() throws NoSuchAlgorithmException {
return serverSslConfig.getCiphers();
}
protected CipherSuiteFilter getCiphersFilter() {
return SupportedCipherSuiteFilter.INSTANCE;
}
protected ArrayList<X509Certificate> getTrustedX509Certificates()
throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException {
ArrayList<X509Certificate> trustedCerts = new ArrayList<>();
// Add the certificates from the JKS truststore - ie. the CA's of the client cert that peer Zuul's will use.
if (serverSslConfig.getClientAuth() == ClientAuth.REQUIRE
|| serverSslConfig.getClientAuth() == ClientAuth.OPTIONAL) {
// Get the encrypted bytes of the truststore password.
byte[] trustStorePwdBytes;
if (serverSslConfig.getClientAuthTrustStorePassword() != null) {
trustStorePwdBytes = Base64.getDecoder().decode(serverSslConfig.getClientAuthTrustStorePassword());
} else if (serverSslConfig.getClientAuthTrustStorePasswordFile() != null) {
trustStorePwdBytes = Files.readAllBytes(
serverSslConfig.getClientAuthTrustStorePasswordFile().toPath());
} else {
throw new IllegalArgumentException(
"Must specify either ClientAuthTrustStorePassword or ClientAuthTrustStorePasswordFile!");
}
// Decrypt the truststore password.
String trustStorePassword = getTruststorePassword(trustStorePwdBytes);
boolean dumpDecryptedTrustStorePassword = false;
if (dumpDecryptedTrustStorePassword) {
LOG.debug("X509Cert Trust Store Password {}", trustStorePassword);
}
final KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(
new FileInputStream(serverSslConfig.getClientAuthTrustStoreFile()),
trustStorePassword.toCharArray());
Enumeration<String> aliases = trustStore.aliases();
while (aliases.hasMoreElements()) {
X509Certificate cert = (X509Certificate) trustStore.getCertificate(aliases.nextElement());
trustedCerts.add(cert);
}
}
return trustedCerts;
}
/**
* Can be overridden to implement your own decryption scheme.
*
*/
protected String getTruststorePassword(byte[] trustStorePwdBytes) {
return new String(trustStorePwdBytes).trim();
}
/**
* Can be overridden to implement your own decryption scheme.
*/
protected InputStream getKeyInputStream() throws IOException {
return new FileInputStream(serverSslConfig.getKeyFile());
}
}
| 6,340 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/timeouts/OriginTimeoutManager.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.netty.timeouts;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.client.config.IClientConfig;
import com.netflix.config.DynamicLongProperty;
import com.netflix.zuul.context.CommonContextKeys;
import com.netflix.zuul.message.http.HttpRequestMessage;
import com.netflix.zuul.origins.NettyOrigin;
import javax.annotation.Nullable;
import java.time.Duration;
import java.util.Objects;
import java.util.Optional;
/**
* Origin Timeout Manager
*
* @author Arthur Gonigberg
* @since February 24, 2021
*/
public class OriginTimeoutManager {
private final NettyOrigin origin;
public OriginTimeoutManager(NettyOrigin origin) {
this.origin = Objects.requireNonNull(origin);
}
@VisibleForTesting
static final DynamicLongProperty MAX_OUTBOUND_READ_TIMEOUT_MS = new DynamicLongProperty(
"zuul.origin.readtimeout.max", Duration.ofSeconds(90).toMillis());
/**
* Derives the read timeout from the configuration. This implementation prefers the longer of either the origin
* timeout or the request timeout.
* <p>
* This method can also be used to validate timeout and deadline boundaries and throw exceptions as needed. If
* extending this method to do validation, you should extend {@link com.netflix.zuul.exception.OutboundException}
* and set the appropriate {@link com.netflix.zuul.exception.ErrorType}.
*
* @param request the request.
* @param attemptNum the attempt number, starting at 1.
*/
public Duration computeReadTimeout(HttpRequestMessage request, int attemptNum) {
IClientConfig clientConfig = getRequestClientConfig(request);
Long originTimeout = getOriginReadTimeout();
Long requestTimeout = getRequestReadTimeout(clientConfig);
long computedTimeout;
if (originTimeout == null && requestTimeout == null) {
computedTimeout = MAX_OUTBOUND_READ_TIMEOUT_MS.get();
} else if (originTimeout == null || requestTimeout == null) {
computedTimeout = originTimeout == null ? requestTimeout : originTimeout;
} else {
// return the stricter (i.e. lower) of the two timeouts
computedTimeout = Math.min(originTimeout, requestTimeout);
}
// enforce max timeout upperbound
return Duration.ofMillis(Math.min(computedTimeout, MAX_OUTBOUND_READ_TIMEOUT_MS.get()));
}
/**
* This method will create a new client config or retrieve the existing one from the current request.
*
* @param zuulRequest - the request
* @return the config
*/
protected IClientConfig getRequestClientConfig(HttpRequestMessage zuulRequest) {
IClientConfig overriddenClientConfig = zuulRequest.getContext().get(CommonContextKeys.REST_CLIENT_CONFIG);
if (overriddenClientConfig == null) {
overriddenClientConfig = new DefaultClientConfigImpl();
zuulRequest.getContext().put(CommonContextKeys.REST_CLIENT_CONFIG, overriddenClientConfig);
}
return overriddenClientConfig;
}
/**
* This method makes the assumption that the timeout is a numeric value
*/
@Nullable
private Long getRequestReadTimeout(IClientConfig clientConfig) {
return Optional.ofNullable(clientConfig.get(CommonClientConfigKey.ReadTimeout))
.map(Long::valueOf)
.orElse(null);
}
/**
* This method makes the assumption that the timeout is a numeric value
*/
@Nullable
private Long getOriginReadTimeout() {
return Optional.ofNullable(origin.getClientConfig().get(CommonClientConfigKey.ReadTimeout))
.map(Long::valueOf)
.orElse(null);
}
}
| 6,341 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/OriginResponseReceiver.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.netty.server;
import com.netflix.zuul.exception.OutboundErrorType;
import com.netflix.zuul.exception.OutboundException;
import com.netflix.zuul.exception.ZuulException;
import com.netflix.zuul.filters.endpoint.ProxyEndpoint;
import com.netflix.zuul.message.Header;
import com.netflix.zuul.message.http.HttpQueryParams;
import com.netflix.zuul.message.http.HttpRequestMessage;
import com.netflix.zuul.netty.ChannelUtils;
import com.netflix.zuul.netty.connectionpool.OriginConnectException;
import com.netflix.zuul.passport.PassportState;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.ssl.SslHandshakeCompletionEvent;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.ReadTimeoutException;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import io.perfmark.PerfMark;
import io.perfmark.TaskCloseable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent;
import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason;
/**
* Created by saroskar on 1/18/17.
*/
public class OriginResponseReceiver extends ChannelDuplexHandler {
private volatile ProxyEndpoint edgeProxy;
private static final Logger logger = LoggerFactory.getLogger(OriginResponseReceiver.class);
private static final AttributeKey<Throwable> SSL_HANDSHAKE_UNSUCCESS_FROM_ORIGIN_THROWABLE =
AttributeKey.newInstance("_ssl_handshake_from_origin_throwable");
public static final String CHANNEL_HANDLER_NAME = "_origin_response_receiver";
public OriginResponseReceiver(final ProxyEndpoint edgeProxy) {
this.edgeProxy = edgeProxy;
}
public void unlinkFromClientRequest() {
edgeProxy = null;
}
@Override
public final void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
try (TaskCloseable a = PerfMark.traceTask("ORR.channelRead")) {
channelReadInternal(ctx, msg);
}
}
private void channelReadInternal(final ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpResponse) {
if (edgeProxy != null) {
edgeProxy.responseFromOrigin((HttpResponse) msg);
} else if (ReferenceCountUtil.refCnt(msg) > 0) {
// this handles the case of a DefaultFullHttpResponse that could have content that needs to be released
ReferenceCountUtil.safeRelease(msg);
}
ctx.channel().read();
} else if (msg instanceof HttpContent) {
final HttpContent chunk = (HttpContent) msg;
if (edgeProxy != null) {
edgeProxy.invokeNext(chunk);
} else {
ReferenceCountUtil.safeRelease(chunk);
}
ctx.channel().read();
} else {
// should never happen
ReferenceCountUtil.release(msg);
final Exception error = new IllegalStateException("Received invalid message from origin");
if (edgeProxy != null) {
edgeProxy.errorFromOrigin(error);
}
ctx.fireExceptionCaught(error);
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof CompleteEvent) {
final CompleteReason reason = ((CompleteEvent) evt).getReason();
if ((reason != CompleteReason.SESSION_COMPLETE) && (edgeProxy != null)) {
logger.error(
"Origin request completed with reason other than COMPLETE: {}, {}",
reason.name(),
ChannelUtils.channelInfoForLogging(ctx.channel()));
final ZuulException ze = new ZuulException("CompleteEvent", reason.name(), true);
edgeProxy.errorFromOrigin(ze);
}
// First let this event propagate along the pipeline, before cleaning vars from the channel.
// See channelWrite() where these vars are first set onto the channel.
try {
super.userEventTriggered(ctx, evt);
} finally {
postCompleteHook(ctx, evt);
}
} else if (evt instanceof SslHandshakeCompletionEvent && !((SslHandshakeCompletionEvent) evt).isSuccess()) {
Throwable cause = ((SslHandshakeCompletionEvent) evt).cause();
ctx.channel().attr(SSL_HANDSHAKE_UNSUCCESS_FROM_ORIGIN_THROWABLE).set(cause);
} else if (evt instanceof IdleStateEvent) {
if (edgeProxy != null) {
logger.error(
"Origin request received IDLE event: {}", ChannelUtils.channelInfoForLogging(ctx.channel()));
edgeProxy.errorFromOrigin(
new OutboundException(OutboundErrorType.READ_TIMEOUT, edgeProxy.getRequestAttempts()));
}
super.userEventTriggered(ctx, evt);
} else {
super.userEventTriggered(ctx, evt);
}
}
/**
* Override to add custom post complete functionality
*
* @param ctx - channel handler context
* @param evt - netty event
* @throws Exception
*/
protected void postCompleteHook(ChannelHandlerContext ctx, Object evt) throws Exception {}
private HttpRequest buildOriginHttpRequest(final HttpRequestMessage zuulRequest) {
final String method = zuulRequest.getMethod().toUpperCase();
final String uri = pathAndQueryString(zuulRequest);
customRequestProcessing(zuulRequest);
final DefaultHttpRequest nettyReq =
new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method), uri, false);
// Copy headers across.
for (final Header h : zuulRequest.getHeaders().entries()) {
nettyReq.headers().add(h.getKey(), h.getValue());
}
return nettyReq;
}
/**
* Override to add custom modifications to the request before it goes out
*
* @param headers
*/
protected void customRequestProcessing(HttpRequestMessage headers) {}
private static String pathAndQueryString(HttpRequestMessage request) {
// parsing the params cleans up any empty/null params using the logic of the HttpQueryParams class
final HttpQueryParams cleanParams =
HttpQueryParams.parse(request.getQueryParams().toEncodedString());
final String cleanQueryStr = cleanParams.toEncodedString();
if (cleanQueryStr == null || cleanQueryStr.isEmpty()) {
return request.getPath();
} else {
return request.getPath() + "?" + cleanParams.toEncodedString();
}
}
@Override
public final void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
try (TaskCloseable ignore = PerfMark.traceTask("ORR.writeInternal")) {
writeInternal(ctx, msg, promise);
}
}
private void writeInternal(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (!ctx.channel().isActive()) {
ReferenceCountUtil.release(msg);
return;
}
if (msg instanceof HttpRequestMessage) {
promise.addListener((future) -> {
if (!future.isSuccess()) {
Throwable cause = ctx.channel()
.attr(SSL_HANDSHAKE_UNSUCCESS_FROM_ORIGIN_THROWABLE)
.get();
if (cause != null) {
// Set the specific SSL handshake error if the handlers have already caught them
ctx.channel()
.attr(SSL_HANDSHAKE_UNSUCCESS_FROM_ORIGIN_THROWABLE)
.set(null);
fireWriteError("request headers", cause, ctx);
logger.debug(
"SSLException is overridden by SSLHandshakeException caught in handler level. Original SSL exception message: ",
future.cause());
} else {
fireWriteError("request headers", future.cause(), ctx);
}
}
});
HttpRequestMessage zuulReq = (HttpRequestMessage) msg;
preWriteHook(ctx, zuulReq);
super.write(ctx, buildOriginHttpRequest(zuulReq), promise);
} else if (msg instanceof HttpContent) {
promise.addListener((future) -> {
if (!future.isSuccess()) {
fireWriteError("request content chunk", future.cause(), ctx);
}
});
super.write(ctx, msg, promise);
} else {
// should never happen
ReferenceCountUtil.release(msg);
throw new ZuulException("Received invalid message from client", true);
}
}
/**
* Override to add custom pre-write functionality
*
* @param ctx channel handler context
* @param zuulReq request message to modify
*/
protected void preWriteHook(ChannelHandlerContext ctx, HttpRequestMessage zuulReq) {}
private void fireWriteError(String requestPart, Throwable cause, ChannelHandlerContext ctx) throws Exception {
String errMesg = "Error while proxying " + requestPart + " to origin ";
if (edgeProxy != null) {
final ProxyEndpoint ep = edgeProxy;
edgeProxy = null;
errMesg += ep.getOrigin().getName();
ep.errorFromOrigin(cause);
}
ctx.fireExceptionCaught(new ZuulException(cause, errMesg, true));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (edgeProxy != null) {
if (cause instanceof ReadTimeoutException) {
edgeProxy.getPassport().add(PassportState.ORIGIN_CH_READ_TIMEOUT);
logger.debug(
"read timeout on origin channel {} ", ChannelUtils.channelInfoForLogging(ctx.channel()), cause);
} else if (cause instanceof IOException) {
edgeProxy.getPassport().add(PassportState.ORIGIN_CH_IO_EX);
logger.debug(
"I/O error on origin channel {} ", ChannelUtils.channelInfoForLogging(ctx.channel()), cause);
} else {
logger.error("Error from Origin connection:", cause);
}
edgeProxy.errorFromOrigin(cause);
}
ctx.fireExceptionCaught(cause);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
if (edgeProxy != null) {
logger.debug("Origin channel inactive. channel-info={}", ChannelUtils.channelInfoForLogging(ctx.channel()));
OriginConnectException ex =
new OriginConnectException("Origin server inactive", OutboundErrorType.RESET_CONNECTION);
edgeProxy.errorFromOrigin(ex);
}
super.channelInactive(ctx);
ctx.close();
}
}
| 6,342 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/ClientRequestReceiver.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.netty.server;
import com.netflix.netty.common.SourceAddressChannelHandler;
import com.netflix.netty.common.ssl.SslHandshakeInfo;
import com.netflix.netty.common.throttle.RejectionUtils;
import com.netflix.spectator.api.Spectator;
import com.netflix.zuul.context.CommonContextKeys;
import com.netflix.zuul.context.Debug;
import com.netflix.zuul.context.SessionContext;
import com.netflix.zuul.context.SessionContextDecorator;
import com.netflix.zuul.exception.ZuulException;
import com.netflix.zuul.message.Headers;
import com.netflix.zuul.message.http.HttpQueryParams;
import com.netflix.zuul.message.http.HttpRequestMessage;
import com.netflix.zuul.message.http.HttpRequestMessageImpl;
import com.netflix.zuul.message.http.HttpResponseMessage;
import com.netflix.zuul.netty.ChannelUtils;
import com.netflix.zuul.netty.server.http2.Http2OrHttpHandler;
import com.netflix.zuul.netty.server.ssl.SslHandshakeInfoHandler;
import com.netflix.zuul.passport.CurrentPassport;
import com.netflix.zuul.passport.PassportState;
import com.netflix.zuul.stats.status.StatusCategoryUtils;
import com.netflix.zuul.stats.status.ZuulStatusCategory;
import com.netflix.zuul.util.HttpUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.unix.Errors;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
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.HttpHeaderNames;
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.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2Exception;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import io.perfmark.PerfMark;
import io.perfmark.TaskCloseable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent;
import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason;
/**
* Created by saroskar on 1/6/17.
*/
public class ClientRequestReceiver extends ChannelDuplexHandler {
public static final AttributeKey<HttpRequestMessage> ATTR_ZUUL_REQ = AttributeKey.newInstance("_zuul_request");
public static final AttributeKey<HttpResponseMessage> ATTR_ZUUL_RESP = AttributeKey.newInstance("_zuul_response");
public static final AttributeKey<Boolean> ATTR_LAST_CONTENT_RECEIVED =
AttributeKey.newInstance("_last_content_received");
private static final Logger LOG = LoggerFactory.getLogger(ClientRequestReceiver.class);
private static final String SCHEME_HTTP = "http";
private static final String SCHEME_HTTPS = "https";
// via @stephenhay https://mathiasbynens.be/demo/url-regex, groups added
// group 1: scheme, group 2: domain, group 3: path+query
private static final Pattern URL_REGEX = Pattern.compile("^(https?)://([^\\s/$.?#].[^\\s/]*)([^\\s]*)$");
private final SessionContextDecorator decorator;
private HttpRequestMessage zuulRequest;
private HttpRequest clientRequest;
public ClientRequestReceiver(SessionContextDecorator decorator) {
this.decorator = decorator;
}
public static HttpRequestMessage getRequestFromChannel(Channel ch) {
return ch.attr(ATTR_ZUUL_REQ).get();
}
public static HttpResponseMessage getResponseFromChannel(Channel ch) {
return ch.attr(ATTR_ZUUL_RESP).get();
}
public static boolean isLastContentReceivedForChannel(Channel ch) {
Boolean value = ch.attr(ATTR_LAST_CONTENT_RECEIVED).get();
return value == null ? false : value;
}
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
try (TaskCloseable ignore = PerfMark.traceTask("CRR.channelRead")) {
channelReadInternal(ctx, msg);
}
}
private void channelReadInternal(final ChannelHandlerContext ctx, Object msg) throws Exception {
// Flag that we have now received the LastContent for this request from the client.
// This is needed for ClientResponseReceiver to know whether it's yet safe to start writing
// a response to the client channel.
if (msg instanceof LastHttpContent) {
ctx.channel().attr(ATTR_LAST_CONTENT_RECEIVED).set(Boolean.TRUE);
}
if (msg instanceof HttpRequest) {
clientRequest = (HttpRequest) msg;
zuulRequest = buildZuulHttpRequest(clientRequest, ctx);
// Handle invalid HTTP requests.
if (clientRequest.decoderResult().isFailure()) {
LOG.warn(
"Invalid http request. clientRequest = {} , uri = {}, info = {}",
clientRequest,
clientRequest.uri(),
ChannelUtils.channelInfoForLogging(ctx.channel()),
clientRequest.decoderResult().cause());
StatusCategoryUtils.setStatusCategory(
zuulRequest.getContext(),
ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST,
"Invalid request provided: Decode failure");
RejectionUtils.rejectByClosingConnection(
ctx,
ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST,
"decodefailure",
clientRequest,
/* injectedLatencyMillis= */ null);
return;
} else if (zuulRequest.hasBody() && zuulRequest.getBodyLength() > zuulRequest.getMaxBodySize()) {
String errorMsg = "Request too large. "
+ "clientRequest = " + clientRequest.toString()
+ ", uri = " + String.valueOf(clientRequest.uri())
+ ", info = " + ChannelUtils.channelInfoForLogging(ctx.channel());
final ZuulException ze = new ZuulException(errorMsg);
ze.setStatusCode(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE.code());
StatusCategoryUtils.setStatusCategory(
zuulRequest.getContext(),
ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST,
"Invalid request provided: Request body size " + zuulRequest.getBodyLength()
+ " is above limit of " + zuulRequest.getMaxBodySize());
zuulRequest.getContext().setError(ze);
zuulRequest.getContext().setShouldSendErrorResponse(true);
} else if (zuulRequest
.getHeaders()
.getAll(HttpHeaderNames.HOST.toString())
.size()
> 1) {
LOG.debug(
"Multiple Host headers. clientRequest = {} , uri = {}, info = {}",
clientRequest,
clientRequest.uri(),
ChannelUtils.channelInfoForLogging(ctx.channel()));
final ZuulException ze = new ZuulException("Multiple Host headers");
ze.setStatusCode(HttpResponseStatus.BAD_REQUEST.code());
StatusCategoryUtils.setStatusCategory(
zuulRequest.getContext(),
ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST,
"Invalid request provided: Multiple Host headers");
zuulRequest.getContext().setError(ze);
zuulRequest.getContext().setShouldSendErrorResponse(true);
}
handleExpect100Continue(ctx, clientRequest);
// Send the request down the filter pipeline
ctx.fireChannelRead(zuulRequest);
} else if (msg instanceof HttpContent) {
if ((zuulRequest != null) && (!zuulRequest.getContext().isCancelled())) {
ctx.fireChannelRead(msg);
} else {
// We already sent response for this request, these are laggard request body chunks that are still
// arriving
ReferenceCountUtil.release(msg);
}
} else if (msg instanceof HAProxyMessage) {
// do nothing, should already be handled by ElbProxyProtocolHandler
LOG.debug("Received HAProxyMessage for Proxy Protocol IP: {}", ((HAProxyMessage) msg).sourceAddress());
ReferenceCountUtil.release(msg);
} else {
LOG.debug("Received unrecognized message type. {}", msg.getClass().getName());
ReferenceCountUtil.release(msg);
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof CompleteEvent) {
final CompleteReason reason = ((CompleteEvent) evt).getReason();
if (zuulRequest != null) {
zuulRequest.getContext().cancel();
zuulRequest.disposeBufferedBody();
final CurrentPassport passport = CurrentPassport.fromSessionContext(zuulRequest.getContext());
if ((passport != null) && (passport.findState(PassportState.OUT_RESP_LAST_CONTENT_SENT) == null)) {
// Only log this state if the response does not seem to have completed normally.
passport.add(PassportState.IN_REQ_CANCELLED);
}
}
if (reason == CompleteReason.INACTIVE && zuulRequest != null) {
// Client closed connection prematurely.
StatusCategoryUtils.setStatusCategory(
zuulRequest.getContext(), ZuulStatusCategory.FAILURE_CLIENT_CANCELLED);
}
if (reason == CompleteReason.PIPELINE_REJECT && zuulRequest != null) {
StatusCategoryUtils.setStatusCategory(
zuulRequest.getContext(), ZuulStatusCategory.FAILURE_CLIENT_PIPELINE_REJECT);
}
if (reason != CompleteReason.SESSION_COMPLETE && zuulRequest != null) {
final SessionContext zuulCtx = zuulRequest.getContext();
if (clientRequest != null) {
if (LOG.isInfoEnabled()) {
// With http/2, the netty codec closes/completes the stream immediately after writing the
// lastcontent
// of response to the channel, which causes this CompleteEvent to fire before we have cleaned up
// state. But
// thats ok, so don't log in that case.
if (!"HTTP/2".equals(zuulRequest.getProtocol())) {
LOG.debug(
"Client {} request UUID {} to {} completed with reason = {}, {}",
clientRequest.method(),
zuulCtx.getUUID(),
clientRequest.uri(),
reason.name(),
ChannelUtils.channelInfoForLogging(ctx.channel()));
}
}
}
if (zuulCtx.debugRequest()) {
LOG.debug("Endpoint = {}", zuulCtx.getEndpoint());
dumpDebugInfo(Debug.getRequestDebug(zuulCtx));
dumpDebugInfo(Debug.getRoutingDebug(zuulCtx));
}
}
if (zuulRequest == null) {
Spectator.globalRegistry()
.counter("zuul.client.complete.null", "reason", String.valueOf(reason))
.increment();
}
clientRequest = null;
zuulRequest = null;
}
super.userEventTriggered(ctx, evt);
if (evt instanceof CompleteEvent) {
final Channel channel = ctx.channel();
channel.attr(ATTR_ZUUL_REQ).set(null);
channel.attr(ATTR_ZUUL_RESP).set(null);
channel.attr(ATTR_LAST_CONTENT_RECEIVED).set(null);
}
}
private static void dumpDebugInfo(final List<String> debugInfo) {
debugInfo.forEach((dbg) -> LOG.debug(dbg));
}
private void handleExpect100Continue(ChannelHandlerContext ctx, HttpRequest req) {
if (HttpUtil.is100ContinueExpected(req)) {
PerfMark.event("CRR.handleExpect100Continue");
final ChannelFuture f =
ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
f.addListener((s) -> {
if (!s.isSuccess()) {
throw new ZuulException(s.cause(), "Failed while writing 100-continue response", true);
}
});
// Remove the Expect: 100-Continue header from request as we don't want to proxy it downstream.
req.headers().remove(HttpHeaderNames.EXPECT);
zuulRequest.getHeaders().remove(HttpHeaderNames.EXPECT.toString());
}
}
// Build a ZuulMessage from the netty request.
private HttpRequestMessage buildZuulHttpRequest(
final HttpRequest nativeRequest, final ChannelHandlerContext clientCtx) {
PerfMark.attachTag("path", nativeRequest, HttpRequest::uri);
// Setup the context for this request.
final SessionContext context;
if (decorator != null) { // Optionally decorate the context.
SessionContext tempContext = new SessionContext();
// Store the netty channel in SessionContext.
tempContext.set(CommonContextKeys.NETTY_SERVER_CHANNEL_HANDLER_CONTEXT, clientCtx);
context = decorator.decorate(tempContext);
// We expect the UUID is present after decoration
PerfMark.attachTag("uuid", context, SessionContext::getUUID);
} else {
context = new SessionContext();
}
// Get the client IP (ignore XFF headers at this point, as that can be app specific).
final Channel channel = clientCtx.channel();
final String clientIp =
channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get();
// This is the only way I found to get the port of the request with netty...
final int port =
channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).get();
final String serverName = channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_ADDRESS)
.get();
final SocketAddress clientDestinationAddress =
channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).get();
final InetSocketAddress proxyProtocolDestinationAddress = channel.attr(
SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS)
.get();
if (proxyProtocolDestinationAddress != null) {
context.set(CommonContextKeys.PROXY_PROTOCOL_DESTINATION_ADDRESS, proxyProtocolDestinationAddress);
}
// Store info about the SSL handshake if applicable, and choose the http scheme.
String scheme = SCHEME_HTTP;
final SslHandshakeInfo sslHandshakeInfo =
channel.attr(SslHandshakeInfoHandler.ATTR_SSL_INFO).get();
if (sslHandshakeInfo != null) {
context.set(CommonContextKeys.SSL_HANDSHAKE_INFO, sslHandshakeInfo);
scheme = SCHEME_HTTPS;
}
// Decide if this is HTTP/1 or HTTP/2.
String protocol = channel.attr(Http2OrHttpHandler.PROTOCOL_NAME).get();
if (protocol == null) {
protocol = nativeRequest.protocolVersion().text();
}
// Strip off the query from the path.
String path = parsePath(nativeRequest.uri());
// Setup the req/resp message objects.
final HttpRequestMessage request = new HttpRequestMessageImpl(
context,
protocol,
nativeRequest.method().asciiName().toString().toLowerCase(),
path,
copyQueryParams(nativeRequest),
copyHeaders(nativeRequest),
clientIp,
scheme,
port,
serverName,
clientDestinationAddress,
false);
// Try to decide if this request 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(request) || HttpUtils.hasNonZeroContentLengthHeader(request)) {
request.setHasBody(true);
}
// Store this original request info for future reference (ie. for metrics and access logging purposes).
request.storeInboundRequest();
// Store the netty request for use later.
context.set(CommonContextKeys.NETTY_HTTP_REQUEST, nativeRequest);
// Store zuul request on netty channel for later use.
channel.attr(ATTR_ZUUL_REQ).set(request);
if (nativeRequest instanceof DefaultFullHttpRequest) {
final ByteBuf chunk = ((DefaultFullHttpRequest) nativeRequest).content();
request.bufferBodyContents(new DefaultLastHttpContent(chunk));
}
return request;
}
private String parsePath(String uri) {
String path;
// relative uri
if (uri.startsWith("/")) {
path = uri;
} else {
Matcher m = URL_REGEX.matcher(uri);
// absolute uri
if (m.matches()) {
String match = m.group(3);
if (match == null) {
// in case of no match, default to existing behavior
path = uri;
} else {
path = match;
}
}
// unknown value
else {
// in case of unknown value, default to existing behavior
path = uri;
}
}
int queryIndex = path.indexOf('?');
if (queryIndex > -1) {
return path.substring(0, queryIndex);
} else {
return path;
}
}
private static Headers copyHeaders(final HttpRequest req) {
final Headers headers = new Headers(req.headers().size());
for (Iterator<Entry<String, String>> it = req.headers().iteratorAsString(); it.hasNext(); ) {
Entry<String, String> header = it.next();
headers.add(header.getKey(), header.getValue());
}
return headers;
}
public static HttpQueryParams copyQueryParams(final HttpRequest nativeRequest) {
final String uri = nativeRequest.uri();
int queryStart = uri.indexOf('?');
final String query = queryStart == -1 ? null : uri.substring(queryStart + 1);
return HttpQueryParams.parse(query);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
try (TaskCloseable ignored = PerfMark.traceTask("CRR.write")) {
if (msg instanceof HttpResponse) {
promise.addListener((future) -> {
if (!future.isSuccess()) {
fireWriteError("response headers", future.cause(), ctx);
}
});
super.write(ctx, msg, promise);
} else if (msg instanceof HttpContent) {
promise.addListener((future) -> {
if (!future.isSuccess()) {
fireWriteError("response content", future.cause(), ctx);
}
});
super.write(ctx, msg, promise);
} else {
// should never happen
ReferenceCountUtil.release(msg);
throw new ZuulException(
"Attempt to write invalid content type to client: "
+ msg.getClass().getSimpleName(),
true);
}
}
}
private void fireWriteError(String requestPart, Throwable cause, ChannelHandlerContext ctx) throws Exception {
final String errMesg = String.format("Error writing %s to client", requestPart);
if (cause instanceof java.nio.channels.ClosedChannelException
|| cause instanceof Errors.NativeIoException
|| cause instanceof SSLException
|| (cause.getCause() != null && cause.getCause() instanceof SSLException)
|| isStreamCancelled(cause)) {
LOG.debug("{} - client connection is closed.", errMesg);
if (zuulRequest != null) {
zuulRequest.getContext().cancel();
StatusCategoryUtils.storeStatusCategoryIfNotAlreadyFailure(
zuulRequest.getContext(), ZuulStatusCategory.FAILURE_CLIENT_CANCELLED);
}
} else {
LOG.error(errMesg, cause);
ctx.fireExceptionCaught(new ZuulException(cause, errMesg, true));
}
}
private boolean isStreamCancelled(Throwable cause) {
// Detect if the stream is cancelled or closed.
// If the stream was closed before the write occured, then netty flags it with INTERNAL_ERROR code.
if (cause instanceof Http2Exception.StreamException) {
Http2Exception http2Exception = (Http2Exception) cause;
if (http2Exception.error() == Http2Error.INTERNAL_ERROR) {
return true;
}
}
return false;
}
}
| 6,343 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/Http1MutualSslChannelInitializer.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.netty.server;
import com.netflix.netty.common.channel.config.ChannelConfig;
import com.netflix.netty.common.channel.config.CommonChannelConfigKeys;
import com.netflix.zuul.netty.ssl.SslContextFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import javax.net.ssl.SSLException;
/**
* User: michaels@netflix.com
* Date: 1/31/17
* Time: 11:43 PM
*/
public class Http1MutualSslChannelInitializer extends BaseZuulChannelInitializer {
private final SslContextFactory sslContextFactory;
private final SslContext sslContext;
private final boolean isSSlFromIntermediary;
/**
* Use {@link #Http1MutualSslChannelInitializer(String, ChannelConfig, ChannelConfig, ChannelGroup)} instead.
*/
@Deprecated
public Http1MutualSslChannelInitializer(
int port, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) {
this(String.valueOf(port), channelConfig, channelDependencies, channels);
}
public Http1MutualSslChannelInitializer(
String metricId, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) {
super(metricId, channelConfig, channelDependencies, channels);
this.isSSlFromIntermediary = channelConfig.get(CommonChannelConfigKeys.isSSlFromIntermediary);
this.sslContextFactory = channelConfig.get(CommonChannelConfigKeys.sslContextFactory);
try {
sslContext = sslContextFactory.createBuilderForServer().build();
} catch (SSLException e) {
throw new RuntimeException("Error configuring SslContext!", e);
}
// Enable TLS Session Tickets support.
sslContextFactory.enableSessionTickets(sslContext);
// Setup metrics tracking the OpenSSL stats.
sslContextFactory.configureOpenSslStatsMetrics(sslContext, metricId);
}
@Override
protected void initChannel(Channel ch) throws Exception {
SslHandler sslHandler = sslContext.newHandler(ch.alloc());
sslHandler.engine().setEnabledProtocols(sslContextFactory.getProtocols());
// Configure our pipeline of ChannelHandlerS.
ChannelPipeline pipeline = ch.pipeline();
storeChannel(ch);
addTimeoutHandlers(pipeline);
addPassportHandler(pipeline);
addTcpRelatedHandlers(pipeline);
pipeline.addLast("ssl", sslHandler);
addSslInfoHandlers(pipeline, isSSlFromIntermediary);
addSslClientCertChecks(pipeline);
addHttp1Handlers(pipeline);
addHttpRelatedHandlers(pipeline);
addZuulHandlers(pipeline);
}
}
| 6,344 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/ZuulDependencyKeys.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.netty.server;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.discovery.EurekaClient;
import com.netflix.netty.common.accesslog.AccessLogPublisher;
import com.netflix.netty.common.channel.config.ChannelConfigKey;
import com.netflix.netty.common.metrics.EventLoopGroupMetrics;
import com.netflix.netty.common.status.ServerStatusManager;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import com.netflix.zuul.FilterLoader;
import com.netflix.zuul.FilterUsageNotifier;
import com.netflix.zuul.RequestCompleteHandler;
import com.netflix.zuul.context.SessionContextDecorator;
import com.netflix.zuul.netty.server.push.PushConnectionRegistry;
import io.netty.channel.ChannelHandler;
import javax.inject.Provider;
/**
* User: michaels@netflix.com
* Date: 2/9/17
* Time: 9:35 AM
*/
public class ZuulDependencyKeys {
public static final ChannelConfigKey<AccessLogPublisher> accessLogPublisher =
new ChannelConfigKey<>("accessLogPublisher");
public static final ChannelConfigKey<EventLoopGroupMetrics> eventLoopGroupMetrics =
new ChannelConfigKey<>("eventLoopGroupMetrics");
public static final ChannelConfigKey<Registry> registry = new ChannelConfigKey<>("registry");
public static final ChannelConfigKey<SessionContextDecorator> sessionCtxDecorator =
new ChannelConfigKey<>("sessionCtxDecorator");
public static final ChannelConfigKey<RequestCompleteHandler> requestCompleteHandler =
new ChannelConfigKey<>("requestCompleteHandler");
public static final ChannelConfigKey<Counter> httpRequestReadTimeoutCounter =
new ChannelConfigKey<>("httpRequestReadTimeoutCounter");
public static final ChannelConfigKey<FilterLoader> filterLoader = new ChannelConfigKey<>("filterLoader");
public static final ChannelConfigKey<FilterUsageNotifier> filterUsageNotifier =
new ChannelConfigKey<>("filterUsageNotifier");
public static final ChannelConfigKey<EurekaClient> discoveryClient = new ChannelConfigKey<>("discoveryClient");
public static final ChannelConfigKey<ApplicationInfoManager> applicationInfoManager =
new ChannelConfigKey<>("applicationInfoManager");
public static final ChannelConfigKey<ServerStatusManager> serverStatusManager =
new ChannelConfigKey<>("serverStatusManager");
public static final ChannelConfigKey<Boolean> SSL_CLIENT_CERT_CHECK_REQUIRED =
new ChannelConfigKey<>("requiresSslClientCertCheck", false);
public static final ChannelConfigKey<Provider<ChannelHandler>> rateLimitingChannelHandlerProvider =
new ChannelConfigKey<>("rateLimitingChannelHandlerProvider");
public static final ChannelConfigKey<Provider<ChannelHandler>> sslClientCertCheckChannelHandlerProvider =
new ChannelConfigKey<>("sslClientCertCheckChannelHandlerProvider");
public static final ChannelConfigKey<PushConnectionRegistry> pushConnectionRegistry =
new ChannelConfigKey<>("pushConnectionRegistry");
}
| 6,345 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/SocketAddressProperty.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.netty.server;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.config.StringDerivedProperty;
import io.netty.channel.unix.DomainSocketAddress;
import javax.annotation.Nullable;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Locale;
import java.util.concurrent.Callable;
import java.util.function.Supplier;
/**
* This class expresses an address that Zuul can bind to. Similar to {@link
* com.netflix.config.DynamicStringMapProperty} this class uses a similar key=value syntax, but only supports a single
* pair.
*
* <p>To use this class, set a bind type such as {@link BindType#ANY} and assign it a port number like {@code 7001}.
* Sample usage:
* <ul>
* <li>{@code =7001} - equivalent to {@code ANY=7001}</li>
* <li>{@code ANY=7001} Binds on all IP addresses and IP stack for port 7001</li>
* <li>{@code IPV4_ANY=7001} Binds on all IPv4 address 0.0.0.0 for port 7001</li>
* <li>{@code IPV6_ANY=7001} Binds on all IPv6 address :: for port 7001</li>
* <li>{@code ANY_LOCAL=7001} Binds on localhost for all IP stacks for port 7001</li>
* <li>{@code IPV4_LOCAL=7001} Binds on IPv4 localhost (127.0.0.1) for port 7001</li>
* <li>{@code IPV6_LOCAL=7001} Binds on IPv6 localhost (::1) for port 7001</li>
* <li>{@code UDS=/var/run/zuul.sock} Binds a domain socket at /var/run/zuul.sock</li>
* </ul>
*
* <p>Note that the local IPv4 binds only work for {@code 127.0.0.1}, and not any other loopback addresses. Currently,
* all IP stack specific bind types only "prefer" a stack; it is up to the OS and the JVM to pick the the final
* address.
*/
public final class SocketAddressProperty extends StringDerivedProperty<SocketAddress> {
public enum BindType {
/**
* Supports any IP stack, for a given port. This is the default behaviour. This also indicates that the
* caller doesn't prefer a given IP stack.
*/
ANY,
/**
* Binds on IPv4 {@code 0.0.0.0} address.
*/
IPV4_ANY(() -> InetAddress.getByAddress("0.0.0.0", new byte[] {0, 0, 0, 0})),
/**
* Binds on IPv6 {@code ::} address.
*/
IPV6_ANY(() -> InetAddress.getByAddress("::", new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})),
/**
* Binds on any local address. This indicates that the caller doesn't prefer a given IP stack.
*/
ANY_LOCAL(InetAddress::getLoopbackAddress),
/**
* Binds on the IPv4 {@code 127.0.0.1} localhost address.
*/
IPV4_LOCAL(() -> InetAddress.getByAddress("localhost", new byte[] {127, 0, 0, 1})),
/**
* Binds on the IPv6 {@code ::1} localhost address.
*/
IPV6_LOCAL(() ->
InetAddress.getByAddress("localhost", new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1})),
/**
* Binds on the Unix Domain Socket path.
*/
UDS,
;
@Nullable
private final Supplier<? extends InetAddress> addressSupplier;
BindType() {
addressSupplier = null;
}
BindType(Callable<? extends InetAddress> addressFn) {
this.addressSupplier = () -> {
try {
return addressFn.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
}
@VisibleForTesting
static final class Decoder implements com.google.common.base.Function<String, SocketAddress> {
static final Decoder INSTANCE = new Decoder();
@Override
public SocketAddress apply(String input) {
if (input == null || input.isEmpty()) {
throw new IllegalArgumentException("Invalid address");
}
int equalsPosition = input.indexOf('=');
if (equalsPosition == -1) {
throw new IllegalArgumentException("Invalid address " + input);
}
String rawBindType = equalsPosition != 0 ? input.substring(0, equalsPosition) : BindType.ANY.name();
BindType bindType = BindType.valueOf(rawBindType.toUpperCase(Locale.ROOT));
String rawAddress = input.substring(equalsPosition + 1);
int port;
parsePort:
{
switch (bindType) {
case ANY: // fallthrough
case IPV4_ANY: // fallthrough
case IPV6_ANY: // fallthrough
case ANY_LOCAL: // fallthrough
case IPV4_LOCAL: // fallthrough
case IPV6_LOCAL: // fallthrough
try {
port = Integer.parseInt(rawAddress);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid Port " + input, e);
}
break parsePort;
case UDS:
port = -1;
break parsePort;
}
throw new AssertionError("Missed cased: " + bindType);
}
switch (bindType) {
case ANY:
return new InetSocketAddress(port);
case IPV4_ANY: // fallthrough
case IPV6_ANY: // fallthrough
case ANY_LOCAL: // fallthrough
case IPV4_LOCAL: // fallthrough
case IPV6_LOCAL: // fallthrough
return new InetSocketAddress(bindType.addressSupplier.get(), port);
case UDS:
return new DomainSocketAddress(rawAddress);
}
throw new AssertionError("Missed cased: " + bindType);
}
@Override
public boolean equals(Object object) {
return false;
}
}
public SocketAddressProperty(String propName, SocketAddress defaultValue) {
super(propName, defaultValue, Decoder.INSTANCE);
}
public SocketAddressProperty(String propName, String defaultValue) {
this(propName, Decoder.INSTANCE.apply(defaultValue));
}
}
| 6,346 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/ServerTimeout.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.netty.server;
public class ServerTimeout {
private final int connectionIdleTimeout;
public ServerTimeout(int connectionIdleTimeout) {
this.connectionIdleTimeout = connectionIdleTimeout;
}
public int connectionIdleTimeout() {
return connectionIdleTimeout;
}
public int defaultRequestExpiryTimeout() {
// Note this is the timeout for the inbound request to zuul, not for each outbound attempt.
// It needs to align with the inbound connection idle timeout and/or the ELB idle timeout. So we
// set it here to 1 sec less than that.
return connectionIdleTimeout > 1000 ? connectionIdleTimeout - 1000 : 1000;
}
}
| 6,347 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/MethodBinding.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.netty.server;
import java.util.concurrent.Callable;
import java.util.function.BiConsumer;
/**
* Utility used for binding context variables or thread variables, depending on requirements.
*
* Author: Arthur Gonigberg
* Date: November 29, 2017
*/
public class MethodBinding<T> {
private final BiConsumer<Runnable, T> boundMethod;
private final Callable<T> bindingContextExtractor;
public static MethodBinding<?> NO_OP_BINDING = new MethodBinding<>((r, t) -> {}, () -> null);
public MethodBinding(BiConsumer<Runnable, T> boundMethod, Callable<T> bindingContextExtractor) {
this.boundMethod = boundMethod;
this.bindingContextExtractor = bindingContextExtractor;
}
public void bind(Runnable method) throws Exception {
T bindingContext = bindingContextExtractor.call();
if (bindingContext == null) {
method.run();
} else {
boundMethod.accept(method, bindingContext);
}
}
}
| 6,348 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/NamedSocketAddress.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.netty.server;
import javax.annotation.CheckReturnValue;
import java.net.SocketAddress;
import java.util.Objects;
public final class NamedSocketAddress extends SocketAddress {
private final String name;
private final SocketAddress delegate;
public NamedSocketAddress(String name, SocketAddress delegate) {
this.name = Objects.requireNonNull(name);
this.delegate = Objects.requireNonNull(delegate);
}
public String name() {
return name;
}
public SocketAddress unwrap() {
return delegate;
}
@CheckReturnValue
public NamedSocketAddress withNewSocket(SocketAddress delegate) {
return new NamedSocketAddress(this.name, delegate);
}
@Override
public String toString() {
return "NamedSocketAddress{" + "name='" + name + '\'' + ", delegate=" + delegate + '}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NamedSocketAddress that = (NamedSocketAddress) o;
return Objects.equals(name, that.name) && Objects.equals(delegate, that.delegate);
}
@Override
public int hashCode() {
return Objects.hash(name, delegate);
}
}
| 6,349 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/ClientResponseWriter.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.netty.server;
import com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.NoopRegistry;
import com.netflix.spectator.api.Registry;
import com.netflix.zuul.RequestCompleteHandler;
import com.netflix.zuul.context.CommonContextKeys;
import com.netflix.zuul.exception.ZuulException;
import com.netflix.zuul.message.Header;
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.netty.ChannelUtils;
import com.netflix.zuul.stats.status.StatusCategory;
import com.netflix.zuul.stats.status.StatusCategoryUtils;
import com.netflix.zuul.stats.status.ZuulStatusCategory;
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.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
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.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http2.HttpConversionUtil;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.ReadTimeoutException;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent;
import static com.netflix.netty.common.HttpLifecycleChannelHandler.StartEvent;
/**
* Created by saroskar on 2/26/17.
*/
public class ClientResponseWriter extends ChannelInboundHandlerAdapter {
private static final Registry NOOP_REGISTRY = new NoopRegistry();
private final RequestCompleteHandler requestCompleteHandler;
private final Counter responseBeforeReceivedLastContentCounter;
// state
private boolean isHandlingRequest;
private boolean startedSendingResponseToClient;
private boolean closeConnection;
// data
private HttpResponseMessage zuulResponse;
private static final Logger logger = LoggerFactory.getLogger(ClientResponseWriter.class);
public ClientResponseWriter(RequestCompleteHandler requestCompleteHandler) {
this(requestCompleteHandler, NOOP_REGISTRY);
}
public ClientResponseWriter(RequestCompleteHandler requestCompleteHandler, Registry registry) {
this.requestCompleteHandler = requestCompleteHandler;
this.responseBeforeReceivedLastContentCounter =
registry.counter("server.http.requests.responseBeforeReceivedLastContent");
}
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
final Channel channel = ctx.channel();
if (msg instanceof HttpResponseMessage) {
final HttpResponseMessage resp = (HttpResponseMessage) msg;
if (skipProcessing(resp)) {
return;
}
if ((!isHandlingRequest) || (startedSendingResponseToClient)) {
/* This can happen if we are already in the process of streaming response back to client OR NOT within active
request/response cycle and something like IDLE or Request Read timeout occurs. In that case we have no way
to recover other than closing the socket and cleaning up resources used by BOTH responses.
*/
resp.disposeBufferedBody();
if (zuulResponse != null) {
zuulResponse.disposeBufferedBody();
}
ctx.close(); // This will trigger CompleteEvent if one is needed
return;
}
startedSendingResponseToClient = true;
zuulResponse = resp;
if ("close".equalsIgnoreCase(zuulResponse.getHeaders().getFirst("Connection"))) {
closeConnection = true;
}
channel.attr(ClientRequestReceiver.ATTR_ZUUL_RESP).set(zuulResponse);
if (channel.isActive()) {
// Track if this is happening.
if (!ClientRequestReceiver.isLastContentReceivedForChannel(channel)
&& !shouldAllowPreemptiveResponse(channel)) {
responseBeforeReceivedLastContentCounter.increment();
logger.warn(
"Writing response to client channel before have received the LastContent of request! {}, {}",
zuulResponse.getInboundRequest().getInfoForLogging(),
ChannelUtils.channelInfoForLogging(channel));
}
// Write out and flush the response to the client channel.
channel.write(buildHttpResponse(zuulResponse));
writeBufferedBodyContent(zuulResponse, channel);
channel.flush();
} else {
resp.disposeBufferedBody();
channel.close();
}
} else if (msg instanceof HttpContent) {
final HttpContent chunk = (HttpContent) msg;
if (channel.isActive()) {
channel.writeAndFlush(chunk);
} else {
chunk.release();
channel.close();
}
} else {
// should never happen
ReferenceCountUtil.release(msg);
throw new ZuulException("Received invalid message from origin", true);
}
}
protected boolean shouldAllowPreemptiveResponse(Channel channel) {
// If the request timed-out while being read, then there won't have been any LastContent, but thats ok because
// the connection will have to be discarded anyway.
StatusCategory status =
StatusCategoryUtils.getStatusCategory(ClientRequestReceiver.getRequestFromChannel(channel));
return status == ZuulStatusCategory.FAILURE_CLIENT_TIMEOUT;
}
protected boolean skipProcessing(HttpResponseMessage resp) {
// override if you need to skip processing of response
return false;
}
private static void writeBufferedBodyContent(final HttpResponseMessage zuulResponse, final Channel channel) {
zuulResponse.getBodyContents().forEach(chunk -> channel.write(chunk.retain()));
}
private HttpResponse buildHttpResponse(final HttpResponseMessage zuulResp) {
final HttpRequestInfo zuulRequest = zuulResp.getInboundRequest();
HttpVersion responseHttpVersion;
final String inboundProtocol = zuulRequest.getProtocol();
if (inboundProtocol.startsWith("HTTP/1")) {
responseHttpVersion = HttpVersion.valueOf(inboundProtocol);
} else {
// Default to 1.1. We do this to cope with HTTP/2 inbound requests.
responseHttpVersion = HttpVersion.HTTP_1_1;
}
// Create the main http response to send, with body.
final DefaultHttpResponse nativeResponse = new DefaultHttpResponse(
responseHttpVersion, HttpResponseStatus.valueOf(zuulResp.getStatus()), false, false);
// Now set all of the response headers - note this is a multi-set in keeping with HTTP semantics
final HttpHeaders nativeHeaders = nativeResponse.headers();
for (Header entry : zuulResp.getHeaders().entries()) {
nativeHeaders.add(entry.getKey(), entry.getValue());
}
// Netty does not automatically add Content-Length or Transfer-Encoding: chunked. So we add here if missing.
if (!HttpUtil.isContentLengthSet(nativeResponse) && !HttpUtil.isTransferEncodingChunked(nativeResponse)) {
nativeResponse.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
}
final HttpRequest nativeReq = (HttpRequest) zuulResp.getContext().get(CommonContextKeys.NETTY_HTTP_REQUEST);
if (!closeConnection && HttpUtil.isKeepAlive(nativeReq)) {
HttpUtil.setKeepAlive(nativeResponse, true);
} else {
// Send a Connection: close response header (only needed for HTTP/1.0 but no harm in doing for 1.1 too).
nativeResponse.headers().set("Connection", "close");
}
// TODO - temp hack for http/2 handling.
if (nativeReq.headers().contains(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text())) {
String streamId = nativeReq.headers().get(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
nativeResponse.headers().set(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), streamId);
}
return nativeResponse;
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof StartEvent) {
isHandlingRequest = true;
startedSendingResponseToClient = false;
closeConnection = false;
zuulResponse = null;
} else if (evt instanceof CompleteEvent) {
HttpResponse response = ((CompleteEvent) evt).getResponse();
if (response != null) {
if ("close".equalsIgnoreCase(response.headers().get("Connection"))) {
closeConnection = true;
}
}
if (zuulResponse != null) {
zuulResponse.disposeBufferedBody();
}
// Do all the post-completion metrics and logging.
handleComplete(ctx.channel());
// Choose to either close the connection, or prepare it for next use.
final CompleteEvent completeEvent = (CompleteEvent) evt;
final CompleteReason reason = completeEvent.getReason();
if (reason == CompleteReason.SESSION_COMPLETE || reason == CompleteReason.INACTIVE) {
if (!closeConnection) {
// Start reading next request over HTTP 1.1 persistent connection
ctx.channel().read();
} else {
ctx.close();
}
} else {
if (isHandlingRequest) {
logger.debug(
"Received complete event while still handling the request. With reason: {} -- {}",
reason.name(),
ChannelUtils.channelInfoForLogging(ctx.channel()));
}
ctx.close();
}
isHandlingRequest = false;
} else if (evt instanceof IdleStateEvent) {
logger.debug("Received IdleStateEvent.");
} else {
logger.debug("ClientResponseWriter Received event {}", evt);
}
}
private void handleComplete(Channel channel) {
try {
if ((isHandlingRequest)) {
completeMetrics(channel, zuulResponse);
// Notify requestComplete listener if configured.
final HttpRequestMessage zuulRequest = ClientRequestReceiver.getRequestFromChannel(channel);
if ((requestCompleteHandler != null) && (zuulRequest != null)) {
requestCompleteHandler.handle(zuulRequest.getInboundRequest(), zuulResponse);
}
}
} catch (Throwable ex) {
logger.error("Error in RequestCompleteHandler.", ex);
}
}
protected void completeMetrics(Channel channel, HttpResponseMessage zuulResponse) {
// override for recording complete metrics
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
int status = 500;
if (cause instanceof ZuulException) {
final ZuulException ze = (ZuulException) cause;
status = ze.getStatusCode();
logger.error(
"Exception caught in ClientResponseWriter for channel {} ",
ChannelUtils.channelInfoForLogging(ctx.channel()),
cause);
} else if (cause instanceof ReadTimeoutException) {
logger.debug("Read timeout for channel {} ", ChannelUtils.channelInfoForLogging(ctx.channel()), cause);
status = 504;
} else {
logger.error("Exception caught in ClientResponseWriter: ", cause);
}
if (isHandlingRequest
&& !startedSendingResponseToClient
&& ctx.channel().isActive()) {
final HttpResponse httpResponse =
new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(status));
ctx.writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
startedSendingResponseToClient = true;
} else {
ctx.close();
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
ctx.close();
}
}
| 6,350 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/EventLoopConfig.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.netty.server;
public interface EventLoopConfig {
int eventLoopCount();
int acceptorCount();
}
| 6,351 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/ClientConnectionsShutdown.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.netty.server;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicIntProperty;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.StatusChangeEvent;
import com.netflix.netty.common.ConnectionCloseChannelAttributes;
import com.netflix.netty.common.ConnectionCloseType;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPromise;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelGroupFuture;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Promise;
import io.netty.util.concurrent.ScheduledFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit;
/**
* TODO: Change this class to be an instance per-port.
* So that then the configuration can be different per-port, which is need for the combined FTL/Cloud clusters.
* <p>
* User: michaels@netflix.com
* Date: 3/6/17
* Time: 12:36 PM
*/
public class ClientConnectionsShutdown {
private static final Logger LOG = LoggerFactory.getLogger(ClientConnectionsShutdown.class);
private static final DynamicBooleanProperty ENABLED =
new DynamicBooleanProperty("server.outofservice.connections.shutdown", false);
private static final DynamicIntProperty DELAY_AFTER_OUT_OF_SERVICE_MS =
new DynamicIntProperty("server.outofservice.connections.delay", 2000);
private static final DynamicIntProperty GRACEFUL_CLOSE_TIMEOUT =
new DynamicIntProperty("server.outofservice.close.timeout", 30);
private final ChannelGroup channels;
private final EventExecutor executor;
private final EurekaClient discoveryClient;
public ClientConnectionsShutdown(ChannelGroup channels, EventExecutor executor, EurekaClient discoveryClient) {
this.channels = channels;
this.executor = executor;
this.discoveryClient = discoveryClient;
if (discoveryClient != null) {
initDiscoveryListener();
}
}
private void initDiscoveryListener() {
this.discoveryClient.registerEventListener(event -> {
if (event instanceof StatusChangeEvent) {
StatusChangeEvent sce = (StatusChangeEvent) event;
LOG.info("Received {}", sce);
if (sce.getPreviousStatus() == InstanceInfo.InstanceStatus.UP
&& (sce.getStatus() == InstanceInfo.InstanceStatus.OUT_OF_SERVICE
|| sce.getStatus() == InstanceInfo.InstanceStatus.DOWN)) {
// TODO - Also should stop accepting any new client connections now too?
// Schedule to gracefully close all the client connections.
if (ENABLED.get()) {
executor.schedule(
() -> gracefullyShutdownClientChannels(false),
DELAY_AFTER_OUT_OF_SERVICE_MS.get(),
TimeUnit.MILLISECONDS);
}
}
}
});
}
public Promise<Void> gracefullyShutdownClientChannels() {
return gracefullyShutdownClientChannels(true);
}
Promise<Void> gracefullyShutdownClientChannels(boolean forceCloseAfterTimeout) {
// Mark all active connections to be closed after next response sent.
LOG.warn("Flagging CLOSE_AFTER_RESPONSE on {} client channels.", channels.size());
// racy situation if new connections are still coming in, but any channels created after newCloseFuture will
// be closed during the force close stage
ChannelGroupFuture closeFuture = channels.newCloseFuture();
for (Channel channel : channels) {
ConnectionCloseType.setForChannel(channel, ConnectionCloseType.DELAYED_GRACEFUL);
ChannelPromise closePromise = channel.pipeline().newPromise();
channel.attr(ConnectionCloseChannelAttributes.CLOSE_AFTER_RESPONSE).set(closePromise);
}
Promise<Void> promise = executor.newPromise();
Runnable cancelTimeoutTask;
if (forceCloseAfterTimeout) {
ScheduledFuture<?> timeoutTask = executor.schedule(
() -> {
LOG.warn("Force closing remaining {} active client channels.", channels.size());
channels.close();
},
GRACEFUL_CLOSE_TIMEOUT.get(),
TimeUnit.SECONDS);
cancelTimeoutTask = () -> {
if (!timeoutTask.isDone()) {
// close happened before the timeout
timeoutTask.cancel(false);
}
};
} else {
cancelTimeoutTask = () -> {};
}
closeFuture.addListener(future -> {
cancelTimeoutTask.run();
promise.setSuccess(null);
});
return promise;
}
}
| 6,352 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/ZuulServerChannelInitializer.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.netty.server;
import com.netflix.netty.common.channel.config.ChannelConfig;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.group.ChannelGroup;
/**
* User: Mike Smith
* Date: 3/5/16
* Time: 6:44 PM
*/
public class ZuulServerChannelInitializer extends BaseZuulChannelInitializer {
public ZuulServerChannelInitializer(
String metricId, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) {
super(metricId, channelConfig, channelDependencies, channels);
}
/**
* Use {@link #ZuulServerChannelInitializer(String, ChannelConfig, ChannelConfig, ChannelGroup)} instead.
*/
@Deprecated
public ZuulServerChannelInitializer(
int port, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) {
this(String.valueOf(port), channelConfig, channelDependencies, channels);
}
@Override
protected void initChannel(Channel ch) throws Exception {
// Configure our pipeline of ChannelHandlerS.
ChannelPipeline pipeline = ch.pipeline();
storeChannel(ch);
addTimeoutHandlers(pipeline);
addPassportHandler(pipeline);
addTcpRelatedHandlers(pipeline);
addHttp1Handlers(pipeline);
addHttpRelatedHandlers(pipeline);
addZuulHandlers(pipeline);
}
}
| 6,353 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/Server.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.netty.server;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.netty.common.CategorizedThreadFactory;
import com.netflix.netty.common.LeastConnsEventLoopChooserFactory;
import com.netflix.netty.common.metrics.EventLoopGroupMetrics;
import com.netflix.netty.common.status.ServerStatusManager;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Spectator;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.zuul.Attrs;
import com.netflix.zuul.monitoring.ConnCounter;
import com.netflix.zuul.monitoring.ConnTimer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufAllocatorMetric;
import io.netty.buffer.ByteBufAllocatorMetricProvider;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultSelectStrategyFactory;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ServerChannel;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollChannelOption;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.kqueue.KQueue;
import io.netty.channel.kqueue.KQueueEventLoopGroup;
import io.netty.channel.kqueue.KQueueServerSocketChannel;
import io.netty.channel.kqueue.KQueueSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.incubator.channel.uring.IOUring;
import io.netty.incubator.channel.uring.IOUringEventLoopGroup;
import io.netty.incubator.channel.uring.IOUringServerSocketChannel;
import io.netty.incubator.channel.uring.IOUringSocketChannel;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.DefaultEventExecutorChooserFactory;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.EventExecutorChooserFactory;
import io.netty.util.concurrent.ThreadPerTaskExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.nio.channels.spi.SelectorProvider;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
*
* NOTE: Shout-out to <a href="https://github.com/adamfisk/LittleProxy">LittleProxy</a> which was great as a reference.
*
* User: michaels
* Date: 11/8/14
* Time: 8:39 PM
*/
public class Server {
/**
* This field is effectively a noop, as Epoll is enabled automatically if available. This can be disabled by
* using the {@link #FORCE_NIO} property.
*/
@Deprecated
public static final DynamicBooleanProperty USE_EPOLL =
new DynamicBooleanProperty("zuul.server.netty.socket.epoll", false);
/**
* If {@code true}, The Zuul server will avoid autodetecting the transport type and use the default Java NIO
* transport.
*/
private static final DynamicBooleanProperty FORCE_NIO =
new DynamicBooleanProperty("zuul.server.netty.socket.force_nio", false);
private static final DynamicBooleanProperty FORCE_IO_URING =
new DynamicBooleanProperty("zuul.server.netty.socket.force_io_uring", false);
private static final Logger LOG = LoggerFactory.getLogger(Server.class);
private static final DynamicBooleanProperty USE_LEASTCONNS_FOR_EVENTLOOPS =
new DynamicBooleanProperty("zuul.server.eventloops.use_leastconns", false);
private static final DynamicBooleanProperty MANUAL_DISCOVERY_STATUS =
new DynamicBooleanProperty("zuul.server.netty.manual.discovery.status", true);
private final EventLoopGroupMetrics eventLoopGroupMetrics;
private final Thread jvmShutdownHook;
private final Registry registry;
private ServerGroup serverGroup;
private final ClientConnectionsShutdown clientConnectionsShutdown;
private final ServerStatusManager serverStatusManager;
private final Map<NamedSocketAddress, ? extends ChannelInitializer<?>> addressesToInitializers;
/**
* Unlike the above, the socket addresses in this map are the *bound* addresses, rather than the requested ones.
*/
private final Map<NamedSocketAddress, Channel> addressesToChannels = new LinkedHashMap<>();
private final EventLoopConfig eventLoopConfig;
/**
* This is a hack to expose the channel type to the origin channel. It is NOT API stable and should not be
* referenced by non-Zuul code.
*/
@Deprecated
public static final AtomicReference<Class<? extends Channel>> defaultOutboundChannelType = new AtomicReference<>();
/**
* Use {@link #Server(Registry, ServerStatusManager, Map, ClientConnectionsShutdown, EventLoopGroupMetrics,
* EventLoopConfig)}
* instead.
*/
@SuppressWarnings("rawtypes")
@Deprecated
public Server(
Map<Integer, ChannelInitializer> portsToChannelInitializers,
ServerStatusManager serverStatusManager,
ClientConnectionsShutdown clientConnectionsShutdown,
EventLoopGroupMetrics eventLoopGroupMetrics) {
this(
portsToChannelInitializers,
serverStatusManager,
clientConnectionsShutdown,
eventLoopGroupMetrics,
new DefaultEventLoopConfig());
}
/**
* Use {@link #Server(Registry, ServerStatusManager, Map, ClientConnectionsShutdown, EventLoopGroupMetrics,
* EventLoopConfig)}
* instead.
*/
@SuppressWarnings({"unchecked", "rawtypes"
}) // Channel init map has the wrong generics and we can't fix without api breakage.
@Deprecated
public Server(
Map<Integer, ChannelInitializer> portsToChannelInitializers,
ServerStatusManager serverStatusManager,
ClientConnectionsShutdown clientConnectionsShutdown,
EventLoopGroupMetrics eventLoopGroupMetrics,
EventLoopConfig eventLoopConfig) {
this(
Spectator.globalRegistry(),
serverStatusManager,
convertPortMap((Map<Integer, ChannelInitializer<?>>) (Map) portsToChannelInitializers),
clientConnectionsShutdown,
eventLoopGroupMetrics,
eventLoopConfig);
}
public Server(
Registry registry,
ServerStatusManager serverStatusManager,
Map<NamedSocketAddress, ? extends ChannelInitializer<?>> addressesToInitializers,
ClientConnectionsShutdown clientConnectionsShutdown,
EventLoopGroupMetrics eventLoopGroupMetrics,
EventLoopConfig eventLoopConfig) {
this.registry = Objects.requireNonNull(registry);
this.addressesToInitializers = Collections.unmodifiableMap(new LinkedHashMap<>(addressesToInitializers));
this.serverStatusManager = Preconditions.checkNotNull(serverStatusManager, "serverStatusManager");
this.clientConnectionsShutdown =
Preconditions.checkNotNull(clientConnectionsShutdown, "clientConnectionsShutdown");
this.eventLoopConfig = Preconditions.checkNotNull(eventLoopConfig, "eventLoopConfig");
this.eventLoopGroupMetrics = Preconditions.checkNotNull(eventLoopGroupMetrics, "eventLoopGroupMetrics");
this.jvmShutdownHook = new Thread(this::stop, "Zuul-JVM-shutdown-hook");
}
public Server(
Registry registry,
ServerStatusManager serverStatusManager,
Map<NamedSocketAddress, ? extends ChannelInitializer<?>> addressesToInitializers,
ClientConnectionsShutdown clientConnectionsShutdown,
EventLoopGroupMetrics eventLoopGroupMetrics,
EventLoopConfig eventLoopConfig,
Thread jvmShutdownHook) {
this.registry = Objects.requireNonNull(registry);
this.addressesToInitializers = Collections.unmodifiableMap(new LinkedHashMap<>(addressesToInitializers));
this.serverStatusManager = Preconditions.checkNotNull(serverStatusManager, "serverStatusManager");
this.clientConnectionsShutdown =
Preconditions.checkNotNull(clientConnectionsShutdown, "clientConnectionsShutdown");
this.eventLoopConfig = Preconditions.checkNotNull(eventLoopConfig, "eventLoopConfig");
this.eventLoopGroupMetrics = Preconditions.checkNotNull(eventLoopGroupMetrics, "eventLoopGroupMetrics");
this.jvmShutdownHook = jvmShutdownHook;
}
public void stop() {
LOG.info("Shutting down Zuul.");
serverGroup.stop();
LOG.info("Completed zuul shutdown.");
}
public void start() {
if (jvmShutdownHook != null) {
Runtime.getRuntime().addShutdownHook(jvmShutdownHook);
}
serverGroup = new ServerGroup(
"Salamander", eventLoopConfig.acceptorCount(), eventLoopConfig.eventLoopCount(), eventLoopGroupMetrics);
serverGroup.initializeTransport();
try {
List<ChannelFuture> allBindFutures = new ArrayList<>(addressesToInitializers.size());
// Setup each of the channel initializers on requested ports.
for (Map.Entry<NamedSocketAddress, ? extends ChannelInitializer<?>> entry :
addressesToInitializers.entrySet()) {
NamedSocketAddress requestedNamedAddr = entry.getKey();
ChannelFuture nettyServerFuture = setupServerBootstrap(requestedNamedAddr, entry.getValue());
Channel chan = nettyServerFuture.channel();
addressesToChannels.put(requestedNamedAddr.withNewSocket(chan.localAddress()), chan);
allBindFutures.add(nettyServerFuture);
}
// All channels should share a single ByteBufAllocator instance.
// Add metrics to monitor that allocator's memory usage.
if (!allBindFutures.isEmpty()) {
ByteBufAllocator alloc = allBindFutures.get(0).channel().alloc();
if (alloc instanceof ByteBufAllocatorMetricProvider) {
ByteBufAllocatorMetric metrics = ((ByteBufAllocatorMetricProvider) alloc).metric();
PolledMeter.using(registry)
.withId(registry.createId("zuul.nettybuffermem.live", "type", "heap"))
.monitorValue(metrics, ByteBufAllocatorMetric::usedHeapMemory);
PolledMeter.using(registry)
.withId(registry.createId("zuul.nettybuffermem.live", "type", "direct"))
.monitorValue(metrics, ByteBufAllocatorMetric::usedDirectMemory);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public final void awaitTermination() throws InterruptedException {
for (Channel chan : addressesToChannels.values()) {
chan.closeFuture().sync();
}
}
public final List<NamedSocketAddress> getListeningAddresses() {
if (serverGroup == null) {
throw new IllegalStateException("Server has not been started");
}
return Collections.unmodifiableList(new ArrayList<>(addressesToChannels.keySet()));
}
@VisibleForTesting
public void waitForEachEventLoop() throws InterruptedException, ExecutionException {
for (EventExecutor exec : serverGroup.clientToProxyWorkerPool) {
exec.submit(() -> {
// Do nothing.
})
.get();
}
}
private ChannelFuture setupServerBootstrap(
NamedSocketAddress listenAddress, ChannelInitializer<?> channelInitializer) throws InterruptedException {
ServerBootstrap serverBootstrap =
new ServerBootstrap().group(serverGroup.clientToProxyBossPool, serverGroup.clientToProxyWorkerPool);
LOG.info("Proxy listening with {}", serverGroup.channelType);
serverBootstrap.channel(serverGroup.channelType);
serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
serverBootstrap.childOption(ChannelOption.SO_LINGER, -1);
serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
// Apply transport specific socket options.
for (Map.Entry<ChannelOption<?>, ?> optionEntry : serverGroup.transportChannelOptions.entrySet()) {
serverBootstrap = serverBootstrap.option((ChannelOption) optionEntry.getKey(), optionEntry.getValue());
}
serverBootstrap.handler(new NewConnHandler());
serverBootstrap.childHandler(channelInitializer);
serverBootstrap.validate();
LOG.info("Binding to : {}", listenAddress);
if (MANUAL_DISCOVERY_STATUS.get()) {
// Flag status as UP just before binding to the port.
serverStatusManager.localStatus(InstanceInfo.InstanceStatus.UP);
}
// Bind and start to accept incoming connections.
ChannelFuture bindFuture = serverBootstrap.bind(listenAddress.unwrap());
try {
return bindFuture.sync();
} catch (Exception e) {
// sync() sneakily throws a checked Exception, but doesn't declare it. This can happen if there is a bind
// failure, which is typically an IOException. Just chain it and rethrow.
throw new RuntimeException("Failed to bind on addr " + listenAddress, e);
}
}
/**
* Override for metrics or informational purposes
*
* @param clientToProxyBossPool - acceptor pool
* @param clientToProxyWorkerPool - worker pool
*/
public void postEventLoopCreationHook(
EventLoopGroup clientToProxyBossPool, EventLoopGroup clientToProxyWorkerPool) {}
private final class ServerGroup {
/** A name for this ServerGroup to use in naming threads. */
private final String name;
private final int acceptorThreads;
private final int workerThreads;
private final EventLoopGroupMetrics eventLoopGroupMetrics;
private EventLoopGroup clientToProxyBossPool;
private EventLoopGroup clientToProxyWorkerPool;
private Class<? extends ServerChannel> channelType;
private Map<ChannelOption<?>, ?> transportChannelOptions;
private volatile boolean stopped = false;
private ServerGroup(
String name, int acceptorThreads, int workerThreads, EventLoopGroupMetrics eventLoopGroupMetrics) {
this.name = name;
this.acceptorThreads = acceptorThreads;
this.workerThreads = workerThreads;
this.eventLoopGroupMetrics = eventLoopGroupMetrics;
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(final Thread t, final Throwable e) {
LOG.error("Uncaught throwable", e);
}
});
}
private void initializeTransport() {
// TODO - try our own impl of ChooserFactory that load-balances across the eventloops using leastconns algo?
EventExecutorChooserFactory chooserFactory;
if (USE_LEASTCONNS_FOR_EVENTLOOPS.get()) {
chooserFactory = new LeastConnsEventLoopChooserFactory(eventLoopGroupMetrics);
} else {
chooserFactory = DefaultEventExecutorChooserFactory.INSTANCE;
}
ThreadFactory workerThreadFactory = new CategorizedThreadFactory(name + "-ClientToZuulWorker");
Executor workerExecutor = new ThreadPerTaskExecutor(workerThreadFactory);
Map<ChannelOption<?>, Object> extraOptions = new HashMap<>();
final boolean useNio = FORCE_NIO.get();
final boolean useIoUring = FORCE_IO_URING.get();
if (useIoUring && ioUringIsAvailable()) {
channelType = IOUringServerSocketChannel.class;
defaultOutboundChannelType.set(IOUringSocketChannel.class);
clientToProxyBossPool = new IOUringEventLoopGroup(
acceptorThreads, new CategorizedThreadFactory(name + "-ClientToZuulAcceptor"));
clientToProxyWorkerPool = new IOUringEventLoopGroup(workerThreads, workerExecutor);
} else if (!useNio && epollIsAvailable()) {
channelType = EpollServerSocketChannel.class;
defaultOutboundChannelType.set(EpollSocketChannel.class);
extraOptions.put(EpollChannelOption.TCP_DEFER_ACCEPT, -1);
clientToProxyBossPool = new EpollEventLoopGroup(
acceptorThreads, new CategorizedThreadFactory(name + "-ClientToZuulAcceptor"));
clientToProxyWorkerPool = new EpollEventLoopGroup(
workerThreads, workerExecutor, chooserFactory, DefaultSelectStrategyFactory.INSTANCE);
} else if (!useNio && kqueueIsAvailable()) {
channelType = KQueueServerSocketChannel.class;
defaultOutboundChannelType.set(KQueueSocketChannel.class);
clientToProxyBossPool = new KQueueEventLoopGroup(
acceptorThreads, new CategorizedThreadFactory(name + "-ClientToZuulAcceptor"));
clientToProxyWorkerPool = new KQueueEventLoopGroup(
workerThreads, workerExecutor, chooserFactory, DefaultSelectStrategyFactory.INSTANCE);
} else {
channelType = NioServerSocketChannel.class;
defaultOutboundChannelType.set(NioSocketChannel.class);
NioEventLoopGroup elg = new NioEventLoopGroup(
workerThreads,
workerExecutor,
chooserFactory,
SelectorProvider.provider(),
DefaultSelectStrategyFactory.INSTANCE);
elg.setIoRatio(90);
clientToProxyBossPool = new NioEventLoopGroup(
acceptorThreads, new CategorizedThreadFactory(name + "-ClientToZuulAcceptor"));
clientToProxyWorkerPool = elg;
}
transportChannelOptions = Collections.unmodifiableMap(extraOptions);
postEventLoopCreationHook(clientToProxyBossPool, clientToProxyWorkerPool);
}
private synchronized void stop() {
LOG.info("Shutting down");
if (stopped) {
LOG.info("Already stopped");
return;
}
if (MANUAL_DISCOVERY_STATUS.get()) {
// Flag status as down.
// that we can flag to return DOWN here (would that then update Discovery? or still be a delay?)
serverStatusManager.localStatus(InstanceInfo.InstanceStatus.DOWN);
}
// Shutdown each of the client connections (blocks until complete).
// NOTE: ClientConnectionsShutdown can also be configured to gracefully close connections when the
// discovery status changes to DOWN. So if it has been configured that way, then this will be an additional
// call to gracefullyShutdownClientChannels(), which will be a noop.
clientConnectionsShutdown.gracefullyShutdownClientChannels().syncUninterruptibly();
LOG.info("Shutting down event loops");
List<EventLoopGroup> allEventLoopGroups = new ArrayList<>();
allEventLoopGroups.add(clientToProxyBossPool);
allEventLoopGroups.add(clientToProxyWorkerPool);
for (EventLoopGroup group : allEventLoopGroups) {
group.shutdownGracefully();
}
for (EventLoopGroup group : allEventLoopGroups) {
try {
group.awaitTermination(20, TimeUnit.SECONDS);
} catch (InterruptedException ie) {
LOG.warn("Interrupted while shutting down event loop");
}
}
stopped = true;
LOG.info("Done shutting down");
}
}
/**
* Keys should be a short string usable in metrics.
*/
public static final AttributeKey<Attrs> CONN_DIMENSIONS = AttributeKey.newInstance("zuulconndimensions");
private final class NewConnHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
Long now = System.nanoTime();
final Channel child = (Channel) msg;
child.attr(CONN_DIMENSIONS).set(Attrs.newInstance());
ConnTimer timer = ConnTimer.install(child, registry, registry.createId("zuul.conn.client.timing"));
timer.record(now, "ACCEPT");
ConnCounter.install(child, registry, registry.createId("zuul.conn.client.current"));
super.channelRead(ctx, msg);
}
}
static Map<NamedSocketAddress, ChannelInitializer<?>> convertPortMap(
Map<Integer, ChannelInitializer<?>> portsToChannelInitializers) {
Map<NamedSocketAddress, ChannelInitializer<?>> addrsToInitializers =
new LinkedHashMap<>(portsToChannelInitializers.size());
for (Map.Entry<Integer, ChannelInitializer<?>> portToInitializer : portsToChannelInitializers.entrySet()) {
int portNumber = portToInitializer.getKey();
addrsToInitializers.put(
new NamedSocketAddress("port" + portNumber, new InetSocketAddress(portNumber)),
portToInitializer.getValue());
}
return Collections.unmodifiableMap(addrsToInitializers);
}
private static boolean epollIsAvailable() {
boolean available;
try {
available = Epoll.isAvailable();
} catch (NoClassDefFoundError e) {
LOG.debug("Epoll is unavailable, skipping", e);
return false;
} catch (RuntimeException | Error e) {
LOG.warn("Epoll is unavailable, skipping", e);
return false;
}
if (!available) {
LOG.debug("Epoll is unavailable, skipping", Epoll.unavailabilityCause());
}
return available;
}
private static boolean ioUringIsAvailable() {
boolean available;
try {
available = IOUring.isAvailable();
} catch (NoClassDefFoundError e) {
LOG.debug("io_uring is unavailable, skipping", e);
return false;
} catch (RuntimeException | Error e) {
LOG.warn("io_uring is unavailable, skipping", e);
return false;
}
if (!available) {
LOG.debug("io_uring is unavailable, skipping", IOUring.unavailabilityCause());
}
return available;
}
private static boolean kqueueIsAvailable() {
boolean available;
try {
available = KQueue.isAvailable();
} catch (NoClassDefFoundError e) {
LOG.debug("KQueue is unavailable, skipping", e);
return false;
} catch (RuntimeException | Error e) {
LOG.warn("KQueue is unavailable, skipping", e);
return false;
}
if (!available) {
LOG.debug("KQueue is unavailable, skipping", KQueue.unavailabilityCause());
}
return available;
}
} | 6,354 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/DirectMemoryMonitor.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.netty.server;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.config.DynamicIntProperty;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.patterns.PolledMeter;
import io.netty.util.internal.PlatformDependent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
/**
* User: michaels@netflix.com
* Date: 4/29/16
* Time: 10:23 AM
*/
@Singleton
public final class DirectMemoryMonitor {
private static final Logger LOG = LoggerFactory.getLogger(DirectMemoryMonitor.class);
private static final String PROP_PREFIX = "zuul.directmemory";
private static final DynamicIntProperty TASK_DELAY_PROP = new DynamicIntProperty(PROP_PREFIX + ".task.delay", 10);
private final ScheduledExecutorService service;
@Inject
public DirectMemoryMonitor(Registry registry) {
service = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("dmm-%d")
.build());
PolledMeter.using(registry)
.withName(PROP_PREFIX + ".reserved")
.withDelay(Duration.ofSeconds(TASK_DELAY_PROP.get()))
.scheduleOn(service)
.monitorValue(DirectMemoryMonitor.class, DirectMemoryMonitor::getReservedMemory);
PolledMeter.using(registry)
.withName(PROP_PREFIX + ".max")
.withDelay(Duration.ofSeconds(TASK_DELAY_PROP.get()))
.scheduleOn(service)
.monitorValue(DirectMemoryMonitor.class, DirectMemoryMonitor::getMaxMemory);
}
public DirectMemoryMonitor() {
// no-op constructor
this.service = null;
}
private static double getReservedMemory(Object discard) {
try {
return PlatformDependent.usedDirectMemory();
} catch (Throwable e) {
LOG.warn("Error in DirectMemoryMonitor task.", e);
}
return -1;
}
private static double getMaxMemory(Object discard) {
try {
return PlatformDependent.maxDirectMemory();
} catch (Throwable e) {
LOG.warn("Error in DirectMemoryMonitor task.", e);
}
return -1;
}
}
| 6,355 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/DefaultEventLoopConfig.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.netty.server;
import com.netflix.config.DynamicIntProperty;
import javax.inject.Singleton;
/**
* Event loop configuration for the Zuul server.
* By default, it configures a single acceptor thread with workers = logical cores available.
*/
@Singleton
public class DefaultEventLoopConfig implements EventLoopConfig {
private static final DynamicIntProperty ACCEPTOR_THREADS =
new DynamicIntProperty("zuul.server.netty.threads.acceptor", 1);
private static final DynamicIntProperty WORKER_THREADS =
new DynamicIntProperty("zuul.server.netty.threads.worker", -1);
private static final int PROCESSOR_COUNT = Runtime.getRuntime().availableProcessors();
private final int eventLoopCount;
private final int acceptorCount;
public DefaultEventLoopConfig() {
eventLoopCount = WORKER_THREADS.get() > 0 ? WORKER_THREADS.get() : PROCESSOR_COUNT;
acceptorCount = ACCEPTOR_THREADS.get();
}
public DefaultEventLoopConfig(int eventLoopCount, int acceptorCount) {
this.eventLoopCount = eventLoopCount;
this.acceptorCount = acceptorCount;
}
@Override
public int eventLoopCount() {
return eventLoopCount;
}
@Override
public int acceptorCount() {
return acceptorCount;
}
}
| 6,356 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/BaseZuulChannelInitializer.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.netty.server;
import com.google.common.base.Preconditions;
import com.netflix.config.CachedDynamicIntProperty;
import com.netflix.netty.common.CloseOnIdleStateHandler;
import com.netflix.netty.common.Http1ConnectionCloseHandler;
import com.netflix.netty.common.Http1ConnectionExpiryHandler;
import com.netflix.netty.common.HttpRequestReadTimeoutHandler;
import com.netflix.netty.common.HttpServerLifecycleChannelHandler;
import com.netflix.netty.common.SourceAddressChannelHandler;
import com.netflix.netty.common.SslExceptionsHandler;
import com.netflix.netty.common.accesslog.AccessLogChannelHandler;
import com.netflix.netty.common.accesslog.AccessLogPublisher;
import com.netflix.netty.common.channel.config.ChannelConfig;
import com.netflix.netty.common.channel.config.CommonChannelConfigKeys;
import com.netflix.netty.common.metrics.EventLoopGroupMetrics;
import com.netflix.netty.common.metrics.HttpBodySizeRecordingChannelHandler;
import com.netflix.netty.common.metrics.HttpMetricsChannelHandler;
import com.netflix.netty.common.metrics.PerEventLoopMetricsChannelHandler;
import com.netflix.netty.common.proxyprotocol.ElbProxyProtocolChannelHandler;
import com.netflix.netty.common.proxyprotocol.StripUntrustedProxyHeadersHandler;
import com.netflix.netty.common.throttle.MaxInboundConnectionsHandler;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import com.netflix.zuul.FilterLoader;
import com.netflix.zuul.FilterUsageNotifier;
import com.netflix.zuul.RequestCompleteHandler;
import com.netflix.zuul.context.SessionContextDecorator;
import com.netflix.zuul.filters.ZuulFilter;
import com.netflix.zuul.filters.passport.InboundPassportStampingFilter;
import com.netflix.zuul.filters.passport.OutboundPassportStampingFilter;
import com.netflix.zuul.message.ZuulMessage;
import com.netflix.zuul.message.http.HttpRequestMessage;
import com.netflix.zuul.message.http.HttpResponseMessage;
import com.netflix.zuul.netty.filter.FilterRunner;
import com.netflix.zuul.netty.filter.ZuulEndPointRunner;
import com.netflix.zuul.netty.filter.ZuulFilterChainHandler;
import com.netflix.zuul.netty.filter.ZuulFilterChainRunner;
import com.netflix.zuul.netty.insights.PassportLoggingHandler;
import com.netflix.zuul.netty.insights.PassportStateHttpServerHandler;
import com.netflix.zuul.netty.insights.ServerStateHandler;
import com.netflix.zuul.netty.server.ssl.SslHandshakeInfoHandler;
import com.netflix.zuul.passport.PassportState;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.AttributeKey;
import java.util.SortedSet;
import java.util.concurrent.TimeUnit;
/**
* User: Mike Smith
* Date: 3/5/16
* Time: 6:26 PM
*/
public abstract class BaseZuulChannelInitializer extends ChannelInitializer<Channel> {
public static final String HTTP_CODEC_HANDLER_NAME = "codec";
public static final AttributeKey<ChannelConfig> ATTR_CHANNEL_CONFIG = AttributeKey.newInstance("channel_config");
protected static final LoggingHandler nettyLogger = new LoggingHandler("zuul.server.nettylog", LogLevel.INFO);
public static final CachedDynamicIntProperty MAX_INITIAL_LINE_LENGTH =
new CachedDynamicIntProperty("server.http.decoder.maxInitialLineLength", 16384);
public static final CachedDynamicIntProperty MAX_HEADER_SIZE =
new CachedDynamicIntProperty("server.http.decoder.maxHeaderSize", 32768);
public static final CachedDynamicIntProperty MAX_CHUNK_SIZE =
new CachedDynamicIntProperty("server.http.decoder.maxChunkSize", 32768);
/**
* The port that the server intends to listen on. Subclasses should NOT use this field, as it may not be set, and
* may differ from the actual listening port. For example:
*
* <ul>
* <li>When binding the server to port `0`, the actual port will be different from the one provided here.
* <li>If there is no port (such as in a LocalSocket, or DomainSocket), the port number may be `-1`.
* </ul>
*
* <p>Instead, subclasses should read the local address on channel initialization, and decide to take action then.
*/
@Deprecated
protected final int port;
protected final String metricId;
protected final ChannelConfig channelConfig;
protected final ChannelConfig channelDependencies;
protected final int idleTimeout;
protected final int httpRequestReadTimeout;
protected final int maxRequestsPerConnection;
protected final int maxRequestsPerConnectionInBrownout;
protected final int connectionExpiry;
protected final int maxConnections;
private final int connCloseDelay;
protected final Registry registry;
protected final HttpMetricsChannelHandler httpMetricsHandler;
protected final PerEventLoopMetricsChannelHandler.Connections perEventLoopConnectionMetricsHandler;
protected final PerEventLoopMetricsChannelHandler.HttpRequests perEventLoopRequestsMetricsHandler;
protected final MaxInboundConnectionsHandler maxConnectionsHandler;
protected final AccessLogPublisher accessLogPublisher;
protected final PassportLoggingHandler passportLoggingHandler;
protected final boolean withProxyProtocol;
protected final StripUntrustedProxyHeadersHandler stripInboundProxyHeadersHandler;
// TODO
// protected final HttpRequestThrottleChannelHandler requestThrottleHandler;
protected final ChannelHandler rateLimitingChannelHandler;
protected final ChannelHandler sslClientCertCheckChannelHandler;
// protected final RequestRejectedChannelHandler requestRejectedChannelHandler;
protected final SessionContextDecorator sessionContextDecorator;
protected final RequestCompleteHandler requestCompleteHandler;
protected final Counter httpRequestReadTimeoutCounter;
protected final FilterLoader filterLoader;
protected final FilterUsageNotifier filterUsageNotifier;
protected final SourceAddressChannelHandler sourceAddressChannelHandler;
/** A collection of all the active channels that we can use to things like graceful shutdown */
protected final ChannelGroup channels;
/**
* After calling this method, child classes should not reference {@link #port} any more.
*/
protected BaseZuulChannelInitializer(
String metricId, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) {
this(-1, metricId, channelConfig, channelDependencies, channels);
}
/**
* Call {@link #BaseZuulChannelInitializer(String, ChannelConfig, ChannelConfig, ChannelGroup)} instead.
*/
@Deprecated
protected BaseZuulChannelInitializer(
int port, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) {
this(port, String.valueOf(port), channelConfig, channelDependencies, channels);
}
private BaseZuulChannelInitializer(
int port,
String metricId,
ChannelConfig channelConfig,
ChannelConfig channelDependencies,
ChannelGroup channels) {
this.port = port;
Preconditions.checkNotNull(metricId, "metricId");
this.metricId = metricId;
this.channelConfig = channelConfig;
this.channelDependencies = channelDependencies;
this.channels = channels;
this.accessLogPublisher = channelDependencies.get(ZuulDependencyKeys.accessLogPublisher);
this.withProxyProtocol = channelConfig.get(CommonChannelConfigKeys.withProxyProtocol);
this.idleTimeout = channelConfig.get(CommonChannelConfigKeys.idleTimeout);
this.httpRequestReadTimeout = channelConfig.get(CommonChannelConfigKeys.httpRequestReadTimeout);
this.registry = channelDependencies.get(ZuulDependencyKeys.registry);
this.httpMetricsHandler = new HttpMetricsChannelHandler(registry, "server", "http-" + metricId);
EventLoopGroupMetrics eventLoopGroupMetrics = channelDependencies.get(ZuulDependencyKeys.eventLoopGroupMetrics);
PerEventLoopMetricsChannelHandler perEventLoopMetricsHandler =
new PerEventLoopMetricsChannelHandler(eventLoopGroupMetrics);
this.perEventLoopConnectionMetricsHandler = perEventLoopMetricsHandler.new Connections();
this.perEventLoopRequestsMetricsHandler = perEventLoopMetricsHandler.new HttpRequests();
this.maxConnections = channelConfig.get(CommonChannelConfigKeys.maxConnections);
this.maxConnectionsHandler = new MaxInboundConnectionsHandler(registry, metricId, maxConnections);
this.maxRequestsPerConnection = channelConfig.get(CommonChannelConfigKeys.maxRequestsPerConnection);
this.maxRequestsPerConnectionInBrownout =
channelConfig.get(CommonChannelConfigKeys.maxRequestsPerConnectionInBrownout);
this.connectionExpiry = channelConfig.get(CommonChannelConfigKeys.connectionExpiry);
this.connCloseDelay = channelConfig.get(CommonChannelConfigKeys.connCloseDelay);
StripUntrustedProxyHeadersHandler.AllowWhen allowProxyHeadersWhen =
channelConfig.get(CommonChannelConfigKeys.allowProxyHeadersWhen);
this.stripInboundProxyHeadersHandler = new StripUntrustedProxyHeadersHandler(allowProxyHeadersWhen);
this.rateLimitingChannelHandler = channelDependencies
.get(ZuulDependencyKeys.rateLimitingChannelHandlerProvider)
.get();
this.sslClientCertCheckChannelHandler = channelDependencies
.get(ZuulDependencyKeys.sslClientCertCheckChannelHandlerProvider)
.get();
this.passportLoggingHandler = new PassportLoggingHandler(registry);
this.sessionContextDecorator = channelDependencies.get(ZuulDependencyKeys.sessionCtxDecorator);
this.requestCompleteHandler = channelDependencies.get(ZuulDependencyKeys.requestCompleteHandler);
this.httpRequestReadTimeoutCounter = channelDependencies.get(ZuulDependencyKeys.httpRequestReadTimeoutCounter);
this.filterLoader = channelDependencies.get(ZuulDependencyKeys.filterLoader);
this.filterUsageNotifier = channelDependencies.get(ZuulDependencyKeys.filterUsageNotifier);
this.sourceAddressChannelHandler = new SourceAddressChannelHandler();
}
protected void storeChannel(Channel ch) {
this.channels.add(ch);
// Also add the ChannelConfig as an attribute on each channel. So interested filters/channel-handlers can
// introspect
// and potentially act differently based on the config.
ch.attr(ATTR_CHANNEL_CONFIG).set(channelConfig);
}
protected void addPassportHandler(ChannelPipeline pipeline) {
pipeline.addLast(new ServerStateHandler.InboundHandler(registry, "http-" + metricId));
pipeline.addLast(new ServerStateHandler.OutboundHandler(registry));
}
protected void addTcpRelatedHandlers(ChannelPipeline pipeline) {
pipeline.addLast(sourceAddressChannelHandler);
pipeline.addLast(perEventLoopConnectionMetricsHandler);
new ElbProxyProtocolChannelHandler(registry, withProxyProtocol).addProxyProtocol(pipeline);
pipeline.addLast(maxConnectionsHandler);
}
protected void addHttp1Handlers(ChannelPipeline pipeline) {
pipeline.addLast(HTTP_CODEC_HANDLER_NAME, createHttpServerCodec());
pipeline.addLast(new Http1ConnectionCloseHandler());
pipeline.addLast(
"conn_expiry_handler",
new Http1ConnectionExpiryHandler(
maxRequestsPerConnection, maxRequestsPerConnectionInBrownout, connectionExpiry));
}
protected HttpServerCodec createHttpServerCodec() {
return new HttpServerCodec(MAX_INITIAL_LINE_LENGTH.get(), MAX_HEADER_SIZE.get(), MAX_CHUNK_SIZE.get(), false);
}
protected void addHttpRelatedHandlers(ChannelPipeline pipeline) {
pipeline.addLast(new PassportStateHttpServerHandler.InboundHandler());
pipeline.addLast(new PassportStateHttpServerHandler.OutboundHandler());
if (httpRequestReadTimeout > -1) {
HttpRequestReadTimeoutHandler.addLast(
pipeline, httpRequestReadTimeout, TimeUnit.MILLISECONDS, httpRequestReadTimeoutCounter);
}
pipeline.addLast(new HttpServerLifecycleChannelHandler.HttpServerLifecycleInboundChannelHandler());
pipeline.addLast(new HttpServerLifecycleChannelHandler.HttpServerLifecycleOutboundChannelHandler());
pipeline.addLast(new HttpBodySizeRecordingChannelHandler.InboundChannelHandler());
pipeline.addLast(new HttpBodySizeRecordingChannelHandler.OutboundChannelHandler());
pipeline.addLast(httpMetricsHandler);
pipeline.addLast(perEventLoopRequestsMetricsHandler);
if (accessLogPublisher != null) {
pipeline.addLast(new AccessLogChannelHandler.AccessLogInboundChannelHandler(accessLogPublisher));
pipeline.addLast(new AccessLogChannelHandler.AccessLogOutboundChannelHandler());
}
pipeline.addLast(stripInboundProxyHeadersHandler);
if (rateLimitingChannelHandler != null) {
pipeline.addLast(rateLimitingChannelHandler);
}
// pipeline.addLast(requestRejectedChannelHandler);
}
protected void addTimeoutHandlers(ChannelPipeline pipeline) {
pipeline.addLast(new IdleStateHandler(0, 0, idleTimeout, TimeUnit.MILLISECONDS));
pipeline.addLast(new CloseOnIdleStateHandler(registry, metricId));
}
protected void addSslInfoHandlers(ChannelPipeline pipeline, boolean isSSlFromIntermediary) {
pipeline.addLast("ssl_info", new SslHandshakeInfoHandler(registry, isSSlFromIntermediary));
pipeline.addLast("ssl_exceptions", new SslExceptionsHandler(registry));
}
protected void addSslClientCertChecks(ChannelPipeline pipeline) {
if (channelConfig.get(ZuulDependencyKeys.SSL_CLIENT_CERT_CHECK_REQUIRED)) {
if (this.sslClientCertCheckChannelHandler == null) {
throw new IllegalArgumentException("A sslClientCertCheckChannelHandler is required!");
}
pipeline.addLast(this.sslClientCertCheckChannelHandler);
}
}
protected void addZuulHandlers(final ChannelPipeline pipeline) {
pipeline.addLast("logger", nettyLogger);
pipeline.addLast(new ClientRequestReceiver(sessionContextDecorator));
pipeline.addLast(passportLoggingHandler);
addZuulFilterChainHandler(pipeline);
pipeline.addLast(new ClientResponseWriter(requestCompleteHandler, registry));
}
protected void addZuulFilterChainHandler(final ChannelPipeline pipeline) {
final ZuulFilter<HttpResponseMessage, HttpResponseMessage>[] responseFilters = getFilters(
new OutboundPassportStampingFilter(PassportState.FILTERS_OUTBOUND_START),
new OutboundPassportStampingFilter(PassportState.FILTERS_OUTBOUND_END));
// response filter chain
final ZuulFilterChainRunner<HttpResponseMessage> responseFilterChain =
getFilterChainRunner(responseFilters, filterUsageNotifier);
// endpoint | response filter chain
final FilterRunner<HttpRequestMessage, HttpResponseMessage> endPoint =
getEndpointRunner(responseFilterChain, filterUsageNotifier, filterLoader);
final ZuulFilter<HttpRequestMessage, HttpRequestMessage>[] requestFilters = getFilters(
new InboundPassportStampingFilter(PassportState.FILTERS_INBOUND_START),
new InboundPassportStampingFilter(PassportState.FILTERS_INBOUND_END));
// request filter chain | end point | response filter chain
final ZuulFilterChainRunner<HttpRequestMessage> requestFilterChain =
getFilterChainRunner(requestFilters, filterUsageNotifier, endPoint);
pipeline.addLast(new ZuulFilterChainHandler(requestFilterChain, responseFilterChain));
}
protected ZuulEndPointRunner getEndpointRunner(
ZuulFilterChainRunner<HttpResponseMessage> responseFilterChain,
FilterUsageNotifier filterUsageNotifier,
FilterLoader filterLoader) {
return new ZuulEndPointRunner(filterUsageNotifier, filterLoader, responseFilterChain, registry);
}
protected <T extends ZuulMessage> ZuulFilterChainRunner<T> getFilterChainRunner(
ZuulFilter<T, T>[] filters, FilterUsageNotifier filterUsageNotifier) {
return new ZuulFilterChainRunner<>(filters, filterUsageNotifier, registry);
}
protected <T extends ZuulMessage, R extends ZuulMessage> ZuulFilterChainRunner<T> getFilterChainRunner(
ZuulFilter<T, T>[] filters, FilterUsageNotifier filterUsageNotifier, FilterRunner<T, R> filterRunner) {
return new ZuulFilterChainRunner<>(filters, filterUsageNotifier, filterRunner, registry);
}
@SuppressWarnings("unchecked") // For the conversion from getFiltersByType. It's not safe, sorry.
public <T extends ZuulMessage> ZuulFilter<T, T>[] getFilters(ZuulFilter<T, T> start, ZuulFilter<T, T> stop) {
final SortedSet<ZuulFilter<?, ?>> zuulFilters = filterLoader.getFiltersByType(start.filterType());
final ZuulFilter<T, T>[] filters = new ZuulFilter[zuulFilters.size() + 2];
filters[0] = start;
int i = 1;
for (ZuulFilter<?, ?> filter : zuulFilters) {
// TODO(carl-mastrangelo): find some way to make this cast not needed.
filters[i++] = (ZuulFilter<T, T>) filter;
}
filters[filters.length - 1] = stop;
return filters;
}
}
| 6,357 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/BaseServerStartup.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.netty.server;
import com.google.errorprone.annotations.ForOverride;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.config.ChainedDynamicProperty;
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicIntProperty;
import com.netflix.discovery.EurekaClient;
import com.netflix.netty.common.accesslog.AccessLogPublisher;
import com.netflix.netty.common.channel.config.ChannelConfig;
import com.netflix.netty.common.channel.config.ChannelConfigValue;
import com.netflix.netty.common.channel.config.CommonChannelConfigKeys;
import com.netflix.netty.common.metrics.EventLoopGroupMetrics;
import com.netflix.netty.common.proxyprotocol.StripUntrustedProxyHeadersHandler;
import com.netflix.netty.common.ssl.ServerSslConfig;
import com.netflix.netty.common.status.ServerStatusManager;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import com.netflix.zuul.FilterLoader;
import com.netflix.zuul.FilterUsageNotifier;
import com.netflix.zuul.RequestCompleteHandler;
import com.netflix.zuul.context.SessionContextDecorator;
import com.netflix.zuul.netty.ratelimiting.NullChannelHandlerProvider;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.ssl.SslContext;
import io.netty.util.AsyncMapping;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Map;
public abstract class BaseServerStartup {
protected static final Logger LOG = LoggerFactory.getLogger(BaseServerStartup.class);
protected final ServerStatusManager serverStatusManager;
protected final Registry registry;
@SuppressWarnings("unused") // force initialization
protected final DirectMemoryMonitor directMemoryMonitor;
protected final EventLoopGroupMetrics eventLoopGroupMetrics;
protected final EventLoopConfig eventLoopConfig;
protected final EurekaClient discoveryClient;
protected final ApplicationInfoManager applicationInfoManager;
protected final AccessLogPublisher accessLogPublisher;
protected final SessionContextDecorator sessionCtxDecorator;
protected final RequestCompleteHandler reqCompleteHandler;
protected final FilterLoader filterLoader;
protected final FilterUsageNotifier usageNotifier;
private Map<NamedSocketAddress, ? extends ChannelInitializer<?>> addrsToChannelInitializers;
private ClientConnectionsShutdown clientConnectionsShutdown;
private Server server;
@Inject
public BaseServerStartup(
ServerStatusManager serverStatusManager,
FilterLoader filterLoader,
SessionContextDecorator sessionCtxDecorator,
FilterUsageNotifier usageNotifier,
RequestCompleteHandler reqCompleteHandler,
Registry registry,
DirectMemoryMonitor directMemoryMonitor,
EventLoopGroupMetrics eventLoopGroupMetrics,
EventLoopConfig eventLoopConfig,
EurekaClient discoveryClient,
ApplicationInfoManager applicationInfoManager,
AccessLogPublisher accessLogPublisher) {
this.serverStatusManager = serverStatusManager;
this.registry = registry;
this.directMemoryMonitor = directMemoryMonitor;
this.eventLoopGroupMetrics = eventLoopGroupMetrics;
this.eventLoopConfig = eventLoopConfig;
this.discoveryClient = discoveryClient;
this.applicationInfoManager = applicationInfoManager;
this.accessLogPublisher = accessLogPublisher;
this.sessionCtxDecorator = sessionCtxDecorator;
this.reqCompleteHandler = reqCompleteHandler;
this.filterLoader = filterLoader;
this.usageNotifier = usageNotifier;
}
public Server server() {
return server;
}
@Inject
public void init() throws Exception {
ChannelGroup clientChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
clientConnectionsShutdown =
new ClientConnectionsShutdown(clientChannels, GlobalEventExecutor.INSTANCE, discoveryClient);
addrsToChannelInitializers = chooseAddrsAndChannels(clientChannels);
server = new Server(
registry,
serverStatusManager,
addrsToChannelInitializers,
clientConnectionsShutdown,
eventLoopGroupMetrics,
eventLoopConfig);
}
// TODO(carl-mastrangelo): remove this after 2.1.7
/**
* Use {@link #chooseAddrsAndChannels(ChannelGroup)} instead.
*/
@Deprecated
protected Map<Integer, ChannelInitializer> choosePortsAndChannels(ChannelGroup clientChannels) {
throw new UnsupportedOperationException("unimplemented");
}
@ForOverride
protected Map<NamedSocketAddress, ChannelInitializer<?>> chooseAddrsAndChannels(ChannelGroup clientChannels) {
@SuppressWarnings("unchecked") // Channel init map has the wrong generics and we can't fix without api breakage.
Map<Integer, ChannelInitializer<?>> portMap =
(Map<Integer, ChannelInitializer<?>>) (Map) choosePortsAndChannels(clientChannels);
return Server.convertPortMap(portMap);
}
protected ChannelConfig defaultChannelDependencies(String listenAddressName) {
ChannelConfig channelDependencies = new ChannelConfig();
addChannelDependencies(channelDependencies, listenAddressName);
return channelDependencies;
}
protected void addChannelDependencies(
ChannelConfig channelDeps,
@SuppressWarnings("unused") String listenAddressName) { // listenAddressName is used by subclasses
channelDeps.set(ZuulDependencyKeys.registry, registry);
channelDeps.set(ZuulDependencyKeys.applicationInfoManager, applicationInfoManager);
channelDeps.set(ZuulDependencyKeys.serverStatusManager, serverStatusManager);
channelDeps.set(ZuulDependencyKeys.accessLogPublisher, accessLogPublisher);
channelDeps.set(ZuulDependencyKeys.sessionCtxDecorator, sessionCtxDecorator);
channelDeps.set(ZuulDependencyKeys.requestCompleteHandler, reqCompleteHandler);
final Counter httpRequestReadTimeoutCounter = registry.counter("server.http.request.read.timeout");
channelDeps.set(ZuulDependencyKeys.httpRequestReadTimeoutCounter, httpRequestReadTimeoutCounter);
channelDeps.set(ZuulDependencyKeys.filterLoader, filterLoader);
channelDeps.set(ZuulDependencyKeys.filterUsageNotifier, usageNotifier);
channelDeps.set(ZuulDependencyKeys.eventLoopGroupMetrics, eventLoopGroupMetrics);
channelDeps.set(ZuulDependencyKeys.sslClientCertCheckChannelHandlerProvider, new NullChannelHandlerProvider());
channelDeps.set(ZuulDependencyKeys.rateLimitingChannelHandlerProvider, new NullChannelHandlerProvider());
}
/**
* First looks for a property specific to the named listen address of the form -
* "server.${addrName}.${propertySuffix}". If none found, then looks for a server-wide property of the form -
* "server.${propertySuffix}". If that is also not found, then returns the specified default value.
*/
public static int chooseIntChannelProperty(String listenAddressName, String propertySuffix, int defaultValue) {
String globalPropertyName = "server." + propertySuffix;
String listenAddressPropertyName = "server." + listenAddressName + "." + propertySuffix;
Integer value = new DynamicIntProperty(listenAddressPropertyName, -999).get();
if (value == -999) {
value = new DynamicIntProperty(globalPropertyName, -999).get();
if (value == -999) {
value = defaultValue;
}
}
return value;
}
public static boolean chooseBooleanChannelProperty(
String listenAddressName, String propertySuffix, boolean defaultValue) {
String globalPropertyName = "server." + propertySuffix;
String listenAddressPropertyName = "server." + listenAddressName + "." + propertySuffix;
Boolean value = new ChainedDynamicProperty.DynamicBooleanPropertyThatSupportsNull(
listenAddressPropertyName, null)
.get();
if (value == null) {
value = new DynamicBooleanProperty(globalPropertyName, defaultValue)
.getDynamicProperty()
.getBoolean();
if (value == null) {
value = defaultValue;
}
}
return value;
}
public static ChannelConfig defaultChannelConfig(String listenAddressName) {
ChannelConfig config = new ChannelConfig();
config.add(new ChannelConfigValue<>(
CommonChannelConfigKeys.maxConnections,
chooseIntChannelProperty(
listenAddressName, "connection.max", CommonChannelConfigKeys.maxConnections.defaultValue())));
config.add(new ChannelConfigValue<>(
CommonChannelConfigKeys.maxRequestsPerConnection,
chooseIntChannelProperty(listenAddressName, "connection.max.requests", 20000)));
config.add(new ChannelConfigValue<>(
CommonChannelConfigKeys.maxRequestsPerConnectionInBrownout,
chooseIntChannelProperty(
listenAddressName,
"connection.max.requests.brownout",
CommonChannelConfigKeys.maxRequestsPerConnectionInBrownout.defaultValue())));
config.add(new ChannelConfigValue<>(
CommonChannelConfigKeys.connectionExpiry,
chooseIntChannelProperty(
listenAddressName,
"connection.expiry",
CommonChannelConfigKeys.connectionExpiry.defaultValue())));
config.add(new ChannelConfigValue<>(
CommonChannelConfigKeys.httpRequestReadTimeout,
chooseIntChannelProperty(
listenAddressName,
"http.request.read.timeout",
CommonChannelConfigKeys.httpRequestReadTimeout.defaultValue())));
int connectionIdleTimeout = chooseIntChannelProperty(
listenAddressName, "connection.idle.timeout", CommonChannelConfigKeys.idleTimeout.defaultValue());
config.add(new ChannelConfigValue<>(CommonChannelConfigKeys.idleTimeout, connectionIdleTimeout));
config.add(new ChannelConfigValue<>(
CommonChannelConfigKeys.serverTimeout, new ServerTimeout(connectionIdleTimeout)));
// For security, default to NEVER allowing XFF/Proxy headers from client.
config.add(new ChannelConfigValue<>(
CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER));
config.set(CommonChannelConfigKeys.withProxyProtocol, true);
config.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true);
config.add(new ChannelConfigValue<>(
CommonChannelConfigKeys.connCloseDelay,
chooseIntChannelProperty(
listenAddressName,
"connection.close.delay",
CommonChannelConfigKeys.connCloseDelay.defaultValue())));
return config;
}
public static void addHttp2DefaultConfig(ChannelConfig config, String listenAddressName) {
config.add(new ChannelConfigValue<>(
CommonChannelConfigKeys.maxConcurrentStreams,
chooseIntChannelProperty(
listenAddressName,
"http2.max.concurrent.streams",
CommonChannelConfigKeys.maxConcurrentStreams.defaultValue())));
config.add(new ChannelConfigValue<>(
CommonChannelConfigKeys.initialWindowSize,
chooseIntChannelProperty(
listenAddressName,
"http2.initialwindowsize",
CommonChannelConfigKeys.initialWindowSize.defaultValue())));
config.add(new ChannelConfigValue<>(
CommonChannelConfigKeys.maxHttp2HeaderTableSize,
chooseIntChannelProperty(listenAddressName, "http2.maxheadertablesize", 65536)));
config.add(new ChannelConfigValue<>(
CommonChannelConfigKeys.maxHttp2HeaderListSize,
chooseIntChannelProperty(listenAddressName, "http2.maxheaderlistsize", 32768)));
// Override this to a lower value, as we'll be using ELB TCP listeners for h2, and therefore the connection
// is direct from each device rather than shared in an ELB pool.
config.add(new ChannelConfigValue<>(
CommonChannelConfigKeys.maxRequestsPerConnection,
chooseIntChannelProperty(listenAddressName, "connection.max.requests", 4000)));
config.add(new ChannelConfigValue<>(
CommonChannelConfigKeys.http2AllowGracefulDelayed,
chooseBooleanChannelProperty(listenAddressName, "connection.close.graceful.delayed.allow", true)));
config.add(new ChannelConfigValue<>(
CommonChannelConfigKeys.http2SwallowUnknownExceptionsOnConnClose,
chooseBooleanChannelProperty(listenAddressName, "connection.close.swallow.unknown.exceptions", false)));
}
// TODO(carl-mastrangelo): remove this after 2.1.7
/**
* Use {@link #logAddrConfigured(SocketAddress)} instead.
*/
@Deprecated
protected void logPortConfigured(int port) {
logAddrConfigured(new InetSocketAddress(port));
}
// TODO(carl-mastrangelo): remove this after 2.1.7
/**
* Use {@link #logAddrConfigured(SocketAddress, ServerSslConfig)} instead.
*/
@Deprecated
protected void logPortConfigured(int port, ServerSslConfig serverSslConfig) {
logAddrConfigured(new InetSocketAddress(port), serverSslConfig);
}
// TODO(carl-mastrangelo): remove this after 2.1.7
/**
* Use {@link #logAddrConfigured(SocketAddress, AsyncMapping)} instead.
*/
@Deprecated
protected void logPortConfigured(int port, AsyncMapping<String, SslContext> sniMapping) {
logAddrConfigured(new InetSocketAddress(port), sniMapping);
}
protected final void logAddrConfigured(SocketAddress socketAddress) {
LOG.info("Configured address: {}", socketAddress);
}
protected final void logAddrConfigured(SocketAddress socketAddress, @Nullable ServerSslConfig serverSslConfig) {
String msg = "Configured address: " + socketAddress;
if (serverSslConfig != null) {
msg = msg + " with SSL config: " + serverSslConfig;
}
LOG.info(msg);
}
protected final void logAddrConfigured(
SocketAddress socketAddress, @Nullable AsyncMapping<String, SslContext> sniMapping) {
String msg = "Configured address: " + socketAddress;
if (sniMapping != null) {
msg = msg + " with SNI config: " + sniMapping;
}
LOG.info(msg);
}
protected final void logSecureAddrConfigured(SocketAddress socketAddress, @Nullable Object securityConfig) {
LOG.info("Configured address: {} with security config {}", socketAddress, securityConfig);
}
}
| 6,358 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/ssl/SslHandshakeInfoHandler.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.netty.server.ssl;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.netflix.netty.common.SourceAddressChannelHandler;
import com.netflix.netty.common.ssl.SslHandshakeInfo;
import com.netflix.spectator.api.NoopRegistry;
import com.netflix.spectator.api.Registry;
import com.netflix.zuul.netty.ChannelUtils;
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.handler.ssl.ClientAuth;
import io.netty.handler.ssl.SniCompletionEvent;
import io.netty.handler.ssl.SslCloseCompletionEvent;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.SslHandshakeCompletionEvent;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import java.nio.channels.ClosedChannelException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Stores info about the client and server's SSL certificates in the context, after a successful handshake.
* <p>
* User: michaels@netflix.com Date: 3/29/16 Time: 10:48 AM
*/
public class SslHandshakeInfoHandler extends ChannelInboundHandlerAdapter {
public static final AttributeKey<SslHandshakeInfo> ATTR_SSL_INFO = AttributeKey.newInstance("_ssl_handshake_info");
private static final Logger logger = LoggerFactory.getLogger(SslHandshakeInfoHandler.class);
// extracts reason string from SSL errors formatted in the open ssl style
// error:[error code]:[library name]:OPENSSL_internal:[reason string]
// see https://github.com/google/boringssl/blob/d206f3db6ac2b74e8949ddd9947b94a5424d6a1d/include/openssl/err.h#L231
private static final Pattern OPEN_SSL_PATTERN = Pattern.compile("OPENSSL_internal:(.+)");
private final Registry spectatorRegistry;
private final boolean isSSlFromIntermediary;
public SslHandshakeInfoHandler(Registry spectatorRegistry, boolean isSSlFromIntermediary) {
this.spectatorRegistry = Preconditions.checkNotNull(spectatorRegistry);
this.isSSlFromIntermediary = isSSlFromIntermediary;
}
@VisibleForTesting
SslHandshakeInfoHandler() {
spectatorRegistry = new NoopRegistry();
isSSlFromIntermediary = false;
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof SslHandshakeCompletionEvent) {
try {
SslHandshakeCompletionEvent sslEvent = (SslHandshakeCompletionEvent) evt;
if (sslEvent.isSuccess()) {
CurrentPassport.fromChannel(ctx.channel()).add(PassportState.SERVER_CH_SSL_HANDSHAKE_COMPLETE);
SslHandler sslhandler = ctx.channel().pipeline().get(SslHandler.class);
SSLSession session = sslhandler.engine().getSession();
ClientAuth clientAuth = whichClientAuthEnum(sslhandler);
Certificate serverCert = null;
X509Certificate peerCert = null;
if ((clientAuth == ClientAuth.REQUIRE || clientAuth == ClientAuth.OPTIONAL)
&& session.getPeerCertificates() != null
&& session.getPeerCertificates().length > 0) {
peerCert = (X509Certificate) session.getPeerCertificates()[0];
}
if (session.getLocalCertificates() != null && session.getLocalCertificates().length > 0) {
serverCert = session.getLocalCertificates()[0];
}
SslHandshakeInfo info = new SslHandshakeInfo(
isSSlFromIntermediary,
session.getProtocol(),
session.getCipherSuite(),
clientAuth,
serverCert,
peerCert);
ctx.channel().attr(ATTR_SSL_INFO).set(info);
// Metrics.
incrementCounters(sslEvent, info);
logger.debug("Successful SSL Handshake: {}", info);
} else {
String clientIP = ctx.channel()
.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS)
.get();
Throwable cause = sslEvent.cause();
PassportState passportState =
CurrentPassport.fromChannel(ctx.channel()).getState();
if (cause instanceof ClosedChannelException
&& (PassportState.SERVER_CH_INACTIVE.equals(passportState)
|| PassportState.SERVER_CH_IDLE_TIMEOUT.equals(passportState))) {
// Either client closed the connection without/before having completed a handshake, or
// the connection idle timed-out before handshake.
// NOTE: we were seeing a lot of these in prod and can repro by just telnetting to port and then
// closing terminal
// without sending anything.
// So don't treat these as SSL handshake failures.
logger.debug(
"Client closed connection or it idle timed-out without doing an ssl handshake. , client_ip = {}, channel_info = {}",
clientIP,
ChannelUtils.channelInfoForLogging(ctx.channel()));
} else if (cause instanceof SSLException
&& cause.getMessage().contains("handshake timed out")) {
logger.debug(
"Client timed-out doing the ssl handshake. , client_ip = {}, channel_info = {}",
clientIP,
ChannelUtils.channelInfoForLogging(ctx.channel()));
} else if (cause instanceof SSLException
&& cause.getMessage().contains("failure when writing TLS control frames")) {
// This can happen if the ClientHello is sent followed by a RST packet, before we can respond.
logger.debug(
"Client terminated handshake early., client_ip = {}, channel_info = {}",
clientIP,
ChannelUtils.channelInfoForLogging(ctx.channel()));
} else {
if (logger.isDebugEnabled()) {
String msg = "Unsuccessful SSL Handshake: " + sslEvent
+ ", client_ip = " + clientIP
+ ", channel_info = " + ChannelUtils.channelInfoForLogging(ctx.channel())
+ ", error = " + cause;
if (cause instanceof ClosedChannelException) {
logger.debug(msg);
} else {
logger.debug(msg, cause);
}
}
incrementCounters(sslEvent, null);
}
}
} catch (Throwable e) {
logger.warn("Error getting the SSL handshake info.", e);
} finally {
// Now remove this handler from the pipeline as no longer needed once the ssl handshake has completed.
ctx.pipeline().remove(this);
}
} else if (evt instanceof SslCloseCompletionEvent) {
// TODO - increment a separate metric for this event?
} else if (evt instanceof SniCompletionEvent) {
logger.debug("SNI Parsing Complete: {}", evt);
SniCompletionEvent sniCompletionEvent = (SniCompletionEvent) evt;
if (sniCompletionEvent.isSuccess()) {
spectatorRegistry.counter("zuul.sni.parse.success").increment();
} else {
Throwable cause = sniCompletionEvent.cause();
spectatorRegistry
.counter("zuul.sni.parse.failure", "cause", cause != null ? cause.getMessage() : "UNKNOWN")
.increment();
}
}
super.userEventTriggered(ctx, evt);
}
private ClientAuth whichClientAuthEnum(SslHandler sslhandler) {
ClientAuth clientAuth;
if (sslhandler.engine().getNeedClientAuth()) {
clientAuth = ClientAuth.REQUIRE;
} else if (sslhandler.engine().getWantClientAuth()) {
clientAuth = ClientAuth.OPTIONAL;
} else {
clientAuth = ClientAuth.NONE;
}
return clientAuth;
}
private void incrementCounters(
SslHandshakeCompletionEvent sslHandshakeCompletionEvent, SslHandshakeInfo handshakeInfo) {
try {
if (sslHandshakeCompletionEvent.isSuccess()) {
String proto = handshakeInfo.getProtocol().length() > 0 ? handshakeInfo.getProtocol() : "unknown";
String ciphsuite =
handshakeInfo.getCipherSuite().length() > 0 ? handshakeInfo.getCipherSuite() : "unknown";
spectatorRegistry
.counter(
"server.ssl.handshake",
"success",
"true",
"protocol",
proto,
"ciphersuite",
ciphsuite,
"clientauth",
String.valueOf(handshakeInfo.getClientAuthRequirement()))
.increment();
} else {
spectatorRegistry
.counter(
"server.ssl.handshake",
"success",
"false",
"failure_cause",
getFailureCause(sslHandshakeCompletionEvent.cause()))
.increment();
}
} catch (Exception e) {
logger.error("Error incrementing counters for SSL handshake!", e);
}
}
@VisibleForTesting
String getFailureCause(Throwable throwable) {
String message = throwable.getMessage();
if (message == null) {
return throwable.toString();
}
Matcher matcher = OPEN_SSL_PATTERN.matcher(message);
return matcher.find() ? matcher.group(1) : message;
}
}
| 6,359 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2ResetFrameHandler.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.netty.server.http2;
import com.netflix.zuul.netty.RequestCancelledEvent;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http2.Http2ResetFrame;
import io.netty.util.ReferenceCountUtil;
/**
* User: michaels@netflix.com
* Date: 4/13/17
* Time: 6:02 PM
*/
@ChannelHandler.Sharable
public class Http2ResetFrameHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof Http2ResetFrame) {
// Inform zuul to cancel the request.
ctx.fireUserEventTriggered(new RequestCancelledEvent());
ReferenceCountUtil.safeRelease(msg);
} else {
super.channelRead(ctx, msg);
}
}
}
| 6,360 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2OrHttpHandler.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.netty.server.http2;
import com.netflix.netty.common.channel.config.ChannelConfig;
import com.netflix.netty.common.channel.config.CommonChannelConfigKeys;
import com.netflix.netty.common.http2.DynamicHttp2FrameLogger;
import com.netflix.zuul.netty.server.BaseZuulChannelInitializer;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http2.DefaultHttp2RemoteFlowController;
import io.netty.handler.codec.http2.Http2Connection;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.codec.http2.UniformStreamByteDistributor;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.ssl.ApplicationProtocolNames;
import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler;
import io.netty.util.AttributeKey;
import java.util.function.Consumer;
/**
* Http2 Or Http Handler
*
* Author: Arthur Gonigberg
* Date: December 15, 2017
*/
public class Http2OrHttpHandler extends ApplicationProtocolNegotiationHandler {
public static final AttributeKey<String> PROTOCOL_NAME = AttributeKey.valueOf("protocol_name");
private static final DynamicHttp2FrameLogger FRAME_LOGGER =
new DynamicHttp2FrameLogger(LogLevel.DEBUG, Http2FrameCodec.class);
private final ChannelHandler http2StreamHandler;
private final int maxConcurrentStreams;
private final int initialWindowSize;
private final long maxHeaderTableSize;
private final long maxHeaderListSize;
private final Consumer<ChannelPipeline> addHttpHandlerFn;
public Http2OrHttpHandler(
ChannelHandler http2StreamHandler,
ChannelConfig channelConfig,
Consumer<ChannelPipeline> addHttpHandlerFn) {
super(ApplicationProtocolNames.HTTP_1_1);
this.http2StreamHandler = http2StreamHandler;
this.maxConcurrentStreams = channelConfig.get(CommonChannelConfigKeys.maxConcurrentStreams);
this.initialWindowSize = channelConfig.get(CommonChannelConfigKeys.initialWindowSize);
this.maxHeaderTableSize = channelConfig.get(CommonChannelConfigKeys.maxHttp2HeaderTableSize);
this.maxHeaderListSize = channelConfig.get(CommonChannelConfigKeys.maxHttp2HeaderListSize);
this.addHttpHandlerFn = addHttpHandlerFn;
}
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
ctx.channel().attr(PROTOCOL_NAME).set("HTTP/2");
configureHttp2(ctx.pipeline());
return;
}
if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
ctx.channel().attr(PROTOCOL_NAME).set("HTTP/1.1");
configureHttp1(ctx.pipeline());
return;
}
throw new IllegalStateException("unknown protocol: " + protocol);
}
private void configureHttp2(ChannelPipeline pipeline) {
// setup the initial stream settings for the server to use.
Http2Settings settings = new Http2Settings()
.maxConcurrentStreams(maxConcurrentStreams)
.initialWindowSize(initialWindowSize)
.headerTableSize(maxHeaderTableSize)
.maxHeaderListSize(maxHeaderListSize);
Http2FrameCodec frameCodec = Http2FrameCodecBuilder.forServer()
.frameLogger(FRAME_LOGGER)
.initialSettings(settings)
.validateHeaders(true)
.build();
Http2Connection conn = frameCodec.connection();
// Use the uniform byte distributor until https://github.com/netty/netty/issues/10525 is fixed.
conn.remote()
.flowController(new DefaultHttp2RemoteFlowController(conn, new UniformStreamByteDistributor(conn)));
Http2MultiplexHandler multiplexHandler = new Http2MultiplexHandler(http2StreamHandler);
// The frame codec MUST be in the pipeline.
pipeline.addBefore("codec_placeholder", /* name= */ null, frameCodec);
pipeline.replace("codec_placeholder", BaseZuulChannelInitializer.HTTP_CODEC_HANDLER_NAME, multiplexHandler);
}
private void configureHttp1(ChannelPipeline pipeline) {
addHttpHandlerFn.accept(pipeline);
}
}
| 6,361 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/DummyChannelHandler.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.netty.server.http2;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
/**
* Dummy Channel Handler
*
* Author: Arthur Gonigberg
* Date: December 15, 2017
*/
public class DummyChannelHandler implements ChannelHandler {
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {}
}
| 6,362 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2SslChannelInitializer.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.netty.server.http2;
import com.google.common.base.Preconditions;
import com.netflix.netty.common.Http2ConnectionCloseHandler;
import com.netflix.netty.common.Http2ConnectionExpiryHandler;
import com.netflix.netty.common.SwallowSomeHttp2ExceptionsHandler;
import com.netflix.netty.common.channel.config.ChannelConfig;
import com.netflix.netty.common.channel.config.CommonChannelConfigKeys;
import com.netflix.netty.common.metrics.Http2MetricsChannelHandlers;
import com.netflix.netty.common.ssl.ServerSslConfig;
import com.netflix.zuul.logging.Http2FrameLoggingPerClientIpHandler;
import com.netflix.zuul.netty.server.BaseZuulChannelInitializer;
import com.netflix.zuul.netty.ssl.SslContextFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* User: Mike Smith
* Date: 3/5/16
* Time: 5:41 PM
*/
public final class Http2SslChannelInitializer extends BaseZuulChannelInitializer {
private static final Logger LOG = LoggerFactory.getLogger(Http2SslChannelInitializer.class);
private static final DummyChannelHandler DUMMY_HANDLER = new DummyChannelHandler();
private final ServerSslConfig serverSslConfig;
private final SslContext sslContext;
private final boolean isSSlFromIntermediary;
private final SwallowSomeHttp2ExceptionsHandler swallowSomeHttp2ExceptionsHandler;
private final String metricId;
/**
* Use {@link #Http2SslChannelInitializer(String, ChannelConfig, ChannelConfig, ChannelGroup)} instead.
*/
@Deprecated
public Http2SslChannelInitializer(
int port, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) {
this(String.valueOf(port), channelConfig, channelDependencies, channels);
}
public Http2SslChannelInitializer(
String metricId, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) {
super(metricId, channelConfig, channelDependencies, channels);
this.metricId = Preconditions.checkNotNull(metricId, "metricId");
this.swallowSomeHttp2ExceptionsHandler = new SwallowSomeHttp2ExceptionsHandler(registry);
this.serverSslConfig = channelConfig.get(CommonChannelConfigKeys.serverSslConfig);
this.isSSlFromIntermediary = channelConfig.get(CommonChannelConfigKeys.isSSlFromIntermediary);
SslContextFactory sslContextFactory = channelConfig.get(CommonChannelConfigKeys.sslContextFactory);
sslContext = Http2Configuration.configureSSL(sslContextFactory, metricId);
}
@Override
protected void initChannel(Channel ch) throws Exception {
SslHandler sslHandler = sslContext.newHandler(ch.alloc());
sslHandler.engine().setEnabledProtocols(serverSslConfig.getProtocols());
// SSLParameters sslParameters = new SSLParameters();
// AlgorithmConstraints algoConstraints = new AlgorithmConstraints();
// sslParameters.setAlgorithmConstraints(algoConstraints);
// sslParameters.setUseCipherSuitesOrder(true);
// sslHandler.engine().setSSLParameters(sslParameters);
if (LOG.isDebugEnabled()) {
LOG.debug(
"ssl protocols supported: {}",
String.join(", ", sslHandler.engine().getSupportedProtocols()));
LOG.debug(
"ssl protocols enabled: {}",
String.join(", ", sslHandler.engine().getEnabledProtocols()));
LOG.debug(
"ssl ciphers supported: {}",
String.join(", ", sslHandler.engine().getSupportedCipherSuites()));
LOG.debug(
"ssl ciphers enabled: {}",
String.join(", ", sslHandler.engine().getEnabledCipherSuites()));
}
// Configure our pipeline of ChannelHandlerS.
ChannelPipeline pipeline = ch.pipeline();
storeChannel(ch);
addTimeoutHandlers(pipeline);
addPassportHandler(pipeline);
addTcpRelatedHandlers(pipeline);
pipeline.addLast(new Http2FrameLoggingPerClientIpHandler());
pipeline.addLast("ssl", sslHandler);
addSslInfoHandlers(pipeline, isSSlFromIntermediary);
addSslClientCertChecks(pipeline);
Http2MetricsChannelHandlers http2MetricsChannelHandlers =
new Http2MetricsChannelHandlers(registry, "server", "http2-" + metricId);
Http2ConnectionCloseHandler connectionCloseHandler = new Http2ConnectionCloseHandler(registry);
Http2ConnectionExpiryHandler connectionExpiryHandler = new Http2ConnectionExpiryHandler(
maxRequestsPerConnection, maxRequestsPerConnectionInBrownout, connectionExpiry);
pipeline.addLast(
"http2CodecSwapper",
new Http2OrHttpHandler(
new Http2StreamInitializer(
ch,
this::http1Handlers,
http2MetricsChannelHandlers,
connectionCloseHandler,
connectionExpiryHandler),
channelConfig,
cp -> {
http1Codec(cp);
http1Handlers(cp);
}));
pipeline.addLast("codec_placeholder", DUMMY_HANDLER);
pipeline.addLast(swallowSomeHttp2ExceptionsHandler);
}
protected void http1Handlers(ChannelPipeline pipeline) {
addHttpRelatedHandlers(pipeline);
addZuulHandlers(pipeline);
}
protected void http1Codec(ChannelPipeline pipeline) {
pipeline.replace("codec_placeholder", HTTP_CODEC_HANDLER_NAME, createHttpServerCodec());
}
}
| 6,363 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2StreamHeaderCleaner.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.netty.server.http2;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;
/**
* The Http2ServerDowngrader currently is always incorrectly setting the "x-http2-stream-id"
* header to "0", which is confusing. And as we don't actually need it and the other "x-http2-" headers, we
* strip them out here to avoid the confusion.
*
* Hopefully in a future netty release that header value will be correct and we can then
* stop doing this. Although potentially we _never_ want to pass these downstream to origins .... ?
*/
@ChannelHandler.Sharable
public class Http2StreamHeaderCleaner extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpRequest) {
HttpRequest req = (HttpRequest) msg;
for (String name : req.headers().names()) {
if (name.startsWith("x-http2-")) {
req.headers().remove(name);
}
}
}
super.channelRead(ctx, msg);
}
}
| 6,364 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2StreamErrorHandler.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.netty.server.http2;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2Exception;
/**
* Author: Susheel Aroskar
* Date: 5/7/2018
*/
@ChannelHandler.Sharable
public class Http2StreamErrorHandler extends ChannelInboundHandlerAdapter {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (cause instanceof Http2Exception.StreamException) {
Http2Exception.StreamException streamEx = (Http2Exception.StreamException) cause;
ctx.writeAndFlush(new DefaultHttp2ResetFrame(streamEx.error()));
} else if (cause instanceof DecoderException) {
ctx.writeAndFlush(new DefaultHttp2ResetFrame(Http2Error.PROTOCOL_ERROR));
} else {
super.exceptionCaught(ctx, cause);
}
}
}
| 6,365 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2ContentLengthEnforcingHandler.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.netty.server.http2;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.util.ReferenceCountUtil;
import java.util.List;
/**
* This class is only suitable for use on HTTP/2 child channels.
*/
public final class Http2ContentLengthEnforcingHandler extends ChannelInboundHandlerAdapter {
private static final long UNSET_CONTENT_LENGTH = -1;
private long expectedContentLength = UNSET_CONTENT_LENGTH;
private long seenContentLength;
/**
* This checks that the content length does what it says, preventing a client from causing Zuul to misinterpret the
* request. Because this class is meant to work in an HTTP/2 setting, the content length and transfer encoding
* checks are more semantics. In particular, this checks:
* <ul>
* <li>No duplicate Content length</li>
* <li>Content Length (if present) must always be greater than or equal to how much content has been seen</li>
* <li>Content Length (if present) must always be equal to how much content has been seen by the end</li>
* <li>Content Length cannot be present along with chunked transfer encoding.</li>
* </ul>
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpRequest) {
HttpRequest req = (HttpRequest) msg;
List<String> lengthHeaders = req.headers().getAll(HttpHeaderNames.CONTENT_LENGTH);
if (lengthHeaders.size() > 1) {
ctx.writeAndFlush(new DefaultHttp2ResetFrame(Http2Error.PROTOCOL_ERROR));
ReferenceCountUtil.safeRelease(msg);
return;
} else if (lengthHeaders.size() == 1) {
expectedContentLength = Long.parseLong(lengthHeaders.get(0));
if (expectedContentLength < 0) {
// TODO(carl-mastrangelo): this is not right, but meh. Fix this to return a proper 400.
ctx.writeAndFlush(new DefaultHttp2ResetFrame(Http2Error.PROTOCOL_ERROR));
ReferenceCountUtil.safeRelease(msg);
return;
}
}
if (hasContentLength() && HttpUtil.isTransferEncodingChunked(req)) {
// TODO(carl-mastrangelo): this is not right, but meh. Fix this to return a proper 400.
ctx.writeAndFlush(new DefaultHttp2ResetFrame(Http2Error.PROTOCOL_ERROR));
ReferenceCountUtil.safeRelease(msg);
return;
}
}
if (msg instanceof HttpContent) {
ByteBuf content = ((HttpContent) msg).content();
incrementSeenContent(content.readableBytes());
if (hasContentLength() && seenContentLength > expectedContentLength) {
// TODO(carl-mastrangelo): this is not right, but meh. Fix this to return a proper 400.
ctx.writeAndFlush(new DefaultHttp2ResetFrame(Http2Error.PROTOCOL_ERROR));
ReferenceCountUtil.safeRelease(msg);
return;
}
}
if (msg instanceof LastHttpContent) {
if (hasContentLength() && seenContentLength != expectedContentLength) {
// TODO(carl-mastrangelo): this is not right, but meh. Fix this to return a proper 400.
ctx.writeAndFlush(new DefaultHttp2ResetFrame(Http2Error.PROTOCOL_ERROR));
ReferenceCountUtil.safeRelease(msg);
return;
}
}
super.channelRead(ctx, msg);
}
private boolean hasContentLength() {
return expectedContentLength != UNSET_CONTENT_LENGTH;
}
private void incrementSeenContent(int length) {
seenContentLength = Math.addExact(seenContentLength, length);
}
}
| 6,366 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2Configuration.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.netty.server.http2;
import com.netflix.zuul.netty.ssl.SslContextFactory;
import io.netty.handler.ssl.ApplicationProtocolConfig;
import io.netty.handler.ssl.ApplicationProtocolNames;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import javax.net.ssl.SSLException;
public class Http2Configuration {
public static SslContext configureSSL(SslContextFactory sslContextFactory, String metricId) {
SslContextBuilder builder = sslContextFactory.createBuilderForServer();
String[] supportedProtocols = new String[] {ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1};
ApplicationProtocolConfig apn = new ApplicationProtocolConfig(
ApplicationProtocolConfig.Protocol.ALPN,
// NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
// ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
supportedProtocols);
final SslContext sslContext;
try {
sslContext = builder.applicationProtocolConfig(apn).build();
} catch (SSLException e) {
throw new RuntimeException("Error configuring SslContext with ALPN!", e);
}
// Enable TLS Session Tickets support.
sslContextFactory.enableSessionTickets(sslContext);
// Setup metrics tracking the OpenSSL stats.
sslContextFactory.configureOpenSslStatsMetrics(sslContext, metricId);
return sslContext;
}
/**
* This is meant to be use in cases where the server wishes not to advertise h2 as part of ALPN.
*/
public static SslContext configureSSLWithH2Disabled(SslContextFactory sslContextFactory, String host) {
ApplicationProtocolConfig apn = new ApplicationProtocolConfig(
ApplicationProtocolConfig.Protocol.ALPN,
// NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
// ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
ApplicationProtocolNames.HTTP_1_1);
final SslContext sslContext;
try {
sslContext = sslContextFactory
.createBuilderForServer()
.applicationProtocolConfig(apn)
.build();
} catch (SSLException e) {
throw new RuntimeException("Error configuring SslContext with ALPN!", e);
}
sslContextFactory.enableSessionTickets(sslContext);
sslContextFactory.configureOpenSslStatsMetrics(sslContext, host);
return sslContext;
}
}
| 6,367 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/http2/Http2StreamInitializer.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.netty.server.http2;
import com.netflix.netty.common.Http2ConnectionCloseHandler;
import com.netflix.netty.common.Http2ConnectionExpiryHandler;
import com.netflix.netty.common.SourceAddressChannelHandler;
import com.netflix.netty.common.metrics.Http2MetricsChannelHandlers;
import com.netflix.netty.common.proxyprotocol.HAProxyMessageChannelHandler;
import com.netflix.zuul.netty.server.BaseZuulChannelInitializer;
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.channel.ChannelPipeline;
import io.netty.handler.codec.http2.Http2StreamFrameToHttpObjectCodec;
import io.netty.util.AttributeKey;
import java.util.function.Consumer;
/**
* TODO - can this be done when we create the Http2StreamChannelBootstrap instead now?
*/
@ChannelHandler.Sharable
public class Http2StreamInitializer extends ChannelInboundHandlerAdapter {
private static final Http2StreamHeaderCleaner http2StreamHeaderCleaner = new Http2StreamHeaderCleaner();
private static final Http2ResetFrameHandler http2ResetFrameHandler = new Http2ResetFrameHandler();
private static final Http2StreamErrorHandler http2StreamErrorHandler = new Http2StreamErrorHandler();
private final Channel parent;
private final Consumer<ChannelPipeline> addHttpHandlerFn;
private final Http2MetricsChannelHandlers http2MetricsChannelHandlers;
private final Http2ConnectionCloseHandler connectionCloseHandler;
private final Http2ConnectionExpiryHandler connectionExpiryHandler;
public Http2StreamInitializer(
Channel parent,
Consumer<ChannelPipeline> addHttpHandlerFn,
Http2MetricsChannelHandlers http2MetricsChannelHandlers,
Http2ConnectionCloseHandler connectionCloseHandler,
Http2ConnectionExpiryHandler connectionExpiryHandler) {
this.parent = parent;
this.addHttpHandlerFn = addHttpHandlerFn;
this.http2MetricsChannelHandlers = http2MetricsChannelHandlers;
this.connectionCloseHandler = connectionCloseHandler;
this.connectionExpiryHandler = connectionExpiryHandler;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
copyAttrsFromParentChannel(this.parent, ctx.channel());
addHttp2StreamSpecificHandlers(ctx.pipeline());
addHttpHandlerFn.accept(ctx.pipeline());
ctx.pipeline().remove(this);
}
protected void addHttp2StreamSpecificHandlers(ChannelPipeline pipeline) {
pipeline.addLast("h2_metrics_inbound", http2MetricsChannelHandlers.inbound());
pipeline.addLast("h2_metrics_outbound", http2MetricsChannelHandlers.outbound());
pipeline.addLast("h2_max_requests_per_conn", connectionExpiryHandler);
pipeline.addLast("h2_conn_close", connectionCloseHandler);
pipeline.addLast(http2ResetFrameHandler);
pipeline.addLast("h2_downgrader", new Http2StreamFrameToHttpObjectCodec(true));
pipeline.addLast(http2StreamErrorHandler);
pipeline.addLast(http2StreamHeaderCleaner);
pipeline.addLast(new Http2ContentLengthEnforcingHandler());
}
protected void copyAttrsFromParentChannel(Channel parent, Channel child) {
AttributeKey[] attributesToCopy = {
SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS,
SourceAddressChannelHandler.ATTR_LOCAL_INET_ADDR,
SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS,
SourceAddressChannelHandler.ATTR_REMOTE_ADDR,
SourceAddressChannelHandler.ATTR_SOURCE_INET_ADDR,
SourceAddressChannelHandler.ATTR_SERVER_LOCAL_ADDRESS,
SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT,
SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS,
Http2OrHttpHandler.PROTOCOL_NAME,
SslHandshakeInfoHandler.ATTR_SSL_INFO,
HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE,
HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION,
BaseZuulChannelInitializer.ATTR_CHANNEL_CONFIG
};
for (AttributeKey key : attributesToCopy) {
copyAttrFromParentChannel(parent, child, key);
}
}
protected void copyAttrFromParentChannel(Channel parent, Channel child, AttributeKey key) {
child.attr(key).set(parent.attr(key).get());
}
}
| 6,368 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushConnection.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.netty.server.push;
import com.google.common.base.Charsets;
import com.netflix.config.CachedDynamicIntProperty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
/**
* Author: Susheel Aroskar
* Date:
*/
public class PushConnection {
private final PushProtocol pushProtocol;
private final ChannelHandlerContext ctx;
private String secureToken;
// Token bucket implementation state.
private double tkBktAllowance;
private long tkBktLastCheckTime;
public static final CachedDynamicIntProperty TOKEN_BUCKET_RATE =
new CachedDynamicIntProperty("zuul.push.tokenBucket.rate", 3);
public static final CachedDynamicIntProperty TOKEN_BUCKET_WINDOW =
new CachedDynamicIntProperty("zuul.push.tokenBucket.window.millis", 2000);
public PushConnection(PushProtocol pushProtocol, ChannelHandlerContext ctx) {
this.pushProtocol = pushProtocol;
this.ctx = ctx;
tkBktAllowance = TOKEN_BUCKET_RATE.get();
tkBktLastCheckTime = System.currentTimeMillis();
}
public String getSecureToken() {
return secureToken;
}
public void setSecureToken(String secureToken) {
this.secureToken = secureToken;
}
/**
* Implementation of TokenBucket algorithm to do rate limiting: http://stackoverflow.com/a/668327
* @return true if should be rate limited, false if it is OK to send the message
*/
public synchronized boolean isRateLimited() {
final double rate = TOKEN_BUCKET_RATE.get();
final double window = TOKEN_BUCKET_WINDOW.get();
final long current = System.currentTimeMillis();
final double timePassed = current - tkBktLastCheckTime;
tkBktLastCheckTime = current;
tkBktAllowance = tkBktAllowance + timePassed * (rate / window);
if (tkBktAllowance > rate) {
tkBktAllowance = rate; // cap max to rate
}
if (tkBktAllowance < 1.0) {
return true;
}
tkBktAllowance = tkBktAllowance - 1.0;
return false;
}
public ChannelFuture sendPushMessage(ByteBuf mesg) {
return pushProtocol.sendPushMessage(ctx, mesg);
}
public ChannelFuture sendPushMessage(String mesg) {
return sendPushMessage(Unpooled.copiedBuffer(mesg, Charsets.UTF_8));
}
public ChannelFuture sendPing() {
return pushProtocol.sendPing(ctx);
}
}
| 6,369 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushAuthHandler.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.netty.server.push;
import com.google.common.base.Strings;
import com.netflix.zuul.message.http.Cookies;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.Cookie;
import io.netty.handler.codec.http.CookieDecoder;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
/**
* Author: Susheel Aroskar
* Date: 5/11/18
*/
@ChannelHandler.Sharable
public abstract class PushAuthHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
private final String pushConnectionPath;
private final String originDomain;
public static final String NAME = "push_auth_handler";
private static Logger logger = LoggerFactory.getLogger(PushAuthHandler.class);
public PushAuthHandler(String pushConnectionPath, String originDomain) {
this.pushConnectionPath = pushConnectionPath;
this.originDomain = originDomain;
}
public final void sendHttpResponse(HttpRequest req, ChannelHandlerContext ctx, HttpResponseStatus status) {
FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
resp.headers().add("Content-Length", "0");
final boolean closeConn = ((status != HttpResponseStatus.OK) || (!HttpUtil.isKeepAlive(req)));
if (closeConn) {
resp.headers().add(HttpHeaderNames.CONNECTION, "Close");
}
final ChannelFuture cf = ctx.channel().writeAndFlush(resp);
if (closeConn) {
cf.addListener(ChannelFutureListener.CLOSE);
}
}
@Override
protected final void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
if (req.method() != HttpMethod.GET) {
sendHttpResponse(req, ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
return;
}
final String path = req.uri();
if ("/healthcheck".equals(path)) {
sendHttpResponse(req, ctx, HttpResponseStatus.OK);
} else if (pushConnectionPath.equals(path)) {
// CSRF protection
if (isInvalidOrigin(req)) {
sendHttpResponse(req, ctx, HttpResponseStatus.BAD_REQUEST);
} else if (isDelayedAuth(req, ctx)) {
// client auth will happen later, continue with WebSocket upgrade handshake
ctx.fireChannelRead(req.retain());
} else {
final PushUserAuth authEvent = doAuth(req);
if (authEvent.isSuccess()) {
ctx.fireChannelRead(req.retain()); // continue with WebSocket upgrade handshake
ctx.fireUserEventTriggered(authEvent);
} else {
logger.warn("Auth failed: {}", authEvent.statusCode());
sendHttpResponse(req, ctx, HttpResponseStatus.valueOf(authEvent.statusCode()));
}
}
} else {
sendHttpResponse(req, ctx, HttpResponseStatus.NOT_FOUND);
}
}
protected boolean isInvalidOrigin(FullHttpRequest req) {
final String origin = req.headers().get(HttpHeaderNames.ORIGIN);
if (origin == null || !origin.toLowerCase().endsWith(originDomain)) {
logger.error("Invalid Origin header {} in WebSocket upgrade request", origin);
return true;
}
return false;
}
protected final Cookies parseCookies(FullHttpRequest req) {
final Cookies cookies = new Cookies();
final String cookieStr = req.headers().get(HttpHeaderNames.COOKIE);
if (!Strings.isNullOrEmpty(cookieStr)) {
final Set<Cookie> decoded = CookieDecoder.decode(cookieStr, false);
decoded.forEach(cookie -> cookies.add(cookie));
}
return cookies;
}
/**
* @return true if Auth credentials will be provided later, for example in first WebSocket frame sent
*/
protected abstract boolean isDelayedAuth(FullHttpRequest req, ChannelHandlerContext ctx);
protected abstract PushUserAuth doAuth(FullHttpRequest req);
}
| 6,370 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushClientProtocolHandler.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.netty.server.push;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
/**
* Author: Susheel Aroskar
* Date: 11/2/2018
*/
public class PushClientProtocolHandler extends ChannelInboundHandlerAdapter {
protected PushUserAuth authEvent;
protected boolean isAuthenticated() {
return (authEvent != null && authEvent.isSuccess());
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof PushUserAuth) {
authEvent = (PushUserAuth) evt;
}
super.userEventTriggered(ctx, evt);
}
}
| 6,371 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushMessageSender.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.netty.server.push;
import com.google.common.base.Strings;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
/**
* Serves "/push" URL that is used by the backend to POST push messages to a given Zuul instance. This URL handler
* MUST BE accessible ONLY from RFC 1918 private internal network space (10.0.0.0 or 172.16.0.0) to guarantee that
* external applications/agents cannot push messages to your client. In AWS this can typically be achieved using
* correctly configured security groups.
*
* Author: Susheel Aroskar
* Date: 5/14/18
*/
@ChannelHandler.Sharable
public abstract class PushMessageSender extends SimpleChannelInboundHandler<FullHttpRequest> {
private final PushConnectionRegistry pushConnectionRegistry;
public static final String SECURE_TOKEN_HEADER_NAME = "X-Zuul.push.secure.token";
private static final Logger logger = LoggerFactory.getLogger(PushMessageSender.class);
@Inject
public PushMessageSender(PushConnectionRegistry pushConnectionRegistry) {
this.pushConnectionRegistry = pushConnectionRegistry;
}
private void sendHttpResponse(
ChannelHandlerContext ctx, FullHttpRequest request, HttpResponseStatus status, PushUserAuth userAuth) {
final FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
resp.headers().add("Content-Length", "0");
final ChannelFuture cf = ctx.channel().writeAndFlush(resp);
if (!HttpUtil.isKeepAlive(request)) {
cf.addListener(ChannelFutureListener.CLOSE);
}
logPushEvent(request, status, userAuth);
}
protected boolean verifySecureToken(final FullHttpRequest request, final PushConnection conn) {
final String secureToken = request.headers().get(SECURE_TOKEN_HEADER_NAME);
if (Strings.isNullOrEmpty(secureToken)) {
// caller is not asking to verify secure token
return true;
}
return secureToken.equals(conn.getSecureToken());
}
@Override
protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) throws Exception {
if (!request.decoderResult().isSuccess()) {
sendHttpResponse(ctx, request, HttpResponseStatus.BAD_REQUEST, null);
return;
}
final String path = request.uri();
if (path == null) {
sendHttpResponse(ctx, request, HttpResponseStatus.BAD_REQUEST, null);
return;
}
if (path.endsWith("/push")) {
logPushAttempt();
final HttpMethod method = request.method();
if ((method != HttpMethod.POST) && (method != HttpMethod.GET)) {
sendHttpResponse(ctx, request, HttpResponseStatus.METHOD_NOT_ALLOWED, null);
return;
}
final PushUserAuth userAuth = getPushUserAuth(request);
if (!userAuth.isSuccess()) {
sendHttpResponse(ctx, request, HttpResponseStatus.UNAUTHORIZED, userAuth);
logNoIdentity();
return;
}
final PushConnection pushConn = pushConnectionRegistry.get(userAuth.getClientIdentity());
if (pushConn == null) {
sendHttpResponse(ctx, request, HttpResponseStatus.NOT_FOUND, userAuth);
logClientNotConnected();
return;
}
if (!verifySecureToken(request, pushConn)) {
sendHttpResponse(ctx, request, HttpResponseStatus.FORBIDDEN, userAuth);
logSecurityTokenVerificationFail();
return;
}
if (method == HttpMethod.GET) {
// client only checking if particular CID + ESN is connected to this instance
sendHttpResponse(ctx, request, HttpResponseStatus.OK, userAuth);
return;
}
if (pushConn.isRateLimited()) {
sendHttpResponse(ctx, request, HttpResponseStatus.SERVICE_UNAVAILABLE, userAuth);
logRateLimited();
return;
}
final ByteBuf body = request.content().retain();
if (body.readableBytes() <= 0) {
sendHttpResponse(ctx, request, HttpResponseStatus.NO_CONTENT, userAuth);
// Because we are not passing the body to the pushConn (who would normally handle destroying),
// we need to release it here.
ReferenceCountUtil.release(body);
return;
}
final ChannelFuture clientFuture = pushConn.sendPushMessage(body);
clientFuture.addListener(cf -> {
HttpResponseStatus status;
if (cf.isSuccess()) {
logPushSuccess();
status = HttpResponseStatus.OK;
} else {
logPushError(cf.cause());
status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
}
sendHttpResponse(ctx, request, status, userAuth);
});
} else {
// Last handler in the chain
sendHttpResponse(ctx, request, HttpResponseStatus.BAD_REQUEST, null);
}
}
protected void logPushAttempt() {
logger.debug("pushing notification");
}
protected void logNoIdentity() {
logger.debug("push notification missing identity");
}
protected void logClientNotConnected() {
logger.debug("push notification, client not connected");
}
protected void logPushSuccess() {
logger.debug("push notification success");
}
protected void logPushError(Throwable t) {
logger.debug("pushing notification error", t);
}
protected void logRateLimited() {
logger.warn("Push message was rejected because of the rate limiting");
}
protected void logSecurityTokenVerificationFail() {
logger.warn("Push secure token verification failed");
}
protected void logPushEvent(FullHttpRequest request, HttpResponseStatus status, PushUserAuth userAuth) {
logger.debug("Push notification status: {}, auth: {}", status.code(), userAuth != null ? userAuth : "-");
}
protected abstract PushUserAuth getPushUserAuth(FullHttpRequest request);
}
| 6,372 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushChannelInitializer.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.netty.server.push;
import com.netflix.netty.common.channel.config.ChannelConfig;
import com.netflix.zuul.netty.server.BaseZuulChannelInitializer;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
/**
* Author: Susheel Aroskar
* Date: 5/15/18
*/
public abstract class PushChannelInitializer extends BaseZuulChannelInitializer {
/**
* Use {@link #PushChannelInitializer(String, ChannelConfig, ChannelConfig, ChannelGroup)} instead.
*/
@Deprecated
public PushChannelInitializer(
int port, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) {
this(String.valueOf(port), channelConfig, channelDependencies, channels);
}
protected PushChannelInitializer(
String metricId, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) {
super(metricId, channelConfig, channelDependencies, channels);
}
@Override
protected void addHttp1Handlers(ChannelPipeline pipeline) {
pipeline.addLast(
HTTP_CODEC_HANDLER_NAME,
new HttpServerCodec(MAX_INITIAL_LINE_LENGTH.get(), MAX_HEADER_SIZE.get(), MAX_CHUNK_SIZE.get(), false));
pipeline.addLast(new HttpObjectAggregator(8192));
}
@Override
protected void addHttpRelatedHandlers(ChannelPipeline pipeline) {
pipeline.addLast(stripInboundProxyHeadersHandler);
}
@Override
protected void initChannel(Channel ch) throws Exception {
final ChannelPipeline pipeline = ch.pipeline();
storeChannel(ch);
addTcpRelatedHandlers(pipeline);
addHttp1Handlers(pipeline);
addHttpRelatedHandlers(pipeline);
addPushHandlers(pipeline);
}
protected abstract void addPushHandlers(final ChannelPipeline pipeline);
}
| 6,373 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushProtocol.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.netty.server.push;
import com.google.common.base.Charsets;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
/**
* Created by saroskar on 10/10/16.
*/
public enum PushProtocol {
WEBSOCKET {
@Override
// The alternative object for HANDSHAKE_COMPLETE is not publicly visible, so disable deprecation warnings. In
// the future, it may be possible to not fire this even and remove the suppression.
@SuppressWarnings("deprecation")
public Object getHandshakeCompleteEvent() {
return WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE;
}
@Override
public String getPath() {
return "/ws";
}
@Override
public ChannelFuture sendPushMessage(ChannelHandlerContext ctx, ByteBuf mesg) {
final TextWebSocketFrame wsf = new TextWebSocketFrame(mesg);
return ctx.channel().writeAndFlush(wsf);
}
@Override
public ChannelFuture sendPing(ChannelHandlerContext ctx) {
return ctx.channel().writeAndFlush(new PingWebSocketFrame());
}
@Override
public Object goAwayMessage() {
return new TextWebSocketFrame("_CLOSE_");
}
@Override
public Object serverClosingConnectionMessage(int statusCode, String reasonText) {
return new CloseWebSocketFrame(statusCode, reasonText);
}
},
SSE {
private static final String SSE_HANDSHAKE_COMPLETE_EVENT = "sse_handshake_complete";
@Override
public Object getHandshakeCompleteEvent() {
return SSE_HANDSHAKE_COMPLETE_EVENT;
}
@Override
public String getPath() {
return "/sse";
}
private static final String SSE_PREAMBLE = "event: push\r\ndata: ";
private static final String SSE_TERMINATION = "\r\n\r\n";
@Override
public ChannelFuture sendPushMessage(ChannelHandlerContext ctx, ByteBuf mesg) {
final ByteBuf newBuff = ctx.alloc().buffer();
newBuff.ensureWritable(SSE_PREAMBLE.length());
newBuff.writeCharSequence(SSE_PREAMBLE, Charsets.UTF_8);
newBuff.ensureWritable(mesg.writableBytes());
newBuff.writeBytes(mesg);
newBuff.ensureWritable(SSE_TERMINATION.length());
newBuff.writeCharSequence(SSE_TERMINATION, Charsets.UTF_8);
mesg.release();
return ctx.channel().writeAndFlush(newBuff);
}
private static final String SSE_PING = "event: ping\r\ndata: ping\r\n\r\n";
@Override
public ChannelFuture sendPing(ChannelHandlerContext ctx) {
final ByteBuf newBuff = ctx.alloc().buffer();
newBuff.ensureWritable(SSE_PING.length());
newBuff.writeCharSequence(SSE_PING, Charsets.UTF_8);
return ctx.channel().writeAndFlush(newBuff);
}
@Override
public Object goAwayMessage() {
return "event: goaway\r\ndata: _CLOSE_\r\n\r\n";
}
@Override
public Object serverClosingConnectionMessage(int statusCode, String reasonText) {
return "event: close\r\ndata: " + statusCode + " " + reasonText + "\r\n\r\n";
}
};
public final void sendErrorAndClose(ChannelHandlerContext ctx, int statusCode, String reasonText) {
final Object mesg = serverClosingConnectionMessage(statusCode, reasonText);
ctx.writeAndFlush(mesg).addListener(ChannelFutureListener.CLOSE);
}
public abstract Object getHandshakeCompleteEvent();
public abstract String getPath();
public abstract ChannelFuture sendPushMessage(ChannelHandlerContext ctx, ByteBuf mesg);
public abstract ChannelFuture sendPing(ChannelHandlerContext ctx);
/**
* Application level protocol for asking client to close connection
* @return WebSocketFrame which when sent to client will cause it to close the WebSocket
*/
public abstract Object goAwayMessage();
/**
* Message server sends to the client just before it force closes connection from its side
*/
public abstract Object serverClosingConnectionMessage(int statusCode, String reasonText);
}
| 6,374 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushMessageSenderInitializer.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.netty.server.push;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
/**
* Author: Susheel Aroskar
* Date: 5/16/18
*/
public abstract class PushMessageSenderInitializer extends ChannelInitializer<Channel> {
@Override
protected void initChannel(Channel ch) throws Exception {
final ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(65536));
addPushMessageHandlers(pipeline);
}
protected abstract void addPushMessageHandlers(final ChannelPipeline pipeline);
}
| 6,375 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushConnectionRegistry.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.netty.server.push;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Maintains client identity to web socket or SSE channel mapping.
*
* Created by saroskar on 9/26/16.
*/
@Singleton
public class PushConnectionRegistry {
private final ConcurrentMap<String, PushConnection> clientPushConnectionMap;
private final SecureRandom secureTokenGenerator;
@Inject
public PushConnectionRegistry() {
clientPushConnectionMap = new ConcurrentHashMap<>(1024 * 32);
secureTokenGenerator = new SecureRandom();
}
@Nullable
public PushConnection get(final String clientId) {
return clientPushConnectionMap.get(clientId);
}
public List<PushConnection> getAll() {
return new ArrayList<>(clientPushConnectionMap.values());
}
public String mintNewSecureToken() {
byte[] tokenBuffer = new byte[15];
secureTokenGenerator.nextBytes(tokenBuffer);
return Base64.getUrlEncoder().encodeToString(tokenBuffer);
}
public void put(final String clientId, final PushConnection pushConnection) {
pushConnection.setSecureToken(mintNewSecureToken());
clientPushConnectionMap.put(clientId, pushConnection);
}
public PushConnection remove(final String clientId) {
final PushConnection pc = clientPushConnectionMap.remove(clientId);
return pc;
}
public int size() {
return clientPushConnectionMap.size();
}
}
| 6,376 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushRegistrationHandler.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.netty.server.push;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.config.CachedDynamicBooleanProperty;
import com.netflix.config.CachedDynamicIntProperty;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.util.concurrent.ScheduledFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Author: Susheel Aroskar
* Date: 5/14/18
*/
public class PushRegistrationHandler extends ChannelInboundHandlerAdapter {
protected final PushConnectionRegistry pushConnectionRegistry;
protected final PushProtocol pushProtocol;
/* Identity */
private volatile PushUserAuth authEvent;
/* state */
protected final AtomicBoolean destroyed;
private ChannelHandlerContext ctx;
private volatile PushConnection pushConnection;
private final List<ScheduledFuture<?>> scheduledFutures;
public static final CachedDynamicIntProperty PUSH_REGISTRY_TTL =
new CachedDynamicIntProperty("zuul.push.registry.ttl.seconds", 30 * 60);
public static final CachedDynamicIntProperty RECONNECT_DITHER =
new CachedDynamicIntProperty("zuul.push.reconnect.dither.seconds", 3 * 60);
public static final CachedDynamicIntProperty UNAUTHENTICATED_CONN_TTL =
new CachedDynamicIntProperty("zuul.push.noauth.ttl.seconds", 8);
public static final CachedDynamicIntProperty CLIENT_CLOSE_GRACE_PERIOD =
new CachedDynamicIntProperty("zuul.push.client.close.grace.period", 4);
public static final CachedDynamicBooleanProperty KEEP_ALIVE_ENABLED =
new CachedDynamicBooleanProperty("zuul.push.keepalive.enabled", true);
public static final CachedDynamicIntProperty KEEP_ALIVE_INTERVAL =
new CachedDynamicIntProperty("zuul.push.keepalive.interval.seconds", 3 * 60);
private static final Logger logger = LoggerFactory.getLogger(PushRegistrationHandler.class);
public PushRegistrationHandler(PushConnectionRegistry pushConnectionRegistry, PushProtocol pushProtocol) {
this.pushConnectionRegistry = pushConnectionRegistry;
this.pushProtocol = pushProtocol;
this.destroyed = new AtomicBoolean();
this.scheduledFutures = Collections.synchronizedList(new ArrayList<>());
}
protected final boolean isAuthenticated() {
return (authEvent != null && authEvent.isSuccess());
}
private void tearDown() {
if (!destroyed.getAndSet(true)) {
if (authEvent != null) {
// We should only remove the PushConnection entry from the registry if it's still this pushConnection.
String clientID = authEvent.getClientIdentity();
PushConnection savedPushConnection = pushConnectionRegistry.get(clientID);
if (savedPushConnection != null && savedPushConnection == pushConnection) {
pushConnectionRegistry.remove(authEvent.getClientIdentity());
logger.debug("Removed connection from registry for {}", authEvent);
}
logger.debug("Closing connection for {}", authEvent);
}
}
scheduledFutures.forEach(f -> f.cancel(false));
scheduledFutures.clear();
}
@Override
public final void channelInactive(ChannelHandlerContext ctx) throws Exception {
tearDown();
super.channelInactive(ctx);
ctx.close();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.error("Exception caught, closing push channel for {}", authEvent, cause);
ctx.close();
}
protected final void forceCloseConnectionFromServerSide() {
if (!destroyed.get()) {
logger.debug("server forcing close connection");
pushProtocol.sendErrorAndClose(ctx, 1000, "Server closed connection");
}
}
private void closeIfNotAuthenticated() {
if (!isAuthenticated()) {
logger.error(
"Closing connection because it is still unauthenticated after {} seconds.",
UNAUTHENTICATED_CONN_TTL.get());
forceCloseConnectionFromServerSide();
}
}
private void requestClientToCloseConnection() {
if (ctx.channel().isActive()) {
// Application level protocol for asking client to close connection
ctx.writeAndFlush(pushProtocol.goAwayMessage());
// Force close connection if client doesn't close in reasonable time after we made request
scheduledFutures.add(ctx.executor()
.schedule(
this::forceCloseConnectionFromServerSide,
CLIENT_CLOSE_GRACE_PERIOD.get(),
TimeUnit.SECONDS));
} else {
forceCloseConnectionFromServerSide();
}
}
protected void keepAlive() {
if (KEEP_ALIVE_ENABLED.get()) {
ctx.writeAndFlush(new PingWebSocketFrame());
}
}
private int ditheredReconnectDeadline() {
final int dither = ThreadLocalRandom.current().nextInt(RECONNECT_DITHER.get());
return PUSH_REGISTRY_TTL.get() - dither - CLIENT_CLOSE_GRACE_PERIOD.get();
}
@Override
public final void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
this.ctx = ctx;
if (!destroyed.get()) {
if (evt == pushProtocol.getHandshakeCompleteEvent()) {
pushConnection = new PushConnection(pushProtocol, ctx);
// Unauthenticated connection, wait for small amount of time for a client to send auth token in
// a first web socket frame, otherwise close connection
ctx.executor()
.schedule(this::closeIfNotAuthenticated, UNAUTHENTICATED_CONN_TTL.get(), TimeUnit.SECONDS);
logger.debug("WebSocket handshake complete.");
} else if (evt instanceof PushUserAuth) {
authEvent = (PushUserAuth) evt;
if ((authEvent.isSuccess()) && (pushConnection != null)) {
logger.debug("registering client {}", authEvent);
ctx.pipeline().remove(PushAuthHandler.NAME);
registerClient(ctx, authEvent, pushConnection, pushConnectionRegistry);
logger.debug("Authentication complete {}", authEvent);
} else {
logger.error(
"Push registration failed: Auth success={}, WS handshake success={}",
authEvent.isSuccess(),
pushConnection != null);
if (pushConnection != null) {
pushProtocol.sendErrorAndClose(ctx, 1008, "Auth failed");
}
}
}
}
super.userEventTriggered(ctx, evt);
}
/**
* Register authenticated client - represented by PushAuthEvent - with PushConnectionRegistry of this instance.
*
* For all but really simplistic case - basically anything other than a single node push cluster, You'd most likely
* need some sort of off-box, partitioned, global registration registry that keeps track of which client is connected
* to which push server instance. You should override this default implementation for such cases and register your
* client with your global registry in addition to local push connection registry that is limited to this JVM instance
* Make sure such a registration is done in strictly non-blocking fashion lest you will block Netty event loop
* decimating your throughput.
*
* A typical arrangement is to use something like Memcached or redis cluster sharded by client connection key and
* to use blocking Memcached/redis driver in a background thread-pool to do the actual registration so that Netty
* event loop doesn't block
*/
protected void registerClient(
ChannelHandlerContext ctx, PushUserAuth authEvent, PushConnection conn, PushConnectionRegistry registry) {
registry.put(authEvent.getClientIdentity(), conn);
// Make client reconnect after ttl seconds by closing this connection to limit stickiness of the client
scheduledFutures.add(ctx.executor()
.schedule(this::requestClientToCloseConnection, ditheredReconnectDeadline(), TimeUnit.SECONDS));
if (KEEP_ALIVE_ENABLED.get()) {
scheduledFutures.add(ctx.executor()
.scheduleWithFixedDelay(
this::keepAlive, KEEP_ALIVE_INTERVAL.get(), KEEP_ALIVE_INTERVAL.get(), TimeUnit.SECONDS));
}
}
@VisibleForTesting
PushConnection getPushConnection() {
return pushConnection;
}
@VisibleForTesting
List<ScheduledFuture<?>> getScheduledFutures() {
return scheduledFutures;
}
}
| 6,377 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushUserAuth.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.netty.server.push;
public interface PushUserAuth {
boolean isSuccess();
int statusCode();
String getClientIdentity();
}
| 6,378 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/server/push/PushMessageFactory.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.netty.server.push;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
/**
* Author: Susheel Aroskar
* Date: 11/2/2018
*/
public abstract class PushMessageFactory {
public final void sendErrorAndClose(ChannelHandlerContext ctx, int statusCode, String reasonText) {
ctx.writeAndFlush(serverClosingConnectionMessage(statusCode, reasonText))
.addListener(ChannelFutureListener.CLOSE);
}
/**
* Application level protocol for asking client to close connection
* @return WebSocketFrame which when sent to client will cause it to close the WebSocket
*/
protected abstract Object goAwayMessage();
/**
* Message server sends to the client just before it force closes connection from its side
*/
protected abstract Object serverClosingConnectionMessage(int statusCode, String reasonText);
}
| 6,379 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/ratelimiting/NullChannelHandlerProvider.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.netty.ratelimiting;
import io.netty.channel.ChannelHandler;
import javax.inject.Provider;
import javax.inject.Singleton;
@Singleton
public class NullChannelHandlerProvider implements Provider<ChannelHandler> {
@Override
public ChannelHandler get() {
return null;
}
}
| 6,380 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/IConnectionPool.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.netty.connectionpool;
import com.netflix.zuul.passport.CurrentPassport;
import io.netty.channel.EventLoop;
import io.netty.util.concurrent.Promise;
import java.net.InetAddress;
import java.util.concurrent.atomic.AtomicReference;
/**
* User: michaels@netflix.com
* Date: 7/8/16
* Time: 1:10 PM
*/
public interface IConnectionPool {
Promise<PooledConnection> acquire(
EventLoop eventLoop, CurrentPassport passport, AtomicReference<? super InetAddress> selectedHostAddr);
boolean release(PooledConnection conn);
boolean remove(PooledConnection conn);
void shutdown();
default void drain() {
shutdown();
}
boolean isAvailable();
int getConnsInUse();
int getConnsInPool();
ConnectionPoolConfig getConfig();
}
| 6,381 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ClientChannelManager.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.netty.connectionpool;
import com.netflix.zuul.discovery.DiscoveryResult;
import com.netflix.zuul.passport.CurrentPassport;
import io.netty.channel.EventLoop;
import io.netty.util.concurrent.Promise;
import java.net.InetAddress;
import java.util.concurrent.atomic.AtomicReference;
/**
* User: michaels@netflix.com
* Date: 7/8/16
* Time: 12:36 PM
*/
public interface ClientChannelManager {
void init();
boolean isAvailable();
int getInflightRequestsCount();
void shutdown();
default void gracefulShutdown() {
shutdown();
}
boolean release(PooledConnection conn);
Promise<PooledConnection> acquire(EventLoop eventLoop);
Promise<PooledConnection> acquire(
EventLoop eventLoop,
Object key,
CurrentPassport passport,
AtomicReference<DiscoveryResult> selectedServer,
AtomicReference<? super InetAddress> selectedHostAddr);
boolean isCold();
boolean remove(PooledConnection conn);
int getConnsInPool();
int getConnsInUse();
ConnectionPoolConfig getConfig();
}
| 6,382 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/OriginConnectException.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.netty.connectionpool;
import com.netflix.zuul.exception.ErrorType;
/**
* Wrapper for exceptions failing to connect to origin with details on which server failed the attempt.
*/
public class OriginConnectException extends Exception {
private final ErrorType errorType;
public OriginConnectException(String message, ErrorType errorType) {
// ensure this exception does not fill its stacktrace, this causes a 10x slowdown
super(message, null, true, false);
this.errorType = errorType;
}
public OriginConnectException(String message, Throwable cause, ErrorType errorType) {
// ensure this exception does not fill its stacktrace, this causes a 10x slowdown
super(message, cause, true, false);
this.errorType = errorType;
}
public ErrorType getErrorType() {
return errorType;
}
}
| 6,383 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/OriginChannelInitializer.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.netty.connectionpool;
import com.netflix.netty.common.metrics.HttpMetricsChannelHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
/**
* Origin Channel Initializer
*
* Author: Arthur Gonigberg
* Date: December 01, 2017
*/
public abstract class OriginChannelInitializer extends ChannelInitializer<Channel> {
public abstract HttpMetricsChannelHandler getHttpMetricsHandler();
}
| 6,384 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ConnectionPoolConfig.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.netty.connectionpool;
import com.netflix.zuul.origins.OriginName;
/**
* Created by saroskar on 3/24/16.
*/
public interface ConnectionPoolConfig {
/* Origin name from connection pool */
OriginName getOriginName();
/* Max number of requests per connection before it needs to be recycled */
int getMaxRequestsPerConnection();
/* Max connections per host */
int maxConnectionsPerHost();
int perServerWaterline();
/* Origin client TCP configuration options */
int getConnectTimeout();
/* number of milliseconds connection can stay idle in a connection pool before it is closed */
int getIdleTimeout();
int getTcpReceiveBufferSize();
int getTcpSendBufferSize();
int getNettyWriteBufferHighWaterMark();
int getNettyWriteBufferLowWaterMark();
boolean getTcpKeepAlive();
boolean getTcpNoDelay();
boolean getNettyAutoRead();
boolean isSecure();
boolean useIPAddrForServer();
}
| 6,385 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ConnectionPoolHandler.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.netty.connectionpool;
import com.netflix.spectator.api.Counter;
import com.netflix.zuul.netty.ChannelUtils;
import com.netflix.zuul.netty.SpectatorUtils;
import com.netflix.zuul.origins.OriginName;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent;
import static com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason;
/**
* User: michaels@netflix.com
* Date: 6/23/16
* Time: 1:57 PM
*/
@ChannelHandler.Sharable
public class ConnectionPoolHandler extends ChannelDuplexHandler {
private static final Logger LOG = LoggerFactory.getLogger(ConnectionPoolHandler.class);
public static final String METRIC_PREFIX = "connectionpool";
private final OriginName originName;
private final Counter idleCounter;
private final Counter inactiveCounter;
private final Counter errorCounter;
private final Counter headerCloseCounter;
public ConnectionPoolHandler(OriginName originName) {
if (originName == null) {
throw new IllegalArgumentException("Null originName passed to constructor!");
}
this.originName = originName;
this.idleCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_idle", originName.getMetricId());
this.inactiveCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_inactive", originName.getMetricId());
this.errorCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_error", originName.getMetricId());
this.headerCloseCounter = SpectatorUtils.newCounter(METRIC_PREFIX + "_headerClose", originName.getMetricId());
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
// First let other handlers do their thing ...
// super.userEventTriggered(ctx, evt);
if (evt instanceof IdleStateEvent) {
// Log some info about this.
idleCounter.increment();
final String msg = "Origin channel for origin - " + originName + " - idle timeout has fired. "
+ ChannelUtils.channelInfoForLogging(ctx.channel());
closeConnection(ctx, msg);
} else if (evt instanceof CompleteEvent) {
// The HttpLifecycleChannelHandler instance will fire this event when either a response has finished being
// written, or
// the channel is no longer active or disconnected.
// Return the connection to pool.
CompleteEvent completeEvt = (CompleteEvent) evt;
final CompleteReason reason = completeEvt.getReason();
if (reason == CompleteReason.SESSION_COMPLETE) {
final PooledConnection conn = PooledConnection.getFromChannel(ctx.channel());
if (conn != null) {
if ("close".equalsIgnoreCase(getConnectionHeader(completeEvt))) {
final String msg = "Origin channel for origin - " + originName
+ " - completed because of expired keep-alive. "
+ ChannelUtils.channelInfoForLogging(ctx.channel());
headerCloseCounter.increment();
closeConnection(ctx, msg);
} else {
conn.setConnectionState(PooledConnection.ConnectionState.WRITE_READY);
conn.release();
}
}
} else {
final String msg = "Origin channel for origin - " + originName + " - completed with reason "
+ reason.name() + ", " + ChannelUtils.channelInfoForLogging(ctx.channel());
closeConnection(ctx, msg);
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// super.exceptionCaught(ctx, cause);
errorCounter.increment();
final String mesg = "Exception on Origin channel for origin - " + originName + ". "
+ ChannelUtils.channelInfoForLogging(ctx.channel()) + " - "
+ cause.getClass().getCanonicalName()
+ ": " + cause.getMessage();
closeConnection(ctx, mesg);
if (LOG.isDebugEnabled()) {
LOG.debug(mesg, cause);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// super.channelInactive(ctx);
inactiveCounter.increment();
final String msg = "Client channel for origin - " + originName + " - inactive event has fired. "
+ ChannelUtils.channelInfoForLogging(ctx.channel());
closeConnection(ctx, msg);
}
private void closeConnection(ChannelHandlerContext ctx, String msg) {
PooledConnection conn = PooledConnection.getFromChannel(ctx.channel());
if (conn != null) {
if (LOG.isDebugEnabled()) {
msg = msg + " Closing the PooledConnection and releasing. conn={}";
LOG.debug(msg, conn);
}
flagCloseAndReleaseConnection(conn);
} else {
// If somehow we don't have a PooledConnection instance attached to this channel, then
// close the channel directly.
LOG.warn("{} But no PooledConnection attribute. So just closing Channel.", msg);
ctx.close();
}
}
private void flagCloseAndReleaseConnection(PooledConnection pooledConnection) {
if (pooledConnection.isInPool()) {
pooledConnection.closeAndRemoveFromPool();
} else {
pooledConnection.flagShouldClose();
pooledConnection.release();
}
}
private static String getConnectionHeader(CompleteEvent completeEvt) {
HttpResponse response = completeEvt.getResponse();
if (response != null) {
return response.headers().get(HttpHeaderNames.CONNECTION);
}
return null;
}
}
| 6,386 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/BasicRequestStat.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.netty.connectionpool;
import com.google.common.base.Stopwatch;
import com.netflix.zuul.discovery.DiscoveryResult;
import com.netflix.zuul.exception.ErrorType;
import com.netflix.zuul.exception.OutboundErrorType;
import java.util.concurrent.TimeUnit;
/**
* @author michaels
*/
public class BasicRequestStat implements RequestStat {
private volatile boolean isFinished;
private volatile Stopwatch stopwatch;
public BasicRequestStat() {
this.isFinished = false;
this.stopwatch = Stopwatch.createStarted();
}
@Override
public RequestStat server(DiscoveryResult server) {
return this;
}
@Override
public boolean isFinished() {
return isFinished;
}
@Override
public long duration() {
long ms = stopwatch.elapsed(TimeUnit.MILLISECONDS);
return ms > 0 ? ms : 0;
}
@Override
public void serviceUnavailable() {
failAndSetErrorCode(OutboundErrorType.SERVICE_UNAVAILABLE);
}
@Override
public void generalError() {
failAndSetErrorCode(OutboundErrorType.OTHER);
}
@Override
public void failAndSetErrorCode(ErrorType error) {
// override to implement metric tracking
}
@Override
public void updateWithHttpStatusCode(int httpStatusCode) {
// override to implement metric tracking
}
@Override
public void finalAttempt(boolean finalAttempt) {}
@Override
public boolean finishIfNotAlready() {
if (isFinished) {
return false;
}
stopwatch.stop();
publishMetrics();
isFinished = true;
return true;
}
protected void publishMetrics() {
// override to publish metrics here
}
}
| 6,387 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ZuulNettyExceptionMapper.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.netty.connectionpool;
/**
* User: Mike Smith
* Date: 7/13/16
* Time: 6:02 PM
*/
public class ZuulNettyExceptionMapper {}
| 6,388 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ConnectionPoolConfigImpl.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.netty.connectionpool;
import com.netflix.client.config.IClientConfig;
import com.netflix.client.config.IClientConfigKey;
import com.netflix.config.CachedDynamicBooleanProperty;
import com.netflix.config.CachedDynamicIntProperty;
import com.netflix.zuul.origins.OriginName;
import java.util.Objects;
/**
* Created by saroskar on 3/24/16.
*/
public class ConnectionPoolConfigImpl implements ConnectionPoolConfig {
private static final int DEFAULT_BUFFER_SIZE = 32 * 1024;
private static final int DEFAULT_CONNECT_TIMEOUT = 500;
private static final int DEFAULT_IDLE_TIMEOUT = 60000;
private static final int DEFAULT_MAX_CONNS_PER_HOST = 50;
private final OriginName originName;
private final IClientConfig clientConfig;
private final CachedDynamicIntProperty MAX_REQUESTS_PER_CONNECTION;
private final CachedDynamicIntProperty PER_SERVER_WATERLINE;
private final CachedDynamicBooleanProperty SOCKET_KEEP_ALIVE;
private final CachedDynamicBooleanProperty TCP_NO_DELAY;
private final CachedDynamicIntProperty WRITE_BUFFER_HIGH_WATER_MARK;
private final CachedDynamicIntProperty WRITE_BUFFER_LOW_WATER_MARK;
private final CachedDynamicBooleanProperty AUTO_READ;
public ConnectionPoolConfigImpl(final OriginName originName, IClientConfig clientConfig) {
this.originName = Objects.requireNonNull(originName, "originName");
String niwsClientName = originName.getNiwsClientName();
this.clientConfig = clientConfig;
this.MAX_REQUESTS_PER_CONNECTION =
new CachedDynamicIntProperty(niwsClientName + ".netty.client.maxRequestsPerConnection", 1000);
// NOTE that the each eventloop has it's own connection pool per host, and this is applied per event-loop.
this.PER_SERVER_WATERLINE =
new CachedDynamicIntProperty(niwsClientName + ".netty.client.perServerWaterline", 4);
this.SOCKET_KEEP_ALIVE = new CachedDynamicBooleanProperty(niwsClientName + ".netty.client.TcpKeepAlive", false);
this.TCP_NO_DELAY = new CachedDynamicBooleanProperty(niwsClientName + ".netty.client.TcpNoDelay", false);
// TODO(argha-c): Document why these values were chosen, as opposed to defaults of 32k/64k
this.WRITE_BUFFER_HIGH_WATER_MARK =
new CachedDynamicIntProperty(niwsClientName + ".netty.client.WriteBufferHighWaterMark", 32 * 1024);
this.WRITE_BUFFER_LOW_WATER_MARK =
new CachedDynamicIntProperty(niwsClientName + ".netty.client.WriteBufferLowWaterMark", 8 * 1024);
this.AUTO_READ = new CachedDynamicBooleanProperty(niwsClientName + ".netty.client.AutoRead", false);
}
@Override
public OriginName getOriginName() {
return originName;
}
@Override
public int getConnectTimeout() {
return clientConfig.getPropertyAsInteger(IClientConfigKey.Keys.ConnectTimeout, DEFAULT_CONNECT_TIMEOUT);
}
@Override
public int getMaxRequestsPerConnection() {
return MAX_REQUESTS_PER_CONNECTION.get();
}
@Override
public int maxConnectionsPerHost() {
return clientConfig.getPropertyAsInteger(
IClientConfigKey.Keys.MaxConnectionsPerHost, DEFAULT_MAX_CONNS_PER_HOST);
}
@Override
public int perServerWaterline() {
return PER_SERVER_WATERLINE.get();
}
@Override
public int getIdleTimeout() {
return clientConfig.getPropertyAsInteger(
IClientConfigKey.Keys.ConnIdleEvictTimeMilliSeconds, DEFAULT_IDLE_TIMEOUT);
}
@Override
public boolean getTcpKeepAlive() {
return SOCKET_KEEP_ALIVE.get();
}
@Override
public boolean getTcpNoDelay() {
return TCP_NO_DELAY.get();
}
@Override
public int getTcpReceiveBufferSize() {
return clientConfig.getPropertyAsInteger(IClientConfigKey.Keys.ReceiveBufferSize, DEFAULT_BUFFER_SIZE);
}
@Override
public int getTcpSendBufferSize() {
return clientConfig.getPropertyAsInteger(IClientConfigKey.Keys.SendBufferSize, DEFAULT_BUFFER_SIZE);
}
@Override
public int getNettyWriteBufferHighWaterMark() {
return WRITE_BUFFER_HIGH_WATER_MARK.get();
}
@Override
public int getNettyWriteBufferLowWaterMark() {
return WRITE_BUFFER_LOW_WATER_MARK.get();
}
@Override
public boolean getNettyAutoRead() {
return AUTO_READ.get();
}
@Override
public boolean isSecure() {
return clientConfig.getPropertyAsBoolean(IClientConfigKey.Keys.IsSecure, false);
}
@Override
public boolean useIPAddrForServer() {
return clientConfig.getPropertyAsBoolean(IClientConfigKey.Keys.UseIPAddrForServer, true);
}
}
| 6,389 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/PerServerConnectionPool.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.netty.connectionpool;
import com.netflix.client.config.IClientConfig;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Timer;
import com.netflix.zuul.discovery.DiscoveryResult;
import com.netflix.zuul.exception.OutboundErrorType;
import com.netflix.zuul.passport.CurrentPassport;
import com.netflix.zuul.passport.PassportState;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoop;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.Promise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Deque;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
/**
* User: michaels@netflix.com
* Date: 7/8/16
* Time: 1:09 PM
*/
public class PerServerConnectionPool implements IConnectionPool {
private static final Logger LOG = LoggerFactory.getLogger(PerServerConnectionPool.class);
public static final AttributeKey<IConnectionPool> CHANNEL_ATTR = AttributeKey.newInstance("_connection_pool");
protected final ConcurrentHashMap<EventLoop, Deque<PooledConnection>> connectionsPerEventLoop =
new ConcurrentHashMap<>();
protected final PooledConnectionFactory pooledConnectionFactory;
protected final DiscoveryResult server;
protected final SocketAddress serverAddr;
protected final NettyClientConnectionFactory connectionFactory;
protected final ConnectionPoolConfig config;
protected final IClientConfig niwsClientConfig;
protected final Counter createNewConnCounter;
protected final Counter createConnSucceededCounter;
protected final Counter createConnFailedCounter;
protected final Counter requestConnCounter;
protected final Counter reuseConnCounter;
protected final Counter connTakenFromPoolIsNotOpen;
protected final Counter maxConnsPerHostExceededCounter;
protected final Counter closeAboveHighWaterMarkCounter;
protected final Timer connEstablishTimer;
protected final AtomicInteger connsInPool;
protected final AtomicInteger connsInUse;
/**
* This is the count of connections currently in progress of being established.
* They will only be added to connsInUse _after_ establishment has completed.
*/
protected final AtomicInteger connCreationsInProgress;
protected volatile boolean draining;
public PerServerConnectionPool(
DiscoveryResult server,
SocketAddress serverAddr,
NettyClientConnectionFactory connectionFactory,
PooledConnectionFactory pooledConnectionFactory,
ConnectionPoolConfig config,
IClientConfig niwsClientConfig,
Counter createNewConnCounter,
Counter createConnSucceededCounter,
Counter createConnFailedCounter,
Counter requestConnCounter,
Counter reuseConnCounter,
Counter connTakenFromPoolIsNotOpen,
Counter closeAboveHighWaterMarkCounter,
Counter maxConnsPerHostExceededCounter,
Timer connEstablishTimer,
AtomicInteger connsInPool,
AtomicInteger connsInUse) {
this.server = server;
// Note: child classes can sometimes connect to different addresses than
this.serverAddr = Objects.requireNonNull(serverAddr, "serverAddr");
this.connectionFactory = connectionFactory;
this.pooledConnectionFactory = pooledConnectionFactory;
this.config = config;
this.niwsClientConfig = niwsClientConfig;
this.createNewConnCounter = createNewConnCounter;
this.createConnSucceededCounter = createConnSucceededCounter;
this.createConnFailedCounter = createConnFailedCounter;
this.requestConnCounter = requestConnCounter;
this.reuseConnCounter = reuseConnCounter;
this.connTakenFromPoolIsNotOpen = connTakenFromPoolIsNotOpen;
this.closeAboveHighWaterMarkCounter = closeAboveHighWaterMarkCounter;
this.maxConnsPerHostExceededCounter = maxConnsPerHostExceededCounter;
this.connEstablishTimer = connEstablishTimer;
this.connsInPool = connsInPool;
this.connsInUse = connsInUse;
this.connCreationsInProgress = new AtomicInteger(0);
}
@Override
public ConnectionPoolConfig getConfig() {
return this.config;
}
public IClientConfig getNiwsClientConfig() {
return niwsClientConfig;
}
@Override
public boolean isAvailable() {
return !draining;
}
/** function to run when a connection is acquired before returning it to caller. */
protected void onAcquire(final PooledConnection conn, CurrentPassport passport) {
passport.setOnChannel(conn.getChannel());
removeIdleStateHandler(conn);
conn.setInUse();
LOG.debug("PooledConnection acquired: {}", conn);
}
protected void removeIdleStateHandler(PooledConnection conn) {
DefaultClientChannelManager.removeHandlerFromPipeline(
DefaultClientChannelManager.IDLE_STATE_HANDLER_NAME,
conn.getChannel().pipeline());
}
@Override
public Promise<PooledConnection> acquire(
EventLoop eventLoop, CurrentPassport passport, AtomicReference<? super InetAddress> selectedHostAddr) {
if (draining) {
throw new IllegalStateException("Attempt to acquire connection while draining");
}
requestConnCounter.increment();
updateServerStatsOnAcquire();
Promise<PooledConnection> promise = eventLoop.newPromise();
// Try getting a connection from the pool.
final PooledConnection conn = tryGettingFromConnectionPool(eventLoop);
if (conn != null) {
// There was a pooled connection available, so use this one.
conn.startRequestTimer();
conn.incrementUsageCount();
conn.getChannel().read();
onAcquire(conn, passport);
initPooledConnection(conn, promise);
selectedHostAddr.set(getSelectedHostString(serverAddr));
} else {
// connection pool empty, create new connection using client connection factory.
tryMakingNewConnection(eventLoop, promise, passport, selectedHostAddr);
}
return promise;
}
protected void updateServerStatsOnAcquire() {
server.incrementActiveRequestsCount();
}
public PooledConnection tryGettingFromConnectionPool(EventLoop eventLoop) {
PooledConnection conn;
Deque<PooledConnection> connections = getPoolForEventLoop(eventLoop);
while ((conn = connections.poll()) != null) {
conn.setInPool(false);
/* Check that the connection is still open. */
if (isValidFromPool(conn)) {
reuseConnCounter.increment();
connsInUse.incrementAndGet();
connsInPool.decrementAndGet();
return conn;
} else {
connTakenFromPoolIsNotOpen.increment();
connsInPool.decrementAndGet();
conn.close();
}
}
return null;
}
protected boolean isValidFromPool(PooledConnection conn) {
return conn.isActive() && conn.getChannel().isOpen();
}
protected void initPooledConnection(PooledConnection conn, Promise<PooledConnection> promise) {
// add custom init code by overriding this method
promise.setSuccess(conn);
}
protected Deque<PooledConnection> getPoolForEventLoop(EventLoop eventLoop) {
// We don't want to block under any circumstances, so can't use CHM.computeIfAbsent().
// Instead we accept the slight inefficiency of an unnecessary instantiation of a ConcurrentLinkedDeque.
Deque<PooledConnection> pool = connectionsPerEventLoop.get(eventLoop);
if (pool == null) {
pool = new ConcurrentLinkedDeque<>();
connectionsPerEventLoop.putIfAbsent(eventLoop, pool);
}
return pool;
}
protected void tryMakingNewConnection(
EventLoop eventLoop,
Promise<PooledConnection> promise,
CurrentPassport passport,
AtomicReference<? super InetAddress> selectedHostAddr) {
// Enforce MaxConnectionsPerHost config.
int maxConnectionsPerHost = config.maxConnectionsPerHost();
int openAndOpeningConnectionCount = server.getOpenConnectionsCount() + connCreationsInProgress.get();
if (maxConnectionsPerHost != -1 && openAndOpeningConnectionCount >= maxConnectionsPerHost) {
maxConnsPerHostExceededCounter.increment();
promise.setFailure(new OriginConnectException(
"maxConnectionsPerHost=" + maxConnectionsPerHost + ", connectionsPerHost="
+ openAndOpeningConnectionCount,
OutboundErrorType.ORIGIN_SERVER_MAX_CONNS));
LOG.warn(
"Unable to create new connection because at MaxConnectionsPerHost! maxConnectionsPerHost={}, connectionsPerHost={}, host={}origin={}",
maxConnectionsPerHost,
openAndOpeningConnectionCount,
server.getServerId(),
config.getOriginName());
return;
}
try {
createNewConnCounter.increment();
connCreationsInProgress.incrementAndGet();
passport.add(PassportState.ORIGIN_CH_CONNECTING);
selectedHostAddr.set(getSelectedHostString(serverAddr));
final ChannelFuture cf = connectToServer(eventLoop, passport, serverAddr);
if (cf.isDone()) {
handleConnectCompletion(cf, promise, passport);
} else {
cf.addListener(future -> {
try {
handleConnectCompletion((ChannelFuture) future, promise, passport);
} catch (Throwable e) {
if (!promise.isDone()) {
promise.setFailure(e);
}
LOG.warn(
"Error creating new connection! origin={}, host={}",
config.getOriginName(),
server.getServerId());
}
});
}
} catch (Throwable e) {
promise.setFailure(e);
}
}
protected ChannelFuture connectToServer(EventLoop eventLoop, CurrentPassport passport, SocketAddress serverAddr) {
return connectionFactory.connect(eventLoop, serverAddr, passport, this);
}
protected void handleConnectCompletion(
ChannelFuture cf, Promise<PooledConnection> callerPromise, CurrentPassport passport) {
connCreationsInProgress.decrementAndGet();
updateServerStatsOnConnectCompletion(cf);
if (cf.isSuccess()) {
passport.add(PassportState.ORIGIN_CH_CONNECTED);
createConnSucceededCounter.increment();
connsInUse.incrementAndGet();
createConnection(cf, callerPromise, passport);
} else {
createConnFailedCounter.increment();
callerPromise.setFailure(
new OriginConnectException(cf.cause().getMessage(), cf.cause(), OutboundErrorType.CONNECT_ERROR));
}
}
protected void updateServerStatsOnConnectCompletion(ChannelFuture cf) {
if (cf.isSuccess()) {
server.incrementOpenConnectionsCount();
} else {
server.incrementSuccessiveConnectionFailureCount();
server.addToFailureCount();
server.decrementActiveRequestsCount();
}
}
protected void createConnection(
ChannelFuture cf, Promise<PooledConnection> callerPromise, CurrentPassport passport) {
final PooledConnection conn = pooledConnectionFactory.create(cf.channel());
conn.incrementUsageCount();
conn.startRequestTimer();
conn.getChannel().read();
onAcquire(conn, passport);
callerPromise.setSuccess(conn);
}
@Override
public boolean release(PooledConnection conn) {
if (conn == null) {
return false;
}
if (conn.isInPool()) {
return false;
}
if (draining) {
LOG.debug(
"[{}] closing released connection during drain",
conn.getChannel().id());
conn.getChannel().close();
return false;
}
// Get the eventloop for this channel.
EventLoop eventLoop = conn.getChannel().eventLoop();
Deque<PooledConnection> connections = getPoolForEventLoop(eventLoop);
CurrentPassport passport = CurrentPassport.fromChannel(conn.getChannel());
// Discard conn if already at least above waterline in the pool already for this server.
int poolWaterline = config.perServerWaterline();
if (poolWaterline > -1 && connections.size() >= poolWaterline) {
closeAboveHighWaterMarkCounter.increment();
conn.close();
conn.setInPool(false);
return false;
}
// Attempt to return connection to the pool.
else if (connections.offer(conn)) {
conn.setInPool(true);
connsInPool.incrementAndGet();
passport.add(PassportState.ORIGIN_CH_POOL_RETURNED);
return true;
} else {
// If the pool is full, then close the conn and discard.
conn.close();
conn.setInPool(false);
return false;
}
}
@Override
public boolean remove(PooledConnection conn) {
if (conn == null) {
return false;
}
if (!conn.isInPool()) {
return false;
}
// Get the eventloop for this channel.
EventLoop eventLoop = conn.getChannel().eventLoop();
// Attempt to remove connection from the pool.
Deque<PooledConnection> connections = getPoolForEventLoop(eventLoop);
if (connections.remove(conn)) {
conn.setInPool(false);
connsInPool.decrementAndGet();
return true;
} else {
return false;
}
}
@Override
public void shutdown() {
for (Deque<PooledConnection> connections : connectionsPerEventLoop.values()) {
for (PooledConnection conn : connections) {
conn.close();
}
}
}
@Override
public void drain() {
if (draining) {
throw new IllegalStateException("Already draining");
}
draining = true;
connectionsPerEventLoop.forEach((eventLoop, v) -> drainIdleConnectionsOnEventLoop(eventLoop));
}
@Override
public int getConnsInPool() {
return connsInPool.get();
}
@Override
public int getConnsInUse() {
return connsInUse.get();
}
@Nullable
private static InetAddress getSelectedHostString(SocketAddress addr) {
if (addr instanceof InetSocketAddress) {
return ((InetSocketAddress) addr).getAddress();
} else {
// If it's some other kind of address, just set it to empty
return null;
}
}
/**
* Closes idle connections in the connection pool for a given EventLoop. The closing is performed on the EventLoop
* thread since the connection pool is not thread safe.
*
* @param eventLoop - the event loop to drain
*/
void drainIdleConnectionsOnEventLoop(EventLoop eventLoop) {
eventLoop.execute(() -> {
Deque<PooledConnection> connections = connectionsPerEventLoop.get(eventLoop);
if (connections == null) {
return;
}
for (PooledConnection connection : connections) {
// any connections in the Deque are idle since they are removed in tryGettingFromConnectionPool()
connection.setInPool(false);
LOG.debug("Closing connection {}", connection);
connection.close();
connsInPool.decrementAndGet();
}
});
}
}
| 6,390 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/RequestStat.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.netty.connectionpool;
import com.netflix.zuul.context.SessionContext;
import com.netflix.zuul.discovery.DiscoveryResult;
import com.netflix.zuul.exception.ErrorType;
/**
* Request Stat
*
* Author: Arthur Gonigberg
* Date: November 29, 2017
*/
public interface RequestStat {
String SESSION_CONTEXT_KEY = "niwsRequestStat";
static RequestStat putInSessionContext(RequestStat stat, SessionContext context) {
context.put(SESSION_CONTEXT_KEY, stat);
return stat;
}
static RequestStat getFromSessionContext(SessionContext context) {
return (RequestStat) context.get(SESSION_CONTEXT_KEY);
}
RequestStat server(DiscoveryResult server);
boolean isFinished();
long duration();
void serviceUnavailable();
void generalError();
void failAndSetErrorCode(ErrorType errorType);
void updateWithHttpStatusCode(int httpStatusCode);
void finalAttempt(boolean finalAttempt);
boolean finishIfNotAlready();
}
| 6,391 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/PooledConnectionFactory.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.netty.connectionpool;
import io.netty.channel.Channel;
/**
* User: Mike Smith
* Date: 7/9/16
* Time: 2:25 PM
*/
public interface PooledConnectionFactory {
PooledConnection create(Channel ch);
}
| 6,392 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/DefaultOriginChannelInitializer.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.netty.connectionpool;
import com.netflix.netty.common.HttpClientLifecycleChannelHandler;
import com.netflix.netty.common.metrics.HttpMetricsChannelHandler;
import com.netflix.spectator.api.Registry;
import com.netflix.zuul.netty.insights.PassportStateHttpClientHandler;
import com.netflix.zuul.netty.insights.PassportStateOriginHandler;
import com.netflix.zuul.netty.server.BaseZuulChannelInitializer;
import com.netflix.zuul.netty.ssl.ClientSslContextFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
/**
* Default Origin Channel Initializer
*
* Author: Arthur Gonigberg
* Date: December 01, 2017
*/
public class DefaultOriginChannelInitializer extends OriginChannelInitializer {
public static final String ORIGIN_NETTY_LOGGER = "originNettyLogger";
public static final String CONNECTION_POOL_HANDLER = "connectionPoolHandler";
private final ConnectionPoolConfig connectionPoolConfig;
private final SslContext sslContext;
protected final ConnectionPoolHandler connectionPoolHandler;
protected final HttpMetricsChannelHandler httpMetricsHandler;
protected final LoggingHandler nettyLogger;
public DefaultOriginChannelInitializer(ConnectionPoolConfig connPoolConfig, Registry spectatorRegistry) {
this.connectionPoolConfig = connPoolConfig;
String niwsClientName = connectionPoolConfig.getOriginName().getNiwsClientName();
this.connectionPoolHandler = new ConnectionPoolHandler(connectionPoolConfig.getOriginName());
this.httpMetricsHandler = new HttpMetricsChannelHandler(spectatorRegistry, "client", niwsClientName);
this.nettyLogger = new LoggingHandler("zuul.origin.nettylog." + niwsClientName, LogLevel.INFO);
this.sslContext = getClientSslContext(spectatorRegistry);
}
@Override
protected void initChannel(Channel ch) throws Exception {
final ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new PassportStateOriginHandler.InboundHandler());
pipeline.addLast(new PassportStateOriginHandler.OutboundHandler());
if (connectionPoolConfig.isSecure()) {
pipeline.addLast("ssl", sslContext.newHandler(ch.alloc()));
}
pipeline.addLast(
BaseZuulChannelInitializer.HTTP_CODEC_HANDLER_NAME,
new HttpClientCodec(
BaseZuulChannelInitializer.MAX_INITIAL_LINE_LENGTH.get(),
BaseZuulChannelInitializer.MAX_HEADER_SIZE.get(),
BaseZuulChannelInitializer.MAX_CHUNK_SIZE.get(),
false,
false));
pipeline.addLast(new PassportStateHttpClientHandler.InboundHandler());
pipeline.addLast(new PassportStateHttpClientHandler.OutboundHandler());
pipeline.addLast(ORIGIN_NETTY_LOGGER, nettyLogger);
pipeline.addLast(httpMetricsHandler);
addMethodBindingHandler(pipeline);
pipeline.addLast(HttpClientLifecycleChannelHandler.INBOUND_CHANNEL_HANDLER);
pipeline.addLast(HttpClientLifecycleChannelHandler.OUTBOUND_CHANNEL_HANDLER);
pipeline.addLast(new ClientTimeoutHandler.InboundHandler());
pipeline.addLast(new ClientTimeoutHandler.OutboundHandler());
pipeline.addLast(CONNECTION_POOL_HANDLER, connectionPoolHandler);
}
/**
* This method can be overridden to create your own custom SSL context
*
* @param spectatorRegistry metrics registry
* @return Netty SslContext
*/
protected SslContext getClientSslContext(Registry spectatorRegistry) {
return new ClientSslContextFactory(spectatorRegistry).getClientSslContext();
}
/**
* This method can be overridden to add your own MethodBinding handler for preserving thread locals or thread variables.
*
* This should be a handler that binds downstream channelRead and userEventTriggered with the
* MethodBinding class. It should be added using the pipeline.addLast method.
*
* @param pipeline the channel pipeline
*/
protected void addMethodBindingHandler(ChannelPipeline pipeline) {}
@Override
public HttpMetricsChannelHandler getHttpMetricsHandler() {
return httpMetricsHandler;
}
}
| 6,393 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/ClientTimeoutHandler.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.netty.connectionpool;
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.LastHttpContent;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
/**
* Client Timeout Handler
*
* Author: Arthur Gonigberg
* Date: July 01, 2019
*/
public final class ClientTimeoutHandler {
private static final Logger LOG = LoggerFactory.getLogger(ClientTimeoutHandler.class);
public static final AttributeKey<Duration> ORIGIN_RESPONSE_READ_TIMEOUT =
AttributeKey.newInstance("originResponseReadTimeout");
public static final class InboundHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
if (msg instanceof LastHttpContent) {
LOG.debug(
"[{}] Removing read timeout handler", ctx.channel().id());
PooledConnection.getFromChannel(ctx.channel()).removeReadTimeoutHandler();
}
} finally {
super.channelRead(ctx, msg);
}
}
}
public static final class OutboundHandler extends ChannelOutboundHandlerAdapter {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
try {
final Duration timeout =
ctx.channel().attr(ORIGIN_RESPONSE_READ_TIMEOUT).get();
if (timeout != null && msg instanceof LastHttpContent) {
promise.addListener(e -> {
LOG.debug(
"[{}] Adding read timeout handler: {}",
ctx.channel().id(),
timeout.toMillis());
PooledConnection.getFromChannel(ctx.channel()).startReadTimeoutHandler(timeout);
});
}
} finally {
super.write(ctx, msg, promise);
}
}
}
}
| 6,394 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/PooledConnection.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.netty.connectionpool;
import com.netflix.spectator.api.Counter;
import com.netflix.zuul.discovery.DiscoveryResult;
import com.netflix.zuul.passport.CurrentPassport;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
/**
* Created by saroskar on 3/15/16.
*/
public class PooledConnection {
public static final AttributeKey<PooledConnection> CHANNEL_ATTR = AttributeKey.newInstance("_pooled_connection");
public static final String READ_TIMEOUT_HANDLER_NAME = "readTimeoutHandler";
private final DiscoveryResult server;
private final Channel channel;
private final ClientChannelManager channelManager;
private final long creationTS;
private final Counter closeConnCounter;
private final Counter closeWrtBusyConnCounter;
private static final Logger LOG = LoggerFactory.getLogger(PooledConnection.class);
/**
* Connection State
*/
public enum ConnectionState {
/**
* valid state in pool
*/
WRITE_READY,
/**
* Can not be put in pool
*/
WRITE_BUSY
}
private ConnectionState connectionState;
private long usageCount = 0;
private long reqStartTime;
private boolean inPool = false;
private boolean shouldClose = false;
protected boolean released = false;
public PooledConnection(
final Channel channel,
final DiscoveryResult server,
final ClientChannelManager channelManager,
final Counter closeConnCounter,
final Counter closeWrtBusyConnCounter) {
this.channel = channel;
this.server = server;
this.channelManager = channelManager;
this.creationTS = System.currentTimeMillis();
this.closeConnCounter = closeConnCounter;
this.closeWrtBusyConnCounter = closeWrtBusyConnCounter;
this.connectionState = ConnectionState.WRITE_READY;
// Store ourself as an attribute on the underlying Channel.
channel.attr(CHANNEL_ATTR).set(this);
}
public void setInUse() {
this.connectionState = ConnectionState.WRITE_BUSY;
this.released = false;
}
public void setConnectionState(ConnectionState state) {
this.connectionState = state;
}
public static PooledConnection getFromChannel(Channel ch) {
return ch.attr(CHANNEL_ATTR).get();
}
public ConnectionPoolConfig getConfig() {
return this.channelManager.getConfig();
}
public DiscoveryResult getServer() {
return server;
}
public Channel getChannel() {
return channel;
}
public long getUsageCount() {
return usageCount;
}
public void incrementUsageCount() {
this.usageCount++;
}
public long getCreationTS() {
return creationTS;
}
public long getAgeInMillis() {
return System.currentTimeMillis() - creationTS;
}
public void startRequestTimer() {
reqStartTime = System.nanoTime();
}
public long stopRequestTimer() {
final long responseTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - reqStartTime);
server.noteResponseTime(responseTime);
return responseTime;
}
public boolean isActive() {
return (channel.isActive() && channel.isRegistered());
}
public boolean isInPool() {
return inPool;
}
public void setInPool(boolean inPool) {
this.inPool = inPool;
}
public boolean isShouldClose() {
return shouldClose;
}
public void flagShouldClose() {
this.shouldClose = true;
}
public ChannelFuture close() {
server.decrementOpenConnectionsCount();
closeConnCounter.increment();
return channel.close();
}
public void updateServerStats() {
server.decrementOpenConnectionsCount();
server.stopPublishingStats();
}
public ChannelFuture closeAndRemoveFromPool() {
channelManager.remove(this);
return this.close();
}
public boolean release() {
if (released) {
return true;
}
if (isActive()) {
if (connectionState != ConnectionState.WRITE_READY) {
closeWrtBusyConnCounter.increment();
}
}
if (!isShouldClose() && connectionState != ConnectionState.WRITE_READY) {
CurrentPassport passport = CurrentPassport.fromChannel(channel);
LOG.info(
"Error - Attempt to put busy connection into the pool = {}, {}",
this.toString(),
String.valueOf(passport));
this.shouldClose = true;
}
// reset the connectionState
connectionState = ConnectionState.WRITE_READY;
released = true;
return channelManager.release(this);
}
public void removeReadTimeoutHandler() {
// Remove (and therefore destroy) the readTimeoutHandler when we release the
// channel back to the pool. As don't want it timing-out when it's not in use.
final ChannelPipeline pipeline = getChannel().pipeline();
removeHandlerFromPipeline(READ_TIMEOUT_HANDLER_NAME, pipeline);
}
private void removeHandlerFromPipeline(String handlerName, ChannelPipeline pipeline) {
if (pipeline.get(handlerName) != null) {
pipeline.remove(handlerName);
}
}
public void startReadTimeoutHandler(Duration readTimeout) {
getChannel()
.pipeline()
.addBefore(
DefaultOriginChannelInitializer.ORIGIN_NETTY_LOGGER,
READ_TIMEOUT_HANDLER_NAME,
new ReadTimeoutHandler(readTimeout.toMillis(), TimeUnit.MILLISECONDS));
}
ConnectionState getConnectionState() {
return connectionState;
}
boolean isReleased() {
return released;
}
@Override
public String toString() {
return "PooledConnection{" + "channel=" + channel + ", usageCount=" + usageCount + '}';
}
}
| 6,395 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/NettyClientConnectionFactory.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.netty.connectionpool;
import com.netflix.zuul.netty.server.Server;
import com.netflix.zuul.passport.CurrentPassport;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoop;
import io.netty.channel.WriteBufferWaterMark;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Objects;
/**
* Created by saroskar on 3/16/16.
*/
public final class NettyClientConnectionFactory {
private final ConnectionPoolConfig connPoolConfig;
private final ChannelInitializer<? extends Channel> channelInitializer;
NettyClientConnectionFactory(
final ConnectionPoolConfig connPoolConfig, final ChannelInitializer<? extends Channel> channelInitializer) {
this.connPoolConfig = connPoolConfig;
this.channelInitializer = channelInitializer;
}
public ChannelFuture connect(
final EventLoop eventLoop, SocketAddress socketAddress, CurrentPassport passport, IConnectionPool pool) {
Objects.requireNonNull(socketAddress, "socketAddress");
if (socketAddress instanceof InetSocketAddress) {
// This should be checked by the ClientConnectionManager
assert !((InetSocketAddress) socketAddress).isUnresolved() : socketAddress;
}
final Bootstrap bootstrap = new Bootstrap()
.channel(Server.defaultOutboundChannelType.get())
.handler(channelInitializer)
.group(eventLoop)
.attr(CurrentPassport.CHANNEL_ATTR, passport)
.attr(PerServerConnectionPool.CHANNEL_ATTR, pool)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connPoolConfig.getConnectTimeout())
.option(ChannelOption.SO_KEEPALIVE, connPoolConfig.getTcpKeepAlive())
.option(ChannelOption.TCP_NODELAY, connPoolConfig.getTcpNoDelay())
.option(ChannelOption.SO_SNDBUF, connPoolConfig.getTcpSendBufferSize())
.option(ChannelOption.SO_RCVBUF, connPoolConfig.getTcpReceiveBufferSize())
.option(
ChannelOption.WRITE_BUFFER_WATER_MARK,
new WriteBufferWaterMark(
connPoolConfig.getNettyWriteBufferLowWaterMark(),
connPoolConfig.getNettyWriteBufferHighWaterMark()))
.option(ChannelOption.AUTO_READ, connPoolConfig.getNettyAutoRead())
.remoteAddress(socketAddress);
return bootstrap.connect();
}
}
| 6,396 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/connectionpool/DefaultClientChannelManager.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.netty.connectionpool;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.InetAddresses;
import com.netflix.client.config.IClientConfig;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.histogram.PercentileTimer;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.zuul.discovery.DiscoveryResult;
import com.netflix.zuul.discovery.DynamicServerResolver;
import com.netflix.zuul.discovery.ResolverResult;
import com.netflix.zuul.exception.OutboundErrorType;
import com.netflix.zuul.netty.SpectatorUtils;
import com.netflix.zuul.netty.insights.PassportStateHttpClientHandler;
import com.netflix.zuul.netty.server.OriginResponseReceiver;
import com.netflix.zuul.origins.OriginName;
import com.netflix.zuul.passport.CurrentPassport;
import com.netflix.zuul.resolver.Resolver;
import com.netflix.zuul.resolver.ResolverListener;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoop;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.Promise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
/**
* User: michaels@netflix.com
* Date: 7/8/16
* Time: 12:39 PM
*/
public class DefaultClientChannelManager implements ClientChannelManager {
private static final Logger LOG = LoggerFactory.getLogger(DefaultClientChannelManager.class);
public static final String METRIC_PREFIX = "connectionpool_";
private final Resolver<DiscoveryResult> dynamicServerResolver;
private final ConnectionPoolConfig connPoolConfig;
private final IClientConfig clientConfig;
private final Registry registry;
private final OriginName originName;
private static final Throwable SHUTTING_DOWN_ERR =
new IllegalStateException("ConnectionPool is shutting down now.");
private volatile boolean shuttingDown = false;
private final Counter createNewConnCounter;
private final Counter createConnSucceededCounter;
private final Counter createConnFailedCounter;
private final Counter closeConnCounter;
private final Counter requestConnCounter;
private final Counter closeAbovePoolHighWaterMarkCounter;
private final Counter closeExpiredConnLifetimeCounter;
private final Counter reuseConnCounter;
private final Counter releaseConnCounter;
private final Counter alreadyClosedCounter;
private final Counter connTakenFromPoolIsNotOpen;
private final Counter maxConnsPerHostExceededCounter;
private final Counter closeWrtBusyConnCounter;
private final Counter circuitBreakerClose;
private final PercentileTimer connEstablishTimer;
private final AtomicInteger connsInPool;
private final AtomicInteger connsInUse;
private final ConcurrentHashMap<DiscoveryResult, IConnectionPool> perServerPools;
private NettyClientConnectionFactory clientConnFactory;
private OriginChannelInitializer channelInitializer;
public static final String IDLE_STATE_HANDLER_NAME = "idleStateHandler";
public DefaultClientChannelManager(OriginName originName, IClientConfig clientConfig, Registry registry) {
this(originName, clientConfig, new DynamicServerResolver(clientConfig), registry);
}
public DefaultClientChannelManager(
OriginName originName, IClientConfig clientConfig, Resolver<DiscoveryResult> resolver, Registry registry) {
this.originName = Objects.requireNonNull(originName, "originName");
this.dynamicServerResolver = resolver;
this.clientConfig = clientConfig;
this.registry = registry;
this.perServerPools = new ConcurrentHashMap<>(200);
this.connPoolConfig = new ConnectionPoolConfigImpl(originName, this.clientConfig);
this.createNewConnCounter = newCounter("create");
this.createConnSucceededCounter = newCounter("create_success");
this.createConnFailedCounter = newCounter("create_fail");
this.closeConnCounter = newCounter("close");
this.closeAbovePoolHighWaterMarkCounter = newCounter("closeAbovePoolHighWaterMark");
this.closeExpiredConnLifetimeCounter = newCounter("closeExpiredConnLifetime");
this.requestConnCounter = newCounter("request");
this.reuseConnCounter = newCounter("reuse");
this.releaseConnCounter = newCounter("release");
this.alreadyClosedCounter = newCounter("alreadyClosed");
this.connTakenFromPoolIsNotOpen = newCounter("fromPoolIsClosed");
this.maxConnsPerHostExceededCounter = newCounter("maxConnsPerHostExceeded");
this.closeWrtBusyConnCounter = newCounter("closeWrtBusyConnCounter");
this.circuitBreakerClose = newCounter("closeCircuitBreaker");
this.connEstablishTimer = PercentileTimer.get(
registry, registry.createId(METRIC_PREFIX + "createTiming", "id", originName.getMetricId()));
this.connsInPool = newGauge("inPool");
this.connsInUse = newGauge("inUse");
}
@Override
public void init() {
dynamicServerResolver.setListener(new ServerPoolListener());
// Load channel initializer and conn factory.
// We don't do this within the constructor because some subclass may not be initialized until post-construct.
this.channelInitializer = createChannelInitializer(clientConfig, connPoolConfig, registry);
this.clientConnFactory = createNettyClientConnectionFactory(connPoolConfig, channelInitializer);
}
protected OriginChannelInitializer createChannelInitializer(
IClientConfig clientConfig, ConnectionPoolConfig connPoolConfig, Registry registry) {
return new DefaultOriginChannelInitializer(connPoolConfig, registry);
}
protected NettyClientConnectionFactory createNettyClientConnectionFactory(
ConnectionPoolConfig connPoolConfig, ChannelInitializer<? extends Channel> clientConnInitializer) {
return new NettyClientConnectionFactory(connPoolConfig, clientConnInitializer);
}
@Override
public ConnectionPoolConfig getConfig() {
return connPoolConfig;
}
@Override
public boolean isAvailable() {
return dynamicServerResolver.hasServers();
}
@Override
public boolean isCold() {
return false;
}
@Override
public int getInflightRequestsCount() {
return this.channelInitializer.getHttpMetricsHandler().getInflightRequestsCount();
}
@Override
public void shutdown() {
this.shuttingDown = true;
dynamicServerResolver.shutdown();
for (IConnectionPool pool : perServerPools.values()) {
pool.shutdown();
}
}
/**
* Gracefully shuts down a DefaultClientChannelManager by allowing in-flight requests to finish before closing the connections.
* Idle connections in the connection pools are closed, and any connections associated with an in-flight request
* will be closed upon trying to return the connection to the pool
*/
@Override
public void gracefulShutdown() {
LOG.info("Starting a graceful shutdown of {}", clientConfig.getClientName());
shuttingDown = true;
dynamicServerResolver.shutdown();
perServerPools.values().forEach(IConnectionPool::drain);
}
@Override
public boolean release(final PooledConnection conn) {
conn.stopRequestTimer();
releaseConnCounter.increment();
connsInUse.decrementAndGet();
final DiscoveryResult discoveryResult = conn.getServer();
updateServerStatsOnRelease(conn);
boolean released = false;
// if the connection has been around too long (i.e. too many requests), then close it
// TODO(argha-c): Document what is a reasonable default here, and the class of origins that optimizes for
final boolean connExpiredLifetime = conn.getUsageCount() > connPoolConfig.getMaxRequestsPerConnection();
if (conn.isShouldClose() || connExpiredLifetime) {
// Close and discard the connection, as it has been flagged (possibly due to receiving a non-channel error
// like a 503).
conn.setInPool(false);
conn.close();
if (connExpiredLifetime) {
closeExpiredConnLifetimeCounter.increment();
LOG.debug(
"[{}] closing conn lifetime expired, usage: {}",
conn.getChannel().id(),
conn.getUsageCount());
} else {
LOG.debug(
"[{}] closing conn flagged to be closed",
conn.getChannel().id());
}
} else if (discoveryResult.isCircuitBreakerTripped()) {
LOG.debug(
"[{}] closing conn, server circuit breaker tripped",
conn.getChannel().id());
circuitBreakerClose.increment();
// Don't put conns for currently circuit-tripped servers back into the pool.
conn.setInPool(false);
conn.close();
} else if (!conn.isActive()) {
LOG.debug("[{}] conn inactive, cleaning up", conn.getChannel().id());
// Connection is already closed, so discard.
alreadyClosedCounter.increment();
// make sure to decrement OpenConnectionCounts
conn.updateServerStats();
conn.setInPool(false);
} else {
releaseHandlers(conn);
// Attempt to return connection to the pool.
IConnectionPool pool = perServerPools.get(discoveryResult);
if (pool != null) {
released = pool.release(conn);
} else {
// The pool for this server no longer exists (maybe due to it falling out of
// discovery).
conn.setInPool(false);
released = false;
conn.close();
}
LOG.debug("PooledConnection released: {}", conn);
}
return released;
}
protected void updateServerStatsOnRelease(final PooledConnection conn) {
final DiscoveryResult discoveryResult = conn.getServer();
discoveryResult.decrementActiveRequestsCount();
discoveryResult.incrementNumRequests();
}
protected void releaseHandlers(PooledConnection conn) {
final ChannelPipeline pipeline = conn.getChannel().pipeline();
removeHandlerFromPipeline(OriginResponseReceiver.CHANNEL_HANDLER_NAME, pipeline);
// The Outbound handler is always after the inbound handler, so look for it.
ChannelHandlerContext passportStateHttpClientHandlerCtx =
pipeline.context(PassportStateHttpClientHandler.OutboundHandler.class);
pipeline.addAfter(
passportStateHttpClientHandlerCtx.name(),
IDLE_STATE_HANDLER_NAME,
new IdleStateHandler(0, 0, connPoolConfig.getIdleTimeout(), TimeUnit.MILLISECONDS));
}
public static void removeHandlerFromPipeline(final String handlerName, final ChannelPipeline pipeline) {
if (pipeline.get(handlerName) != null) {
pipeline.remove(handlerName);
}
}
@Override
public boolean remove(PooledConnection conn) {
if (conn == null) {
return false;
}
if (!conn.isInPool()) {
return false;
}
// Attempt to remove the connection from the pool.
IConnectionPool pool = perServerPools.get(conn.getServer());
if (pool != null) {
return pool.remove(conn);
} else {
// The pool for this server no longer exists (maybe due to it failling out of
// discovery).
conn.setInPool(false);
connsInPool.decrementAndGet();
return false;
}
}
@Override
public Promise<PooledConnection> acquire(final EventLoop eventLoop) {
return acquire(eventLoop, null, CurrentPassport.create(), new AtomicReference<>(), new AtomicReference<>());
}
@Override
public Promise<PooledConnection> acquire(
EventLoop eventLoop,
@Nullable Object key,
CurrentPassport passport,
AtomicReference<DiscoveryResult> selectedServer,
AtomicReference<? super InetAddress> selectedHostAddr) {
if (shuttingDown) {
Promise<PooledConnection> promise = eventLoop.newPromise();
promise.setFailure(SHUTTING_DOWN_ERR);
return promise;
}
// Choose the next load-balanced server.
final DiscoveryResult chosenServer = dynamicServerResolver.resolve(key);
// (argha-c): Always ensure the selected server is updated, since the call chain relies on this mutation.
selectedServer.set(chosenServer);
if (chosenServer == DiscoveryResult.EMPTY) {
Promise<PooledConnection> promise = eventLoop.newPromise();
promise.setFailure(
new OriginConnectException("No servers available", OutboundErrorType.NO_AVAILABLE_SERVERS));
return promise;
}
// Now get the connection-pool for this server.
IConnectionPool pool = perServerPools.computeIfAbsent(chosenServer, s -> {
SocketAddress finalServerAddr = pickAddress(chosenServer);
final ClientChannelManager clientChannelMgr = this;
PooledConnectionFactory pcf = createPooledConnectionFactory(
chosenServer, clientChannelMgr, closeConnCounter, closeWrtBusyConnCounter);
// Create a new pool for this server.
return createConnectionPool(
chosenServer,
finalServerAddr,
clientConnFactory,
pcf,
connPoolConfig,
clientConfig,
createNewConnCounter,
createConnSucceededCounter,
createConnFailedCounter,
requestConnCounter,
reuseConnCounter,
connTakenFromPoolIsNotOpen,
closeAbovePoolHighWaterMarkCounter,
maxConnsPerHostExceededCounter,
connEstablishTimer,
connsInPool,
connsInUse);
});
return pool.acquire(eventLoop, passport, selectedHostAddr);
}
protected PooledConnectionFactory createPooledConnectionFactory(
DiscoveryResult chosenServer,
ClientChannelManager clientChannelMgr,
Counter closeConnCounter,
Counter closeWrtBusyConnCounter) {
return ch ->
new PooledConnection(ch, chosenServer, clientChannelMgr, closeConnCounter, closeWrtBusyConnCounter);
}
protected IConnectionPool createConnectionPool(
DiscoveryResult discoveryResult,
SocketAddress serverAddr,
NettyClientConnectionFactory clientConnFactory,
PooledConnectionFactory pcf,
ConnectionPoolConfig connPoolConfig,
IClientConfig clientConfig,
Counter createNewConnCounter,
Counter createConnSucceededCounter,
Counter createConnFailedCounter,
Counter requestConnCounter,
Counter reuseConnCounter,
Counter connTakenFromPoolIsNotOpen,
Counter closeAbovePoolHighWaterMarkCounter,
Counter maxConnsPerHostExceededCounter,
PercentileTimer connEstablishTimer,
AtomicInteger connsInPool,
AtomicInteger connsInUse) {
return new PerServerConnectionPool(
discoveryResult,
serverAddr,
clientConnFactory,
pcf,
connPoolConfig,
clientConfig,
createNewConnCounter,
createConnSucceededCounter,
createConnFailedCounter,
requestConnCounter,
reuseConnCounter,
connTakenFromPoolIsNotOpen,
closeAbovePoolHighWaterMarkCounter,
maxConnsPerHostExceededCounter,
connEstablishTimer,
connsInPool,
connsInUse);
}
final class ServerPoolListener implements ResolverListener<DiscoveryResult> {
@Override
public void onChange(List<DiscoveryResult> removedSet) {
if (!removedSet.isEmpty()) {
LOG.debug(
"Removing connection pools for missing servers. name = {}. {} servers gone.",
originName,
removedSet.size());
for (DiscoveryResult s : removedSet) {
IConnectionPool pool = perServerPools.remove(s);
if (pool != null) {
pool.shutdown();
}
}
}
}
}
@Override
public int getConnsInPool() {
return connsInPool.get();
}
@Override
public int getConnsInUse() {
return connsInUse.get();
}
protected ConcurrentHashMap<DiscoveryResult, IConnectionPool> getPerServerPools() {
return perServerPools;
}
@VisibleForTesting
static SocketAddress pickAddressInternal(ResolverResult chosenServer, @Nullable OriginName originName) {
String rawHost;
int port;
rawHost = chosenServer.getHost();
port = chosenServer.getPort();
InetSocketAddress serverAddr;
try {
InetAddress ipAddr = InetAddresses.forString(rawHost);
serverAddr = new InetSocketAddress(ipAddr, port);
} catch (IllegalArgumentException e1) {
LOG.warn("NettyClientConnectionFactory got an unresolved address, addr: {}", rawHost);
Counter unresolvedDiscoveryHost = SpectatorUtils.newCounter(
"unresolvedDiscoveryHost", originName == null ? "unknownOrigin" : originName.getTarget());
unresolvedDiscoveryHost.increment();
try {
serverAddr = new InetSocketAddress(rawHost, port);
} catch (RuntimeException e2) {
e1.addSuppressed(e2);
throw e1;
}
}
return serverAddr;
}
/**
* Given a server chosen from the load balancer, pick the appropriate address to connect to.
*/
protected SocketAddress pickAddress(DiscoveryResult chosenServer) {
return pickAddressInternal(chosenServer, connPoolConfig.getOriginName());
}
private AtomicInteger newGauge(String name) {
return PolledMeter.using(registry)
.withName(METRIC_PREFIX + name)
.withTag("id", originName.getMetricId())
.monitorValue(new AtomicInteger());
}
private Counter newCounter(String name) {
return registry.counter(METRIC_PREFIX + name, "id", originName.getMetricId());
}
}
| 6,397 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulFilterChainRunner.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.netty.filter;
import com.netflix.netty.common.ByteBufUtil;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.impl.Preconditions;
import com.netflix.zuul.FilterUsageNotifier;
import com.netflix.zuul.filters.ZuulFilter;
import com.netflix.zuul.message.ZuulMessage;
import com.netflix.zuul.message.http.HttpRequestMessage;
import com.netflix.zuul.message.http.HttpResponseMessage;
import com.netflix.zuul.passport.CurrentPassport;
import com.netflix.zuul.passport.PassportState;
import io.netty.handler.codec.http.HttpContent;
import io.netty.util.ReferenceCountUtil;
import io.perfmark.PerfMark;
import io.perfmark.TaskCloseable;
import javax.annotation.concurrent.ThreadSafe;
import java.util.concurrent.atomic.AtomicInteger;
/**
* This class is supposed to be thread safe and hence should not have any non final member variables
* Created by saroskar on 5/17/17.
*/
@ThreadSafe
public class ZuulFilterChainRunner<T extends ZuulMessage> extends BaseZuulFilterRunner<T, T> {
private final ZuulFilter<T, T>[] filters;
public ZuulFilterChainRunner(
ZuulFilter<T, T>[] zuulFilters,
FilterUsageNotifier usageNotifier,
FilterRunner<T, ?> nextStage,
Registry registry) {
super(zuulFilters[0].filterType(), usageNotifier, nextStage, registry);
this.filters = zuulFilters;
}
public ZuulFilterChainRunner(ZuulFilter<T, T>[] zuulFilters, FilterUsageNotifier usageNotifier, Registry registry) {
this(zuulFilters, usageNotifier, null, registry);
}
@Override
public void filter(final T inMesg) {
try (TaskCloseable ignored = PerfMark.traceTask(this, s -> s.getClass().getSimpleName() + ".filter")) {
addPerfMarkTags(inMesg);
runFilters(inMesg, initRunningFilterIndex(inMesg));
}
}
@Override
protected void resume(final T inMesg) {
try (TaskCloseable ignored = PerfMark.traceTask(this, s -> s.getClass().getSimpleName() + ".resume")) {
final AtomicInteger runningFilterIdx = getRunningFilterIndex(inMesg);
runningFilterIdx.incrementAndGet();
runFilters(inMesg, runningFilterIdx);
}
}
private final void runFilters(final T mesg, final AtomicInteger runningFilterIdx) {
T inMesg = mesg;
String filterName = "-";
try {
Preconditions.checkNotNull(mesg, "Input message");
int i = runningFilterIdx.get();
while (i < filters.length) {
final ZuulFilter<T, T> filter = filters[i];
filterName = filter.filterName();
final T outMesg = filter(filter, inMesg);
if (outMesg == null) {
return; // either async filter or waiting for the message body to be buffered
}
inMesg = outMesg;
i = runningFilterIdx.incrementAndGet();
}
// Filter chain has reached its end, pass result to the next stage
invokeNextStage(inMesg);
} catch (Exception ex) {
handleException(inMesg, filterName, ex);
}
}
@Override
public void filter(T inMesg, HttpContent chunk) {
String filterName = "-";
try (TaskCloseable ignored = PerfMark.traceTask(this, s -> s.getClass().getSimpleName() + ".filterChunk")) {
addPerfMarkTags(inMesg);
Preconditions.checkNotNull(inMesg, "input message");
final AtomicInteger runningFilterIdx = getRunningFilterIndex(inMesg);
final int limit = runningFilterIdx.get();
for (int i = 0; i < limit; i++) {
final ZuulFilter<T, T> filter = filters[i];
filterName = filter.filterName();
if ((!filter.isDisabled()) && (!shouldSkipFilter(inMesg, filter))) {
ByteBufUtil.touch(chunk, "Filter runner processing chunk, filter: ", filterName);
final HttpContent newChunk = filter.processContentChunk(inMesg, chunk);
if (newChunk == null) {
// Filter wants to break the chain and stop propagating this chunk any further
return;
}
// deallocate original chunk if necessary
if ((newChunk != chunk) && (chunk.refCnt() > 0)) {
ByteBufUtil.touch(chunk, "Filter runner processing newChunk, filter: ", filterName);
chunk.release(chunk.refCnt());
}
chunk = newChunk;
}
}
if (limit >= filters.length) {
// Filter chain has run to end, pass down the channel pipeline
ByteBufUtil.touch(chunk, "Filter runner chain complete, message: ", inMesg);
invokeNextStage(inMesg, chunk);
} else {
ByteBufUtil.touch(chunk, "Filter runner buffering chunk, message: ", inMesg);
inMesg.bufferBodyContents(chunk);
boolean isAwaitingBody = isFilterAwaitingBody(inMesg.getContext());
// Record passport states for start and end of buffering bodies.
if (isAwaitingBody) {
CurrentPassport passport = CurrentPassport.fromSessionContext(inMesg.getContext());
if (inMesg.hasCompleteBody()) {
if (inMesg instanceof HttpRequestMessage) {
passport.addIfNotAlready(PassportState.FILTERS_INBOUND_BUF_END);
} else if (inMesg instanceof HttpResponseMessage) {
passport.addIfNotAlready(PassportState.FILTERS_OUTBOUND_BUF_END);
}
} else {
if (inMesg instanceof HttpRequestMessage) {
passport.addIfNotAlready(PassportState.FILTERS_INBOUND_BUF_START);
} else if (inMesg instanceof HttpResponseMessage) {
passport.addIfNotAlready(PassportState.FILTERS_OUTBOUND_BUF_START);
}
}
}
if (isAwaitingBody && inMesg.hasCompleteBody()) {
// whole body has arrived, resume filter chain
ByteBufUtil.touch(chunk, "Filter body complete, resume chain, ZuulMessage: ", inMesg);
runFilters(inMesg, runningFilterIdx);
}
}
} catch (Exception ex) {
ReferenceCountUtil.safeRelease(chunk);
handleException(inMesg, filterName, ex);
}
}
}
| 6,398 |
0 | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty | Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/filter/ZuulFilterChainHandler.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.netty.filter;
import com.google.common.base.Preconditions;
import com.netflix.netty.common.HttpLifecycleChannelHandler;
import com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent;
import com.netflix.netty.common.HttpRequestReadTimeoutEvent;
import com.netflix.zuul.context.CommonContextKeys;
import com.netflix.zuul.context.SessionContext;
import com.netflix.zuul.filters.ZuulFilter;
import com.netflix.zuul.filters.endpoint.ProxyEndpoint;
import com.netflix.zuul.message.Headers;
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.RequestCancelledEvent;
import com.netflix.zuul.netty.SpectatorUtils;
import com.netflix.zuul.netty.server.ClientRequestReceiver;
import com.netflix.zuul.stats.status.StatusCategory;
import com.netflix.zuul.stats.status.StatusCategoryUtils;
import com.netflix.zuul.stats.status.ZuulStatusCategory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.unix.Errors;
import io.netty.handler.codec.http.DefaultLastHttpContent;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLException;
import java.nio.channels.ClosedChannelException;
/**
* Created by saroskar on 5/18/17.
*/
public class ZuulFilterChainHandler extends ChannelInboundHandlerAdapter {
private final ZuulFilterChainRunner<HttpRequestMessage> requestFilterChain;
private final ZuulFilterChainRunner<HttpResponseMessage> responseFilterChain;
private HttpRequestMessage zuulRequest;
private static final Logger logger = LoggerFactory.getLogger(ZuulFilterChainHandler.class);
public ZuulFilterChainHandler(
ZuulFilterChainRunner<HttpRequestMessage> requestFilterChain,
ZuulFilterChainRunner<HttpResponseMessage> responseFilterChain) {
this.requestFilterChain = Preconditions.checkNotNull(requestFilterChain, "request filter chain");
this.responseFilterChain = Preconditions.checkNotNull(responseFilterChain, "response filter chain");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpRequestMessage) {
zuulRequest = (HttpRequestMessage) msg;
// Replace NETTY_SERVER_CHANNEL_HANDLER_CONTEXT in SessionContext
final SessionContext zuulCtx = zuulRequest.getContext();
zuulCtx.put(CommonContextKeys.NETTY_SERVER_CHANNEL_HANDLER_CONTEXT, ctx);
requestFilterChain.filter(zuulRequest);
} else if ((msg instanceof HttpContent) && (zuulRequest != null)) {
requestFilterChain.filter(zuulRequest, (HttpContent) msg);
} else {
logger.debug(
"Received unrecognized message type. {}", msg.getClass().getName());
ReferenceCountUtil.release(msg);
}
}
@Override
public final void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof CompleteEvent) {
final CompleteEvent completeEvent = (CompleteEvent) evt;
fireEndpointFinish(
completeEvent.getReason() != HttpLifecycleChannelHandler.CompleteReason.SESSION_COMPLETE, ctx);
} else if (evt instanceof HttpRequestReadTimeoutEvent) {
sendResponse(ZuulStatusCategory.FAILURE_CLIENT_TIMEOUT, 408, ctx);
} else if (evt instanceof IdleStateEvent) {
sendResponse(ZuulStatusCategory.FAILURE_LOCAL_IDLE_TIMEOUT, 504, ctx);
} else if (evt instanceof RequestCancelledEvent) {
if (zuulRequest != null) {
zuulRequest.getContext().cancel();
StatusCategoryUtils.storeStatusCategoryIfNotAlreadyFailure(
zuulRequest.getContext(), ZuulStatusCategory.FAILURE_CLIENT_CANCELLED);
}
fireEndpointFinish(true, ctx);
ctx.close();
}
super.userEventTriggered(ctx, evt);
}
private void sendResponse(final StatusCategory statusCategory, final int status, ChannelHandlerContext ctx) {
if (zuulRequest == null) {
ctx.close();
} else {
final SessionContext zuulCtx = zuulRequest.getContext();
zuulRequest.getContext().cancel();
StatusCategoryUtils.storeStatusCategoryIfNotAlreadyFailure(zuulCtx, statusCategory);
final HttpResponseMessage zuulResponse = new HttpResponseMessageImpl(zuulCtx, zuulRequest, status);
final Headers headers = zuulResponse.getHeaders();
headers.add("Connection", "close");
headers.add("Content-Length", "0");
zuulResponse.finishBufferedBodyIfIncomplete();
responseFilterChain.filter(zuulResponse);
fireEndpointFinish(true, ctx);
}
}
protected HttpRequestMessage getZuulRequest() {
return zuulRequest;
}
protected void fireEndpointFinish(final boolean error, final ChannelHandlerContext ctx) {
// make sure filter chain is not left hanging
finishResponseFilters(ctx);
final ZuulFilter endpoint = ZuulEndPointRunner.getEndpoint(zuulRequest);
if (endpoint instanceof ProxyEndpoint) {
final ProxyEndpoint edgeProxyEndpoint = (ProxyEndpoint) endpoint;
edgeProxyEndpoint.finish(error);
}
zuulRequest = null;
}
private void finishResponseFilters(ChannelHandlerContext ctx) {
// check if there are any response filters awaiting a buffered body
if (zuulRequest != null && responseFilterChain.isFilterAwaitingBody(zuulRequest.getContext())) {
HttpResponseMessage zuulResponse =
ctx.channel().attr(ClientRequestReceiver.ATTR_ZUUL_RESP).get();
if (zuulResponse != null) {
// fire a last content into the filter chain to unblock any filters awaiting a buffered body
responseFilterChain.filter(zuulResponse, new DefaultLastHttpContent());
SpectatorUtils.newCounter(
"zuul.filterChain.bodyBuffer.hanging",
zuulRequest.getContext().getRouteVIP())
.increment();
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (cause instanceof SSLException) {
logger.debug("SSL exception not handled in filter chain", cause);
} else {
logger.error(
"zuul filter chain handler caught exception on channel: {}",
ChannelUtils.channelInfoForLogging(ctx.channel()),
cause);
}
if (zuulRequest != null && !isClientChannelClosed(cause)) {
final SessionContext zuulCtx = zuulRequest.getContext();
zuulCtx.setError(cause);
zuulCtx.setShouldSendErrorResponse(true);
sendResponse(ZuulStatusCategory.FAILURE_LOCAL, 500, ctx);
} else {
fireEndpointFinish(true, ctx);
ctx.close();
}
}
// Race condition: channel.isActive() did not catch
// channel close..resulting in an i/o exception
private boolean isClientChannelClosed(Throwable cause) {
if (cause instanceof ClosedChannelException || cause instanceof Errors.NativeIoException) {
logger.error("ZuulFilterChainHandler::isClientChannelClosed - IO Exception");
return true;
}
return false;
}
}
| 6,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.